Thursday, 3 October 2013

algorithm complexity , solving recursive equation

algorithm complexity , solving recursive equation

I am a student at University of Tehran and this semester I've taken a Data
Structures and Algorithm course . anyway not to bore you with details ,
for solving complexity for an algorithm , I'm stuck in this recursive
equation :
T(n) = logn*T(logn) + n
obviously this cant be handled with the use of the Master Theorem , so I
was wondering if anybody has any ideas for solving this recursive equation
. P.S. : I'm pretty sure that it should be solved with a change in the
parameters , like considering n to be 2^m , but I couldn't manage to find
any good fix . anyways , thanks for your help in advance

Wednesday, 2 October 2013

Release bugs only show up when running EXE outside of Visual Studio

Release bugs only show up when running EXE outside of Visual Studio

I have an issue that I am trying to debug that only happens when I run the
release exe built directly outside of Visual Studio. When I am executing
it from within Visual Studio the program behaves normally, even when using
specific project properties to debug a "release" build, such as turning on
optimizations, explained on the following page.
http://msdn.microsoft.com/en-us/library/fsk896zz%28v=vs.100%29.aspx
I experience no issues using those settings and running/debugging from
withing VS, but when I copy the exe and required files (images and some
dll) to it's own directory and run the exe directly instead of through
VS2010 I experience a couple errors. This is making it hard to debug as I
can't get the issue to occur inside VS no matter what settings I use.
Am I missing some settings or is there still more things that happen
differently outside of VS2010 that I can't simulate from within VS 2010?
I am not using any arguments or environment variables that could be
affecting it and the file structure from the working directory is
identical to the way it is in the source code directory.

How to create a kernel thread in atomic context and use it multiple times [BUG: Scheduling while atomic]

How to create a kernel thread in atomic context and use it multiple times
[BUG: Scheduling while atomic]

I need to kthread_run in a driver kernel code. This thread tends to turns
an LED on/OFF where the device is transmitting data. So basically I won't
want the transmission be slowed down be cause of the LED blinking delay
time. I would like to create a thread somewhere around packet transmission
code so the thread will do the LED blinking process based on the rate of
transmission. But apparently creating a thread there requires interaction
with the thread scheduler, which is not allowed at interrupt/atomic
context and will generate the BUG:Scheduling while atomic. according to my
research,an approach could be to create the kernel thread elsewhere, and
queue interrupt request processing to it. Can someone please elaborate
this a bit more? So this is not a case where we have interruption thread.
I basically need a Function that has it's own thread away from my main
thread. And I will call this function anytime! Please let me know if this
is still unclear. Thanks.

Popup message after redirect OR message after user visits from a particular site

Popup message after redirect OR message after user visits from a
particular site

I'd like to show a popup welcome message AFTER a visitor has been
redirected from my old site to the new one.
I'm going to set up the old site with 301 redirects to the new content -
and only people coming from the old site should see the welcome message.
Users who access the new site directly should not see the message.
I know that I can set up a message before redirect on the old site - but I
currently only have access to my client's new site.
I can't find anything anywhere about doing something like this. Is it
possible?

How to use variables in Java?

How to use variables in Java?

This question may seem dumb at first, but after having worked with
different person, I see everyone seems to have their own, different
knowledge about it, so here's my question.
So now I'm wondering what is the best way to do it, and why (why is more
important for me):
I'm wondering about two methods to write Java code:
Do you always pass Object or can you pass primitive data type ?
Do you call variables using this.name, name or getName() inside your class
instance ?
public class MyClass {
private String someStr;
private int someNumber;
private Integer someOtherNumber; // int, Integer ? which one to choose ?
public MyClass(String someStr, int someNumber, int someOtherNumber) {
// int someNumber ? Integer someNumber ? why ?
this.someStr = someStr; // Here, it's clearly this.{name} = {name}
because of the variable name conflict
this.someNumber = someNumber;
this.someOtherNumber = someOtherNumber;
}
public int someMethod(boolean first) { // Boolean ? boolean ?
if (first) {
return someNumber;
} else {
return this.someOtherNumber; // this.{name} ? just {name} or
even this.get{name}() or get{name}() ? (supposing getters
exists)
}
}
}
I hope I'm clear about it and I hope someone will provide me with a great
explanation about which to use in order for me to write better code (and
maybe help others too ! :))
Thanks for your help.

Tuesday, 1 October 2013

Is it a common/good practice to save/update the session *after* sending the response?

Is it a common/good practice to save/update the session *after* sending
the response?

I started updating the session after sending the response and it seems
like a good way to get a little more speed, since it's now a non-blocking
task.
But I'm worried that a minimal slow down in the database could cause
problems when updating the session this way.
Imagine I want to set a session flash message for the next request, but
the next request/response happen before the session is updated. The user
won't see it, or he will see it in a different request.
And the worst case is when you need to regenerate the session ID. If the
update is slow and the next request comes faster than that, the user will
get logged out because he will be asking for a non-existent or expired
session (he received the new session ID in the cookie as part of the
response).
So what I wanna know is whether this has already been studied, whether
people are using it, when should I do it, when I shouldn't, if there is a
fix for it, etc.

spring security bean not found exception

spring security bean not found exception

