Is it necessary to free a shared_ptr?
I'm using Boost library to benefit from the smart pointers : shared_ptr.
I suspect that in my unit test, i'm doing a bad assignment.
What are the drawbacks of my implementation, specially the instuction that
has //suspected comment?
Do I need to free shared_ptr pointers (impossible to do in the way i'm
assigning in my unit test, i guess)?
Any advice? Thanks a lot!
In Class2 declaration:
static boost::shared_ptr<Class1> getInstanceOfClass1();
In Class2 definition:
boost::shared_ptr<Class1> Class2::getInstanceOfClass1()
{
boost::shared_ptr<Class1> inst1 = boost::make_shared<Class1>();
//.... some instructions on inst1
return inst1 ;
}
In a Unit Test using Boost.Test:
BOOST_AUTO_TEST_CASE( test_some_label_here )
{
string input;
//instructions...
// mocking the input
//...
Class2 a = *(Class2::getInstanceOfClass1()); //suspected
int code = a.useInputAndReturnCode(input);
// having CODE_X as a macro
BOOST_CHECK_EQUAL(code, CODE_X);
}
Thursday, 3 October 2013
Wednesday, 2 October 2013
How aright write query?
How aright write query?
Good day.
For my database i use next query.
Code:
SELECT TOP 20
ha.datetime as ha_date,
ha.id_hist_calls as ha_id_hist_calls,
ha.name as ha_name,
s.name as s_name,
ss.name as ss_name
FROM Hist_answer ha
left join Hist_calls hc on hc.id_hist_calls = ha.id_hist_calls
left join Service s on s.id_service = ha.from_id_service
left join Service ss on ss.id_service = ha.id_service
WHERE ha.id_hist_calls NOT IN (
SELECT
ha.id_hist_calls as ha_id_hist_calls
FROM Hist_answer ha
WHERE ha.id_firm='39273' AND ha.datetime BETWEEN '2010.06.01 00:00:000'
AND '2013.10.01 00:00:000'
ORDER BY ha.datetime ASC
)
AND ha.id_firm='39273'
AND ha.datetime BETWEEN '2010.06.01 00:00:000' AND '2013.10.01 00:00:000'
ORDER BY ha.datetime ASC
But when i use this query i get error:
Msg 1033, Level 15, State 1, Line 17
The ORDER BY clause is invalid in views, inline functions, derived tables,
subqueries, and common table expressions, unless TOP or FOR XML is also
specified.
How aright write this select?
Good day.
For my database i use next query.
Code:
SELECT TOP 20
ha.datetime as ha_date,
ha.id_hist_calls as ha_id_hist_calls,
ha.name as ha_name,
s.name as s_name,
ss.name as ss_name
FROM Hist_answer ha
left join Hist_calls hc on hc.id_hist_calls = ha.id_hist_calls
left join Service s on s.id_service = ha.from_id_service
left join Service ss on ss.id_service = ha.id_service
WHERE ha.id_hist_calls NOT IN (
SELECT
ha.id_hist_calls as ha_id_hist_calls
FROM Hist_answer ha
WHERE ha.id_firm='39273' AND ha.datetime BETWEEN '2010.06.01 00:00:000'
AND '2013.10.01 00:00:000'
ORDER BY ha.datetime ASC
)
AND ha.id_firm='39273'
AND ha.datetime BETWEEN '2010.06.01 00:00:000' AND '2013.10.01 00:00:000'
ORDER BY ha.datetime ASC
But when i use this query i get error:
Msg 1033, Level 15, State 1, Line 17
The ORDER BY clause is invalid in views, inline functions, derived tables,
subqueries, and common table expressions, unless TOP or FOR XML is also
specified.
How aright write this select?
Rescale an Image using Python3.2
Rescale an Image using Python3.2
I'm working on a python code that takes an image name from the command
line, and prints its, rescaled to the user's likings, i.e., the input
python3.2 resize.py image.gif 2 3 would take image.gif and double the
width and triple the height. I've written a code for quadrupling an image:
import sys
from cImage import *
def main():
oldImage = FileImage(sys.argv[1])
width = oldImage.getWidth()
height = oldImage.getHeight()
myWin = ImageWin("Old Image", width, height)
myNewWin = ImageWin("Quadrupled Image", width*4, height*4)
newImage = EmptyImage(width*4, height*4)
for r in range(width):
for c in range(height):
pixel = oldImage.getPixel(r, c)
newImage.setPixel(4*r, 4*c, pixel)
newImage.setPixel(4*r, 4*c+1, pixel)
newImage.setPixel(4*r, 4*c+2, pixel)
newImage.setPixel(4*r, 4*c+3, pixel)
newImage.setPixel(4*r+1, 4*c, pixel)
newImage.setPixel(4*r+1, 4*c+1, pixel)
newImage.setPixel(4*r+1, 4*c+2, pixel)
newImage.setPixel(4*r+1, 4*c+3, pixel)
newImage.setPixel(4*r+2, 4*c, pixel)
newImage.setPixel(4*r+2, 4*c+1, pixel)
newImage.setPixel(4*r+2, 4*c+2, pixel)
newImage.setPixel(4*r+2, 4*c+3, pixel)
newImage.setPixel(4*r+3, 4*c, pixel)
newImage.setPixel(4*r+3, 4*c+1, pixel)
newImage.setPixel(4*r+3, 4*c+2, pixel)
newImage.setPixel(4*r+3, 4*c+3, pixel)
oldImage.draw(myWin)
newImage.draw(myNewWin)
myWin.exitOnClick()
myNewWin.exitOnClick()
main()
But I am having trouble try to figure out how to edit my code so it scales
the parameters requested. I feel that I should probably be able to
implement a for loop, but I'm having a hard time getting things to work.
Any help would be much appreciated!
I'm working on a python code that takes an image name from the command
line, and prints its, rescaled to the user's likings, i.e., the input
python3.2 resize.py image.gif 2 3 would take image.gif and double the
width and triple the height. I've written a code for quadrupling an image:
import sys
from cImage import *
def main():
oldImage = FileImage(sys.argv[1])
width = oldImage.getWidth()
height = oldImage.getHeight()
myWin = ImageWin("Old Image", width, height)
myNewWin = ImageWin("Quadrupled Image", width*4, height*4)
newImage = EmptyImage(width*4, height*4)
for r in range(width):
for c in range(height):
pixel = oldImage.getPixel(r, c)
newImage.setPixel(4*r, 4*c, pixel)
newImage.setPixel(4*r, 4*c+1, pixel)
newImage.setPixel(4*r, 4*c+2, pixel)
newImage.setPixel(4*r, 4*c+3, pixel)
newImage.setPixel(4*r+1, 4*c, pixel)
newImage.setPixel(4*r+1, 4*c+1, pixel)
newImage.setPixel(4*r+1, 4*c+2, pixel)
newImage.setPixel(4*r+1, 4*c+3, pixel)
newImage.setPixel(4*r+2, 4*c, pixel)
newImage.setPixel(4*r+2, 4*c+1, pixel)
newImage.setPixel(4*r+2, 4*c+2, pixel)
newImage.setPixel(4*r+2, 4*c+3, pixel)
newImage.setPixel(4*r+3, 4*c, pixel)
newImage.setPixel(4*r+3, 4*c+1, pixel)
newImage.setPixel(4*r+3, 4*c+2, pixel)
newImage.setPixel(4*r+3, 4*c+3, pixel)
oldImage.draw(myWin)
newImage.draw(myNewWin)
myWin.exitOnClick()
myNewWin.exitOnClick()
main()
But I am having trouble try to figure out how to edit my code so it scales
the parameters requested. I feel that I should probably be able to
implement a for loop, but I'm having a hard time getting things to work.
Any help would be much appreciated!
how can I populate and retrieve table of record using java
how can I populate and retrieve table of record using java
Package, in which I declared my Data Types
create or replace package pkg_var is
type array_table is table of varchar2(50);
type array_int is table of number;
type p_arr_rec is record(p_no number,p_val varchar2(50));
type array_record is table of p_arr_rec;
end pkg_var;
/
My procedure to populate record
create or replace procedure proc1(p_array in pkg_var.array_table,
arr_int in pkg_var.array_int,len out number,arr_rec out
pkg_var.array_record)
as
v_count number;
begin
len := p_array.count;
v_count :=0;
for i in 1..p_array.count
loop
--dbms_output.put_line(p_array(i));
arr_rec(i).p_no := arr_int(i);
arr_rec(i).p_val := p_array(i);
v_count := v_count+1;
end loop;
end;
/
This is my class to call the above procedure to populate array into table
of record
public class TestDatabase {
public static void passArray()
{
try{
dbcon conn = new dbcon();
Connection con = conn.dbstate().getConnection();
String str_array[] = {"one", "two", "three","four"};
int int_array[] = {1, 2, 4,8};
ArrayDescriptor str_des =
ArrayDescriptor.createDescriptor("SCOTT.PKG_VAR.ARRAY_TABLE",
con);
ARRAY arr_str = new ARRAY(str_des,con,str_array);
ArrayDescriptor des =
ArrayDescriptor.createDescriptor("SCOTT.PKG_VAR.ARRAY_INT",
con);
ARRAY arr_int = new ARRAY(des,con,int_array);
CallableStatement st = con.prepareCall("call
SCOTT.proc1(?,?,?)");
// Passing an array to the procedure -
st.setArray(1, arr_str);
st.setArray(2, arr_int);
st.registerOutParameter(3, Types.INTEGER);
st.registerOutParameter(4,OracleTypes.ARRAY,"SCOTT.PKG_VAR.ARRAY_RECORD");
st.execute();
System.out.println("size : "+st.getInt(3));
// Retrieving array from the resultset of the procedure after
execution -
ARRAY arr = ((OracleCallableStatement)st).getARRAY(4);
BigDecimal[] recievedArray = (BigDecimal[])(arr.getArray());
for(int i=0;i<recievedArray.length;i++)
System.out.println("element" + i + ":" + recievedArray[i]
+ "\n");
} catch(Exception e) {
System.out.println(e);
}
}
public static void main(String args[]){
passArray();
}
}
I'm getting java.sql.SQLException: invalid name pattern:
SCOTT.PKG_VAR.ARRAY_TABLE Exception, anyone help me to solve this
exception.
One more question how do I retrieve table of record of SQL in Java ? My
second question is for this code ARRAY arr =
((OracleCallableStatement)st).getARRAY(4);
Is it a valid code to get table of record ?
Package, in which I declared my Data Types
create or replace package pkg_var is
type array_table is table of varchar2(50);
type array_int is table of number;
type p_arr_rec is record(p_no number,p_val varchar2(50));
type array_record is table of p_arr_rec;
end pkg_var;
/
My procedure to populate record
create or replace procedure proc1(p_array in pkg_var.array_table,
arr_int in pkg_var.array_int,len out number,arr_rec out
pkg_var.array_record)
as
v_count number;
begin
len := p_array.count;
v_count :=0;
for i in 1..p_array.count
loop
--dbms_output.put_line(p_array(i));
arr_rec(i).p_no := arr_int(i);
arr_rec(i).p_val := p_array(i);
v_count := v_count+1;
end loop;
end;
/
This is my class to call the above procedure to populate array into table
of record
public class TestDatabase {
public static void passArray()
{
try{
dbcon conn = new dbcon();
Connection con = conn.dbstate().getConnection();
String str_array[] = {"one", "two", "three","four"};
int int_array[] = {1, 2, 4,8};
ArrayDescriptor str_des =
ArrayDescriptor.createDescriptor("SCOTT.PKG_VAR.ARRAY_TABLE",
con);
ARRAY arr_str = new ARRAY(str_des,con,str_array);
ArrayDescriptor des =
ArrayDescriptor.createDescriptor("SCOTT.PKG_VAR.ARRAY_INT",
con);
ARRAY arr_int = new ARRAY(des,con,int_array);
CallableStatement st = con.prepareCall("call
SCOTT.proc1(?,?,?)");
// Passing an array to the procedure -
st.setArray(1, arr_str);
st.setArray(2, arr_int);
st.registerOutParameter(3, Types.INTEGER);
st.registerOutParameter(4,OracleTypes.ARRAY,"SCOTT.PKG_VAR.ARRAY_RECORD");
st.execute();
System.out.println("size : "+st.getInt(3));
// Retrieving array from the resultset of the procedure after
execution -
ARRAY arr = ((OracleCallableStatement)st).getARRAY(4);
BigDecimal[] recievedArray = (BigDecimal[])(arr.getArray());
for(int i=0;i<recievedArray.length;i++)
System.out.println("element" + i + ":" + recievedArray[i]
+ "\n");
} catch(Exception e) {
System.out.println(e);
}
}
public static void main(String args[]){
passArray();
}
}
I'm getting java.sql.SQLException: invalid name pattern:
SCOTT.PKG_VAR.ARRAY_TABLE Exception, anyone help me to solve this
exception.
One more question how do I retrieve table of record of SQL in Java ? My
second question is for this code ARRAY arr =
((OracleCallableStatement)st).getARRAY(4);
Is it a valid code to get table of record ?
Is there anyway to extract comments from facebook
Is there anyway to extract comments from facebook
I have project to extract the comments from Facebook and shows than we
will put behavior on it weather is in good mood happy mood sad mood
etc.Actually i don't have an idea where to is there any API available
which programing language will be good please give me a way .
I have project to extract the comments from Facebook and shows than we
will put behavior on it weather is in good mood happy mood sad mood
etc.Actually i don't have an idea where to is there any API available
which programing language will be good please give me a way .
Tuesday, 1 October 2013
Synology Mail server SMTP 535 error
Synology Mail server SMTP 535 error
Good day Ladies and Gentlemen! I don't know if I am allowed to do this,
this is not really a programming problem but a setup problem in my
synology mail server. I can receive mail but the problem is I can't send a
mail. My smtp relay is smtp.gmail.com with a port 587. I really need a
help. I googled it before but it seems that synology forums are not that
active. Thanks and God bless! My NAS is DS1512+
Good day Ladies and Gentlemen! I don't know if I am allowed to do this,
this is not really a programming problem but a setup problem in my
synology mail server. I can receive mail but the problem is I can't send a
mail. My smtp relay is smtp.gmail.com with a port 587. I really need a
help. I googled it before but it seems that synology forums are not that
active. Thanks and God bless! My NAS is DS1512+
I dropped a table in Oracle, how can I retrieve it from the undo tablespace?
I dropped a table in Oracle, how can I retrieve it from the undo tablespace?
I accidentally dropped a fairly large table -- recycling bin is not
enabled. I'm fairly certain the data still exists in the UNDO tablespace,
but I'm not sure how to get it out. I recreated the table exactly as it
was before it was dropped -- the structure is exactly the same. However,
when I attempt to flashback the table, I get this error:
flashback table tablex to timestamp (systimestamp - interval '120'
minute); Error: 01466 DBD::Oracle::db do failed: ORA-01466: unable to read
data - table definition has changed
Any idea how I can overcome this error? From all of the searching I've
done, it seems as if it believes the table is not structurally the same as
when it was dropped.
Thanks so much!
I accidentally dropped a fairly large table -- recycling bin is not
enabled. I'm fairly certain the data still exists in the UNDO tablespace,
but I'm not sure how to get it out. I recreated the table exactly as it
was before it was dropped -- the structure is exactly the same. However,
when I attempt to flashback the table, I get this error:
flashback table tablex to timestamp (systimestamp - interval '120'
minute); Error: 01466 DBD::Oracle::db do failed: ORA-01466: unable to read
data - table definition has changed
Any idea how I can overcome this error? From all of the searching I've
done, it seems as if it believes the table is not structurally the same as
when it was dropped.
Thanks so much!
Making the terminal interface non closable
Making the terminal interface non closable
Let me explain in more details. What i want to do is when i click the
close button on the terminal interface, the terminal should not close. It
should remain open. How can i do this. Thanks in advance.
Let me explain in more details. What i want to do is when i click the
close button on the terminal interface, the terminal should not close. It
should remain open. How can i do this. Thanks in advance.
How to make sure a 3 character filename contains one of 2 characters?
How to make sure a 3 character filename contains one of 2 characters?
So I have to search a directory for files that are of 3 character length.
That is easy, the problem is that at least 1 of the 3 characters needs to
be either a "B" or a "y". I know that [By] would make sure the character
is either a B or a y, however simply doing [By][By][By] would not suffice
since it is not a requirement for all 3 characters to be either B or y;
only 1 of them has to be. Please help.
So I have to search a directory for files that are of 3 character length.
That is easy, the problem is that at least 1 of the 3 characters needs to
be either a "B" or a "y". I know that [By] would make sure the character
is either a B or a y, however simply doing [By][By][By] would not suffice
since it is not a requirement for all 3 characters to be either B or y;
only 1 of them has to be. Please help.
Monday, 30 September 2013
How do I protect a .bat from being erased? [on hold]
How do I protect a .bat from being erased? [on hold]
I have a batch that contain coding that would allow me to protect a secure
folder with password but I'm worried if the batch is erased intentionally
I may not be able to retrieve the file that the batch has password
protected.
Is there a way I can secure this batch file without using things like user
premission etc. Since I am going to be using this batch file on a memory
stick on different computers.
I have a batch that contain coding that would allow me to protect a secure
folder with password but I'm worried if the batch is erased intentionally
I may not be able to retrieve the file that the batch has password
protected.
Is there a way I can secure this batch file without using things like user
premission etc. Since I am going to be using this batch file on a memory
stick on different computers.
help with bash, password delete script
help with bash, password delete script
I would like to make a script that deletes a directory with 'rmdir' after
confirming with a password useing 'read' to set the variable.
so far i have this:
!/bin/bash -x
echo "Password:"
read -t 30 S1
S2='55555'
if [ $S1=$S2 ]; then
rmdir /home/william/test
else
echo "fail"
sleep 10
fi
so i have the "-x" to try to debug it but every time the script either
fails to echo(if i put the password in wrong) or it wont remove the
directory needed.
if someone has a modifiable script that i could use or if you could point
out the problems with the current script that would be great.
I would like to make a script that deletes a directory with 'rmdir' after
confirming with a password useing 'read' to set the variable.
so far i have this:
!/bin/bash -x
echo "Password:"
read -t 30 S1
S2='55555'
if [ $S1=$S2 ]; then
rmdir /home/william/test
else
echo "fail"
sleep 10
fi
so i have the "-x" to try to debug it but every time the script either
fails to echo(if i put the password in wrong) or it wont remove the
directory needed.
if someone has a modifiable script that i could use or if you could point
out the problems with the current script that would be great.
Trying to Pass an Intent from a SherlockActivity to a SherlockFragment
Trying to Pass an Intent from a SherlockActivity to a SherlockFragment
I want to pass an intent from my SherlockActivity to my SherlockFragment
but I am not getting a clue on how to do this. I want to pass the
CategoryID in MaterialsActivity to BooksFragment below. The code of the
MaterialActivity is below and at the far end the BooksFragment is pasted.
public class MaterialsActivity extends SherlockFragmentActivity{
String categoryID = null;
Context context = null;
Resources resources = null;
IDatabaseHelper databaseHelper = null;
// store the active tab here
public static String ACTIVE_TAB = "activeTab";
//Initializing the Tab Fragments that would be added to this view
AudiosFragment audioFragment = null;
BooksFragment bookFragment = null;
VideosFragment videoFragment = null;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setContentView(R.layout.materials);
Intent intent = getIntent();
categoryID = intent.getExtras().getString("categoryID");
context = MaterialsActivity.this;
resources = getResources();
databaseHelper = new DatabaseHelper(context);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// add tabs
Tab tab1 = actionBar.newTab()
.setText("Books")
.setTabListener(new BooksListener<BooksFragment>(
this, "book", BooksFragment.class));
actionBar.addTab(tab1);
// check if there is a saved state to select active tab
if( savedInstanceState != null ){
getSupportActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(ACTIVE_TAB));
}
new CollectMaterials(context,resources).execute();
}
//This is the BooksFragment Listener that would make the Tab
components to listener to a tab click events
public class BooksListener<T extends SherlockListFragment>
implements ActionBar.TabListener{
private BooksFragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public BooksListener(Activity activity, String tag, Class<T>
clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = (BooksFragment) Fragment.instantiate(
mActivity, mClass.getName());
// mFragment..setProviderId(mTag); // id for event provider
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null){
// Detach the fragment, because another one is being
attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do
nothing.
}
}
}
//This is my fragment code below. I would to get the CategoryID here
public class BooksFragment extends SherlockListFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.books, container, false);
// do your view initialization here
return view;
}
}
I want to pass an intent from my SherlockActivity to my SherlockFragment
but I am not getting a clue on how to do this. I want to pass the
CategoryID in MaterialsActivity to BooksFragment below. The code of the
MaterialActivity is below and at the far end the BooksFragment is pasted.
public class MaterialsActivity extends SherlockFragmentActivity{
String categoryID = null;
Context context = null;
Resources resources = null;
IDatabaseHelper databaseHelper = null;
// store the active tab here
public static String ACTIVE_TAB = "activeTab";
//Initializing the Tab Fragments that would be added to this view
AudiosFragment audioFragment = null;
BooksFragment bookFragment = null;
VideosFragment videoFragment = null;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//setContentView(R.layout.materials);
Intent intent = getIntent();
categoryID = intent.getExtras().getString("categoryID");
context = MaterialsActivity.this;
resources = getResources();
databaseHelper = new DatabaseHelper(context);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// add tabs
Tab tab1 = actionBar.newTab()
.setText("Books")
.setTabListener(new BooksListener<BooksFragment>(
this, "book", BooksFragment.class));
actionBar.addTab(tab1);
// check if there is a saved state to select active tab
if( savedInstanceState != null ){
getSupportActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(ACTIVE_TAB));
}
new CollectMaterials(context,resources).execute();
}
//This is the BooksFragment Listener that would make the Tab
components to listener to a tab click events
public class BooksListener<T extends SherlockListFragment>
implements ActionBar.TabListener{
private BooksFragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public BooksListener(Activity activity, String tag, Class<T>
clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = (BooksFragment) Fragment.instantiate(
mActivity, mClass.getName());
// mFragment..setProviderId(mTag); // id for event provider
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null){
// Detach the fragment, because another one is being
attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do
nothing.
}
}
}
//This is my fragment code below. I would to get the CategoryID here
public class BooksFragment extends SherlockListFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.books, container, false);
// do your view initialization here
return view;
}
}
ttk widgets in frame not displayed
ttk widgets in frame not displayed
I'm having some difficulty with Python and ttk. I built a UI that works
correctly, but looks a bit cluttered. I wanted to add a frame so I could
add some padding and enable resizing and so on, but now none of the
widgets are displayed. My code is below.
Previously I was just passing parent as the parent to the widgets, which
did work. I've been working through a few tutorials, and I can't see
anything obviously wrong, though I'm sure it's something simple.
class Application:
def __init__(self, parent):
self.parent = parent
self.content = ttk.Frame(parent, padding=(3,3,12,12))
self.content.columnconfigure(1, weight=1)
self.content.rowconfigure(1, weight=1)
self.row1()
def row1(self):
self.enButton = ttk.Button(self.content, text="Enable",
command=self.enableCmd)
self.disButton = ttk.Button(self.content, text="Disable",
command=self.disableCmd)
self.enButton.grid(column=1, row=1)
self.disButton.grid(column=2, row=1)
self.disButton.state(['disabled'])
if __name__ == '__main__':
root = Tk()
root.title("Wilton Control Interface")
img = Image("photo", file="appicon.gif")
root.tk.call('wm','iconphoto',root._w,img)
app = Application(root)
root.mainloop()
I'm having some difficulty with Python and ttk. I built a UI that works
correctly, but looks a bit cluttered. I wanted to add a frame so I could
add some padding and enable resizing and so on, but now none of the
widgets are displayed. My code is below.
Previously I was just passing parent as the parent to the widgets, which
did work. I've been working through a few tutorials, and I can't see
anything obviously wrong, though I'm sure it's something simple.
class Application:
def __init__(self, parent):
self.parent = parent
self.content = ttk.Frame(parent, padding=(3,3,12,12))
self.content.columnconfigure(1, weight=1)
self.content.rowconfigure(1, weight=1)
self.row1()
def row1(self):
self.enButton = ttk.Button(self.content, text="Enable",
command=self.enableCmd)
self.disButton = ttk.Button(self.content, text="Disable",
command=self.disableCmd)
self.enButton.grid(column=1, row=1)
self.disButton.grid(column=2, row=1)
self.disButton.state(['disabled'])
if __name__ == '__main__':
root = Tk()
root.title("Wilton Control Interface")
img = Image("photo", file="appicon.gif")
root.tk.call('wm','iconphoto',root._w,img)
app = Application(root)
root.mainloop()
Sunday, 29 September 2013
Q.js any() function
Q.js any() function
Is there a way for Q.js to wait until any promise has finished, whether it
has succeeded or not? Maybe there's an obvious way of doing this, as I
can't find an appropriate library function in the docs, but I'm not sure
how to.
Is there a way for Q.js to wait until any promise has finished, whether it
has succeeded or not? Maybe there's an obvious way of doing this, as I
can't find an appropriate library function in the docs, but I'm not sure
how to.
Notify friends of a user who starts using your facebook app
Notify friends of a user who starts using your facebook app
I realize this is a bit vague, but I have no idea where to even begin
searching for this. I know for a fact that when a user registers on
"Circle" using facebook they somehow have found a way to notify all of
that users facebook friends that they joined Circle or at the very least
it notify all of a users friends who also registered with circle that they
joined. How did they accomplish this using the Facebook SDK?
One more time to be perfectly clear: Currently when one of my friends
registers with the social app "Circle" using facebook I end up getting a
notification on Facebook telling me "Joe Smith joined Circle" and I would
like to know how to get my app to do the same thing using the fb sdk
I realize this is a bit vague, but I have no idea where to even begin
searching for this. I know for a fact that when a user registers on
"Circle" using facebook they somehow have found a way to notify all of
that users facebook friends that they joined Circle or at the very least
it notify all of a users friends who also registered with circle that they
joined. How did they accomplish this using the Facebook SDK?
One more time to be perfectly clear: Currently when one of my friends
registers with the social app "Circle" using facebook I end up getting a
notification on Facebook telling me "Joe Smith joined Circle" and I would
like to know how to get my app to do the same thing using the fb sdk
How does Float round when converting it into integer
How does Float round when converting it into integer
If I have
(float)value = 10.50
and do
int new_value = (int)value
what rules will round number?
If I have
(float)value = 10.50
and do
int new_value = (int)value
what rules will round number?
Emacs forms-mode: multiple forms for one file?
Emacs forms-mode: multiple forms for one file?
Is there a way in forms-mode, to have multiple different
"forms-format-lists" which depend on the record currently being read into
the buffer? For example, say I have 5 different types of records in my
file, all with different fields, but each record type is categorized by
say field number 1. Is it possible to define based on the value of a field
number, which form is loaded for a particular record? i.e. a file with
both student and teacher records, and field number one starts with either
"T" or "S". If it begins with "T", load the teacher's form, else the
student one.
Is there a way in forms-mode, to have multiple different
"forms-format-lists" which depend on the record currently being read into
the buffer? For example, say I have 5 different types of records in my
file, all with different fields, but each record type is categorized by
say field number 1. Is it possible to define based on the value of a field
number, which form is loaded for a particular record? i.e. a file with
both student and teacher records, and field number one starts with either
"T" or "S". If it begins with "T", load the teacher's form, else the
student one.
Saturday, 28 September 2013
declaration has no storage class or type specifier
declaration has no storage class or type specifier
Hello: I have the following code used for counting characters:
#include <stdafx.h>
#include <stdio.h>
int main();
{
int CharCount=0; //character counter
int Text; //Text variable
Text = getchar();
while(Text != EOF);
{
CharCounter++
Text = getchar();
}
return 0;
}
in the line Text = getchar(); the program says declaration has no storage
class or type specifier. I thought it was enough to declare Texts as
integer.
Can you help me please?
Hello: I have the following code used for counting characters:
#include <stdafx.h>
#include <stdio.h>
int main();
{
int CharCount=0; //character counter
int Text; //Text variable
Text = getchar();
while(Text != EOF);
{
CharCounter++
Text = getchar();
}
return 0;
}
in the line Text = getchar(); the program says declaration has no storage
class or type specifier. I thought it was enough to declare Texts as
integer.
Can you help me please?
Creating workflow and node in Java
Creating workflow and node in Java
I just start to learn java.
I have a question about way to build object for workflow and node.
I would like to create the workflow which is based on the node for example
each node will contains information such as 1. int time 2. int cost 3.
arraylist relationship 4. boolean is_traveled.
However, I am not really sure how to building workflow with nodes.
I keep searching "workflow" and"node" but it can't find reasonable resources.
Does anybody can give some example or useful resource ?
thanks
I just start to learn java.
I have a question about way to build object for workflow and node.
I would like to create the workflow which is based on the node for example
each node will contains information such as 1. int time 2. int cost 3.
arraylist relationship 4. boolean is_traveled.
However, I am not really sure how to building workflow with nodes.
I keep searching "workflow" and"node" but it can't find reasonable resources.
Does anybody can give some example or useful resource ?
thanks
Is it possible to form design in Java like c#?
Is it possible to form design in Java like c#?
pI'm a new java app developer. I've just installed swing plug-in and when
I'm searching for swing tutorial there is just code to create forms and
other components! I want to know if it's possible to create forms as
simple as we do it in c# with drag and drop?/p
pI'm a new java app developer. I've just installed swing plug-in and when
I'm searching for swing tutorial there is just code to create forms and
other components! I want to know if it's possible to create forms as
simple as we do it in c# with drag and drop?/p
Friday, 27 September 2013
What is the IDE used for Android FRAMEWORK development?
What is the IDE used for Android FRAMEWORK development?
I used Eclipse to develop Android apps. Now, I am going down to the
kernel\framework level. Is there any recommendation of IDEs for Android
framework development, like re-write some kernel codes, create a custom
ROM, etc? Thanks in advance
I used Eclipse to develop Android apps. Now, I am going down to the
kernel\framework level. Is there any recommendation of IDEs for Android
framework development, like re-write some kernel codes, create a custom
ROM, etc? Thanks in advance
delete and return all items in an array
delete and return all items in an array
Is there a helper method to delete all items from an array and return
those items in ruby?
For example,
array = [{:a=>1, :b=>2},{:a=>3,:b=>4},{:a=>5,:b=>6}]
and I want to delete all the array elements and return them so I can do
some processing on those elements?
Is there a helper method to delete all items from an array and return
those items in ruby?
For example,
array = [{:a=>1, :b=>2},{:a=>3,:b=>4},{:a=>5,:b=>6}]
and I want to delete all the array elements and return them so I can do
some processing on those elements?
everything compiles but i dont get any kind of feed back as if the main is not calling the functions does anyone know why?
everything compiles but i dont get any kind of feed back as if the main is
not calling the functions does anyone know why?
i have tested each part individually and i know they work the problem is
when i paste the function roll_dice back in or vise verse.When i compile
the two together i get the error C2143 missing ';' before 'type' on line
32 which is the play_game function. can someone tell me why im getting
this error when they work separately but do not work when they are put
together. This is a craps game and i am a beginner at using c.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_DIE 6
#define true 1
#define false 0
int num1 = 0;
int num2 = 0;
int roll = 0;
int point = 0;
int wins = 0;
int losses = 0;
int keep_rolling = 1;
int main(void)
{
void roll_dice(int num1, int num2, int roll);
{
srand ( time(NULL));
num1 = ("%d",rand() % MAX_DIE +1);
num2 = ("%d",rand() % MAX_DIE +1);
roll = (num1 + num2);
printf("this is your number : %d\n",num1);
printf("this is your 2nd number : %d\n",num2);
printf("this is your total : %d\n",roll);
}
void play_game(int wins, int losses, int point, int roll);
{
if (( roll == 7) ||( roll == 11)){
printf("you rolled %d you won \n", roll);
wins+=1;
}
else if ((roll == 2) || (roll == 3) || (roll== 12)){
printf("you rolled %d you lost \n", roll);
losses+=1;
}
else if ((roll == 1) || (roll == 4) || (roll == 5) || (roll == 6) ||
(roll == 8) || (roll == 9) || (roll == 10)){
printf("you have pointed : %d\n", roll);
point = roll ;
printf("you rolled %d you pointed \n", roll);
while (keep_rolling = 1)
{
void roll_dice(int num1, int num2,int roll);
if(roll == point)
{
printf("you rolled %d you won \n", roll);
wins+=1;
return keep_rolling = false;
}
else if(roll == 7)
{
printf("you rolled %d you lost \n", roll);
losses+=1;
return keep_rolling = false;
}
else
{
printf("you rolled : %d\n", roll);
printf("your point is : %d\n",point);
}
}
}
}
}
not calling the functions does anyone know why?
i have tested each part individually and i know they work the problem is
when i paste the function roll_dice back in or vise verse.When i compile
the two together i get the error C2143 missing ';' before 'type' on line
32 which is the play_game function. can someone tell me why im getting
this error when they work separately but do not work when they are put
together. This is a craps game and i am a beginner at using c.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_DIE 6
#define true 1
#define false 0
int num1 = 0;
int num2 = 0;
int roll = 0;
int point = 0;
int wins = 0;
int losses = 0;
int keep_rolling = 1;
int main(void)
{
void roll_dice(int num1, int num2, int roll);
{
srand ( time(NULL));
num1 = ("%d",rand() % MAX_DIE +1);
num2 = ("%d",rand() % MAX_DIE +1);
roll = (num1 + num2);
printf("this is your number : %d\n",num1);
printf("this is your 2nd number : %d\n",num2);
printf("this is your total : %d\n",roll);
}
void play_game(int wins, int losses, int point, int roll);
{
if (( roll == 7) ||( roll == 11)){
printf("you rolled %d you won \n", roll);
wins+=1;
}
else if ((roll == 2) || (roll == 3) || (roll== 12)){
printf("you rolled %d you lost \n", roll);
losses+=1;
}
else if ((roll == 1) || (roll == 4) || (roll == 5) || (roll == 6) ||
(roll == 8) || (roll == 9) || (roll == 10)){
printf("you have pointed : %d\n", roll);
point = roll ;
printf("you rolled %d you pointed \n", roll);
while (keep_rolling = 1)
{
void roll_dice(int num1, int num2,int roll);
if(roll == point)
{
printf("you rolled %d you won \n", roll);
wins+=1;
return keep_rolling = false;
}
else if(roll == 7)
{
printf("you rolled %d you lost \n", roll);
losses+=1;
return keep_rolling = false;
}
else
{
printf("you rolled : %d\n", roll);
printf("your point is : %d\n",point);
}
}
}
}
}
javascript prompt with name
javascript prompt with name
If my form is filled out completely how do I prompt "Thanks for completing
the form, "name"!"
function submit_onclick() {
if(confirm("Thanks for completing the form " + form.name.value))
document.forms[0].submit();
else
return false;
}
this prompts even when form is empty.
If my form is filled out completely how do I prompt "Thanks for completing
the form, "name"!"
function submit_onclick() {
if(confirm("Thanks for completing the form " + form.name.value))
document.forms[0].submit();
else
return false;
}
this prompts even when form is empty.
C++ design suggestions
C++ design suggestions
I made a program in Java a while back that is essentially a math quiz, it
randomly generates simple math problems based on user input. Now, I'm
teaching myself C++ and I was just wondering, based on efficiency and
organization, what is the best way to convert this program. For example
should my methods be classes, should they stay in one class, ect. Any help
on this would be much appreciated! This is my current Java code
public class MathQuiz {
Scanner s = new Scanner(System.in);
int numberOne;
int numberTwo;
int actualSolution;
int userSolution;
int numberOfQuestions;
int counter = 1;
int temp;
int randomOperation;
int totalCorrect;
int totalIncorrect;
long startTime;
long endTime;
long totalTime;
double percent;
String operation;
String done;
public void mathQuizzer(){
System.out.println("Welcome to Math Quiz!");
System.out.println("What kind of questions would you like to answer?");
System.out.println("Enter + for Addition");
System.out.println("Enter - for Subtraction");
System.out.println("Enter * for Multiplication");
System.out.println("Enter / for Division");
System.out.println("Enter m for Mix");
operation = s.next();
System.out.println("How many questions would you like to answer? ");
numberOfQuestions = s.nextInt();
System.out.println();
startTime = System.currentTimeMillis();
while(counter <= numberOfQuestions){
if(operation.equals("+")){
System.out.println("Question " + counter + ":");
createAdditionEquation();
checkSolution();
counter++;
}
else if(operation.equals("-")){
System.out.println("Question " + counter + ":");
createSubtractionEquation();
checkSolution();
counter++;
}
else if(operation.equals("*")){
System.out.println("Question " + counter + ":");
createMultiplicationEquation();
checkSolution();
counter++;
}
else if(operation.equals("/")){
System.out.println("Question " + counter + ":");
createDivisionEquation();
checkSolution();
counter++;
}
else if (operation.equals("m")){
System.out.println("Question " + counter + ":");
createMixEquation();
checkSolution();
counter++;
}
else{
System.out.println("Sorry invalid operation");
System.exit(0);
}
}
endTime = System.currentTimeMillis();
report();
}
public void createAdditionEquation(){
numberOne = (int)(Math.random() * (100 + 1));
numberTwo = (int)(Math.random() * (100 + 1));
actualSolution = numberOne + numberTwo;
System.out.println(numberOne + " + " + numberTwo + "= ?");
}
public void createSubtractionEquation(){
numberOne = (int)(Math.random() * (100 + 1));
numberTwo = (int)(Math.random() * (100 + 1));
if(numberOne >= numberTwo){
actualSolution = numberOne - numberTwo;
}
else{
numberOne = temp;
numberOne = numberTwo;
numberTwo = temp;
actualSolution = numberOne - numberTwo;
}
System.out.println(numberOne + " - " + numberTwo + "= ?");
}
public void createMultiplicationEquation(){
numberOne = (int)(Math.random() * (10 + 1));
numberTwo = (int)(Math.random() * ((20 - 1) + 1));
actualSolution = numberOne * numberTwo;
System.out.println(numberOne + " * " + numberTwo + "= ?");
}
public void createDivisionEquation(){
numberOne = (int)(Math.random() * (100 + 1));
numberTwo = (int)(1 +(Math.random() * (10 - 1)));
if((numberOne >= numberTwo) && (numberOne%numberTwo == 0)){
System.out.println(numberOne + " / " + numberTwo + "= ?");
actualSolution = numberOne / numberTwo;
}
else{
createDivisionEquation();
}
}
public void createMixEquation(){
randomOperation = (int)(Math.random() * (5 - 1));
System.out.println("Random Operation: " + randomOperation);
if(randomOperation == 0){
createAdditionEquation();
}
else if(randomOperation == 1){
createSubtractionEquation();
}
else if(randomOperation == 2){
createMultiplicationEquation();
}
else
createDivisionEquation();
}
public void checkSolution(){
System.out.println("Answer = ");
userSolution = s.nextInt();
System.out.println();
if(userSolution == actualSolution){
System.out.println("Correct!");
System.out.println("#########################");
System.out.println();
totalCorrect++;
}
else if(userSolution != actualSolution){
System.out.println("Sorry, wrong answer. The correct solution is:
" + actualSolution);
System.out.println("#########################");
System.out.println();
totalIncorrect++;
}
}
public void report(){
percent = ((double) totalCorrect / numberOfQuestions) * 100;
totalTime = (endTime - startTime) / 1000;
System.out.println("Report:");
System.out.println("Questions Answered: " + numberOfQuestions);
System.out.println("Total Correct: " + totalCorrect);
System.out.println("Total Incorrect: " + totalIncorrect);
System.out.println("Percent: " + percent + "%");
System.out.println("Time taken: " + totalTime + " seconds");
}
}
It should be noted that I know this program isn't optimized, and I'm okay
with that for the time being
I made a program in Java a while back that is essentially a math quiz, it
randomly generates simple math problems based on user input. Now, I'm
teaching myself C++ and I was just wondering, based on efficiency and
organization, what is the best way to convert this program. For example
should my methods be classes, should they stay in one class, ect. Any help
on this would be much appreciated! This is my current Java code
public class MathQuiz {
Scanner s = new Scanner(System.in);
int numberOne;
int numberTwo;
int actualSolution;
int userSolution;
int numberOfQuestions;
int counter = 1;
int temp;
int randomOperation;
int totalCorrect;
int totalIncorrect;
long startTime;
long endTime;
long totalTime;
double percent;
String operation;
String done;
public void mathQuizzer(){
System.out.println("Welcome to Math Quiz!");
System.out.println("What kind of questions would you like to answer?");
System.out.println("Enter + for Addition");
System.out.println("Enter - for Subtraction");
System.out.println("Enter * for Multiplication");
System.out.println("Enter / for Division");
System.out.println("Enter m for Mix");
operation = s.next();
System.out.println("How many questions would you like to answer? ");
numberOfQuestions = s.nextInt();
System.out.println();
startTime = System.currentTimeMillis();
while(counter <= numberOfQuestions){
if(operation.equals("+")){
System.out.println("Question " + counter + ":");
createAdditionEquation();
checkSolution();
counter++;
}
else if(operation.equals("-")){
System.out.println("Question " + counter + ":");
createSubtractionEquation();
checkSolution();
counter++;
}
else if(operation.equals("*")){
System.out.println("Question " + counter + ":");
createMultiplicationEquation();
checkSolution();
counter++;
}
else if(operation.equals("/")){
System.out.println("Question " + counter + ":");
createDivisionEquation();
checkSolution();
counter++;
}
else if (operation.equals("m")){
System.out.println("Question " + counter + ":");
createMixEquation();
checkSolution();
counter++;
}
else{
System.out.println("Sorry invalid operation");
System.exit(0);
}
}
endTime = System.currentTimeMillis();
report();
}
public void createAdditionEquation(){
numberOne = (int)(Math.random() * (100 + 1));
numberTwo = (int)(Math.random() * (100 + 1));
actualSolution = numberOne + numberTwo;
System.out.println(numberOne + " + " + numberTwo + "= ?");
}
public void createSubtractionEquation(){
numberOne = (int)(Math.random() * (100 + 1));
numberTwo = (int)(Math.random() * (100 + 1));
if(numberOne >= numberTwo){
actualSolution = numberOne - numberTwo;
}
else{
numberOne = temp;
numberOne = numberTwo;
numberTwo = temp;
actualSolution = numberOne - numberTwo;
}
System.out.println(numberOne + " - " + numberTwo + "= ?");
}
public void createMultiplicationEquation(){
numberOne = (int)(Math.random() * (10 + 1));
numberTwo = (int)(Math.random() * ((20 - 1) + 1));
actualSolution = numberOne * numberTwo;
System.out.println(numberOne + " * " + numberTwo + "= ?");
}
public void createDivisionEquation(){
numberOne = (int)(Math.random() * (100 + 1));
numberTwo = (int)(1 +(Math.random() * (10 - 1)));
if((numberOne >= numberTwo) && (numberOne%numberTwo == 0)){
System.out.println(numberOne + " / " + numberTwo + "= ?");
actualSolution = numberOne / numberTwo;
}
else{
createDivisionEquation();
}
}
public void createMixEquation(){
randomOperation = (int)(Math.random() * (5 - 1));
System.out.println("Random Operation: " + randomOperation);
if(randomOperation == 0){
createAdditionEquation();
}
else if(randomOperation == 1){
createSubtractionEquation();
}
else if(randomOperation == 2){
createMultiplicationEquation();
}
else
createDivisionEquation();
}
public void checkSolution(){
System.out.println("Answer = ");
userSolution = s.nextInt();
System.out.println();
if(userSolution == actualSolution){
System.out.println("Correct!");
System.out.println("#########################");
System.out.println();
totalCorrect++;
}
else if(userSolution != actualSolution){
System.out.println("Sorry, wrong answer. The correct solution is:
" + actualSolution);
System.out.println("#########################");
System.out.println();
totalIncorrect++;
}
}
public void report(){
percent = ((double) totalCorrect / numberOfQuestions) * 100;
totalTime = (endTime - startTime) / 1000;
System.out.println("Report:");
System.out.println("Questions Answered: " + numberOfQuestions);
System.out.println("Total Correct: " + totalCorrect);
System.out.println("Total Incorrect: " + totalIncorrect);
System.out.println("Percent: " + percent + "%");
System.out.println("Time taken: " + totalTime + " seconds");
}
}
It should be noted that I know this program isn't optimized, and I'm okay
with that for the time being
Titanium window open animation left to right showing black screen
Titanium window open animation left to right showing black screen
Titanium SDK: 3.1.2 Platform: Android Titanium Studio: 3.1.3. Hi all I am
new for Titanium and trying to add some animation to my window. When the
window opens, it should open from left to right. I have achieved this with
following code. But there is a problem, before showing animated window, a
black screen appears. So my questions are:- 1) What should i do to remove
the black screen..? 2) What should i do to close the same window with
animation right to left..?
//Application Window Component Constructor
var self = Ti.UI.createWindow({
backgroundColor:'#123',
navBarHidden:false,
exitOnClose:true
});
var devWidth = Ti.Platform.displayCaps.platformWidth;
var button = Ti.UI.createButton({title:'Click',width:100,height:50});
button.addEventListener('click', function(e) {
var detailContainerWindow = Ti.UI.createWindow({
title: 'View Details',
navBarHidden: false,
backgroundColor:'#fff'
});
detailContainerWindow.addEventListener('open', function(){
var anim1 = Ti.UI.createAnimation({
left: "-" + devWidth,
duration: 1000
});
detailContainerWindow.animate(anim1);
});
detailContainerWindow.open();
});
self.add(button);
Titanium SDK: 3.1.2 Platform: Android Titanium Studio: 3.1.3. Hi all I am
new for Titanium and trying to add some animation to my window. When the
window opens, it should open from left to right. I have achieved this with
following code. But there is a problem, before showing animated window, a
black screen appears. So my questions are:- 1) What should i do to remove
the black screen..? 2) What should i do to close the same window with
animation right to left..?
//Application Window Component Constructor
var self = Ti.UI.createWindow({
backgroundColor:'#123',
navBarHidden:false,
exitOnClose:true
});
var devWidth = Ti.Platform.displayCaps.platformWidth;
var button = Ti.UI.createButton({title:'Click',width:100,height:50});
button.addEventListener('click', function(e) {
var detailContainerWindow = Ti.UI.createWindow({
title: 'View Details',
navBarHidden: false,
backgroundColor:'#fff'
});
detailContainerWindow.addEventListener('open', function(){
var anim1 = Ti.UI.createAnimation({
left: "-" + devWidth,
duration: 1000
});
detailContainerWindow.animate(anim1);
});
detailContainerWindow.open();
});
self.add(button);
Thursday, 26 September 2013
How to add a class to an element using jQuery and javascript?
How to add a class to an element using jQuery and javascript?
I have the HTML code as given below to add the navigation to my site.
(Note that the list is nested)
<div id="navigation">
<ul>
<li><a href="default.html">Home</a></li>
<li><a href="about.html">About us</a></li>
<li><a href="help.html">Help</a></li>
<li><a href="#">DropDown</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</li>
<li class="last"><a href="#">A Last Link Text</a></li>
</ul>
</div>
I want to show the currently active page link in new color. So the
corresponding list item should have the class active and I use the CSS to
change the color. For example, if the default.html is the currently opened
page, the code should be <li class="active"><a
href="default.html">Home</a></li>.
How to do that in jQuery and JavaScript (I need both for two different
websites). Can anyone help me?
Thanks for your help.
I have the HTML code as given below to add the navigation to my site.
(Note that the list is nested)
<div id="navigation">
<ul>
<li><a href="default.html">Home</a></li>
<li><a href="about.html">About us</a></li>
<li><a href="help.html">Help</a></li>
<li><a href="#">DropDown</a>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</li>
<li class="last"><a href="#">A Last Link Text</a></li>
</ul>
</div>
I want to show the currently active page link in new color. So the
corresponding list item should have the class active and I use the CSS to
change the color. For example, if the default.html is the currently opened
page, the code should be <li class="active"><a
href="default.html">Home</a></li>.
How to do that in jQuery and JavaScript (I need both for two different
websites). Can anyone help me?
Thanks for your help.
Wednesday, 25 September 2013
Orchard CMS 1.7 - Change in header does not appear on the site. Layout.cshtml issue
Orchard CMS 1.7 - Change in header does not appear on the site.
Layout.cshtml issue
I cannot figure out how to change a text in the header section of my site.
I am trying to do this in my custom module's theme. This is how my header
looks like:
<header>
<div class="container">
<div class="row-fluid">
<div id="Logo"><h1><a href="/" title="Go to
Home">@WorkContext.CurrentSite.SiteName</a></h1></div>
<h3>[ We Know Business ]</h3>
<a class="btn btn-navbar btn-menuh"
data-parent="#collapse-nav"
data-target=".collapse-menuh">btn</a>
<a class="btn btn-navbar btn-search"
data-parent="#collapse-nav"
data-target=".collapse-search">btn</a>
</div>
</div>
</header>
I changed [We Know Business] to [We know Businesses] but the updated text
is not coming up on any page of my site.
However, my main objective is to use HTML5 and Responsive compatibility in
IE8 by injecting conditional CSS and js like this:
<!--[if lt IE 9]>
<script src="/themes/intrust/js/html5shiv.js"></script>
<![endif]-->
I cannot see the above snippet in "View Source" option.
The reason I changed the text only to check whether I am doing it at the
right place or not. When it didn't work I turned Shape Tracing tool on to
see what template is being used for the header. But could not highlight
any part of the header at all!
Isn't Layout.cshtml of my custom theme liable to render the header
section? If not, which template I have to look for?
I must be doing something wrong here but cannot figure out what! Please help!
NB: I tried resetting IIS several times but had no luck either.
Layout.cshtml issue
I cannot figure out how to change a text in the header section of my site.
I am trying to do this in my custom module's theme. This is how my header
looks like:
<header>
<div class="container">
<div class="row-fluid">
<div id="Logo"><h1><a href="/" title="Go to
Home">@WorkContext.CurrentSite.SiteName</a></h1></div>
<h3>[ We Know Business ]</h3>
<a class="btn btn-navbar btn-menuh"
data-parent="#collapse-nav"
data-target=".collapse-menuh">btn</a>
<a class="btn btn-navbar btn-search"
data-parent="#collapse-nav"
data-target=".collapse-search">btn</a>
</div>
</div>
</header>
I changed [We Know Business] to [We know Businesses] but the updated text
is not coming up on any page of my site.
However, my main objective is to use HTML5 and Responsive compatibility in
IE8 by injecting conditional CSS and js like this:
<!--[if lt IE 9]>
<script src="/themes/intrust/js/html5shiv.js"></script>
<![endif]-->
I cannot see the above snippet in "View Source" option.
The reason I changed the text only to check whether I am doing it at the
right place or not. When it didn't work I turned Shape Tracing tool on to
see what template is being used for the header. But could not highlight
any part of the header at all!
Isn't Layout.cshtml of my custom theme liable to render the header
section? If not, which template I have to look for?
I must be doing something wrong here but cannot figure out what! Please help!
NB: I tried resetting IIS several times but had no luck either.
Thursday, 19 September 2013
Disable revert chunk in codemirror merge view
Disable revert chunk in codemirror merge view
I am trying to play with the demo of codemirror merge view and I wanted to
disable the Revert Chunk link. Can anyone tell me if this is doable or if
there is an option to turn off ?
Thanks
I am trying to play with the demo of codemirror merge view and I wanted to
disable the Revert Chunk link. Can anyone tell me if this is doable or if
there is an option to turn off ?
Thanks
How do I get ActionParameters in OnActionExecuted
How do I get ActionParameters in OnActionExecuted
I'm building an history of the action a user called. For this I need all
the parameters in the original querystring. This needs to be done in the
OnActionExecuted (After the action) because some description information
are stored in the filterAction.Result.Model.MyDescription.
On the ActionExecutedContext I do not have access to the ActionParameters
and the RoutesValues only contains action, controller, id and culture. It
doesn't contains any of the other parameters that was included in the
querystring.
How can I preserve the ActionParameters from the OnActionExecuting to the
OnActionExecuted?
Controller:
[ReportHistoryLink]
public ActionResult Index(int id, DateTime at, string by)
{
var model = new ReportModel();
model.ReportDescription = "Some logic get the ReportDescription";
return View("Index", model);
}
ActionFilter:
public class ReportHistoryLinkAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext
filterContext)
{
var model =
(IModelWithReportDescription)((ViewResult)filterContext.Result).Model;
var description = model.ReportDescription;
var boxedId = filterContext.RouteData.Values["id"];
var id = Convert.ToInt32(boxedId);
if (id != 0 && !string.IsNullOrWhiteSpace(targetDescription))
{
var link = new HistoryLink
{
Id = id,
Description = description,
Route = filterContext.RouteData.Values //This doesn't
contains the "at and by parameters"
};
}
}
}
I'm building an history of the action a user called. For this I need all
the parameters in the original querystring. This needs to be done in the
OnActionExecuted (After the action) because some description information
are stored in the filterAction.Result.Model.MyDescription.
On the ActionExecutedContext I do not have access to the ActionParameters
and the RoutesValues only contains action, controller, id and culture. It
doesn't contains any of the other parameters that was included in the
querystring.
How can I preserve the ActionParameters from the OnActionExecuting to the
OnActionExecuted?
Controller:
[ReportHistoryLink]
public ActionResult Index(int id, DateTime at, string by)
{
var model = new ReportModel();
model.ReportDescription = "Some logic get the ReportDescription";
return View("Index", model);
}
ActionFilter:
public class ReportHistoryLinkAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext
filterContext)
{
var model =
(IModelWithReportDescription)((ViewResult)filterContext.Result).Model;
var description = model.ReportDescription;
var boxedId = filterContext.RouteData.Values["id"];
var id = Convert.ToInt32(boxedId);
if (id != 0 && !string.IsNullOrWhiteSpace(targetDescription))
{
var link = new HistoryLink
{
Id = id,
Description = description,
Route = filterContext.RouteData.Values //This doesn't
contains the "at and by parameters"
};
}
}
}
Rounding issues when converting between arrays and tuples
Rounding issues when converting between arrays and tuples
I have a nested list of 2-element lists (lat/lon coordinates)
xlist = [[-75.555476, 42.121701],
[-75.552684, 42.121725],
[-75.55268, 42.122023],
[-75.55250199999999, 42.125071999999996],
[-75.552611, 42.131277] ... ]
that I want to convert into a set. Before I do the conversion, however, I
really want to round these values down to a lower precision so I can
perform set operations on other similar lists and look for points common
to both lists.
I can round with numpy,
x = np.round( xlist, decimals = 4 )
array([[-75.5555, 42.1217],
[-75.5527, 42.1217],
[-75.5527, 42.122 ],
...,
[-75.5552, 42.1086],
[-75.5553, 42.1152],
[-75.5555, 42.1217]])
but then the resulting object is a numpy array which I can't convert to a set
s = set( x )
TypeError: unhashable type: 'numpy.ndarray'
I tried converting the array back into a tuple of tuples
t = ( tuple( row ) for row in x )
but this does nasty things to the precision in the conversion
t.next()
(-75.555499999999995, 42.121699999999997)
I've also tried doing this in a single step, and had no luck
map( tuple, np.round( x, decimals =5 ) )
[(-75.555480000000003, 42.121699999999997),
(-75.552679999999995, 42.121720000000003),
(-75.552679999999995, 42.122019999999999),
(-75.552499999999995, 42.125070000000001)]
Is there something I'm missing about converting between tuples and arrays?
How can I get from a list to a set that has its items rounded to lower
precision?
I have a nested list of 2-element lists (lat/lon coordinates)
xlist = [[-75.555476, 42.121701],
[-75.552684, 42.121725],
[-75.55268, 42.122023],
[-75.55250199999999, 42.125071999999996],
[-75.552611, 42.131277] ... ]
that I want to convert into a set. Before I do the conversion, however, I
really want to round these values down to a lower precision so I can
perform set operations on other similar lists and look for points common
to both lists.
I can round with numpy,
x = np.round( xlist, decimals = 4 )
array([[-75.5555, 42.1217],
[-75.5527, 42.1217],
[-75.5527, 42.122 ],
...,
[-75.5552, 42.1086],
[-75.5553, 42.1152],
[-75.5555, 42.1217]])
but then the resulting object is a numpy array which I can't convert to a set
s = set( x )
TypeError: unhashable type: 'numpy.ndarray'
I tried converting the array back into a tuple of tuples
t = ( tuple( row ) for row in x )
but this does nasty things to the precision in the conversion
t.next()
(-75.555499999999995, 42.121699999999997)
I've also tried doing this in a single step, and had no luck
map( tuple, np.round( x, decimals =5 ) )
[(-75.555480000000003, 42.121699999999997),
(-75.552679999999995, 42.121720000000003),
(-75.552679999999995, 42.122019999999999),
(-75.552499999999995, 42.125070000000001)]
Is there something I'm missing about converting between tuples and arrays?
How can I get from a list to a set that has its items rounded to lower
precision?
C# switch case not compiles when we do not write break in case 1 why is it not working in C# instead of this why we should we use to compile...
C# switch case not compiles when we do not write break in case 1 why is it
not working in C# instead of this why we should we use to compile...
switch (x)
{
case 1:
MessageBox.Show("You enter 1 ");
case 2:
MessageBox.Show("you enter 2");
break;
}
not working in C# instead of this why we should we use to compile...
switch (x)
{
case 1:
MessageBox.Show("You enter 1 ");
case 2:
MessageBox.Show("you enter 2");
break;
}
How to update table2 with table1's id only on a unique match
How to update table2 with table1's id only on a unique match
I have two tables: - table 1 with id, firstname and lastname - table 2
with t1_id, firstname and lastname
I'd like a SQL query (if possible, not a PL/SQL) to update table2 with
table1's id when I have a unique match on firstname and lastname
the word "unique" here is my problem :
update table2 t2
set t1_id = (select id from table1 t1
where t1.firstname=t2.lastname and t1.lastname=t2.lastname)
Whenever I have a match from t2 to multiple t1 records, I get the
"ORA-01427: single-row subquery returns more than one row" error. Any clue
to not update on multiple matches?
Thanks.
I have two tables: - table 1 with id, firstname and lastname - table 2
with t1_id, firstname and lastname
I'd like a SQL query (if possible, not a PL/SQL) to update table2 with
table1's id when I have a unique match on firstname and lastname
the word "unique" here is my problem :
update table2 t2
set t1_id = (select id from table1 t1
where t1.firstname=t2.lastname and t1.lastname=t2.lastname)
Whenever I have a match from t2 to multiple t1 records, I get the
"ORA-01427: single-row subquery returns more than one row" error. Any clue
to not update on multiple matches?
Thanks.
how to previewing the xml files in android studio
how to previewing the xml files in android studio
I am using Android studio and everything is OK and installed and my
project has been built successfully. But I do not have Preview tab for the
actual resource file in layout and there is no "Preview" menu in "Tool
Windows". its grayed out. Why? How can I solve this?
I am using Android studio and everything is OK and installed and my
project has been built successfully. But I do not have Preview tab for the
actual resource file in layout and there is no "Preview" menu in "Tool
Windows". its grayed out. Why? How can I solve this?
I got Exeption handling At ExexuteNonQuery at gridview in asp.net
I got Exeption handling At ExexuteNonQuery at gridview in asp.net
enter code here
Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
TextBox tx1 =
(TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
TextBox tx2 =
(TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
mycon.Open();
SqlCommand myupdatecommand = new SqlCommand("update Users set
(user_name,user_surname) values('"+tx1.Text+"','"+tx2.Text+"') where
user_id='"+lb.Text+"'", mycon);
myupdatecommand.ExecuteNonQuery();
GridView1.EditIndex = -1;
GridView1.DataBind();
enter code here
Label lb = (Label)GridView1.Rows[e.RowIndex].FindControl("Label6");
TextBox tx1 =
(TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
TextBox tx2 =
(TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
mycon.Open();
SqlCommand myupdatecommand = new SqlCommand("update Users set
(user_name,user_surname) values('"+tx1.Text+"','"+tx2.Text+"') where
user_id='"+lb.Text+"'", mycon);
myupdatecommand.ExecuteNonQuery();
GridView1.EditIndex = -1;
GridView1.DataBind();
Wednesday, 18 September 2013
how to make a progress view like the one in KAYAK app
how to make a progress view like the one in KAYAK app
I wonder how to make a progress view that looks like the one in KAYAK app
(it's a travel app to search for flights and hotels), screenshot:
i dig into the resources of KAYAK app on a jailbroken iPhone and found the
following 3 images that construct this progress view:
progressbar-background@2x.png
progressbar-gradient@2x.png
progressbar-overlay@2x.png
giving that the progress view has a moving overlay images that moves
repeatedly along with the gradient image.
any ideas or sample code would be highly appreciated.
I wonder how to make a progress view that looks like the one in KAYAK app
(it's a travel app to search for flights and hotels), screenshot:
i dig into the resources of KAYAK app on a jailbroken iPhone and found the
following 3 images that construct this progress view:
progressbar-background@2x.png
progressbar-gradient@2x.png
progressbar-overlay@2x.png
giving that the progress view has a moving overlay images that moves
repeatedly along with the gradient image.
any ideas or sample code would be highly appreciated.
Using .*; after importing a class
Using .*; after importing a class
I'm learning some java classes through the Java API and I'm just wondering
when you should be using the .*; after each import. Here is what I have
for the program so far.
import java.awt.GridLayout;
public class GridLayoutClass {
public static void main(String[] args){
GridLayout grid = new GridLayout(3, 4);
}
}
I'm learning some java classes through the Java API and I'm just wondering
when you should be using the .*; after each import. Here is what I have
for the program so far.
import java.awt.GridLayout;
public class GridLayoutClass {
public static void main(String[] args){
GridLayout grid = new GridLayout(3, 4);
}
}
Mysqli multi_query Search of 2 Tables Not showing Results
Mysqli multi_query Search of 2 Tables Not showing Results
I'm up to my neck trying to figure out why my query isn't working. This is
what my search.php page results in. I am able to _GET the search term
perfectly but can't display the results.
Not sure if the issue is the fetch_array_assoc or what! Here's my code.
Any help with this would be appreciated. Not 100% sure if my syntax is
correct.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$button = $_GET ['submit'];
$search = $_GET ['query'];
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
$con= new mysqli("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$query = "Keyword_ID LIKE '%$search_each%' or
Keyword_Name LIKE '%$search_each%' ";
else
$query .= "OR Keyword_ID LIKE '%$search_each%' or
Keyword_Name LIKE '%$search_each%' ";
}
$construct = mysqli_query($con,"SELECT * FROM profileTable WHERE
$query");
$construct = mysqli_query($con,"SELECT * FROM addKeywordTable
(Keyword_Name) WHERE $query");
$constructs = mysqli_multi_query($construct);
if(mysqli_multi_query($construct))
{
$numrows = mysqli_num_rows($query);
if ($numrows > 0) {
while ($row = mysqli_fetch_assoc($constructs)) {
$key = $row['Keyword_Name'];
$keyID = $row['keyID'];
$fname = $row['FirName'];
$lname = $row['LaName'];
$mname = $row['MName'];
$suffix = $row['Suffix'];
$title = $row['Title'];
$dept = $row['Dept'];
$phone1 = $row['PH1'];
$phone2 = $row['PH2'];
$email = $row['Email'];
$photo = $row['Photo'];
$bio = $row['BioLK'];
$tags = $row['Tags'];
echo '<h2>$fname $lname</h2>';
echo $key;
echo $title;
echo $dept;
}
}
else
echo "Results found: \"<b>$x</b>\"";
}
}
mysqli_close();
?>
I am trying to search two different tables. addKeywordTable and
profileTable. Profile table has all of the profile info for a user. The
addKeywordTable stores the keywords/tag names 'Keyword_Name'.
I attempted to create a mysqli_multi_query but its not working at all.
I'm up to my neck trying to figure out why my query isn't working. This is
what my search.php page results in. I am able to _GET the search term
perfectly but can't display the results.
Not sure if the issue is the fetch_array_assoc or what! Here's my code.
Any help with this would be appreciated. Not 100% sure if my syntax is
correct.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$button = $_GET ['submit'];
$search = $_GET ['query'];
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
$con= new mysqli("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$query = "Keyword_ID LIKE '%$search_each%' or
Keyword_Name LIKE '%$search_each%' ";
else
$query .= "OR Keyword_ID LIKE '%$search_each%' or
Keyword_Name LIKE '%$search_each%' ";
}
$construct = mysqli_query($con,"SELECT * FROM profileTable WHERE
$query");
$construct = mysqli_query($con,"SELECT * FROM addKeywordTable
(Keyword_Name) WHERE $query");
$constructs = mysqli_multi_query($construct);
if(mysqli_multi_query($construct))
{
$numrows = mysqli_num_rows($query);
if ($numrows > 0) {
while ($row = mysqli_fetch_assoc($constructs)) {
$key = $row['Keyword_Name'];
$keyID = $row['keyID'];
$fname = $row['FirName'];
$lname = $row['LaName'];
$mname = $row['MName'];
$suffix = $row['Suffix'];
$title = $row['Title'];
$dept = $row['Dept'];
$phone1 = $row['PH1'];
$phone2 = $row['PH2'];
$email = $row['Email'];
$photo = $row['Photo'];
$bio = $row['BioLK'];
$tags = $row['Tags'];
echo '<h2>$fname $lname</h2>';
echo $key;
echo $title;
echo $dept;
}
}
else
echo "Results found: \"<b>$x</b>\"";
}
}
mysqli_close();
?>
I am trying to search two different tables. addKeywordTable and
profileTable. Profile table has all of the profile info for a user. The
addKeywordTable stores the keywords/tag names 'Keyword_Name'.
I attempted to create a mysqli_multi_query but its not working at all.
KineticJS apply multiple filters to the image and I saw a hue-filter also
KineticJS apply multiple filters to the image and I saw a hue-filter also
Since filters are poorly documented in the kineticJS I have a problem
applying two filters to a image. Couple of questions:
1) I want to set Blur and Brighten filters to the same image.
Both works separetely:
if (!!image.getAttr('filterBrightness')) {
image.setFilter(Kinetic.Filters.Brighten);
}
image.setFilterBrightness(120);
and
if (!!image.getAttr('filterAmount')){
image.setFilter(Kinetic.Filters.Blur);
}
image.setFilterRadius(2);
I tried
image.applyFilter(Kinetic.Filters.Blur)
image.setFilterAmount(2);
and it worked but again when reapplyin another filter, the blur filter
went off.
2) How do I correctly check if there is a filter set? I tried getFilter()
function but firebug's console.log only shows "function".
3) There is some ShiftHue-filter, but obviously I don't understand a word
from the source. See: http://kineticjs.com/docs/Kinetic.Filters.html and
the source
(http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.js) says
as below. What I don't understand is "set hue shift amount @name
setFilterBrightness" is it a mistake in the source documentation?
How to use that filter? Set filter
/**
* get hue shift amount. The shift amount is a number between 0 and 360.
* @name getFilterBrightness
* @method
* @memberof Kinetic.Image.prototype
*/
/**
* set hue shift amount
* @name setFilterBrightness
* @method
* @memberof Kinetic.Image.prototype
*/
Thank you!
Since filters are poorly documented in the kineticJS I have a problem
applying two filters to a image. Couple of questions:
1) I want to set Blur and Brighten filters to the same image.
Both works separetely:
if (!!image.getAttr('filterBrightness')) {
image.setFilter(Kinetic.Filters.Brighten);
}
image.setFilterBrightness(120);
and
if (!!image.getAttr('filterAmount')){
image.setFilter(Kinetic.Filters.Blur);
}
image.setFilterRadius(2);
I tried
image.applyFilter(Kinetic.Filters.Blur)
image.setFilterAmount(2);
and it worked but again when reapplyin another filter, the blur filter
went off.
2) How do I correctly check if there is a filter set? I tried getFilter()
function but firebug's console.log only shows "function".
3) There is some ShiftHue-filter, but obviously I don't understand a word
from the source. See: http://kineticjs.com/docs/Kinetic.Filters.html and
the source
(http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.0.js) says
as below. What I don't understand is "set hue shift amount @name
setFilterBrightness" is it a mistake in the source documentation?
How to use that filter? Set filter
/**
* get hue shift amount. The shift amount is a number between 0 and 360.
* @name getFilterBrightness
* @method
* @memberof Kinetic.Image.prototype
*/
/**
* set hue shift amount
* @name setFilterBrightness
* @method
* @memberof Kinetic.Image.prototype
*/
Thank you!
Hide tweet button and trigger it?
Hide tweet button and trigger it?
I tried using trigger('click') and display:none,#quickShare {display:none}.
But I am not able to hide this tweet button and trigger it. I added
id="tw" and style="" My code so far:
<a href="https://twitter.com/share" id="tw" class="twitter-share-button"
data-related="jasoncosta" data-lang="en" data-size="large" data-count="none"
style="#quickShare {display:none}">Tweet</a>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$('#tw').trigger('click');//added this!!!rest of code is dumped.
! function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
}
}(document, "script", "twitter-wjs");
</script>
I tried using trigger('click') and display:none,#quickShare {display:none}.
But I am not able to hide this tweet button and trigger it. I added
id="tw" and style="" My code so far:
<a href="https://twitter.com/share" id="tw" class="twitter-share-button"
data-related="jasoncosta" data-lang="en" data-size="large" data-count="none"
style="#quickShare {display:none}">Tweet</a>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$('#tw').trigger('click');//added this!!!rest of code is dumped.
! function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
}
}(document, "script", "twitter-wjs");
</script>
Haxe - compile haxe code to a .NET DLL rather than an EXE
Haxe - compile haxe code to a .NET DLL rather than an EXE
Is is possible to compile haxe code directly to a .NET DLL rather than an
EXE using the haxe compiler?
Is is possible to compile haxe code directly to a .NET DLL rather than an
EXE using the haxe compiler?
List - how to find item by reference?
List - how to find item by reference?
I want to make something like this:
class BaseClass
{
private List<MyClass> list;
private void addData()
{
list.Add(new MyClass(this));
}
public void removeData(MyClass data)
{
list.Remove(data);
}
}
class MyClass
{
private BaseClass baseClass;
public MyClass(BaseClass baseClass)
{
this.baseClass = baseClass;
// DO SOMETHING
calculationDone();
}
private void calculationDone()
{
baseClass.removeData(this);
}
}
My problem is that list.Remove() returns false and item is not removed
from the list. What's wrong with my code?
I want to make something like this:
class BaseClass
{
private List<MyClass> list;
private void addData()
{
list.Add(new MyClass(this));
}
public void removeData(MyClass data)
{
list.Remove(data);
}
}
class MyClass
{
private BaseClass baseClass;
public MyClass(BaseClass baseClass)
{
this.baseClass = baseClass;
// DO SOMETHING
calculationDone();
}
private void calculationDone()
{
baseClass.removeData(this);
}
}
My problem is that list.Remove() returns false and item is not removed
from the list. What's wrong with my code?
Why does not recommend Default encoding in C#?
Why does not recommend Default encoding in C#?
I Googled about encoding. I found that Default encoding is not recommended
in C#. Full message is:
Different computers can use different encodings as the default, and the
default encoding can even change on a single computer. Therefore, data
streamed from one computer to another or even retrieved at different times
on the same computer might be translated incorrectly. In addition, the
encoding returned by the Default property uses best-fit fallback to map
unsupported characters to characters supported by the code page. For these
two reasons, using the default encoding is generally not recommended. To
ensure that encoded bytes are decoded properly, your application should
use a Unicode encoding, such as UTF8Encoding or UnicodeEncoding, with a
preamble. Another option is to use a higher-level protocol to ensure that
the same format is used for encoding and decoding.
Source MSDN
But how to change decoding of Computer ? I am not clear about the bit
"Different computers can use different encodings as the default".
I Googled about encoding. I found that Default encoding is not recommended
in C#. Full message is:
Different computers can use different encodings as the default, and the
default encoding can even change on a single computer. Therefore, data
streamed from one computer to another or even retrieved at different times
on the same computer might be translated incorrectly. In addition, the
encoding returned by the Default property uses best-fit fallback to map
unsupported characters to characters supported by the code page. For these
two reasons, using the default encoding is generally not recommended. To
ensure that encoded bytes are decoded properly, your application should
use a Unicode encoding, such as UTF8Encoding or UnicodeEncoding, with a
preamble. Another option is to use a higher-level protocol to ensure that
the same format is used for encoding and decoding.
Source MSDN
But how to change decoding of Computer ? I am not clear about the bit
"Different computers can use different encodings as the default".
Tuesday, 17 September 2013
Navigation bar disappears when pushing to the next viewController
Navigation bar disappears when pushing to the next viewController
Currently the home page of my application hides the navigation bar;
however, whenever I attempt to push that controller over to the next
viewController it also hides that navigation bar too. I currently have
this is the view controller WITHOUT a navigation bar:
[self.navigationController pushViewController: mapView animated:YES];
Whenever this pushes to the next one it does not have one anymore. The
next viewController's navigation bar is in the viewWillAppear method, so
it should show up. Any ideas?
ANSWER:
If you hide your navigation bar in a ViewController and wish to show it in
the next one then use the following code:
someVC *VC = [someVC alloc] init];
self.navigationController.navigationBarHidden=NO;
[self.navigationController pushViewController: someVC animated:YES];
Thank you!
Currently the home page of my application hides the navigation bar;
however, whenever I attempt to push that controller over to the next
viewController it also hides that navigation bar too. I currently have
this is the view controller WITHOUT a navigation bar:
[self.navigationController pushViewController: mapView animated:YES];
Whenever this pushes to the next one it does not have one anymore. The
next viewController's navigation bar is in the viewWillAppear method, so
it should show up. Any ideas?
ANSWER:
If you hide your navigation bar in a ViewController and wish to show it in
the next one then use the following code:
someVC *VC = [someVC alloc] init];
self.navigationController.navigationBarHidden=NO;
[self.navigationController pushViewController: someVC animated:YES];
Thank you!
Three.js shadow makes everything black
Three.js shadow makes everything black
Scene renders correctly before renderer.shadowMapEnabled = true; is set:
http://jsfiddle.net/NtSv9/
When renderer.shadowMapEnabled = true; is set, along with casting and
receiving shadow, using MeshLambertMaterial, the scene is rendered to be
all black.
Code:
var scene = null;
var camera = null;
var renderer = null;
init();
function init() {
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('mainCanvas')
});
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
renderer.shadowCameraNear = 0.5;
renderer.shadowCameraFar = 100;
renderer.shadowCameraFov = 50;
renderer.shadowMapBias = 0.0039;
renderer.shadowMapDarkness = 0.5;
renderer.shadowMapWidth = 1024;
renderer.shadowMapHeight = 1024;
scene = new THREE.Scene();
camera = new THREE.OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
camera.position.set(5, 15, 25);
camera.lookAt(new THREE.Vector3(0, 0, 0));
scene.add(camera);
var light = new THREE.DirectionalLight(0xffffff);
light.castShadow = true;
light.shadowCameraVisible = true;
light.position.set(-2.0, 5.0, 3.0);
scene.add(light);
var greenCube = new THREE.Mesh(new THREE.CubeGeometry(2, 2, 2),
new THREE.MeshLambertMaterial({color:
0x00ff00}));
greenCube.castShadow = true;
scene.add(greenCube);
var plane = new THREE.Mesh(new THREE.PlaneGeometry(8, 8),
new THREE.MeshLambertMaterial({color:
0xcccccc}));
plane.rotation.x = -Math.PI / 2;
plane.position.y = -1;
plane.receiveShadow = true;
scene.add(plane);
renderer.render(scene, camera);
}
I don't know what went wrong, please have a look at full code at
http://jsfiddle.net/NtSv9/1/
Scene renders correctly before renderer.shadowMapEnabled = true; is set:
http://jsfiddle.net/NtSv9/
When renderer.shadowMapEnabled = true; is set, along with casting and
receiving shadow, using MeshLambertMaterial, the scene is rendered to be
all black.
Code:
var scene = null;
var camera = null;
var renderer = null;
init();
function init() {
renderer = new THREE.WebGLRenderer({
canvas: document.getElementById('mainCanvas')
});
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
renderer.shadowCameraNear = 0.5;
renderer.shadowCameraFar = 100;
renderer.shadowCameraFov = 50;
renderer.shadowMapBias = 0.0039;
renderer.shadowMapDarkness = 0.5;
renderer.shadowMapWidth = 1024;
renderer.shadowMapHeight = 1024;
scene = new THREE.Scene();
camera = new THREE.OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
camera.position.set(5, 15, 25);
camera.lookAt(new THREE.Vector3(0, 0, 0));
scene.add(camera);
var light = new THREE.DirectionalLight(0xffffff);
light.castShadow = true;
light.shadowCameraVisible = true;
light.position.set(-2.0, 5.0, 3.0);
scene.add(light);
var greenCube = new THREE.Mesh(new THREE.CubeGeometry(2, 2, 2),
new THREE.MeshLambertMaterial({color:
0x00ff00}));
greenCube.castShadow = true;
scene.add(greenCube);
var plane = new THREE.Mesh(new THREE.PlaneGeometry(8, 8),
new THREE.MeshLambertMaterial({color:
0xcccccc}));
plane.rotation.x = -Math.PI / 2;
plane.position.y = -1;
plane.receiveShadow = true;
scene.add(plane);
renderer.render(scene, camera);
}
I don't know what went wrong, please have a look at full code at
http://jsfiddle.net/NtSv9/1/
How to define a PHP function to evaluate if url is frontpage?
How to define a PHP function to evaluate if url is frontpage?
How can I define a class to evaluate if url is frontpage and then use it
in my template?
Example:
The class:
public static function url()
{
#The code?
}
To use with this or other function in my template:
<?php if (front_page()): ?>
<p>This will shows only in frontpage</p>
<?php endif;?>
Thank you in advance
How can I define a class to evaluate if url is frontpage and then use it
in my template?
Example:
The class:
public static function url()
{
#The code?
}
To use with this or other function in my template:
<?php if (front_page()): ?>
<p>This will shows only in frontpage</p>
<?php endif;?>
Thank you in advance
How to use preg_match_all according to url?
How to use preg_match_all according to url?
I want to find all about a href tags that include my url in any html source.
I use this code :
preg_match_all("'<a.*?href=\"(http[s]*://[^>\"]*?)\"[^>]*?>(.*?)</a>'si",
$target_source, $matches);
Example, I try to find a href tags that include http://www.emrekadan.com
How can I do it ?
I want to find all about a href tags that include my url in any html source.
I use this code :
preg_match_all("'<a.*?href=\"(http[s]*://[^>\"]*?)\"[^>]*?>(.*?)</a>'si",
$target_source, $matches);
Example, I try to find a href tags that include http://www.emrekadan.com
How can I do it ?
Can I parody the logo of a TV show in my free iOS app? [on hold]
Can I parody the logo of a TV show in my free iOS app? [on hold]
The name of the free game app I am developing is a play on a popular TV
show's name and logo. Everything else is different. I won't give away the
exact concept obviously, but it's as if the name of the game was "Game of
Drones", written with the same font style as "Game of Thrones", but it's
just a simple game where you fly drones around. Would really appreciate
some feedback, thank you!
The name of the free game app I am developing is a play on a popular TV
show's name and logo. Everything else is different. I won't give away the
exact concept obviously, but it's as if the name of the game was "Game of
Drones", written with the same font style as "Game of Thrones", but it's
just a simple game where you fly drones around. Would really appreciate
some feedback, thank you!
AttributeError: 'str' object has no attribute 'toLowerCase'
AttributeError: 'str' object has no attribute 'toLowerCase'
I am writing a program that asks you to enter 5 words (one at a time) and
then prints them out in reverse order. (I am using Python 3.3.2) Here is
what it should look like: http://s11.postimg.org/rayd8m3oj/Untitled.png
But instead it gives me this:
http://s10.postimg.org/c1p590vex/example.png
Here is my code:
fifth_word = input("Please enter your 1st word: ")
fifth_word = fifth_word.toLowerCase
fourth_word = input("Please enter your 2nd word: ")
fourth_word = fourth_word.toLowerCase
third_word = input("Please enter your 3rd word: ")
third_word = third_word.toLowerCase
second_word = input("Please enter your 4th word: ")
second_word = second_word.toLowerCase()
first_word = input("Please enter your 5th word: ")
first_word = first_word.capitalize()
print("The sentence is: " + first_word + second_word + third_word +
fourth_word + fifth_word)
Thanks in advance
I am writing a program that asks you to enter 5 words (one at a time) and
then prints them out in reverse order. (I am using Python 3.3.2) Here is
what it should look like: http://s11.postimg.org/rayd8m3oj/Untitled.png
But instead it gives me this:
http://s10.postimg.org/c1p590vex/example.png
Here is my code:
fifth_word = input("Please enter your 1st word: ")
fifth_word = fifth_word.toLowerCase
fourth_word = input("Please enter your 2nd word: ")
fourth_word = fourth_word.toLowerCase
third_word = input("Please enter your 3rd word: ")
third_word = third_word.toLowerCase
second_word = input("Please enter your 4th word: ")
second_word = second_word.toLowerCase()
first_word = input("Please enter your 5th word: ")
first_word = first_word.capitalize()
print("The sentence is: " + first_word + second_word + third_word +
fourth_word + fifth_word)
Thanks in advance
Sunday, 15 September 2013
How to get a chinese version of Geographical Targeting in Adwords Api?
How to get a chinese version of Geographical Targeting in Adwords Api?
I am developing on Adwords Api, the page:
https://developers.google.com/adwords/api/docs/appendix/geotargeting?hl=cn
provide a english version, but my product need a chinese version. I tried
to translate it by google translate, the result was not so good. Could you
do me a favor to help me if you know?
Any feedback you provide will be greatly appreciated.
I am developing on Adwords Api, the page:
https://developers.google.com/adwords/api/docs/appendix/geotargeting?hl=cn
provide a english version, but my product need a chinese version. I tried
to translate it by google translate, the result was not so good. Could you
do me a favor to help me if you know?
Any feedback you provide will be greatly appreciated.
Dynamically change background color with animated transition
Dynamically change background color with animated transition
I'm trying to generate a random color and set it as the background at the
rate of 1 second. I have created a thread that will handle this change,
now I would like to add a transition between the color changes to make it
blend well.
As a reference, take a look at this app.
My current code is as follows:
new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Main.this.runOnUiThread(new Runnable() {
public void run() {
final LinearLayout mainView = (LinearLayout)
findViewById(R.id.mainLayout);
int red = (int)(Math.random() * 128 + 127);
int green = (int)(Math.random() * 128 + 127);
int blue = (int)(Math.random() * 128 + 127);
int color = 0xff << 24 | (red << 16) |
(green << 8) | blue;
mainView.setBackgroundColor(color);
}
});
}
}
}.start();
}
I've looked into using TransitionDrawable, however I cannot manage to
implement this dynamically. Or perhaps there's an entirely different route
as to getting this color effect- anybody have any ideas?
I'm trying to generate a random color and set it as the background at the
rate of 1 second. I have created a thread that will handle this change,
now I would like to add a transition between the color changes to make it
blend well.
As a reference, take a look at this app.
My current code is as follows:
new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Main.this.runOnUiThread(new Runnable() {
public void run() {
final LinearLayout mainView = (LinearLayout)
findViewById(R.id.mainLayout);
int red = (int)(Math.random() * 128 + 127);
int green = (int)(Math.random() * 128 + 127);
int blue = (int)(Math.random() * 128 + 127);
int color = 0xff << 24 | (red << 16) |
(green << 8) | blue;
mainView.setBackgroundColor(color);
}
});
}
}
}.start();
}
I've looked into using TransitionDrawable, however I cannot manage to
implement this dynamically. Or perhaps there's an entirely different route
as to getting this color effect- anybody have any ideas?
CSS3 sibling selector hover
CSS3 sibling selector hover
I have a problem with css3 and html5. So I decided to make a css effect
when hover column div, column icon starts spinning. But i can't do it. So
where is my problem? http://goo.gl/BLXDF9
I have a problem with css3 and html5. So I decided to make a css effect
when hover column div, column icon starts spinning. But i can't do it. So
where is my problem? http://goo.gl/BLXDF9
stop page from jumping back to top when empty tag is clicked
stop page from jumping back to top when empty tag is clicked
The title says it all, how would I make it using only html to stop the
page from jumping back to the top if a user clicks on an empty tag? So for
example, if at the very bottom of my site, I have a link that is empty,
but click on it, it takes be clear back up to the top...
The title says it all, how would I make it using only html to stop the
page from jumping back to the top if a user clicks on an empty tag? So for
example, if at the very bottom of my site, I have a link that is empty,
but click on it, it takes be clear back up to the top...
Change name of SQL Server's Service
Change name of SQL Server's Service
I already have SQLServerPro 2008. I just installed SQL Server 2008 R2 with
instance name sqlserverr2. Now, I want to change the name of the service
also. I could change name of the server.
select @@SERVICENAME, @@SERVERNAME
It outputs -
SQLEXPRESSR2, HOME\SQLEXPRESS
Means service name is not changed. Only servername changed. Even I cannot
use .\sqlexpress to connect from Managment Studio.
I already have SQLServerPro 2008. I just installed SQL Server 2008 R2 with
instance name sqlserverr2. Now, I want to change the name of the service
also. I could change name of the server.
select @@SERVICENAME, @@SERVERNAME
It outputs -
SQLEXPRESSR2, HOME\SQLEXPRESS
Means service name is not changed. Only servername changed. Even I cannot
use .\sqlexpress to connect from Managment Studio.
How to animate a path using PathMeasure
How to animate a path using PathMeasure
I want to animate a path using the PathMeasure class. My constructor code
is :
Paint paint = new Paint()....
Path p = new Path();
p.moveTo(0,0)
etc etc...
And my overriden onDraw method :
protected void onDraw(Canvas canvas){
canvas.drawPath(p,paint);
etc etc...
}
Is there any way to draw the path animated using the pathMeasure?? Thank you
I want to animate a path using the PathMeasure class. My constructor code
is :
Paint paint = new Paint()....
Path p = new Path();
p.moveTo(0,0)
etc etc...
And my overriden onDraw method :
protected void onDraw(Canvas canvas){
canvas.drawPath(p,paint);
etc etc...
}
Is there any way to draw the path animated using the pathMeasure?? Thank you
How to install ruby-debug-base19 for ruby 2.0.0 and rails 4
How to install ruby-debug-base19 for ruby 2.0.0 and rails 4
I have switched to ruby 2.0.0, rails 4 from rails 3, when i run the
command bundle update rails i get this error
An error occurred while installing ruby-debug-base19 (0.11.25), and
Bundler cannot continue.
Make sure that `gem install ruby-debug-base19 -v '0.11.25'` succeeds
before bundling.
But when run gem install ruby-debug-base19 -v '0.11.25' i got that error:
Building native extensions. This could take a while...
ERROR: Error installing ruby-debug-base19:
ERROR: Failed to build gem native extension.
/home/sunloverz/.rvm/rubies/ruby-2.0.0-p247/bin/ruby extconf.rb
checking for rb_method_entry_t.body in method.h... no
checking for vm_core.h... no
/home/sunloverz/.rvm/gems/ruby-2.0.0-p247@rails-4.0/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:39:in
`create_makefile_with_core': Use RbConfig instead of obsolete and
deprecated Config.
/home/sunloverz/.rvm/gems/ruby-2.0.0-p247@rails-4.0/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:39:in
`create_makefile_with_core': Use RbConfig instead of obsolete and
deprecated Config.
checking for rb_method_entry_t.body in method.h... no
checking for vm_core.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers. Check the mkmf.log file for more details.
You may
need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/sunloverz/.rvm/rubies/ruby-2.0.0-p247/bin/ruby
--with-ruby-dir
--without-ruby-dir
--with-ruby-include
--without-ruby-include=${ruby-dir}/include
--with-ruby-lib
--without-ruby-lib=${ruby-dir}/
/home/sunloverz/.rvm/gems/ruby-2.0.0-p247@rails-4.0/gems/ruby_core_source-0.1.5/lib/contrib/uri_ext.rb:268:in
`block (2 levels) in read': Looking for
http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-2.0.0-p247.tar.gz and all I
got was a 404! (URI::NotFoundError)
I have switched to ruby 2.0.0, rails 4 from rails 3, when i run the
command bundle update rails i get this error
An error occurred while installing ruby-debug-base19 (0.11.25), and
Bundler cannot continue.
Make sure that `gem install ruby-debug-base19 -v '0.11.25'` succeeds
before bundling.
But when run gem install ruby-debug-base19 -v '0.11.25' i got that error:
Building native extensions. This could take a while...
ERROR: Error installing ruby-debug-base19:
ERROR: Failed to build gem native extension.
/home/sunloverz/.rvm/rubies/ruby-2.0.0-p247/bin/ruby extconf.rb
checking for rb_method_entry_t.body in method.h... no
checking for vm_core.h... no
/home/sunloverz/.rvm/gems/ruby-2.0.0-p247@rails-4.0/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:39:in
`create_makefile_with_core': Use RbConfig instead of obsolete and
deprecated Config.
/home/sunloverz/.rvm/gems/ruby-2.0.0-p247@rails-4.0/gems/ruby_core_source-0.1.5/lib/ruby_core_source.rb:39:in
`create_makefile_with_core': Use RbConfig instead of obsolete and
deprecated Config.
checking for rb_method_entry_t.body in method.h... no
checking for vm_core.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers. Check the mkmf.log file for more details.
You may
need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/sunloverz/.rvm/rubies/ruby-2.0.0-p247/bin/ruby
--with-ruby-dir
--without-ruby-dir
--with-ruby-include
--without-ruby-include=${ruby-dir}/include
--with-ruby-lib
--without-ruby-lib=${ruby-dir}/
/home/sunloverz/.rvm/gems/ruby-2.0.0-p247@rails-4.0/gems/ruby_core_source-0.1.5/lib/contrib/uri_ext.rb:268:in
`block (2 levels) in read': Looking for
http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-2.0.0-p247.tar.gz and all I
got was a 404! (URI::NotFoundError)
Saturday, 14 September 2013
What did language constructs Java leave out that C had and why were they left out?
What did language constructs Java leave out that C had and why were they
left out?
just curious about the language constructs Java leave out that C++ had and
why were they left out?
left out?
just curious about the language constructs Java leave out that C++ had and
why were they left out?
Can i restore my website to original site when it was uploaded from cpanel?
Can i restore my website to original site when it was uploaded from cpanel?
I am new to use cpanel. i was having my website(wordpress) in WWW folder
on server.but after 2months of account creation i tried to upload new
folder in my website, but by mistake i override WWW folder to my new
uploaded folder.
So, right now there is no website in WWW folder as i replaced it with new
folder.so how can i get back to my original site ?
is it possible ? now i want to keep it as original it was.is cpanel keeps
bakup automatically ? i even don't have bakup my site. please help
I am new to use cpanel. i was having my website(wordpress) in WWW folder
on server.but after 2months of account creation i tried to upload new
folder in my website, but by mistake i override WWW folder to my new
uploaded folder.
So, right now there is no website in WWW folder as i replaced it with new
folder.so how can i get back to my original site ?
is it possible ? now i want to keep it as original it was.is cpanel keeps
bakup automatically ? i even don't have bakup my site. please help
What is the equivalent to Type.BaseType in WinRT?
What is the equivalent to Type.BaseType in WinRT?
What is the equivalent to Type.BaseType in WinRT?
What is the equivalent to Type.BaseType in WinRT?
"decode" an aproximation of sin Taylor series
"decode" an aproximation of sin Taylor series
I'm using Taylor series to compute sin(). The Taylor series for the sin are:
The implementation I'm using looks like follows:
float sine(float x, int j)
{
float val = 1;
for (int k = j - 1; k >= 0; --k)
val = 1 - x*x/(2*k+2)/(2*k+3)*val;
return x * val;
}
As far I understand, that code is an aproximation of j terms of the
polynomial (In other words, the aproximation is a sumatory from zero to j
instead of from zero to ‡), k is n in the formula, and of course x is x.
I'm trying to understand that implementation, that is, the transformation
from the formula above to the code. My goal is to write the same kind of
implementation for the cos() series.
Could you help me to understand that? Thanks
I'm using Taylor series to compute sin(). The Taylor series for the sin are:
The implementation I'm using looks like follows:
float sine(float x, int j)
{
float val = 1;
for (int k = j - 1; k >= 0; --k)
val = 1 - x*x/(2*k+2)/(2*k+3)*val;
return x * val;
}
As far I understand, that code is an aproximation of j terms of the
polynomial (In other words, the aproximation is a sumatory from zero to j
instead of from zero to ‡), k is n in the formula, and of course x is x.
I'm trying to understand that implementation, that is, the transformation
from the formula above to the code. My goal is to write the same kind of
implementation for the cos() series.
Could you help me to understand that? Thanks
How can I align page # icons to center?
How can I align page # icons to center?
I need help aligning the page # icons (pagination) at the bottom from
right to center.
Here is a link to the page: http://www.vapestore.co/collections/all
Here is the CSS code:
.pagination { margin: 15px; padding:10px; border-bottom:1px solid {{
settings.border_and_underline_color }}; border-top:1px solid {{
settings.border_and_underline_color }}; }
.pagination .parts { float:right; }
.pagination .item.dots, .pagination .item.link, .pagination .item.current
{ display:block; float:left; text-align:center; margin:0 6px 0 0;
padding:0; height:20px; line-height:20px; }
.pagination .item.link { color:{{ settings.shop_bg_color_content_area }};
background-color:{{ settings.link_color }}; -webkit-border-radius:3px;
width:20px; }
I need help aligning the page # icons (pagination) at the bottom from
right to center.
Here is a link to the page: http://www.vapestore.co/collections/all
Here is the CSS code:
.pagination { margin: 15px; padding:10px; border-bottom:1px solid {{
settings.border_and_underline_color }}; border-top:1px solid {{
settings.border_and_underline_color }}; }
.pagination .parts { float:right; }
.pagination .item.dots, .pagination .item.link, .pagination .item.current
{ display:block; float:left; text-align:center; margin:0 6px 0 0;
padding:0; height:20px; line-height:20px; }
.pagination .item.link { color:{{ settings.shop_bg_color_content_area }};
background-color:{{ settings.link_color }}; -webkit-border-radius:3px;
width:20px; }
Extracting the terms of a String using regex in java
Extracting the terms of a String using regex in java
Sorry for the bad title, but really could not find some other words for
it. But, I am working in java and i have the following pattern matching to
do.
The pattern is (\\w)*(\\s+)(\\w)*(\\,)(\\s*)(\\w)*(\\,)?(\\s*)(\\w)*
The String to be matched is of the type "add r0, r1, r2". Now, how can I
extract the all the individual strings from the above string, ie.
add,r0,r1 and r2? To make it clearer, if the input string were "mov r1,
r4", I would like to extract mov, r1 and r4. How to go about this?
Sorry for the bad title, but really could not find some other words for
it. But, I am working in java and i have the following pattern matching to
do.
The pattern is (\\w)*(\\s+)(\\w)*(\\,)(\\s*)(\\w)*(\\,)?(\\s*)(\\w)*
The String to be matched is of the type "add r0, r1, r2". Now, how can I
extract the all the individual strings from the above string, ie.
add,r0,r1 and r2? To make it clearer, if the input string were "mov r1,
r4", I would like to extract mov, r1 and r4. How to go about this?
Spring MVC 3 throwing Not Acceptable error on post request
Spring MVC 3 throwing Not Acceptable error on post request
In my web app users can upload an epub file. The server extracts some data
from the file and returns this to the client in xml or json. Files are
uploaded using the jquery.form plugin from malsup.
I get a 406 (not acceptable) status from spring. Why does this happen?
The response is:
The resource identified by this request is only capable of generating
responses with characteristics not acceptable according to the request
"accept" headers.
My controller looks like:
@Controller
public class FileUploadController {
// handles file form submit
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public SerializedClass save(@RequestParam("posted_file") MultipartFile
file) throws IOException, JAXBException {
return new SerializedClass();
}
The serializedclass:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="body")
public class SerializedClass {
@XmlElement(name="p")
private String p = "a paragraph";
@XmlElement(name="title")
private String title = "the title";
public String getP() {
return p;
}
public void setP(String p) {
this.p = p;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
The request:
Request URL:http://localhost:8080/save.html
Request Method:POST
Status Code:406 Not Acceptable
Request Headersview source
Accept:application/xml, text/xml, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Connection:keep-alive
Content-Length:1160288
Content-Type:multipart/form-data;
boundary=----WebKitFormBoundarytbhYBrnCSDu5T0UB
Cookie:JSESSIONID=BA1C6A44828C145A3F6CD56FD195ACAA
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
------WebKitFormBoundarytbhYBrnCSDu5T0UB
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundarytbhYBrnCSDu5T0UB
Content-Disposition: form-data; name="posted_file"; filename="Sprookjes -
Wilhelm en Jacob Grimm.epub"
Content-Type: application/epub+zip
------WebKitFormBoundarytbhYBrnCSDu5T0UB
Content-Disposition: form-data; name="uploadSubmitter1"
Submit 1
------WebKitFormBoundarytbhYBrnCSDu5T0UB--
Response Headersview source
Content-Length:1067
Content-Type:text/html;charset=utf-8
Date:Sat, 14 Sep 2013 08:58:39 GMT
Server:Apache-Coyote/1.1
I use Maven and JAXB is in my dependency list:
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
What am I missing?
Thank you
In my web app users can upload an epub file. The server extracts some data
from the file and returns this to the client in xml or json. Files are
uploaded using the jquery.form plugin from malsup.
I get a 406 (not acceptable) status from spring. Why does this happen?
The response is:
The resource identified by this request is only capable of generating
responses with characteristics not acceptable according to the request
"accept" headers.
My controller looks like:
@Controller
public class FileUploadController {
// handles file form submit
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public SerializedClass save(@RequestParam("posted_file") MultipartFile
file) throws IOException, JAXBException {
return new SerializedClass();
}
The serializedclass:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="body")
public class SerializedClass {
@XmlElement(name="p")
private String p = "a paragraph";
@XmlElement(name="title")
private String title = "the title";
public String getP() {
return p;
}
public void setP(String p) {
this.p = p;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
The request:
Request URL:http://localhost:8080/save.html
Request Method:POST
Status Code:406 Not Acceptable
Request Headersview source
Accept:application/xml, text/xml, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Connection:keep-alive
Content-Length:1160288
Content-Type:multipart/form-data;
boundary=----WebKitFormBoundarytbhYBrnCSDu5T0UB
Cookie:JSESSIONID=BA1C6A44828C145A3F6CD56FD195ACAA
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
------WebKitFormBoundarytbhYBrnCSDu5T0UB
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundarytbhYBrnCSDu5T0UB
Content-Disposition: form-data; name="posted_file"; filename="Sprookjes -
Wilhelm en Jacob Grimm.epub"
Content-Type: application/epub+zip
------WebKitFormBoundarytbhYBrnCSDu5T0UB
Content-Disposition: form-data; name="uploadSubmitter1"
Submit 1
------WebKitFormBoundarytbhYBrnCSDu5T0UB--
Response Headersview source
Content-Length:1067
Content-Type:text/html;charset=utf-8
Date:Sat, 14 Sep 2013 08:58:39 GMT
Server:Apache-Coyote/1.1
I use Maven and JAXB is in my dependency list:
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
What am I missing?
Thank you
Friday, 13 September 2013
String Compareto actual return value
String Compareto actual return value
In the Java API on oracles website: "compareTo Returns: "the value 0 if
the argument string is equal to this string; a value less than 0 if this
string is lexicographically less than the string argument; and a value
greater than 0 if this string is lexicographically greater than the string
argument." "
Here is an if statement:
String a = "abd";
String b = "abc";
if(a.compareTo(b) >= 1)
returns true since string a is greater, lexicographically.
My question is, does the compareTo always return a 0, 1, or -1? or does it
return the actual amount that the string is greater than or less than the
string argument.
So in the above if statement, since "abd" is one greater than "abc" is it
returning 1?
In the Java API on oracles website: "compareTo Returns: "the value 0 if
the argument string is equal to this string; a value less than 0 if this
string is lexicographically less than the string argument; and a value
greater than 0 if this string is lexicographically greater than the string
argument." "
Here is an if statement:
String a = "abd";
String b = "abc";
if(a.compareTo(b) >= 1)
returns true since string a is greater, lexicographically.
My question is, does the compareTo always return a 0, 1, or -1? or does it
return the actual amount that the string is greater than or less than the
string argument.
So in the above if statement, since "abd" is one greater than "abc" is it
returning 1?
Established TCP connections not crossing more than 400 on particular socket
Established TCP connections not crossing more than 400 on particular socket
I written one program in java which handles request from particular
socket. Some times request comes concurrently we can say 1000/sec and that
time ESTABLISHED TCP connections touched around 400. When ESTABLISHED
connections touched 400 then socket start refusing the request and then I
miss my reporting. Can I increase ESTABLISHED TCP connections on
particular port ? Any time wait condition for ESTABLISHED TCP ?
I written one program in java which handles request from particular
socket. Some times request comes concurrently we can say 1000/sec and that
time ESTABLISHED TCP connections touched around 400. When ESTABLISHED
connections touched 400 then socket start refusing the request and then I
miss my reporting. Can I increase ESTABLISHED TCP connections on
particular port ? Any time wait condition for ESTABLISHED TCP ?
Laravel 4: img, css, js folders are returning 404
Laravel 4: img, css, js folders are returning 404
For some reason (I've never had this issue before) all of the files that
exist in either my img, js, or css folder "dont exist" ... I'm getting a
404 Not Found
For some reason (I've never had this issue before) all of the files that
exist in either my img, js, or css folder "dont exist" ... I'm getting a
404 Not Found
Why exactly malloc is used?
Why exactly malloc is used?
I have been trying to understand what is malloc() and why is it used. I
understand that malloc is for dynamic allocation of memory, it is needed
if you don't know how much memory you wan't to create. I have been doing
some hands-on on it.
The following code declares an array of character pointers, and 1st
character pointer is initialized with "hello". This works fine.
int main()
{
char *strarray[5];
strarray[0]="hello";
printf("%s\n",strarray[0]);
return 0;
}
But if i try to use strcpy() function to copy "hello" string into
strarray[0] (without malloc()) it gives a problem. And it goes into some
loop and does not copy the string. And it works fine if i use malloc to
allocate memory.
int main()
{
char *strarray[5];
//strarray[0]=(char *)malloc(sizeof(char)*10);
strcpy(strarray[0],"hello");
printf("%s\n",strarray[0]);
return 0;
}
I want to know what makes the difference? If i can initialize "hello" to a
char pointer for which malloc is not used, why can't i do the same with
strcpy().
I have been trying to understand what is malloc() and why is it used. I
understand that malloc is for dynamic allocation of memory, it is needed
if you don't know how much memory you wan't to create. I have been doing
some hands-on on it.
The following code declares an array of character pointers, and 1st
character pointer is initialized with "hello". This works fine.
int main()
{
char *strarray[5];
strarray[0]="hello";
printf("%s\n",strarray[0]);
return 0;
}
But if i try to use strcpy() function to copy "hello" string into
strarray[0] (without malloc()) it gives a problem. And it goes into some
loop and does not copy the string. And it works fine if i use malloc to
allocate memory.
int main()
{
char *strarray[5];
//strarray[0]=(char *)malloc(sizeof(char)*10);
strcpy(strarray[0],"hello");
printf("%s\n",strarray[0]);
return 0;
}
I want to know what makes the difference? If i can initialize "hello" to a
char pointer for which malloc is not used, why can't i do the same with
strcpy().
How to plot a heatmap of a big matrix with matplotlib (45K * 446)
How to plot a heatmap of a big matrix with matplotlib (45K * 446)
I am trying to plot a heatmap of a big microarray dataset (45K rows per
446 columns). Using pcolor from matplotlib I am unable to do it because my
pc goes easily out of memory (more than 8G)..
I'd prefer to use python/matplotlib instead of R for personal opinion..
Any way to plot heatmaps in an efficient way?
Thanks
I am trying to plot a heatmap of a big microarray dataset (45K rows per
446 columns). Using pcolor from matplotlib I am unable to do it because my
pc goes easily out of memory (more than 8G)..
I'd prefer to use python/matplotlib instead of R for personal opinion..
Any way to plot heatmaps in an efficient way?
Thanks
CONFIGURATION WINDOWS BIND9 DNS SERVER
CONFIGURATION WINDOWS BIND9 DNS SERVER
I've node.js running an application with a vhost listening on
"example.com" on my local windows pc. A WLAN-Router is attached to that
pc. With my mobile phone I try to connect to the app (connected in the
local WLAN). I can't configure the DNS on the router that's why I tried to
install and configure BIND9.
Address | IP of my computer connected to the router
------------+--------------
example.com | 192.168.1.2
Content of c:\bind\etc\named.conf
options {
directory "c:\bind\etc\";
allow-transfer { none; };
recursion no;
listen-on {any;};
};
zone "example.com" {
type master;
file "c:\bind\etc\master\db\db.example.com";
};
key "rndc-key" {
algorithm hmac-md5;
secret "pj7p+9yRbo78//21zNnu4A==";
};
controls {
inet 192.168.1.2 port 953
allow { 192.168.1.2; } keys { "rndc-key"; };
};
Content of my zone file "c:\bind\etc\master\db\db.example.com"
$TTL 24h
@ IN SOA ns1.example.com. root.example.com. (
2013110901
10800
3600
604800
86400 )
NS ns1.example.com.
ns1 A 192.168.1.2
primary A 192.168.1.2
www CNAME primary
I don't care if the vshost is working, the only thing I try is,
nevertheless what I type into my mobile phones browser (it can be facebook
or google or anything else), I want to come out on my appfrontend, which
node.js deploys.
checkconf and checkzone worked without throwing an error. The name server
is listening on port 53.
Would be great if anybody could take a look at it and give me hint on what
I am doing wrong? Thanks
I've node.js running an application with a vhost listening on
"example.com" on my local windows pc. A WLAN-Router is attached to that
pc. With my mobile phone I try to connect to the app (connected in the
local WLAN). I can't configure the DNS on the router that's why I tried to
install and configure BIND9.
Address | IP of my computer connected to the router
------------+--------------
example.com | 192.168.1.2
Content of c:\bind\etc\named.conf
options {
directory "c:\bind\etc\";
allow-transfer { none; };
recursion no;
listen-on {any;};
};
zone "example.com" {
type master;
file "c:\bind\etc\master\db\db.example.com";
};
key "rndc-key" {
algorithm hmac-md5;
secret "pj7p+9yRbo78//21zNnu4A==";
};
controls {
inet 192.168.1.2 port 953
allow { 192.168.1.2; } keys { "rndc-key"; };
};
Content of my zone file "c:\bind\etc\master\db\db.example.com"
$TTL 24h
@ IN SOA ns1.example.com. root.example.com. (
2013110901
10800
3600
604800
86400 )
NS ns1.example.com.
ns1 A 192.168.1.2
primary A 192.168.1.2
www CNAME primary
I don't care if the vshost is working, the only thing I try is,
nevertheless what I type into my mobile phones browser (it can be facebook
or google or anything else), I want to come out on my appfrontend, which
node.js deploys.
checkconf and checkzone worked without throwing an error. The name server
is listening on port 53.
Would be great if anybody could take a look at it and give me hint on what
I am doing wrong? Thanks
To find the difference b/w two numbers in a column of file?
To find the difference b/w two numbers in a column of file?
Consider a input file with 5 column(0-5):
1 0 937 306 97 3
2 164472 75 17 81 3
3 197154 35268 306 97 3
4 310448 29493 64 38 1
5 310541 29063 64 38 1
6 310684 33707 64 38 1
7 319091 47451 16 41 1
8 319101 49724 16 41 1
9 324746 61578 1 5 1
10 324939 54611 1 5 1
for the second column i,e column1(0,164472,197154-----------) need to find
the difference b/w numbers so that the column1 should be
(0,164472-0,197154-164472,____) so (0,164472,32682..............).
And the output file must change only the column1 values all other values
must remain the same as input file:
1 0 937 306 97 3
2 164472 75 17 81 3
3 32682 35268 306 97 3
4 113294 29493 64 38 1
5 93 29063 64 38 1
6 143 33707 64 38 1
7 8407 47451 16 41 1
8 10 49724 16 41 1
9 5645 61578 1 5 1
10 193 54611 1 5 1
if anyone could suggest a python code to do this it would be helpfull........
Consider a input file with 5 column(0-5):
1 0 937 306 97 3
2 164472 75 17 81 3
3 197154 35268 306 97 3
4 310448 29493 64 38 1
5 310541 29063 64 38 1
6 310684 33707 64 38 1
7 319091 47451 16 41 1
8 319101 49724 16 41 1
9 324746 61578 1 5 1
10 324939 54611 1 5 1
for the second column i,e column1(0,164472,197154-----------) need to find
the difference b/w numbers so that the column1 should be
(0,164472-0,197154-164472,____) so (0,164472,32682..............).
And the output file must change only the column1 values all other values
must remain the same as input file:
1 0 937 306 97 3
2 164472 75 17 81 3
3 32682 35268 306 97 3
4 113294 29493 64 38 1
5 93 29063 64 38 1
6 143 33707 64 38 1
7 8407 47451 16 41 1
8 10 49724 16 41 1
9 5645 61578 1 5 1
10 193 54611 1 5 1
if anyone could suggest a python code to do this it would be helpfull........
Thursday, 12 September 2013
Decrypting hex string and getting non-hex characters when I try to print
Decrypting hex string and getting non-hex characters when I try to print
In the code below I'm trying to decrypt an encrypted message given two
messages encrypted with the same key (two-time pad). The code works as I
want it too until the last line where I try an print out the hex string as
ascii.
I get the error:
print result.decode('hex')
File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found
The hex string that is causing the error is:
ab51e67kba7<4:72fd`d
Which has some non hex characters in it. I'm not sure why it has the
non-hex in it. Or where to go from here.
Here's the full code:
# Messages
m1 = "31aa4573aa487946aa15"
m2 = "32510ba9babebbbefd00"
# Key
k = "6b6bdfa4rqggrgwereff"
guess = 'aa'
#guess = guess.encode('hex')
result = ''
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)],
b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a,
b[:len(a)])])
# Make cipher texts
c1 = strxor(m1,k)
c2 = strxor(m2,k)
# xor of the two messages
m1m2 = strxor(c1,c2)
# loop through each bit of the m1m2 message and xor against a test char or
string
# see if any of the output makes sense
for e in range(0, len(m1), 2):
subString = m1m2[e:e+2]
try:
result = result + "".join( strxor(subString, guess))
except exception:
pass
#print hex and ascii results
print result
print result.decode('hex')
In the code below I'm trying to decrypt an encrypted message given two
messages encrypted with the same key (two-time pad). The code works as I
want it too until the last line where I try an print out the hex string as
ascii.
I get the error:
print result.decode('hex')
File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found
The hex string that is causing the error is:
ab51e67kba7<4:72fd`d
Which has some non hex characters in it. I'm not sure why it has the
non-hex in it. Or where to go from here.
Here's the full code:
# Messages
m1 = "31aa4573aa487946aa15"
m2 = "32510ba9babebbbefd00"
# Key
k = "6b6bdfa4rqggrgwereff"
guess = 'aa'
#guess = guess.encode('hex')
result = ''
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)],
b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a,
b[:len(a)])])
# Make cipher texts
c1 = strxor(m1,k)
c2 = strxor(m2,k)
# xor of the two messages
m1m2 = strxor(c1,c2)
# loop through each bit of the m1m2 message and xor against a test char or
string
# see if any of the output makes sense
for e in range(0, len(m1), 2):
subString = m1m2[e:e+2]
try:
result = result + "".join( strxor(subString, guess))
except exception:
pass
#print hex and ascii results
print result
print result.decode('hex')
How Can I debug Classic ASP in Visual Studio 2010 with out local IIS installed?
How Can I debug Classic ASP in Visual Studio 2010 with out local IIS
installed?
I am aware that Classic ASP debugging is not possible with Visual Studio
2010 Development server.
It is possible with IIS installed locally, but my case was bit tricky. Due
to security restrictions, I need to work with Visual Studio 2010 - but
without IIS installed locally.
Is there any alternative, workaround, or easy trick to make it debug
classic ASP?
installed?
I am aware that Classic ASP debugging is not possible with Visual Studio
2010 Development server.
It is possible with IIS installed locally, but my case was bit tricky. Due
to security restrictions, I need to work with Visual Studio 2010 - but
without IIS installed locally.
Is there any alternative, workaround, or easy trick to make it debug
classic ASP?
oracle -- Split multiple comma separated values in oracle table to multiple rows
oracle -- Split multiple comma separated values in oracle table to
multiple rows
I Have a problem with oracle split query
While splitting comma separated data into multiple rows using connect by
and regular expression in oracle query i am getting more duplicate rows.
for example actually my table having 150 rows in that one two rows having
comma separated strings so overall i have to get only 155 rows but i am
getting 2000 rows. If i use distinct its working fine but i dont want
duplicate rows in query result.
I tried the following query
WITH CTE AS (SELECT 'a,b,c,d,e' temp,1 slno FROM DUAL
UNION
SELECT 'f,g',2 from dual
UNION
SELECT 'h',3 FROM DUAL)
SELECT TRIM(REGEXP_SUBSTR( TEMP, '[^,]+', 1, LEVEL)) ,SLNO FROM CTE
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(temp, '[^,]+')) + 1
multiple rows
I Have a problem with oracle split query
While splitting comma separated data into multiple rows using connect by
and regular expression in oracle query i am getting more duplicate rows.
for example actually my table having 150 rows in that one two rows having
comma separated strings so overall i have to get only 155 rows but i am
getting 2000 rows. If i use distinct its working fine but i dont want
duplicate rows in query result.
I tried the following query
WITH CTE AS (SELECT 'a,b,c,d,e' temp,1 slno FROM DUAL
UNION
SELECT 'f,g',2 from dual
UNION
SELECT 'h',3 FROM DUAL)
SELECT TRIM(REGEXP_SUBSTR( TEMP, '[^,]+', 1, LEVEL)) ,SLNO FROM CTE
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(temp, '[^,]+')) + 1
Ejabberd Server not allowing user to login
Ejabberd Server not allowing user to login
Steps to Create the Issue:
logged into my ejabberd admin portal.
Added a User.
Attempted to login with the same configuration as a working account.
Pidgeon says "Not Authorized"
Additional info: I see the user in the list of "Users" in the admin portal.
Whats wrong?
Note: Restarting the server/service is not a viable option at the moment.
I don't know much about this at the moment, I inherited this project from
someone else.
Steps to Create the Issue:
logged into my ejabberd admin portal.
Added a User.
Attempted to login with the same configuration as a working account.
Pidgeon says "Not Authorized"
Additional info: I see the user in the list of "Users" in the admin portal.
Whats wrong?
Note: Restarting the server/service is not a viable option at the moment.
I don't know much about this at the moment, I inherited this project from
someone else.
IOS: How to draw and calculate position of the custom callout arrow in IOS 6?
IOS: How to draw and calculate position of the custom callout arrow in IOS 6?
I am trying to implement an application which has a map and on that map
there are several pins. Also I am implementing a custom callout view for
the map annotations by sub classing the MKAnnotationView class.
Every thing is working fine but I am unable to draw the callout arrow and
cannot calculate the exact position of the callout arrow so that it shows
right on top of the annottaion pin. Any help would be greatly appreciated.
Currently I am just adding my custom callout view as a subview of
MKAnnotationView and altering its frame. But cannot draw and position the
callout arrow on the map.
I am trying to implement an application which has a map and on that map
there are several pins. Also I am implementing a custom callout view for
the map annotations by sub classing the MKAnnotationView class.
Every thing is working fine but I am unable to draw the callout arrow and
cannot calculate the exact position of the callout arrow so that it shows
right on top of the annottaion pin. Any help would be greatly appreciated.
Currently I am just adding my custom callout view as a subview of
MKAnnotationView and altering its frame. But cannot draw and position the
callout arrow on the map.
Resultset not giving values (not entering in while loop)
Resultset not giving values (not entering in while loop)
I have following code in android:
protected void onPostExecute(ResultSet rsData)
{
try
{
int size=0;
while(rsData.next())
{
size++;
}
mlst = new String[size];
int i=0;
while(rsData.next())
{
String mid = rsData.getString(rsData.findColumn("mid"));
String uid = rsData.getString(rsData.findColumn("uid"));
String messages =
rsData.getString(rsData.findColumn("message"));
String
read=rsData.getString(rsData.findColumn("rstamp"));
mdb.addMessage(new Contact(mid, uid, messages, read));
mlst[i]=mid;
i++;
}
con.UpdateMessage(mlst);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In this i kept debugger on each line.
I found that in first while loop value of size becomes 7.
Means there are 7 rows in rsData ResultSet.
But as soon as it comes on second while loop, it suddenly does not enters
in while loop and control directly goes to line : con.UpdateMessage(mlst);
I am not able to understand why its happening so?
If resultset has 7 rows in it, then it should enter in it 7 times, but its
not entering a single time.
Please help me.
I have following code in android:
protected void onPostExecute(ResultSet rsData)
{
try
{
int size=0;
while(rsData.next())
{
size++;
}
mlst = new String[size];
int i=0;
while(rsData.next())
{
String mid = rsData.getString(rsData.findColumn("mid"));
String uid = rsData.getString(rsData.findColumn("uid"));
String messages =
rsData.getString(rsData.findColumn("message"));
String
read=rsData.getString(rsData.findColumn("rstamp"));
mdb.addMessage(new Contact(mid, uid, messages, read));
mlst[i]=mid;
i++;
}
con.UpdateMessage(mlst);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In this i kept debugger on each line.
I found that in first while loop value of size becomes 7.
Means there are 7 rows in rsData ResultSet.
But as soon as it comes on second while loop, it suddenly does not enters
in while loop and control directly goes to line : con.UpdateMessage(mlst);
I am not able to understand why its happening so?
If resultset has 7 rows in it, then it should enter in it 7 times, but its
not entering a single time.
Please help me.
Wednesday, 11 September 2013
Expected initializer before function name in header. C
Expected initializer before function name in header. C
I'm getting "expected initializer before 'read_file' as an error. The
error is on the line "instruction code[] read_file(instruction code[])."
Its on line Been searching the web for help, all im finding is c++ related
post, so to clarify this is for C.
I've tried moving around the positioning of the function protypes. I wrote
the same program earlier that implemented linked list instead of an array
and I had no errors, so I'm thinking it may have something to do with the
structure array.
Thanks for the help.
#include<stdio.h>
#include <stdlib.h>
typedef struct instruction{
int op; //opcode
int l; // L
int m; // M
} instr;
FILE * ifp; //input file pointer
FILE * ofp; //output file pointer
instruction code[501];
instruction code[] read_file(instruction code[]);
char* lookup_OP(int OP);
void print_program(instruction code[]);
void print_input_list(instruction code[]);
int main(){
code = read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
instruction code[] read_file(instruction code[]){
int i = 0;
ifp = fopen("input.txt", "r");
while(!feof(ifp)){
fscanf(ifp,"%d%d%d",&code[i]->op, &code[i]->l, &code[i]->m);
i++;
}
code[i]->op = -1; //identifies the end of the code in the array
fclose(ifp);
return code;
}
I'm getting "expected initializer before 'read_file' as an error. The
error is on the line "instruction code[] read_file(instruction code[])."
Its on line Been searching the web for help, all im finding is c++ related
post, so to clarify this is for C.
I've tried moving around the positioning of the function protypes. I wrote
the same program earlier that implemented linked list instead of an array
and I had no errors, so I'm thinking it may have something to do with the
structure array.
Thanks for the help.
#include<stdio.h>
#include <stdlib.h>
typedef struct instruction{
int op; //opcode
int l; // L
int m; // M
} instr;
FILE * ifp; //input file pointer
FILE * ofp; //output file pointer
instruction code[501];
instruction code[] read_file(instruction code[]);
char* lookup_OP(int OP);
void print_program(instruction code[]);
void print_input_list(instruction code[]);
int main(){
code = read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
instruction code[] read_file(instruction code[]){
int i = 0;
ifp = fopen("input.txt", "r");
while(!feof(ifp)){
fscanf(ifp,"%d%d%d",&code[i]->op, &code[i]->l, &code[i]->m);
i++;
}
code[i]->op = -1; //identifies the end of the code in the array
fclose(ifp);
return code;
}
Interpolation between several values at the same point of consecutive arrays
Interpolation between several values at the same point of consecutive arrays
I have data of arrays such as:
[[1 3 5 1 . . 2] [9 3 6 1 . . 5] . . . [1 8 5 1 . . 7]]
[[2 2 3 7 . . 1] [10 2 5 3 . . 2] . . . [3 1 3 6 . . 11]]
.
.
[[7 10 15 11 . . 12] [4 7 1 3 . . 3] . . . [2 3 7 2 . . 1]]
I would like to get the value by interpolation between each set of arrays
in the same point. For example, the first values of the first array
(column) would be 1 2 ....7. In that series of numbers, I would like to
interpolate the value between 1 and 2, 2 and next number .... the previous
number and 7. The number of these array set would be 200 and I should be
extract those data array by using loop.
Such as:
for c in range(0,199):
w = wles[:,c,:,:]
th = Theta[:,c,:,:]
th_total = th + 300
w_mean = np.mean(w)
th_mean = np.mean(th_total)
wp = w - w_mean
thp = th_total - th_mean
mwtp = wp * thp
mwtp = list(mwtp)
mwtp1 = mwtp1 + [mwtp]
In that code, I would like to get values at each point in the array
between each loop for th by interpolation.
I am sorry that question itself is too messy and not organized, but I am
not sure even how to make the list of values for interpolation because it
will be accumulated by loop and too big.
I have data of arrays such as:
[[1 3 5 1 . . 2] [9 3 6 1 . . 5] . . . [1 8 5 1 . . 7]]
[[2 2 3 7 . . 1] [10 2 5 3 . . 2] . . . [3 1 3 6 . . 11]]
.
.
[[7 10 15 11 . . 12] [4 7 1 3 . . 3] . . . [2 3 7 2 . . 1]]
I would like to get the value by interpolation between each set of arrays
in the same point. For example, the first values of the first array
(column) would be 1 2 ....7. In that series of numbers, I would like to
interpolate the value between 1 and 2, 2 and next number .... the previous
number and 7. The number of these array set would be 200 and I should be
extract those data array by using loop.
Such as:
for c in range(0,199):
w = wles[:,c,:,:]
th = Theta[:,c,:,:]
th_total = th + 300
w_mean = np.mean(w)
th_mean = np.mean(th_total)
wp = w - w_mean
thp = th_total - th_mean
mwtp = wp * thp
mwtp = list(mwtp)
mwtp1 = mwtp1 + [mwtp]
In that code, I would like to get values at each point in the array
between each loop for th by interpolation.
I am sorry that question itself is too messy and not organized, but I am
not sure even how to make the list of values for interpolation because it
will be accumulated by loop and too big.
C++ Operator precedence and the return statement
C++ Operator precedence and the return statement
If I do something like return a ? b : c; or return a && a2 && a3;
Could it ever be evaluated as just return a and then the function just
returns immediately before evaluating the rest?
If I do something like return a ? b : c; or return a && a2 && a3;
Could it ever be evaluated as just return a and then the function just
returns immediately before evaluating the rest?
How do you silently save an inspect object in R's tm package?
How do you silently save an inspect object in R's tm package?
When I save the inspect() object in R's tm package it prints to screen. It
does save the data that I want in the data.frame, but I have thousands of
documents to analyze and the printing to screen is eating up my memory.
library(tm)
data("crude")
matrix <- TermDocumentMatrix(corpus,control=list(removePunctuation = TRUE,
stopwords=TRUE))
out= data.frame(inspect(matrix))
I have tried every trick that I can think of. capture.output() changes the
object (not the desired effect), as does sink(). dev.off() does not work.
invisible() does nothing. suppressWarnings(), suppressMessages(), and
try() unsurprisingly do nothing. There are no silent or quiet options in
the inspect command.
The closest that I can get is
out= capture.output(inspect(matrix))
out= data.frame(out)
which notably does not give the same data.frame, but pretty easily could
be if I need to go down this route. Any other (less hacky) suggestions
would be helpful. Thanks.
Windows 7 64- bit R-3.0.1 tm package is the most recent version (0.5-9.1).
When I save the inspect() object in R's tm package it prints to screen. It
does save the data that I want in the data.frame, but I have thousands of
documents to analyze and the printing to screen is eating up my memory.
library(tm)
data("crude")
matrix <- TermDocumentMatrix(corpus,control=list(removePunctuation = TRUE,
stopwords=TRUE))
out= data.frame(inspect(matrix))
I have tried every trick that I can think of. capture.output() changes the
object (not the desired effect), as does sink(). dev.off() does not work.
invisible() does nothing. suppressWarnings(), suppressMessages(), and
try() unsurprisingly do nothing. There are no silent or quiet options in
the inspect command.
The closest that I can get is
out= capture.output(inspect(matrix))
out= data.frame(out)
which notably does not give the same data.frame, but pretty easily could
be if I need to go down this route. Any other (less hacky) suggestions
would be helpful. Thanks.
Windows 7 64- bit R-3.0.1 tm package is the most recent version (0.5-9.1).
Mute/Unmute Application Sounds
Mute/Unmute Application Sounds
How do I mute/unmute sounds in my application without touching the master
volume control of my computer when the the code I'm using is:
My.Computer.Audio.Play(My.Resources.audio_here, AudioPlayMode.Background)
How do I mute/unmute sounds in my application without touching the master
volume control of my computer when the the code I'm using is:
My.Computer.Audio.Play(My.Resources.audio_here, AudioPlayMode.Background)
Netty 4 OrderedMemoryAwareThreadPoolExecutor
Netty 4 OrderedMemoryAwareThreadPoolExecutor
I can not find the OrderedMemoryAwareThreadPoolExecutor in Netty 4.0.7.
I am writing a demo based on Netty 4.0.7's proxy example, I am doing a
file transfer from backend to frontend.
When my backend server send all the bytes to proxy, the server will FIN
the connection;
I found that when the speed of frontend network is slower than backend
network, the backend channelInActive() triggered before all the read event
of backend is processed, I can not find a way to make sure the close event
is always triggered after all the read event done.
I think the OrderedMemoryAwareThreadPoolExecutor in Netty 3.x maybe doing
this, but I can not find it in Netty 4, then how Netty 4 ensure the event
process order?
Thanks in advance
I can not find the OrderedMemoryAwareThreadPoolExecutor in Netty 4.0.7.
I am writing a demo based on Netty 4.0.7's proxy example, I am doing a
file transfer from backend to frontend.
When my backend server send all the bytes to proxy, the server will FIN
the connection;
I found that when the speed of frontend network is slower than backend
network, the backend channelInActive() triggered before all the read event
of backend is processed, I can not find a way to make sure the close event
is always triggered after all the read event done.
I think the OrderedMemoryAwareThreadPoolExecutor in Netty 3.x maybe doing
this, but I can not find it in Netty 4, then how Netty 4 ensure the event
process order?
Thanks in advance
Push Notification issue in PHP
Push Notification issue in PHP
I am using Apple push notification in my PHP project. It works fine when I
use static device token(static string) to send notification to multiple
devices but when I am fetching it from DB it doesn't sends notification
but I shows success delivery of message. When I compared the the value
coming from DB and my static values they are same. Please help me.
Thanks
Here is my code snippets
while($resultRow = mysql_fetch_object($subscriberResult))
{
if($resultRow->device_type =='android')
{
$gcm = new GCM();
$registatoin_ids = array($resultRow->device_id);
$message = array("message" => $msgText);
$result = $gcm->send_notification($registatoin_ids, $message);//send
notification on andoroid
}
elseif($resultRow->device_type =='ios')
{
// Put your device token here (without spaces):
$deviceToken = $resultRow->device_id;
//$deviceToken =
'eb4085335d91d0ae07a2736dd0fc0ccb095486a1d54bf9addc75785f427fea91';
// Put your private key's passphrase here:
$passphrase = 'pushchat';
// Put your alert message here:
$message = $msgText;
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert',
'server_certificates_bundle_sandbox.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
stream_context_set_option($ctx, 'ssl', 'cafile', 'entrust_2048_ca.cer');
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
//echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n',
strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
echo $result."</br>";
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
}
}
// Close the connection to the server if $fp defined
if($fp) {
fclose($fp);
}
I am using Apple push notification in my PHP project. It works fine when I
use static device token(static string) to send notification to multiple
devices but when I am fetching it from DB it doesn't sends notification
but I shows success delivery of message. When I compared the the value
coming from DB and my static values they are same. Please help me.
Thanks
Here is my code snippets
while($resultRow = mysql_fetch_object($subscriberResult))
{
if($resultRow->device_type =='android')
{
$gcm = new GCM();
$registatoin_ids = array($resultRow->device_id);
$message = array("message" => $msgText);
$result = $gcm->send_notification($registatoin_ids, $message);//send
notification on andoroid
}
elseif($resultRow->device_type =='ios')
{
// Put your device token here (without spaces):
$deviceToken = $resultRow->device_id;
//$deviceToken =
'eb4085335d91d0ae07a2736dd0fc0ccb095486a1d54bf9addc75785f427fea91';
// Put your private key's passphrase here:
$passphrase = 'pushchat';
// Put your alert message here:
$message = $msgText;
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert',
'server_certificates_bundle_sandbox.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
stream_context_set_option($ctx, 'ssl', 'cafile', 'entrust_2048_ca.cer');
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
//echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n',
strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
echo $result."</br>";
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
}
}
// Close the connection to the server if $fp defined
if($fp) {
fclose($fp);
}
Tuesday, 10 September 2013
Access parent's members when extending android.widget.xxx
Access parent's members when extending android.widget.xxx
I'm writing a custom gridview this way:
public class MyGridView extends GridView {
....
Is there any way to access package-private members(methods), or I have to
write a huge bunch of reflection code?
I'm writing a custom gridview this way:
public class MyGridView extends GridView {
....
Is there any way to access package-private members(methods), or I have to
write a huge bunch of reflection code?
Insert data from uploaded Excel document to database using ASP.net (Vb.net)
Insert data from uploaded Excel document to database using ASP.net (Vb.net)
Im working on a web application, I want to Know if there is a possibility
to insert the data fields information of an Excel file into my SqlServer
database after uploading it, using Asp.net(VB.net) ??
Thank's
Im working on a web application, I want to Know if there is a possibility
to insert the data fields information of an Excel file into my SqlServer
database after uploading it, using Asp.net(VB.net) ??
Thank's
UILabel Multiple Lines
UILabel Multiple Lines
I have a UILable which displays text as I press buttons. The text is from
an attributed string. One of the buttons calls for a superscript
attribute:
string = [[NSMutableAttributedString alloc]initWithString:@"A"];
[string addAttribute:NSFontAttributeName value:(font)
range:NSMakeRange(string.length-1, 1)];
[string addAttribute:(NSString*)kCTSuperscriptAttributeName value:@"1"
range:NSMakeRange(string.length-1, 1)];
[string2 appendSttributedString: string];
label.attributedText = string2;
This code works as long as string2 fits onto one line in the UILable. When
the text begins to span two lines at first it appears as it should.
However when the kCTSuperscriptAttributeName superscript attribute is
added the second line of the label disappears and gets truncated. Im not
sure whats going on. Anyone have an idea?
I have a UILable which displays text as I press buttons. The text is from
an attributed string. One of the buttons calls for a superscript
attribute:
string = [[NSMutableAttributedString alloc]initWithString:@"A"];
[string addAttribute:NSFontAttributeName value:(font)
range:NSMakeRange(string.length-1, 1)];
[string addAttribute:(NSString*)kCTSuperscriptAttributeName value:@"1"
range:NSMakeRange(string.length-1, 1)];
[string2 appendSttributedString: string];
label.attributedText = string2;
This code works as long as string2 fits onto one line in the UILable. When
the text begins to span two lines at first it appears as it should.
However when the kCTSuperscriptAttributeName superscript attribute is
added the second line of the label disappears and gets truncated. Im not
sure whats going on. Anyone have an idea?
Working with classes Visual C++ 2010
Working with classes Visual C++ 2010
I'm new to VC++ and I'm trying to work with classes. My subroutine worked
fine as straight code, but I Keep getting errors when I try using it in a
class Here is the code for the header file.
[using namespace std;
#ifndef Deck_h
#define Deck_h
class Deck
{
public:
// Default constructor
Deck();
//Destructor
~Deck();
// access functions
//function1
// Member variables
int InDeck[53];
int OutDeck[53];
};
I'm new to VC++ and I'm trying to work with classes. My subroutine worked
fine as straight code, but I Keep getting errors when I try using it in a
class Here is the code for the header file.
[using namespace std;
#ifndef Deck_h
#define Deck_h
class Deck
{
public:
// Default constructor
Deck();
//Destructor
~Deck();
// access functions
//function1
// Member variables
int InDeck[53];
int OutDeck[53];
};
Import 3D models to Android/iOS
Import 3D models to Android/iOS
In which tool should i design my 3D models, so that it would be easy to
import in Android/iOS application.
I thought of using SketchUp and exporting models as collada files and
parsing that file to get opengl vertices and then render them in my apps.
My question is can i do the same in the blender also. And is there any
better way to render the models.
In which tool should i design my 3D models, so that it would be easy to
import in Android/iOS application.
I thought of using SketchUp and exporting models as collada files and
parsing that file to get opengl vertices and then render them in my apps.
My question is can i do the same in the blender also. And is there any
better way to render the models.
How to select the title with the latest datetime?
How to select the title with the latest datetime?
I have these two tables in mysql:
posts (id)
post_titles (id, post_id, title, datetime, user_id)
post_contents (id, post_id, content, datetime, user_id)
posts (id) == posts_titles (post_id)
In the post_titles and post_contents can be multiple entries for 1 posts
(id).
What i need, is to select the title which has the latest datetime. I would
have to select it all by using the posts (id). How could i do that?
EDIT: i need to select the title and the content together.
I have these two tables in mysql:
posts (id)
post_titles (id, post_id, title, datetime, user_id)
post_contents (id, post_id, content, datetime, user_id)
posts (id) == posts_titles (post_id)
In the post_titles and post_contents can be multiple entries for 1 posts
(id).
What i need, is to select the title which has the latest datetime. I would
have to select it all by using the posts (id). How could i do that?
EDIT: i need to select the title and the content together.
Catching fatal PHP errors and throwing an exception
Catching fatal PHP errors and throwing an exception
The entry point (front controller) for our software is wrapped in a try
catch block which catches exceptions and then includes a PHP file to show
a friendly error page, as well as emailing us about the exception. This
work perfectly, however it misses PHP fatal errors which just show a HTTP
500 response. I'm trying to catch those errors in the same way as
exceptions.
At the moment, we have this in the application's entry point:
try {
// Register a shutdown handler for fatal errors
register_shutdown_function(function() {
$error = error_get_last();
// Did this request throw an error that wasn't handled?
if ($error !== null) {
throw new Exception('PHP fatal error!');
}
});
// ...normal front controller stuff
} catch (Exception $e) {
// show fancy error screen with debug information
include 'themes/error/500.php';
}
Here, I'm throwing an exception when PHP throws a fatal error in the hopes
that it gets handled by the normal exception handling procedure. However,
the exception never gets caught:
Fatal error: Uncaught exception 'Exception' with message 'PHP fatal error!'
How can I achieve what I want to do here?
The entry point (front controller) for our software is wrapped in a try
catch block which catches exceptions and then includes a PHP file to show
a friendly error page, as well as emailing us about the exception. This
work perfectly, however it misses PHP fatal errors which just show a HTTP
500 response. I'm trying to catch those errors in the same way as
exceptions.
At the moment, we have this in the application's entry point:
try {
// Register a shutdown handler for fatal errors
register_shutdown_function(function() {
$error = error_get_last();
// Did this request throw an error that wasn't handled?
if ($error !== null) {
throw new Exception('PHP fatal error!');
}
});
// ...normal front controller stuff
} catch (Exception $e) {
// show fancy error screen with debug information
include 'themes/error/500.php';
}
Here, I'm throwing an exception when PHP throws a fatal error in the hopes
that it gets handled by the normal exception handling procedure. However,
the exception never gets caught:
Fatal error: Uncaught exception 'Exception' with message 'PHP fatal error!'
How can I achieve what I want to do here?
Python Tkinter: Embed a matplotlib plot in a widget
Python Tkinter: Embed a matplotlib plot in a widget
I have already search for this, for example Python Tkinter Embed
Matplotlib in GUI but still can't figure it out. Basically i am trying to
plot a fancy graph for a player abilities for a basketball game inside the
player window made up with tkinter
self.fig = Figure(figsize=(1.5,1.5))
self.ax = self.fig.add_axes([0.025,0.025,0.95,0.95],polar=True)
self.plot_widget = FigureCanvasTkAgg(self.fig, master=self.top)
self.ax.grid(False)
N = 5
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii =
[self.thisPlayer.rebounds,self.thisPlayer.freeThrows,self.thisPlayer.steal,self.thisPlayer.underRim,self.thisPlayer.distance]
width = [2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N)]
bars = pl.bar(0 , 20,width=2*np.pi, linewidth = 0) + pl.bar(theta,
radii, width=width, bottom=0.2)
for r,bar in zip(radii, bars):
bar.set_facecolor( cm.jet(r/20.))
bar.set_alpha(0.5)
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
self.plot_widget.show()
self.plot_widget.get_tk_widget().pack()
what happens is that the player window has now the plot widget but the
plot is not shown. On the other side, just plotting the abilities not
embedded in tkinter works fine. Sorry for my english. thanks in advance
I have already search for this, for example Python Tkinter Embed
Matplotlib in GUI but still can't figure it out. Basically i am trying to
plot a fancy graph for a player abilities for a basketball game inside the
player window made up with tkinter
self.fig = Figure(figsize=(1.5,1.5))
self.ax = self.fig.add_axes([0.025,0.025,0.95,0.95],polar=True)
self.plot_widget = FigureCanvasTkAgg(self.fig, master=self.top)
self.ax.grid(False)
N = 5
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii =
[self.thisPlayer.rebounds,self.thisPlayer.freeThrows,self.thisPlayer.steal,self.thisPlayer.underRim,self.thisPlayer.distance]
width = [2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N)]
bars = pl.bar(0 , 20,width=2*np.pi, linewidth = 0) + pl.bar(theta,
radii, width=width, bottom=0.2)
for r,bar in zip(radii, bars):
bar.set_facecolor( cm.jet(r/20.))
bar.set_alpha(0.5)
self.ax.set_xticklabels([])
self.ax.set_yticklabels([])
self.plot_widget.show()
self.plot_widget.get_tk_widget().pack()
what happens is that the player window has now the plot widget but the
plot is not shown. On the other side, just plotting the abilities not
embedded in tkinter works fine. Sorry for my english. thanks in advance
How can I process Unacknowledged messages in Activemq
How can I process Unacknowledged messages in Activemq
I wrote a class in Java name as ExternalFileProcess.java for processing
externalFile(.exe). I have written one more class name as MyListener for
processing messages in Activemq.
Whenever JMS Provider(Activemq) gets the messages, subscriber needs to run
External(.EXE) file.For this I called ExternalFileProcess.java in
MyListener.It's working fine.
Now I am trying to implement error handling. Assume If external(.EXE) file
process is crashed because of some reasons, I want to resend processing
message to JMS Provider(Activemq).
If I resend processing message from MyListener to Activemq, I will process
that message again and never lose any message.
if (Whether process is successfully done or not) {
//process completed sucessfully
msg.acknowledge();
}else {
//Process Not completely done
Here I want to resend the message to Activemq. If I resend
messages,Activemq deliver that message to
Subscriber(MessageListener) so I can process that message one more
time.
}
Thanks.
I wrote a class in Java name as ExternalFileProcess.java for processing
externalFile(.exe). I have written one more class name as MyListener for
processing messages in Activemq.
Whenever JMS Provider(Activemq) gets the messages, subscriber needs to run
External(.EXE) file.For this I called ExternalFileProcess.java in
MyListener.It's working fine.
Now I am trying to implement error handling. Assume If external(.EXE) file
process is crashed because of some reasons, I want to resend processing
message to JMS Provider(Activemq).
If I resend processing message from MyListener to Activemq, I will process
that message again and never lose any message.
if (Whether process is successfully done or not) {
//process completed sucessfully
msg.acknowledge();
}else {
//Process Not completely done
Here I want to resend the message to Activemq. If I resend
messages,Activemq deliver that message to
Subscriber(MessageListener) so I can process that message one more
time.
}
Thanks.
Subscribe to:
Comments (Atom)