wsimport or likewise in android?
For my work I need to generate a proxy from a wsdl file. I used wsimport
successfully, only it doesn't work on android for some reasons such as
using the java - javax package name and maybe more.
My question is can I somehow make it work? did anyone successfully used
wsimport outputs in an android project?
Saturday, 31 August 2013
Should I throw an exception or print out an error statement in a program?
Should I throw an exception or print out an error statement in a program?
I have my program working and all done (java). It's a short and easy
program for a job interview. I handle stuff like improper input format by
throwing a custom exception. Is that the best way to do it or should I
just make a print statement?
I have my program working and all done (java). It's a short and easy
program for a job interview. I handle stuff like improper input format by
throwing a custom exception. Is that the best way to do it or should I
just make a print statement?
Spring + Hibernate Not able to address issue
Spring + Hibernate Not able to address issue
i am using spring 3.2.4 (latest stable version) with hibernate i have
added all the dependencies but still i am getting the error which is below
java.lang.NoClassDefFoundError:
org/springframework/transaction/interceptor/TransactionInterceptor
if i use maven then i get too many errors like Failed to Autowired (in
both service and DAO),
org.springframework.beans.factory.BeanCreationException:
java.lang.ClassNotFoundException: org.hibernate.cache.CacheProvider
please help me to solve problem for one of above. i want to create an
application (spring + Hibernate) any of way (with maven or without maven)
i am using spring 3.2.4 (latest stable version) with hibernate i have
added all the dependencies but still i am getting the error which is below
java.lang.NoClassDefFoundError:
org/springframework/transaction/interceptor/TransactionInterceptor
if i use maven then i get too many errors like Failed to Autowired (in
both service and DAO),
org.springframework.beans.factory.BeanCreationException:
java.lang.ClassNotFoundException: org.hibernate.cache.CacheProvider
please help me to solve problem for one of above. i want to create an
application (spring + Hibernate) any of way (with maven or without maven)
twisted: test my service's stop sequence
twisted: test my service's stop sequence
We have a complex multiservice that needs to do some fairly intricate
accounting when shutting down in order to implement a "graceful" shutdown.
I'm trying to write tests for this under trial. The issue is that the
reactor is effectively a process-global resource, and shutting down my
service means that trial's reactor is also stopped, which (of course)
makes it explode.
This is documented to be a no-no in trial, but I need some kind of
workaround that allows me to write my tests. My first thought was to use a
mock.Mock, but this means we're not really using a reactor that's shutting
down, which isn't going to give me behavior that's faithful to the actual
shutdown process.
I believe what I need is a way to separate trial's reactor from the
reactor of my service-under-test. Sharing a mutable resource between the
test system and the system under test is surely an anti-pattern.
We have a complex multiservice that needs to do some fairly intricate
accounting when shutting down in order to implement a "graceful" shutdown.
I'm trying to write tests for this under trial. The issue is that the
reactor is effectively a process-global resource, and shutting down my
service means that trial's reactor is also stopped, which (of course)
makes it explode.
This is documented to be a no-no in trial, but I need some kind of
workaround that allows me to write my tests. My first thought was to use a
mock.Mock, but this means we're not really using a reactor that's shutting
down, which isn't going to give me behavior that's faithful to the actual
shutdown process.
I believe what I need is a way to separate trial's reactor from the
reactor of my service-under-test. Sharing a mutable resource between the
test system and the system under test is surely an anti-pattern.
Relational division - SQL
Relational division - SQL
I have 3 tables.
Owner(owner_id, name)
House(code, owner_id, price)
Buyer(buyer_id, name)
Bought(buyer_id, code, price_bought, date_bought)
I have the following query:
List the names of the buyers that bought all the houses from some owner?
I know how to find if someone bought all the houses from a particular
owner (say owner with id = 1):
SELECT name
FROM buyer
WHERE NOT EXISTS (SELECT code
FROM house
WHERE owner_id = 1
AND code NOT IN (SELECT code
FROM bought
WHERE bought.buyer_id=
buyer.buyer_id))
How can I make this work for all owners?
I have 3 tables.
Owner(owner_id, name)
House(code, owner_id, price)
Buyer(buyer_id, name)
Bought(buyer_id, code, price_bought, date_bought)
I have the following query:
List the names of the buyers that bought all the houses from some owner?
I know how to find if someone bought all the houses from a particular
owner (say owner with id = 1):
SELECT name
FROM buyer
WHERE NOT EXISTS (SELECT code
FROM house
WHERE owner_id = 1
AND code NOT IN (SELECT code
FROM bought
WHERE bought.buyer_id=
buyer.buyer_id))
How can I make this work for all owners?
Simple bit setting and cleaning
Simple bit setting and cleaning
I'm coding an exercise from a book. This program should set a "bitmapped
graphics device" bits, and then check for any of them if they are 1 or 0.
The setting function was already written so I only wrote the test_bit
function, but it doesn't work. In the main() I set the first byte's first
bit to 1, so the byte is 10000000, then I want to test it: 1000000 &
10000000 == 10000000, so not null, but I still get false when I want to
print it out. What's wrong?
#include <iostream>
const int X_SIZE = 32;
const int Y_SIZE = 24;
char graphics[X_SIZE / 8][Y_SIZE];
inline void set_bit(const int x, const int y)
{
graphics[(x)/8][y] |= (0x80 >> ((x)%8));
}
inline bool test_bit(const int x, const int y)
{
if(graphics[x/8][y] & (0.80 >> ((x)%8)) != 0)
return true;
else return false;
}
void print_graphics(void) //this function simulate the bitmapped graphics
device
{
int x;
int y;
int bit;
for(y=0; y < Y_SIZE; y++)
{
for(x = 0; x < X_SIZE / 8; x++)
{
for(bit = 0x80;bit > 0; bit = (bit >> 1))
{
if((graphics[x][y] & bit) != 0)
std::cout << 'X';
else
std::cout << '.';
}
}
std::cout << '\n';
}
}
main()
{
int loc;
for (loc = 0; loc < X_SIZE; loc++)
{
set_bit(loc,loc);
}
print_graphics();
std::cout << "Bit(0,0): " << test_bit(0,0) << std::endl;
return 0;
}
I'm coding an exercise from a book. This program should set a "bitmapped
graphics device" bits, and then check for any of them if they are 1 or 0.
The setting function was already written so I only wrote the test_bit
function, but it doesn't work. In the main() I set the first byte's first
bit to 1, so the byte is 10000000, then I want to test it: 1000000 &
10000000 == 10000000, so not null, but I still get false when I want to
print it out. What's wrong?
#include <iostream>
const int X_SIZE = 32;
const int Y_SIZE = 24;
char graphics[X_SIZE / 8][Y_SIZE];
inline void set_bit(const int x, const int y)
{
graphics[(x)/8][y] |= (0x80 >> ((x)%8));
}
inline bool test_bit(const int x, const int y)
{
if(graphics[x/8][y] & (0.80 >> ((x)%8)) != 0)
return true;
else return false;
}
void print_graphics(void) //this function simulate the bitmapped graphics
device
{
int x;
int y;
int bit;
for(y=0; y < Y_SIZE; y++)
{
for(x = 0; x < X_SIZE / 8; x++)
{
for(bit = 0x80;bit > 0; bit = (bit >> 1))
{
if((graphics[x][y] & bit) != 0)
std::cout << 'X';
else
std::cout << '.';
}
}
std::cout << '\n';
}
}
main()
{
int loc;
for (loc = 0; loc < X_SIZE; loc++)
{
set_bit(loc,loc);
}
print_graphics();
std::cout << "Bit(0,0): " << test_bit(0,0) << std::endl;
return 0;
}
Trying to make a periodic table
Trying to make a periodic table
I have a file called "periodic_table". Inside this file is multiple lines.
Each line has an atomic number on the side and a corresponding element
name on the right like this:
1 Hydrogen
2 Helium
3 Lithium
4 Beryllium
5 Boron
6 Carbon
7 Nitrogen
8 Oxygen
9 Fluorine
10 Neon
11 Sodium
12 Magnesium
13 Aluminium
14 Silicon
etc...
I made a program that asks for either the element name or number, and
prints out the corresponding value in the dictionary. If the user inputs 1
it will print Hydrogen, similarly if the user inputs Silicon it will
output 14. HOWEVER - I want the program to inform the user if he enters a
non existent atomic number (such as 150) or a non existent element (such
as Blanket or any other string). Tried using an if but it printed out an
infinite loop.
element_list = {}
name = input("Enter element number or element name: ")
while name:
with open("periodic_table.txt") as f:
for line in f:
(key, val) = line.split()
element_list[int(key)] = val
if name == key:
print(val)
elif name == val:
print(key)
name = input("Enter element number or element name: ")
Thanks in advance fellas!
I have a file called "periodic_table". Inside this file is multiple lines.
Each line has an atomic number on the side and a corresponding element
name on the right like this:
1 Hydrogen
2 Helium
3 Lithium
4 Beryllium
5 Boron
6 Carbon
7 Nitrogen
8 Oxygen
9 Fluorine
10 Neon
11 Sodium
12 Magnesium
13 Aluminium
14 Silicon
etc...
I made a program that asks for either the element name or number, and
prints out the corresponding value in the dictionary. If the user inputs 1
it will print Hydrogen, similarly if the user inputs Silicon it will
output 14. HOWEVER - I want the program to inform the user if he enters a
non existent atomic number (such as 150) or a non existent element (such
as Blanket or any other string). Tried using an if but it printed out an
infinite loop.
element_list = {}
name = input("Enter element number or element name: ")
while name:
with open("periodic_table.txt") as f:
for line in f:
(key, val) = line.split()
element_list[int(key)] = val
if name == key:
print(val)
elif name == val:
print(key)
name = input("Enter element number or element name: ")
Thanks in advance fellas!
Friday, 30 August 2013
RegEx pattern to match between nth and mth occurence of a word
RegEx pattern to match between nth and mth occurence of a word
I have some example String like :
There is one wherever you one and here is the one , nowhere is the one .
I want to extract between the second one and the third one , that is, and
here is the
I am not sure how to position my patterns accordingly .. Can any one help ?
I have some example String like :
There is one wherever you one and here is the one , nowhere is the one .
I want to extract between the second one and the third one , that is, and
here is the
I am not sure how to position my patterns accordingly .. Can any one help ?
cocos2dx working with files
cocos2dx working with files
my game engine is cocos2dx 3.0 and I want to know how to read information
about players from file (and how to write it). What is the best
cross-platform solution to do it? I know that there are such classes as
FileUtils, UserDefault, but I believe that there is a better way to work
with files. P.S. I will not use cocos2dx 2, 3.0 only.
my game engine is cocos2dx 3.0 and I want to know how to read information
about players from file (and how to write it). What is the best
cross-platform solution to do it? I know that there are such classes as
FileUtils, UserDefault, but I believe that there is a better way to work
with files. P.S. I will not use cocos2dx 2, 3.0 only.
Thursday, 29 August 2013
Multiple TestInitialize attributes in MSTEST
Multiple TestInitialize attributes in MSTEST
Using MSTEST in VS2012.3 .NET4.5 and R# for the test runner.
The code below works in the order 1,2,3,4.
However I'm concerned that it may not always execute in this order as
multiple TestInitialize attributes are not supported MSDN
Question: Is this allowed, and do the docs just mean that multiple
TestInitialize attributes are not allowed in the same class?
I would like to keep this structure as have many integration tests
inheriting off TransactedTestBase, yet requiring different SQL scripts to
setup.
[TestClass]
public class DelegationTest : TransactedTestBase
{
[TestInitialize]
public void Setup()
{
Console.WriteLine("2 Setup");
//var script = "INSERT INTO blah...";
//var sqlConnect = new SqlConnection(dbConnection.ConnectionString);
//sqlConnect.Open();
//var server = new Server(sqlConnect);
//var database = server.Databases[sqlConnect.Database];
//database.ExecuteNonQuery(script);
}
[TestMethod]
public void TestMethod1()
{
Console.WriteLine("3 Test Method");
}
}
[TestClass]
public class TransactedTestBase
{
//protected userEntities userEntities;
//private TransactionScope scope;
//public static SqlDatabase dbConnection;
//private const bool ShouldWriteToDB = true;
//private const bool ShouldWriteToDB = false;
[TestInitialize()]
public virtual void TestStart()
{
Console.WriteLine("1 TestStart");
//if (ShouldWriteToDB)
//{
// dbConnection =
EnterpriseLibraryContainer.Current.GetInstance<SqlDatabase>("DBConnect");
// return;
//}
//scope = new TransactionScope(TransactionScopeOption.RequiresNew);
//user = new userEntities();
//dbConnection =
EnterpriseLibraryContainer.Current.GetInstance<SqlDatabase>("DBConnect");
}
[TestCleanup()]
public virtual void TestEnd()
{
Console.WriteLine("4 TestEnd");
//if (ShouldWriteToDB) return;
//scope.Dispose();
}
}
Using MSTEST in VS2012.3 .NET4.5 and R# for the test runner.
The code below works in the order 1,2,3,4.
However I'm concerned that it may not always execute in this order as
multiple TestInitialize attributes are not supported MSDN
Question: Is this allowed, and do the docs just mean that multiple
TestInitialize attributes are not allowed in the same class?
I would like to keep this structure as have many integration tests
inheriting off TransactedTestBase, yet requiring different SQL scripts to
setup.
[TestClass]
public class DelegationTest : TransactedTestBase
{
[TestInitialize]
public void Setup()
{
Console.WriteLine("2 Setup");
//var script = "INSERT INTO blah...";
//var sqlConnect = new SqlConnection(dbConnection.ConnectionString);
//sqlConnect.Open();
//var server = new Server(sqlConnect);
//var database = server.Databases[sqlConnect.Database];
//database.ExecuteNonQuery(script);
}
[TestMethod]
public void TestMethod1()
{
Console.WriteLine("3 Test Method");
}
}
[TestClass]
public class TransactedTestBase
{
//protected userEntities userEntities;
//private TransactionScope scope;
//public static SqlDatabase dbConnection;
//private const bool ShouldWriteToDB = true;
//private const bool ShouldWriteToDB = false;
[TestInitialize()]
public virtual void TestStart()
{
Console.WriteLine("1 TestStart");
//if (ShouldWriteToDB)
//{
// dbConnection =
EnterpriseLibraryContainer.Current.GetInstance<SqlDatabase>("DBConnect");
// return;
//}
//scope = new TransactionScope(TransactionScopeOption.RequiresNew);
//user = new userEntities();
//dbConnection =
EnterpriseLibraryContainer.Current.GetInstance<SqlDatabase>("DBConnect");
}
[TestCleanup()]
public virtual void TestEnd()
{
Console.WriteLine("4 TestEnd");
//if (ShouldWriteToDB) return;
//scope.Dispose();
}
}
How to display the children under the parent of an xmll file using jquery ?
How to display the children under the parent of an xmll file using jquery ?
I want to display the children tags in a listview. In that listview i'm
adding the parent tag as a list-divider.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<page count="89" name="Sample">
<sections>
<section count="3" name="Alphabets" order="1">
<content file="220993.txt" order="1">A</content>
<content file="220994.txt" order="2">B</content>
<content file="220995.txt" order="3">C</content>
</section>
<section count="5" name="Numbers" order="2">
<content file="221006.txt" order="4">five</content>
<content file="221007.txt" order="5">four</content>
<content file="221008.txt" order="6">three</content>
<content file="221009.txt" order="7">two</content>
<content file="221010.txt" order="8">one</content>
</section>
<section count="2" name="Names" order="3">
<content file="221013.txt" order="9">Sam</content>
<content file="221014.txt" order="10">Sansha</content>
</section>
</sections>
</page>
Code:
$(xml).find('section').each(function () {
var section = $(this).attr("name");
var count = $(this).attr('count');
var order = $(this).attr('order');
$(this).children().each(function () {
var content = $(this).text();
var order = $(this).attr("order");
var seq = order + '' + $(this).attr('order');
$("#section_list").append('<li
data-role="list-divider">' + section + '</li>');
$("#section_list").append('<li><a href=""
class="style1" data-sequence="s' + seq + '" ><h2>'
+ content + ' </h2></a></li>');
$("#section_list").listview('refresh');
});
});
If i'm doing like this parent tag is repeating for every children.
Thanks in Advance.
I want to display the children tags in a listview. In that listview i'm
adding the parent tag as a list-divider.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<page count="89" name="Sample">
<sections>
<section count="3" name="Alphabets" order="1">
<content file="220993.txt" order="1">A</content>
<content file="220994.txt" order="2">B</content>
<content file="220995.txt" order="3">C</content>
</section>
<section count="5" name="Numbers" order="2">
<content file="221006.txt" order="4">five</content>
<content file="221007.txt" order="5">four</content>
<content file="221008.txt" order="6">three</content>
<content file="221009.txt" order="7">two</content>
<content file="221010.txt" order="8">one</content>
</section>
<section count="2" name="Names" order="3">
<content file="221013.txt" order="9">Sam</content>
<content file="221014.txt" order="10">Sansha</content>
</section>
</sections>
</page>
Code:
$(xml).find('section').each(function () {
var section = $(this).attr("name");
var count = $(this).attr('count');
var order = $(this).attr('order');
$(this).children().each(function () {
var content = $(this).text();
var order = $(this).attr("order");
var seq = order + '' + $(this).attr('order');
$("#section_list").append('<li
data-role="list-divider">' + section + '</li>');
$("#section_list").append('<li><a href=""
class="style1" data-sequence="s' + seq + '" ><h2>'
+ content + ' </h2></a></li>');
$("#section_list").listview('refresh');
});
});
If i'm doing like this parent tag is repeating for every children.
Thanks in Advance.
Wednesday, 28 August 2013
android: where is the android.provider.Telephony.SMS_RECEIVED?
android: where is the android.provider.Telephony.SMS_RECEIVED?
I'm writing an App that needs to receive sms, everyone use
"android.provider.Telephony.SMS_RECEIVED" intent action in their code, but
it looks like API level 17 doesn't support it anymore! where it is now? I
didn't found it in "android.telephony" class too! please someone tell me,
I'm totally confused. should I use older APIs?
I'm writing an App that needs to receive sms, everyone use
"android.provider.Telephony.SMS_RECEIVED" intent action in their code, but
it looks like API level 17 doesn't support it anymore! where it is now? I
didn't found it in "android.telephony" class too! please someone tell me,
I'm totally confused. should I use older APIs?
T-SQL - query filtering
T-SQL - query filtering
table1:
Id Customer No_
7044900804 Z0172132
7044900804 Z0194585
7044907735 Z0172222
7044907735 Z0172222
7044910337 Z0172216
7044911903 Z0117392
I would like to get only the values with the same Id AND different
Customer No_ from table1.
Id Customer No_
7044900804 Z0172132
7044900804 Z0194585
I've already tried to use query for finding duplicates, but it won't
filter values with the same Id AND same Customer No_ from table1.
SELECT Id
, [Customer No_]
FROM table1
GROUP BY Id, [Customer No_]
HAVING COUNT(*) > 1
Could you help me with T-SQL query solution? Thanks for all the advices.
table1:
Id Customer No_
7044900804 Z0172132
7044900804 Z0194585
7044907735 Z0172222
7044907735 Z0172222
7044910337 Z0172216
7044911903 Z0117392
I would like to get only the values with the same Id AND different
Customer No_ from table1.
Id Customer No_
7044900804 Z0172132
7044900804 Z0194585
I've already tried to use query for finding duplicates, but it won't
filter values with the same Id AND same Customer No_ from table1.
SELECT Id
, [Customer No_]
FROM table1
GROUP BY Id, [Customer No_]
HAVING COUNT(*) > 1
Could you help me with T-SQL query solution? Thanks for all the advices.
How to assign html title from variable with vbscript?
How to assign html title from variable with vbscript?
I'm currently trying to get a modal window to set my html <title> from a
vbscript function like this:
<title> <%foo.bar%> </title>
where foo.bar
Function bar() as string
bar = "some text"
end function
This gives no success.
I also tried the below snippets, but without success. It throws "An
unhandled exception" for incompatible types.
<%@Language=VBScript%>
<% barVar = "fooFoo" %>
<title><%barVar%></title>
Does anyone know what possibly could be the problem here? Thanks for reading.
I'm currently trying to get a modal window to set my html <title> from a
vbscript function like this:
<title> <%foo.bar%> </title>
where foo.bar
Function bar() as string
bar = "some text"
end function
This gives no success.
I also tried the below snippets, but without success. It throws "An
unhandled exception" for incompatible types.
<%@Language=VBScript%>
<% barVar = "fooFoo" %>
<title><%barVar%></title>
Does anyone know what possibly could be the problem here? Thanks for reading.
Tuesday, 27 August 2013
DateTime input format?
DateTime input format?
there's something I can't quite get my head around. Just hoping someone
could please help.
I've a WPF TextBox that is bound to a DateTime property, as follows;
<TextBox Text="{Binding DOB, StringFormat='{}{0:dd/MM/yyyy}'}" />
If I enter the text '01/30/2013' it correctly converts and displays it as
'30/01/2013'. If I enter the text '30/01/2013' it throws a validation
error, as it expects the INPUT to be in the format MM/dd/YYYY.
How can I change the input format? I realise I can write a custom
converter. I was just wondering if there was another way?
thanks
there's something I can't quite get my head around. Just hoping someone
could please help.
I've a WPF TextBox that is bound to a DateTime property, as follows;
<TextBox Text="{Binding DOB, StringFormat='{}{0:dd/MM/yyyy}'}" />
If I enter the text '01/30/2013' it correctly converts and displays it as
'30/01/2013'. If I enter the text '30/01/2013' it throws a validation
error, as it expects the INPUT to be in the format MM/dd/YYYY.
How can I change the input format? I realise I can write a custom
converter. I was just wondering if there was another way?
thanks
Django: making {% block "div" %} conditional with a conditional {% extends %}
Django: making {% block "div" %} conditional with a conditional {% extends %}
I would like to share a template between AJAX and regualr HTTP calls, the
only difference is that one template needs to extend base.html html, while
the other dose not.
I can use
{% extends request.is_ajax|yesno:"app/base_ajax.html,app/base.html" %}
To dynamically decide when to extend, but I also need to include {% block
'some_div' %}{% endbock %} tags to tell the renderer where to put my
content. The ajax call needs those tags to be left out because jQuery
tells it where to put the content with $('somediv').html(response).
Any idea on how to dynamically include those block tags when its not an
ajax call?
I've been referencing this question to figure it out:
Any way to make {% extends '...' %} conditional? - Django
Attempt to make it work through an {% if %}:
{% extends request.is_ajax|yesno:",stamped/home.html" %}
{% if request.is_ajax == False%}
{% block results %}
{% endif %}
{% load stamped_custom_tags %}
...
Content
...
{% if request.is_ajax == False%}
{% endblock %}
{% endif %}
but this fails when parser runs into the {% endif %}
I would like to share a template between AJAX and regualr HTTP calls, the
only difference is that one template needs to extend base.html html, while
the other dose not.
I can use
{% extends request.is_ajax|yesno:"app/base_ajax.html,app/base.html" %}
To dynamically decide when to extend, but I also need to include {% block
'some_div' %}{% endbock %} tags to tell the renderer where to put my
content. The ajax call needs those tags to be left out because jQuery
tells it where to put the content with $('somediv').html(response).
Any idea on how to dynamically include those block tags when its not an
ajax call?
I've been referencing this question to figure it out:
Any way to make {% extends '...' %} conditional? - Django
Attempt to make it work through an {% if %}:
{% extends request.is_ajax|yesno:",stamped/home.html" %}
{% if request.is_ajax == False%}
{% block results %}
{% endif %}
{% load stamped_custom_tags %}
...
Content
...
{% if request.is_ajax == False%}
{% endblock %}
{% endif %}
but this fails when parser runs into the {% endif %}
Working with slices of structs concurrently using references
Working with slices of structs concurrently using references
I have a JSON I need to do some processing on. It uses a slice that I need
to reference in some way for the Room-struct to be modified at the end of
the function. How can I work with this struct concurrently in a by
reference type of way?
http://play.golang.org/p/wRhd1sDqtb
type Window struct {
Height int64 `json:"Height"`
Width int64 `json:"Width"`
}
type Room struct {
Windows []Window `json:"Windows"`
}
func main() {
js :=
[]byte(`{"Windows":[{"Height":10,"Width":20},{"Height":10,"Width":20}]}`)
fmt.Printf("Should have 2 windows: %v\n", string(js))
var room Room
_ = json.Unmarshal(js, &room)
var wg sync.WaitGroup
// Add meny windows to room
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
addWindow(room.Windows)
}()
}
wg.Wait()
js, _ = json.Marshal(room)
fmt.Printf("Sould have 12 windows: %v\n", string(js))
}
func addWindow(windows []Window) {
window := Window{1, 1}
fmt.Printf("Adding %v to %v\n", window, windows)
windows = append(windows, window)
}
I have a JSON I need to do some processing on. It uses a slice that I need
to reference in some way for the Room-struct to be modified at the end of
the function. How can I work with this struct concurrently in a by
reference type of way?
http://play.golang.org/p/wRhd1sDqtb
type Window struct {
Height int64 `json:"Height"`
Width int64 `json:"Width"`
}
type Room struct {
Windows []Window `json:"Windows"`
}
func main() {
js :=
[]byte(`{"Windows":[{"Height":10,"Width":20},{"Height":10,"Width":20}]}`)
fmt.Printf("Should have 2 windows: %v\n", string(js))
var room Room
_ = json.Unmarshal(js, &room)
var wg sync.WaitGroup
// Add meny windows to room
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
addWindow(room.Windows)
}()
}
wg.Wait()
js, _ = json.Marshal(room)
fmt.Printf("Sould have 12 windows: %v\n", string(js))
}
func addWindow(windows []Window) {
window := Window{1, 1}
fmt.Printf("Adding %v to %v\n", window, windows)
windows = append(windows, window)
}
JQuery script issue (not working when i click for the second time)
JQuery script issue (not working when i click for the second time)
When i click on the link it will show a pop-up(twitter bootstrap) and in
that i have a select field called country, and i when i select US it will
auto-populate all the states of US in the another select field , else it
will show a text field. It is working when i click link for the first time
, after closing and when i click the link for second time , the script is
not getting loaded. I don't know the reason , Please help me out !
Here is the script :
<script>
$("#job_country").click(function() {
$a = $("#job_country option:selected").text();
if ($a == "United States") {
$("#job_state").show();
$(".text_state").hide();
}
else
{
$("#job_state").hide();
$(".text_state").show();
}
});
});
When i click on the link it will show a pop-up(twitter bootstrap) and in
that i have a select field called country, and i when i select US it will
auto-populate all the states of US in the another select field , else it
will show a text field. It is working when i click link for the first time
, after closing and when i click the link for second time , the script is
not getting loaded. I don't know the reason , Please help me out !
Here is the script :
<script>
$("#job_country").click(function() {
$a = $("#job_country option:selected").text();
if ($a == "United States") {
$("#job_state").show();
$(".text_state").hide();
}
else
{
$("#job_state").hide();
$(".text_state").show();
}
});
});
Display all locale languages in a spinner in android
Display all locale languages in a spinner in android
I want a spinner which contains all the Locale languages. Spinner should
show the full language names and not the code.
For eg: "English" not "en".
Thanx in advance.
I want a spinner which contains all the Locale languages. Spinner should
show the full language names and not the code.
For eg: "English" not "en".
Thanx in advance.
Monday, 26 August 2013
I have 2 if statements in one, the first is being skipped, why?
I have 2 if statements in one, the first is being skipped, why?
Hi there I'm having trouble using multiple if statements. Here is my code:
if ([itemOnSpecial caseInsensitiveCompare: @"yes"] == NSOrderedSame) {
UILabel *specialLabel = (UILabel*) [cell viewWithTag:5];
specialLabel.text = specialPrice;
[specialLabel setHidden:NO];
}
//This statement is completely skipped
if ([isOnBulkSpecial caseInsensitiveCompare:@"yes"] == NSOrderedSame) {
UILabel *specialLabel = (UILabel*) [cell viewWithTag:5];
specialLabel.text = bulkSpecialPrice;
[specialLabel setHidden:NO];
}else{
UILabel *specialLabel = (UILabel*) [cell viewWithTag:5];
[specialLabel setHidden:YES];
}
Only the second if statement is taken into account. The first if statement
seems to be completely disregarded.
Hi there I'm having trouble using multiple if statements. Here is my code:
if ([itemOnSpecial caseInsensitiveCompare: @"yes"] == NSOrderedSame) {
UILabel *specialLabel = (UILabel*) [cell viewWithTag:5];
specialLabel.text = specialPrice;
[specialLabel setHidden:NO];
}
//This statement is completely skipped
if ([isOnBulkSpecial caseInsensitiveCompare:@"yes"] == NSOrderedSame) {
UILabel *specialLabel = (UILabel*) [cell viewWithTag:5];
specialLabel.text = bulkSpecialPrice;
[specialLabel setHidden:NO];
}else{
UILabel *specialLabel = (UILabel*) [cell viewWithTag:5];
[specialLabel setHidden:YES];
}
Only the second if statement is taken into account. The first if statement
seems to be completely disregarded.
Batch files to list files saved in last 24 hours
Batch files to list files saved in last 24 hours
Hi I'm trying to write a batch files that will search some directories and
output a text file report with a list of files saved in the last day
between a certain file size.
The files size part is no problem - but how to I parse the date and check
it against todays date, and add it to the 'if' statement?
This is what I have so far:
@echo Report will open when complete
@echo Working
@echo off
setlocal
set "SEARCH_DIR=f:"
set "MIN_SIZE=1"
set "MAX_SIZE=300000"
set "REPORT=F:\Error_report.txt"
echo **************************************************** >> %REPORT%
echo File report %date% %time% >> %REPORT%
echo File size %MIN_SIZE% to %MAX_SIZE% >> %REPORT%
echo **************************************************** >> %REPORT%
echo File list: >> %REPORT%
for /R "%SEARCH_DIR%" %%F in (*) do (
if exist "%%F" if %%~zF LSS %MAX_SIZE% if %%~zF GEQ %MIN_SIZE% echo %%F
>> %REPORT%
)
@echo Done
START %REPORT%
I've tried adding if forfiles /d +1 to the if statement - but that doesn't
work!
Any help would be appreciated.
Hi I'm trying to write a batch files that will search some directories and
output a text file report with a list of files saved in the last day
between a certain file size.
The files size part is no problem - but how to I parse the date and check
it against todays date, and add it to the 'if' statement?
This is what I have so far:
@echo Report will open when complete
@echo Working
@echo off
setlocal
set "SEARCH_DIR=f:"
set "MIN_SIZE=1"
set "MAX_SIZE=300000"
set "REPORT=F:\Error_report.txt"
echo **************************************************** >> %REPORT%
echo File report %date% %time% >> %REPORT%
echo File size %MIN_SIZE% to %MAX_SIZE% >> %REPORT%
echo **************************************************** >> %REPORT%
echo File list: >> %REPORT%
for /R "%SEARCH_DIR%" %%F in (*) do (
if exist "%%F" if %%~zF LSS %MAX_SIZE% if %%~zF GEQ %MIN_SIZE% echo %%F
>> %REPORT%
)
@echo Done
START %REPORT%
I've tried adding if forfiles /d +1 to the if statement - but that doesn't
work!
Any help would be appreciated.
Jquery image count elements
Jquery image count elements
I'm working with bjqs slider and fancybox. I'm trying to calculate the
number of images shown and display them as Image 1/3, 2/3, 3/3 etc... At
the moment, the script is showing count, but its not responding to first
click and count number of total images is wrong.
Any help would be appreciated, Here is the code:
<script>
$(function() { $('.toggle').click(function() { $('.col_2').toggle();
return false; }); });
$(window).resize(function(){ if(window.innerWidth > 960) {
$(".col_2").removeAttr("style"); } });
jQuery(document).ready(function($) {
$('#banner-slide').bjqs({
animtype : 'slide',
height : 690,
width : 536,
responsive : true,
randomstart : false,
});
$(".fancybox").fancybox();
//var numImgs = $('#banner-slide img').length - 2;
// $('.count').text(numImgs);
var images = $('#banner-slide img');
var imageIndex = 1;
$("li.bjqs-next a").click(function(){
$('.count').text(imageIndex++ + "/" + images.length/2);
if( imageIndex > images.length/2 )
{
imageIndex = 1;
}
else { }
})
$("li.bjqs-prev a").click(function(){
$('.count').text(imageIndex-- + "/" + images.length/2);
if( imageIndex < 1 )
{
imageIndex = images.length/2;
}
})
// $('ul.bjqs-controls li.bjqs-next a').click( function(){
$('.count').text(($current++) + "/" + $iCount); });
//$('ul.bjqs-controls li.bjqs-prev a').click( function(){
$('.count').text(($current--) + "/" + iCount); });
$('.count').text("1" + "/" + images.length/2);
//setInterval(function () { }, 1000);
});
</script>
I'm working with bjqs slider and fancybox. I'm trying to calculate the
number of images shown and display them as Image 1/3, 2/3, 3/3 etc... At
the moment, the script is showing count, but its not responding to first
click and count number of total images is wrong.
Any help would be appreciated, Here is the code:
<script>
$(function() { $('.toggle').click(function() { $('.col_2').toggle();
return false; }); });
$(window).resize(function(){ if(window.innerWidth > 960) {
$(".col_2").removeAttr("style"); } });
jQuery(document).ready(function($) {
$('#banner-slide').bjqs({
animtype : 'slide',
height : 690,
width : 536,
responsive : true,
randomstart : false,
});
$(".fancybox").fancybox();
//var numImgs = $('#banner-slide img').length - 2;
// $('.count').text(numImgs);
var images = $('#banner-slide img');
var imageIndex = 1;
$("li.bjqs-next a").click(function(){
$('.count').text(imageIndex++ + "/" + images.length/2);
if( imageIndex > images.length/2 )
{
imageIndex = 1;
}
else { }
})
$("li.bjqs-prev a").click(function(){
$('.count').text(imageIndex-- + "/" + images.length/2);
if( imageIndex < 1 )
{
imageIndex = images.length/2;
}
})
// $('ul.bjqs-controls li.bjqs-next a').click( function(){
$('.count').text(($current++) + "/" + $iCount); });
//$('ul.bjqs-controls li.bjqs-prev a').click( function(){
$('.count').text(($current--) + "/" + iCount); });
$('.count').text("1" + "/" + images.length/2);
//setInterval(function () { }, 1000);
});
</script>
Execution order of services, factories & providers in AngularJS?
Execution order of services, factories & providers in AngularJS?
Does AngularJS framework executes all mentioned above in a predefined
order or is this done by the programmer?
Does AngularJS framework executes all mentioned above in a predefined
order or is this done by the programmer?
Implement a class ListOfIntegers to hold numbers in Java [on hold]
Implement a class ListOfIntegers to hold numbers in Java [on hold]
i have to Implement a class ListOfIntegers to hold numbers in Java. The
class should support the following operations:
ListOfIntegers read()
void displayList(ListOfIntegers ob)
boolean insertBefore(int numBefore, int numToInsert)
boolean deleteAll(int num)
i am new to programming and do not know much about java, i would be
greatfull if anyone could help me with this problem. thank you.
i have to Implement a class ListOfIntegers to hold numbers in Java. The
class should support the following operations:
ListOfIntegers read()
void displayList(ListOfIntegers ob)
boolean insertBefore(int numBefore, int numToInsert)
boolean deleteAll(int num)
i am new to programming and do not know much about java, i would be
greatfull if anyone could help me with this problem. thank you.
Is there an easy way to retrieve the start time stamp from TimeSpan
Is there an easy way to retrieve the start time stamp from TimeSpan
What is the difference between the TimeSpan private field startTimeStamp
and the DateTime.Ticks property? Is there an easy way to retrieve the
startTimeStamp (without using reflection) ?
What is the difference between the TimeSpan private field startTimeStamp
and the DateTime.Ticks property? Is there an easy way to retrieve the
startTimeStamp (without using reflection) ?
Not logout the facebook session
Not logout the facebook session
I have created one face book integrate application.when i login & logout
my application which is login and logged out correctly.And if i login the
facebook and close the application and then open that application click
the logout which is logout correctly.My problem is when i login the
application and then again run the application from my eclipse ide at that
time i am trying to logout this one show error.thanks...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAsyncRunner = new AsyncFacebookRunner(facebook);
facebook = new Facebook(APP_ID);
sharePref = getPreferences(MODE_PRIVATE);
facebook.setAccessToken(sharePref.getString(ACCESS_TOKEN, null));
facebook.setAccessExpires(sharePref.getLong(EXPIRE_SESSION, 0));
buttonLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
loginToFacebook();
}
});
buttonLogout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
logoutFacebook();
}
});
}
public void loginToFacebook() {
if (!facebook.isSessionValid()) {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new DialogListener() {
@Override
public void onFacebookError(FacebookError e) {
}
@Override
public void onError(DialogError e) {
}
@Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor =
sharePref.edit();
editor.putString(ACCESS_TOKEN,
facebook.getAccessToken());
editor.putLong(EXPIRE_SESSION,
facebook.getAccessExpires());
editor.commit();
}
@Override
public void onCancel() {
}
});
} else {
Toast.makeText(getApplicationContext(), "You Already Login",
Toast.LENGTH_SHORT).show();
}
}
protected void logoutFacebook() {
if (facebook.isSessionValid()) {
mAsyncRunner.logout(this,
new RequestListener() {
@Override
public void onComplete(String response, Object
state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
Log.e("Logout from Facebook", "Great");
}
}
@Override
public void onIOException(IOException e, Object
state) {
}
@Override
public void onFileNotFoundException(
FileNotFoundException e, Object state) {
}
@Override
public void onMalformedURLException(
MalformedURLException e, Object state) {
}
@Override
public void onFacebookError(FacebookError e,
Object state) {
}
});
} else {
Toast.makeText(getApplicationContext(), "Login First",
Toast.LENGTH_SHORT).show();
}
}
I got this type of error:
E/AndroidRuntime( 6331): FATAL EXCEPTION: Thread-264
E/AndroidRuntime( 6331): java.lang.IllegalArgumentException: Invalid
context argument E/AndroidRuntime( 6331): at
android.webkit.CookieSyncManager.createInstance(CookieSyncManager.java:86)
E/AndroidRuntime( 6331): at
com.facebook.internal.Utility.clearCookiesForDomain(Utility.java:261)
E/AndroidRuntime( 6331): at
com.facebook.internal.Utility.clearFacebookCookies(Utility.java:285)
E/AndroidRuntime( 6331): at
com.facebook.Session.closeAndClearTokenInformation(Session.java:593)
E/AndroidRuntime( 6331): at
com.facebook.android.Facebook.logoutImpl(Facebook.java:698)
E/AndroidRuntime( 6331): at
com.facebook.android.AsyncFacebookRunner$1.run(AsyncFacebookRunner.java:89)
W/ActivityManager( 1202): Force finishing activity
com.facebook.androidhive/.AndroidFacebookConnectActivity W/WindowManager(
1202): Failure taking screenshot for (246x437) to layer 21020 W/Trace (
6331): Unexpected value from nativeGetEnabledTags: 0 W/Trace ( 1202):
Unexpected value from nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected
value from nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6331): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 E/SurfaceFlinger( 786): ro.sf.lcd_density must be
defined as a build property W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6331): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0
I have created one face book integrate application.when i login & logout
my application which is login and logged out correctly.And if i login the
facebook and close the application and then open that application click
the logout which is logout correctly.My problem is when i login the
application and then again run the application from my eclipse ide at that
time i am trying to logout this one show error.thanks...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAsyncRunner = new AsyncFacebookRunner(facebook);
facebook = new Facebook(APP_ID);
sharePref = getPreferences(MODE_PRIVATE);
facebook.setAccessToken(sharePref.getString(ACCESS_TOKEN, null));
facebook.setAccessExpires(sharePref.getLong(EXPIRE_SESSION, 0));
buttonLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
loginToFacebook();
}
});
buttonLogout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
logoutFacebook();
}
});
}
public void loginToFacebook() {
if (!facebook.isSessionValid()) {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new DialogListener() {
@Override
public void onFacebookError(FacebookError e) {
}
@Override
public void onError(DialogError e) {
}
@Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor =
sharePref.edit();
editor.putString(ACCESS_TOKEN,
facebook.getAccessToken());
editor.putLong(EXPIRE_SESSION,
facebook.getAccessExpires());
editor.commit();
}
@Override
public void onCancel() {
}
});
} else {
Toast.makeText(getApplicationContext(), "You Already Login",
Toast.LENGTH_SHORT).show();
}
}
protected void logoutFacebook() {
if (facebook.isSessionValid()) {
mAsyncRunner.logout(this,
new RequestListener() {
@Override
public void onComplete(String response, Object
state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
Log.e("Logout from Facebook", "Great");
}
}
@Override
public void onIOException(IOException e, Object
state) {
}
@Override
public void onFileNotFoundException(
FileNotFoundException e, Object state) {
}
@Override
public void onMalformedURLException(
MalformedURLException e, Object state) {
}
@Override
public void onFacebookError(FacebookError e,
Object state) {
}
});
} else {
Toast.makeText(getApplicationContext(), "Login First",
Toast.LENGTH_SHORT).show();
}
}
I got this type of error:
E/AndroidRuntime( 6331): FATAL EXCEPTION: Thread-264
E/AndroidRuntime( 6331): java.lang.IllegalArgumentException: Invalid
context argument E/AndroidRuntime( 6331): at
android.webkit.CookieSyncManager.createInstance(CookieSyncManager.java:86)
E/AndroidRuntime( 6331): at
com.facebook.internal.Utility.clearCookiesForDomain(Utility.java:261)
E/AndroidRuntime( 6331): at
com.facebook.internal.Utility.clearFacebookCookies(Utility.java:285)
E/AndroidRuntime( 6331): at
com.facebook.Session.closeAndClearTokenInformation(Session.java:593)
E/AndroidRuntime( 6331): at
com.facebook.android.Facebook.logoutImpl(Facebook.java:698)
E/AndroidRuntime( 6331): at
com.facebook.android.AsyncFacebookRunner$1.run(AsyncFacebookRunner.java:89)
W/ActivityManager( 1202): Force finishing activity
com.facebook.androidhive/.AndroidFacebookConnectActivity W/WindowManager(
1202): Failure taking screenshot for (246x437) to layer 21020 W/Trace (
6331): Unexpected value from nativeGetEnabledTags: 0 W/Trace ( 1202):
Unexpected value from nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected
value from nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6331): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 E/SurfaceFlinger( 786): ro.sf.lcd_density must be
defined as a build property W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6331): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 6239): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0 W/Trace ( 1202): Unexpected value from
nativeGetEnabledTags: 0
Match a string and the 5 characters before and after
Match a string and the 5 characters before and after
I need to match the string one or two and the 5 characters before and after
with the following text in input
Lorem Ipsum is simply dummy one text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen two book. It has survived not only
five centuries, but also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more recently with
desktop publishing software like Aldus PageMaker including versions of
Lorem Ipsum.
the output should be
ummy one text
imen two book
the regex should works with the scan method in ruby
I need to match the string one or two and the 5 characters before and after
with the following text in input
Lorem Ipsum is simply dummy one text of the printing and typesetting
industry. Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s, when an unknown printer took a galley of type and
scrambled it to make a type specimen two book. It has survived not only
five centuries, but also the leap into electronic typesetting, remaining
essentially unchanged. It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more recently with
desktop publishing software like Aldus PageMaker including versions of
Lorem Ipsum.
the output should be
ummy one text
imen two book
the regex should works with the scan method in ruby
Sunday, 25 August 2013
Can I active the Trackmania 2 Steam Key on Maniaplanet?
Can I active the Trackmania 2 Steam Key on Maniaplanet?
Is it possible to activate the Key on Maniaplanet if I bought Trackmania 2
on Steam?
Is it possible to activate the Key on Maniaplanet if I bought Trackmania 2
on Steam?
get the geolocation from IP , with "ipinfodb"
get the geolocation from IP , with "ipinfodb"
i know good javascript but totally novice in json and need to do the
following:
get the geolocation from IP , with "ipinfodb" like this response:
OK;;174.88.229.95;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
i found many codes for that but all seem to be complicate and long with
more options like saving the results in cookies i want the least necessary
code to retrieve those informations for saving them in cookies and more i
want to care for it my self after.. (i don't like to put code i dont
understand) the best would be a simple function that returns this
information as string or array, like this
function getLocFromIP(IP){
(js + json code)
return result;
}
much thank in advance
i know good javascript but totally novice in json and need to do the
following:
get the geolocation from IP , with "ipinfodb" like this response:
OK;;174.88.229.95;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
i found many codes for that but all seem to be complicate and long with
more options like saving the results in cookies i want the least necessary
code to retrieve those informations for saving them in cookies and more i
want to care for it my self after.. (i don't like to put code i dont
understand) the best would be a simple function that returns this
information as string or array, like this
function getLocFromIP(IP){
(js + json code)
return result;
}
much thank in advance
Saturday, 24 August 2013
Connect CellPhone to ADK installed on a Virtual Machine in VirtualBox
Connect CellPhone to ADK installed on a Virtual Machine in VirtualBox
So, here is the thing: I wanted to do some Android App Development and
some Google Glass Dev using the Mirror API as well. I wanted to do it in
Linux since well, I prefer that.
I have a Windows laptop which I don't want to mess too much with and hence
have an Ubuntu VM installed through Virtual Box which I use to code
everything.
Now, My Ubuntu VM is required to connect to my Android Phone and work with
it through Bluetooth. However, since I am using a Virtual Box VM, can I
possibly face any problems with it? I mean... the phone will connect to
the Windows Bluetooth... Can I get it to work with my Ubuntu VM? Is my
initial start (what I'm doing right now) a recipe for future failure?
So, here is the thing: I wanted to do some Android App Development and
some Google Glass Dev using the Mirror API as well. I wanted to do it in
Linux since well, I prefer that.
I have a Windows laptop which I don't want to mess too much with and hence
have an Ubuntu VM installed through Virtual Box which I use to code
everything.
Now, My Ubuntu VM is required to connect to my Android Phone and work with
it through Bluetooth. However, since I am using a Virtual Box VM, can I
possibly face any problems with it? I mean... the phone will connect to
the Windows Bluetooth... Can I get it to work with my Ubuntu VM? Is my
initial start (what I'm doing right now) a recipe for future failure?
WP get first and last post title
WP get first and last post title
I am listing cities and order them alphabetically and I came up with this
code
<?php
$args=array(
'post_type' => 'cities',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=>-1,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();?>
<?php
$this_char = strtoupper(substr($post->post_title,0,1));
if ($this_char != $last_char) {
$last_char = $this_char;
if (isset($flag))
echo '</div>';
echo '<div data-role="collapsible" class="excerpts">';
echo '<h3 class="alphabet">'. '<div>'.$last_char. '</div>' .'</h3>';
$flag = true;
} ?>
<p class="inner"><a data-transition="slide" href="<?php the_permalink()
?>" rel="bookmark" title="Permanent Link to <?php
the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php endwhile; }
if (isset($flag))
echo '</div>';
wp_reset_query();?>
This code generates the following HTML
<div class="collapsible">
<h3><div>A</div></h3>
<p>Atlanta</p>
<p>Alabama</p>
<p>Arizona</p>
</div>
but what I am trying to achieve is to have the first and last post title
next to the letter, something like this
<div class="collapsible">
<h3><div>A</div> Atlanta - Arizona</h3>
<p>Atlanta</p>
<p>Alabama</p>
<p>Arizona</p>
</div>
How can I get in wordpress the last post title? Any ideas? Thank You.
I tried this for the first but I don't know about the last
echo '<h3 class="alphabet">'. '<div>'.$last_char. '</div>' .
get_the_title() .' - get_the_last_title' .'</h3>';
I am listing cities and order them alphabetically and I came up with this
code
<?php
$args=array(
'post_type' => 'cities',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=>-1,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();?>
<?php
$this_char = strtoupper(substr($post->post_title,0,1));
if ($this_char != $last_char) {
$last_char = $this_char;
if (isset($flag))
echo '</div>';
echo '<div data-role="collapsible" class="excerpts">';
echo '<h3 class="alphabet">'. '<div>'.$last_char. '</div>' .'</h3>';
$flag = true;
} ?>
<p class="inner"><a data-transition="slide" href="<?php the_permalink()
?>" rel="bookmark" title="Permanent Link to <?php
the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php endwhile; }
if (isset($flag))
echo '</div>';
wp_reset_query();?>
This code generates the following HTML
<div class="collapsible">
<h3><div>A</div></h3>
<p>Atlanta</p>
<p>Alabama</p>
<p>Arizona</p>
</div>
but what I am trying to achieve is to have the first and last post title
next to the letter, something like this
<div class="collapsible">
<h3><div>A</div> Atlanta - Arizona</h3>
<p>Atlanta</p>
<p>Alabama</p>
<p>Arizona</p>
</div>
How can I get in wordpress the last post title? Any ideas? Thank You.
I tried this for the first but I don't know about the last
echo '<h3 class="alphabet">'. '<div>'.$last_char. '</div>' .
get_the_title() .' - get_the_last_title' .'</h3>';
Dreamhost VPS PHP Startup: Unable to open package2.xml
Dreamhost VPS PHP Startup: Unable to open package2.xml
I have a new Dreamhost VPS server running PHP 5.3. Whenever I run a PHP
program I get this error every time.
PHP Warning: PHP Startup: Unable to load dynamic library '/imagick.so' -
/imagick.so: cannot open shared object file: No such file or directory in
Unknown on line 0 Unable to open package2.xml
I've installed php5-imagick using aptitude and I've followed the
instructions at
http://wiki.dreamhost.com/ImageMagick_and_imagick_php_module_on_shared_hosting#Install_ImageMagick
but the problem persists.
What is package2.xml and how can I fix this problem?
I have a new Dreamhost VPS server running PHP 5.3. Whenever I run a PHP
program I get this error every time.
PHP Warning: PHP Startup: Unable to load dynamic library '/imagick.so' -
/imagick.so: cannot open shared object file: No such file or directory in
Unknown on line 0 Unable to open package2.xml
I've installed php5-imagick using aptitude and I've followed the
instructions at
http://wiki.dreamhost.com/ImageMagick_and_imagick_php_module_on_shared_hosting#Install_ImageMagick
but the problem persists.
What is package2.xml and how can I fix this problem?
Correct LESS CSS computation syntax
Correct LESS CSS computation syntax
I have a variable that sets a percentage:
@var-a: 50%;
And another that is a fixed width:
@var-b: 100px;
I want to calculate @var-c as below:
@var-c: (@var-a * @var-b);
I expected 50px, but actually get 5000px. What am I doing wrong?
I have a variable that sets a percentage:
@var-a: 50%;
And another that is a fixed width:
@var-b: 100px;
I want to calculate @var-c as below:
@var-c: (@var-a * @var-b);
I expected 50px, but actually get 5000px. What am I doing wrong?
VS2010 Debug and Release Clean and Rebuild
VS2010 Debug and Release Clean and Rebuild
I have one project (in c/c++ ) which consist of two solutions. First one
is "build_model", another is "fit_model". I set up properties to put all
binaries in the same directory as "fit_model" will invoke during it's
execution "build_model".
So, I first compile "build_model" and it goes well. All files are put into
.../bin\ Then I compile "fit_model" and it is OK as well. All files are
put into .../bin\ Everything works fine. Even if do "Clean" and "Rebuild"
for "fit_model" only it's binaries are deleted are re-created. That is for
Release build. Clean & Re-build of "build_model" also cleans only it's own
binaries (as it should be).
But when I switch to Debug mode, as soon as I do Clean for "fit_model" it
deletes all of the binaries in .../bin\ folder, including it's own and
binaries from "build_model". This is NOT what I want.
So, this is not happening in Release, but only for Debug clean & rebuild.
The problem is that even with different directories it does the same.
Which settings should I change? (VS2010, Windows7)
I have one project (in c/c++ ) which consist of two solutions. First one
is "build_model", another is "fit_model". I set up properties to put all
binaries in the same directory as "fit_model" will invoke during it's
execution "build_model".
So, I first compile "build_model" and it goes well. All files are put into
.../bin\ Then I compile "fit_model" and it is OK as well. All files are
put into .../bin\ Everything works fine. Even if do "Clean" and "Rebuild"
for "fit_model" only it's binaries are deleted are re-created. That is for
Release build. Clean & Re-build of "build_model" also cleans only it's own
binaries (as it should be).
But when I switch to Debug mode, as soon as I do Clean for "fit_model" it
deletes all of the binaries in .../bin\ folder, including it's own and
binaries from "build_model". This is NOT what I want.
So, this is not happening in Release, but only for Debug clean & rebuild.
The problem is that even with different directories it does the same.
Which settings should I change? (VS2010, Windows7)
d3.js - blank object when applying y-axis scale
d3.js - blank object when applying y-axis scale
I'm trying to apply a scale to y-axis in my chart, but when I do it I get
a blank svg object. I did the same thing with the x-axis and it's working
fine.
Problem happens when you uncomment this section
// .y(function(d) {
// return yScale(d[1])
// })
http://jsfiddle.net/MgwR5/
Could anyone tell me what I'm doing wrong?
I'm trying to apply a scale to y-axis in my chart, but when I do it I get
a blank svg object. I did the same thing with the x-axis and it's working
fine.
Problem happens when you uncomment this section
// .y(function(d) {
// return yScale(d[1])
// })
http://jsfiddle.net/MgwR5/
Could anyone tell me what I'm doing wrong?
Downgrade Nexus 4 from Android 4.3 to 4.2.2
Downgrade Nexus 4 from Android 4.3 to 4.2.2
I updated my Nexus 4 to Android 4.3. I don't like it, so I want to return
to version 4.2.2. How do I go back to a previous version?
I updated my Nexus 4 to Android 4.3. I don't like it, so I want to return
to version 4.2.2. How do I go back to a previous version?
how to use a scanner's input( used in a swtich case in main's body) in a method('s body) defined outside the main
how to use a scanner's input( used in a swtich case in main's body) in a
method('s body) defined outside the main
I am stuck in a code as I have used scanner class(system.in) multiple
times in a switch case in the main's and I have also declared a public
method before main, which need to take the argument from that scanner's
keyboard input. how can I access scanner values obtained in main method,
in a method declared outside the main?
below is a chunk of method's code before the main:
public class temp_cnvrter {
public static double cels(double input1) /* this input1 needs to be
fetched from scanner inside main method*/
{
double output1;
output1= input1 + 273.15;
System.out.println("temperature in rankine is:" +output1 );
return output1;
}
public static void main(String[] args) {
}
method('s body) defined outside the main
I am stuck in a code as I have used scanner class(system.in) multiple
times in a switch case in the main's and I have also declared a public
method before main, which need to take the argument from that scanner's
keyboard input. how can I access scanner values obtained in main method,
in a method declared outside the main?
below is a chunk of method's code before the main:
public class temp_cnvrter {
public static double cels(double input1) /* this input1 needs to be
fetched from scanner inside main method*/
{
double output1;
output1= input1 + 273.15;
System.out.println("temperature in rankine is:" +output1 );
return output1;
}
public static void main(String[] args) {
}
Friday, 23 August 2013
How to setup Ubuntu using raid 5
How to setup Ubuntu using raid 5
I would like to set up a desktop computer with Ubuntu 13.04 instaled. I
would like to use raid 5. Where can find info on hownto do this? Thanks
for any help.
Willie
I would like to set up a desktop computer with Ubuntu 13.04 instaled. I
would like to use raid 5. Where can find info on hownto do this? Thanks
for any help.
Willie
Rename with pattern
Rename with pattern
I have a lot of files looking like this:
"THIS IS my file.txt"
"THIS IS My file.txt"
"THIS IS m file.txt"
"THIS IS M file.txt"
So basically, if I try to describe it, it's a string composed of words
(eventually 1 character words) in upper case, then words in lower case
(eventually with first letter of word in upper case).
I'd like to extract the first part of the filename, composed of upper case
words, put them to lowercase (with just the first letter as uppercase),
and seperate it from the rest with an hyphen.
So the result I'm expecting is:
"This Is - my file.txt"
"This Is - My file.txt"
"This Is - m file.txt"
"This Is M - file.txt"
What I have so far is:
rename 's/^(([A-Z]{2,}| )+)(.*)/\u\L$1\E - $3/g' *
But there are quite a few problems with it (one letter upper case words
don't match, and only the first word is capitalized).
I have a lot of files looking like this:
"THIS IS my file.txt"
"THIS IS My file.txt"
"THIS IS m file.txt"
"THIS IS M file.txt"
So basically, if I try to describe it, it's a string composed of words
(eventually 1 character words) in upper case, then words in lower case
(eventually with first letter of word in upper case).
I'd like to extract the first part of the filename, composed of upper case
words, put them to lowercase (with just the first letter as uppercase),
and seperate it from the rest with an hyphen.
So the result I'm expecting is:
"This Is - my file.txt"
"This Is - My file.txt"
"This Is - m file.txt"
"This Is M - file.txt"
What I have so far is:
rename 's/^(([A-Z]{2,}| )+)(.*)/\u\L$1\E - $3/g' *
But there are quite a few problems with it (one letter upper case words
don't match, and only the first word is capitalized).
How to get the favorites from flickr
How to get the favorites from flickr
I am working on node.js to get the list of favorites photos from a user in
flickr, I know there is other method to get the public list of favorites,
and that one works fine to me, but using this the flickr api return me
this error.
{"stat":"fail", "code":98, "message":"Invalid auth token"}
This is my code.
var util = require('util'),
http = require('http'),
keys = require(__dirname + '/../oauth/flickrKeys'),
utilities = require(__dirname + '/Utilities');
var requestResponse,
parameters,
requestPoint,
url,
toHash,
secretKey,
api_signature,
method = "flickr.favorites.getList",
format = "json";
requestPoint = 'http://api.flickr.com/services/rest/';
url = requestPoint
+ '?api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
parameters = 'api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
toHash = 'GET&'
+ encodeURIComponent(requestPoint) + '&'
+ encodeURIComponent(parameters);
// coding hash.
secretKey = keys.secreto + "&" + userInfo.oauth_token_secret;
api_signature = utilities.generateFlickrSignatureHex(toHash, secretKey);
// adding api signature to the url.
url = url + '&api_sig=' + encodeURIComponent(api_signature);
http.get(url, function(res) {});
I am working on node.js to get the list of favorites photos from a user in
flickr, I know there is other method to get the public list of favorites,
and that one works fine to me, but using this the flickr api return me
this error.
{"stat":"fail", "code":98, "message":"Invalid auth token"}
This is my code.
var util = require('util'),
http = require('http'),
keys = require(__dirname + '/../oauth/flickrKeys'),
utilities = require(__dirname + '/Utilities');
var requestResponse,
parameters,
requestPoint,
url,
toHash,
secretKey,
api_signature,
method = "flickr.favorites.getList",
format = "json";
requestPoint = 'http://api.flickr.com/services/rest/';
url = requestPoint
+ '?api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
parameters = 'api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
toHash = 'GET&'
+ encodeURIComponent(requestPoint) + '&'
+ encodeURIComponent(parameters);
// coding hash.
secretKey = keys.secreto + "&" + userInfo.oauth_token_secret;
api_signature = utilities.generateFlickrSignatureHex(toHash, secretKey);
// adding api signature to the url.
url = url + '&api_sig=' + encodeURIComponent(api_signature);
http.get(url, function(res) {});
Syncsvn with https repository
Syncsvn with https repository
I am on a Windows Server machine and trying to make a mirror of an SVN
repository using svnsync. The server requires a client certificate to
grant access (https).
The message I get from svnsync is "An error occurred during SSL
communication".
I can check out the repository via TortoiseSVN, providing my certificate
as pfx-file.
I assume I have to provide the certificate for the svnsync command as
well. Question is how? Or are there other options?
I am on a Windows Server machine and trying to make a mirror of an SVN
repository using svnsync. The server requires a client certificate to
grant access (https).
The message I get from svnsync is "An error occurred during SSL
communication".
I can check out the repository via TortoiseSVN, providing my certificate
as pfx-file.
I assume I have to provide the certificate for the svnsync command as
well. Question is how? Or are there other options?
when fails theorem of cauchy integral
when fails theorem of cauchy integral
i am interesting what is a condition when following theorem of cauchy
integral fails let $U$ be an open subset of $C$ which is simply connected,
let $f : U ¨ C$ be a holomorphic function, and let $\!\,\gamma$ be a
rectifiable path in $U$ whose start point is equal to its end point. Then
as i understand ,first condition of failing this statement should be that
function should not be holomorphic or function that is not complex
differentiable in a neighborhood of every point in its domain.also maybe
also $U$ substet if it is not connected,then this theorem may fail,what is
also other conditions?thanks in advance
i am interesting what is a condition when following theorem of cauchy
integral fails let $U$ be an open subset of $C$ which is simply connected,
let $f : U ¨ C$ be a holomorphic function, and let $\!\,\gamma$ be a
rectifiable path in $U$ whose start point is equal to its end point. Then
as i understand ,first condition of failing this statement should be that
function should not be holomorphic or function that is not complex
differentiable in a neighborhood of every point in its domain.also maybe
also $U$ substet if it is not connected,then this theorem may fail,what is
also other conditions?thanks in advance
Unplugging usb device refreshes my app (Phonegap)
Unplugging usb device refreshes my app (Phonegap)
I built this Android app using phonegap (cordova) and whenever I plug in a
usb barcode reader the app seems to refresh itself and I loose all the
data I've entered into my fields. It also refreshes the app whenever I try
scanning a barcode too.
I'm building this for Android 4.2 and higher. Is there a way to prevent
this from happening?
I built this Android app using phonegap (cordova) and whenever I plug in a
usb barcode reader the app seems to refresh itself and I loose all the
data I've entered into my fields. It also refreshes the app whenever I try
scanning a barcode too.
I'm building this for Android 4.2 and higher. Is there a way to prevent
this from happening?
Thursday, 22 August 2013
R: Custom Legend for Multiple Layer ggplot
R: Custom Legend for Multiple Layer ggplot
I'm trying to get a custom legend for a ggplot with data coming from two
separate data frames. See below for a minimum reproducible example.
What I'm trying to accomplish is to have a legend describing the ribbon
fill, the black line, and the red line.
require(ggplot2)
x=seq(1,10,length=100)
data=data.frame(x,
dnorm(x,mean=5,sd=1)+.01,
dnorm(x,mean=5,sd=1)-.01,
dnorm(x,mean=5,sd=1),
dnorm(x,mean=5.5,sd=1))
names(data)=c('x','max','min','avg','new.data')
ggplot()+geom_ribbon(data=data,aes(ymin=min,ymax=max,x=x),fill='lightgreen')+
geom_line(data=data,aes(x=x,y=avg),color='black')+
geom_line(data=data,aes(x=x,y=new.data),color='red')+
xlab('x')+ylab('density')
In my full dataset, the data from the geom_ribbon comes from a different
data frame.
I'm trying to get a custom legend for a ggplot with data coming from two
separate data frames. See below for a minimum reproducible example.
What I'm trying to accomplish is to have a legend describing the ribbon
fill, the black line, and the red line.
require(ggplot2)
x=seq(1,10,length=100)
data=data.frame(x,
dnorm(x,mean=5,sd=1)+.01,
dnorm(x,mean=5,sd=1)-.01,
dnorm(x,mean=5,sd=1),
dnorm(x,mean=5.5,sd=1))
names(data)=c('x','max','min','avg','new.data')
ggplot()+geom_ribbon(data=data,aes(ymin=min,ymax=max,x=x),fill='lightgreen')+
geom_line(data=data,aes(x=x,y=avg),color='black')+
geom_line(data=data,aes(x=x,y=new.data),color='red')+
xlab('x')+ylab('density')
In my full dataset, the data from the geom_ribbon comes from a different
data frame.
OpenCV Kalman Filter stack overflow
OpenCV Kalman Filter stack overflow
I'm trying to implement a kalman filter for 3D tracking in OpenCV 2.2. The
state variables are the coordinates x,y,z followed by the velocities Vx,Vy
and Vz and I can only measure x,y and z.
I used an example from the book Learning OpenCV from O'reilly to get
started, but when I tried to adapt the example to my problem things got a
little confusing.
This is my implementation (I've tried to reduce the code to just the
relevant parts, and I've commented a lot to hopefully ease the reading).
CvKalman* kalman = cvCreateKalman( 6, 3, 0 );
// Setting the initial state estimates to [0,0,0,0,0,0].
CvMat* x_k = cvCreateMat( 6, 1, CV_32FC1 );
cvZero(x_k);
// Setting the a posteriori estimate to zero.
cvZero(kalman->state_post);
// Creating the process noise vector.
CvMat* w_k = cvCreateMat( 2, 1, CV_32FC1 );
// Creating the measurement vector.
CvMat* z_k = cvCreateMat( 6, 1, CV_32FC1 );
cvZero( z_k );
// Initializing the state transition matrix.
float F_kalman[] = { 1,0,0,0.05,0,0, 0,1,0,0,0.05,0, 0,0,1,0,0,0.05,
0,0,0,1,0,0, 0,0,0,0,0,1 };
memcpy( kalman->transition_matrix->data.fl, F_kalman, sizeof(F_kalman));
// Initializing the other necessary parameters for the filter.
cvSetIdentity( kalman->measurement_matrix);
cvSetIdentity( kalman->process_noise_cov, cvRealScalar(1e-2) );
cvSetIdentity( kalman->measurement_noise_cov, cvRealScalar(1e-1) );
cvSetIdentity( kalman->error_cov_post, cvRealScalar(1));
// Updates the measurement vector with my sensor values, wich were in
the variable xyz (an array of CvScalar).
cvSetReal1D(z_k,0,xyz[i].val[0]);
cvSetReal1D(z_k,1,xyz[i].val[1]);
cvSetReal1D(z_k,2,xyz[i].val[2]);
cvKalmanPredict(kalman,0);
cvKalmanCorrect(kalman,z_k);
The problem is, when I run the code I get a "Unhandled exception at
0x55a3e757 in test.exe: 0xC00000FD: Stack overflow." at the
cvKalmanCorrect line.
Perhaps I've initialized one of the matrices to the wrong expected size,
but I'm really lost on how to check this.
Any thoughts?
I'm trying to implement a kalman filter for 3D tracking in OpenCV 2.2. The
state variables are the coordinates x,y,z followed by the velocities Vx,Vy
and Vz and I can only measure x,y and z.
I used an example from the book Learning OpenCV from O'reilly to get
started, but when I tried to adapt the example to my problem things got a
little confusing.
This is my implementation (I've tried to reduce the code to just the
relevant parts, and I've commented a lot to hopefully ease the reading).
CvKalman* kalman = cvCreateKalman( 6, 3, 0 );
// Setting the initial state estimates to [0,0,0,0,0,0].
CvMat* x_k = cvCreateMat( 6, 1, CV_32FC1 );
cvZero(x_k);
// Setting the a posteriori estimate to zero.
cvZero(kalman->state_post);
// Creating the process noise vector.
CvMat* w_k = cvCreateMat( 2, 1, CV_32FC1 );
// Creating the measurement vector.
CvMat* z_k = cvCreateMat( 6, 1, CV_32FC1 );
cvZero( z_k );
// Initializing the state transition matrix.
float F_kalman[] = { 1,0,0,0.05,0,0, 0,1,0,0,0.05,0, 0,0,1,0,0,0.05,
0,0,0,1,0,0, 0,0,0,0,0,1 };
memcpy( kalman->transition_matrix->data.fl, F_kalman, sizeof(F_kalman));
// Initializing the other necessary parameters for the filter.
cvSetIdentity( kalman->measurement_matrix);
cvSetIdentity( kalman->process_noise_cov, cvRealScalar(1e-2) );
cvSetIdentity( kalman->measurement_noise_cov, cvRealScalar(1e-1) );
cvSetIdentity( kalman->error_cov_post, cvRealScalar(1));
// Updates the measurement vector with my sensor values, wich were in
the variable xyz (an array of CvScalar).
cvSetReal1D(z_k,0,xyz[i].val[0]);
cvSetReal1D(z_k,1,xyz[i].val[1]);
cvSetReal1D(z_k,2,xyz[i].val[2]);
cvKalmanPredict(kalman,0);
cvKalmanCorrect(kalman,z_k);
The problem is, when I run the code I get a "Unhandled exception at
0x55a3e757 in test.exe: 0xC00000FD: Stack overflow." at the
cvKalmanCorrect line.
Perhaps I've initialized one of the matrices to the wrong expected size,
but I'm really lost on how to check this.
Any thoughts?
Best way to get a file's path and paste it in a text file
Best way to get a file's path and paste it in a text file
I am trying to write a program, or HTML page actually, to get a file's
path, then open a New E-mail in Microsoft Outlook (or the default e-mail
program the user uses) and paste the link in the new message.
The program will have 3 inputs, Firstname, Lastname, and Date, and a OK
button. It should look for the file with those three inputs as a file name
(ie.: John_Smith_22AUG13.pdf) and get the path to paste it in the email.
Now I am good at programming in javascript, but I'm sure this is not the
best way to do something like this, or even if it's possible.
I was wondering if someone has done something similar in the past and has
any advice or programming language I should use to do this. I would like
this to be a webpage like HTML but will be used internally so security is
not really an issue.
Anything helps! Thanks!
I am trying to write a program, or HTML page actually, to get a file's
path, then open a New E-mail in Microsoft Outlook (or the default e-mail
program the user uses) and paste the link in the new message.
The program will have 3 inputs, Firstname, Lastname, and Date, and a OK
button. It should look for the file with those three inputs as a file name
(ie.: John_Smith_22AUG13.pdf) and get the path to paste it in the email.
Now I am good at programming in javascript, but I'm sure this is not the
best way to do something like this, or even if it's possible.
I was wondering if someone has done something similar in the past and has
any advice or programming language I should use to do this. I would like
this to be a webpage like HTML but will be used internally so security is
not really an issue.
Anything helps! Thanks!
Variable assignments prints out output
Variable assignments prints out output
Well, when you assign something to a variable in Python:
a = 1
nothing visible happens, nothing is printed out.
But in this case:
import ftplib
ftp = ftplib.FTP("igscb.jpl.nasa.gov")
ftp.login()
a=ftp.retrlines('LIST')
When the last line is executed, this is printed out:
d--X--X--X--X 2 0 0 4096 Nov 29 2001 bin
d--X--X--X--X 2 0 0 4096 Nov 29 2001 etc
which is the information related to the FTP directory.
How comes that a variable assignment yields an output?
Well, when you assign something to a variable in Python:
a = 1
nothing visible happens, nothing is printed out.
But in this case:
import ftplib
ftp = ftplib.FTP("igscb.jpl.nasa.gov")
ftp.login()
a=ftp.retrlines('LIST')
When the last line is executed, this is printed out:
d--X--X--X--X 2 0 0 4096 Nov 29 2001 bin
d--X--X--X--X 2 0 0 4096 Nov 29 2001 etc
which is the information related to the FTP directory.
How comes that a variable assignment yields an output?
Dequeue a queued OpenCL kernel
Dequeue a queued OpenCL kernel
I need to dequeue a queued OpenCL kernel, if order to free GPU resources.
Is it even possible?
What I am doing is queueing a kernel and a I/O copy. Then check in the
host side if this result is correct or not. But since 70% of the time is
not correct, I queue another run while I check for the result in the host
(CPU+GPU is parallel!). This way the GPU is 100% in use.
However, as soon as I found that the result is correct I can't cancel the
ongoing kernel. With is wasting GPU resources.
I am using many OpenCL queues and kernels in parallel, so this is
effectively slowing me down and putting the bottleneck in the GPU. Is it
even possible to dequeue that kernel?
Thanks.
I need to dequeue a queued OpenCL kernel, if order to free GPU resources.
Is it even possible?
What I am doing is queueing a kernel and a I/O copy. Then check in the
host side if this result is correct or not. But since 70% of the time is
not correct, I queue another run while I check for the result in the host
(CPU+GPU is parallel!). This way the GPU is 100% in use.
However, as soon as I found that the result is correct I can't cancel the
ongoing kernel. With is wasting GPU resources.
I am using many OpenCL queues and kernels in parallel, so this is
effectively slowing me down and putting the bottleneck in the GPU. Is it
even possible to dequeue that kernel?
Thanks.
Wednesday, 21 August 2013
How to reading part of string in javascript
How to reading part of string in javascript
I have a string btnHome. How can I remove btn and only get Home from it in
javascript / jQuery?
I used slice like str.slice(3, -1) but it gives me Hom whereas I need Home.
I have a string btnHome. How can I remove btn and only get Home from it in
javascript / jQuery?
I used slice like str.slice(3, -1) but it gives me Hom whereas I need Home.
Is there a MACRO to test the arch of Intel CPU?
Is there a MACRO to test the arch of Intel CPU?
Such that one can write different code path using arch-specific
instructions in a single file.
Such that one can write different code path using arch-specific
instructions in a single file.
Get username from the database from current session
Get username from the database from current session
So been looking on the web for some time and have attempted to follow
examples...
What I want to do is get the user to login and then a session to start
which I have and have tested and it does work, however I'm having trouble
getting the username or any other item of data from the database.
The user logs in with the username and password. They are then directed to
another page with this code...
<?php
session_start();
if(!session_is_registered(user_name));
$con = mysql_connect("****","****","****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//Finds database
mysql_select_db("****", $con);
$result = mysql_query("SELECT * FROM fyp_users;");
$first_name = $_SESSION['first_name'];
$_SESSION['views']=200;
header('location:../profile.php');
?>
The Session views thing was just a test and that works find and displays
the number when the user is logged in. I have then attempted to do the
first_name session.
This is the page that it then redirects too...
<?php
$con = mysql_connect("****","****","****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//Finds database
mysql_select_db("****", $con);
?>
<?php
session_start( );
//$result = mysql_query("SELECT * FROM fyp_users;");
?>
Some HTML....
<?php
echo "Pageviews=". $_SESSION['views'];
echo "Welcome=" . $_SESSION['$first_name']
?>
How it's not displaying the name, I know no if it's an easy fix or not,
can anybody help me?
Thanks James
So been looking on the web for some time and have attempted to follow
examples...
What I want to do is get the user to login and then a session to start
which I have and have tested and it does work, however I'm having trouble
getting the username or any other item of data from the database.
The user logs in with the username and password. They are then directed to
another page with this code...
<?php
session_start();
if(!session_is_registered(user_name));
$con = mysql_connect("****","****","****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//Finds database
mysql_select_db("****", $con);
$result = mysql_query("SELECT * FROM fyp_users;");
$first_name = $_SESSION['first_name'];
$_SESSION['views']=200;
header('location:../profile.php');
?>
The Session views thing was just a test and that works find and displays
the number when the user is logged in. I have then attempted to do the
first_name session.
This is the page that it then redirects too...
<?php
$con = mysql_connect("****","****","****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//Finds database
mysql_select_db("****", $con);
?>
<?php
session_start( );
//$result = mysql_query("SELECT * FROM fyp_users;");
?>
Some HTML....
<?php
echo "Pageviews=". $_SESSION['views'];
echo "Welcome=" . $_SESSION['$first_name']
?>
How it's not displaying the name, I know no if it's an easy fix or not,
can anybody help me?
Thanks James
windows 8 minor version returning 0 instead of 2
windows 8 minor version returning 0 instead of 2
I have code in C++ that has the purpose of finding the Windows version:
OSVERSIONINFOEX osvi;
BOOL bOsVersionInfoEx;
int iRet = OS_UNKNOWN;
ZeroMemory ( & osvi, sizeof ( OSVERSIONINFOEX ) );
osvi.dwOSVersionInfoSize = sizeof ( OSVERSIONINFOEX );
if ( !( bOsVersionInfoEx = GetVersionEx ( ( OSVERSIONINFO * ) & osvi ) ) )
{
osvi.dwOSVersionInfoSize = sizeof ( OSVERSIONINFO );
if ( ! GetVersionEx ( ( OSVERSIONINFO * ) & osvi ) )
return OS_UNKNOWN;
}
//the rest is irrelevant ...
iRet will return an internal enum value identifying the Windows version.
It will be ajusted according to the values returned in osvi.dwPlatformId,
osvi.dwMajorVersion and osvi.dwMinorVersion.
According to MSDN, for Windows 8 the value of MajorVersion is 6 and the
value for MinorVersion is 2.
I have this code compiled in a dll and the code actually works if I call
the DLL from a test EXE program.
But if I call THE SAME CODE FROM THE SAME DLL from within a Custom Action
within a windows installer package (MSI), GetVersionEx() returns 0 for the
MinorVersion field.
Did anybody else experience this bug? Does anybody know how to work around
it?
I have code in C++ that has the purpose of finding the Windows version:
OSVERSIONINFOEX osvi;
BOOL bOsVersionInfoEx;
int iRet = OS_UNKNOWN;
ZeroMemory ( & osvi, sizeof ( OSVERSIONINFOEX ) );
osvi.dwOSVersionInfoSize = sizeof ( OSVERSIONINFOEX );
if ( !( bOsVersionInfoEx = GetVersionEx ( ( OSVERSIONINFO * ) & osvi ) ) )
{
osvi.dwOSVersionInfoSize = sizeof ( OSVERSIONINFO );
if ( ! GetVersionEx ( ( OSVERSIONINFO * ) & osvi ) )
return OS_UNKNOWN;
}
//the rest is irrelevant ...
iRet will return an internal enum value identifying the Windows version.
It will be ajusted according to the values returned in osvi.dwPlatformId,
osvi.dwMajorVersion and osvi.dwMinorVersion.
According to MSDN, for Windows 8 the value of MajorVersion is 6 and the
value for MinorVersion is 2.
I have this code compiled in a dll and the code actually works if I call
the DLL from a test EXE program.
But if I call THE SAME CODE FROM THE SAME DLL from within a Custom Action
within a windows installer package (MSI), GetVersionEx() returns 0 for the
MinorVersion field.
Did anybody else experience this bug? Does anybody know how to work around
it?
SUM (some_column) WHERE some_column matches
SUM (some_column) WHERE some_column matches
So I have a table, and I'm trying to get the SUM(activity_weight) WHERE
activity_typeid is unique.
Each competition has an unlimited amount of activity_typeid's.
As you can see in my code below, I wonder if there is some SQL function to
find the SUM of something WHERE the id is unique for example?
THANKS FOR ANY HELP IN ADVANCE!
I've attached a photo of my table and desired output below
SELECT a.userid, u.name, u.profilePic ,
SUM(activity_weight) AS totalPoints ,
//sum the points when the activity_typeid is unique and make an extra
column for each of those sums
SUM(CASE WHEN activity_typeid //is unique// THEN activity_weight ELSE
NULL END) AS specific_points ,
FROM activity_entries a INNER JOIN users1 u ON u.id = a.userid
WHERE competitionId = '$competitionId' GROUP BY a.userid ORDER BY
totalPoints
So I have a table, and I'm trying to get the SUM(activity_weight) WHERE
activity_typeid is unique.
Each competition has an unlimited amount of activity_typeid's.
As you can see in my code below, I wonder if there is some SQL function to
find the SUM of something WHERE the id is unique for example?
THANKS FOR ANY HELP IN ADVANCE!
I've attached a photo of my table and desired output below
SELECT a.userid, u.name, u.profilePic ,
SUM(activity_weight) AS totalPoints ,
//sum the points when the activity_typeid is unique and make an extra
column for each of those sums
SUM(CASE WHEN activity_typeid //is unique// THEN activity_weight ELSE
NULL END) AS specific_points ,
FROM activity_entries a INNER JOIN users1 u ON u.id = a.userid
WHERE competitionId = '$competitionId' GROUP BY a.userid ORDER BY
totalPoints
Apache Tomcat 7---MITM on HTTP to HTTPS redirect
Apache Tomcat 7---MITM on HTTP to HTTPS redirect
I have the following in server.xml, to redirect users from HTTP to HTTPS:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
server="Apache" redirectPort="443" />
And in the web service's web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected area</web-resource-name>
<url-pattern>/topsecret/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>premiumrole</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<deny-uncovered-http-methods />
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
Server authenticates to the user through certificate, user authenticates
to server using credentials. Under these configurations, would it be
possible to perform a MITM attack when the redirect from HTTP to HTTPS
happens? (e.g., to capture the user's credentials)
I have the following in server.xml, to redirect users from HTTP to HTTPS:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
server="Apache" redirectPort="443" />
And in the web service's web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>Protected area</web-resource-name>
<url-pattern>/topsecret/*</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>premiumrole</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<deny-uncovered-http-methods />
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
Server authenticates to the user through certificate, user authenticates
to server using credentials. Under these configurations, would it be
possible to perform a MITM attack when the redirect from HTTP to HTTPS
happens? (e.g., to capture the user's credentials)
Tuesday, 20 August 2013
How to get arp tables from switch to server mysql database using snmp
How to get arp tables from switch to server mysql database using snmp
I would like to obtain ARP tables from a switch to a syslog server(Ubuntu
12.04 LTS). I have done some research on how to do it and i decided to use
SNMP. I have done some research and i know that my server will be the
manager whereas the switch will act as an agent.My problem is, i am not
quite sure of the process of getting the arp tables and having them
directed to the mysql database in my server.
I would like to obtain ARP tables from a switch to a syslog server(Ubuntu
12.04 LTS). I have done some research on how to do it and i decided to use
SNMP. I have done some research and i know that my server will be the
manager whereas the switch will act as an agent.My problem is, i am not
quite sure of the process of getting the arp tables and having them
directed to the mysql database in my server.
Opening a specific contact in a list Android
Opening a specific contact in a list Android
We are developing a portion of our app that displays a persons name in a
list view and they can click on the name and it goes to a phone list of
all people but I want to be able to take the user straight to the selected
contact not just the full list on contacts.
Any thoughts on how to achieve this would be helpful
Stephen
We are developing a portion of our app that displays a persons name in a
list view and they can click on the name and it goes to a phone list of
all people but I want to be able to take the user straight to the selected
contact not just the full list on contacts.
Any thoughts on how to achieve this would be helpful
Stephen
How to debug a website on Android?
How to debug a website on Android?
I don't have an Android phone or tablet, and it seems that on some Android
devices using stock browser my website is stuck for half a minute until it
loads.
I've been testing with various emulators found online like BrowserStack,
etc. The browser is just stuck for a while. That's not the case for iPhone
or desktop.
How can I debug this issue? How can I see a developer console or errors or
figure out what's causing the slowness?
I don't have an Android phone or tablet, and it seems that on some Android
devices using stock browser my website is stuck for half a minute until it
loads.
I've been testing with various emulators found online like BrowserStack,
etc. The browser is just stuck for a while. That's not the case for iPhone
or desktop.
How can I debug this issue? How can I see a developer console or errors or
figure out what's causing the slowness?
Error handling between button and bean method
Error handling between button and bean method
I have a jsf button that calls a bean method called generateLicense. This
bean method returns a string to perform a redirect, like this
"/licenseGenerated.xhtml?faces-redirect=true"
This method is supposed to do several back-end calls based on the user's
input. Now, this means that in I have to add some error handling. Here's
the behavior I need.
The user accesses the application and is in the main.xhtml page. The user
inputs the value and clicks the button. If the whole procedure works
correctly, then the user should be redirected to the
/licenseGenerated.xhtml page. Otherwise, in case an error happened, I
don't need a redirect. What I need is to render a jsf component that
contains an error message on the main.xhtml page.
So, what should the generateLicense method return in case of an error, and
what would the button's jsf code be like?
Thanks for the help!
I have a jsf button that calls a bean method called generateLicense. This
bean method returns a string to perform a redirect, like this
"/licenseGenerated.xhtml?faces-redirect=true"
This method is supposed to do several back-end calls based on the user's
input. Now, this means that in I have to add some error handling. Here's
the behavior I need.
The user accesses the application and is in the main.xhtml page. The user
inputs the value and clicks the button. If the whole procedure works
correctly, then the user should be redirected to the
/licenseGenerated.xhtml page. Otherwise, in case an error happened, I
don't need a redirect. What I need is to render a jsf component that
contains an error message on the main.xhtml page.
So, what should the generateLicense method return in case of an error, and
what would the button's jsf code be like?
Thanks for the help!
Will Log writing in text file affect performance of a website?
Will Log writing in text file affect performance of a website?
I am have a asp website.I am writing log files to get total time span for
the page.Is writing log in txt files affect the performance of my
program?I am logging this in events like OnUnload.
private DateTime _startTime;
private DateTime _endTime;
string _page;
_endTime = CommonFunctions.getTodayDateTime();
TimeSpan span = _endTime - _startTime;
WriteLog(string.Format("The total time span for the '{0}' is {1}ms",
_page, span.TotalMilliseconds));
I am have a asp website.I am writing log files to get total time span for
the page.Is writing log in txt files affect the performance of my
program?I am logging this in events like OnUnload.
private DateTime _startTime;
private DateTime _endTime;
string _page;
_endTime = CommonFunctions.getTodayDateTime();
TimeSpan span = _endTime - _startTime;
WriteLog(string.Format("The total time span for the '{0}' is {1}ms",
_page, span.TotalMilliseconds));
WPF DataGrid, converting value in cell
WPF DataGrid, converting value in cell
I have DataGrid with column populated by value of field xxx:
<DataGridTextColumn Binding="{Binding Path=xxx, Mode=OneWay}"
Width="140" Header="Some Header"/>
I am now allowed to make any changes to class being used to populate this
DataGrid. I created MyConverter but I do not know how I should modify my
xaml to get it working. Any help on this please?
Thank you!
I have DataGrid with column populated by value of field xxx:
<DataGridTextColumn Binding="{Binding Path=xxx, Mode=OneWay}"
Width="140" Header="Some Header"/>
I am now allowed to make any changes to class being used to populate this
DataGrid. I created MyConverter but I do not know how I should modify my
xaml to get it working. Any help on this please?
Thank you!
Monday, 19 August 2013
Searching listview with custom ArrayAdapter
Searching listview with custom ArrayAdapter
I have a listview that has a custom adapter, and I was trying to make it
searchable using an Action Item. When I click the search icon in the
action bar, the edit text comes up, but when I enter text and click "done"
on the keyboard, nothing happens.
Here is the main class:
public class ItemId extends SherlockListActivity {
EditText editsearch;
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context ctx = getApplication();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.item_ids);
String[] ids = res.getStringArray(R.array.item_names);
TypedArray icons = res.obtainTypedArray(R.array.item_images);
adapter = new ItemIDAdapter(ctx, R.layout.idslistitem, ids,
options, icons);
setListAdapter(adapter );
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Get the options menu view from menu.xml in menu folder
getSupportMenuInflater().inflate(R.menu.items_menu, menu);
// Locate the EditText in menu.xml
editsearch = (EditText)
menu.findItem(R.id.menu_search).getActionView();
// Capture Text in EditText
editsearch.addTextChangedListener(textWatcher);
// Show the search menu item in menu.xml
MenuItem menuSearch = menu.findItem(R.id.menu_search);
menuSearch.setOnActionExpandListener(new
OnActionExpandListener() {
// Menu Action Collapse
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Empty EditText to remove text filtering
editsearch.setText("");
editsearch.clearFocus();
return true;
}
// Menu Action Expand
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Focus on EditText
editsearch.requestFocus();
// Force the keyboard to show on EditText focus
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
return true;
}
});
// Show the settings menu item in menu.xml
MenuItem menuSettings = menu.findItem(R.id.home);
// Capture menu item clicks
menuSettings.setOnMenuItemClickListener(new
OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent2 = new Intent(ItemId.this, Home.class);
startActivity(intent2);
return true;
}
});
return true;
}
// EditText TextWatcher
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.getFilter().filter(text);
};
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int
arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
};
}
And here is the Adapter class:
public class ItemIDAdapter extends ArrayAdapter<String> implements
Filterable {
public LayoutInflater mInflater;
public String[] mStrings;
public String[] mIds;
public TypedArray mIcons;
public int mViewResourceId;
public ItemIDAdapter(Context ctx, int viewResourceId,
String[] strings, String[] ids, TypedArray icons) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIds = ids;
mIcons = icons;
mViewResourceId = viewResourceId;
}
@Override
public int getCount() {
return mStrings.length;
}
@Override
public String getItem(int position) {
return mStrings[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
TextView tv1 = (TextView)convertView.findViewById(R.id.itemids);
tv1.setText(mIds[position]);
return convertView;
}
}
If anyone has any idea as to why nothing happens when I search, or knows
how to fix it, it'd be greatly appreciated. Thanks!!
I have a listview that has a custom adapter, and I was trying to make it
searchable using an Action Item. When I click the search icon in the
action bar, the edit text comes up, but when I enter text and click "done"
on the keyboard, nothing happens.
Here is the main class:
public class ItemId extends SherlockListActivity {
EditText editsearch;
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context ctx = getApplication();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.item_ids);
String[] ids = res.getStringArray(R.array.item_names);
TypedArray icons = res.obtainTypedArray(R.array.item_images);
adapter = new ItemIDAdapter(ctx, R.layout.idslistitem, ids,
options, icons);
setListAdapter(adapter );
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Get the options menu view from menu.xml in menu folder
getSupportMenuInflater().inflate(R.menu.items_menu, menu);
// Locate the EditText in menu.xml
editsearch = (EditText)
menu.findItem(R.id.menu_search).getActionView();
// Capture Text in EditText
editsearch.addTextChangedListener(textWatcher);
// Show the search menu item in menu.xml
MenuItem menuSearch = menu.findItem(R.id.menu_search);
menuSearch.setOnActionExpandListener(new
OnActionExpandListener() {
// Menu Action Collapse
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Empty EditText to remove text filtering
editsearch.setText("");
editsearch.clearFocus();
return true;
}
// Menu Action Expand
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Focus on EditText
editsearch.requestFocus();
// Force the keyboard to show on EditText focus
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
return true;
}
});
// Show the settings menu item in menu.xml
MenuItem menuSettings = menu.findItem(R.id.home);
// Capture menu item clicks
menuSettings.setOnMenuItemClickListener(new
OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent2 = new Intent(ItemId.this, Home.class);
startActivity(intent2);
return true;
}
});
return true;
}
// EditText TextWatcher
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.getFilter().filter(text);
};
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int
arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
};
}
And here is the Adapter class:
public class ItemIDAdapter extends ArrayAdapter<String> implements
Filterable {
public LayoutInflater mInflater;
public String[] mStrings;
public String[] mIds;
public TypedArray mIcons;
public int mViewResourceId;
public ItemIDAdapter(Context ctx, int viewResourceId,
String[] strings, String[] ids, TypedArray icons) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIds = ids;
mIcons = icons;
mViewResourceId = viewResourceId;
}
@Override
public int getCount() {
return mStrings.length;
}
@Override
public String getItem(int position) {
return mStrings[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
TextView tv1 = (TextView)convertView.findViewById(R.id.itemids);
tv1.setText(mIds[position]);
return convertView;
}
}
If anyone has any idea as to why nothing happens when I search, or knows
how to fix it, it'd be greatly appreciated. Thanks!!
TikZ current page.north west shifted ~4pts?
TikZ current page.north west shifted ~4pts?
I'm trying to draw a background grid on a page, but current page.north
west is shifted down and to the right ~4pt. Anyone know how I can get the
exact north west corner of the page?
Here's an example:
\documentclass{article}
\setlength{\parindent}{0pt}
\usepackage[papersize={2.5in,0.5in},margin=0in]{geometry}
\usepackage{tikz}
\pagestyle{empty}
\begin{document}%
\begin{tikzpicture}[remember picture,overlay]%
\node at (current page.north west) [anchor=north west]{%
\tikz{\draw[step=0.25in,color=red,thick] (0,0)
grid (\paperwidth,\paperheight);}%
};%
\end{tikzpicture}%
\begin{minipage}{\linewidth}%
In Ti\emph{k}Z, \texttt{current page.north west} is shifted $\sim$4pt
right and down%
\end{minipage}%
\end{document}
I'm trying to draw a background grid on a page, but current page.north
west is shifted down and to the right ~4pt. Anyone know how I can get the
exact north west corner of the page?
Here's an example:
\documentclass{article}
\setlength{\parindent}{0pt}
\usepackage[papersize={2.5in,0.5in},margin=0in]{geometry}
\usepackage{tikz}
\pagestyle{empty}
\begin{document}%
\begin{tikzpicture}[remember picture,overlay]%
\node at (current page.north west) [anchor=north west]{%
\tikz{\draw[step=0.25in,color=red,thick] (0,0)
grid (\paperwidth,\paperheight);}%
};%
\end{tikzpicture}%
\begin{minipage}{\linewidth}%
In Ti\emph{k}Z, \texttt{current page.north west} is shifted $\sim$4pt
right and down%
\end{minipage}%
\end{document}
Eclipse file search: how can search a file with both the word A and the word B?
Eclipse file search: how can search a file with both the word A and the
word B?
I want to search a file in a project in Eclipse, which has both the word A
and the word B.
How can I search it?
From stackoverflow.com, I only find the solution to search or option, such
as A|B.
Thanks.
word B?
I want to search a file in a project in Eclipse, which has both the word A
and the word B.
How can I search it?
From stackoverflow.com, I only find the solution to search or option, such
as A|B.
Thanks.
How to calculate unicod URLs length for SEO?
How to calculate unicod URLs length for SEO?
As you know, URL Length is important for SEO.
There is a ambiguity in URL length calculation for Unicode URLs.
How search engines view my Unicode URLs?
For Example the following URLs are same, which of them are calculated by
search engines?
1)
http://aroushaafzar.ir/%D8%AE%D8%AF%D9%85%D8%A7%D8%AA/%D8%B7%D8%B1%D8%A7%D8%AD%DB%8C-%D9%88%D8%A8-%D8%B3%D8%A7%DB%8C%D8%AA.html
=> Length: 47 characters
2)
http://aroushaafzar.ir/%D8%AE%D8%AF%D9%85%D8%A7%D8%AA/%D8%B7%D8%B1%D8%A7%D8%AD%DB%8C-%D9%88%D8%A8-%D8%B3%D8%A7%DB%8C%D8%AA.html
=> Length: 120 characters
Please help me and offer your reference please.
Thanks in advance.
As you know, URL Length is important for SEO.
There is a ambiguity in URL length calculation for Unicode URLs.
How search engines view my Unicode URLs?
For Example the following URLs are same, which of them are calculated by
search engines?
1)
http://aroushaafzar.ir/%D8%AE%D8%AF%D9%85%D8%A7%D8%AA/%D8%B7%D8%B1%D8%A7%D8%AD%DB%8C-%D9%88%D8%A8-%D8%B3%D8%A7%DB%8C%D8%AA.html
=> Length: 47 characters
2)
http://aroushaafzar.ir/%D8%AE%D8%AF%D9%85%D8%A7%D8%AA/%D8%B7%D8%B1%D8%A7%D8%AD%DB%8C-%D9%88%D8%A8-%D8%B3%D8%A7%DB%8C%D8%AA.html
=> Length: 120 characters
Please help me and offer your reference please.
Thanks in advance.
Cannot resize Image with tkinter
Cannot resize Image with tkinter
I am trying to create a tkinter project in python 2.7, where the user can
resize the window, and everything inside the window will scale with it.
This means the canvas, the shapes in the canvas and most importantly the
PhotoImages will scale with the window. My problem, is for the life of me
I cannot get my images to resize properly. I know that subsample and zoom
exist for this purpose, but first of all
plantImage = PhotoImage(file="images/Arable_Cell.gif")
plantImage.subsample(2, 2)
canvas.create_image(0, 0, anchor=NW, image=plantImage)
Makes no noticeable change in a 50x50 pixel image and same for zoom(2, 2).
It is important to note I know PIL exists but for the purposes of this
project I cannot download any extra libraries. So what am I doing wrong?
I am trying to create a tkinter project in python 2.7, where the user can
resize the window, and everything inside the window will scale with it.
This means the canvas, the shapes in the canvas and most importantly the
PhotoImages will scale with the window. My problem, is for the life of me
I cannot get my images to resize properly. I know that subsample and zoom
exist for this purpose, but first of all
plantImage = PhotoImage(file="images/Arable_Cell.gif")
plantImage.subsample(2, 2)
canvas.create_image(0, 0, anchor=NW, image=plantImage)
Makes no noticeable change in a 50x50 pixel image and same for zoom(2, 2).
It is important to note I know PIL exists but for the purposes of this
project I cannot download any extra libraries. So what am I doing wrong?
Sunday, 18 August 2013
A calculus problem about extreme value
A calculus problem about extreme value
Let $g(x,y)=0$ be a closed curve, and $g(x,y)<0$ is the interior of the
curve, and the interior is a convex set. For example, $g(x,y)=x^2+y^2-1=0$
is a closed curve(circle), and its interior is a convex set.
My question is, given a point $(x_0,y_0)$ satisfying $g(x_0,y_0)>0$, what
is the maximum of the function $f(x,y)=\nabla
g(x_0,y_0)\cdot(x,y)-g(x,y)$?
If we use the derivative, $\nabla f=\nabla g(x_0,y_0)-\nabla g(x,y)=0$,
then $(x,y)=(x_0,y_0)$ is the root of $\nabla f=0$, but how to prove the
root is the only one? and how to prove the stationary point is the maximum
point?
I think the key to solve this problem is to find out the relationship
between the convex set, $g(x,y)=0$, and its (second) derivative.
Let $g(x,y)=0$ be a closed curve, and $g(x,y)<0$ is the interior of the
curve, and the interior is a convex set. For example, $g(x,y)=x^2+y^2-1=0$
is a closed curve(circle), and its interior is a convex set.
My question is, given a point $(x_0,y_0)$ satisfying $g(x_0,y_0)>0$, what
is the maximum of the function $f(x,y)=\nabla
g(x_0,y_0)\cdot(x,y)-g(x,y)$?
If we use the derivative, $\nabla f=\nabla g(x_0,y_0)-\nabla g(x,y)=0$,
then $(x,y)=(x_0,y_0)$ is the root of $\nabla f=0$, but how to prove the
root is the only one? and how to prove the stationary point is the maximum
point?
I think the key to solve this problem is to find out the relationship
between the convex set, $g(x,y)=0$, and its (second) derivative.
python pyinotify to monitor the specified suffix files in a dir
python pyinotify to monitor the specified suffix files in a dir
pI want to monitor a dir , and the dir has sub dirs and in subdir there
are somes files with code.md/code. (maybe there are some other files, such
as *.swp...)/p pI only want to monitor the .md files, I have read the doc,
and there is only a codeExcludeFilter/code, and in the issue : a
href=https://github.com/seb-m/pyinotify/issues/31
rel=nofollowhttps://github.com/seb-m/pyinotify/issues/31/a says, only dir
can be filter but not files./p pNow what I do is to filter in
codeprocess_*/code functions to check the codeevent.name/code by
codefnmatch/code./p pSo if I only want to monitor the specified suffix
files, is there a better way? Thanks./p pThis is the main code I have
written:/p precode!/usr/bin/env python # -*- coding: utf-8 -*- import
pyinotify import fnmatch def suffix_filter(fn): suffixes = [*.md,
*.markdown] for suffix in suffixes: if fnmatch.fnmatch(fn, suffix): return
False return True class EventHandler(pyinotify.ProcessEvent): def
process_IN_CREATE(self, event): if not suffix_filter(event.name): print
Creating:, event.pathname def process_IN_DELETE(self, event): if not
suffix_filter(event.name): print Removing:, event.pathname def
process_IN_MODIFY(self, event): if not suffix_filter(event.name): print
Modifing:, event.pathname def process_default(self, event): print
Default:, event.pathname /code/pre
pI want to monitor a dir , and the dir has sub dirs and in subdir there
are somes files with code.md/code. (maybe there are some other files, such
as *.swp...)/p pI only want to monitor the .md files, I have read the doc,
and there is only a codeExcludeFilter/code, and in the issue : a
href=https://github.com/seb-m/pyinotify/issues/31
rel=nofollowhttps://github.com/seb-m/pyinotify/issues/31/a says, only dir
can be filter but not files./p pNow what I do is to filter in
codeprocess_*/code functions to check the codeevent.name/code by
codefnmatch/code./p pSo if I only want to monitor the specified suffix
files, is there a better way? Thanks./p pThis is the main code I have
written:/p precode!/usr/bin/env python # -*- coding: utf-8 -*- import
pyinotify import fnmatch def suffix_filter(fn): suffixes = [*.md,
*.markdown] for suffix in suffixes: if fnmatch.fnmatch(fn, suffix): return
False return True class EventHandler(pyinotify.ProcessEvent): def
process_IN_CREATE(self, event): if not suffix_filter(event.name): print
Creating:, event.pathname def process_IN_DELETE(self, event): if not
suffix_filter(event.name): print Removing:, event.pathname def
process_IN_MODIFY(self, event): if not suffix_filter(event.name): print
Modifing:, event.pathname def process_default(self, event): print
Default:, event.pathname /code/pre
Change Default Directory in SharePoint Designer 2007
Change Default Directory in SharePoint Designer 2007
Despite it being an older editor, I still use Microsoft's SharePoint
Designer 2007 for local development, I guess because I'm used to the
layout, color coding, and ease of use. I know there are other development
packages like Joomla! and Drupal, and I know there are lots of editors
that recognize PHP code and such, but I prefer SP Designer 2007 simply
because I've used it since it first came out and I like it. However, I
have never figured out how to change the default directory. Upon opening
the editor, the default folder it shows is located at
c:/users/owner/documents/my web sites/. How would I go about changing that
to a different path, like c:/webpages/?
Thanks, Harold
Despite it being an older editor, I still use Microsoft's SharePoint
Designer 2007 for local development, I guess because I'm used to the
layout, color coding, and ease of use. I know there are other development
packages like Joomla! and Drupal, and I know there are lots of editors
that recognize PHP code and such, but I prefer SP Designer 2007 simply
because I've used it since it first came out and I like it. However, I
have never figured out how to change the default directory. Upon opening
the editor, the default folder it shows is located at
c:/users/owner/documents/my web sites/. How would I go about changing that
to a different path, like c:/webpages/?
Thanks, Harold
Connecting android tablet as testing device
Connecting android tablet as testing device
I have a problem related to connectivity between my desktop (Windows) and
tablet (Android 4.1). I bought a new device (Colorovo City Tab Vision 7)
and now I want to use it for testing of my applications, because emulation
of android is very slow on my computer, although I forced it to create
snapshot every run. I have downloaded SDK with Google drivers and also
some unofficial drivers I found on web.
When I connect my device, it first appears 'Other device' (label is
CTVision7) and it's marked as unknown. I tried to install drivers (Google)
for it, but windows said that they aren't suitable for my device, as it's
not able to find them in specified directory. After these attempts I tried
unofficial drivers. Their installation worked and now my device appears as
Android phone, what seems to be good. But when I run adb devices or launch
application in eclipse, there's no avaible device. I have turned USB
debugging on, so it should work.
Am I missing some step to make my device avaible for debugging, or are my
drivers wrong? Is there any way to get drivers which surely work?
I have a problem related to connectivity between my desktop (Windows) and
tablet (Android 4.1). I bought a new device (Colorovo City Tab Vision 7)
and now I want to use it for testing of my applications, because emulation
of android is very slow on my computer, although I forced it to create
snapshot every run. I have downloaded SDK with Google drivers and also
some unofficial drivers I found on web.
When I connect my device, it first appears 'Other device' (label is
CTVision7) and it's marked as unknown. I tried to install drivers (Google)
for it, but windows said that they aren't suitable for my device, as it's
not able to find them in specified directory. After these attempts I tried
unofficial drivers. Their installation worked and now my device appears as
Android phone, what seems to be good. But when I run adb devices or launch
application in eclipse, there's no avaible device. I have turned USB
debugging on, so it should work.
Am I missing some step to make my device avaible for debugging, or are my
drivers wrong? Is there any way to get drivers which surely work?
Remove 'X' from vim tab bar
Remove 'X' from vim tab bar
When using multiple tabs in vim, there is a bar at the top displaying the
tabs. At the far right of that bar there is an X. This is used to close
the current tab if use of the mouse is enabled; however, I don't use the
mouse in vim, so for me it is a bit of useless cruft taking up space.
With many tabs open, vim doesn't display the whole filename in each files,
only the last few characters. Getting rid of this X -- and the small
amount of empty space that seems to be reserved next to it -- would free
up a little bit of space. I would be interested in a method to simply turn
it invisible, but the ideal answer would give me a way to remove it
entirely and free up this space.
When using multiple tabs in vim, there is a bar at the top displaying the
tabs. At the far right of that bar there is an X. This is used to close
the current tab if use of the mouse is enabled; however, I don't use the
mouse in vim, so for me it is a bit of useless cruft taking up space.
With many tabs open, vim doesn't display the whole filename in each files,
only the last few characters. Getting rid of this X -- and the small
amount of empty space that seems to be reserved next to it -- would free
up a little bit of space. I would be interested in a method to simply turn
it invisible, but the ideal answer would give me a way to remove it
entirely and free up this space.
NTFS Drive Write Access denied
NTFS Drive Write Access denied
In ubuntu I tried to paly(?) with the permission of NTFS drive. I
installed an app from Software Center named NTFS Configuration Tool. After
using it a few times, that one started to close and wasn't responding. So
I removed the app.
The next day I opened my PC, started the Torrent client Transmission. That
was a huge file so I downloaded that in my NTFS drive. So I resumed the
torrent, but it said Permission denied to write. :( It seems like all of
my NTFS drives become read-only. I can't write anything.
How to fix this permanently?
(I've run Transmission using sudo command, its working, but using sudo
command everywhere isn't the solution, I need it back like it was before.
Please help.)
Here is my fstab contents:
In ubuntu I tried to paly(?) with the permission of NTFS drive. I
installed an app from Software Center named NTFS Configuration Tool. After
using it a few times, that one started to close and wasn't responding. So
I removed the app.
The next day I opened my PC, started the Torrent client Transmission. That
was a huge file so I downloaded that in my NTFS drive. So I resumed the
torrent, but it said Permission denied to write. :( It seems like all of
my NTFS drives become read-only. I can't write anything.
How to fix this permanently?
(I've run Transmission using sudo command, its working, but using sudo
command everywhere isn't the solution, I need it back like it was before.
Please help.)
Here is my fstab contents:
Why do font substitutions need to happen even with vector fonts?
Why do font substitutions need to happen even with vector fonts?
I often get errors saying Size substitutions with differences up to ...
have occurred, even while using fonts like Palatino, which as far as I
understand are defined to be arbitrarily scalable. Why do such
substitutions happen at all?
Also, is there a systematic way of figuring out which variation of the
font is causing the problems, and to manually force the compiler to
include the correct sizes?
I have very basic knowledge about how fonts are handled in the TeX
backend, so if my questions don't make sense at all, please feel free to
enlighten me.
I often get errors saying Size substitutions with differences up to ...
have occurred, even while using fonts like Palatino, which as far as I
understand are defined to be arbitrarily scalable. Why do such
substitutions happen at all?
Also, is there a systematic way of figuring out which variation of the
font is causing the problems, and to manually force the compiler to
include the correct sizes?
I have very basic knowledge about how fonts are handled in the TeX
backend, so if my questions don't make sense at all, please feel free to
enlighten me.
Saturday, 17 August 2013
Pulling from bitbucket to Xcode
Pulling from bitbucket to Xcode
I am using bitbucket git repository so I can work on my iMac and Macbook.
I have all my files on the bitbucket repository but when I pull to my
Macbook and open the project I can't see all the files although the files
are found in the finder.
Do you guys know how can I fix that?
Regards.
I am using bitbucket git repository so I can work on my iMac and Macbook.
I have all my files on the bitbucket repository but when I pull to my
Macbook and open the project I can't see all the files although the files
are found in the finder.
Do you guys know how can I fix that?
Regards.
Autolayout, programed vs interface builder
Autolayout, programed vs interface builder
Just to add a view that lives in the same parent view as the other two
related views.
self.vDist = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 42, 21)];
[self.vDist setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:self.vDist];
NSLayoutConstraint *lc;
lc = [NSLayoutConstraint constraintWithItem:self.vDist
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0
constant:20.0];
[self.view addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.vDist
attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0
constant:20.0];
[self.view addConstraint:lc];
Then, I create the small squared view on top
/*********************** video view */
self.videoView = [[UIView alloc] initWithFrame:CGRectMake(90, 20, 140, 140)];
[self.videoView setBackgroundColor:[UIColor greenColor]];
[self.videoView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:self.videoView];
// width & height constraints, as UIViews don't have intrinsic constraints
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:140.0];
[self.videoView addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:140.0];
[self.videoView addConstraint:lc];
// center constraint
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0
constant:0.0];
[self.view addConstraint:lc];
// top constraint with its parent view
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0
constant:20.0];
[self.view addConstraint:lc];
This squared view shows ok in any device orientation
Now I create the second view on the lower part of the screen. It really
doesn't matter its dimensions here as I create a constraint for each size
attribute
/*********************** listado view */
self.listadoView = [[UIView alloc] initWithFrame:CGRectMake(5, 248, 310,
100)];
[self.listadoView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.listadoView setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:self.listadoView];
// height and width constraints as UIView don't have intrinsic constraints
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:310];
[self.listadoView addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:300];
// make it weak to be able to squeeze contents
lc.priority = 250;
[self.listadoView addConstraint:lc];
// top with videoView's bottom
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationLessThanOrEqual
toItem:self.videoView attribute:NSLayoutAttributeBottom multiplier:1.0
constant:88.0];
[self.view addConstraint:lc];
// top with parent's view top
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0
constant:248.0];
[self.view addConstraint:lc];
// center constraint
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0
constant:0.0];
[self.view addConstraint:lc];
trying to replicate here what IB did with the constraints in the other view
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0
constant:5];
[self.view addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0
constant:10];
[self.view addConstraint:lc];
Te resulting screens are below with the green square. The vertical green
screen shows what I was expecting (see yellow images down below), but in
the green horizontal, as you can see, the bottom edge of the listadoView
is below the edge of the screen, even though I'm setting all the
constraints IB sets for the yellow one, those along with the ones I set in
the yellow one too.
Any advice on how to set the constraints?... maybe the order in which they
are created has something to do with it?, because there were times when I
removed a constraint and it worked, then I re-added that constraint and
still worked!. Ran it again with all the constraints, and then stopped
working (what?!). And it's been hard to successfully reproduce it in order
to file a bug, but it happened.
I've tested this code in XCode 4.6 under iOS5.1 and 6.x and with xCode 5
under iOS6.1.
Just to add a view that lives in the same parent view as the other two
related views.
self.vDist = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 42, 21)];
[self.vDist setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:self.vDist];
NSLayoutConstraint *lc;
lc = [NSLayoutConstraint constraintWithItem:self.vDist
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0
constant:20.0];
[self.view addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.vDist
attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0
constant:20.0];
[self.view addConstraint:lc];
Then, I create the small squared view on top
/*********************** video view */
self.videoView = [[UIView alloc] initWithFrame:CGRectMake(90, 20, 140, 140)];
[self.videoView setBackgroundColor:[UIColor greenColor]];
[self.videoView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:self.videoView];
// width & height constraints, as UIViews don't have intrinsic constraints
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:140.0];
[self.videoView addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:140.0];
[self.videoView addConstraint:lc];
// center constraint
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0
constant:0.0];
[self.view addConstraint:lc];
// top constraint with its parent view
lc = [NSLayoutConstraint constraintWithItem:self.videoView
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0
constant:20.0];
[self.view addConstraint:lc];
This squared view shows ok in any device orientation
Now I create the second view on the lower part of the screen. It really
doesn't matter its dimensions here as I create a constraint for each size
attribute
/*********************** listado view */
self.listadoView = [[UIView alloc] initWithFrame:CGRectMake(5, 248, 310,
100)];
[self.listadoView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.listadoView setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:self.listadoView];
// height and width constraints as UIView don't have intrinsic constraints
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:310];
[self.listadoView addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0
constant:300];
// make it weak to be able to squeeze contents
lc.priority = 250;
[self.listadoView addConstraint:lc];
// top with videoView's bottom
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationLessThanOrEqual
toItem:self.videoView attribute:NSLayoutAttributeBottom multiplier:1.0
constant:88.0];
[self.view addConstraint:lc];
// top with parent's view top
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0
constant:248.0];
[self.view addConstraint:lc];
// center constraint
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0
constant:0.0];
[self.view addConstraint:lc];
trying to replicate here what IB did with the constraints in the other view
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0
constant:5];
[self.view addConstraint:lc];
lc = [NSLayoutConstraint constraintWithItem:self.listadoView
attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual
toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0
constant:10];
[self.view addConstraint:lc];
Te resulting screens are below with the green square. The vertical green
screen shows what I was expecting (see yellow images down below), but in
the green horizontal, as you can see, the bottom edge of the listadoView
is below the edge of the screen, even though I'm setting all the
constraints IB sets for the yellow one, those along with the ones I set in
the yellow one too.
Any advice on how to set the constraints?... maybe the order in which they
are created has something to do with it?, because there were times when I
removed a constraint and it worked, then I re-added that constraint and
still worked!. Ran it again with all the constraints, and then stopped
working (what?!). And it's been hard to successfully reproduce it in order
to file a bug, but it happened.
I've tested this code in XCode 4.6 under iOS5.1 and 6.x and with xCode 5
under iOS6.1.
Columns auto-resize to size of QTableView
Columns auto-resize to size of QTableView
I am new to QT and I have just managed to make a QTableView work with my
model. It has fixed 3 columns. When I open a window, it look ok but when i
resize the window, the QTableView itself gets resized but columns' width
remains the same. Is there any build-in way to make it work? I want
columns to resize to fit the edges of QTableView every the the window gets
resized.
I am new to QT and I have just managed to make a QTableView work with my
model. It has fixed 3 columns. When I open a window, it look ok but when i
resize the window, the QTableView itself gets resized but columns' width
remains the same. Is there any build-in way to make it work? I want
columns to resize to fit the edges of QTableView every the the window gets
resized.
giving id to many objects - is it a bad idea?
giving id to many objects - is it a bad idea?
I was working on a django project and soon the template became a mess and
ended up with nearly all elements having an ID (just to clarify, all IDs
are unique). I can reduce the number of IDs by giving their parents an ID
but that would increase my jQuery code. So what I am asking is
Is it better to have many IDs in HTML or slightly less IDs and a bit
longer JS/jQuery code?
Here's a sample code:
<ol>
<li>
<p>
<a href="/vote/" class="vote" id="story-vote-26"><img
src="/static/images/arrow.gif"></a>
<a
href="http://www.lettersofnote.com/2012/10/people-simply-empty-out.html"
class="title" id="story-title-26">"People simply empty
out"</a> <span class="domain">(www.lettersofnote.com)</span>
</p>
<p class="story-info">
<span id="story-points-26">660</span> points by tantaman
ǀ 31 minutess ago
</p>
</li>
...
there are at least 100 of these li and each with 4 IDs (I haven't added
4th one yet). So total of 400 IDs, or 100 IDs if I add ID to lis instead
I was working on a django project and soon the template became a mess and
ended up with nearly all elements having an ID (just to clarify, all IDs
are unique). I can reduce the number of IDs by giving their parents an ID
but that would increase my jQuery code. So what I am asking is
Is it better to have many IDs in HTML or slightly less IDs and a bit
longer JS/jQuery code?
Here's a sample code:
<ol>
<li>
<p>
<a href="/vote/" class="vote" id="story-vote-26"><img
src="/static/images/arrow.gif"></a>
<a
href="http://www.lettersofnote.com/2012/10/people-simply-empty-out.html"
class="title" id="story-title-26">"People simply empty
out"</a> <span class="domain">(www.lettersofnote.com)</span>
</p>
<p class="story-info">
<span id="story-points-26">660</span> points by tantaman
ǀ 31 minutess ago
</p>
</li>
...
there are at least 100 of these li and each with 4 IDs (I haven't added
4th one yet). So total of 400 IDs, or 100 IDs if I add ID to lis instead
My job finishes with echo statement but does not finish without
My job finishes with echo statement but does not finish without
I have a job that I ran several times on a shared host. It starts, then
calculates and updates the database for a few minutes and then ends with a
comment telling me it finished.
When I run it, then the program terminates somewhere in the middle and the
last comment never comes. But when I do an echo statement in the main
loop, the exact same program DOES reach the final comment and does all it
is supposed to do even though it apparently has to do more work.
Question: Who know why the echoing output can make a program finish while
it does not without the echo's?
I have a job that I ran several times on a shared host. It starts, then
calculates and updates the database for a few minutes and then ends with a
comment telling me it finished.
When I run it, then the program terminates somewhere in the middle and the
last comment never comes. But when I do an echo statement in the main
loop, the exact same program DOES reach the final comment and does all it
is supposed to do even though it apparently has to do more work.
Question: Who know why the echoing output can make a program finish while
it does not without the echo's?
could not initialize class org.apache.xerces.jaxp.datatype.xmlgregoriancalendar
could not initialize class
org.apache.xerces.jaxp.datatype.xmlgregoriancalendar
I am using web serices to send and receive information. The request is
being formed properly and I am also getting a response. However, during
the the mapping of the response to actual DTO, I am getting the following
error:
could not initialize class
org.apache.xerces.jaxp.datatype.xmlgregoriancalendar
There are some calednar date form in the response, but I am not sure, why
it is not able to initialize xmlgregoriancalendar class. I run it on my
local with stubs, and it give me no problems at all.
any adivse would be helpful...Thanks in advance
org.apache.xerces.jaxp.datatype.xmlgregoriancalendar
I am using web serices to send and receive information. The request is
being formed properly and I am also getting a response. However, during
the the mapping of the response to actual DTO, I am getting the following
error:
could not initialize class
org.apache.xerces.jaxp.datatype.xmlgregoriancalendar
There are some calednar date form in the response, but I am not sure, why
it is not able to initialize xmlgregoriancalendar class. I run it on my
local with stubs, and it give me no problems at all.
any adivse would be helpful...Thanks in advance
Scala, P08 - pack
Scala, P08 - pack
I'm doing the packing problem from P08 from the 99 Problems, I think I'm
doing this right but there's something wrong with the syntax of Scala that
I think I don't know..
def pack(list: List[Char]): List[List[Char]] = {
@tailrec
def checkNext(a: List[List[Char]], prev: Char, l: List[Char] ):
List[List[Char]] = {
if (!l.nonEmpty) a
else {
val res = if (prev==l.head) List(a.head:::List(l.head)) else
a:::List(List(l.head))
checkNext(res, l.head, l.tail)
}
}
checkNext(List(List(list.head)), list.head, list.tail)
}
I'm doing the packing problem from P08 from the 99 Problems, I think I'm
doing this right but there's something wrong with the syntax of Scala that
I think I don't know..
def pack(list: List[Char]): List[List[Char]] = {
@tailrec
def checkNext(a: List[List[Char]], prev: Char, l: List[Char] ):
List[List[Char]] = {
if (!l.nonEmpty) a
else {
val res = if (prev==l.head) List(a.head:::List(l.head)) else
a:::List(List(l.head))
checkNext(res, l.head, l.tail)
}
}
checkNext(List(List(list.head)), list.head, list.tail)
}
Friday, 16 August 2013
In C, how do I create a `static` array of constant size with zeroed values, but without calloc?
In C, how do I create a `static` array of constant size with zeroed
values, but without calloc?
I currently have some code in a function that looks like this:
static const int kFrameCountSample = 250;
static float * samples = (float *)calloc(kFrameCountSample,
sizeof(float));
I like that the samples array is zeroed out exactly once with calloc().
I can also write the code so samples is allocated on the stack.
static const int kFrameCountSample = 250;
static float samples[kFrameCountSample];
but now samples is not initialized to zero values. How would I also
initialize it at the time it is allocated?
values, but without calloc?
I currently have some code in a function that looks like this:
static const int kFrameCountSample = 250;
static float * samples = (float *)calloc(kFrameCountSample,
sizeof(float));
I like that the samples array is zeroed out exactly once with calloc().
I can also write the code so samples is allocated on the stack.
static const int kFrameCountSample = 250;
static float samples[kFrameCountSample];
but now samples is not initialized to zero values. How would I also
initialize it at the time it is allocated?
Saturday, 10 August 2013
ListView update after any change
ListView update after any change
I have a listview in my android app which does two functions with the
listview itself.
Fist, I can delete an item from the listview.
Second, I can rename something in the listview.
Anytime any of the above happens,
How do I display a different XML layout if the last item on the listview
is deleted?
adapter = new SetRowsCustomAdapter(getActivity(), R.layout.customlist,
rowsArray);
dataList = (ListView) mFrame3.findViewById(R.id.lvFiles); //lvfiles from
xml layout
dataList.setAdapter(adapter);
dataList.setEmptyView(noFilesDisplayed); //not working
Second, once I rename anything within the listview, how do I update the
listview to reflect the changes?
adapter.notifyDataSetChanged(); //not working
I have a listview in my android app which does two functions with the
listview itself.
Fist, I can delete an item from the listview.
Second, I can rename something in the listview.
Anytime any of the above happens,
How do I display a different XML layout if the last item on the listview
is deleted?
adapter = new SetRowsCustomAdapter(getActivity(), R.layout.customlist,
rowsArray);
dataList = (ListView) mFrame3.findViewById(R.id.lvFiles); //lvfiles from
xml layout
dataList.setAdapter(adapter);
dataList.setEmptyView(noFilesDisplayed); //not working
Second, once I rename anything within the listview, how do I update the
listview to reflect the changes?
adapter.notifyDataSetChanged(); //not working
Run UIViewController inside UINavigationController as a second view of UISplitViewController
Run UIViewController inside UINavigationController as a second view of
UISplitViewController
I have a problem trying to access a navigation controller of the view
controller from it, always returns as nill to me, though it is shown
within the navigation controller. Here is what I have (I have a split view
controller, that is presented as tab controller for master and
viewcontroller (inside navigation controller) as detail):
FirstDetailViewController *fdvc = [[FirstDetailViewController alloc]
initWithNibName:@"FirstDetailViewController" bundle:nil];
UINavigationController *fdvcNav = [[UINavigationController alloc]
initWithRootViewController:fdvc];
NSArray *ipadVCs = [[NSArray alloc] initWithObjects:tabController,
fdvcNav, nil];
UISplitViewController *splitvc = [[UISplitViewController alloc]
initWithNibName:nil bundle:nil];
[splitvc setViewControllers:ipadVCs];
[[splitvc view] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage
imageNamed:@"splitViewControllerBG"]]];
[splitvc setDelegate:fdvc];
[[self window] setRootViewController:splitvc];
[[self window] makeKeyAndVisible];
But when I'm trying to access a navigation controller from the fdvc view
controller in ViewDidLoad with [self navigationController] it gives me
(Null) always. Thanks!
UISplitViewController
I have a problem trying to access a navigation controller of the view
controller from it, always returns as nill to me, though it is shown
within the navigation controller. Here is what I have (I have a split view
controller, that is presented as tab controller for master and
viewcontroller (inside navigation controller) as detail):
FirstDetailViewController *fdvc = [[FirstDetailViewController alloc]
initWithNibName:@"FirstDetailViewController" bundle:nil];
UINavigationController *fdvcNav = [[UINavigationController alloc]
initWithRootViewController:fdvc];
NSArray *ipadVCs = [[NSArray alloc] initWithObjects:tabController,
fdvcNav, nil];
UISplitViewController *splitvc = [[UISplitViewController alloc]
initWithNibName:nil bundle:nil];
[splitvc setViewControllers:ipadVCs];
[[splitvc view] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage
imageNamed:@"splitViewControllerBG"]]];
[splitvc setDelegate:fdvc];
[[self window] setRootViewController:splitvc];
[[self window] makeKeyAndVisible];
But when I'm trying to access a navigation controller from the fdvc view
controller in ViewDidLoad with [self navigationController] it gives me
(Null) always. Thanks!
Friday, 9 August 2013
How to create an emacs macro for text templates
How to create an emacs macro for text templates
I am new to lisp and I am having trouble figuring out how to create a
macro in emacs with the following functionality: Say I am tired of writing
out the pattern in c++ for a for loop:
for (int i = 0; i < N; i++) {
}
Call this macro "forloop" then I would like to do the following: when I
type "M-x forloop" the macro prints out
for (int
in the buffer and waits for an input. Then I type "i" and hit return after
which the macro continues and prints
for (int i = 0; i <
And again waits for input. Finally after I type "N" and hit return the
macro finishes by printing the rest:
for (int i = 0; i < N; i++) {
}
After some extensive reading and testing, I was able to write simple lisp
functions, create my own macros, save them and call them and so on... but
I still can't quite figure out how to make a macro that does something
like I have described above. Any thoughts would be much appreciated!
Thanks in advance!
Macros like this could be really nice for speeding up coding in any
language. I would prefer the macro to be dynamic in the way described so
that you don't have to remember how many arguments it needs and in which
order they go when calling it.
I am new to lisp and I am having trouble figuring out how to create a
macro in emacs with the following functionality: Say I am tired of writing
out the pattern in c++ for a for loop:
for (int i = 0; i < N; i++) {
}
Call this macro "forloop" then I would like to do the following: when I
type "M-x forloop" the macro prints out
for (int
in the buffer and waits for an input. Then I type "i" and hit return after
which the macro continues and prints
for (int i = 0; i <
And again waits for input. Finally after I type "N" and hit return the
macro finishes by printing the rest:
for (int i = 0; i < N; i++) {
}
After some extensive reading and testing, I was able to write simple lisp
functions, create my own macros, save them and call them and so on... but
I still can't quite figure out how to make a macro that does something
like I have described above. Any thoughts would be much appreciated!
Thanks in advance!
Macros like this could be really nice for speeding up coding in any
language. I would prefer the macro to be dynamic in the way described so
that you don't have to remember how many arguments it needs and in which
order they go when calling it.
How do I merge messages using either OR or JOIN?
How do I merge messages using either OR or JOIN?
I want to show the conversation between person A and person B only.
Type in Facebook messages ...
The problem is that my query is returning all messages and not only the
ones between the selected people.
How do I fix this with OR or JOIN?
$mysql = mysql_query("SELECT *
FROM msgs
WHERE usr_to = 'myself' AND
author_msg = 'he' OR
author_msg = 'myself' AND
usr_to = 'he'
ORDER BY id DESC
LIMIT 12", $mysql);
I want to show the conversation between person A and person B only.
Type in Facebook messages ...
The problem is that my query is returning all messages and not only the
ones between the selected people.
How do I fix this with OR or JOIN?
$mysql = mysql_query("SELECT *
FROM msgs
WHERE usr_to = 'myself' AND
author_msg = 'he' OR
author_msg = 'myself' AND
usr_to = 'he'
ORDER BY id DESC
LIMIT 12", $mysql);
What is the best fix, for mouseleave (over select) bug?
What is the best fix, for mouseleave (over select) bug?
#childBox {
width:200px;
height:200px;
border:solid thin #900;
}
<div id="parentBox">
<div id="childBox">
<select>
<option>Opt1</option>
<option>Opt2</option>
<option>Opt3</option>
</select>
</div>
<div id="mesIn"></div>
<div id="mesOut"></div>
</div>
var i = 0, y=0;
$('#parentBox').on({
mouseenter:function(e){
//console.log ('in: ');
i++; $('#mesIn').text('IN '+i);
},
mouseleave: function(e){
//console.log ('out: ');
y++; $('#mesOut').text('OUT '+y);
}
}, '#childBox');
When the mouse enters the options it will fire first as 'out' and then as
'in' again. I found this prb in FF23 & IE9 (FF is crashing) It's working
as it should in Chrome 28 & Opera 12.16 I have jquery 1.10.02 For above
code: http://jsfiddle.net/buicu/ZCmRP/1/ For a more detailed version of my
code: http://jsfiddle.net/buicu/ZH6qm/4/
I know I could put a bunch of setTimeout/clearTimeout. But I want
something more simple/cleaner.
e.stopImmediatePropagation(); doesn't help (at least in my test.).
To bind a click to select (and to set false a variable) doesn't help
either. Because if the select drop down menu remains open and then the
mouse leaves the big menu, then the big menu will also remain open (I know
I could track when the mouse leaves the options and change back the
variable. But checking when the mouse leaves the option can't be done
consistently across browsers).
Does anyone has a simple/cleaner fix for this bug?
#childBox {
width:200px;
height:200px;
border:solid thin #900;
}
<div id="parentBox">
<div id="childBox">
<select>
<option>Opt1</option>
<option>Opt2</option>
<option>Opt3</option>
</select>
</div>
<div id="mesIn"></div>
<div id="mesOut"></div>
</div>
var i = 0, y=0;
$('#parentBox').on({
mouseenter:function(e){
//console.log ('in: ');
i++; $('#mesIn').text('IN '+i);
},
mouseleave: function(e){
//console.log ('out: ');
y++; $('#mesOut').text('OUT '+y);
}
}, '#childBox');
When the mouse enters the options it will fire first as 'out' and then as
'in' again. I found this prb in FF23 & IE9 (FF is crashing) It's working
as it should in Chrome 28 & Opera 12.16 I have jquery 1.10.02 For above
code: http://jsfiddle.net/buicu/ZCmRP/1/ For a more detailed version of my
code: http://jsfiddle.net/buicu/ZH6qm/4/
I know I could put a bunch of setTimeout/clearTimeout. But I want
something more simple/cleaner.
e.stopImmediatePropagation(); doesn't help (at least in my test.).
To bind a click to select (and to set false a variable) doesn't help
either. Because if the select drop down menu remains open and then the
mouse leaves the big menu, then the big menu will also remain open (I know
I could track when the mouse leaves the options and change back the
variable. But checking when the mouse leaves the option can't be done
consistently across browsers).
Does anyone has a simple/cleaner fix for this bug?
Android Permission denied - com.android.alarm.permission.SET_ALARM
Android Permission denied - com.android.alarm.permission.SET_ALARM
I am trying to set a Alarm from my app, but when I start the intent by
doing the following, as described here: How to launch Alarm Clock screen
using Intent in Android?
public boolean onMenuItemSelected(int featureId, MenuItem item) {
Intent alarmas = new Intent(AlarmClock.ACTION_SET_ALARM);
alarmas.putExtra(AlarmClock.EXTRA_MESSAGE, "Prueba Custom Alarm Clock");
alarmas.putExtra(AlarmClock.EXTRA_HOUR, 10);
alarmas.putExtra(AlarmClock.EXTRA_MINUTES, 30);
startActivity(alarmas);
return true;
}
I get this exception:
08-09 18:23:42.782 7461-7461/? E/AndroidRuntime: Uncaught handler:
thread main exiting due to uncaught exception
08-09 18:23:42.927 7461-7461/? E/AndroidRuntime:
java.lang.SecurityException: Permission Denial: starting Intent {
act=android.intent.action.SET_ALARM
cmp=com.urbandroid.sleep/.alarmclock.AddAlarmActivity (has extras) } from
ProcessRecord{442bf618 7461:com.TurryBoeing.customalarmclock/10067}
(pid=7461, uid=10067) requires com.android.alarm.permission.SET_ALARM
at android.os.Parcel.readException(Parcel.java:1218)
at android.os.Parcel.readException(Parcel.java:1206)
at
android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1214)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1373)
at android.app.Activity.startActivityForResult(Activity.java:2749)
at android.app.Activity.startActivity(Activity.java:2855)
at
com.TurryBoeing.customalarmclock.ClockActivity.onMenuItemSelected(ClockActivity.java:109)
at
com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:730)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:139)
at
com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
at
com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:525)
at
com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
at android.view.View.onTouchEvent(View.java:4179)
at android.widget.TextView.onTouchEvent(TextView.java:6541)
at android.view.View.dispatchTouchEvent(View.java:3709)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1649)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1694)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)
And I don't know why it's asking for
"com.android.alarm.permission.SET_ALARM" because that is set in my
manifest.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.TurryBoeing.customalarmclock"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
<activity
android:name="com.TurryBoeing.customalarmclock.ClockActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<action android:name="android.intent.action.TIME_TICK"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Thank you.
I am trying to set a Alarm from my app, but when I start the intent by
doing the following, as described here: How to launch Alarm Clock screen
using Intent in Android?
public boolean onMenuItemSelected(int featureId, MenuItem item) {
Intent alarmas = new Intent(AlarmClock.ACTION_SET_ALARM);
alarmas.putExtra(AlarmClock.EXTRA_MESSAGE, "Prueba Custom Alarm Clock");
alarmas.putExtra(AlarmClock.EXTRA_HOUR, 10);
alarmas.putExtra(AlarmClock.EXTRA_MINUTES, 30);
startActivity(alarmas);
return true;
}
I get this exception:
08-09 18:23:42.782 7461-7461/? E/AndroidRuntime: Uncaught handler:
thread main exiting due to uncaught exception
08-09 18:23:42.927 7461-7461/? E/AndroidRuntime:
java.lang.SecurityException: Permission Denial: starting Intent {
act=android.intent.action.SET_ALARM
cmp=com.urbandroid.sleep/.alarmclock.AddAlarmActivity (has extras) } from
ProcessRecord{442bf618 7461:com.TurryBoeing.customalarmclock/10067}
(pid=7461, uid=10067) requires com.android.alarm.permission.SET_ALARM
at android.os.Parcel.readException(Parcel.java:1218)
at android.os.Parcel.readException(Parcel.java:1206)
at
android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1214)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1373)
at android.app.Activity.startActivityForResult(Activity.java:2749)
at android.app.Activity.startActivity(Activity.java:2855)
at
com.TurryBoeing.customalarmclock.ClockActivity.onMenuItemSelected(ClockActivity.java:109)
at
com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:730)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:139)
at
com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855)
at
com.android.internal.view.menu.IconMenuView.invokeItem(IconMenuView.java:525)
at
com.android.internal.view.menu.IconMenuItemView.performClick(IconMenuItemView.java:122)
at android.view.View.onTouchEvent(View.java:4179)
at android.widget.TextView.onTouchEvent(TextView.java:6541)
at android.view.View.dispatchTouchEvent(View.java:3709)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1649)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1694)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)
And I don't know why it's asking for
"com.android.alarm.permission.SET_ALARM" because that is set in my
manifest.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.TurryBoeing.customalarmclock"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
<activity
android:name="com.TurryBoeing.customalarmclock.ClockActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<action android:name="android.intent.action.TIME_TICK"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Thank you.
MySQL TIMEDIFF negative value
MySQL TIMEDIFF negative value
I've a problem using TIMEDIFF with two different date. The following query
"should" return 00:04:51
mysql> SELECT TIMEDIFF(TIME('2013-07-21 00:04:50'),TIME('2013-07-20
23:59:59'));
+-------------------------------------------------------------------+
|TIMEDIFF(TIME('2013-07-21 00:04:50'),TIME('2013-07-20 23:59:59')) |
+-------------------------------------------------------------------+
| -23:55:09 |
+-------------------------------------------------------------------+
1 row in set (0.00 sec)
Any tips? Which is the easiest way? Thank you
I've a problem using TIMEDIFF with two different date. The following query
"should" return 00:04:51
mysql> SELECT TIMEDIFF(TIME('2013-07-21 00:04:50'),TIME('2013-07-20
23:59:59'));
+-------------------------------------------------------------------+
|TIMEDIFF(TIME('2013-07-21 00:04:50'),TIME('2013-07-20 23:59:59')) |
+-------------------------------------------------------------------+
| -23:55:09 |
+-------------------------------------------------------------------+
1 row in set (0.00 sec)
Any tips? Which is the easiest way? Thank you
Subscribe to:
Comments (Atom)