I'm trying to set up spring security for an mvc project, and I'm having a
hard time. I'm using the spring security 3.1.4.Release. I have a
spring-security.xml file set up along with and mvc-dispatcher-servlet file
set up for configuration. Right now I'm getting a bean not found exception
for my User Details Bean.
In intellij I get a "cannot resolve bean" message for the
myUserDetailService. I also cannot resolve the package "controller". The
root error when I run the project is:
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0':
Cannot resolve reference to bean 'myUserDetailService' while setting bean
property 'userDetailsService'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean
named 'myUserDetailService' is defined
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
[spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
[spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE]
Here is my spring-security.xml file:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enabling Spring beans auto-discovery -->
<context:component-scan base-package="controller, com.company.admin" />
<http auto-config="true">
<intercept-url pattern="/admin/*" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/admin/welcome"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailService"/>
</authentication-manager>
</beans:beans>
Here is my mvc-dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Enabling Spring beans auto-discovery -->
<context:component-scan base-package="com.company.admin" />
<!-- Enabling Spring MVC configuration through annotations -->
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Here is my web.xml:
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
I'm basically trying to follow this tutorial:
http://kh-yiu.blogspot.com/2012/12/spring-mvc-security-custom.html and the
UserDetailServiceImpl is pretty identical to that, but I do have it in a
different folder in my main/java directory. It's important to note I use
annotations to declare the class:
@Service("myUserDetailService")
public class UserDetailsServiceImpl implements UserDetailsService{
Any ideas? I'm having a very hard time finding tutorials with the same
spring version that I'm using, so it's quite possible I've messed up xsd
refs. Thanks.

upper bound of sequence of functions

upper bound of sequence of functions

What function will be an upper bound of the sequence
$f_{n}(x)=\Bigl(1-\frac{x}{n}\Bigr)^{n}\ln(x)$
since $\displaystyle\lim_{n\to\infty}\Bigl(1-\frac{x}{n}\Bigr)^{n}=e^{-x}$
so we should probably bound above by the exponential function.
Someone knows how to do that?

can some tell me that my answer is right or wrong

can some tell me that my answer is right or wrong

If $\mathbb R$^5be a vector space .and
$$W_1={(0,x_2,x_3,x_4,x_5)/x_2,x_3,x_4,x_5\in R}$$and
$$W2={(x_1,0,x_3,x_4,x_5)/x_1,x_3,x_4,x_5\in R}$$be two subspaces of $R^5$
then the dimension of $W1\cap$W_2 is according two me its dimension is 3
as then $W_1\cap W_2$ have elements of the form $$(0,0,x_3,x_4,x_5)$$
hence $W_1\cap W_2$ will be isomorphic to $ R^3$.

Monday, 30 September 2013

LDAP query doesn't return all accounts with specific login

LDAP query doesn't return all accounts with specific login

I have a Windows 2008 domain that I am querying via ldapsearch and if I
use a domain administrator account I get all the users I would expect, but
if I use the service account I created for this purpose I miss random
objects.
For example:
#> ldapsearch -LLL -H ldap://domain-controller.my-domain.com:389 -b
'dc=MY-DOMAIN,dc=COM' -D 'MY-DOMAIN\administrator' -W
'(&(objectClass=Person)(sAMAccountName=*)(memberof=cn=StashTeam,ou=MyTeams,ou=MyDomainUsers,dc=MY-DOMAIN,dc=COM)(!(userAccountControl=514)))'
| grep cn:
I get a list of:
cn: Homer Simpson
cn: Marge Simpson
cn: Bart Simpson
cn: Lisa Simpson
cn: Maggie Simpson
However if I run (using my Service Account):
#> ldapsearch -LLL -H ldap://domain-controller.my-domain.com:389 -b
'dc=MY-DOMAIN,dc=COM' -D 'MY-DOMAIN\ServiceUser' -W
'(&(objectClass=Person)(sAMAccountName=*)(memberof=cn=StashTeam,ou=MyTeams,ou=MyDomainUsers,dc=MY-DOMAIN,dc=COM)(!(userAccountControl=514)))'
| grep cn:
I get a list like:
cn: Homer Simpson
cn: Lisa Simpson
cn: Maggie Simpson

An abelian subgroup of a group of order 32:

An abelian subgroup of a group of order 32:

I know that a group of order 32 has an abelian subgroup of order 16 using
GAP (Groups, Algorithms, Programming). Is there a way without using
programming to show this. Any help will be highly appreciated.

iOS 7 adding UIView to UITableView

iOS 7 adding UIView to UITableView

I am trying to add a UIView to UITableView in iOS 7 to display and "Not
Results" view.
My code works fine in iOS 6, but getting white page in iOS 7.
[self.tableView insertSubview:_nomatchesView
belowSubview:self.tableView];
Anyone run into this issue?
Thanks.

Passing data from C# to unmanaged C++ (using COM Interop)

Passing data from C# to unmanaged C++ (using COM Interop)

I'm using Com Interop method to communicate with unmanaged C++ and C#.
I need to send data to unmanaged C++ from C#.
Im already sending "bool" values values from C# & accessing it through
"VARIANT_BOOL*" in c++.
I need to send a integer from C#. How can i access that integer value in
unmanaged c++ side ?
for example:
C#
public int myValue()
{
return 5;
}
Unmanaged C++
CoInitialize(NULL);
hRes = IMyPointer.CreateInstance(MyNSpace::CLSID_MyClass);
if (hRes == S_OK)
{
//// ??? define x type
IMyPointer->myValue(x);
}

Sunday, 29 September 2013

Regex "greedy" check

Regex "greedy" check

I'm trying to use a simple Regex to match a patttern but get some
unexpected results...
The search pattern and results are given below,
public class Test {
public static void main(String[] args) throws IOException {
Pattern p = Pattern.compile(".*xx");
Matcher m = p.matcher("yyxxxyxx");
while (m.find()){
System.out.println("match start");
System.out.println("Start = " + m.start());
System.out.println("End = " + m.end());
System.out.println("Group = " + m.group());
}
}
}
Result:
match start Start = 0 End = 8 Group = yyxxxyxx
Expected Result:
match start Start = 0 End = 4 Group = yyxx match start Start = 4 End = 8
Group = xyxx
Can someone explain how the regex operates ?

wpf Converter with Combobox

wpf Converter with Combobox

lets say i have a class address
public partial class Address
{
public int Id { get; set; }
public Nullable<int> CountryId { get; set; }
public Nullable<int> CityId { get; set; }
public string Details { get; set; }
public Nullable<bool> IsDefault { get; set; }
public Nullable<int> PersonId { get; set; }
}
i want to know how can i use converter with a combobox inside the grid to
show cities in that combobox based on selected country in another combobox
inside the grid. i need to now the syntax how can i use the countryID to
pass it to converter to get list of cities and binding it to CityCombobox
in datagrid and on changing the Country this list is updated according to
the selected country.. Thanks

Implementation of DDA Line Algorithm

Implementation of DDA Line Algorithm

I have tested all the cases of how a line could be 1. vertically 2.
horizontally 3. has a positive or less than 1 slope. The function works,
but I would like to review it, if there are overflows, lost test
cases..etc. I just read the algorithm in wikipedia, and tried to implement
it out of the wikipedia article.
// Draw line using DDA Algorithm
void Graphics::DrawLine( int x1, int y1, int x2, int y2, Color&color )
{
float xdiff = x1-x2;
float ydiff = y1-y2;
int slope = 1;
if ( y1 == y2 )
{
slope = 0;
}
else if ( x1 == x2 )
{
slope = 2; // vertical lines have no slopes...
}
else
{
slope = (int)xdiff/ydiff;
}
if ( slope <= 1 )
{
int startx = 0;
int endx = 0;
if ( x1 > x2 )
{
startx = x2;
endx = x1;
}
else
{
startx = x1;
endx = x2;
}
float y = y1; // initial value
for(int x = startx; x <= endx; x++)
{
y += slope;
DrawPixel(x, (int)abs(y), color);
}
}
else if ( slope > 1 )
{
float x = x1; // initial value
int starty = 0;
int endy = 0;
if ( y1 > y2 )
{
starty = y2;
endy = y1;
}
else
{
starty = y1;
endy = y2;
}
for(int y = starty; y <= endy; y++)
{
x += 1/slope;
DrawPixel((int)x, y, color);
}
}
}

mysql get data from three tables using one id

mysql get data from three tables using one id

I have three different tables, which have following structure:
Food
ID | title
---+----------
1 | sandwich
2 | spaghetti
Ingridients
ID | food_reference | type | location | bought
----+----------------+------+----------+----------
100 | 1 | ham | storeA | 11-1-2013
101 | 1 | jam | storeB | 11-1-2013
102 | 2 | tuna | storeB | 11-6-2013
Tags
ID | food_reference | tag
----+----------------+-----
1000| 1 | Tag
1001| 1 | Tag2
1002| 2 | fish
and using one select I want to get all information from these three tables
(title,type,location,bought,tag) for one specific ID. I have tried
something like
SELECT food.*,ingridients.*,tags.* FROM food
JOIN ingridients
ON :id=ingridients.food_reference
JOIN tags
ON :id=tags.food_reference
WHERE id=:id
BUT this query returns for id=1 only one row from ingridients and tags
even though there are two matching rows (ham and jam, Tag and Tag2). Could
you tell me what am I doing wrong?

Saturday, 28 September 2013

In PHP would this be deemed correct?

In PHP would this be deemed correct?

I already wrote a post about an issue I had before about this but I had
that issue taken care of. Like my last post I have a form, text-box and a
button. I have everything done with this including Printing the original
word, Printing the number of characters in the word, Printing the word in
all caps and Printing the word in reverse order. My only issue I'm having
is trying to get whatever text I enter and then click the button to output
to Print the first letter of the word and Print the last letter of the
word. I've been doing a lot of looking around of PHP.net and I found that
substr is used to return a part of a string that I could use. The only
issue is when I write the code for it and try to execute my program it
errors out on that specific line. I'm not looking for the answer but could
someone just take a look and see what I'm doing wrong because I understand
everything completely but this is the only thing I'm hung up on.
$first = substr($_POST['entertext']);
echo "The first letter of the word is " . $first. "<br />\n";
$last = substr($_POST['entertext']);
echo "The first letter of the word is " . $last. "<br />\n";

WPF: How to bind object to ComboBox

WPF: How to bind object to ComboBox

Trying to learn how to bind objects to various types of controls. In this
instance, I want to get sample data in my object to appear in ComboBox.
The code runs but what appears instead of values (David, Helen, Joe) is
text "TheProtect.UserControls.Client")
XAML: (ucDataBindingObject.xaml)
<UserControl x:Class="TheProject.UserControls.ucDataBindingObject"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Width="Auto"
Height="Auto"
mc:Ignorable="d">
<Grid Width="130"
Height="240"
Margin="0">
<ComboBox Width="310"
HorizontalAlignment="Left"
VerticalAlignment="Top"
ItemsSource="{Binding Path=Clients}" />
</Grid>
</UserControl>
C#: ucDataBindingObject.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
namespace TheProject.UserControls
{
public partial class ucDataBindingObject : UserControl
{
public List<Client> Clients { get; set; }
public ucDataBindingObject()
{
Clients = new List<Client>();
Clients.Add(new Client(1, "David")); // sample data
Clients.Add(new Client(2, "Helen"));
Clients.Add(new Client(3, "Joe"));
InitializeComponent();
this.DataContext = this;
}
}
C# Client.cs
using System;
using System.Linq;
namespace TheProject.UserControls
{
public class Client
{
public int ID { get; set; }
public string Name { get; set; }
public Client(int id, string name)
{
this.ID = id;
this.Name = name;
}
}
}

Installing Gnuradio on ubuntu

Installing Gnuradio on ubuntu

Im trying to install Gnuradio, i need this to be able to install gqrx to
use my software defined radio dongle.
I have folloewd the guide at
https://www.jeroennijhof.nl/wiki/index.php/Software-Defined_Radio_on_Ubuntu
but the installation aborts because cheetah isnt installed. Python-cheetah
is in fact installed in its latest version, running sudo apt-get install
python-cheetah only states that it is already installed.
Does anyone know why gnuradio doesnt accept that Cheetah is installed?
Output from installation atempt:
-- Python checking for Cheetah >= 2.0.0
-- Python checking for Cheetah >= 2.0.0 - not found
CMake Error at volk/CMakeLists.txt:62 (message):
Cheetah templates required to build VOLK
-- Configuring incomplete, errors occurred!

Friday, 27 September 2013

cloud code : User can't access object which has ACL for the role it belongs

cloud code : User can't access object which has ACL for the role it belongs

The functionality i want to achieve is this
When a user registers, two roles(admin, users) are created
If the user is an admin he should be able to invite other users to join
for the same account with user privilege (non admin)
A user who is not admin should not be able to invite people to join
This is how i am trying to achieve this in cloud code
Create two roles when an account is created
Create two dummy objects with admin and user ACLs, below is the code for
these two steps
Parse.Cloud.afterSave("account", function(request) {
var accountName = request.object.get("name");
//create admin role
var adminRoleACL = new Parse.ACL();
adminRoleACL.setPublicReadAccess(false);
adminRoleACL.setPublicWriteAccess(false);
var adminRole = new Parse.Role(accountName + ADMINISTRATOR,
adminRoleACL);
adminRole.save();
//create user role
var userRoleACL = new Parse.ACL();
userRoleACL.setPublicReadAccess(false);
userRoleACL.setPublicWriteAccess(false);
var userRole = new Parse.Role(accountName + USER, userRoleACL);
userRole.save();
// create dummy object for each role with access to only that role
// we will use these dummy objects in cloud code to figure out whether
// the user belongs to that group.
//create dummy for admin
var dummy = new Dummy();
dummy.set("name", accountName + ADMINISTRATOR + DUMMY);
var dummyACL = new Parse.ACL();
dummyACL.setPublicReadAccess(false);
dummyACL.setRoleReadAccess(adminRole, true);
dummy.setACL(dummyACL);
dummy.save();
//create dummy for user
dummy = new Dummy();
dummy.set("name", accountName + USER + DUMMY);
dummyACL = new Parse.ACL();
dummyACL.setPublicReadAccess(false);
dummyACL.setRoleReadAccess(userRole, true);
dummy.setACL(dummyACL);
dummy.save();
});
After account is created i add this user to both admin as well as to the
user group, here is the code
Parse.Cloud.define("addUsersToRole", function(request, response) {
Parse.Cloud.useMasterKey();
var currentUser = request.user;
var accountName = request.params.accountname;
var query = new Parse.Query(Parse.Role);
query.contains("name", accountName);
query.find({
success : function(roles) {
console.log("roles: " + roles.length);
for (var i = 0; i < roles.length; i++) {
roles[i].getUsers().add(currentUser);
roles[i].save();
}
response.success();
},
error : function(error) {
response.error("error adding to admin role " + error);
}
});
});
Now when i try to do signup i just want to check if the current user can
find the admin dummy object which was created (since the ACL for that was
set to be accessed by only admin role). If the object can be read then it
should mean that the current user belongs to admin role right? Here is the
code
Parse.Cloud.define("inviteToSignUp", function(request, response) {
var userEmail = request.params.email;
var currentUser = request.user;
var accountName = currentUser.get("accountname");
//do it only if the user is admin
var query = new Parse.Query(Dummy);
query.equalTo("name", + accountName + ADMINISTRATOR + DUMMY);
query.first({
success : function(dummy) {
if(dummy) {
sendSignupEmail(userEmail, currentUser, request, response);
} else {
response.error("Invitation failed. You don't have the
priviledges to add new user. Please contact your
administrator'");
}
},
error : function(error) {
response.error("error while inviting users. " + error.message);
}
})
});
Now the problem is that even though the admin user is logged in the dummy
object created doesn't get returned in the query in the above method. Is
there anything i am missing? Is there a better way to achieve this
functionality?
I checked the data browser and i can see the two roles being created, the
user being member of both the groups. I also see that two dummy objects
are created each with these two ACL
{"role:XYZ_Administrator":{"read":true}}
{"role:XYZ_user":{"read":true}}

Detecting Mobile Safari

Detecting Mobile Safari

I need to detect if the user is browsing via mobile safari (either iPad,
iPhone or iPod). I could do this with JS or PHP but I would prefer to do
it with PHP. I need to detect just mobile safari and not other browsers on
the device.
Please don't reply and suggest feature detection as that is not an option
for me.

Show a menu on text selection

Show a menu on text selection

I want to be able to display a popover menu when a user highlights a
selection of text in a text area or content-editable. As far as I can
tell, Angular doesn't have any event binding around text selection, so has
anyone come across a solution for doing this whether it be in a directive
or otherwise?
A decent example of the intended behavior is if you go to
http://www.zenpen.io/ and highlight come of the text. A small menu comes
up. That is the behavior I am looking to emulate.

#EANF#

#EANF#

I am trying to use Reveal.js (https://github.com/hakimel/reveal.js/) on
WordPress with the Posts being the content per each slide.
I have gotten the post to display properly on the slides, but I am having
trouble finding a way to wrap posts that have the same category in a tag.
Basically, My current code looks something like this:
<section class="section chapter-1 ">
</section>
<section class="section chapter-1 ">
</section>
<section class="section chapter-1 ">
</section>
<section class="section chapter-2 ">
</section>
<section class="section chapter-2 ">
</section>
But I need it to look like this:
<section id="category-1">
<section class="section chapter-1 ">
</section>
<section class="section chapter-1 ">
</section>
<section class="section chapter-1 ">
</section>
</section>
<section id="category-2">
<section class="section chapter-2 ">
</section>
<section class="section chapter-2 ">
</section>
</section>
Here is my index.php code:
<div class="reveal content-area">
<div id="content" class="slides site-content" role="main">
<?php if ( have_posts() ) : ?>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentythirteen_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</div><!-- #content -->
</div><!-- #primary -->
... and so on with more 'chapters' and more categories
If you notice the second code example are grouped and wrapped in a section
tag with an ID of the category name.

Text in rounded corners and hover not working

Text in rounded corners and hover not working

<!DOCTYPE html>
<html>
<head>
<style>
.round{
-moz-border-radius:50%; /* for Firefox */
-webkit-border-radius:50%; /* for Webkit-Browsers */
border-radius:50%; /* regular */
opacity:1; /* Transparent Background 50% */
background:#eee;
padding:40px;
height:70px;
width:70px;
text-align: center;
alignment-adjust: middle;
vertical-align:middle;
text-decoration: none;
color:#000;
}
.round:hover{
-moz-border-radius:50%; /* for Firefox */
-webkit-border-radius:50%; /* for Webkit-Browsers */
border-radius:50%; /* regular */
opacity:1; /* Transparent Background 50% */
background:#000;
padding:40px;
height:70px;
width:70px;
text-align: center;
alignment-adjust: middle;
vertical-align:middle;
text-decoration: none;
color:#fff;
}
</style>
</head>
<body>
<a href="#"><div class="round"><img src="favicon.png" align="center"><br
/>Power and Electricity</div></a>
<a href="#"><div class="round"><img src="favicon.png" align="center"><br
/>Power and Electricity</div></a>
<a href="#"><div class="round"><img src="favicon.png" align="center"><br
/>Power and Electricity</div></a>
<a href="#"><div class="round"><img src="favicon.png" align="center"><br
/>Power and Electricity</div></a>
</body>
</html>
and goes my questions: 1. Why is the text decoration not working? 2. The
text changes color on hover but not the underline! Why? 3. All the div
appears in vertical one after another. How do i place it horizontally
across the screen and auto have it come to second row at the end of the
screen? 4. Is this the best practice? Which browsers will this not work
on? I tried on all the latest version of safari, chrome and firefox. Not
sure if it will work on IE8

Call to undefined function str_getcsv()

Call to undefined function str_getcsv()

I get this error
Call to undefined function str_getcsv()
It seems to be a php version. it didn't come out until version 5.3
Anyone know a way replace this function instead upgrade the PHP version?

Thursday, 26 September 2013

Declare a method inside an if statement and have it known to following method calls

Declare a method inside an if statement and have it known to following
method calls

I'm writing something in Android and in order to tailor for an older SDK,
I need to change what a variable becomes. I'm using ClipboardManager which
has different versions based on SDK. The issue is to create this variable
easily, I have to do it in an if, and my code won't compile after due to
the variable not being detected.
Example:
if(android.os.Build.VERSION.SDK_INT >= 11){
final android.content.ClipboardManager clipboard =
(ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
} else {
final android.text.ClipboardManager clipboard =
(ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
}
if (clipboard.hasPrimaryClip()) {
// Do stuff
}
Because the instance of clipboard depends on the SDK, if
(clipboard.hasPrimaryClip()) complains at me.
Is there any way to do this other than making two variables and checking
for null?

Wednesday, 25 September 2013

Get End Time from Start Time and Duration C#

Get End Time from Start Time and Duration C#

I have start time in format hh:mm:ss and then entering duration in hours
and selecting a day of week.
I want to calculate the end time based on above parameters.
For Example: of start time is 00:00:00 and duartion entered is 48 hours
with day of week as Sunday. The end time must be 00:00:00 hrs on Tuesday.
How to do it?

Thursday, 19 September 2013

How do I split a string into a bunch of variables?

How do I split a string into a bunch of variables?

I'm trying to make a calculator as to were you can input numbers and
operators regardless of spaces and I want to know how to split up the
input and convert it into other types.

event fired just before an elemet renders on html

event fired just before an elemet renders on html

I am working on a code where I am genrating my own DIVs using mustache and
appending it to the main index.html (keeping this a single page
application)
I know if I use jQueryMobile, there is a page event 'beforePageShow' which
is fired just before the page starts loading. You can use this to set some
dynamic variables that is used in the page.
I want to do something same in my page where I am rendering a div : a new
one if its not already appeneded to index.html or just hide/shiow if it
already exists. Although I want to initialize some environment variables
before the div loads. Is this possible?
Please help
Thanks Ankur

autocomplete in each row will return multiple values to fill-up the edit boxes in same row in a dynamic table

autocomplete in each row will return multiple values to fill-up the edit
boxes in same row in a dynamic table

I have a dynamic table with multi rows
<table>
<tr>
<td><input id="CustomerCompanyName" type="text"
class="Autocompletecompany" /></td>
<td><input id="QuoteCustomerId" type="text" class="QuoteCustomerId"
disabled /></td>
<td><input id="QuoteCurrencyId" type="text" class="QuoteCurrencyId"
disabled /></td>
</tr>
<tr>
<td><input id="CustomerCompanyName2" type="text"
class="Autocompletecompany" /></td>
<td><input id="QuoteCustomerId2" type="text" class="QuoteCustomerId"
disabled /></td>
<td><input id="QuoteCurrencyId2" type="text" class="QuoteCurrencyId"
disabled /></td>
</tr>
</table>
each row has an autocomplete textbox which will return more then value to
fill-up different edit box after spending couple of days searching for
solution I find a way to put all code together and making it work but I'm
facing one issue and I'm not able to resolve it
When the user searches in first row a list will display so the user can
select the company name and by selecting it, it will fill-up the
QuoteCustomerId and the QuoteCurrencyId
but then I try to do same scenario in second row the same list will be
display with a blank value and if you select any of them it will fill-up
the QuoteCustomerId and the QuoteCurrencyId with the correct value any
help please do i miss something there :
JavaScript
$(document).ready(function(){
$('.Autocompletecompany').autocomplete({
source:'CustomerList.php',
minLength:1,
select:function(event, ui)
{
var p = $(this).parent().parent(), i=ui.item;
p.find( ".QuoteCustomerId" ).val( i.id );
p.find( ".QuoteCurrencyId" ).val( i.QuoteCurrencyId );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item )
{
return $( "<li>" )
.append( "<a><strong>" + item.CustomerCompanyName + "</strong><br>
Currency :" + item.QuoteCurrencyId + "<br> Address :" +
item.Address + "</a><hr>" )
.appendTo( ul );
};
});
thanks a lot I appreciate any help

Lauch a process on a remote machine with impersonation c#

Lauch a process on a remote machine with impersonation c#

I'm trying to launch a process using impersonation with WMI and C#.
Here's what I have so far:
var coptions = new ConnectionOptions();
coptions.Username = String.Format(@"{0}\{1}", machine.Domain,
machine.Username);
coptions.Password = machine.Password;
coptions.Impersonation = ImpersonationLevel.Impersonate;
coptions.EnablePrivileges = true;
var mScope = new ManagementScope(String.Format(@"\\{0}\root\cimv2",
machine.Address), coptions);
var mClass = new ManagementClass(mScope, new
ManagementPath("Win32_Process"), new ObjectGetOptions());
object[] generatorProcess = { @"C:\test\test1.exe" };
mClass.InvokeMethod("Create", generatorProcess);
Exception:
E_ACCESSDENIED at mClass.InvokeMethod
How can I do it?
PS: The user I'm launching the process with does not have admin
privileges, is it required?

Run command on the Ansible host

Run command on the Ansible host

Is it possible to run commands on the Ansible host?
My scenario is that I want to take a checkout from a git server that is
hosted internally (and isn't accessible outside the company firewall).
Then I want to upload the checkout (tarballed) to the production server
(hosted externally).
At the moment, I'm looking at running a script that does the checkout,
tarballs it, and then runs the deployment script - but if I could
integrate this into Ansible that would be preferable.

unable to find what causes a compile time error

unable to find what causes a compile time error

I'm really frustrated. I'm using MinGW 4.8.0 (included in QtCreator 5.1)
with C++11. The problem is that I get a compile time error but I can not
find the source of the error. Is there a diagnostic tool that is a little
more specific?
The gcc log is the following:
Makefile.Debug:1491: recipe for target 'debug/adsync.o' failed
In file included from
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\memory:64:0,
from ..\aams/iocontroller/iocontroller.hpp:15,
from ..\aams/aams/aamscontext.h:13,
from ..\aams\src\aams\adsync.cpp:8:
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_construct.h:
In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1
= std::unique_ptr<aams::device::ADMessageReqRSSingle>; _Args = {const
std::unique_ptr<aams::device::ADMessageReqRSSingle,
std::default_delete<aams::device::ADMessageReqRSSingle> >&}]':
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_uninitialized.h:75:53:
required from 'static _ForwardIterator
std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator,
_InputIterator, _ForwardIterator) [with _InputIterator =
__gnu_cxx::__normal_iterator<const
std::unique_ptr<aams::device::ADMessageReqRSSingle>*,
std::vector<std::unique_ptr<aams::device::ADMessageReqRSSingle> > >;
_ForwardIterator =
std::unique_ptr<aams::device::ADMessageReqRSSingle>*; bool
_TrivialValueTypes = false]'
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_uninitialized.h:117:41:
required from '_ForwardIterator
std::uninitialized_copy(_InputIterator, _InputIterator,
_ForwardIterator) [with _InputIterator =
__gnu_cxx::__normal_iterator<const
std::unique_ptr<aams::device::ADMessageReqRSSingle>*,
std::vector<std::unique_ptr<aams::device::ADMessageReqRSSingle> > >;
_ForwardIterator =
std::unique_ptr<aams::device::ADMessageReqRSSingle>*]'
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_uninitialized.h:258:63:
required from '_ForwardIterator
std::__uninitialized_copy_a(_InputIterator, _InputIterator,
_ForwardIterator, std::allocator<_Tp>&) [with _InputIterator =
__gnu_cxx::__normal_iterator<const
std::unique_ptr<aams::device::ADMessageReqRSSingle>*,
std::vector<std::unique_ptr<aams::device::ADMessageReqRSSingle> > >;
_ForwardIterator =
std::unique_ptr<aams::device::ADMessageReqRSSingle>*; _Tp =
std::unique_ptr<aams::device::ADMessageReqRSSingle>]'
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_vector.h:316:32:
required from 'std::vector<_Tp, _Alloc>::vector(const
std::vector<_Tp, _Alloc>&) [with _Tp =
std::unique_ptr<aams::device::ADMessageReqRSSingle>; _Alloc =
std::allocator<std::unique_ptr<aams::device::ADMessageReqRSSingle> >]'
..\aams/aams/device/admessagereq.h:687:50: required from here
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\stl_construct.h:75:7:
error: use of deleted function 'std::unique_ptr<_Tp,
_Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp =
aams::device::ADMessageReqRSSingle; _Dp =
std::default_delete<aams::device::ADMessageReqRSSingle>]'
{ ::new(static_cast<void*>(__p))
_T1(std::forward<_Args>(__args)...); }
^
In file included from
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\memory:81:0,
from ..\aams/iocontroller/iocontroller.hpp:15,
from ..\aams/aams/aamscontext.h:13,
from ..\aams\src\aams\adsync.cpp:8:
c:\qt\tools\mingw48_32\lib\gcc\i686-w64-mingw32\4.8.0\include\c++\bits\unique_ptr.h:273:7:
error: declared here
unique_ptr(const unique_ptr&) = delete;
^

Oracle Business intelligence - multiple standalone BI on single machine

Oracle Business intelligence - multiple standalone BI on single machine

Im going to install new Oracle BI enterprise edition along existing Oracle
BI source edition. Is there any way i can install it on single machine?
Even using same BIPLATFORM schemas?
There isnt much to read about on oracle webpages. I see i can use software
only to install binaries or install new oracle BI. But my question is.
From tutorial I can see there is something like : Ensure you install New
oracle Business intelligence to separet middleware home.
My middleware home is .../fmw/ where Oracle BI is but also weblogic and
others. So should i install new instance of weblogic too, or just install
it under ../fmw/ to new folder named f.e. : .../fmw/Oracle_BI2/
Im quite confused. Im working for the first time with business
intelligence from oracle.
IF someone experienced can give me a hint it would be much appreciated.
MATT.

Wednesday, 18 September 2013

C# and .Net Programming on windows phone

C# and .Net Programming on windows phone

i'm currently developing windows 8 Application using visual studio 2012
with C# and .Net.
I'm used template from visual studio 2012 (in new project -> Installed ->
other template -> other languages -> visual C# -> window store -> blank
app xaml)
then i execute it on the simulator (then windows tablet simulator appear),
my question, can my application that i built can running on windows phone
7 or 8?

Add AtomicLong to AtomicLong?

Add AtomicLong to AtomicLong?

I'm creating a program to create the Fibonacci sequence, but it keeps
messing up because longs can't contain it for very long. I'm trying to
switch to AtomicLongs, but I cannot add a atomiclong to an atomiclong,
only a regular long? How can I do this, or would it be better to do
something more dynamic, like adding two arrays of bytes?

Coffescript: Reserved Word error

Coffescript: Reserved Word error

I have the following piece of code in Coffee-script
class @Badge
setIssues: (count)->
@count = count
@render()
When i run my script, i get the following error ,
Uncaught Syntax-Error: Unexpected reserved word
I am complete newbie in Coffee-script , so totally off-guard as of how to
fix this error
I tried removing the word 'class' , hence removing the first
line(including @Badge), as it is mentioned here , that 'class' is a
reserved word . On doing so , it resulted in the error ,
Uncaught SyntaxError: Unexpected token >
How can i fix this error ?

how to grabb version name,version code, package name and minsdk level of an apk using php

how to grabb version name,version code, package name and minsdk level of
an apk using php

i need a class or maybe a function for get version name,version code,
package name and minsdk level from and apk file...
i found apk parser php class but in server it do not work good....
i found this function too but this function has error too...
function apps_infosfromapk($file)
{
global $AAPT_DIR;
$infos=array();
$retour = array();
exec ($AAPT_DIR." l -a ".realpath($file),$retour);
$txt = "";
for($i = 0; $i < sizeof ($retour); $i++)
$txt .= $retour[$i];
$t1 = explode('android:versionName(0x0101021c)="',$txt);
$t3 = explode('"',$t1[1]);
$version = $t3[0];
$t2 = explode ('package="', $txt);
$t4 = explode ('"', $t2[1]);
$package = $t4[0];
$t5 = explode('A: android:minSdkVersion(0x0101020c)=(type 0x10)0x',$txt);
$t6 = explode(' ',$t5[1]);
$minSdk = intval($t6[0]);
$txt2=explode('android:name(0x01010003)="android.permission.',$txt);
$it=0;
$permissions="";
for($i=1;$i<sizeof($txt2);$i++)
{
$tmp=explode('"',$txt2[$i]);
if($it==0)
$permissions.=$tmp[0];
else
$permissions.=";".$tmp[0];
$it++;
}
$infos[0]=$version;
$infos[1]=$package;
$infos[2]=$minSdk;
$infos[3]=$permissions;
return $infos;
}

VB 6 ActiveX component name under DCOM config

VB 6 ActiveX component name under DCOM config

I have created an ActiveX component in VB 6.0 It's a single dll
(appname.dll). The app works fine. But when I try to see my application
under DCOM config in component services mmc I don't see the name of the
app but rather I just see the GUID. My question is, how do I create an
ActiveX dll that shows name in DCOM config window and not the GUID.
Thanks in advance.

Where do a Grails controller's "expando" methods come from?

Where do a Grails controller's "expando" methods come from?

According to the documentation, a Grails controller is simply a class with
"Controller" appended to the name and saved in grails-app/controllers/.
The simplest of such a class being:
package some.package
class FooController {
def index = {}
}
When the Grails application is run, this controller will inherit some
standard methods like getParams and getSession. From the attached
screenshot I can see that these are added via
groovy.lang.ExpandoMetaClass. What I don't see is how this happens. The
controller doesn't implement any interfaces or extend any abstractions.
Where do these methods come from?

Why does a margin appear on the right side of my site?

Why does a margin appear on the right side of my site?

HI hope someone can help answer my question its really starting to bug me!
The site is here http://www.calypsopretattoo.com/
When you click on the about tab the information comes up but a margin on
the right hand side of the page appears and creates a massive white space?
I've tried editing the css a number of times but nothing. any ideas??

How do I fetch attribute's value of any element in Angular?

How do I fetch attribute's value of any element in Angular?

We can define an attribute in angular the following ways:
ng:model="name"
ng_model="name"
ng-model="name"
data-ng-model="name"
x-data-ng-model="name"
When I try to get the attribute value using .attr('ng-model') then it
ignores the other variants.
Is there any way in angular to get the attribute's value regardless of how
it was used?

Tuesday, 17 September 2013

Is there Any possibility available to create a Slideshow of images in html page without using jquery and javascript

Is there Any possibility available to create a Slideshow of images in html
page without using jquery and javascript

i`m a newbie for web development.. someone clear my doubt..
"Is there Any possibility available to create a Slideshow of images in
html page without using jquery and javascript..."

Text issues on pygame

Text issues on pygame

Im making a Pong game that displays the player and enemy score based on
the screen width. Both scores should keep a 20 pixels distance from the
middle of the screen and everything was working just fine but i've ran in
to some problems:
First, i've made the game in a way that the player can be in both sides,
left or right. When the scores are initialized, some attributes are passed
to a Text class (like top or centerx) and these attributes will define
where it should be placed. I tried to do it like:
self.player_score = Text(self.player.score, 32, WHITE,
top = 10, right = SCREEN_WIDTH/2 - 20)
self.enemy_score = Text(self.player.score, 32, WHITE,
top = 10, left = SCREEN_WIDTH/2 + 20)
but since the player and sides can change thats not a good solution.
Second, I want the text to always be at the same distance from the center
of the screen, but when the score grows to two or more digits the text
occupies more space. For the right side its not a problem, but for the
left side the text keeps getting closer and closer to the middle of the
screen. Here's the set_value method from my Text class:
def set_value(self, new_value):
if new_value != self._value:
self._value = new_value
self.image = self._create_surface()
self.rect = self.image.get_rect(top = self.rect.top,
bottom = self.rect.bottom,
left = self.rect.left,
right = self.rect.right,
centerx = self.rect.centerx,
centery = self.rect.centery)
How can I solve these problems?

Issue after upgrading struts2

Issue after upgrading struts2

We recently upgraded the version of struts in our website from 2.1.8.1 to
2.3.4. Immediately after upgrading we noticed the following exception
after the first post back to the server. Any help in determining the issue
or how to troubleshoot this would be appreciated. We've been scratching
our head for days. The thing that makes this really bad is when the site
is deployed to websphere once this exception is thrown the site stops
working completely until you restart the jvm. In tom cat the exception is
thrown but the site continues to work.
2013-09-17 15:09:18,919 [WebContainer : 0] ERROR
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager -
Caught exception while loading file java/lang/Object-validation.xml
java.lang.NullPointerException at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.loadFile(AnnotationActionValidatorManager.java:383)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.buildClassValidatorConfigs(AnnotationActionValidatorManager.java:271)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.buildValidatorConfigs(AnnotationActionValidatorManager.java:363)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.buildValidatorConfigs(AnnotationActionValidatorManager.java:342)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.buildValidatorConfigs(AnnotationActionValidatorManager.java:342)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.getValidators(AnnotationActionValidatorManager.java:94)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.validate(AnnotationActionValidatorManager.java:133)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.validate(AnnotationActionValidatorManager.java:125)
at
com.opensymphony.xwork2.validator.AnnotationActionValidatorManager.validate(AnnotationActionValidatorManager.java:120)
at
com.opensymphony.xwork2.validator.ValidationInterceptor.doBeforeInvocation(ValidationInterceptor.java:222)
at
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
at
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
at
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:511)
at
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)
at
com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
at
com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:125)
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:83)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at
com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:190)
at
com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:125)
at
com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:80)
at
com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908)
at
com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:997)
at
com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.invokeFilters(DefaultExtensionProcessor.java:1079)
at
com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.handleRequest(DefaultExtensionProcessor.java:999)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3954)
at
com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
at
com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:945)
at
com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1592)
at
com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:191)
at
com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:453)
at
com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:515)
at
com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:306)
at
com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:84)
at
com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1784)
at
com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at
com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at
com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) at
com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204) at
com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905) at
com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1656)

Java String.toUpperCase()

Java String.toUpperCase()

Just the other day I ran into a strange strange bug. I had a string of
characters that I had to build. And as a delimiter the host system I was
communicating with used char 254. Anyway I build out my string and sent it
to the host. On the host I was receiving char 222 as the delimiter! After
scratching my head and looking into it deeper it seemed odd that
hex : FE, binary: 11111110
was turning into
hex: DE, binary: 11011110
I tried the Locale.getDefault() and Locale.ENGLISH to no avail.
Could it be that the implementation of String.toUpperCase has a mask for
ALL chars except specific hard coded ones?
For now I'm using the following to get around the problem:
public static String toUpperCase(String input) {
char[] chars = input.toCharArray();
for(int i = 0; i < chars.length; ++i ) {
if( chars[i] > 96 && chars[i] < 123 ) {
chars[i] &= 223;
}
}
return new String(chars);
}
my question is am I missing something? Is there a better way that I am not
aware of? Thanks a bunch!

Box API on iOS 7

Box API on iOS 7

BoxAppToAppAPInfo.h
BoxAppToAppAPIInfo * info == [BoxAppToAppAPI appToAppInfoFromOpenURL:url
sourceApplication:source annotation:annotation]
NSData * data = [info receivedFileData];
This line works perfectly fine in iOS 6, but it returns nil in iOS 7 GM.
Is this a known issue? Should I be doing something different in iOS 7 to
get this to return the proper data?

Equivalent of boxplot lwd parameter for bwplot

Equivalent of boxplot lwd parameter for bwplot

I want to have the box plotted with thicker lines. In boxplot function I
simply put lwd=2, but in the lattice bwplot I can pull my hair out and
haven't found a solution! (with the box I mean the blue thing in the image
above)
Sample code to work with:
require(lattice)
set.seed(123)
n <- 300
type <- sample(c("city", "river", "village"), n, replace = TRUE)
month <- sample(c("may", "june"), n, replace = TRUE)
x <- rnorm(n)
df <- data.frame(x, type, month)
bwplot(x ~ type|month, data = df, panel=function(...) {
panel.abline(h=0, col="green")
panel.bwplot(...)
})

Sunday, 15 September 2013

Creating a For loop to create multiple 'Click' events in JavaScript/JQuery

Creating a For loop to create multiple 'Click' events in JavaScript/JQuery

I want to create a For loop for a series of 'click' events on my page. I'm
creating a timetable where clicking on a Day button will display the
events assigned to that day in a div box.
HTML
<div class="cwt-buttons">
<a id="cwt-button1">Monday</a>
<a id="cwt-button2">Tuesday</a>
<a id="cwt-button3">Wednesday</a>
<a id="cwt-button4">Thursday</a>
<a id="cwt-button5">Friday</a>
<a id="cwt-button6">Saturday</a>
<a id="cwt-button7">Sunday</a>
</div>
<div id="cwt-timetable">
<div class="current">Housework</div>
<div class="cwt-Day1">Kickboxing</div>
<div class="cwt-Day2">Homework</div>
<div class="cwt-Day3">Yoga</div>
<div class="cwt-Day4">Eating</div>
<div class="cwt-Day5">Fasting</div>
<div class="cwt-Day6">Running</div>
<div class="cwt-Day7">Funeral</div>
</div>
JS
$(function() {
for ( var i = 1; i < 8; i++ ) {
var clickedButton = $("#cwt-button"+i);
$(clickedButton).click(function() {
var currentDay = $('#cwt-timetable div.current');
var selectedDay = $('#cwt-timetable div.cwt-Day'+i);
currentDay.removeClass('current').addClass('previous');
(selectedDay).css({ opacity: 0.0 }).addClass('current').animate({
opacity: 1.0 }, 1000,
function() {
currentDay.removeClass('previous');
});
})
}
});
The JavaScript works fine when I have the exact value in e.g. "#cwt-button1"
It just doesn't work when I concatenate the 'i' counter in the loop.
Can anyone see where I'm going wrong? Or am I do something JavaScript
can't handle?

Read xml node attribute

Read xml node attribute

I have an xml document that have nodes like this, <ITEM id="1"
name="bleh"... /> What I want to do is get all id's attribute value for
each ITEM node that exists in the document. So, how can I do that?

use python to create 2D coordinate

use python to create 2D coordinate

I am truly novice in python. Now, I am doing a project which involves
creating a list of 2D coordinates. The coordinates should be uniformly
placed, using a square grid (10*10),
like(0,0)(0,1)(0,2)(0,3)...(0,10)(1,0)(1,2)(1,3)...(2,0)(2,1)(2,2)...(10,10)
Here is my code:
coordinate = []
x = 0
y = 0
while y < 10:
while x < 10:
coordinate.append((x,y))
x += 1
coordinate.append((x,y))
y += 1
print(coordinate)
But I can only get:[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6,
0), (7, 0), (8, 0), (9, 0), (10, 0), (10, 1), (10, 2), (10, 3), (10, 4),
(10, 5), (10, 6), (10, 7), (10, 8), (10, 9)] How can I rewrite my code to
get all the points? Thanks

Thread.Abort() creates deadlock when worker thread calls Dispatcher.Invoke()

Thread.Abort() creates deadlock when worker thread calls Dispatcher.Invoke()

Two threads: main (GUI) and worker. The worker asks the main to update
using Dispatcher.Invoke(...). At some point, as a result of user
intervention, I must abort the worker using Thread1.Abort(). But a
deadlock seems to be created in this sequence:
T1 invokes for an action
main-thread aborts T1

I know, Aborting is evil (what should I do ? insert CheckIfCanceled()
every two lines ??), but assuming it's necessary - how can I prevent the
deadlock ?

wp_list_pages, hide parent with no ancestor and show children to chosen post

wp_list_pages, hide parent with no ancestor and show children to chosen post

I'am trying to create a menu using wp_list_pages and I want the end result
to look like this:
parent ( no ancestor ) <-- This one should be hidden
- Children "Some Title"( clicked )
- Children1 to "Some Title"
- Children2 to "Some Title"
- Children "Some other title" ( When clicking on this, children to
"Somte Title" will hide and children to "Some other title" show )
I am using the following code, and I cant figure out how to modify it to
give me the result I want.
<?php
//if the post has a parent
if($post->post_parent){
//collect ancestor pages
$relations = get_post_ancestors($post->ID);
//get child pages
$result = $wpdb->get_results( "SELECT ID FROM wp_posts WHERE
post_parent = $post->ID AND post_type='page'" );
if ($result){
foreach($result as $pageID){
array_push($relations, $pageID->ID);
}
}
//add current post to pages
array_push($relations, $post->ID);
//get comma delimited list of children and parents and self
$relations_string = implode(",",$relations);
//use include to list only the collected pages.
$sidelinks =
wp_list_pages("title_li=&echo=0&include=".$relations_string);
}else{
// display only main level and children
$sidelinks =
wp_list_pages("title_li=&echo=0&depth=1&child_of=".$post->ID);
}
if ($sidelinks) { ?>
<?php echo the_title(); ?>
<ul>
<?php //links in <li> tags
echo $sidelinks;
?>
</ul>
<?php } ?>
The example above gives me a layout looking like this and it shows the
parent with no ancestor and not the sibling to the clicked Children:
parent ( no ancestor )
- Children "Some Title"( clicked )
- Children1 to "Some Title"
- Children2 to "Some Title"
Appreciate any help!

ADODC and DBGRID on seperated Dialogs

ADODC and DBGRID on seperated Dialogs

can I bind dbgrid on a dialog to adodc which is on another dialog the main
problem is that the (datasource property) in dbgrid doesnt list the ADODDC
to be selected my project in Visual C++ 6 thank you in advance .

Saturday, 14 September 2013

Django, Postgresql raise OperationalError

Django, Postgresql raise OperationalError

I working in Ubuntu 12.04, Django 1.5.1 and Postgresql 9.1 and suddenly i
get an error
Exception Type: OperationalError
Exception Value: FATAL: cache lookup failed for access method 403
... what did that mean?

History API and History.js hashchange/anchorchange issue

History API and History.js hashchange/anchorchange issue

When I am on www.mysite.com/raj and I do History.pushState(null, '',
'www.mysite.com/raj/bla#side'), the URL seems to immediately move from the
pushed URL to www.mysite.com/raj/side.
I am not understanding why this is happening.

Using + in a java enum type

Using + in a java enum type

I'm fairly new to Java and I'm trying to use the + character as part of an
enum type, but the compiler is complaining about the syntax because I
believe it sees it as an operator.
I'd like to do the following:
enum mediaType{
FACEBOOK,GOOGLE+,TWITTER;
}
Any ideas?
Thanks!

Is BackgroundWorker.RunWorkerCompleted Thread Safe

Is BackgroundWorker.RunWorkerCompleted Thread Safe

Have a problem that is very hard to reproduce.
The exception is:
e.Exception.Message = Object reference not set to an instance of an object.
e.Exception.StackTrace
at
System.Windows.Controls.ItemContainerGenerator.MoveToPosition(GeneratorPosition
position, GeneratorDirection direction, Boolean allowStartAtRealizedItem,
GeneratorState& state)
at
System.Windows.Controls.ItemContainerGenerator.Generator..ctor(ItemContainerGenerator
factory, GeneratorPosition position, GeneratorDirection direction, Boolean
allowStartAtRealizedItem)
I catch that in App.cs App_DispatcherUnhandledException
I think that is from XAML as I have all the Break on Thrown turned on very
every option in Visual Studio
And I am pretty sure I have all the code behind wrapped in Try Catch
For sure the page where I think the error is originating is catching all
code behind exceptions.
And if I don't have the Tab visible so the XAML will not see a
NotifyChanged I cannot get error to happen.
If I break on the get for those public properties I cannot get the error
to happen.
As I slow it down to try and debug then it is harder to reproduce.
Have some tabs where I display text using a TextBlock and formatted text
using FlowDocumentViewer.
Source is bound to public properties. The public property for the
TextBlock.Text is RawText and the backing variable is rawText.
I get the text and information to highlight the text on a BackgroundWorker
Before calling the BackgroundWorker I set the rawText to "getting text"
call CancelAsync().
Then on RunWorkerCompletedEventHandler I set the rawText to the actual
text. Then I only call notifypropertychanged if that tab is selected so it
does not render if it is not visible.
Could the problem be that I am changing the rawText in the
RunWorkerCompletedEventHandler while the control is reading the rawText?
Or I am changing the rawText to "getting text" while the UI control is
reading the text? Reaching but I have worked on this for 3 days and that
is all I can figure.
And other thoughts?
Would placing locks on those assignments fix it?
Not MVVM.

How to send mail with PHP WITHOUT smtp? [on hold]

How to send mail with PHP WITHOUT smtp? [on hold]

I am making a form on my website and I cant seem to get it to work. I have
000webhost as my websites host and they do not support smtp. So I am
wonder how I can send mail on PHP without an smtp server. I have tried
using gmails smtp but so far i have had no luck and get tons of syntax
errors. If you guys have any WORKING code that will help me with this
please answer. Thanks

A field in the dataset 'Dataset1' has the name" " . Field names must be CLS-compliant identifiers

A field in the dataset 'Dataset1' has the name" " . Field names must be
CLS-compliant identifiers

Im having an error when executing my report. I used report.rdlc using
report viewer. My columns are Student ID, First Name, Last Name, Middle
Initial, Contact Number. Can someone help me with this?

Use Ant and Closure Compiler to compile files matching filename pattern?

Use Ant and Closure Compiler to compile files matching filename pattern?

I am working on a web project involving a lot of JavaScript and have
decided to split the JS files for better maintainability.
Here is a quick summary of the JavaScript files I have:
app.core.js
app.pages.all.js
app.pages.page_a.js
app.pages.page_b.js
app.pages.page_c.js
...
app.final.js
I need Closure Compiler to compile the JavaScript files in such a way that
app.core.js is compiled first, followed by app.pages.*.js, and finally
app.final.js.
This needs to be done twice, once to produce a pretty printed version for
development and debugging purposes (output file app.js) and once for a
minified version for production (output file app.min.js).
I understand I can use wildcards (from this article) to select files
matching a filename pattern, but am unsure how to use that in combination
with manually specified files to retain compilation order (necessary due
to dependencies).
Currently, the relevant section of my build.xml file looks like this:
<target name="js.core.compile">
<property name="js.dir" value="app/webroot/js" />
<jscomp compilationLevel="simple" debug="false"
output="${js.dir}\app.js" forceRecompile="true" prettyPrint="true">
<sources dir="${js.dir}">
<file name="app.core.js" />
<file name="app.pages.all.js" />
<file name="app.pages.page_a.js" />
<file name="app.pages.page_b.js" />
<file name="..." /> <!-- simplified for brevity -->
<file name="app.final.js" />
</sources>
</jscomp>
<jscomp compilationLevel="simple" debug="false"
output="${js.dir}\app.min.js" forceRecompile="true">
<sources dir="${js.dir}">
<file name="app.core.js" />
<file name="app.pages.all.js" />
<file name="app.pages.page_a.js" />
<file name="app.pages.page_b.js" />
<file name="..." /> <!-- simplified for brevity -->
<file name="app.final.js" />
</sources>
</jscomp>
</target>
My question in summary is:
How can I get Ant to select all the app.pages.x files automatically but
still retain the compilation order for app.core.js and app.final.js?
Is it possible to specify the just once as some form of variable (similar
to <property>)?

Friday, 13 September 2013

System function matches does not work in Oxygen schematron validation

System function matches does not work in Oxygen schematron validation

I'm using OXygen XML Developer 15 to run a XML file validation against
schematron. I'm getting errors on the system function "matches" on lines
such as the following
<assert
test="matches(cda:languageCode/@code,'(([a-z]{2})(\-[A-Z]{2})?)')">
I searched for answers on the Internet and found this posting indicating
it's an oXygen issue. But, the posting was like 6 years ago. I can't
believe the problem still exists. Or is there something I'm missing here.
Even though I really like oXygen, but I don't have to use it. So if I can
not resolve this issue, can somebody recommend an alternative XML tool
that can do schematron validation?

C++ map an integer to an array of boolean

C++ map an integer to an array of boolean

I have been trying to create a map from integer to an array of bools.
However, the following code does not seem to work.
map<int, bool[]> myMap;
bool one[] = {true, true, false};
myMap[1] = one;
I do not use array that much and there seems to be something seriously
wrong here. Can someone point it out? Thanks in advance.

What is difference between pthread_mutex_lock() and pthread_mutex_trylock()

What is difference between pthread_mutex_lock() and pthread_mutex_trylock()

I am writing an application using parallel programming and want to use
synchronization. What is difference between these two functions and when
to use which.?

SQL for sum of all "children"

SQL for sum of all "children"

Doing a table for budget accounts, my hierarchy is stored in a "path"
column like so:
groceries.produce.vegetables.tomatoes
groceries.produce.vegetables.potatoes
groceries.produce.fruit
groceries.baking.flour
etc
Works great when I need to grab all produce because I can just do a
LIKE 'produce.%'
query and get anything beneath it in the tree.
However, for any given query, I would like to have a "total" column to sum
up prices of all records "beneath".
The only way I can think of is to do a pattern match on a GROUP BY, but I
have a hunch I may be going down the wrong path.
Any suggestions would be much appreciated.

maximum recursion depth exceeded, overriding methods in new class under UserList

maximum recursion depth exceeded, overriding methods in new class under
UserList

I am creating a new class in UserList, and trying to override the add,
append, and extend methods so that duplicate values will not be added to
the list by any of these operations. So far I have started with trying to
override the append method and when I try to implement the class on an
object I get the error: maximum recursion depth exceeded. Here's what I
have so far:
from collections import UserList
class UList(UserList):
def append(self,item):
for s in self:
if item == s:
print ("Item already exists in list")
else:
self.append(item)
x = [1,2,3,4,5]
z = UList(x)
print (z)
z.append(1)

Display Wordpress Taxonomy list with description

Display Wordpress Taxonomy list with description

Is there a way to display the Taxonomy Description under each Taxonomy in
the list.
<?php
$taxonomyName = "tax";
$terms = get_terms($taxonomyName,array('parent' => 0));
foreach($terms as $term) {
echo '<a
href="'.get_term_link($term->slug,$taxonomyName).'">'.$term->name.'</a>';
$term_children = get_term_children($term->term_id,$taxonomyName);
echo '<ul>';
foreach($term_children as $term_child_id) {
$term_child = get_term_by('id',$term_child_id,$taxonomyName);
echo '<li><a href="' . get_term_link( $term_child->name,
$taxonomyName ) . '">' . $term_child->name . '</a></li>';
}
echo '</ul>';
}
?>

Limit the number of attempts in Android

Limit the number of attempts in Android

I developed an android app in which ...SMS can be sent from application to
any mobile number ...I would like to limit this process for four number of
times.. What I have to do for that ... I am giving my code here...
package com.example.sms;
import java.util.StringTokenizer;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
Button btnSendSMS, btnCredit;
EditText txtPhoneNo, txtMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS2);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo2);
txtMessage = (EditText) findViewById(R.id.txtMessage2);
btnCredit = (Button) findViewById(R.id.button1);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String message = txtMessage.getText().toString();
String phoneNo = txtPhoneNo.getText().toString();
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 &&
message.trim().length()>0) {
sendSMS(tempMobileNumber, message);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and
message.",
Toast.LENGTH_SHORT).show();
}
}
}
});
btnCredit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, credits.class );
startActivity(i);
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic
failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
},new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not
delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI,
deliveredPI);
}
}

Thursday, 12 September 2013

how to draw a Bitmap on the Top Right of the Canvas

how to draw a Bitmap on the Top Right of the Canvas

I am trying to draw a bitmap on top right hand corner of the Canvas
So far I have done the following:
//100x40 dimensions for the bitmap
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.backbutton);
Rect source = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Rect bitmapRect = new Rect(0, 0, canvasWidth -200,50);
canvas.drawBitmap(bitmap, source, bitmapRect, paint);
The problem is that when I run the app, the bitmap doesn't appear on the
screen. Full code:
public class MyView extends View {
Rect bitmapRect;
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas); //To change body of overridden methods use
File | Settings | File Templates.
Bitmap bitmap =
BitmapFactory.decodeResource(getResources(),R.drawable.backbutton);
Rect source = new Rect(0,0,bitmap.getWidth(), bitmap.getHeight());
bitmapRect = new Rect(0,0, bitmap.getWidth(), bitmap.getHeight());
canvas.drawBitmap(bitmap, source, bitmapRect, new Paint());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
if(null != bitmapRect && bitmapRect.contains(x,y)){
Toast.makeText(view.getContext(), "this works",
Toast.LENGTH_LONG).show();
}
return super.onTouchEvent(event); //To change body of overridden
methods use File | Settings | File Templates.
}
Can someone help me here please?

HTML app similar to Air Sketch

HTML app similar to Air Sketch

Is it possible to create an app similar to the iPad app Air Sketch using
HTML and Javascript? The app to be developed enables the user to draw in a
canvas on a mobile device and could broadcast it to other devices by
accessing the IP given by the app in a web browser. I will be using
PhoneGap as well to port the HTML app to native platforms.
Thanks.

Print all lines between pattern where any line matches second pattern

Print all lines between pattern where any line matches second pattern

I have an email log file like this:
2013-09-11 12:02:08 INFO: ------------------------------
2013-09-11 12:02:08 INFO: Javamail session sending email
2013-09-11 12:02:08 INFO: Session properties:
2013-09-11 12:02:08 INFO: com.hof.email.starttime=20130911120208
2013-09-11 12:02:08 INFO: mail.smtp.auth=true
2013-09-11 12:02:08 INFO: mail.smtp.connectiontimeout=60000
2013-09-11 12:02:08 INFO: mail.smtp.host=mailserver
2013-09-11 12:02:08 INFO: mail.smtp.port=25
2013-09-11 12:02:08 INFO: mail.smtp.timeout=60000
2013-09-11 12:02:08 INFO: mail.transport.protocol=smtp
2013-09-11 12:02:08 INFO: From: Support
2013-09-11 12:02:08 INFO: To: Customer
2013-09-11 12:02:08 INFO: Subject: Your Report Data
2013-09-11 12:02:08 INFO: Message ID: <id>
2013-09-11 12:02:09 INFO: Email sent successfully
2013-09-11 12:02:09 INFO: Javamail session ended
2013-09-11 12:02:09 INFO: ------------------------------
What I need to do is print this entire record if the email subject matches
a particular string.
That is, what I think I'd like to do is, when Subject = 'Your Report
Data', then print all lines between and including the n-1th occurrence of
'------------------------------' and the 1st occurrence of
'------------------------------' from the Subject match.

XCode: with lldb, how would I call po on zombie object?

XCode: with lldb, how would I call po on zombie object?

I have a crash in some code that happens only when the app is busy running
several NSOperations at once.
With Zombies enabled (I am on ARC with a OS X app), I get a nice message
like: -[__NSDictionaryM release]: message sent to deallocated instance
0x104da4f30
This happens when the OS is cleaning up the NSOperation. I would like to
see the contents of the dictionary, but
(lldb) po 0x104da4f30
or (lldb) po [0x104da4f30 description]
don't work,
error: Execution was interrupted, reason: EXC_BREAKPOINT
(code=EXC_I386_BPT, subcode=0x0).
The process has been returned to the state before expression evaluation.
it seems since the object is a zombie, it will not run the code. By seeing
the dictionary contents, I can tell who made it and where I messed up.
Anyone know how to tell lldb to skip the exception? I can see hints in the
lldb help, but my attempts did not help.

Wednesday, 11 September 2013

ways to inject a object of a class in spring controller?

ways to inject a object of a class in spring controller?

I need to inject a object of a java class in spring controller through
applicaionContext.xml. My controller will be ,
@Controller
public class SpringController{
private MyClass obj;
}
I know I can do it with @Autowired. Is this really good to create a object
for a ontroller through applicaionContext.xml ? Also can I inject a object
using the <property> tag in applicationContect.xml.
Is this really possible ? or please forgive me if it is a stupid question.
I need to know the possible ways for how to inject a object of a class in
Spring controller ?

How does an app with lower base sdk work?

How does an app with lower base sdk work?

In XCode I can specify Base SDK. I am wondering how does that work behind
the scenes? If I am running an app, for example, on a device that has iOS
7 and my base SDK is iOS 6, then how come the app has the old 'look and
feel'? Does XCode compile the older SDK and include it within my app or
does new version of iOS comes with older libraries/SDKs?
In other words, does the run time know this app is compiled with lower
base SDK and somewhere in UIKit's code it does:
if (lower SDK) {
//show old look/feel
} else {
//show new look/feel
}
or does the app itself include the old library and load it ?
Thanks