Changing progressbar level
I have a simple activity that is suppose display a progress bar with
different fill levels. This activity with the progress bar is display
after a student undertake a practice test on my mobile application. So the
progess bar would show if the student passed showing all blue with the
color filling it. if it is an average performance. The color is half
filled in green. If it is a poor performance the color is completely red
with a slight color fill.
My little code to set fill color is below but it not working
if(grade.equals("passed")){
setProgress(100);
}
else{
setProgress(50);
}
Thursday, 3 October 2013
Wednesday, 2 October 2013
how to undo hijacked files in clearcase?
how to undo hijacked files in clearcase?
I have this strange hijacked file in my snapshot view. when I undo it, it
doesn't go away. Is there a way to un-hijack it. I already tried
undo-hijacked but didn't work. I should see .keep file if it unhijacked
but didn't see any. Also tried to check out and uncheck out but this file
still remains as hijacked.
Thanks for any help !!
I have this strange hijacked file in my snapshot view. when I undo it, it
doesn't go away. Is there a way to un-hijack it. I already tried
undo-hijacked but didn't work. I should see .keep file if it unhijacked
but didn't see any. Also tried to check out and uncheck out but this file
still remains as hijacked.
Thanks for any help !!
Multiple Variable Assignment from Single Hash Ruby
Multiple Variable Assignment from Single Hash Ruby
Hello All This seems like a day 1 question, And I feel like I've had it
working before, but for some reason I'm at a loss. But I'm trying to have
an Array assign a value to two variables.
test = "hello, my,name,is,dog,how,are,you"
testsplit = test.split ","
testsplit.each do |x,y|
puts y
end
I would think that it would print my is how you
but it appears the values only get passed to x and not to y. When i run
this code y comes back as empty.
Hello All This seems like a day 1 question, And I feel like I've had it
working before, but for some reason I'm at a loss. But I'm trying to have
an Array assign a value to two variables.
test = "hello, my,name,is,dog,how,are,you"
testsplit = test.split ","
testsplit.each do |x,y|
puts y
end
I would think that it would print my is how you
but it appears the values only get passed to x and not to y. When i run
this code y comes back as empty.
How to pass an ID from a repeater row to a nested gridview?
How to pass an ID from a repeater row to a nested gridview?
QUESTION
If you have a gridview inside a repeater, how do you pass a primary key ID
to the gridview where the primary key relates to the repeaters item
template row?
I am currently attempting to do this by using a hiddenfield that contains
the PK and a control parameter to detect it and bind it to the gridview.
CURRENT ERROR
Could not find control 'hidPK' in ControlParameter 'PK'.
ABBREVIATED CODE
<asp:Repeater ID="rpt" RunAt="Server">
<ItemTemplate>
<asp:HiddenField ID="hidPK" runat="server" Value='<%#
DataBinder.Eval(Container.DataItem, "PK") %>'/>
<asp:GridView DataSourceID="sqlSource"></asp:GridView>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="sqlSource" RunAt="Server"
SelectCommand="spPopulateGridview" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Type="Int32" Name="PK" DefaultValue="0"
ControlID="hidPK"/>
</SelectParameters>
</asp:SqlDataSource>
QUESTION
If you have a gridview inside a repeater, how do you pass a primary key ID
to the gridview where the primary key relates to the repeaters item
template row?
I am currently attempting to do this by using a hiddenfield that contains
the PK and a control parameter to detect it and bind it to the gridview.
CURRENT ERROR
Could not find control 'hidPK' in ControlParameter 'PK'.
ABBREVIATED CODE
<asp:Repeater ID="rpt" RunAt="Server">
<ItemTemplate>
<asp:HiddenField ID="hidPK" runat="server" Value='<%#
DataBinder.Eval(Container.DataItem, "PK") %>'/>
<asp:GridView DataSourceID="sqlSource"></asp:GridView>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="sqlSource" RunAt="Server"
SelectCommand="spPopulateGridview" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Type="Int32" Name="PK" DefaultValue="0"
ControlID="hidPK"/>
</SelectParameters>
</asp:SqlDataSource>
Tuesday, 1 October 2013
Spring Data REST: Silent failure when adding entity relationship
Spring Data REST: Silent failure when adding entity relationship
Fellow Spring Data REST enthusiasts, I am running my Spring Data REST 1.1
application, and I am attempting use curl to add an entity relationship
using the "text/uri-list" Content-type, as described in the link:
Example-API-usage-with-curl.
curl -v -d "http://localhost:8080/simplemvc/rest/enemies/3" -H
"Content-Type: text/uri-list"
http://localhost:8080/simplemvc/rest/heroes/1/defeatedEnemies
Unfortunately, although the server returns "201 Created", the body
contains an empty JSON object, and the entity relationship does not get
created:
{
"links" : [ ],
"content" : [ ]
}
I would expect to see a SQL UPDATE being executed, but analyzing the SQL
reveals that only SELECT statements occur:
Hibernate: select hero0_.HERO_ID as HERO1_1_0_, hero0_.name as name2_1_0_
from HERO hero0_ where hero0_.HERO_ID=?
Hibernate: select defeateden0_.HERO_ID as HERO4_1_1_,
defeateden0_.ENEMY_ID as ENEMY1_0_1_, defeateden0_.ENEMY_ID as
ENEMY1_0_0_, defeateden0_.description as descript2_0_0_,
defeateden0_.HERO_ID as HERO4_0_0_, defeateden0_.name as name3_0_0_ from
ENEMY defeateden0_ where defeateden0_.HERO_ID=?
Hibernate: select enemy0_.ENEMY_ID as ENEMY1_0_1_, enemy0_.description as
descript2_0_1_, enemy0_.HERO_ID as HERO4_0_1_, enemy0_.name as name3_0_1_,
hero1_.HERO_ID as HERO1_1_0_, hero1_.name as name2_1_0_ from ENEMY enemy0_
left outer join HERO hero1_ on enemy0_.HERO_ID=hero1_.HERO_ID where
enemy0_.ENEMY_ID=?
Interestingly, if I "manually" add a relationship by executing a SQL
statement in my database client:
UPDATE ENEMY SET HERO_ID = 1 WHERE ENEMY_ID = 1;
and then execute the curl statement:
curl -v -H "Accept: application/json"
http://localhost:8080/simplemvc/rest/heroes/1/defeatedEnemies
I get a JSON representation that demonstrates -- via hypermedia links --
that Spring Data REST recognizes the one-to-many relationship between the
Hero and Enemy entities:
{
"links" : [ ],
"content" : [ {
"name" : "Red Ghost",
"description" : "Likes to chase",
"links" : [ {
"rel" : "self",
"href" : "http://localhost:8080/simplemvc/rest/enemies/1"
}, {
"rel" : "enemy.enemy.hero",
"href" : "http://localhost:8080/simplemvc/rest/enemies/1/hero"
} ]
} ]
}
This is an existing Spring MVC app to which Spring Data REST is being
added, using the following article as a guide:
Adding-Spring-Data-REST-to-an-existing-Spring-MVC-Application
I have tried using both H2 and MySQL databases with the same result. Below
are my JPA entities, Spring Data JPA Repositories, application context,
and web.xml:
Hero.java
@Entity
@Table(name = "HERO")
public class Hero {
@TableGenerator(
name="heroGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="HERO_ID",
allocationSize=1)
@Id
@GeneratedValue(strategy=TABLE, generator="heroGen")
@Column(name = "HERO_ID")
private Integer id;
@Column
private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy
= "hero")
private Set<Enemy> defeatedEnemies;
...
}
Enemy.java
@Entity
@Table(name = "ENEMY")
public class Enemy {
@TableGenerator(name="enemyGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="ENEMY_ID",
allocationSize=1)
@Id
@GeneratedValue(strategy=TABLE, generator="enemyGen")
@Column(name="ENEMY_ID")
private Integer id;
@Column
private String name;
@Column
private String description;
@ManyToOne
@JoinColumn(name = "HERO_ID")
private Hero hero;
...
}
HeroRepository.java
@RestResource(path = "heroes")
public interface HeroRepository extends CrudRepository<Hero, Integer> {
}
EnemyRepository.java
@RestResource(path = "enemies")
public interface EnemyRepository extends CrudRepository<Enemy, Integer> {
}
root-context.xml includes:
<jpa:repositories base-package="com.simple.simplemvc.repositories" />
<bean id="restConfig"
class="org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration"/>
web.xml includes:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>rest-dispatcher</servlet-name>
<servlet-class>org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Any ideas? Thanks!
Fellow Spring Data REST enthusiasts, I am running my Spring Data REST 1.1
application, and I am attempting use curl to add an entity relationship
using the "text/uri-list" Content-type, as described in the link:
Example-API-usage-with-curl.
curl -v -d "http://localhost:8080/simplemvc/rest/enemies/3" -H
"Content-Type: text/uri-list"
http://localhost:8080/simplemvc/rest/heroes/1/defeatedEnemies
Unfortunately, although the server returns "201 Created", the body
contains an empty JSON object, and the entity relationship does not get
created:
{
"links" : [ ],
"content" : [ ]
}
I would expect to see a SQL UPDATE being executed, but analyzing the SQL
reveals that only SELECT statements occur:
Hibernate: select hero0_.HERO_ID as HERO1_1_0_, hero0_.name as name2_1_0_
from HERO hero0_ where hero0_.HERO_ID=?
Hibernate: select defeateden0_.HERO_ID as HERO4_1_1_,
defeateden0_.ENEMY_ID as ENEMY1_0_1_, defeateden0_.ENEMY_ID as
ENEMY1_0_0_, defeateden0_.description as descript2_0_0_,
defeateden0_.HERO_ID as HERO4_0_0_, defeateden0_.name as name3_0_0_ from
ENEMY defeateden0_ where defeateden0_.HERO_ID=?
Hibernate: select enemy0_.ENEMY_ID as ENEMY1_0_1_, enemy0_.description as
descript2_0_1_, enemy0_.HERO_ID as HERO4_0_1_, enemy0_.name as name3_0_1_,
hero1_.HERO_ID as HERO1_1_0_, hero1_.name as name2_1_0_ from ENEMY enemy0_
left outer join HERO hero1_ on enemy0_.HERO_ID=hero1_.HERO_ID where
enemy0_.ENEMY_ID=?
Interestingly, if I "manually" add a relationship by executing a SQL
statement in my database client:
UPDATE ENEMY SET HERO_ID = 1 WHERE ENEMY_ID = 1;
and then execute the curl statement:
curl -v -H "Accept: application/json"
http://localhost:8080/simplemvc/rest/heroes/1/defeatedEnemies
I get a JSON representation that demonstrates -- via hypermedia links --
that Spring Data REST recognizes the one-to-many relationship between the
Hero and Enemy entities:
{
"links" : [ ],
"content" : [ {
"name" : "Red Ghost",
"description" : "Likes to chase",
"links" : [ {
"rel" : "self",
"href" : "http://localhost:8080/simplemvc/rest/enemies/1"
}, {
"rel" : "enemy.enemy.hero",
"href" : "http://localhost:8080/simplemvc/rest/enemies/1/hero"
} ]
} ]
}
This is an existing Spring MVC app to which Spring Data REST is being
added, using the following article as a guide:
Adding-Spring-Data-REST-to-an-existing-Spring-MVC-Application
I have tried using both H2 and MySQL databases with the same result. Below
are my JPA entities, Spring Data JPA Repositories, application context,
and web.xml:
Hero.java
@Entity
@Table(name = "HERO")
public class Hero {
@TableGenerator(
name="heroGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="HERO_ID",
allocationSize=1)
@Id
@GeneratedValue(strategy=TABLE, generator="heroGen")
@Column(name = "HERO_ID")
private Integer id;
@Column
private String name;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy
= "hero")
private Set<Enemy> defeatedEnemies;
...
}
Enemy.java
@Entity
@Table(name = "ENEMY")
public class Enemy {
@TableGenerator(name="enemyGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="ENEMY_ID",
allocationSize=1)
@Id
@GeneratedValue(strategy=TABLE, generator="enemyGen")
@Column(name="ENEMY_ID")
private Integer id;
@Column
private String name;
@Column
private String description;
@ManyToOne
@JoinColumn(name = "HERO_ID")
private Hero hero;
...
}
HeroRepository.java
@RestResource(path = "heroes")
public interface HeroRepository extends CrudRepository<Hero, Integer> {
}
EnemyRepository.java
@RestResource(path = "enemies")
public interface EnemyRepository extends CrudRepository<Enemy, Integer> {
}
root-context.xml includes:
<jpa:repositories base-package="com.simple.simplemvc.repositories" />
<bean id="restConfig"
class="org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration"/>
web.xml includes:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>rest-dispatcher</servlet-name>
<servlet-class>org.springframework.data.rest.webmvc.RepositoryRestDispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Any ideas? Thanks!
On success of ajax post, how to send a POST request with JQuery .load() method
On success of ajax post, how to send a POST request with JQuery .load()
method
After a successful Ajax post, I would like the template associated with
POST in the handler to be rendered with JQuery's .load() method. The GET
request keeps getting called after a successful POST ...so the template
associated with GET is getting rendered instead of the one associate with
POST. Thanks for any hints you can give.
Javascript:
$(function() {
$(".topic_submit").click(function() {
var topic = $("#topic").val();
refresh = 'false'
$.ajax({
type: "POST",
url: "/mentorlist",
data: {'topic': topic},
success: function(dataString) {
$('#mentor_list').load('/mentorlist');
console.log('**mentor_list div updated via ajax.**');
}
});
return true;
});
});
HTML Form:
<form id="topic_search_form" name="topic_search_form" action="">
Topic: <input id ="topic" type="text" name="topic" size="60"
placeholder="Search by Keyword" />
<input type="submit" class="topic_submit" name="topic_submit"
value="Search" >
method
After a successful Ajax post, I would like the template associated with
POST in the handler to be rendered with JQuery's .load() method. The GET
request keeps getting called after a successful POST ...so the template
associated with GET is getting rendered instead of the one associate with
POST. Thanks for any hints you can give.
Javascript:
$(function() {
$(".topic_submit").click(function() {
var topic = $("#topic").val();
refresh = 'false'
$.ajax({
type: "POST",
url: "/mentorlist",
data: {'topic': topic},
success: function(dataString) {
$('#mentor_list').load('/mentorlist');
console.log('**mentor_list div updated via ajax.**');
}
});
return true;
});
});
HTML Form:
<form id="topic_search_form" name="topic_search_form" action="">
Topic: <input id ="topic" type="text" name="topic" size="60"
placeholder="Search by Keyword" />
<input type="submit" class="topic_submit" name="topic_submit"
value="Search" >
Camera not working but camera light is on when trying to use it
Camera not working but camera light is on when trying to use it
I can't use my camera in Google hangout, I can share desktop in Google
Hangout and it works fine but camera never works, it looks like this
I have also tried using Cheese and i also just get a back screen. The
light beside my camera is on when using Google Hangout or Cheese.
Does anyone know how to fix this?
I can't use my camera in Google hangout, I can share desktop in Google
Hangout and it works fine but camera never works, it looks like this
I have also tried using Cheese and i also just get a back screen. The
light beside my camera is on when using Google Hangout or Cheese.
Does anyone know how to fix this?
Integral of natural log function using substitution
Integral of natural log function using substitution
$$\int_{2} ^{4}\dfrac{dx}{x(lnx)^2}$$
Here is what I did:
$$u=lnx, du=\dfrac{dx}{x}$$
$$\int_{2} ^{4}u^{-2}du$$
$$(-1)u^{-1} |_{2}^{4}$$
$$-\dfrac{1}{lnx}|_{2}^{4}$$
$$-\dfrac{1}{ln4} + \dfrac{1}{ln2}$$
However the answer in the back of my textbook says that the answer is
$\dfrac{1}{ln4}$. I have went over my work a couple of times and I cannot
see what I did wrong. Could someone please explain what's wrong here?
Thank you.
$$\int_{2} ^{4}\dfrac{dx}{x(lnx)^2}$$
Here is what I did:
$$u=lnx, du=\dfrac{dx}{x}$$
$$\int_{2} ^{4}u^{-2}du$$
$$(-1)u^{-1} |_{2}^{4}$$
$$-\dfrac{1}{lnx}|_{2}^{4}$$
$$-\dfrac{1}{ln4} + \dfrac{1}{ln2}$$
However the answer in the back of my textbook says that the answer is
$\dfrac{1}{ln4}$. I have went over my work a couple of times and I cannot
see what I did wrong. Could someone please explain what's wrong here?
Thank you.
Monday, 30 September 2013
Are Fresnel lenses widely used for solar electricity=?iso-8859-1?Q?=3F_If_not=2C_why_not=3F_=96_physics.stackexchange.com?=
Are Fresnel lenses widely used for solar electricity? If not, why not? –
physics.stackexchange.com
I was just wondering why Fresnel Lenses are not widely used in the
production of solar electricity. Their use there would mean that you could
produce heat within a fraction of a second, up to a few …
physics.stackexchange.com
I was just wondering why Fresnel Lenses are not widely used in the
production of solar electricity. Their use there would mean that you could
produce heat within a fraction of a second, up to a few …
What's going on with "Potential Stack Overflow Revenue Models"? meta.stackoverflow.com
What's going on with "Potential Stack Overflow Revenue Models"? –
meta.stackoverflow.com
There is a deleted question that has been linked to by this post, and from
the title, it seems to be of historical significance. However, I don't
have 10k, so I will need someone else to read it for …
meta.stackoverflow.com
There is a deleted question that has been linked to by this post, and from
the title, it seems to be of historical significance. However, I don't
have 10k, so I will need someone else to read it for …
Hotkey control keycodes confusion
Hotkey control keycodes confusion
HKM_GETHOTEKY returns virtual key code and modifiers but they're not the
same as the ordinary virtual key codes? What is the purpose of HOTKEYF_EXT
and how do i use it?
If i press F5 the hotkey control returns 0x74 which is VK_F5, but when i
press the right arrow key, it returns 0x27 which is VK_RIGHT and the
HOTKEYF_EXT bit is set on the modifier. If i use HKM_SETHOTKEY with
VK_RIGHT as virtual key and no modifiers, it shows "Num 6"
I find this very strange and I need to be able to pass any virtual keys to
the hotkey control window, and therefore i need to understand this
HOTKEYF_EXT modifier.
HKM_GETHOTEKY returns virtual key code and modifiers but they're not the
same as the ordinary virtual key codes? What is the purpose of HOTKEYF_EXT
and how do i use it?
If i press F5 the hotkey control returns 0x74 which is VK_F5, but when i
press the right arrow key, it returns 0x27 which is VK_RIGHT and the
HOTKEYF_EXT bit is set on the modifier. If i use HKM_SETHOTKEY with
VK_RIGHT as virtual key and no modifiers, it shows "Num 6"
I find this very strange and I need to be able to pass any virtual keys to
the hotkey control window, and therefore i need to understand this
HOTKEYF_EXT modifier.
simple coursor adapter with sqlite database and custmize listview
simple coursor adapter with sqlite database and custmize listview
i m confused here where is the actual error .i want to display the record
from sqlite db in to listview using simple coursor adapter .there is no
fild like _id in my sqlite databas !! but the error is regarding that,
which i mention below: Error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.blundell.tut/com.blundell.tut.ui.phone.update_page}:
java.lang.IllegalArgumentException: column '_id' does not exist
my java files are mention here..thanx in advance and if any suggestion
then plz comment it.
update_page.java
public class update_page extends Activity
{
DatabaseHandler db = new DatabaseHandler(this);
public String tableName = db.TABLE_CONTACTS;
public String databaseName = db.DATABASE_NAME;
public String task_name = db.KEY_TASK;
public String dt = db.KEY_DATETIME;
private ArrayList<String> results = new ArrayList<String>();
private ArrayList<String> results2 = new ArrayList<String>();
Intent op_intent;
SQLiteDatabase database;
ListView myview;
Cursor c;
String o_name,o_no1;
//String o_id1 = null;
HttpClient client;
Integer op_id,status;
String url;
Context ctx;
Intent myintent;
final MainActivity act = new MainActivity();
public void onCreate(Bundle savedInstanceState)
{
ctx=this;
database = act.getInstance().openOrCreateDatabase("contactsManager",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
Toast.makeText(getApplicationContext(), "Database is open",
1500).show();
final String[] columnsone={"id","task_name","date_time"};
String[] columnstwo={"task_name","date_time"};
int to[] = {R.id.lbl_task,R.id.lbl_datetime};
c = database.query("contacts", columnsone, null, null, null,
null, null);
status=c.getCount();
if(status==0)
{
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(ctx);
// set title
alertDialogBuilder.setTitle("No task are created !!");
// set dialog message
alertDialogBuilder
.setMessage("Click cancle to exit!")
.setCancelable(false)
.setNegativeButton("Cancle",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface
dialog,
int id) {
// if this button is clicked, just
close
// the dialog box and do nothing
dialog.cancel();
myintent = new
Intent(update_page.this,MainActivity.class);
startActivity(myintent);
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
else
{
Toast.makeText(getApplicationContext(), "records are
available in courser", 1500).show();
if(c!=null)
{
Toast.makeText(getApplicationContext(), "in courser",
1500).show();
SimpleCursorAdapter adapter=new
SimpleCursorAdapter(this.ctx,R.layout.update_listview,
c, columnstwo, to);
Toast.makeText(getApplicationContext(), "records are in
list", 1500).show();
myview.setAdapter(adapter);
}
}
update_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!-- <ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#404040"
android:fillViewport="true" > -->
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.68"
android:divider="#000000"
android:dividerHeight="2dp"
android:background="#404040">
</ListView>
<!-- </ScrollView> -->
</LinearLayout>
**update_listview.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/lbl_task"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Medium Text"
android:textColor="#1E90FF"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/lbl_datetime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
i m confused here where is the actual error .i want to display the record
from sqlite db in to listview using simple coursor adapter .there is no
fild like _id in my sqlite databas !! but the error is regarding that,
which i mention below: Error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.blundell.tut/com.blundell.tut.ui.phone.update_page}:
java.lang.IllegalArgumentException: column '_id' does not exist
my java files are mention here..thanx in advance and if any suggestion
then plz comment it.
update_page.java
public class update_page extends Activity
{
DatabaseHandler db = new DatabaseHandler(this);
public String tableName = db.TABLE_CONTACTS;
public String databaseName = db.DATABASE_NAME;
public String task_name = db.KEY_TASK;
public String dt = db.KEY_DATETIME;
private ArrayList<String> results = new ArrayList<String>();
private ArrayList<String> results2 = new ArrayList<String>();
Intent op_intent;
SQLiteDatabase database;
ListView myview;
Cursor c;
String o_name,o_no1;
//String o_id1 = null;
HttpClient client;
Integer op_id,status;
String url;
Context ctx;
Intent myintent;
final MainActivity act = new MainActivity();
public void onCreate(Bundle savedInstanceState)
{
ctx=this;
database = act.getInstance().openOrCreateDatabase("contactsManager",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
Toast.makeText(getApplicationContext(), "Database is open",
1500).show();
final String[] columnsone={"id","task_name","date_time"};
String[] columnstwo={"task_name","date_time"};
int to[] = {R.id.lbl_task,R.id.lbl_datetime};
c = database.query("contacts", columnsone, null, null, null,
null, null);
status=c.getCount();
if(status==0)
{
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(ctx);
// set title
alertDialogBuilder.setTitle("No task are created !!");
// set dialog message
alertDialogBuilder
.setMessage("Click cancle to exit!")
.setCancelable(false)
.setNegativeButton("Cancle",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface
dialog,
int id) {
// if this button is clicked, just
close
// the dialog box and do nothing
dialog.cancel();
myintent = new
Intent(update_page.this,MainActivity.class);
startActivity(myintent);
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
else
{
Toast.makeText(getApplicationContext(), "records are
available in courser", 1500).show();
if(c!=null)
{
Toast.makeText(getApplicationContext(), "in courser",
1500).show();
SimpleCursorAdapter adapter=new
SimpleCursorAdapter(this.ctx,R.layout.update_listview,
c, columnstwo, to);
Toast.makeText(getApplicationContext(), "records are in
list", 1500).show();
myview.setAdapter(adapter);
}
}
update_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!-- <ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#404040"
android:fillViewport="true" > -->
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.68"
android:divider="#000000"
android:dividerHeight="2dp"
android:background="#404040">
</ListView>
<!-- </ScrollView> -->
</LinearLayout>
**update_listview.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/lbl_task"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Medium Text"
android:textColor="#1E90FF"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/lbl_datetime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Sunday, 29 September 2013
There is no build provider registered for the extension '.dll'.
There is no build provider registered for the extension '.dll'.
I'm trying to reference to a .dll file from a .aspx web page. However, I
get the following error:
Description: An error occurred during the parsing of a resource required
to service this request. Please review the following specific parse error
details and modify your source file appropriately.
Parser Error Message: There is no build provider registered for the
extension '.dll'. You can register one in the
<compilation><buildProviders> section in machine.config or web.config.
Make sure is has a BuildProviderAppliesToAttribute attribute which
includes the value 'Web' or 'All'.
Source Error:
Line 2: <%@ Page Title="" Language="C#"
MasterPageFile="CSharpBPTestMaster.master" AutoEventWireup="true"
CodeFile="CSharpBPTest.aspx.cs" Inherits="Button" Debug="true"%>
Line 3:
Line 4: <%@ Register tagprefix="blnc" tagname="Balanced"
src="bin/Debug/BalancedTest.dll" %>
Line 5:
Line 6:
Source File:
/preview/1/balanced-csharp-master/src/BalancedTest/CSharpBPTest.aspx
Line: 4
I'm not sure what I'm doing wrong. I build the .csproj file. I have the
following in bin\Debug\:
Balanced.dll
Balanced.pdb
BalancedTest.dll
BalancedTest.pdb
Here is my CSharpBPTest.aspx:
<%@ Page Title="" Language="C#"
MasterPageFile="CSharpBPTestMaster.master" AutoEventWireup="true"
CodeFile="CSharpBPTest.aspx.cs" Inherits="Button" Debug="true"%>
<%@ Register tagprefix="blnc" tagname="Balanced"
src="bin/Debug/BalancedTest.dll" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<form id="form1" runat="server">
<div>
<asp:Button ID="button1" runat="server" Text="Submit"
OnClick="Button_Command"/>
<br />
<br />
<br><asp:label id="warningLabel" Text="" ForeColor="Red"
runat="server"/><br>
<br />
</div>
</form>
</asp:Content>
And in my C# file, I "import" the project like this (at the top):
using Balanced;
I want to be able to use this compiled .dll file on my C# side. The
Balanced.dll is an external library. It just came with the files and a
.csproj file. I did a build and now I'm trying to use this Balanced.dll
file. Am I missing something? I'm sorry if this is a bad question. I'm new
to asp.net and csproj.
I'm trying to reference to a .dll file from a .aspx web page. However, I
get the following error:
Description: An error occurred during the parsing of a resource required
to service this request. Please review the following specific parse error
details and modify your source file appropriately.
Parser Error Message: There is no build provider registered for the
extension '.dll'. You can register one in the
<compilation><buildProviders> section in machine.config or web.config.
Make sure is has a BuildProviderAppliesToAttribute attribute which
includes the value 'Web' or 'All'.
Source Error:
Line 2: <%@ Page Title="" Language="C#"
MasterPageFile="CSharpBPTestMaster.master" AutoEventWireup="true"
CodeFile="CSharpBPTest.aspx.cs" Inherits="Button" Debug="true"%>
Line 3:
Line 4: <%@ Register tagprefix="blnc" tagname="Balanced"
src="bin/Debug/BalancedTest.dll" %>
Line 5:
Line 6:
Source File:
/preview/1/balanced-csharp-master/src/BalancedTest/CSharpBPTest.aspx
Line: 4
I'm not sure what I'm doing wrong. I build the .csproj file. I have the
following in bin\Debug\:
Balanced.dll
Balanced.pdb
BalancedTest.dll
BalancedTest.pdb
Here is my CSharpBPTest.aspx:
<%@ Page Title="" Language="C#"
MasterPageFile="CSharpBPTestMaster.master" AutoEventWireup="true"
CodeFile="CSharpBPTest.aspx.cs" Inherits="Button" Debug="true"%>
<%@ Register tagprefix="blnc" tagname="Balanced"
src="bin/Debug/BalancedTest.dll" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<form id="form1" runat="server">
<div>
<asp:Button ID="button1" runat="server" Text="Submit"
OnClick="Button_Command"/>
<br />
<br />
<br><asp:label id="warningLabel" Text="" ForeColor="Red"
runat="server"/><br>
<br />
</div>
</form>
</asp:Content>
And in my C# file, I "import" the project like this (at the top):
using Balanced;
I want to be able to use this compiled .dll file on my C# side. The
Balanced.dll is an external library. It just came with the files and a
.csproj file. I did a build and now I'm trying to use this Balanced.dll
file. Am I missing something? I'm sorry if this is a bad question. I'm new
to asp.net and csproj.
bash backup script error
bash backup script error
So I'm writing a simple backup script that when called will either back up
a specific file or all the files in my current directory into my backup
directory. This is my script
#!/bin/bash
#verify if $1 is empty, if so, copy all content to backup directory
if [ -z "$1" ] then
$files=ls
#Looping through files
for file in $files
do
cp $file ../backup/
done
#else copy files specified
else
$files=ls $1
#Looping through files
for file in $files
do
cp $file ../backup/
done
fi
and the only error I'm getting is: ./backup: line 7: =ls: command not found
I'm not sure why the script won't recognize ls as a command. Any ideas?
So I'm writing a simple backup script that when called will either back up
a specific file or all the files in my current directory into my backup
directory. This is my script
#!/bin/bash
#verify if $1 is empty, if so, copy all content to backup directory
if [ -z "$1" ] then
$files=ls
#Looping through files
for file in $files
do
cp $file ../backup/
done
#else copy files specified
else
$files=ls $1
#Looping through files
for file in $files
do
cp $file ../backup/
done
fi
and the only error I'm getting is: ./backup: line 7: =ls: command not found
I'm not sure why the script won't recognize ls as a command. Any ideas?
How to synchronize different java programs to access a common resource
How to synchronize different java programs to access a common resource
I am trying to synchronize instances of a class that access a common
resource(database). This can be done by using notify and wait() but i need
to know that if different java programs are using this class for creating
instances than how can synchronize them. Thank you
I am trying to synchronize instances of a class that access a common
resource(database). This can be done by using notify and wait() but i need
to know that if different java programs are using this class for creating
instances than how can synchronize them. Thank you
Saturday, 28 September 2013
Forward Declaring enum class not working
Forward Declaring enum class not working
In State.h I have
namespace States
{
enum class ID : unsigned int;
}
In State.cpp I have
namespace States
{
enum class ID : unsigned int
{
NullID = 0,
MainMenuID,
GamePlayID,
}
}
The problem is that any class that includes State.h has the forward
declaration, but I can't use any actual enum within a cpp file, like
States::ID::MainMenuID . The error says...
/home/lee/Projects/SuddenAwakening/Source/Game.cpp:24: error: 'MainMenuID'
is not a member of 'States::ID'
I'm running LinuxMint15KDE, g++ 4.7, and I am using c++11 features in
other parts like nullptr, unique_ptr, ect..., so it's not that I forgot
the compiler flag for c++11.
In State.h I have
namespace States
{
enum class ID : unsigned int;
}
In State.cpp I have
namespace States
{
enum class ID : unsigned int
{
NullID = 0,
MainMenuID,
GamePlayID,
}
}
The problem is that any class that includes State.h has the forward
declaration, but I can't use any actual enum within a cpp file, like
States::ID::MainMenuID . The error says...
/home/lee/Projects/SuddenAwakening/Source/Game.cpp:24: error: 'MainMenuID'
is not a member of 'States::ID'
I'm running LinuxMint15KDE, g++ 4.7, and I am using c++11 features in
other parts like nullptr, unique_ptr, ect..., so it's not that I forgot
the compiler flag for c++11.
Incorrect return type from an ArrayList of an ArrayList
Incorrect return type from an ArrayList of an ArrayList
I have an array list of an array list that should be full of Integers, but
when I try to compile the program, I get an error stating that it cannot
add numbers to it because of incompatible operand types Object and Int.
Any help would be appreciated!
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class main{
public static void main(String[] args){
int ntt = 20;
ArrayList<Integer> Factors = new ArrayList<Integer>();
ArrayList<List> FactorsList = new ArrayList<List>();
ArrayList<Integer> Occurences = new ArrayList<Integer>();
System.out.println("Smallest Multiple of Numbers
1-20\n---------------------------------\n\nSearching...");
for(int i = 2; i <= ntt; i++){
FactorsList.add(isPrime(i));
}
for(int i = 2; i <= ntt; i++)
for(int j = 0; j < FactorsList.size(); j++)
for(int k = 0; k < FactorsList.get(j).size();k++){
if(FactorsList.get(j).get(k)==i){
Occurences.set(i, i+1);
}
}
}
static List<Long> isPrime(long num){
List<Long> ar = new ArrayList<Long>();
for(long count=2;count<=num;count++){
while(num%count == 0){
ar.add(count);
num /= count;
}
}
return ar;
}
}
I have an array list of an array list that should be full of Integers, but
when I try to compile the program, I get an error stating that it cannot
add numbers to it because of incompatible operand types Object and Int.
Any help would be appreciated!
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class main{
public static void main(String[] args){
int ntt = 20;
ArrayList<Integer> Factors = new ArrayList<Integer>();
ArrayList<List> FactorsList = new ArrayList<List>();
ArrayList<Integer> Occurences = new ArrayList<Integer>();
System.out.println("Smallest Multiple of Numbers
1-20\n---------------------------------\n\nSearching...");
for(int i = 2; i <= ntt; i++){
FactorsList.add(isPrime(i));
}
for(int i = 2; i <= ntt; i++)
for(int j = 0; j < FactorsList.size(); j++)
for(int k = 0; k < FactorsList.get(j).size();k++){
if(FactorsList.get(j).get(k)==i){
Occurences.set(i, i+1);
}
}
}
static List<Long> isPrime(long num){
List<Long> ar = new ArrayList<Long>();
for(long count=2;count<=num;count++){
while(num%count == 0){
ar.add(count);
num /= count;
}
}
return ar;
}
}
The checkbox value printing twice when checkbox checked in in tree view
The checkbox value printing twice when checkbox checked in in tree view
I am new to pythin programming.I need to implement tree view with
checkbox. Below is the code for tree view with checkbox:
import Tix
class View(object):
def __init__(self, root):
self.root = root
self.makeCheckList()
def makeCheckList(self):
self.cl = Tix.CheckList(self.root, browsecmd=self.selectItem)
self.cl.pack()
self.cl.hlist.add("CL1", text="checklist1")
self.cl.hlist.add("CL1.Item1", text="subitem1")
self.cl.hlist.add("CL2", text="checklist2")
self.cl.hlist.add("CL2.Item1", text="subitem1")
self.cl.setstatus("CL2", "on")
self.cl.setstatus("CL2.Item1", "on")
self.cl.setstatus("CL1", "off")
self.cl.setstatus("CL1.Item1", "off")
self.cl.autosetmode()
def selectItem(self, item):
print item, self.cl.getstatus(item)
def main():
root = Tix.Tk()
view = View(root)
root.update()
root.mainloop()
if __name__ == '__main__':
main()
There is a problem if a checkbox is checked the value of checkbox gets
printed twice for single checkin.
Can anyone please help me to solve the issue such that the value has to be
printed once for single checki.
I am new to pythin programming.I need to implement tree view with
checkbox. Below is the code for tree view with checkbox:
import Tix
class View(object):
def __init__(self, root):
self.root = root
self.makeCheckList()
def makeCheckList(self):
self.cl = Tix.CheckList(self.root, browsecmd=self.selectItem)
self.cl.pack()
self.cl.hlist.add("CL1", text="checklist1")
self.cl.hlist.add("CL1.Item1", text="subitem1")
self.cl.hlist.add("CL2", text="checklist2")
self.cl.hlist.add("CL2.Item1", text="subitem1")
self.cl.setstatus("CL2", "on")
self.cl.setstatus("CL2.Item1", "on")
self.cl.setstatus("CL1", "off")
self.cl.setstatus("CL1.Item1", "off")
self.cl.autosetmode()
def selectItem(self, item):
print item, self.cl.getstatus(item)
def main():
root = Tix.Tk()
view = View(root)
root.update()
root.mainloop()
if __name__ == '__main__':
main()
There is a problem if a checkbox is checked the value of checkbox gets
printed twice for single checkin.
Can anyone please help me to solve the issue such that the value has to be
printed once for single checki.
how to use json array key to javascript variable
how to use json array key to javascript variable
i am try json_encode($updateArray);
and this is call by ajax and after ajax success
return me json string on responseText something like this type
{"title":"superAdmin","id":"50"}
now i want to use this two key
like
var text = title;
var id = id;
who can i user this two to as diff. variable.
thanks.
i am try json_encode($updateArray);
and this is call by ajax and after ajax success
return me json string on responseText something like this type
{"title":"superAdmin","id":"50"}
now i want to use this two key
like
var text = title;
var id = id;
who can i user this two to as diff. variable.
thanks.
Friday, 27 September 2013
Clarification on simulation engine for real time multiplayer network game
Clarification on simulation engine for real time multiplayer network game
I've been doing some reading about the various forms of multiplayer that
exist today. In a nut shell, I believe the industry standard way involves
the following:
Running the physics for each client on the client machine/device
Sending the input data of this physics to the server (could be another
client running a 'server' session along with their own client data)
Server processes this data to determine if the client is making legitimate
moves, and if not, forces the client to sync to it's instructions (Rubber
banding).
Server forwards historic data from other clients to each client for
simulation.
Effective result from each clients perspective, is playing themselves in
the present, while seeing the other clients in the past.
Hit detection is performed on the server by 'rewinding' the game state to
see if at the time stamp an event occurred, where the affected players
were at that point in time.
Presently, I use a pure dead-reckoning system. Inputs are collected from
each client and physics calculated on each client. This works, however
units quikcly get out of sync and rubber band because the dependency on a
players previous position/speed/orientation is not high enough. AKA: they
are free to change directions and speed quickly and often.
With that being said, how do I solve this?
Is my client simulator effectively supposed to collect several data points
for each player and interpolate the rendering between those nodes? (IE:
each client has multiple data points about all the other clients historic
positions).
As such, my client's simulator drawing player B, would have positions X0,
X1, X2, X3 in a queue at time 0. Between the transition of Time 0 -> Time
1, I know the starting relevant values (location, speed, orientation, etc)
and where he should be come Time 1.
Is the solution to interpolate these values between these known historic
times and data points?
Thanks!
Ryan
I've been doing some reading about the various forms of multiplayer that
exist today. In a nut shell, I believe the industry standard way involves
the following:
Running the physics for each client on the client machine/device
Sending the input data of this physics to the server (could be another
client running a 'server' session along with their own client data)
Server processes this data to determine if the client is making legitimate
moves, and if not, forces the client to sync to it's instructions (Rubber
banding).
Server forwards historic data from other clients to each client for
simulation.
Effective result from each clients perspective, is playing themselves in
the present, while seeing the other clients in the past.
Hit detection is performed on the server by 'rewinding' the game state to
see if at the time stamp an event occurred, where the affected players
were at that point in time.
Presently, I use a pure dead-reckoning system. Inputs are collected from
each client and physics calculated on each client. This works, however
units quikcly get out of sync and rubber band because the dependency on a
players previous position/speed/orientation is not high enough. AKA: they
are free to change directions and speed quickly and often.
With that being said, how do I solve this?
Is my client simulator effectively supposed to collect several data points
for each player and interpolate the rendering between those nodes? (IE:
each client has multiple data points about all the other clients historic
positions).
As such, my client's simulator drawing player B, would have positions X0,
X1, X2, X3 in a queue at time 0. Between the transition of Time 0 -> Time
1, I know the starting relevant values (location, speed, orientation, etc)
and where he should be come Time 1.
Is the solution to interpolate these values between these known historic
times and data points?
Thanks!
Ryan
compareTo and insert sort
compareTo and insert sort
Not only am I new to programming, but sorting algorithms as well. I am in
an algorithm and design analysis class so I am understanding the concepts
better because of that... until this problem.
My insert sort will not work. Because this is generic I have to do a lot
comparing it seems (or maybe that is just the way I wrote the code). So,
it gives me this error on the temp = list[i] and also in my while loop
"Operator > cannot be applied to operands of type T and int and Cannot
implicitly convert type T to int. Can someone please explain to me why the
compareto I used did not solve this problem. Also, please explain in
detail so I can learn it. Am I needing to compare both temp and j? I could
not figure that out.
using System;
namespace ArrayListNamespace
{
public abstract class ArrayList<T> where T : IComparable
{
protected T[] list;
protected int length;
public ArrayList()
{
list = new T[100];
length = 0;
}
public abstract void insert(ref T item);
public int remove(ref T item)
{
if (length == 0) return 0;
else
{
//find value, if it exists
for (int i = 0; i < length; i++)
{
if (item.Equals(list[i]))
{
list[i] = list[length - 1];
length--;
return 1;
}
}
return -1;
}
}
public void print()
{
for (int i = 0; i < length; i++)
{
Console.WriteLine(list[i]);
}
}
public void removeAll(ref T item)
{
for (; ; )
{
int r = remove(ref item);
if (r == -1) break;
}
}
public T min(ref T item)
{
T tempItem = list[0];
for (int i = 0; i < length; i++)
{
if (list[i].CompareTo(tempItem) < 0)
{
tempItem = list[i];
}
}
return tempItem;
}
public T max(ref T item)
{
T tempItem = list[0];
for (int i = 0; i > length; i++)
{
if (list[i].CompareTo(tempItem) < 0)
{
tempItem = list[i];
}
}
return tempItem;
}
public void insertSort()
{
int temp, j;
for (int i = 1; i < length; i++)
{
if (list[i].CompareTo(temp) < 0)
{
temp = list[i];
j = i - 1;
while (j >= 0 && list[j] > temp)
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = temp;
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnorderedArrayListNamespace;
namespace test
{
class Program
{
static void Main(string[] args)
{
UnorderedArrayList<int> u = new UnorderedArrayList<int>();
Console.WriteLine("This is the list before removal...");
u.print();
int var = 5;
u.insert(ref var);
var = 12;
u.insert(ref var);
var = 2;
u.insert(ref var);
var = 5;
u.insert(ref var);
var = 29;
u.insert(ref var);
var = 33;
u.insert(ref var);
var = 31;
u.insert(ref var);
var = 7;
u.insert(ref var);
var = 13;
u.insert(ref var);
u.print();
Console.WriteLine();
Console.WriteLine("This is the list after removal...");
var = 5;
u.removeAll(ref var);
u.print();
Console.WriteLine("\nThe min value for integers is " + u.min(ref
var));
Console.WriteLine("The max value for integers is " + u.max(ref var));
UnorderedArrayList<string> p = new UnorderedArrayList<string>();
Console.WriteLine("\nThis is the list before removal..."); ;
p.print();
string cow = "cow";
p.insert(ref cow);
cow = "dog";
p.insert(ref cow);
cow = "cat";
p.insert(ref cow);
cow = "wolf";
p.insert(ref cow);
cow = "dog";
p.insert(ref cow);
cow = "whale";
p.insert(ref cow);
cow = "buffalo";
p.insert(ref cow);
cow = "monkey";
p.insert(ref cow);
cow = "walrus";
p.insert(ref cow);
p.print();
Console.WriteLine();
Console.WriteLine("This is the list after removal...");
cow = "cow";
p.removeAll(ref cow);
p.print();
Console.WriteLine("\nThe min value for strings is..." + p.min(ref
cow));
Console.WriteLine("The max value for strings is..." + p.max(ref
cow));
UnorderedArrayList<double> q = new UnorderedArrayList<double>();
Console.WriteLine("\nThis is the list before removal...");
q.print();
double dub = 5.2;
q.insert(ref dub);
q.insert(ref dub);
dub = 12.54;
q.insert(ref dub);
dub = 2.14;
q.insert(ref dub);
dub = 29.13;
q.insert(ref dub);
dub = 3.56;
q.insert(ref dub);
dub = 32.14;
q.insert(ref dub);
dub = 43.23;
q.insert(ref dub);
dub = 2.33;
q.insert(ref dub);
dub = 4.77;
q.insert(ref dub);
dub = 15.46;
q.insert(ref dub);
q.print();
Console.WriteLine();
Console.WriteLine("This is the list after removal...");
dub = 5.2;
q.removeAll(ref dub);
q.print();
Console.WriteLine("\nThe min value for double is " + q.min(ref dub));
Console.WriteLine("The max value for double is " + q.max(ref dub));
Console.WriteLine();
}
}
}
using System;
namespace ArrayListADTNamespace
{
public interface ArrayListADT<T>
{
// insert() method places one item in the list
void insert(ref T item);
// remove() method removes first instance of item in list
int remove(ref T item);
// print() method prints all items in list
void print();
// removal all method
void removeAll(ref T item);
// min method
T min(ref T item);
// max method
T max(ref T item);
void insertSort();
}
}
using System;
using ArrayListNamespace;
using ArrayListADTNamespace;
namespace UnorderedArrayListNamespace
{
public class UnorderedArrayList<T> : ArrayList<T>, ArrayListADT<T> where
T: IComparable
{
public UnorderedArrayList()
{
}
public override void insert(ref T item)
{
list[length] = item;
length++;
}
}
}
Not only am I new to programming, but sorting algorithms as well. I am in
an algorithm and design analysis class so I am understanding the concepts
better because of that... until this problem.
My insert sort will not work. Because this is generic I have to do a lot
comparing it seems (or maybe that is just the way I wrote the code). So,
it gives me this error on the temp = list[i] and also in my while loop
"Operator > cannot be applied to operands of type T and int and Cannot
implicitly convert type T to int. Can someone please explain to me why the
compareto I used did not solve this problem. Also, please explain in
detail so I can learn it. Am I needing to compare both temp and j? I could
not figure that out.
using System;
namespace ArrayListNamespace
{
public abstract class ArrayList<T> where T : IComparable
{
protected T[] list;
protected int length;
public ArrayList()
{
list = new T[100];
length = 0;
}
public abstract void insert(ref T item);
public int remove(ref T item)
{
if (length == 0) return 0;
else
{
//find value, if it exists
for (int i = 0; i < length; i++)
{
if (item.Equals(list[i]))
{
list[i] = list[length - 1];
length--;
return 1;
}
}
return -1;
}
}
public void print()
{
for (int i = 0; i < length; i++)
{
Console.WriteLine(list[i]);
}
}
public void removeAll(ref T item)
{
for (; ; )
{
int r = remove(ref item);
if (r == -1) break;
}
}
public T min(ref T item)
{
T tempItem = list[0];
for (int i = 0; i < length; i++)
{
if (list[i].CompareTo(tempItem) < 0)
{
tempItem = list[i];
}
}
return tempItem;
}
public T max(ref T item)
{
T tempItem = list[0];
for (int i = 0; i > length; i++)
{
if (list[i].CompareTo(tempItem) < 0)
{
tempItem = list[i];
}
}
return tempItem;
}
public void insertSort()
{
int temp, j;
for (int i = 1; i < length; i++)
{
if (list[i].CompareTo(temp) < 0)
{
temp = list[i];
j = i - 1;
while (j >= 0 && list[j] > temp)
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = temp;
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnorderedArrayListNamespace;
namespace test
{
class Program
{
static void Main(string[] args)
{
UnorderedArrayList<int> u = new UnorderedArrayList<int>();
Console.WriteLine("This is the list before removal...");
u.print();
int var = 5;
u.insert(ref var);
var = 12;
u.insert(ref var);
var = 2;
u.insert(ref var);
var = 5;
u.insert(ref var);
var = 29;
u.insert(ref var);
var = 33;
u.insert(ref var);
var = 31;
u.insert(ref var);
var = 7;
u.insert(ref var);
var = 13;
u.insert(ref var);
u.print();
Console.WriteLine();
Console.WriteLine("This is the list after removal...");
var = 5;
u.removeAll(ref var);
u.print();
Console.WriteLine("\nThe min value for integers is " + u.min(ref
var));
Console.WriteLine("The max value for integers is " + u.max(ref var));
UnorderedArrayList<string> p = new UnorderedArrayList<string>();
Console.WriteLine("\nThis is the list before removal..."); ;
p.print();
string cow = "cow";
p.insert(ref cow);
cow = "dog";
p.insert(ref cow);
cow = "cat";
p.insert(ref cow);
cow = "wolf";
p.insert(ref cow);
cow = "dog";
p.insert(ref cow);
cow = "whale";
p.insert(ref cow);
cow = "buffalo";
p.insert(ref cow);
cow = "monkey";
p.insert(ref cow);
cow = "walrus";
p.insert(ref cow);
p.print();
Console.WriteLine();
Console.WriteLine("This is the list after removal...");
cow = "cow";
p.removeAll(ref cow);
p.print();
Console.WriteLine("\nThe min value for strings is..." + p.min(ref
cow));
Console.WriteLine("The max value for strings is..." + p.max(ref
cow));
UnorderedArrayList<double> q = new UnorderedArrayList<double>();
Console.WriteLine("\nThis is the list before removal...");
q.print();
double dub = 5.2;
q.insert(ref dub);
q.insert(ref dub);
dub = 12.54;
q.insert(ref dub);
dub = 2.14;
q.insert(ref dub);
dub = 29.13;
q.insert(ref dub);
dub = 3.56;
q.insert(ref dub);
dub = 32.14;
q.insert(ref dub);
dub = 43.23;
q.insert(ref dub);
dub = 2.33;
q.insert(ref dub);
dub = 4.77;
q.insert(ref dub);
dub = 15.46;
q.insert(ref dub);
q.print();
Console.WriteLine();
Console.WriteLine("This is the list after removal...");
dub = 5.2;
q.removeAll(ref dub);
q.print();
Console.WriteLine("\nThe min value for double is " + q.min(ref dub));
Console.WriteLine("The max value for double is " + q.max(ref dub));
Console.WriteLine();
}
}
}
using System;
namespace ArrayListADTNamespace
{
public interface ArrayListADT<T>
{
// insert() method places one item in the list
void insert(ref T item);
// remove() method removes first instance of item in list
int remove(ref T item);
// print() method prints all items in list
void print();
// removal all method
void removeAll(ref T item);
// min method
T min(ref T item);
// max method
T max(ref T item);
void insertSort();
}
}
using System;
using ArrayListNamespace;
using ArrayListADTNamespace;
namespace UnorderedArrayListNamespace
{
public class UnorderedArrayList<T> : ArrayList<T>, ArrayListADT<T> where
T: IComparable
{
public UnorderedArrayList()
{
}
public override void insert(ref T item)
{
list[length] = item;
length++;
}
}
}
How to make a button trigger a select drop down options
How to make a button trigger a select drop down options
Im wondering is there is any possible way to link an object to a / tag? I
have a select with three options and I would the users to trigger the
option choices by clicking on an external button?
At this point, I have my select options button, which when I click on,
displays the three optionsin a drop down.
How to make a click on another button opens this three options drop down
as well? Any example would be great!
thank you very much
Im wondering is there is any possible way to link an object to a / tag? I
have a select with three options and I would the users to trigger the
option choices by clicking on an external button?
At this point, I have my select options button, which when I click on,
displays the three optionsin a drop down.
How to make a click on another button opens this three options drop down
as well? Any example would be great!
thank you very much
Mahout - Recommender Evaluator Returns 0.0
Mahout - Recommender Evaluator Returns 0.0
Alright, I'm VERY new to Mahout and java. I'm trying to evaluate a
recommender and the code below returns 0.0 EVERY TIME, no matter the
distance measure or cluster size I use. Clearly, it's not splitting the
training and testing data at all, and I'm not sure why.
Any help with this code is appreciated!
public class Example {
public static void main(String[] args) throws Exception {
final DataModel model = new FileDataModel(new File("FILENAME")) ;
RecommenderEvaluator evaluator = new
AverageAbsoluteDifferenceRecommenderEvaluator();
RecommenderBuilder recommenderBuilder = new RecommenderBuilder() {
@Override
public Recommender buildRecommender(DataModel dataModel) throws
TasteException {
UserSimilarity similarity = new
PearsonCorrelationSimilarity(model);
ClusterSimilarity clusterSimilarity = new
NearestNeighborClusterSimilarity(similarity);
TreeClusteringRecommender tree = new
TreeClusteringRecommender(model, clusterSimilarity, 50);
return tree;
}
} ;
double score = evaluator.evaluate(recommenderBuilder, null, model, .7, 1.0);
System.out.println(score);
}
}
Thank you!
Alright, I'm VERY new to Mahout and java. I'm trying to evaluate a
recommender and the code below returns 0.0 EVERY TIME, no matter the
distance measure or cluster size I use. Clearly, it's not splitting the
training and testing data at all, and I'm not sure why.
Any help with this code is appreciated!
public class Example {
public static void main(String[] args) throws Exception {
final DataModel model = new FileDataModel(new File("FILENAME")) ;
RecommenderEvaluator evaluator = new
AverageAbsoluteDifferenceRecommenderEvaluator();
RecommenderBuilder recommenderBuilder = new RecommenderBuilder() {
@Override
public Recommender buildRecommender(DataModel dataModel) throws
TasteException {
UserSimilarity similarity = new
PearsonCorrelationSimilarity(model);
ClusterSimilarity clusterSimilarity = new
NearestNeighborClusterSimilarity(similarity);
TreeClusteringRecommender tree = new
TreeClusteringRecommender(model, clusterSimilarity, 50);
return tree;
}
} ;
double score = evaluator.evaluate(recommenderBuilder, null, model, .7, 1.0);
System.out.println(score);
}
}
Thank you!
Assembly Code Optimization
Assembly Code Optimization
I have experience programming with C and C++ but i am totally new to
assembly coding. The first assembly code i wrote, failed to beat the
compiler optimization. I have a couple of questions regarding assembly
coding. Would really appreciate if i can get answers to this.
Q1> Is it a good idea to push stuff on stack now and then?
Q2> Is it better to do register transfers than to push them on stack and
re-use it?
Q3> Is loading a value in register and re-using it better than using the
value directly?
Q4> Is it a good idea to put loops in assembly to reduce code size?
Thanks!
I have experience programming with C and C++ but i am totally new to
assembly coding. The first assembly code i wrote, failed to beat the
compiler optimization. I have a couple of questions regarding assembly
coding. Would really appreciate if i can get answers to this.
Q1> Is it a good idea to push stuff on stack now and then?
Q2> Is it better to do register transfers than to push them on stack and
re-use it?
Q3> Is loading a value in register and re-using it better than using the
value directly?
Q4> Is it a good idea to put loops in assembly to reduce code size?
Thanks!
How to moniter memory allocated by some java method at runtime
How to moniter memory allocated by some java method at runtime
I am creating a java program in which my class suppose A has it's some
predefined behavior. But user can over-ride my class to change its
behavior. so my script will check if there is some subclass than i will
call it's behavior but what if he has written some blocking code or memory
leek in his code. This may harm my process. is there is any way in java to
moniter memory allocated by some method.
Please suggest.
I am creating a java program in which my class suppose A has it's some
predefined behavior. But user can over-ride my class to change its
behavior. so my script will check if there is some subclass than i will
call it's behavior but what if he has written some blocking code or memory
leek in his code. This may harm my process. is there is any way in java to
moniter memory allocated by some method.
Please suggest.
Thursday, 26 September 2013
Javascript regex matching literal \\n
Javascript regex matching literal \\n
Stumbled on this little oddity today, can someone explain?
x = 'a \\n b';
x.replace(/\\n/g, '<br>'); // => "a <br> b"
x.replace(RegExp('\\n', 'g'), '<br>'); // => "a \\n b"
x.replace(RegExp('\\n', 'gm'), '<br>'); // => "a <br> b"
I assumed /\\n/g and RegExp('\\n', 'g') would be equivalent, but that
doesn't seem to be the case. In what cases will using one method over the
other give different results?
Why is the multiline flag needed, and only when using a RegExp object?
Stumbled on this little oddity today, can someone explain?
x = 'a \\n b';
x.replace(/\\n/g, '<br>'); // => "a <br> b"
x.replace(RegExp('\\n', 'g'), '<br>'); // => "a \\n b"
x.replace(RegExp('\\n', 'gm'), '<br>'); // => "a <br> b"
I assumed /\\n/g and RegExp('\\n', 'g') would be equivalent, but that
doesn't seem to be the case. In what cases will using one method over the
other give different results?
Why is the multiline flag needed, and only when using a RegExp object?
Wednesday, 25 September 2013
I have WPF window that i want to Print on paper size **4inch by 6inch**
I have WPF window that i want to Print on paper size **4inch by 6inch**
I have WPF window that i want to Print on paper size 4inch by 6inch.
i dont understand where to set this size?? i am using window size to print
but window size its not working. my printer is not fixed paper size.
this is my print code:
private void _print()
{
PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
//printDlg.ShowDialog();
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities =
printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth
/ this.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
this.ActualHeight);
//Transform the Visual to scale
this.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
Size sz = new Size(this.ActualWidth, this.ActualHeight);
//update the layout of the visual to the printer page size.
this.Measure(sz);
this.Arrange(new Rect(new
Point(capabilities.PageImageableArea.OriginWidth,
capabilities.PageImageableArea.OriginHeight), sz));
//now print the visual to printer to fit on the one page.
printDlg.PrintVisual(this, "Print Page");
}
I have WPF window that i want to Print on paper size 4inch by 6inch.
i dont understand where to set this size?? i am using window size to print
but window size its not working. my printer is not fixed paper size.
this is my print code:
private void _print()
{
PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
//printDlg.ShowDialog();
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities =
printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth
/ this.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
this.ActualHeight);
//Transform the Visual to scale
this.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
Size sz = new Size(this.ActualWidth, this.ActualHeight);
//update the layout of the visual to the printer page size.
this.Measure(sz);
this.Arrange(new Rect(new
Point(capabilities.PageImageableArea.OriginWidth,
capabilities.PageImageableArea.OriginHeight), sz));
//now print the visual to printer to fit on the one page.
printDlg.PrintVisual(this, "Print Page");
}
Thursday, 19 September 2013
PHP adding to sessions
PHP adding to sessions
I am making an online quiz, in this quiz, one question is asked at a time.
If the answer is correct, I want to add that point, to the total score
earned. I want the $_SESSION to show how many points the user has earned
so far. The code I have so far is this:
$sql = "SELECT * FROM quiz_questions WHERE Question='$question' AND
Answer='$answer'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if ($num_rows != 0){
$score++;
$total_score += $score;
session_start();
$_SESSION['score'] = $total_score;
} else {
echo "Incorrect";
}
}
I already have $score equal to 0 to start in the beginning of the code.
Thank you in advance for all your help!
I am making an online quiz, in this quiz, one question is asked at a time.
If the answer is correct, I want to add that point, to the total score
earned. I want the $_SESSION to show how many points the user has earned
so far. The code I have so far is this:
$sql = "SELECT * FROM quiz_questions WHERE Question='$question' AND
Answer='$answer'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if ($num_rows != 0){
$score++;
$total_score += $score;
session_start();
$_SESSION['score'] = $total_score;
} else {
echo "Incorrect";
}
}
I already have $score equal to 0 to start in the beginning of the code.
Thank you in advance for all your help!
Highscores - Best time period for a user
Highscores - Best time period for a user
I have a table which keeps track of data from a game, here is an example
of the table:
id | player_name | date | score | kills
1 | test1 | 2013-01-01 00:00:00 | 10000 | 200
2 | test1 | 2013-01-01 00:01:00 | 12000 | 300
I have a leaderboards for players, it ranks people who gain the most
score/kills, etc. in a certain time period. At the moment I have only got
it so that it ranks players in the previous 24 hours. I am doing this by
selecting the first and last records in a specified time period and then
subtracting them to get the difference.
This is my current query:
SELECT date, score FROM datapoints WHERE player_name = :player AND date =
(SELECT MIN(date) FROM datapoints WHERE player_name = :player AND date >
DATE_SUB(CURDATE(), INTERVAL 24 HOUR))
UNION ALL
SELECT date, score FROM datapoints WHERE player_name = :player AND date =
(SELECT MAX(date) FROM datapoints WHERE player_name = :player AND date >
DATE_SUB(CURDATE(), INTERVAL 24 HOUR))
After subtracting I use the PHP arsort() function to order them and then
display them on the page.
However, I want to add another feature. I want to be able to see the on
which day was the users best day for score/kills.
I have been thinking of how I could possibly do it and one was was using
the above query but having a loop for each day and taking out the best
day, however this probably isn't very efficient and I was wondering, if
there was a better way of doing this?
I have a table which keeps track of data from a game, here is an example
of the table:
id | player_name | date | score | kills
1 | test1 | 2013-01-01 00:00:00 | 10000 | 200
2 | test1 | 2013-01-01 00:01:00 | 12000 | 300
I have a leaderboards for players, it ranks people who gain the most
score/kills, etc. in a certain time period. At the moment I have only got
it so that it ranks players in the previous 24 hours. I am doing this by
selecting the first and last records in a specified time period and then
subtracting them to get the difference.
This is my current query:
SELECT date, score FROM datapoints WHERE player_name = :player AND date =
(SELECT MIN(date) FROM datapoints WHERE player_name = :player AND date >
DATE_SUB(CURDATE(), INTERVAL 24 HOUR))
UNION ALL
SELECT date, score FROM datapoints WHERE player_name = :player AND date =
(SELECT MAX(date) FROM datapoints WHERE player_name = :player AND date >
DATE_SUB(CURDATE(), INTERVAL 24 HOUR))
After subtracting I use the PHP arsort() function to order them and then
display them on the page.
However, I want to add another feature. I want to be able to see the on
which day was the users best day for score/kills.
I have been thinking of how I could possibly do it and one was was using
the above query but having a loop for each day and taking out the best
day, however this probably isn't very efficient and I was wondering, if
there was a better way of doing this?
Restart Computer via Flex Application
Restart Computer via Flex Application
I need to restart the computer via a Flex Application, I tried these
methods :
1st
var process:NativeProcess;
var nativeProcessStartupInfo:NativeProcessStartupInfo = new
NativeProcessStartupInfo();
var file:File =
File.applicationDirectory.resolvePath("assets/reboot.bat");
nativeProcessStartupInfo.executable = file;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
2nd
var nativeProcessStartupInfo:NativeProcessStartupInfo = new
NativeProcessStartupInfo();
var mp:File = new File();
mp = mp.resolvePath('C:\Windows\System32\cmd.exe');
nativeProcessStartupInfo.executable = mp;
var args:Vector.<String> = new Vector.<String>();
args.push('shutdown.exe /s /t 00');
nativeProcessStartupInfo.arguments = args;
var process:NativeProcess = new NativeProcess();
process.start(nativeProcessStartupInfo);
Finally, in here I have my file inside a directory named fscommand in the
same directory containing the main application
fscommand("exec", "reboot.bat");
and the reboot.bat contain shutdown.exe /s /t 00
But none of this works ... can anyone help me with this ^^ Thank you
I need to restart the computer via a Flex Application, I tried these
methods :
1st
var process:NativeProcess;
var nativeProcessStartupInfo:NativeProcessStartupInfo = new
NativeProcessStartupInfo();
var file:File =
File.applicationDirectory.resolvePath("assets/reboot.bat");
nativeProcessStartupInfo.executable = file;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
2nd
var nativeProcessStartupInfo:NativeProcessStartupInfo = new
NativeProcessStartupInfo();
var mp:File = new File();
mp = mp.resolvePath('C:\Windows\System32\cmd.exe');
nativeProcessStartupInfo.executable = mp;
var args:Vector.<String> = new Vector.<String>();
args.push('shutdown.exe /s /t 00');
nativeProcessStartupInfo.arguments = args;
var process:NativeProcess = new NativeProcess();
process.start(nativeProcessStartupInfo);
Finally, in here I have my file inside a directory named fscommand in the
same directory containing the main application
fscommand("exec", "reboot.bat");
and the reboot.bat contain shutdown.exe /s /t 00
But none of this works ... can anyone help me with this ^^ Thank you
Updating a single cell (not the entire row) in slickgrid with DataView
Updating a single cell (not the entire row) in slickgrid with DataView
I have a slickgrid (using a DataView) that I'm using to display rapidly
changing values. As far as I know, when a value changes in the underlying
model, the only choice I have is to update the entire row:
dataView.updateItem(rowId, rowData);
Unfortunately, even if certain values haven't changed (i.e. I'm only
updating one cell's value in the entire row), slickgrid repaints the
entire row (I'm using the Chrome dev tools to see what is being rendered).
I also have a implementation of the same UI and here I'm able to paint
individual cells (or groups of cells) that update, and rendering is
roughly 3x as fast. It's not exactly apples-to-apples, but I would like to
be able to limit the amount of painting that occurs if possible,
considering on any given update, generally only one or two cells (on a
long row of data) have changed.
I have a slickgrid (using a DataView) that I'm using to display rapidly
changing values. As far as I know, when a value changes in the underlying
model, the only choice I have is to update the entire row:
dataView.updateItem(rowId, rowData);
Unfortunately, even if certain values haven't changed (i.e. I'm only
updating one cell's value in the entire row), slickgrid repaints the
entire row (I'm using the Chrome dev tools to see what is being rendered).
I also have a implementation of the same UI and here I'm able to paint
individual cells (or groups of cells) that update, and rendering is
roughly 3x as fast. It's not exactly apples-to-apples, but I would like to
be able to limit the amount of painting that occurs if possible,
considering on any given update, generally only one or two cells (on a
long row of data) have changed.
UIActivityViewController in iOS 7
UIActivityViewController in iOS 7
In my app i have added these lines of codes to incorporate the
functionality of uiactivityviewcontroller
UIImage *yourImage = someImg;
UIActivityViewController *activityVC = [[UIActivityViewController
alloc] initWithActivityItems:[NSArray
arrayWithObjects:@"abcdefgh",yourImage, nil]
applicationActivities:nil];
activityVC.excludedActivityTypes = @[ UIActivityTypeMessage
,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
[self presentViewController:activityVC animated:YES completion:nil];
and UIActivityViewContoller working fine , but the UI is like this No FB
icon , No twitter icon
However it is showing perfect UI in iOS 6 . Could Any one tell the the
reason or the answer... Thanks in Advance ...
In my app i have added these lines of codes to incorporate the
functionality of uiactivityviewcontroller
UIImage *yourImage = someImg;
UIActivityViewController *activityVC = [[UIActivityViewController
alloc] initWithActivityItems:[NSArray
arrayWithObjects:@"abcdefgh",yourImage, nil]
applicationActivities:nil];
activityVC.excludedActivityTypes = @[ UIActivityTypeMessage
,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
[self presentViewController:activityVC animated:YES completion:nil];
and UIActivityViewContoller working fine , but the UI is like this No FB
icon , No twitter icon
However it is showing perfect UI in iOS 6 . Could Any one tell the the
reason or the answer... Thanks in Advance ...
Looking up enum label by value
Looking up enum label by value
I have the following enum in my java android application:
static enum PaymentType
{
Scheme(0), Topup(1), Normal(2), Free(3), Promotion(4), Discount(5),
Partial(6),
Refund(7), NoShow(8), Prepay(9), Customer(10), Return(11), Change(12),
PettyCash(13),
StateTax(14), LocalTax(15), Voucher(16), Membership(17), Gratuity(18),
Overpayment(19),
PrepayTime(20), HandlingFee(21);
private int value;
private PaymentType(int i) {
value = i;
}
public int getValue() {
return value;
}
}
I use this enum alot to find out the integer value of one of these string
labels, for example int i = Lookups.PaymentType.Voucher.getValue();.
How can I do this the other way around? I have an integer value from a
database and I need to find which string that corresponds to.
I have the following enum in my java android application:
static enum PaymentType
{
Scheme(0), Topup(1), Normal(2), Free(3), Promotion(4), Discount(5),
Partial(6),
Refund(7), NoShow(8), Prepay(9), Customer(10), Return(11), Change(12),
PettyCash(13),
StateTax(14), LocalTax(15), Voucher(16), Membership(17), Gratuity(18),
Overpayment(19),
PrepayTime(20), HandlingFee(21);
private int value;
private PaymentType(int i) {
value = i;
}
public int getValue() {
return value;
}
}
I use this enum alot to find out the integer value of one of these string
labels, for example int i = Lookups.PaymentType.Voucher.getValue();.
How can I do this the other way around? I have an integer value from a
database and I need to find which string that corresponds to.
How to disable header button of a collapsible in jquery mobile?
How to disable header button of a collapsible in jquery mobile?
I have a simple collapsible, made with jquery mobile. How can i disable
the button in the header of the collapsible which is meant to expand
collapse the collapsible? I want to disable it, being still able to
collapse/expand programmatically. The whole thing is meant to prevent the
user to collapse/expand in order to have the complete programmatical
control of the moment a collapsible has to be expanded or not.
<div data-role="collapsible" data-collapsed="true" id="d27" name="d27"
class="ui-block-a">
<h4></h4>
<div class="ui-block-a">
<legend>D27: Dopo il test, ti sei poi iscritto ad Economia alla
Sapienza?</legend>
</div>
<div class="ui-block-b">
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="iscrittoEconomia" id="si27" value="1" />
<label for="si27">Sì</label>
<input type="radio" name="iscrittoEconomia" id="no27" value="0"
checked="checked" />
<label for="no27">No</label>
</fieldset>
</div>
</div>
This is the button i mean:
I have a simple collapsible, made with jquery mobile. How can i disable
the button in the header of the collapsible which is meant to expand
collapse the collapsible? I want to disable it, being still able to
collapse/expand programmatically. The whole thing is meant to prevent the
user to collapse/expand in order to have the complete programmatical
control of the moment a collapsible has to be expanded or not.
<div data-role="collapsible" data-collapsed="true" id="d27" name="d27"
class="ui-block-a">
<h4></h4>
<div class="ui-block-a">
<legend>D27: Dopo il test, ti sei poi iscritto ad Economia alla
Sapienza?</legend>
</div>
<div class="ui-block-b">
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="iscrittoEconomia" id="si27" value="1" />
<label for="si27">Sì</label>
<input type="radio" name="iscrittoEconomia" id="no27" value="0"
checked="checked" />
<label for="no27">No</label>
</fieldset>
</div>
</div>
This is the button i mean:
Wednesday, 18 September 2013
IMAPLIB socket.error: [Errno 104] Connection reset by peer
IMAPLIB socket.error: [Errno 104] Connection reset by peer
using login() method of imaplib throws
socket.error: [Errno 104] Connection reset by peer
Sometimes the same code works and some times it doesn't. please explain
the reason of it and how to overcome this error
import imaplib
imap_server = imaplib.IMAP4_SSL('imap.gmail.com')
print imap_server
imap_server.login('xxxxxxxxxx@gmail.com', 'xxxxxxxxxxx')
imap_server.select('INBOX')
using login() method of imaplib throws
socket.error: [Errno 104] Connection reset by peer
Sometimes the same code works and some times it doesn't. please explain
the reason of it and how to overcome this error
import imaplib
imap_server = imaplib.IMAP4_SSL('imap.gmail.com')
print imap_server
imap_server.login('xxxxxxxxxx@gmail.com', 'xxxxxxxxxxx')
imap_server.select('INBOX')
NoSuchMethodError when using Apache Tika
NoSuchMethodError when using Apache Tika
The following error is encountered when I extract the metadata of a JPEG
image using Apache Tika
java.lang.NoSuchMethodError:
com.adobe.xmp.properties.XMPPropertyInfo.getValue()Ljava/lang/Object;
at com.drew.metadata.xmp.XmpReader.extract(Unknown Source)
at
com.drew.imaging.jpeg.JpegMetadataReader.extractMetadataFromJpegSegmentReader(Unknown
Source)
at com.drew.imaging.jpeg.JpegMetadataReader.readMetadata(Unknown Source)
at
org.apache.tika.parser.image.ImageMetadataExtractor.parseJpeg(ImageMetadataExtractor.java:91)
at org.apache.tika.parser.jpeg.JpegParser.parse(JpegParser.java:56)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:120
Tika version being used: Tika 1.4
What is the cause of the error?
Also note that the metadata for an image that doesn't contain any XMP
metadata is extracted by the API correctly. This error occurs only for
those images that have XMP metadata.
The following error is encountered when I extract the metadata of a JPEG
image using Apache Tika
java.lang.NoSuchMethodError:
com.adobe.xmp.properties.XMPPropertyInfo.getValue()Ljava/lang/Object;
at com.drew.metadata.xmp.XmpReader.extract(Unknown Source)
at
com.drew.imaging.jpeg.JpegMetadataReader.extractMetadataFromJpegSegmentReader(Unknown
Source)
at com.drew.imaging.jpeg.JpegMetadataReader.readMetadata(Unknown Source)
at
org.apache.tika.parser.image.ImageMetadataExtractor.parseJpeg(ImageMetadataExtractor.java:91)
at org.apache.tika.parser.jpeg.JpegParser.parse(JpegParser.java:56)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:120
Tika version being used: Tika 1.4
What is the cause of the error?
Also note that the metadata for an image that doesn't contain any XMP
metadata is extracted by the API correctly. This error occurs only for
those images that have XMP metadata.
Express Middleware to populate a Jade variable for all app.get()'s
Express Middleware to populate a Jade variable for all app.get()'s
I have a Jade file that all of my templates extend called layout.jade. In
it I want to be able to have a logout button if the user is currently
logged in (this is kept track of in req.session).
So layout.jade will have something like,
-if (loggedin)
a.navButton(href="/logout") Log Out
The route for a page would look something like,
app.get("/foo", function(req, res) {
res.render("foo", {loggedin: req.session.isValidUser});
});
The thing is, I don't want to have to populate the loggedin variable
manually in every single route. Is there a way I can use Express
middleware to automatically set some default options for the object sent
to res.render? Or is there a better method to do this?
I have a Jade file that all of my templates extend called layout.jade. In
it I want to be able to have a logout button if the user is currently
logged in (this is kept track of in req.session).
So layout.jade will have something like,
-if (loggedin)
a.navButton(href="/logout") Log Out
The route for a page would look something like,
app.get("/foo", function(req, res) {
res.render("foo", {loggedin: req.session.isValidUser});
});
The thing is, I don't want to have to populate the loggedin variable
manually in every single route. Is there a way I can use Express
middleware to automatically set some default options for the object sent
to res.render? Or is there a better method to do this?
codeigniter password protect directory with cpanel
codeigniter password protect directory with cpanel
i want to protect my admin panel with password protect directory in
cpanel. The directory structure is;
application
controller
views
admin(directory)
bla.php
models
i want to protect admin directory in views and i set a password in cpanel
but it doesn't work correctly. when i reached www.blabla.com/admin it
doesn't work, when i reached www.blabla.com/application/views/admin it
works. how can i solve it?
note: i removed index.php via .htaccess
i want to protect my admin panel with password protect directory in
cpanel. The directory structure is;
application
controller
views
admin(directory)
bla.php
models
i want to protect admin directory in views and i set a password in cpanel
but it doesn't work correctly. when i reached www.blabla.com/admin it
doesn't work, when i reached www.blabla.com/application/views/admin it
works. how can i solve it?
note: i removed index.php via .htaccess
C# Variable scope in switch statement
C# Variable scope in switch statement
I have a function that begins with this:
void RecordLoadPosition()
{
OdbcCommand command;
if (_hasPlantGenie)
{
command = new OdbcCommand();
string query;
switch (ItemType)
{
case ItemTypeEnum.COIL:
// We're only going to add records to the coils_pg
table when the coil gets moved. After
// a record is added, we'll update it.
command = new OdbcCommand("select * from coils_pg where
coil_id = " + _itemName, _db);
When I compile this, I do not get an error on the first line in the if
block, but I get errors complaining that I cannot use "command" before it
is declared inside the case block. I don't understand why the declaration
at the top of the function is not available inside the case block.
But OK. If it's not visible in the case block, I can just declare it. I
changed the first statement in the case block to "OdbcCommand command...".
Now I get an error complaining that I can't declare a variable that is
already declared in a parent block! I can't win either way!
What is happening here?
Of course, I can just use different OdbcCommand objects, and that's what
I'll do for now, but I'd like to understand this.
I have a function that begins with this:
void RecordLoadPosition()
{
OdbcCommand command;
if (_hasPlantGenie)
{
command = new OdbcCommand();
string query;
switch (ItemType)
{
case ItemTypeEnum.COIL:
// We're only going to add records to the coils_pg
table when the coil gets moved. After
// a record is added, we'll update it.
command = new OdbcCommand("select * from coils_pg where
coil_id = " + _itemName, _db);
When I compile this, I do not get an error on the first line in the if
block, but I get errors complaining that I cannot use "command" before it
is declared inside the case block. I don't understand why the declaration
at the top of the function is not available inside the case block.
But OK. If it's not visible in the case block, I can just declare it. I
changed the first statement in the case block to "OdbcCommand command...".
Now I get an error complaining that I can't declare a variable that is
already declared in a parent block! I can't win either way!
What is happening here?
Of course, I can just use different OdbcCommand objects, and that's what
I'll do for now, but I'd like to understand this.
How simulate the key press event by Qt and use it in JavaScript of QML?
How simulate the key press event by Qt and use it in JavaScript of QML?
I write a program for embedded and my device have physics button and
clickable icons above of this buttons. User can press buttons or touch
icons. Icons must generate keycode as buttons keycode. So icons must
simulate keypress event and translate it to focused items. I new in Qt and
QML. The some tips here very little help me.
I write a program for embedded and my device have physics button and
clickable icons above of this buttons. User can press buttons or touch
icons. Icons must generate keycode as buttons keycode. So icons must
simulate keypress event and translate it to focused items. I new in Qt and
QML. The some tips here very little help me.
android broadcastreceiver vs listeners
android broadcastreceiver vs listeners
If you have a Service that frequently (every second or half a second)
sends updates, are there pros/cons to using Broadcasts vs registering
Listeners (an Interface you create) that get stored in some sort of List
in the Service and sending out updates that way?
I'm thinking in terms of memory usage, battery consumption, etc. I know
it's a little bit open ended, however, there's not much in terms of
documentation so they can be equal, but if someone knows a definite answer
or has some input, it would be appreciated.
If you have a Service that frequently (every second or half a second)
sends updates, are there pros/cons to using Broadcasts vs registering
Listeners (an Interface you create) that get stored in some sort of List
in the Service and sending out updates that way?
I'm thinking in terms of memory usage, battery consumption, etc. I know
it's a little bit open ended, however, there's not much in terms of
documentation so they can be equal, but if someone knows a definite answer
or has some input, it would be appreciated.
Tuesday, 17 September 2013
Python error in functions
Python error in functions
I am an absolute beginner in python. I was practicing simple python code
of functions from a tutorial. But I am getting some wierd error when i try
running this code snippet from terminal. What is the role of main in this
can someone explain me?
def donuts(count):
if count < 10:
return 'Number of donuts: ' +str(count)
else:
return 'Number of donuts: many'
if __name__ == '__main__':
main()
I am an absolute beginner in python. I was practicing simple python code
of functions from a tutorial. But I am getting some wierd error when i try
running this code snippet from terminal. What is the role of main in this
can someone explain me?
def donuts(count):
if count < 10:
return 'Number of donuts: ' +str(count)
else:
return 'Number of donuts: many'
if __name__ == '__main__':
main()
Read/write to same excel file using Apache POI
Read/write to same excel file using Apache POI
i want to read an excel and write to the same excel based on some
conditions. for example
Empno Name Salary
1 jonh 2000
2 Sam 3000
3 Dean 7000
Now my requrient is
1) want to read the data based on column name say 'Name' and get all the
data under that column
2) in the same way based on the column name say 'Name' i want to add one
more row of data ie data should be in the following way after adding new
row to same excel file
Empno Name Salary
1 jonh 2000
2 Sam 3000
3 Dean 7000
4 Smith 8000
how to do this using Apache POI.
can anybody provide me an example . i want to read/read to the same excel
donot want to create a new excel.
thanks in advance.
i want to read an excel and write to the same excel based on some
conditions. for example
Empno Name Salary
1 jonh 2000
2 Sam 3000
3 Dean 7000
Now my requrient is
1) want to read the data based on column name say 'Name' and get all the
data under that column
2) in the same way based on the column name say 'Name' i want to add one
more row of data ie data should be in the following way after adding new
row to same excel file
Empno Name Salary
1 jonh 2000
2 Sam 3000
3 Dean 7000
4 Smith 8000
how to do this using Apache POI.
can anybody provide me an example . i want to read/read to the same excel
donot want to create a new excel.
thanks in advance.
How to uncheck a checkbox
How to uncheck a checkbox
Here is the HTML Code:
<div class="text">
<input value="true" type="checkbox" checked=""
name="copyNewAddrToBilling"><label>
I want to change the value to false. Or just uncheck the checkbox
Here is the HTML Code:
<div class="text">
<input value="true" type="checkbox" checked=""
name="copyNewAddrToBilling"><label>
I want to change the value to false. Or just uncheck the checkbox
Page-Break-inside property is not working in chrome
Page-Break-inside property is not working in chrome
I have a long table data, which having many of the rows and nested tables.
When I am printing this data then the rows of the table and nested tables
are just break on the page break, means tables and data are split into
pages, So I use following CSS property there:-
table tr {
page-break-inside:avoid;
position:relative;
}
But this is not working in my case, you can see the live demo here
:--http://jsfiddle.net/npsingh/S8vr8/2/show/
Please edit the code by following link:--
http://jsfiddle.net/npsingh/S8vr8/2/
I am using Google Chrome Version 29.0.1547.66 m
Please let me know where the problem exactly. Thanks
I have a long table data, which having many of the rows and nested tables.
When I am printing this data then the rows of the table and nested tables
are just break on the page break, means tables and data are split into
pages, So I use following CSS property there:-
table tr {
page-break-inside:avoid;
position:relative;
}
But this is not working in my case, you can see the live demo here
:--http://jsfiddle.net/npsingh/S8vr8/2/show/
Please edit the code by following link:--
http://jsfiddle.net/npsingh/S8vr8/2/
I am using Google Chrome Version 29.0.1547.66 m
Please let me know where the problem exactly. Thanks
MySQL exception handler access exception being handled
MySQL exception handler access exception being handled
I'm trying to rollback on an error, but still let the client receive the
error. This might actually be impossible, unless there is a way to access
the error in an exception handler.
It's possible to "throw" from an exception, i.e. it's possible to raise a
signal:
CREATE PROCEDURE p ()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SIGNAL SQLSTATE VALUE '99999'
SET MESSAGE_TEXT = 'An error occurred';
END;
DROP TABLE no_such_table;
END;
But this sample code from the MySQL doc looks horrible, because it
literally swallows all errors and jams them into one.
SHOW ERRORS seems relevant, but I don't see any way to work with it
programmatically, e.g. SELECT Code FROM (SHOW ERRORS); is not possible.
Is this possible? Is there a better practice that I'm missing entirely?
I'm trying to rollback on an error, but still let the client receive the
error. This might actually be impossible, unless there is a way to access
the error in an exception handler.
It's possible to "throw" from an exception, i.e. it's possible to raise a
signal:
CREATE PROCEDURE p ()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SIGNAL SQLSTATE VALUE '99999'
SET MESSAGE_TEXT = 'An error occurred';
END;
DROP TABLE no_such_table;
END;
But this sample code from the MySQL doc looks horrible, because it
literally swallows all errors and jams them into one.
SHOW ERRORS seems relevant, but I don't see any way to work with it
programmatically, e.g. SELECT Code FROM (SHOW ERRORS); is not possible.
Is this possible? Is there a better practice that I'm missing entirely?
jquery navigation code does not work properly
jquery navigation code does not work properly
I have written a complete website. I have used my own jquery navigation
plugin in it. It works in my localhost, but the hosted version fails to do
so. The problem is reported by the firebug is: mtNav() is not a function.
I don't know what to do. Because the source script of nav plugin is loaded
completely. Here is the URL to the site:
http://www.ms-models.com
Just the third item in the top-navigation should include drop-down menus.
Please ignore the language, just check the third item of nav menu.
Here is the loaded script:
http://ms-models.com/js/jquery.js
and here is the plugin applied to the navigation bar.
<script type="text/javascript">
$(document).ready(function(e) {
$('.top-navigation ul').mtNav();
});
</script>
Thanks in advance
I have written a complete website. I have used my own jquery navigation
plugin in it. It works in my localhost, but the hosted version fails to do
so. The problem is reported by the firebug is: mtNav() is not a function.
I don't know what to do. Because the source script of nav plugin is loaded
completely. Here is the URL to the site:
http://www.ms-models.com
Just the third item in the top-navigation should include drop-down menus.
Please ignore the language, just check the third item of nav menu.
Here is the loaded script:
http://ms-models.com/js/jquery.js
and here is the plugin applied to the navigation bar.
<script type="text/javascript">
$(document).ready(function(e) {
$('.top-navigation ul').mtNav();
});
</script>
Thanks in advance
Sunday, 15 September 2013
Catching a moment when some specific "laggy" application window finishes processing its keyboard input
Catching a moment when some specific "laggy" application window finishes
processing its keyboard input
I want to show a popup when I get some specific input I into any currently
running application A. Depending on popup's dialog result, I want to
modify the text into application A's current textbox by sending keystrokes
using SendKeys class. I'm currently using low level keyboard hook, which
means I could get keydown events before application A process it. In this
case my popup will be shown before last part of the inputted text appears
in the A's text box. Popup will get the focus and prevent this part of
text from reaching A.
For example, I'm searching for lol keyword. User opens Notepad and inputs
"lol". My application should show popup window "Press Enter to add
blahblahblah text" at this moment. Popup window became foreground. If user
presses Enter, application closes this dialog, makes Notepad foreground
back again and sends "blahblahblah" as a keystrokes to the system.
Everything works fine with the Notepad, but what if target
application/system works slowly and not responding sometimes? Considering
the next test app:
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 2000;
}
private void timer1_Tick(object sender, EventArgs e)
{
Sleep();
}
void Sleep()
{
System.Threading.Thread.CurrentThread.Join(1900);
}
This form contains a textbox and its UI thread is sleeping 95% of the
time. It processing keyboard input each 2 seconds. So if user inputs lol
in such a window, my application most likely will show the popup before
"lol" text appears in the textbox.
I do not want to show my popup before all the text reached the target app A.
Can you please suggest any method of getting the moment when some process
consumed all the keyboard input? SendKeys.Flush() is not working for me.
So does Process.WaitForInputIdle(), which is designed for other purpose, I
suppose. I've tried to send WM_ACTIVATE message via SendMessage to the
target app, because I thought it's exactly what I'm looking for:
The SendMessage function calls the window procedure for the specified
window and does not return until the window procedure has processed the
message.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950%28v=vs.85%29.aspx
User32.SendMessage(activeWindow, 6, 1, 0)
call returns 0, but not creating required pause and my popup appears
before the text.
Thanks in advance.
processing its keyboard input
I want to show a popup when I get some specific input I into any currently
running application A. Depending on popup's dialog result, I want to
modify the text into application A's current textbox by sending keystrokes
using SendKeys class. I'm currently using low level keyboard hook, which
means I could get keydown events before application A process it. In this
case my popup will be shown before last part of the inputted text appears
in the A's text box. Popup will get the focus and prevent this part of
text from reaching A.
For example, I'm searching for lol keyword. User opens Notepad and inputs
"lol". My application should show popup window "Press Enter to add
blahblahblah text" at this moment. Popup window became foreground. If user
presses Enter, application closes this dialog, makes Notepad foreground
back again and sends "blahblahblah" as a keystrokes to the system.
Everything works fine with the Notepad, but what if target
application/system works slowly and not responding sometimes? Considering
the next test app:
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 2000;
}
private void timer1_Tick(object sender, EventArgs e)
{
Sleep();
}
void Sleep()
{
System.Threading.Thread.CurrentThread.Join(1900);
}
This form contains a textbox and its UI thread is sleeping 95% of the
time. It processing keyboard input each 2 seconds. So if user inputs lol
in such a window, my application most likely will show the popup before
"lol" text appears in the textbox.
I do not want to show my popup before all the text reached the target app A.
Can you please suggest any method of getting the moment when some process
consumed all the keyboard input? SendKeys.Flush() is not working for me.
So does Process.WaitForInputIdle(), which is designed for other purpose, I
suppose. I've tried to send WM_ACTIVATE message via SendMessage to the
target app, because I thought it's exactly what I'm looking for:
The SendMessage function calls the window procedure for the specified
window and does not return until the window procedure has processed the
message.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950%28v=vs.85%29.aspx
User32.SendMessage(activeWindow, 6, 1, 0)
call returns 0, but not creating required pause and my popup appears
before the text.
Thanks in advance.
toCharArray returns different result between Android 4.3 and previous Android SDKs
toCharArray returns different result between Android 4.3 and previous
Android SDKs
The length of toCharArray for the code below is 2 in Android 4.3, and
others return 1., anybody know why?
byte[] SECRET_BYTES = { (byte) 0xfc, (byte) 0xbc};
Log.i("ctf3", "SECRET_BYTES - " + SECRET_BYTES.length);
String txtPwd = new String(SECRET_BYTES, "UTF-8");
char[] charsPwd = txtPwd.toCharArray();
Log.i("ctf3", "length of charsPwd - " + charsPwd.length);
Android SDKs
The length of toCharArray for the code below is 2 in Android 4.3, and
others return 1., anybody know why?
byte[] SECRET_BYTES = { (byte) 0xfc, (byte) 0xbc};
Log.i("ctf3", "SECRET_BYTES - " + SECRET_BYTES.length);
String txtPwd = new String(SECRET_BYTES, "UTF-8");
char[] charsPwd = txtPwd.toCharArray();
Log.i("ctf3", "length of charsPwd - " + charsPwd.length);
How to include Bootstrap icons in ASP.NET MVC4?
How to include Bootstrap icons in ASP.NET MVC4?
Basically after a bunch of work I've finally managed to get up and running
with Bootstrap in my ASP.NET MVC4 project.
Here is my folder structure:
Here is my bundleconfig:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/bootstrapjs").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new ScriptBundle("~/Content/bootstrapcss").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-responsive.css"));
}
However when I try to add an HTML element with an icon:
<button type="submit" class="btn"><i class="icon-search"></i></button>
The icon does not appear.
Basically after a bunch of work I've finally managed to get up and running
with Bootstrap in my ASP.NET MVC4 project.
Here is my folder structure:
Here is my bundleconfig:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/bootstrapjs").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new ScriptBundle("~/Content/bootstrapcss").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-responsive.css"));
}
However when I try to add an HTML element with an icon:
<button type="submit" class="btn"><i class="icon-search"></i></button>
The icon does not appear.
What exactly would i put into a secton of C# to cause a website in the persons default browser to be opened?
What exactly would i put into a secton of C# to cause a website in the
persons default browser to be opened?
I don't know the first thing about C#, and I've kinda just dove right in.
I'm a little in over my head here, but as of right now the code i have is
below, And i need to know exactly what to put into that section. Lets say
the website is Google.com what would i type in there to open Google on
what their default browser is set to? I've already tried a multitude of
things on this website, and none of them have been helpful. So please do
me a favor and help me?
private void button 1_Click(object sender, Event Args e);
}
persons default browser to be opened?
I don't know the first thing about C#, and I've kinda just dove right in.
I'm a little in over my head here, but as of right now the code i have is
below, And i need to know exactly what to put into that section. Lets say
the website is Google.com what would i type in there to open Google on
what their default browser is set to? I've already tried a multitude of
things on this website, and none of them have been helpful. So please do
me a favor and help me?
private void button 1_Click(object sender, Event Args e);
}
Compile Latex Documents in Android App
Compile Latex Documents in Android App
I developed an Android app, where the user can type in some data and
create a .tex (latex) document of his data. Is there a way to compile
these latex documents within my app, so the user gets an pdf from the
latex document?
Thanks.
I developed an Android app, where the user can type in some data and
create a .tex (latex) document of his data. Is there a way to compile
these latex documents within my app, so the user gets an pdf from the
latex document?
Thanks.
Escape from Recursion with a Time Limit
Escape from Recursion with a Time Limit
I'm writing a program to play checkers where each move is timed. I am
using alpha-beta pruning to find the best move. I can only go so deep in
the decision tree because:
The decision tree is huge for checkers
There is a time limit I have to decide the move
Is there a way to escape from the call stack instantly when I have run out
of time, even when there are lots of frames on the stack? I thought about
throwing an exception, but that seemed like a poor decision.
This is what I am doing now, but it is not fast enough
public Move play(Board board) {
ArrayList<Board> actions = board.findPossibleMoves();
if (actions.size() == 0) {
return new Board();
}
int depth = 3;
// Each move has 1 second (1000ms)
TimeLimit tl = new TimeLimit(1000);
double alpha = Double.NEGATIVE_INFINITY;
double beta = Double.POSITIVE_INFINITY;
Board bestSoFar = actions.get(0);
double v = Double.NEGATIVE_INFINITY;
for (Board b : actions) {
double result = minValue(b, depth, alpha, beta, tl);
if (result >= v) {
bestSoFar = b;
v = result;
}
if (v >= beta) return b;
alpha = Math.max(alpha, v);
}
return bestSoFar;
}
private double maxValue(Board board, int depth, double alpha, double beta,
TimeLimit tl) {
if (tl.isTimeUp())
return score(board);
...
}
private double minValue(Board board, int depth, double alpha, double beta,
TimeLimit tl) {
if (tl.isTimeUp())
return score(board);
...
}
I'm writing a program to play checkers where each move is timed. I am
using alpha-beta pruning to find the best move. I can only go so deep in
the decision tree because:
The decision tree is huge for checkers
There is a time limit I have to decide the move
Is there a way to escape from the call stack instantly when I have run out
of time, even when there are lots of frames on the stack? I thought about
throwing an exception, but that seemed like a poor decision.
This is what I am doing now, but it is not fast enough
public Move play(Board board) {
ArrayList<Board> actions = board.findPossibleMoves();
if (actions.size() == 0) {
return new Board();
}
int depth = 3;
// Each move has 1 second (1000ms)
TimeLimit tl = new TimeLimit(1000);
double alpha = Double.NEGATIVE_INFINITY;
double beta = Double.POSITIVE_INFINITY;
Board bestSoFar = actions.get(0);
double v = Double.NEGATIVE_INFINITY;
for (Board b : actions) {
double result = minValue(b, depth, alpha, beta, tl);
if (result >= v) {
bestSoFar = b;
v = result;
}
if (v >= beta) return b;
alpha = Math.max(alpha, v);
}
return bestSoFar;
}
private double maxValue(Board board, int depth, double alpha, double beta,
TimeLimit tl) {
if (tl.isTimeUp())
return score(board);
...
}
private double minValue(Board board, int depth, double alpha, double beta,
TimeLimit tl) {
if (tl.isTimeUp())
return score(board);
...
}
sending name instead email address usin mailto
sending name instead email address usin mailto
I'm creating an in-office webpage that you can choose the people you want
to sent your mail to with check boxes, and then press a button that will
open outlook and send them an email.
I'm trying to send it with names, instead of email addresses.
Example:
Tomer Amir; John Do; ... etc. And not:
tomer@office.com; john@office.com; ...
the problem is that outlook does not recognizes the names...
my code:
function getSelectedCheckbox(){
var names = "";
$('input[name=checkboxlist]:checked').each(function() {
names += $(this).val();
});
document.getElementById('selectedrows').value = names;
}
function sendMail(){
getSelectedCheckbox();
var mails = document.getElementById('selectedrows').value;
window.open('mailto:'+mails+'?subject=subject&body=body');
}
it returns a string that looks like this:
Tomer Amir; John Do;
Thanks!
I'm creating an in-office webpage that you can choose the people you want
to sent your mail to with check boxes, and then press a button that will
open outlook and send them an email.
I'm trying to send it with names, instead of email addresses.
Example:
Tomer Amir; John Do; ... etc. And not:
tomer@office.com; john@office.com; ...
the problem is that outlook does not recognizes the names...
my code:
function getSelectedCheckbox(){
var names = "";
$('input[name=checkboxlist]:checked').each(function() {
names += $(this).val();
});
document.getElementById('selectedrows').value = names;
}
function sendMail(){
getSelectedCheckbox();
var mails = document.getElementById('selectedrows').value;
window.open('mailto:'+mails+'?subject=subject&body=body');
}
it returns a string that looks like this:
Tomer Amir; John Do;
Thanks!
Saturday, 14 September 2013
NULL TO NOT NULL ALTER TABLE IN SAS
NULL TO NOT NULL ALTER TABLE IN SAS
I'm having difficulties running a SAS Data Intergration job.
One column needs to be removed from the target's structure, but cannot be
removed because of the NULL constraint.
Do I need to remove the constraint first?
How do I do that?
Thank you in advance, Gal.
I'm having difficulties running a SAS Data Intergration job.
One column needs to be removed from the target's structure, but cannot be
removed because of the NULL constraint.
Do I need to remove the constraint first?
How do I do that?
Thank you in advance, Gal.
How to reuse JavaFX GUI? Can I change controllers dynamically?
How to reuse JavaFX GUI? Can I change controllers dynamically?
I have designed a scene using JavaFX Scene Builder/FXML and I want to
create many instances of that scene, but each scene with different
behavior. Is there a way to change the controller of a scene/FXML
dynamically?
What I want is to design one scene and reuse it, but with different
behaviors for each instance.
I have designed a scene using JavaFX Scene Builder/FXML and I want to
create many instances of that scene, but each scene with different
behavior. Is there a way to change the controller of a scene/FXML
dynamically?
What I want is to design one scene and reuse it, but with different
behaviors for each instance.
Laravel - error saving record with one to many relationship
Laravel - error saving record with one to many relationship
Struggling to update my code with laravel relationships.
I have two tables. Customer and Reservations with Customer having a
hasMany relationship with Reservation and Reservation having a belongs to
relationship with Customer.
The reservation table also has a many to many relationship with a product
table via a link table.
I obtain the customer record ok and I now need to create a reservation for
the customer.
I'm assuming the process is: create the reservation object, attach the
reservation to the customer and then link to the product. (the reservation
table has a few relationships but I'll get this working for now)
If I try this code I get an error Field 'customer_id' doesn't have a
default value - the database table allows null and there are no validation
rules set so assume this is to do with the relationship I've set up.
`$reservation = new Reservation;
$reservation->play_date=$play_date->format('Y-m-d');
$reservation->booked_date=$booked_date->format('Y-m-d');
$reservation->am_tee=$am_time->format('H:i:s');
$reservation->pm_tee=$pm_time->format('H:i:s');
$reservation->save();
$customer->reservation()->associate($reservation);`
The error occurs with $reservation->save();
I then need to use the created $reservation to create entries in the
product link table so need to be able to access the newly created
reservation and it's relationship with products.
I can create the entry using $customer->reservation()->save($reservation);
but then I don't seem to have a $reservation object to work with (or do
I?)
I'm very confused by the relationships so grateful for all help to
understand how to get this to work
Thanks
Struggling to update my code with laravel relationships.
I have two tables. Customer and Reservations with Customer having a
hasMany relationship with Reservation and Reservation having a belongs to
relationship with Customer.
The reservation table also has a many to many relationship with a product
table via a link table.
I obtain the customer record ok and I now need to create a reservation for
the customer.
I'm assuming the process is: create the reservation object, attach the
reservation to the customer and then link to the product. (the reservation
table has a few relationships but I'll get this working for now)
If I try this code I get an error Field 'customer_id' doesn't have a
default value - the database table allows null and there are no validation
rules set so assume this is to do with the relationship I've set up.
`$reservation = new Reservation;
$reservation->play_date=$play_date->format('Y-m-d');
$reservation->booked_date=$booked_date->format('Y-m-d');
$reservation->am_tee=$am_time->format('H:i:s');
$reservation->pm_tee=$pm_time->format('H:i:s');
$reservation->save();
$customer->reservation()->associate($reservation);`
The error occurs with $reservation->save();
I then need to use the created $reservation to create entries in the
product link table so need to be able to access the newly created
reservation and it's relationship with products.
I can create the entry using $customer->reservation()->save($reservation);
but then I don't seem to have a $reservation object to work with (or do
I?)
I'm very confused by the relationships so grateful for all help to
understand how to get this to work
Thanks
UIScrollView subclass trigger event
UIScrollView subclass trigger event
I've tried for some days understand Xcode Subclasses and Categories - and
after all I found one event that are fired.
- (void)setContentOffset:(CGPoint)contentOffset {
NSLog(@"foo");
}
And for more confusion, after read Apple iOS Documentation I get this stuff:
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated {
NSLog(@"bar");
}
First event are fired, but from Apple documentation are not. Why?!
But in the first case, although he was fired the UIScrollView loses their
scroll/drag'n' bounce behavior. I think it's because after overrride
setContentOffset I would need to call the parent method to keep the
default behavior of the UIScrollView. But I'm already exhausted from test
obsolete Xcode approaches.
Than why second code are not fired and how call parent overridden method?
Thanks in advance.
I've tried for some days understand Xcode Subclasses and Categories - and
after all I found one event that are fired.
- (void)setContentOffset:(CGPoint)contentOffset {
NSLog(@"foo");
}
And for more confusion, after read Apple iOS Documentation I get this stuff:
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated {
NSLog(@"bar");
}
First event are fired, but from Apple documentation are not. Why?!
But in the first case, although he was fired the UIScrollView loses their
scroll/drag'n' bounce behavior. I think it's because after overrride
setContentOffset I would need to call the parent method to keep the
default behavior of the UIScrollView. But I'm already exhausted from test
obsolete Xcode approaches.
Than why second code are not fired and how call parent overridden method?
Thanks in advance.
why i can interchange field values inside a class using class reference but can't interchange the references themselves
why i can interchange field values inside a class using class reference
but can't interchange the references themselves
Here is the code of the class i have written
class Demo
{
int x,y;
Demo(int a,int b){x=a;y=b;}
public void swap(Demo ref) // interchanges field values of x and y
{
int temp;
temp=ref.x;
ref.x=ref.y;
ref.y=temp;
}
public void change(Demo ref1,Demo ref2) // supposed to interchange to
class variables of Demo class
{
Demo temp = ref1;
ref1 = ref2;
ref2 = temp;
}
}
swap method works fine i.e. interchange values of x and y.
Now, I have two questions here:
how the swap method is able to change the actual data passed to it? (I
have read that their is no pass by reference in Java.)
why change method does not interchange class references?
but can't interchange the references themselves
Here is the code of the class i have written
class Demo
{
int x,y;
Demo(int a,int b){x=a;y=b;}
public void swap(Demo ref) // interchanges field values of x and y
{
int temp;
temp=ref.x;
ref.x=ref.y;
ref.y=temp;
}
public void change(Demo ref1,Demo ref2) // supposed to interchange to
class variables of Demo class
{
Demo temp = ref1;
ref1 = ref2;
ref2 = temp;
}
}
swap method works fine i.e. interchange values of x and y.
Now, I have two questions here:
how the swap method is able to change the actual data passed to it? (I
have read that their is no pass by reference in Java.)
why change method does not interchange class references?
`mysql_query()` result returns blank
`mysql_query()` result returns blank
I made a web page where one have to login. I login, and it redirects me to
my homepage. On that page there is a heading that says "Welcome back, #my
name#!". The name should be selected from a database, using the username I
gave. The problem is that the result of the query returns blank. What's
the problem?
home.php:
$query = mysql_query("SELECT name FROM user_info WHERE username='$user'")
or die(mysql_error());
$result = mysql_fetch_array($query);
if(!$result){echo mysql_error();}
echo $result;
In home.php $user is a variable that stores $_SESSION['ande'].
login.php:
if($count==1){$_SESSION['code'] = "titan" or die(mysql_error());
$_SESSION['ande'] = $user;header("location: home.php");}
In login.php $user stores $_POST['user'], where user is the name of an
input field.
I made a web page where one have to login. I login, and it redirects me to
my homepage. On that page there is a heading that says "Welcome back, #my
name#!". The name should be selected from a database, using the username I
gave. The problem is that the result of the query returns blank. What's
the problem?
home.php:
$query = mysql_query("SELECT name FROM user_info WHERE username='$user'")
or die(mysql_error());
$result = mysql_fetch_array($query);
if(!$result){echo mysql_error();}
echo $result;
In home.php $user is a variable that stores $_SESSION['ande'].
login.php:
if($count==1){$_SESSION['code'] = "titan" or die(mysql_error());
$_SESSION['ande'] = $user;header("location: home.php");}
In login.php $user stores $_POST['user'], where user is the name of an
input field.
WinPhone: How to add custom confirmation dialog in OnBackKeyPress
WinPhone: How to add custom confirmation dialog in OnBackKeyPress
I am going to implement custom confirmation dialog in OnBackKeyPress
method. It is easy to do with native message box:
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
MessageBoxResult result = MessageBox.Show("Text");
if(result==MessageBoxResult.OK)
{
e.Cancel = true;
}
}
It works, but I dislike limitation with two buttons so I am looking for
something else.
I have checked WPtoolkit:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new CustomMessageBox
{
Title = "Title",
Message = "Message",
RightButtonContent = "aas",
IsLeftButtonEnabled = false,
};
messageBox.Dismissed += (sender, args) =>
{
};
messageBox.Show();
}
}
And Coding4Fun:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new MessagePrompt
{
Title = "Title",
Message = "Message",
};
messageBox.Completed += (sender, args) =>
{
//throw new NotImplementedException();
};
messageBox.Show();
}
Both looks good, but don't work in OnBackKeyPress method (show and
immediately disappear without any my action).
Moreover, I've tried XNA:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
Guide.BeginShowMessageBox("Version of Windows", "Pick a version of
Windows.",
new List<string> {"Vista", "Seven"}, 0,
MessageBoxIcon.Error,
asyncResult =>
{
int? returned =
Guide.EndShowMessageBox(asyncResult);
}, null);
}
}
It works as I expected (has customs in OnBackKeyPress method), but I don't
sure that using XNA inside Silverlight app is good practice.
So, I am looking a way to use WPtoolkit or Coding4Fun windows inside
OnBackKeyPress method or any explanation about using XNA inside
Silverlight app (any recomendation or info about approval such kind app by
store).
I am going to implement custom confirmation dialog in OnBackKeyPress
method. It is easy to do with native message box:
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
MessageBoxResult result = MessageBox.Show("Text");
if(result==MessageBoxResult.OK)
{
e.Cancel = true;
}
}
It works, but I dislike limitation with two buttons so I am looking for
something else.
I have checked WPtoolkit:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new CustomMessageBox
{
Title = "Title",
Message = "Message",
RightButtonContent = "aas",
IsLeftButtonEnabled = false,
};
messageBox.Dismissed += (sender, args) =>
{
};
messageBox.Show();
}
}
And Coding4Fun:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
var messageBox = new MessagePrompt
{
Title = "Title",
Message = "Message",
};
messageBox.Completed += (sender, args) =>
{
//throw new NotImplementedException();
};
messageBox.Show();
}
Both looks good, but don't work in OnBackKeyPress method (show and
immediately disappear without any my action).
Moreover, I've tried XNA:
private bool m_cansel = false;
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (!m_cansel)
{
e.Cancel = true;
m_cansel = true;
Guide.BeginShowMessageBox("Version of Windows", "Pick a version of
Windows.",
new List<string> {"Vista", "Seven"}, 0,
MessageBoxIcon.Error,
asyncResult =>
{
int? returned =
Guide.EndShowMessageBox(asyncResult);
}, null);
}
}
It works as I expected (has customs in OnBackKeyPress method), but I don't
sure that using XNA inside Silverlight app is good practice.
So, I am looking a way to use WPtoolkit or Coding4Fun windows inside
OnBackKeyPress method or any explanation about using XNA inside
Silverlight app (any recomendation or info about approval such kind app by
store).
Friday, 13 September 2013
Blink upon incoming call android
Blink upon incoming call android
I am developing an android app, where I want make the home screen blink
upon incoming call. I tried calling the below startblinking() method
within a activity and the screen blinks fine.
But, when I try to call the same method within the Ring state of a
phonelistener(inside a Service class), I get the following error, since
the service class doesnt have a window.
The method getWindow() is undefined for the type PhoneListener
..
private void startblinking()
{
Log.e("inside","blink MEthod");
timerforblinking.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
time = (float) (time + 0.5);
if(time == 0.5 || time == 1.5 || time == 2.5 || time
== 3.5 || time == 4.5 || time == 5.5)
{
Log.e("time","OFF - time = "+time);
layoutParams.screenBrightness = (float) 30 / 255;
getWindow().setAttributes(layoutParams);
}
if(time == 1.0 || time == 2.0 ||time == 3.0 ||time ==
4.0 ||time == 5.0 )
{
Log.e("time","ON - time = "+time);
layoutParams.screenBrightness = (float)255 / 255;
getWindow().setAttributes(layoutParams);
}
if(time >= 6.0)
{
layoutParams.screenBrightness = (float)255 / 255;
getWindow().setAttributes(layoutParams);
timerforblinking.purge();
timerforblinking.cancel();
}
}
});
}
}, 0, 500);
Is there a possible workaround to achieve the screen blinking upon
incoming calls.
Please help.Thanks!
I am developing an android app, where I want make the home screen blink
upon incoming call. I tried calling the below startblinking() method
within a activity and the screen blinks fine.
But, when I try to call the same method within the Ring state of a
phonelistener(inside a Service class), I get the following error, since
the service class doesnt have a window.
The method getWindow() is undefined for the type PhoneListener
..
private void startblinking()
{
Log.e("inside","blink MEthod");
timerforblinking.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
time = (float) (time + 0.5);
if(time == 0.5 || time == 1.5 || time == 2.5 || time
== 3.5 || time == 4.5 || time == 5.5)
{
Log.e("time","OFF - time = "+time);
layoutParams.screenBrightness = (float) 30 / 255;
getWindow().setAttributes(layoutParams);
}
if(time == 1.0 || time == 2.0 ||time == 3.0 ||time ==
4.0 ||time == 5.0 )
{
Log.e("time","ON - time = "+time);
layoutParams.screenBrightness = (float)255 / 255;
getWindow().setAttributes(layoutParams);
}
if(time >= 6.0)
{
layoutParams.screenBrightness = (float)255 / 255;
getWindow().setAttributes(layoutParams);
timerforblinking.purge();
timerforblinking.cancel();
}
}
});
}
}, 0, 500);
Is there a possible workaround to achieve the screen blinking upon
incoming calls.
Please help.Thanks!
Why URL Data does not shows for GET method in ajax?
Why URL Data does not shows for GET method in ajax?
As we know, GET method sends data via URL. We can use both GET and POST
method in ajax. My question is, why can't we see the data in URL when we
use ajax with a GET method?
As we know, GET method sends data via URL. We can use both GET and POST
method in ajax. My question is, why can't we see the data in URL when we
use ajax with a GET method?
Game of Life Problems in C
Game of Life Problems in C
Im creating the Game of Life Program which I created a working copy of but
im having issues making it so that the user can enter the grid's x and
y(rows and columns) when I try alter my code to do it it gets messy and
causes alot of errors. Also im trying to use malloc() and free() to start
using heaps and im having no luck. The code below is just a working hard
coded solution. (I also commented out the test data and user input part).
Thank you in advance for any help given.
#include <stdio.h>
#define HEIGHT 12
#define WIDTH 12
#define LIFE_YES 'X'
#define LIFE_NO 'O'
typedef int TableType[HEIGHT][WIDTH];
void printTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
if (table[height][width] == LIFE_YES) {
printf("X");
}
else {
printf("-");
}
}
printf("\n");
}
printf("\n");
}
void clearTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
table[height][width] = LIFE_NO;
}
}
}
void askUser(TableType tableA) {
int i;
int n;
int height, width;
printf("Enter the amount of initial organisms: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter dimensions (x y) where organism %d will live: ",
i + 1);
scanf("%d %d", &height, &width);
tableA[height][width] = LIFE_YES;
}
printTable(tableA);
printf("Generation 0");
}
int getNeighborValue(TableType table, int row, int col) {
if (row < 0 || row >= HEIGHT || col < 0 || col >= WIDTH ||
table[row][col] != LIFE_YES ) {
return 0;
}
else {
return 1;
}
}
int getNeighborCount(TableType table, int row, int col) {
int neighbor = 0;
neighbor += getNeighborValue(table, row - 1, col - 1);
neighbor += getNeighborValue(table, row - 1, col);
neighbor += getNeighborValue(table, row - 1, col + 1);
neighbor += getNeighborValue(table, row, col - 1);
neighbor += getNeighborValue(table, row, col + 1);
neighbor += getNeighborValue(table, row + 1, col - 1);
neighbor += getNeighborValue(table, row + 1, col);
neighbor += getNeighborValue(table, row + 1, col + 1);
return neighbor;
}
void calculate(TableType tableA) {
TableType tableB;
int neighbor, height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
neighbor = getNeighborCount(tableA, height, width);
if (neighbor==3) {
tableB[height][width] = LIFE_YES;
}
else if (neighbor == 2 && tableA[height][width] == LIFE_YES) {
tableB[height][width] = LIFE_YES;
}
else {
tableB[height][width] = LIFE_NO;
}
}
}
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
tableA[height][width] = tableB[height][width];
}
}
}
/* test data
void loadTestData(TableType table) {
table[3][4] = LIFE_YES;
table[3][5] = LIFE_YES;
table[3][6] = LIFE_YES;
table[10][4] = LIFE_YES;
table[10][5] = LIFE_YES;
table[10][6] = LIFE_YES;
table[11][6] = LIFE_YES;
table[12][5] = LIFE_YES;
}
*/
int main(void) {
TableType table;
char end;
int generation = 0;
clearTable(table);
/*askUser(table);*/
/*loadTestData(table);*/
printTable(table);
while (end != 'q') {
calculate(table);
printTable(table);
printf("Generation %d\n", ++generation);
printf("Press q to quit or 1 to continue: ");
scanf(" %c", &end);
}
return 0;
}
Im creating the Game of Life Program which I created a working copy of but
im having issues making it so that the user can enter the grid's x and
y(rows and columns) when I try alter my code to do it it gets messy and
causes alot of errors. Also im trying to use malloc() and free() to start
using heaps and im having no luck. The code below is just a working hard
coded solution. (I also commented out the test data and user input part).
Thank you in advance for any help given.
#include <stdio.h>
#define HEIGHT 12
#define WIDTH 12
#define LIFE_YES 'X'
#define LIFE_NO 'O'
typedef int TableType[HEIGHT][WIDTH];
void printTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
if (table[height][width] == LIFE_YES) {
printf("X");
}
else {
printf("-");
}
}
printf("\n");
}
printf("\n");
}
void clearTable(TableType table) {
int height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
table[height][width] = LIFE_NO;
}
}
}
void askUser(TableType tableA) {
int i;
int n;
int height, width;
printf("Enter the amount of initial organisms: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter dimensions (x y) where organism %d will live: ",
i + 1);
scanf("%d %d", &height, &width);
tableA[height][width] = LIFE_YES;
}
printTable(tableA);
printf("Generation 0");
}
int getNeighborValue(TableType table, int row, int col) {
if (row < 0 || row >= HEIGHT || col < 0 || col >= WIDTH ||
table[row][col] != LIFE_YES ) {
return 0;
}
else {
return 1;
}
}
int getNeighborCount(TableType table, int row, int col) {
int neighbor = 0;
neighbor += getNeighborValue(table, row - 1, col - 1);
neighbor += getNeighborValue(table, row - 1, col);
neighbor += getNeighborValue(table, row - 1, col + 1);
neighbor += getNeighborValue(table, row, col - 1);
neighbor += getNeighborValue(table, row, col + 1);
neighbor += getNeighborValue(table, row + 1, col - 1);
neighbor += getNeighborValue(table, row + 1, col);
neighbor += getNeighborValue(table, row + 1, col + 1);
return neighbor;
}
void calculate(TableType tableA) {
TableType tableB;
int neighbor, height, width;
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
neighbor = getNeighborCount(tableA, height, width);
if (neighbor==3) {
tableB[height][width] = LIFE_YES;
}
else if (neighbor == 2 && tableA[height][width] == LIFE_YES) {
tableB[height][width] = LIFE_YES;
}
else {
tableB[height][width] = LIFE_NO;
}
}
}
for (height = 0; height < HEIGHT; height++) {
for (width = 0; width < WIDTH; width++) {
tableA[height][width] = tableB[height][width];
}
}
}
/* test data
void loadTestData(TableType table) {
table[3][4] = LIFE_YES;
table[3][5] = LIFE_YES;
table[3][6] = LIFE_YES;
table[10][4] = LIFE_YES;
table[10][5] = LIFE_YES;
table[10][6] = LIFE_YES;
table[11][6] = LIFE_YES;
table[12][5] = LIFE_YES;
}
*/
int main(void) {
TableType table;
char end;
int generation = 0;
clearTable(table);
/*askUser(table);*/
/*loadTestData(table);*/
printTable(table);
while (end != 'q') {
calculate(table);
printTable(table);
printf("Generation %d\n", ++generation);
printf("Press q to quit or 1 to continue: ");
scanf(" %c", &end);
}
return 0;
}
Cannot publish table without primary keys
Cannot publish table without primary keys
I've used the following link Sqltraining to create a job that will keep
historical data of my database growth. However, since I have several
different instances of servers across locations, I will be using a
previously replicated database and add the table as per step #2 in the
link. However, I cannot publish the new article/ table because it does not
have primary key. I am confused as to which one should be the primary key.
Can anyone please help. Thanks.
I've used the following link Sqltraining to create a job that will keep
historical data of my database growth. However, since I have several
different instances of servers across locations, I will be using a
previously replicated database and add the table as per step #2 in the
link. However, I cannot publish the new article/ table because it does not
have primary key. I am confused as to which one should be the primary key.
Can anyone please help. Thanks.
Can I access local file in Pig?
Can I access local file in Pig?
I have a file named blacklist.xml, each line of this file contains a
absolute path, multiple path is in this file. This file is store at
/Users/ABC/
May I know if there is anyway that I can load this file from the local
directory (/Users/ABC/) but not from HDFS? Thanks!!
I have a file named blacklist.xml, each line of this file contains a
absolute path, multiple path is in this file. This file is store at
/Users/ABC/
May I know if there is anyway that I can load this file from the local
directory (/Users/ABC/) but not from HDFS? Thanks!!
How to alert in title bar of browser on receiving a new message?
How to alert in title bar of browser on receiving a new message?
I have coded a simple chat application in php. I want to know that how to
put a blinking title on title bar to notify a user that he received a new
message if he is switched to other tab. My codes: Javascript:
//messager fetcher
function reload_content() {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatBox").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","messages.php",true);
xmlhttp.send();
scrollToBottom();
}
window.setInterval(reload_content, 1000);
and code for messages.php
<?php
//database connection starts
$con = mysql_connect("******","******","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("chat", $con);
//database connection ends
$display_message = mysql_query("SELECT * FROM `messages` WHERE `myname` =
'$_SESSION[name]' or `friend` = '$_SESSION[name]'");
if($display_message === FALSE) {
die(mysql_error()); // TO DO: better error handling
}
while($row_display=mysql_fetch_array($display_message))
{
$display=$row_display['msg'];
}
echo $display;
?>
I have coded a simple chat application in php. I want to know that how to
put a blinking title on title bar to notify a user that he received a new
message if he is switched to other tab. My codes: Javascript:
//messager fetcher
function reload_content() {
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatBox").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","messages.php",true);
xmlhttp.send();
scrollToBottom();
}
window.setInterval(reload_content, 1000);
and code for messages.php
<?php
//database connection starts
$con = mysql_connect("******","******","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("chat", $con);
//database connection ends
$display_message = mysql_query("SELECT * FROM `messages` WHERE `myname` =
'$_SESSION[name]' or `friend` = '$_SESSION[name]'");
if($display_message === FALSE) {
die(mysql_error()); // TO DO: better error handling
}
while($row_display=mysql_fetch_array($display_message))
{
$display=$row_display['msg'];
}
echo $display;
?>
Thursday, 12 September 2013
HTML5 Responsive Web Design: Fixed Header Not Working
HTML5 Responsive Web Design: Fixed Header Not Working
I'm trying to create a basic HTML5 responsive web design where the header
is fixed. I am trying to keep my HTML and CSS code clean and follow best
practices. The header has a max width of 980 pixels but the blue header
background expands to fill the window (see the diagram).
Right now there's a few issues with my CSS (maybe my HTML) that are
causing the header to cover up the content below the header. The header's
blue background is also not expanding to fill the left of the window. I
also can't get the logo image to center vertically on the header. What I
am I missing? I've been playing around with this all night but I've been
unable to iron out these issues.
Fiddle: http://jsfiddle.net/DU3D6/
CSS
* { margin: 0; padding: 0; }
p { margin: 0 0 10px; line-height: 1.4em; font-size: 1.2em;}
#wrapper {
width: 100%;
max-width: 980px;
margin: auto;
}
header {
background-color: blue;
width: 100%;
height: 100px;
top: 0px;
display: block;
margin-left: auto;
margin-right: auto;
position: fixed;
}
#logo {
height: 70px;
width: 160px;
float: left;
display: block;
background: url(logo.png) 0 0 no-repeat;
text-indent: -9999px;
}
HTML
<div id="wrapper">
<header>
<a href="#" id="logo">Logo</a>
</header>
<section id="main">
<h1>Main section</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
</section>
</div>
I deleted and reposted with updated the tags.
I'm trying to create a basic HTML5 responsive web design where the header
is fixed. I am trying to keep my HTML and CSS code clean and follow best
practices. The header has a max width of 980 pixels but the blue header
background expands to fill the window (see the diagram).
Right now there's a few issues with my CSS (maybe my HTML) that are
causing the header to cover up the content below the header. The header's
blue background is also not expanding to fill the left of the window. I
also can't get the logo image to center vertically on the header. What I
am I missing? I've been playing around with this all night but I've been
unable to iron out these issues.
Fiddle: http://jsfiddle.net/DU3D6/
CSS
* { margin: 0; padding: 0; }
p { margin: 0 0 10px; line-height: 1.4em; font-size: 1.2em;}
#wrapper {
width: 100%;
max-width: 980px;
margin: auto;
}
header {
background-color: blue;
width: 100%;
height: 100px;
top: 0px;
display: block;
margin-left: auto;
margin-right: auto;
position: fixed;
}
#logo {
height: 70px;
width: 160px;
float: left;
display: block;
background: url(logo.png) 0 0 no-repeat;
text-indent: -9999px;
}
HTML
<div id="wrapper">
<header>
<a href="#" id="logo">Logo</a>
</header>
<section id="main">
<h1>Main section</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.</p>
</section>
</div>
I deleted and reposted with updated the tags.
Tomcat APR native library not loaded *even* when present and configured
Tomcat APR native library not loaded *even* when present and configured
The system is Ubuntu 13.04 (64-bit). I compiled the latest (1.4.8) library
(process described here) and the files are readable by all:
$ ll /usr/local/apr/lib
-rw-r--r-- 1 root root 8351 Sep 12 19:29 apr.exp
-rw-r--r-- 1 root root 1608792 Sep 12 19:29 libapr-1.a
-rwxr-xr-x 1 root root 965 Sep 12 19:29 libapr-1.la*
lrwxrwxrwx 1 root root 17 Sep 12 19:29 libapr-1.so -> libapr-1.so.0.4.8*
lrwxrwxrwx 1 root root 17 Sep 12 19:29 libapr-1.so.0 ->
libapr-1.so.0.4.8*
-rwxr-xr-x 1 root root 925622 Sep 12 19:29 libapr-1.so.0.4.8*
drwxr-xr-x 2 root root 4096 Sep 12 19:29 pkgconfig/
The environment variable is set in .bashrc and it's loaded:
LD_LIBRARY_PATH=/usr/local/apr/lib
I launched Tomcat's Java with -XshowSettings:properties which shows
java.library.path contains that path.
java.library.path = /usr/local/apr/lib
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
Still, when Tomcat starts I get a message it didn't find it even though it
displays the path to that directory.
Sep 12, 2013 8:14:12 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal
performance in production environments was not found on the
java.library.path:
/usr/local/apr/lib:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
I'm really at a loss what could be the cause.
Thank you very much for any pointers.
The system is Ubuntu 13.04 (64-bit). I compiled the latest (1.4.8) library
(process described here) and the files are readable by all:
$ ll /usr/local/apr/lib
-rw-r--r-- 1 root root 8351 Sep 12 19:29 apr.exp
-rw-r--r-- 1 root root 1608792 Sep 12 19:29 libapr-1.a
-rwxr-xr-x 1 root root 965 Sep 12 19:29 libapr-1.la*
lrwxrwxrwx 1 root root 17 Sep 12 19:29 libapr-1.so -> libapr-1.so.0.4.8*
lrwxrwxrwx 1 root root 17 Sep 12 19:29 libapr-1.so.0 ->
libapr-1.so.0.4.8*
-rwxr-xr-x 1 root root 925622 Sep 12 19:29 libapr-1.so.0.4.8*
drwxr-xr-x 2 root root 4096 Sep 12 19:29 pkgconfig/
The environment variable is set in .bashrc and it's loaded:
LD_LIBRARY_PATH=/usr/local/apr/lib
I launched Tomcat's Java with -XshowSettings:properties which shows
java.library.path contains that path.
java.library.path = /usr/local/apr/lib
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
Still, when Tomcat starts I get a message it didn't find it even though it
displays the path to that directory.
Sep 12, 2013 8:14:12 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal
performance in production environments was not found on the
java.library.path:
/usr/local/apr/lib:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
I'm really at a loss what could be the cause.
Thank you very much for any pointers.
jdbc connection error: not associated with a managed connection
jdbc connection error: not associated with a managed connection
My application is trowing the following exception:
java.sql.SQLException: Connection is not associated with a managed
connection.org.jboss.resource.adapter.jdbc.jdk6.WrappedConnectionJDK6@4fe91321
This is happening in production I'm not able to get this problem in
development and for that I'm not able to solve it.
The root of the exception is code line dbConn.prepareStatement(sql);
From what I was able to find in the web, the cause for this can be:
1. Over jdbc connection, a jboss connection is wrapped but the wrapper
is empty. The original jdbc connection inside is no longer there.
2. JDBC Connection is already closed and trying to work with close
connection is the reason why I'm getting this exception
3. The transaction manger detects transaction that is taking to long
then the transaction timeout,
So if someone can point me what is the problem because I'm not able to get
this problem in mine development environment.
Also what logs can I add that will help me detect the problem in
production - I'm using Java, JBoss, Postgres
I'have enable connection close monitoringa, and also to add is that the
issue is not consistent
My application is trowing the following exception:
java.sql.SQLException: Connection is not associated with a managed
connection.org.jboss.resource.adapter.jdbc.jdk6.WrappedConnectionJDK6@4fe91321
This is happening in production I'm not able to get this problem in
development and for that I'm not able to solve it.
The root of the exception is code line dbConn.prepareStatement(sql);
From what I was able to find in the web, the cause for this can be:
1. Over jdbc connection, a jboss connection is wrapped but the wrapper
is empty. The original jdbc connection inside is no longer there.
2. JDBC Connection is already closed and trying to work with close
connection is the reason why I'm getting this exception
3. The transaction manger detects transaction that is taking to long
then the transaction timeout,
So if someone can point me what is the problem because I'm not able to get
this problem in mine development environment.
Also what logs can I add that will help me detect the problem in
production - I'm using Java, JBoss, Postgres
I'have enable connection close monitoringa, and also to add is that the
issue is not consistent
How do I pass on the search string from one class to another?
How do I pass on the search string from one class to another?
I have a search View which is defined as follows in a class basesearch.java:
protected EditText mSearchView;
(It refers to the basic textbox search view).
Now in class searchfragment.java, I have the following method:
private void runSearch(final String searchTerm) {
if(searchTerm.contains(mSearchView.getText().toString().toLowerCase()
+ " " + mSearchView.getText().toString().toLowerCase())){
AWebViewFragment.newInstanceForSearch(getFragmentManager(), null,
null);
}else {
SearchResultsFragment.newInstance(getFragmentManager(),
searchTerm);
}
}
Note: mSearchView.getText().toString().toLowerCase() is getting the typed
in search value. Now, I want to use this value
"mSearchView.getText().toString().toLowerCase()" and pass it on to another
class which is being called "AWebViewFragment" in the first if clause. I
am defining the AwebViewfragment as follwos:
public static String OUTPUT_ENVIRONMENT =
"https://mobile13.cp.com/msf1.0/fwd/answers/service/v1/?q="+mSearchView.getText().toString().toLowerCase()+"%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
However it throws an error at mSearchView,unless I set some dummy value
defining it. I want it to be able to get information from previous class
for the typed in search term. I wonder what I am doing wrong. I want the
url to display with the dynamically typed search term. Is it possible to
do the same somehow? Feel free to modify the code and walk me thru a new
change, I will try any suggestions for new code or improvements. Any help
greatly appreciated. Thanks! Justin Also, I am already using the bundles
in Awebviewfragment:
private static AWebViewFragment __newInstance(final AnswersWebViewFragment
fragment, final FragmentManager manager,
final String searchTerm, final String symbolType, int
containerViewId, final int inAnimation, final int
outAnimation, final int popInAnimation, final int
popOutAnimation) {
final Bundle bundle = new Bundle();
bundle.putString(SEARCH_TERM, searchTerm);
bundle.putString(AnswersWebViewFragment.SYMBOL_TYPE, symbolType);
bundle.putInt(AnswersWebViewFragment.CONTAINER_ID, containerViewId);
fragment.setArguments(bundle);
FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.ADD, containerViewId);
fragmentInfo.setAnimation(inAnimation, outAnimation);
fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
fragmentInfo.setFragmentTag(TAG_A_FRAGMENT_WEBVIEW);
fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.nav_option_quotes));
FragmentStackManager.getInstance().transitionFragment(manager,
fragment, fragmentInfo);
return fragment;
}
And OUTPUT_ENVIRONMENT is defined outside the method for bundle, how do i
retrieve the search term passed on from the previous class? and oncreate I
am using :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSearchTerm = getArguments().getString(SEARCH_TERM);
}
ENTIRE CODE BELOW:
AbssearchAutisuggestFragment:
public abstract class AbsSearchAutoSuggestFragment extends
AbsLoaderFragment implements SearchAutoSuggestObserver,
SearchAutoSuggestItemClickListener{
protected EditText mSearchView;
protected ListView mSearchListView;
private SearchAutoSuggestsTask mSearchAutoSuggestTask;
private List<SearchAutoSuggestRow> mSearchAutoSuggestRows;
public void startSearchAutoSuggestTask(final String searchTerm) {
killLastSearchAutoSuggestTask();
mSearchAutoSuggestTask = new SearchAutoSuggestsTask(this);
final String params[] = {searchTerm};
mSearchAutoSuggestTask.execute(params);
}
public boolean killLastSearchAutoSuggestTask() {
if (mSearchAutoSuggestTask != null) {
mSearchAutoSuggestTask.cancel();
return true;
}
return false;
}
@Override
public void onSearchAutoSuggestAvailable(final SearchAutoSuggests
searchAutoSuggests) {
final Activity activity = getActivity();
if (activity == null) {
return;
}
mSearchAutoSuggestRows =
populateSearchAutoSuggestRows(searchAutoSuggests);
final SearchAutoSuggestAdapter adapter = new
SearchAutoSuggestAdapter(activity,
R.layout.item_search_history_auto_suggest,
mSearchAutoSuggestRows);
adapter.setOnItemClickedListener(this);
mSearchListView.setAdapter(adapter);
onHasResults();
}
private List<SearchAutoSuggestRow> populateSearchAutoSuggestRows(final
SearchAutoSuggests searchAutoSuggests) {
final List<SearchAutoSuggestRow> searchAutoSuggestRows = new
ArrayList<SearchAutoSuggestRow>();
for (final SearchAutoSuggest searchAutoSuggest :
searchAutoSuggests.getSearchAutoSuggests()) {
final SearchAutoSuggestHeader header = new
SearchAutoSuggestHeader(searchAutoSuggest.getName().toUpperCase());
searchAutoSuggestRows.add(header);
int i = 1;
for (final SearchAutoSuggestHits searchAutoSuggestHits :
searchAutoSuggest.getHits()) {
final String id = searchAutoSuggestHits.getId();
final String title = searchAutoSuggestHits.getTitle();
final String subTitle = searchAutoSuggestHits.getSubtitle();
final String symbol = searchAutoSuggestHits.getSymbol();
final String st = searchAutoSuggestHits.getSt();
final Spanned formattedTitle = formatAutoSuggestText(title);
final Spanned formattedSymbol =
formatAutoSuggestText(symbol);
final SearchAutoSuggestItem searchAutoSuggestItem = new
SearchAutoSuggestItem(id, formattedTitle, subTitle,
formattedSymbol,st);
searchAutoSuggestRows.add(searchAutoSuggestItem);
if(i==3){
break;
}
i++;
}
}
return searchAutoSuggestRows;
}
private Spanned formatAutoSuggestText(final String autoSuggestText) {
if (autoSuggestText == null) {
return Html.fromHtml("");
}
try {
String modifiedAutoSuggestText= "" ;
final String searchText = mSearchView.getText().toString();
final Pattern pattern =
Pattern.compile(StringUtils.INSENSITIVE_CASE + searchText);
final Matcher matcher = pattern.matcher(autoSuggestText); //
TODO: figure out why this line throws NPE "at
java.util.regex.Pattern.matcher(Pattern.java:290)"
int end = 0;
while (matcher.find()) {
final String subStringMatchFound =
autoSuggestText.substring(end, matcher.end());
final String stringToBeReplaced =
autoSuggestText.substring(matcher.start(), matcher.end());
final String stringToReplace = "<b><font color='" +
getResources().getColor(R.color.search_autosuggest_highlighted_text)
+ "'>" +matcher.group()+ "</font></b>";
modifiedAutoSuggestText +=
subStringMatchFound.replace(stringToBeReplaced,stringToReplace);
end = matcher.end();
}
modifiedAutoSuggestText += autoSuggestText.substring(end);
return Html.fromHtml(modifiedAutoSuggestText);
}
catch (final Exception e){
return Html.fromHtml(autoSuggestText);
}
}
public void onHasResults() {
if (getView() == null) {
Log.d("Search Issues", "view is null");
return;
}
LayoutUtils.showResults(getView(),
R.id.search_history_auto_suggest_list);
}
public void onLoading() {
LayoutUtils.showLoading(getView(),
R.id.search_history_auto_suggest_list);
}
public void onNoResults() {
View view = getView().findViewById(R.id.overlay);
if (view != null) {
view.setVisibility(View.GONE);
}
}
}
SearchHistoryAutosuggestFragment:
public class SearchHistoryAutoSuggestFragment extends
AbsSearchAutoSuggestFragment implements ViewBinder,
SearchHistoryItemClickListener, OnClickListener,
MainActivity.BackPressListener {
public final static String TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT =
"SearchHistoryAutoSuggestFragment";
private SearchHistoryListAdapter mAdapter;
private TextWatcher mTextWatcher;
private static final String[] COLUMN_NAMES = {
SearchHistory.Columns.SEARCH_TERM,
SearchHistory.Columns.SEARCH_HISTORY_META_DATA,
SearchHistory.Columns.SEARCH_SYMBOL
};
private static final int[] VIEW_IDS = {
R.id.search_item,
R.id.search_history_metadata,
R.id.search_symbol
};
public static SearchHistoryAutoSuggestFragment newInstance(final
FragmentManager manager) {
final SearchHistoryAutoSuggestFragment fragment = new
SearchHistoryAutoSuggestFragment();
final FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.ADD);
fragmentInfo.setAnimation(R.anim.slide_in_from_top, 0);
fragmentInfo.setFragmentTag(TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT);
FragmentStackManager.getInstance().transitionFragment(manager,
fragment, fragmentInfo);
return fragment;
}
public static void removeInstance(final FragmentManager manager) {
final SearchHistoryAutoSuggestFragment fragment =
(SearchHistoryAutoSuggestFragment)
manager.findFragmentByTag(TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT);
if (fragment == null) {
return;
}
final FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.REMOVE);
fragmentInfo.setAnimation(R.anim.slide_out_to_top,
FragmentInfo.NO_ANIMATION);
fragmentInfo.setFragmentTag(TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT);
final FragmentStackManager stackManager =
FragmentStackManager.getInstance();
if (stackManager.getTopFragment() instanceof
SearchHistoryAutoSuggestFragment) {
stackManager.popTopFragment();
}
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup
container, final Bundle savedInstanceState) {
mSearchView = (EditText) getActivity().findViewById(R.id.search_text);
mAdapter = new SearchHistoryListAdapter(getActivity(),
R.layout.item_search_history_auto_suggest, null, COLUMN_NAMES,
VIEW_IDS, 0);
mAdapter.setViewBinder(this);
final View view =
inflater.inflate(R.layout.fragment_search_history_auto_suggest,
container, false);
mSearchListView = (ListView)
view.findViewById(R.id.search_history_auto_suggest_list);
mAdapter.setOnItemClickedListener(this);
mSearchListView.setAdapter(mAdapter);
setSearchLinkOnclickListener(view);
setSearchViewTextChangedListener();
setSearchViewKeyListener();
return view;
}
@Override
public Uri onCreateContentUri() {
return SearchContentProvider.SEARCH_HISTORY_URI;
}
@Override
public void onOperationStarted(final Uri uri) {
onLoading();
}
@Override
public void onCursorLoaded(final Uri uri, final Cursor cursor) {
super.onCursorLoaded(uri, cursor);
if (!isOperationExecuting()){
if (cursor != null && cursor.getCount() > 0) {
onHasResults();
}
}
}
@Override
public boolean setViewValue(final View view, final Cursor cursor, final
int columnIndex) {
Log.d("SearchHistoryIssue", "setting view value");
switch (view.getId()) {
case R.id.search_symbol:
String symbol = cursor.getString(columnIndex);
View parent = (View) view.getParent();
View dash = parent.findViewById(R.id.search_dash);
TextView symbolTextView = (TextView)
parent.findViewById(R.id.search_symbol);
if (StringUtils.isEmpty(symbol)) {
symbolTextView.setText("");
view.setVisibility(View.GONE);
if (dash != null) {
dash.setVisibility(View.GONE);
}
return true;
} else {
view.setVisibility(View.VISIBLE);
if (dash != null) {
dash.setVisibility(View.VISIBLE);
}
return false;
}
}
return false;
}
private void setSearchViewTextChangedListener(){
mTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(final CharSequence s, final int start,
final int before, final int count) {
handleTextChanged();
}
@Override
public void beforeTextChanged(final CharSequence s, final int
start, final int count,final int after) {
}
@Override
public void afterTextChanged(final Editable s) {
handleAfterTextChanged(s);
}
};
mSearchView.addTextChangedListener(mTextWatcher);
}
private boolean enterButtonClicked = false;
private void setSearchViewKeyListener(){
mSearchView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(final View v, final int keyCode,
final KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_ENTER &&
!enterButtonClicked) {
final String searchString =
mSearchView.getText().toString();
if(!searchString.isEmpty()){
showSearchResults(searchString);
}
enterButtonClicked = true;
return true;
}
enterButtonClicked = false;
return false;
}
});
}
private void handleTextChanged() {
final View clearButton = ((View)
mSearchView.getParent()).findViewById(R.id.clear_search_textbox);
if (mSearchView.getText().length() > 0) {
clearButton.setVisibility(View.VISIBLE);
} else {
handleTextClear(clearButton);
}
displaySearchLink();
}
private void handleAfterTextChanged(final Editable s) {
if (s.length() != 0) {
Log.d("AutoSuggest", "Auto Suggest - text pressed on " +
System.currentTimeMillis());
startSearchAutoSuggestTask(s.toString());
} else {
displaySearchHistory();
}
}
private void handleTextClear(final View clearButton) {
clearButton.setVisibility(View.GONE);
final boolean autoSuggestActive = killLastSearchAutoSuggestTask();
if (!autoSuggestActive) {
displaySearchHistory();
}
}
private void displaySearchHistory() {
final Activity activity = getActivity();
if (activity == null) {
return;
}
mAdapter = new SearchHistoryListAdapter(activity,
R.layout.item_search_history_auto_suggest, null, COLUMN_NAMES,
VIEW_IDS, 0);
mAdapter.setOnItemClickedListener(this);
mAdapter.setViewBinder(this);
mSearchListView.setAdapter(mAdapter);
Log.d("SearchHistoryIssue", "About to restart content loader");
restartContentLoader();
}
public void showSearchResults(final String searchString) {
runSearch(searchString);
saveSearchHistory(searchString, null, null);
}
private void saveSearchHistory(final String searchString, final String
historyMetaData, final String symbol) {
final SearchHistory searchHistory = new SearchHistory(searchString,
historyMetaData, symbol);
DatabaseUtils.addEntryToSearchHistoryTable(searchHistory);
}
private void runSearch(final String searchTerm) {
killLastSearchAutoSuggestTask();
hideSearchView();
if(searchTerm.contains(mSearchView.getText().toString().toLowerCase()
+ " " + mSearchView.getText().toString().toLowerCase())){
AnswersWebViewFragment.newInstanceForSearch(getFragmentManager(),
null, null);
}else {
SearchResultsFragment.newInstance(getFragmentManager(), searchTerm);
}
}
private void displaySearchLink() {
final View view = getView();
if (view != null) {
final String searchText = mSearchView.getText().toString();
final TextView searchLink = (TextView)
view.findViewById(R.id.search_link);
if (StringUtils.isNotEmpty(searchText)) {
searchLink.setText(getResources().getString(R.string.search_for)+"
\"" + searchText + "\"");
searchLink.setVisibility(View.VISIBLE);
}else {
searchLink.setVisibility(View.GONE);
}
}
}
@Override
public void onClick(final View view) {
switch (view.getId()) {
case R.id.search_link:
final String searchText = mSearchView.getText().toString();
showSearchResults(searchText);
break;
default:
break;
}
}
@Override
public void onHistoryItemClicked(final int viewId, final String
searchHistoryTerm, final String searchHistoryMetadata, final String
searchHistorySymbol) {
switch (viewId) {
case R.id.search_history_item_container:
saveSearchHistory(searchHistoryTerm, searchHistoryMetadata,
searchHistorySymbol);
if (StringUtils.isEmpty(searchHistoryMetadata)) {
runSearch(searchHistoryTerm);
} else {
displayQuotes(searchHistoryTerm, searchHistoryMetadata,
searchHistorySymbol);
}
break;
case R.id.search_item_button:
mSearchView.setText(searchHistoryTerm);
mSearchView.requestFocus();
mSearchView.setSelection(searchHistoryTerm.length());
break;
default:
}
}
@Override
public void onAutoSuggestItemClicked(final View view) {
switch (view.getId()) {
case R.id.search_autosuggest_item_container:
final String searchAutoSuggestTitle =
((TextView)view.findViewById(R.id.search_autosuggest_item_name)).getText().toString();
final String searchAutoSuggestSubTitle = (String)
((TextView)view.findViewById(R.id.search_autosuggest_item_subtitle)).getText();
final String searchAutoSuggestSymbol =
((TextView)view.findViewById(R.id.search_autosuggest_item_symbol)).getText().toString();
saveSearchHistory(searchAutoSuggestTitle,
searchAutoSuggestSubTitle, searchAutoSuggestSymbol);
displayQuotes(searchAutoSuggestTitle, searchAutoSuggestSubTitle,
searchAutoSuggestSymbol);
break;
default:
break;
}
}
private void displayQuotes(final String searchAutoSuggestTitle, final
String searchAutoSuggestSubTitle, final String searchAutoSuggestSymbol) {
killLastSearchAutoSuggestTask();
QuotesFragmentWebView.newInstanceForSearch(getFragmentManager(),
searchAutoSuggestSymbol, null);
hideSearchView();
}
private void showKeyboard() {
final MainActivity activity = (MainActivity) getActivity();
if (activity == null) {
return;
}
final EditText searchText = (EditText)
activity.findViewById(R.id.search_text);
KeyboardUtils.showKeyboard(searchText, activity);
}
};
}
Answerswebviewfragment:
public class AnswersWebViewFragment extends Fragment implements
OnClickListener , MainActivity.BackPressListener<Fragment> {
public static String OUTPUT_ENVIRONMENT =
"https://.mobile13.cp.com/msf1.0/fwd/answers/answers/service/v1/?q="+[SEARCHTERM]+"%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
private static AnswersWebViewFragment __newInstance(final
AnswersWebViewFragment fragment, final FragmentManager manager,
final String searchTerm, final String symbolType, int
containerViewId, final int inAnimation, final int
outAnimation, final int popInAnimation, final int
popOutAnimation) {
final Bundle bundle = new Bundle();
bundle.putString(SEARCH_TERM, searchTerm);
bundle.putString(AnswersWebViewFragment.SYMBOL_TYPE, symbolType);
bundle.putInt(AnswersWebViewFragment.CONTAINER_ID, containerViewId);
fragment.setArguments(bundle);
FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.ADD, containerViewId);
fragmentInfo.setAnimation(inAnimation, outAnimation);
fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
fragmentInfo.setFragmentTag(TAG_ANSWERS_FRAGMENT_WEBVIEW);
fragmentInfo.setActionBarTitle(EikonApplication.getAppResources().getString(R.string.nav_option_quotes));
FragmentStackManager.getInstance().transitionFragment(manager,
fragment, fragmentInfo);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSearchTerm = getArguments().getString(SEARCH_TERM);
}
How do I fix the answersWebviewfragment to retrieve the searchterm??
I have a search View which is defined as follows in a class basesearch.java:
protected EditText mSearchView;
(It refers to the basic textbox search view).
Now in class searchfragment.java, I have the following method:
private void runSearch(final String searchTerm) {
if(searchTerm.contains(mSearchView.getText().toString().toLowerCase()
+ " " + mSearchView.getText().toString().toLowerCase())){
AWebViewFragment.newInstanceForSearch(getFragmentManager(), null,
null);
}else {
SearchResultsFragment.newInstance(getFragmentManager(),
searchTerm);
}
}
Note: mSearchView.getText().toString().toLowerCase() is getting the typed
in search value. Now, I want to use this value
"mSearchView.getText().toString().toLowerCase()" and pass it on to another
class which is being called "AWebViewFragment" in the first if clause. I
am defining the AwebViewfragment as follwos:
public static String OUTPUT_ENVIRONMENT =
"https://mobile13.cp.com/msf1.0/fwd/answers/service/v1/?q="+mSearchView.getText().toString().toLowerCase()+"%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
However it throws an error at mSearchView,unless I set some dummy value
defining it. I want it to be able to get information from previous class
for the typed in search term. I wonder what I am doing wrong. I want the
url to display with the dynamically typed search term. Is it possible to
do the same somehow? Feel free to modify the code and walk me thru a new
change, I will try any suggestions for new code or improvements. Any help
greatly appreciated. Thanks! Justin Also, I am already using the bundles
in Awebviewfragment:
private static AWebViewFragment __newInstance(final AnswersWebViewFragment
fragment, final FragmentManager manager,
final String searchTerm, final String symbolType, int
containerViewId, final int inAnimation, final int
outAnimation, final int popInAnimation, final int
popOutAnimation) {
final Bundle bundle = new Bundle();
bundle.putString(SEARCH_TERM, searchTerm);
bundle.putString(AnswersWebViewFragment.SYMBOL_TYPE, symbolType);
bundle.putInt(AnswersWebViewFragment.CONTAINER_ID, containerViewId);
fragment.setArguments(bundle);
FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.ADD, containerViewId);
fragmentInfo.setAnimation(inAnimation, outAnimation);
fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
fragmentInfo.setFragmentTag(TAG_A_FRAGMENT_WEBVIEW);
fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.nav_option_quotes));
FragmentStackManager.getInstance().transitionFragment(manager,
fragment, fragmentInfo);
return fragment;
}
And OUTPUT_ENVIRONMENT is defined outside the method for bundle, how do i
retrieve the search term passed on from the previous class? and oncreate I
am using :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSearchTerm = getArguments().getString(SEARCH_TERM);
}
ENTIRE CODE BELOW:
AbssearchAutisuggestFragment:
public abstract class AbsSearchAutoSuggestFragment extends
AbsLoaderFragment implements SearchAutoSuggestObserver,
SearchAutoSuggestItemClickListener{
protected EditText mSearchView;
protected ListView mSearchListView;
private SearchAutoSuggestsTask mSearchAutoSuggestTask;
private List<SearchAutoSuggestRow> mSearchAutoSuggestRows;
public void startSearchAutoSuggestTask(final String searchTerm) {
killLastSearchAutoSuggestTask();
mSearchAutoSuggestTask = new SearchAutoSuggestsTask(this);
final String params[] = {searchTerm};
mSearchAutoSuggestTask.execute(params);
}
public boolean killLastSearchAutoSuggestTask() {
if (mSearchAutoSuggestTask != null) {
mSearchAutoSuggestTask.cancel();
return true;
}
return false;
}
@Override
public void onSearchAutoSuggestAvailable(final SearchAutoSuggests
searchAutoSuggests) {
final Activity activity = getActivity();
if (activity == null) {
return;
}
mSearchAutoSuggestRows =
populateSearchAutoSuggestRows(searchAutoSuggests);
final SearchAutoSuggestAdapter adapter = new
SearchAutoSuggestAdapter(activity,
R.layout.item_search_history_auto_suggest,
mSearchAutoSuggestRows);
adapter.setOnItemClickedListener(this);
mSearchListView.setAdapter(adapter);
onHasResults();
}
private List<SearchAutoSuggestRow> populateSearchAutoSuggestRows(final
SearchAutoSuggests searchAutoSuggests) {
final List<SearchAutoSuggestRow> searchAutoSuggestRows = new
ArrayList<SearchAutoSuggestRow>();
for (final SearchAutoSuggest searchAutoSuggest :
searchAutoSuggests.getSearchAutoSuggests()) {
final SearchAutoSuggestHeader header = new
SearchAutoSuggestHeader(searchAutoSuggest.getName().toUpperCase());
searchAutoSuggestRows.add(header);
int i = 1;
for (final SearchAutoSuggestHits searchAutoSuggestHits :
searchAutoSuggest.getHits()) {
final String id = searchAutoSuggestHits.getId();
final String title = searchAutoSuggestHits.getTitle();
final String subTitle = searchAutoSuggestHits.getSubtitle();
final String symbol = searchAutoSuggestHits.getSymbol();
final String st = searchAutoSuggestHits.getSt();
final Spanned formattedTitle = formatAutoSuggestText(title);
final Spanned formattedSymbol =
formatAutoSuggestText(symbol);
final SearchAutoSuggestItem searchAutoSuggestItem = new
SearchAutoSuggestItem(id, formattedTitle, subTitle,
formattedSymbol,st);
searchAutoSuggestRows.add(searchAutoSuggestItem);
if(i==3){
break;
}
i++;
}
}
return searchAutoSuggestRows;
}
private Spanned formatAutoSuggestText(final String autoSuggestText) {
if (autoSuggestText == null) {
return Html.fromHtml("");
}
try {
String modifiedAutoSuggestText= "" ;
final String searchText = mSearchView.getText().toString();
final Pattern pattern =
Pattern.compile(StringUtils.INSENSITIVE_CASE + searchText);
final Matcher matcher = pattern.matcher(autoSuggestText); //
TODO: figure out why this line throws NPE "at
java.util.regex.Pattern.matcher(Pattern.java:290)"
int end = 0;
while (matcher.find()) {
final String subStringMatchFound =
autoSuggestText.substring(end, matcher.end());
final String stringToBeReplaced =
autoSuggestText.substring(matcher.start(), matcher.end());
final String stringToReplace = "<b><font color='" +
getResources().getColor(R.color.search_autosuggest_highlighted_text)
+ "'>" +matcher.group()+ "</font></b>";
modifiedAutoSuggestText +=
subStringMatchFound.replace(stringToBeReplaced,stringToReplace);
end = matcher.end();
}
modifiedAutoSuggestText += autoSuggestText.substring(end);
return Html.fromHtml(modifiedAutoSuggestText);
}
catch (final Exception e){
return Html.fromHtml(autoSuggestText);
}
}
public void onHasResults() {
if (getView() == null) {
Log.d("Search Issues", "view is null");
return;
}
LayoutUtils.showResults(getView(),
R.id.search_history_auto_suggest_list);
}
public void onLoading() {
LayoutUtils.showLoading(getView(),
R.id.search_history_auto_suggest_list);
}
public void onNoResults() {
View view = getView().findViewById(R.id.overlay);
if (view != null) {
view.setVisibility(View.GONE);
}
}
}
SearchHistoryAutosuggestFragment:
public class SearchHistoryAutoSuggestFragment extends
AbsSearchAutoSuggestFragment implements ViewBinder,
SearchHistoryItemClickListener, OnClickListener,
MainActivity.BackPressListener {
public final static String TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT =
"SearchHistoryAutoSuggestFragment";
private SearchHistoryListAdapter mAdapter;
private TextWatcher mTextWatcher;
private static final String[] COLUMN_NAMES = {
SearchHistory.Columns.SEARCH_TERM,
SearchHistory.Columns.SEARCH_HISTORY_META_DATA,
SearchHistory.Columns.SEARCH_SYMBOL
};
private static final int[] VIEW_IDS = {
R.id.search_item,
R.id.search_history_metadata,
R.id.search_symbol
};
public static SearchHistoryAutoSuggestFragment newInstance(final
FragmentManager manager) {
final SearchHistoryAutoSuggestFragment fragment = new
SearchHistoryAutoSuggestFragment();
final FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.ADD);
fragmentInfo.setAnimation(R.anim.slide_in_from_top, 0);
fragmentInfo.setFragmentTag(TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT);
FragmentStackManager.getInstance().transitionFragment(manager,
fragment, fragmentInfo);
return fragment;
}
public static void removeInstance(final FragmentManager manager) {
final SearchHistoryAutoSuggestFragment fragment =
(SearchHistoryAutoSuggestFragment)
manager.findFragmentByTag(TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT);
if (fragment == null) {
return;
}
final FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.REMOVE);
fragmentInfo.setAnimation(R.anim.slide_out_to_top,
FragmentInfo.NO_ANIMATION);
fragmentInfo.setFragmentTag(TAG_SEARCH_HISTORY_AUTO_SUGGEST_FRAGMENT);
final FragmentStackManager stackManager =
FragmentStackManager.getInstance();
if (stackManager.getTopFragment() instanceof
SearchHistoryAutoSuggestFragment) {
stackManager.popTopFragment();
}
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup
container, final Bundle savedInstanceState) {
mSearchView = (EditText) getActivity().findViewById(R.id.search_text);
mAdapter = new SearchHistoryListAdapter(getActivity(),
R.layout.item_search_history_auto_suggest, null, COLUMN_NAMES,
VIEW_IDS, 0);
mAdapter.setViewBinder(this);
final View view =
inflater.inflate(R.layout.fragment_search_history_auto_suggest,
container, false);
mSearchListView = (ListView)
view.findViewById(R.id.search_history_auto_suggest_list);
mAdapter.setOnItemClickedListener(this);
mSearchListView.setAdapter(mAdapter);
setSearchLinkOnclickListener(view);
setSearchViewTextChangedListener();
setSearchViewKeyListener();
return view;
}
@Override
public Uri onCreateContentUri() {
return SearchContentProvider.SEARCH_HISTORY_URI;
}
@Override
public void onOperationStarted(final Uri uri) {
onLoading();
}
@Override
public void onCursorLoaded(final Uri uri, final Cursor cursor) {
super.onCursorLoaded(uri, cursor);
if (!isOperationExecuting()){
if (cursor != null && cursor.getCount() > 0) {
onHasResults();
}
}
}
@Override
public boolean setViewValue(final View view, final Cursor cursor, final
int columnIndex) {
Log.d("SearchHistoryIssue", "setting view value");
switch (view.getId()) {
case R.id.search_symbol:
String symbol = cursor.getString(columnIndex);
View parent = (View) view.getParent();
View dash = parent.findViewById(R.id.search_dash);
TextView symbolTextView = (TextView)
parent.findViewById(R.id.search_symbol);
if (StringUtils.isEmpty(symbol)) {
symbolTextView.setText("");
view.setVisibility(View.GONE);
if (dash != null) {
dash.setVisibility(View.GONE);
}
return true;
} else {
view.setVisibility(View.VISIBLE);
if (dash != null) {
dash.setVisibility(View.VISIBLE);
}
return false;
}
}
return false;
}
private void setSearchViewTextChangedListener(){
mTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(final CharSequence s, final int start,
final int before, final int count) {
handleTextChanged();
}
@Override
public void beforeTextChanged(final CharSequence s, final int
start, final int count,final int after) {
}
@Override
public void afterTextChanged(final Editable s) {
handleAfterTextChanged(s);
}
};
mSearchView.addTextChangedListener(mTextWatcher);
}
private boolean enterButtonClicked = false;
private void setSearchViewKeyListener(){
mSearchView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(final View v, final int keyCode,
final KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_ENTER &&
!enterButtonClicked) {
final String searchString =
mSearchView.getText().toString();
if(!searchString.isEmpty()){
showSearchResults(searchString);
}
enterButtonClicked = true;
return true;
}
enterButtonClicked = false;
return false;
}
});
}
private void handleTextChanged() {
final View clearButton = ((View)
mSearchView.getParent()).findViewById(R.id.clear_search_textbox);
if (mSearchView.getText().length() > 0) {
clearButton.setVisibility(View.VISIBLE);
} else {
handleTextClear(clearButton);
}
displaySearchLink();
}
private void handleAfterTextChanged(final Editable s) {
if (s.length() != 0) {
Log.d("AutoSuggest", "Auto Suggest - text pressed on " +
System.currentTimeMillis());
startSearchAutoSuggestTask(s.toString());
} else {
displaySearchHistory();
}
}
private void handleTextClear(final View clearButton) {
clearButton.setVisibility(View.GONE);
final boolean autoSuggestActive = killLastSearchAutoSuggestTask();
if (!autoSuggestActive) {
displaySearchHistory();
}
}
private void displaySearchHistory() {
final Activity activity = getActivity();
if (activity == null) {
return;
}
mAdapter = new SearchHistoryListAdapter(activity,
R.layout.item_search_history_auto_suggest, null, COLUMN_NAMES,
VIEW_IDS, 0);
mAdapter.setOnItemClickedListener(this);
mAdapter.setViewBinder(this);
mSearchListView.setAdapter(mAdapter);
Log.d("SearchHistoryIssue", "About to restart content loader");
restartContentLoader();
}
public void showSearchResults(final String searchString) {
runSearch(searchString);
saveSearchHistory(searchString, null, null);
}
private void saveSearchHistory(final String searchString, final String
historyMetaData, final String symbol) {
final SearchHistory searchHistory = new SearchHistory(searchString,
historyMetaData, symbol);
DatabaseUtils.addEntryToSearchHistoryTable(searchHistory);
}
private void runSearch(final String searchTerm) {
killLastSearchAutoSuggestTask();
hideSearchView();
if(searchTerm.contains(mSearchView.getText().toString().toLowerCase()
+ " " + mSearchView.getText().toString().toLowerCase())){
AnswersWebViewFragment.newInstanceForSearch(getFragmentManager(),
null, null);
}else {
SearchResultsFragment.newInstance(getFragmentManager(), searchTerm);
}
}
private void displaySearchLink() {
final View view = getView();
if (view != null) {
final String searchText = mSearchView.getText().toString();
final TextView searchLink = (TextView)
view.findViewById(R.id.search_link);
if (StringUtils.isNotEmpty(searchText)) {
searchLink.setText(getResources().getString(R.string.search_for)+"
\"" + searchText + "\"");
searchLink.setVisibility(View.VISIBLE);
}else {
searchLink.setVisibility(View.GONE);
}
}
}
@Override
public void onClick(final View view) {
switch (view.getId()) {
case R.id.search_link:
final String searchText = mSearchView.getText().toString();
showSearchResults(searchText);
break;
default:
break;
}
}
@Override
public void onHistoryItemClicked(final int viewId, final String
searchHistoryTerm, final String searchHistoryMetadata, final String
searchHistorySymbol) {
switch (viewId) {
case R.id.search_history_item_container:
saveSearchHistory(searchHistoryTerm, searchHistoryMetadata,
searchHistorySymbol);
if (StringUtils.isEmpty(searchHistoryMetadata)) {
runSearch(searchHistoryTerm);
} else {
displayQuotes(searchHistoryTerm, searchHistoryMetadata,
searchHistorySymbol);
}
break;
case R.id.search_item_button:
mSearchView.setText(searchHistoryTerm);
mSearchView.requestFocus();
mSearchView.setSelection(searchHistoryTerm.length());
break;
default:
}
}
@Override
public void onAutoSuggestItemClicked(final View view) {
switch (view.getId()) {
case R.id.search_autosuggest_item_container:
final String searchAutoSuggestTitle =
((TextView)view.findViewById(R.id.search_autosuggest_item_name)).getText().toString();
final String searchAutoSuggestSubTitle = (String)
((TextView)view.findViewById(R.id.search_autosuggest_item_subtitle)).getText();
final String searchAutoSuggestSymbol =
((TextView)view.findViewById(R.id.search_autosuggest_item_symbol)).getText().toString();
saveSearchHistory(searchAutoSuggestTitle,
searchAutoSuggestSubTitle, searchAutoSuggestSymbol);
displayQuotes(searchAutoSuggestTitle, searchAutoSuggestSubTitle,
searchAutoSuggestSymbol);
break;
default:
break;
}
}
private void displayQuotes(final String searchAutoSuggestTitle, final
String searchAutoSuggestSubTitle, final String searchAutoSuggestSymbol) {
killLastSearchAutoSuggestTask();
QuotesFragmentWebView.newInstanceForSearch(getFragmentManager(),
searchAutoSuggestSymbol, null);
hideSearchView();
}
private void showKeyboard() {
final MainActivity activity = (MainActivity) getActivity();
if (activity == null) {
return;
}
final EditText searchText = (EditText)
activity.findViewById(R.id.search_text);
KeyboardUtils.showKeyboard(searchText, activity);
}
};
}
Answerswebviewfragment:
public class AnswersWebViewFragment extends Fragment implements
OnClickListener , MainActivity.BackPressListener<Fragment> {
public static String OUTPUT_ENVIRONMENT =
"https://.mobile13.cp.com/msf1.0/fwd/answers/answers/service/v1/?q="+[SEARCHTERM]+"%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
private static AnswersWebViewFragment __newInstance(final
AnswersWebViewFragment fragment, final FragmentManager manager,
final String searchTerm, final String symbolType, int
containerViewId, final int inAnimation, final int
outAnimation, final int popInAnimation, final int
popOutAnimation) {
final Bundle bundle = new Bundle();
bundle.putString(SEARCH_TERM, searchTerm);
bundle.putString(AnswersWebViewFragment.SYMBOL_TYPE, symbolType);
bundle.putInt(AnswersWebViewFragment.CONTAINER_ID, containerViewId);
fragment.setArguments(bundle);
FragmentInfo fragmentInfo = new
FragmentInfo(TransactionMethods.ADD, containerViewId);
fragmentInfo.setAnimation(inAnimation, outAnimation);
fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
fragmentInfo.setFragmentTag(TAG_ANSWERS_FRAGMENT_WEBVIEW);
fragmentInfo.setActionBarTitle(EikonApplication.getAppResources().getString(R.string.nav_option_quotes));
FragmentStackManager.getInstance().transitionFragment(manager,
fragment, fragmentInfo);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSearchTerm = getArguments().getString(SEARCH_TERM);
}
How do I fix the answersWebviewfragment to retrieve the searchterm??
Subscribe to:
Posts (Atom)