Monday, 30 September 2013

How to get virtualized SR-IOV Infiniband interface UP?

How to get virtualized SR-IOV Infiniband interface UP?

I've spent several days on this now and I've managed to get SR-IOV working
with the Mellanox Infiniband card using the latest firmware.
The Virtual Functions appear in Dom0 as
06:00.1 Network controller: Mellanox Technologies MT27500 Family
[ConnectX-3 Virtual Function] 06:00.2 Network controller: Mellanox
Technologies MT27500 Family [ConnectX-3 Virtual Function] 06:00.3 Network
controller: Mellanox Technologies MT27500 Family [ConnectX-3 Virtual
Function] 06:00.4 Network controller: Mellanox Technologies MT27500 Family
[ConnectX-3 Virtual Function]
I've then detached 06:00.1 from Dom0 and assigned it to xen-pciback.
I've passed this into a Xen test domain.
lspci inside the test DomU shows:
00:01.1 Network controller: Mellanox Technologies MT27500 Family
[ConnectX-3 Virtual Function]
I have the following modules loaded in DomU
mlx4_ib
rdma_ucm
ib_umad
ib_uverbs
ib_ipoib
dmesg output for mlx4 drivers shows:
[ 11.956787] mlx4_core: Mellanox ConnectX core driver v1.1 (Dec, 2011)
[ 11.956789] mlx4_core: Initializing 0000:00:01.1
[ 11.956859] mlx4_core 0000:00:01.1: enabling device (0000 -> 0002)
[ 11.957242] mlx4_core 0000:00:01.1: Xen PCI mapped GSI0 to IRQ30
[ 11.957581] mlx4_core 0000:00:01.1: Detected virtual function - running
in slave mode
[ 11.957606] mlx4_core 0000:00:01.1: Sending reset
[ 11.957699] mlx4_core 0000:00:01.1: Sending vhcr0
[ 11.976090] mlx4_core 0000:00:01.1: HCA minimum page size:512
[ 11.976672] mlx4_core 0000:00:01.1: Timestamping is not supported in
slave mode.
[ 12.068079] <mlx4_ib> mlx4_ib_add: mlx4_ib: Mellanox ConnectX
InfiniBand driver v1.0 (April 4, 2008)
[ 12.184072] mlx4_core 0000:00:01.1: mlx4_ib: multi-function enabled
[ 12.184075] mlx4_core 0000:00:01.1: mlx4_ib: operating in qp1 tunnel mode
I've even got the ib0 device appearing.
ib0 Link encap:UNSPEC HWaddr
80-00-05-49-FE-80-00-00-00-00-00-00-00-00-00-00
inet addr:10.10.10.10 Bcast:10.10.10.255 Mask:255.255.255.0
UP BROADCAST MULTICAST MTU:2044 Metric:1
RX packets:117303 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:256
RX bytes:6576132 (6.5 MB) TX bytes:0 (0.0 B)
I can even locally ping 10.10.10.10.
However, those pings aren't sent out on the infiniband fabric.
It appears to be because the link is down. ibstat shows:
CA 'mlx4_0'
CA type: MT4100
Number of ports: 1
Firmware version: 2.30.3000
Hardware version: 0
Node GUID: 0x001405005ef41f25
System image GUID: 0x002590ffff175727
Port 1:
State: Down
Physical state: LinkUp
Rate: 10
Base lid: 9
LMC: 0
SM lid: 1
Capability mask: 0x02514868
Port GUID: 0x0000000000000000
How do I get it UP? the domU link is UP but not the VF one?

Weird consistent EC2 CPU spikes

Weird consistent EC2 CPU spikes

One of our m1.small EC2 instances, running a Node.js web server, regularly
gets some CPU spikes. It doesn't seem to matter what the peak CPU reaches,
but whenever our traffic approaches the max for the day, it spikes, and
the same happens when it starts to decline.
This happens when it approaches 80% on a weekday, or even if it appraoches
40% at the weekend.
Does anyone have any idea what could be causing this? Or how I could debug
this and stop it from happening? I've checked the cron jobs and theres
nothing that would cause this.
I've attached a graph to help me explain the scenario.

Thanks.

Users in hawt.io in an standalone java app

Users in hawt.io in an standalone java app

I would like to know how can I have users for hawt.io when using it in an
standalone java app. I believe that you need to define a realm like
containers do, but is there any guide or easy way to do this? I just want
to protect my hawt.io instance with user and password.

XSLT string replace, multiple variables

XSLT string replace, multiple variables

I know there is already a question out there about replacing strings in
XSLT, but I need a conditional statement to replace one string with
multiple variables.
Here is my code:
<xsl:template name="section-01">
<xsl:call-template name="table-open"/>
<xsl:text disable-output-escaping="yes">&lt;table
style="text-align=center;"&gt;</xsl:text>
<xsl:call-template name="display-gen">
<xsl:with-param name="value" select="./z30-collection"/>
<xsl:with-param name="width" select="'30%'"/>
</xsl:call-template>
<xsl:call-template name="display-gen">
<xsl:with-param name="value" select="./call-no-piece-01"/>
<xsl:with-param name="width" select="'30%'"/>
</xsl:call-template>
<xsl:call-template name="table-close"/>
</xsl:template>
I need a statement to replace "./z30-collection"
If ./z30-collection = "Deposit" replace with "DEP"
if ./z30-collection = "General" replace with "GEN"
if ./z30-collection = "Storage" replace with "STORE"
etc...
Any help would be greatly appreciated!

Sunday, 29 September 2013

PageViewer NullPointer on Adding views

PageViewer NullPointer on Adding views

Hello fellow programmers.
Just a glitch here as I am new to these Pageviewer.
Im following this tutorial Android View Pager
and having quite issue
Ive change the required parameters of the Adapter and just past the cursor
(which im quite sure that has 14 counts)
Code are as follows for my Adapter:
public class PagerAdapterInVenue extends PagerAdapter{
private LayoutInflater inflater;
private Context context;
private Cursor cursorFeatured;
public PagerAdapterInVenue(Cursor cursorFeatured, Context context) {
this.cursorFeatured = cursorFeatured;
this.context = context;
}
@Override
public int getCount() {
return cursorFeatured.getCount();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// Declare Variables
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
cursorFeatured.moveToNext();
ImageView fullImage = (ImageView) itemView.findViewById(R.id.imageFull);
if (cursorFeatured.getString(7).toString().equals("")){
}
else
{
ImageLoaderUtil.getInstance(context).displayImage(cursorFeatured.getString(7).toString(),
fullImage);
}
((ViewPager) container).addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
binding it to my activity was
pagerAdapter = new PagerAdapterInVenue(cursorFeatured, MainPage.this);
pagerFeatured.setAdapter(pagerAdapter);
But still Im getting a weird error saying on my Logcat
09-30 09:53:24.650: E/AndroidRuntime(2268): FATAL EXCEPTION: main
09-30 09:53:24.650: E/AndroidRuntime(2268): java.lang.NullPointerException
09-30 09:53:24.650: E/AndroidRuntime(2268): at
com.example.androidinvenue.PagerAdapterInVenue.instantiateItem(PagerAdapterInVenue.java:48)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.support.v4.view.ViewPager.addNewItem(ViewPager.java:829)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.support.v4.view.ViewPager.populate(ViewPager.java:1044)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.support.v4.view.ViewPager.populate(ViewPager.java:911)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.view.View.measure(View.java:15518)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.view.View.measure(View.java:15518)
09-30 09:53:24.650: E/AndroidRuntime(2268): at
android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
My XML is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="10dp" >
<ImageView
android:id="@+id/imageFull"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:background="#000000"
android:padding="1dp" />
</RelativeLayout>
Sorry for posting long codes
Thanks in advance

I expect the program prints the numbers 0 to 99, but when I run the code I see 100 lines of 99

I expect the program prints the numbers 0 to 99, but when I run the code I
see 100 lines of 99

I have a class foo:
class foo{
public:
int i;
};
And a class bar:
class bar{
public:
foo* foo_;
};
And a code similar to:
int i=0;
vector<bar*> fs;
while(i<100){
foo f;
f.i = i;
bar* b = new bar;
b->foo_ = &f;
fs.push_back(b);
i++;
}
I expect that each bar->foo_ refer to a different foo, so when i have:
for(i=0;i<fs.size();i++){
cout << (fs[i]->foo_->i) << "\n";
}
I expect the program prints the numbers 0 to 99, but when i run the code i
see 100 lines of 99!!
why all pointers refers to the last object?

Transparent hierarchical data frames in JavaScript

Transparent hierarchical data frames in JavaScript

Not sure about terminology.
I have a JavaScript "object" with some data:
var parent = { foo: 42, bar: 2.71, baz: 3.14 };
I need to create another JavaScript object that will provide access to the
parent object, while supporting local overrides for parent's entries:
var child = extend(parent, { foo: 1, quo: 2 });
child.bar = 3;
parent.qux = 4;
assert(parent.foo === 42);
assert(child.foo === 1);
assert(parent.bar === 2.71);
assert(child.bar === 3);
assert(parent.baz === 3.14);
assert(child.baz === 3.14);
assert(parent.quo === undefined);
assert(child.quo === 2);
assert(parent.qux === 4);
assert(child.qux === 4);
// NB: I don't care about iteration on these objects.
I need the solution to be as low-overhead as possible while being
cross-browser enough. Copying parent values to the child is too much
overhead.
That is, I'm looking for something akin to Lua metatable chains, but in
JavaScript.
I was reading about [[Prototype]] chains. It looks like the way to go, but
I did not figure out a lightweight way to use them here yet. (__proto__,
as I understand it, is not cross-browser enough.)
Any clues?

SQL Server Join based on max value

SQL Server Join based on max value

I was wondering how I can left join a table to itself or use a case
statement to assign max values within a view. Say I have the following
table:
Lastname Firstname Filename
Smith John 001
Smith John 002
Smith Anna 003
Smith Anna 004
I want to create a view that lists all the values but also has another
column that displays whether the current row is the max row, such as:
Lastname Firstname Filename Max_Filename
Smith John 001 NULL
Smith John 002 002
Smith Anna 003 NULL
Smith Anna 004 NULL
Is this possible? I have tried the following query:
SELECT Lastname, Firstname, Filename, CASE WHEN Filename = MAX(FileName)
THEN Filename ELSE NULL END AS Max_Filename
but I am told that Lastname is not in the group by clause. However, if I
group on Lastname, firstname, filename, then everything in the
max_filename is the same as filename.
Can you please help me understand what I'm doing wrong and how to make
this query work?
Thanks in advance!

Saturday, 28 September 2013

How to save the state of a iPhone Switch and print it out?

How to save the state of a iPhone Switch and print it out?

I have a switch on my ViewController, and whenever I press the save
button, I want to use NSLog to print out if the switch is On/Off.
My question is, What data type saves the state of a switch? And how would
I print out that variable with the state?
EDIT:
If it was a DatePicker, it would be
@property (nonatomic, strong) NSDate *pickerDate;
I need the Switch version of this. NSSwitch doesn't seem to work.

css causing hyperlink to not work

css causing hyperlink to not work

I have a website that I have been working on and all the pages are working
fine except for some hyperlinks on my event registration. The first link
on the page would work and then the next one would not. I created a test
page that didn't have anything else on it except for the two links and the
same problem happened. It has to be something with the CSS because if I
use a blank master page that doesn't tie to my CSS then the links work.
However, I don't have trouble with the rest of my site and I only have one
master page and one CSS. Here is a link to the page. If someone can tell
me what the problem, I would greatly appreciate it. I have the same issue
in Chrome and IE. Browser doesn't seem to matter.
http://www.wmmpa.com/NewsEvents/event_regtest.aspx

Why can I cast implicitly an integer to a char in C

Why can I cast implicitly an integer to a char in C

I was wondering, why is casting implicitly from an integer to a char
possible in C ?
If for example :
int i = 2789;
printf("%c\n",i);
would give me a char back, because it would have truncated the bits
starting from the most significant ones. But usually you can't really cast
implicitly if it means you'll lose in precision so why can I do it here ?

R - ggplot - stat_contour not able to generate contour lines

R - ggplot - stat_contour not able to generate contour lines

I am trying to add contour lines via stat_contour() to my
ggplot/ggplot2-plot. Unfortunately, I can not give you the real data from
which point values should be evaluated. However, another easily
repreducably example behaves the same:
testPts <- data.frame(x=rep(seq(7.08, 7.14, by=0.005), 200))
testPts$y <- runif(length(testPts$x), 50.93, 50.96)
testPts$z <- sin(testPts$y * 500)
(ggplot(data=testPts, aes(x=x, y=y, z=z))
+ geom_point(aes(colour=z))
+ stat_contour()
)
This results in the following error message:
Error in if (nrow(layer_data) == 0) return() : argument is of length zero
In addition: Warning message:
Not possible to generate contour data
The example looks not different to others posted on stackoverflow or in
the official manual/tutorial to me, and it seeminlgy doesn't matter if I
provide more specifications to stat_contour.
Thank you for your ideas and advice!

Friday, 27 September 2013

iOS: Slide Down Animation to display Errors

iOS: Slide Down Animation to display Errors

Can someone please help me with the slide down animation that Facebook has
on iOS that shows errors? i.e. "No Internet Connection" white text on
black background. It seems to scroll down and displays an error and after
a while slides back up.
What is it called? Any pointers on how to implement it? Below is the
image. Thanks.

Boards equals 0

Boards equals 0

i have 1 problem with int boards. When I'm adding a new int in while loop
all of int equals 0.
public class Enemy extends Render {
private int X[] = new int[64];
private int Y[] = new int[64];
private int i = 1;
public Enemy(int x, int y, int num1, int num2) {
//x = 480, y = 360, num2 = 2
X[num1-1] = x;
Y[num1-1] = y;
while(i <= num2) {
System.out.println(X[0]+" "+Y[0]+" "+X[1]+" "+Y[1]);
i++;
}
i = 1;
}
}
1st and 2nd line of output equals 480 360 0 0, next output equals 0 0 30
360 I need to have 480 360 480 360 pls help.

perl, using File::Find is it possible to modify datastructure outside of that function?

perl, using File::Find is it possible to modify datastructure outside of
that function?

I am trying to traverse file in each folder and get info from that file
and update it to array For ex.
use File::Find;
sub main
{
my @names = ();
my $dir = "mydir";
# will traverse directories and look for file 'list.txt'
### now, is it possible to update @names while traversing using find?
find(\&getNames(), $dir);
}
sub getNames
{
#I tried to take names as argument but it doesn't seem to work..
if (-f $_ && $_ eq 'list.txt')
{
#update names possible?
}
}
Is it possible to update data structure while traversing using File::Find?
And I am trying not to use global variable..

Play framework external dynamic HTML handling

Play framework external dynamic HTML handling

I'm developing a web application on a Play framework 2.2.0 (Scala). The
application is generally taking some input from the user, and then calls
external module which in turn processes the input and generates html
report. The report has a rather complex structure with html, javascript
and json data, all put into different files. Then I wish to be able to
render this report to the user by the Play framework, without him having
to download report in an archive.
I tried to put these report files to some directory in the assets, and
Redirect, but this won't work in production. Then I tried to use
Ok.sendFile inline, but since content depends on other files the report
does not render correctly.
I wonder if there is any "intended" way to render such dynamically
generated HTML to the user?

Ruby 2.0:define_method in top level

Ruby 2.0:define_method in top level

define_method can be used at the top level in Ruby 2.0; it doesn't have to
be inside a class or module.
Dir["config/*.yml"].each do |path|
%r{config/(?<name>.*)\.yml\z} =~ path
define_method(:"#{name}_config") {YAML.load_file(path)}
end
But as i know define_method is a method of Module, and main object did not
have such method in Ruby 1.9.
How Ruby 2.0 implement this?

checking status of session with session id

checking status of session with session id

I am trying to develop a chat application and I need to know whether the
other user is active or not.I already went through "timestamp" example( if
the last activity is more than specified time consider the user as offline
) and the problem with this method is that this code need to executed
repeatedly in regular intervals through javascript.
So, I was thinking that if there is any way to check whether a sessions is
active or not in server by knowing the session ID.If this is possible I am
making an extra column for "last session id" in MYSQL table and I will
check if it is active or closed the every time I send a message and I can
know for sure if the person on the other side is active or not.

how to get the values from the list

how to get the values from the list

val list=List[(121,"jags")]
From the above list , i want to fetch 121 and jags . How to do it. I have
tried
list._0
list._1
But doesn't give me the output.

Thursday, 26 September 2013

Is there any design pattern in this? Is there any possible flaw in this java code?

Is there any design pattern in this? Is there any possible flaw in this
java code?

For design of an API in java, I came up with following pattern to fulfill
certain requirements which are listed here
actual public API class should be implemented as a final class, to prevent
inheritance and possible misuses
actual public API class should not expose anything more than required
methods.
separation of API classes and internal implementation into different packages
scope for extensibility or evolution in both public and internal classes
the sample code is as follows:
package external;
import internal.AbstractProduct;
public final class Product extends AbstractProduct{
protected Product(int a, int b){
super(a,b);
}
@Override
public int result(){
return super.result();
}
}
public class ProductFactory {
public static Product createProudct(int a, int b){
return new Product(a, b);
}
}
and internal classes are as follows:
package internal;
public abstract class AbstractProduct {
private final AbstractProduct impl;
protected AbstractProduct(int a, int b){
impl = new ProductImpl(a, b);
}
protected AbstractProduct(){
impl = null;
}
protected int result(){
return impl.result();
}
}
class ProductImpl extends AbstractProduct{
private int a;
private int b;
ProductImpl(int a, int b){
this.a = a;
this.b = b;
}
@Override
protected int result(){
return a*b;
}
}
Although it works fine and also has appropriate access levels, but I only
have beginner level skills with design patterns or API design, so it seems
difficult for me to spot possible glitches with this. So are there any
problems with this Or is it some already practiced pattern?

Wednesday, 25 September 2013

Retracing path in bfs

Retracing path in bfs

With python as coding language used, how do I retrace the path of
different nodes using breadth first search?. I am able to trace only one
node.

Thursday, 19 September 2013

css div positioned absolute not expanding all the way to the bottom

css div positioned absolute not expanding all the way to the bottom

I am trying to use a absolute div as my background (only on certain
pages..I can not use body for this purpose)
However I am not able to expand it to the bottom of page. Pleas help.
Black background is only to the middle of page. Notice in my fiddle
http://jsfiddle.net/z9Unk/317/
CSS
.background {
position:absolute;
width: 100%;
height: 100%;
z-index:-1;
background:black;
}
.container {
height: 100%;
width:100%;
}
.item {
width:100px;
height:100px;
border:1px solid red;
}
HTML:
<div class="background">
Hover Me
</div>
<div class="container">
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
<div class="item">
</div>
</div>

How to get a,b & c parameters in a Zipf distribution of rank/frequency

How to get a,b & c parameters in a Zipf distribution of rank/frequency

I'm trying to approximate the number of ocurrences of a given word with
rank n in a text corpus. I know that rank/frequency follows a power law.
I have sorted all the words (so their position is their rank, 1st word is
the one that most appears and so on). What I am trying to fit is the
following version of Zipf law for rank/frequency in words:
Fr = c / (r+b)^a
Where r is the rank of a given word.
I've been using some R scripts that I've found and I managed to elaborate
a log-log plot so I see that my data follows in fact a power law (as the
log-log plot is lineal, and according to the theory from top-left to
right-bottom). But I have no clue as to how get the c, b & a values. I
have also the best quadratic fit but I'm not sure what this means (is it
"a" parameter value?) this is what R reported:
$minimum
[1] 1.134048
$objective
[1] 15756.57
And I was told that this 1.13 is the best quadratic fit but I don't know
how to translate this to what I'm looking for.

Generating a noun's plural from with Wordnet

Generating a noun's plural from with Wordnet

Given a word, which may or may not be a singular-form noun, how would you
use Wordnet to find its plural form? e.g.
>>> plural('cat')
'cats'
>>> plural('community')
'communities'
>>> plural('fish')
'fish'
>>> plural('reckless')
None

augtool fails to update writeable file

augtool fails to update writeable file

I installed Augeas on my CentOS box and am getting unexpected behaviour
from augtool.
To whit,
[root@boxen tmp]# ll
-rw-r--r--. 1 root root 27 Sep 19 11:58 /tmp/my.conf
[root@boxen tmp]# cat /tmp/my.conf
OptionOne no
OptionTwo yes
Now I want to use augtool to change OptionOne from no to yes.
[root@boxen tmp]# augtool set /tmp/my.conf/OptionOne yes
[root@boxen tmp]# augtool save
[root@boxen tmp]# cat my.conf
OptionOne no
OptionTwo yes
augtool is not writing the config change to the file. I'm not seeing any
errors. What am I doing wrong?

Optimization of inlined values

Optimization of inlined values

I have the following inline method and call it several times in other
methods. Will the vc and gcc compilers with O2 optimization be able to
notice the value is fixed in the calling methods and evaluated it only
once? -- Indeed indexAndFlag is not changed inside those methods. -- Or,
maybe for thread-safety, it will be evaluated per each call?
unsigned int indexAndFlag;
...
inline Index* index() const
{
return (Index*)(indexAndFlag & ~1);
}
The code is only for protected mode x86 32/64bit architecture, so I hope,
I can assume sizeof(unsigned int) == sizeof(Index*). If not, please
correct me.

SOAP REQUEST USING Ruby without using any gem

SOAP REQUEST USING Ruby without using any gem

http = Net::HTTP.new('bts.makemytrip.com', 80)
http.use_ssl = false
path="http://bts.makemytrip.com/MMT_Webs_CreateIncident/MMT_Webs_CreateIncident.asmx?op=CreateIncident"
# Create the SOAP Envelope
data = <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body>
<CreateIncident xmlns="http://MakeMyTrip.org/">
<FirstName>#{params[:name]}</FirstName>
<Email>#{params[:email]}</Email>
<CityOfResidence>#{params[:city]}</CityOfResidence>
<MobilePhone>#{params[:mobile]}</MobilePhone>
</CreateIncident>
</SOAP:Body>
</SOAP-ENV:Envelope>
EOF
# Set Headers
headers = {
'Content-Type' => 'Content-Type: application/soap+xml; charset=utf-8'
}
# Post the request
resp, data = http.post(path, data, headers)
# Output the results
logger.error "code = >>>>>>>>#{resp.code}"
logger.error "Response message = >>>>>>>>Message =#{resp.message}"
resp.each { |key, val|
logger.error "key>#{key}>>>>>#{val}"
}
logger.error "data>>>>>#{ data}"
it gives us this error
code = >>>>>>>>500
Response message = >>>>>>>>Message =Internal Server Error
key>x-powered-by>>>>>ASP.NET
key>x-aspnet-version>>>>>2.0.50727
key>connection>>>>>close
key>content-type>>>>>text/xml; charset=utf-8
key>date>>>>>Thu, 19 Sep 2013 08:35:13 GMT
key>server>>>>>Microsoft-IIS/7.5
key>content-length>>>>>442
key>cache-control>>>>>private
data>>>>><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Server was unable to process request. ---&gt;
'SOAP' is an undeclared namespace. Line 8, position
5.</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
what is wrong in this code

Wednesday, 18 September 2013

Animate CAShapeLayers

Animate CAShapeLayers

I have few CAShapeLayers which are completing circle (refer image).Now i
want to animate that all layers on single touch.Like :Right now,center of
green CAShapeLayer is set to 0 degree. if you are selecting red
CAShapeLayer,then the center point of that CAShapeLayer will set to 0
degree.If you are selecting yellow CAShapeLayer then also its center will
take place at 0 degree.Remember all layers should animate according to
selected layer.I dont want to use UIView.transform. I just want to use
CABasicAnimation,CAAnimationGroup or KeyFrame animation only.I am using
single tap gesture.

Please help me.Thanking you.

Display inline block issues

Display inline block issues

I have a two divs aligned side to side and they work as I want them on
desktop but when it comes to mobile browser (it works on chrome mobile as
the desktop one) like Mozilla Firefox, Safari one of the divs push to the
bottom. I have tried setting overflow:scroll to the div container but that
doesn't solve the prob. Can someone help me out?
css
.container{
margin: 10px auto 20px auto;
display:table;
overflow:scroll;
}
.left_col{
width: 700px;
border:1px solid #C0C0C0;
display: -moz-inline-stack;
display: inline-block;
background-color:#fff;
vertical-align:top;
zoom: 1;
*display: inline;
}
.right_col{
width:300px;
border:1px solid #C0C0C0;
display: -moz-inline-stack;
display: inline-block;
height:1090px;
background-color:#fff;
vertical-align:top;
zoom: 1;
*display: inline;
}
html
<div class="container">
<div class=left_col"></div>
<div class="right_col"></div>
</div>

Ruby: Comparison Operator as a string

Ruby: Comparison Operator as a string

I am working on a Rails app that allows a user to check off tasks as they
have completed them and I am working on a method that will return past due
tasks and upcoming tasks.
Here is my method in my User model:
def task_notification(notification_type = "past")
return false if tasks.empty?
current_month = Time.now.month
tasks.where(classification: classification).select { |task|
task.due_date < current_month }
end
I am basically trying to do something like this:
operator = notification_type.eql?("past") ? "<" : ">"
tasks.where(classification: classification).select { |task| task.due_date
operator current_month }
obviously the above doesn't work, I am just wondering how to make it work.

Is there a way to extract the final board positions from Go games in SGF files?

Is there a way to extract the final board positions from Go games in SGF
files?

I want to parse Simple Game Format files to extract final board positions
for the game of Go. Does anyone know whether this has been done before or
how one should go about starting it?

JSF Facelets how to include external html?

JSF Facelets how to include external html?

I have an app that i'm developing and my company has a header banner that
is required to be on all pages. We have about 6 different versions
floating around my team of that header banner and I now want to make it so
that I just include the banner from the source into my app so that if they
update the source of the banner, my app's version of the banner is
automatically updated as well.
using <ui:include src="http://mycompany.com/banner.html" /> causes the
error The markup in the document following the root element must be
well-formed..
How can i include this banner even if it's not well formed xml?
My current template:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:composition>
<h:body>
<div>
<ui:include src="http://mycompany.com/banner.html" />
</div>
<ui:insert name="content" />
</h:body>
</ui:composition>
</html>

Alternative to Nz and IIF(Is Null)

Alternative to Nz and IIF(Is Null)

I have a query in Access in which one of the fields contains a subquery
returning the sum of a specific field from a related table. The result of
the subquery is used in further calculations in the main query.
This is used in a homemade reporting application in VB.Net (C# would be
fine) using ADO.Net. Queries are stored in a table in Access to allow us
to correct small bugs or adding temporary features related to the data
without publishing our application again.
The problem is that it's possible that the subquery returns no result
(null). Furthermore, a null value used in calculations will also return a
null value. Therefore, I need to replace the null value by 0 if that's
needed. I added NZ(subquery, 0), but ADO.Net throws the following
exception:
Undefined function 'NZ' in expression
I learned that it's not possible to use a VBA function in ADO.Net since
it's part of the Access.Application object.
I also considered using IIF(subquery Is Null, 0, subquery), but that would
force me to duplicate the subquery, and force Access to execute the
subquery twice (probably). Since the subquery is rather complex (and so is
the main query), I want to avoid that, at least for the sake of
readability, if not performance.
Is there another way to replace a null value by another value, or to make
sure my subquery will always return a non-null sum even with no matching
record?

Authorization based on creator

Authorization based on creator

Lets assume we have an ASP.NET MVC blogging app that allows users to
register and then blog on the site. Now lets assume that the blog edit
page takes in the blogId and then presents the information related to the
blog. In the action method how can we ensure that the BlogId that is
received by the action method is the one that the logged in user has
created? We can have a scenario where someone could modify the URL and put
in an ID for a blog that does not belong to the logged in user. What is
the best way of preventing this?
One option that I can think of is getting the creator of the blog in the
action method and then checking it against the ID of the logged in user to
ensure that the user has access to edit that specific blog. Can this be
achieved by some kind of filter rather than having to specify this in the
action method ?

Why always get 5 spaces when nothing inside conteneditable div?

Why always get 5 spaces when nothing inside conteneditable div?

I get innerHTML in contenteditable div to a NSString like this:
NSString *htmlText = [self.webView
stringByEvaluatingJavaScriptFromString:@"document.getElementById('content').innerHTML"];
if (htmlText) {
NSLog(@"TEST: |%@"|,htmlText);
}
I wanna check when nothing inside that div but I always get 5spaces when
nothing inside div. Why? Please help!
<div id="content" contenteditable="true" style="font-family: Helvetica">
</div>

Tuesday, 17 September 2013

In-App Purchase crashes App after release

In-App Purchase crashes App after release

Apple has approved our first app that has In-App Purchases - however
suddenly when a user taps the "Upgrade" button the app hangs momentarily
and then crashes. By using the Console feature in XCode's Organizer I was
able to obtain the following report:
Sep 18 15:12:48 iPad MyApp[53107] <Error>: *** Terminating app due to
uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI
objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(0x316f92a3 0x3958497f 0x31643e8d 0x54b23 0x335ec0c5 0x335ec077
0x335ec055 0x335eb90b 0x335ebe01 0x335145f1 0x33501801 0x3350111b
0x351f35a3 0x351f31d3 0x316ce173 0x316ce117 0x316ccf99 0x3163febd
0x3163fd49 0x351f22eb 0x33555301 0x4b81f 0x399bbb20)
Sep 18 15:12:48 iPad ReportCrash[53109] <Notice>: Formulating crash report
for process MyApp[53107]
Sep 18 15:12:48 iPad com.apple.launchd[1]
(UIKitApplication:com.mycompany.MyApp[0x716c][53107]) <Warning>:
(UIKitApplication:com.mycompany.MyApp[0x716c]) Job appears to have
crashed: Abort trap: 6
Sep 18 15:12:48 iPad ReportCrash[53109] <Error>: libMobileGestalt
copySystemVersionDictionaryValue: Could not lookup ReleaseType from system
version dictionary
Sep 18 15:12:48 iPad backboardd[26] <Warning>: Application
'UIKitApplication:com.mycompany.MyApp[0x716c]' exited abnormally with
signal 6: Abort trap: 6
Sep 18 15:12:48 iPad ReportCrash[53109] <Notice>: Saved crashreport to
/var/mobile/Library/Logs/CrashReporter/MyApp_2013-09-18-151248_iPad.plist
using uid: 0 gid: 0, synthetic_euid: 501 egid: 0
This does not occur when I run the app on my device, and it must've worked
when Apple review it or else they would not have cleared it for sale.
My guess it that my products array is null and when trying to purchase
item[0] (the only available one) it crashes.
To sum up: why does it only work in testing mode?
Thanks in advance!

How to Dynamically assign value to Dojo's object

How to Dynamically assign value to Dojo's object

I am tring to implement TooltipDialog with Dojo, Although the dialog shows
up great,But I still have no idea how to change the content of the tip, I
have code as following:
var _tipContent;
require([
"dijit/TooltipDialog",
"dijit/popup",
"dojo/on",
"dojo/dom",
"dojo/domReady!"
], function (TooltipDialog, popup, on, dom) {
var myTooltipDialog = new TooltipDialog({
id: 'myTooltipDialog',
style: "width: 300px;",
content: _tipContent,
onMouseLeave: function () {
popup.close(myTooltipDialog);
}
});
on(dom.byId('TriggerBlock'), 'mouseover', function () {
popup.open({
popup: myTooltipDialog,
around: dom.byId('TriggerBlock')
});
});
});

Is it possible to use Jackson JSON to serialize a custom annotation?

Is it possible to use Jackson JSON to serialize a custom annotation?

I have created a simple annotation for a class' methods. I would like to
export the value of each annotation in JSON format.
So for example, I have an annotation:
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface MyAnnotation
{
int someInteger();
String someString();
String[] possibleTypes();
}
And then in my class I am annotating I have:
package com.clusin;
public class foo
{
@MyAnnotation(someInteger = 1, someString = "bar", possibleType = {
"a","b","c" })
public int doSomeComputation(Object x, Object y)
{
//Do something here.
}
}
Using reflection we can obtain a reference to these annotations at runtime.
So my question is: Given these annotations obtained at run time, is it
possible to use jackson to serialize the values contained in the
annotation?
I've tried annotating my annotation with @JsonProperty but the
ObjectMapper throws a JsonMappingException when calling
ObjectMapper#writeValueAsString.
org.codehaus.jackson.map.JsonMappingException: No serializer found for
class $Proxy5 and no properties discovered to cre
ate BeanSerializer (to avoid exception, disable
SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
at
org.codehaus.jackson.map.ser.StdSerializerProvider$1.failForEmpty(StdSerializerProvider.java:89)
at
org.codehaus.jackson.map.ser.StdSerializerProvider$1.serialize(StdSerializerProvider.java:62)
at
org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:315)
at
org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:242)
at
org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:1846)
at
org.codehaus.jackson.map.ObjectMapper.writeValueAsString(ObjectMapper.java:1473)
Any ideas?
Thanks for your time.

Entitiy Framework/Database Decimal issue

Entitiy Framework/Database Decimal issue

In my project I have a field in the database that was a Decimal(10,3). It
was recently decided that it should allow 4 spots after the decimal so I
modified the field to be a Decimal(11,4). For some reason the fourth
decimal spot never saves. I traced through my code and I can see the
entity property gets set to "1.2345" for example but the value that is
showing in the database is "1.2340".
I can't figure out why my last decimal spot is not saving. As far as I can
tell my entity framework edmx doesn't have a set number of decimal places
(precision is set to none) and if I manually change the value in the
database it will store a non-zero number in the 4th decimal spot. After
doing so the correct value gets pulled out of the database (through entity
framework) and displayed in my project.
Any ideas on where to look to resolve this issue?

JSF 2 submit form while pressing button (multiple submissions)

JSF 2 submit form while pressing button (multiple submissions)

How can one achieve multiple form submission while the user holds the
button pressed.
<h:commandButton value="Multiple submission" action="#{mngr.doSomething}"/>
Basically I just want to keep invoking mngr.doSomething method as long as
i hold the button pressed. Any ideas?

how to get a string contained in a div

how to get a string contained in a div

I have a div that contains div in HTML code, i just want to retrieve the
string contained in that div, like the word "LATTE" or "price:12" in the
next code:
<!DOCTYPE html>
<html>
<head>

</head>
<body>
<div id="items">
<div id="heapbox_46958322" class="heapBox">

</div>
<select class="basic-example" style="display: none;">

</select>
<div id="dummy">

</div>
<div id="gallery">
<div class="item_block">

</div>
<div class="item_block">

</div>
<div class="item_block hasoptions">
price:12
<div class="add_btn"></div><div class="item_name">
LATTE
</div>
</div>
</div>
<div id="order_list">

</div>
</div>
<script type="text/javascript">

</script>
</body>

Sunday, 15 September 2013

How do i upload image from Rhomobile

How do i upload image from Rhomobile

I need to upload user profile image to server, i have it stored it on the
app's base path.
settings = { :camera_type => @params['camera_type'],
:color_model => @params['color_model'],
:enable_editing => en_ed,
:desired_width => width,
:desired_height => height,
:flash_mode => 'auto',
:saveToDeviceGallery => 'true'}
Camera::take_picture(url_for(:action => :camera_callback), settings)
Then on callback,
Image.create({:id => generateId(), :image_uri => @params['image_uri']})
file_testname =
File.join(Rho::RhoApplication::get_blob_path(@params['image_uri']))
test_content = File.binread(file_testname)
new_file_name = File.join(Rho::RhoApplication::get_base_app_path(),
@params['image_uri'].to_s().split("/")[2])
f = File.new(new_file_name, "wb")
f.write(test_content)
f.close
How can i upload that image to server?

OpenGL Transparency?

OpenGL Transparency?

I'm following some OpenGL tutorials on how to get the transparency effect
using a RGBA texture format, and so I have an image data set up with a
specific color being set to alpha 0, everything else remains the same.
//OpenGL initialization
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
Then I'm creating a VBO, a Texture object, and calling them during the
draw function. In my fragment shader, I have this code (for tests):
#version 330 core
in vec2 UV;
out vec4 color;
uniform sampler2D texture;
void main()
{
vec4 cColor = texture2D(texture, UV).rgba;
//Using just this gets me the original texture, but without the alpha
(black background), so I did this to test:
if(cColor.w == 0) //if this pixel is set to be transparent...
{
color = vec4(1, 0, 0, 1); //show a red pixel
}
else
{
color = texture2D(texture, UV).rgba;
}
}
I'm seeing the red pixels where it is supposed to be transparent, but if I
change the w component of it to 0, it goes back to the black background of
the texture. If I use the glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA), I
get the red pixel even with the w set to 0.
I have another image drawn in the background to test it, I tried changing
the order, but it didn't help, changing the order just hid my small
texture.
I've checked a lot of tutorials and I think the code's mostly correct, but
the transparency just isn't showing.
What am I doing wrong?

Run function on every table entry

Run function on every table entry

I got a table that has an entry that looks like this:
<tr>
<td><input type="checkbox" name="ids[]"/><a style="cursor: pointer;"
onclick="addtopath('parameter1', 'parameter2')" class="btn_addpath">
Add</a></td>
</tr>
As you can see every table entry countains the function
"addtopath('parameter1', 'paramter2');"
The parameters are generated via php; so each item is different. Also,
every entry has a checkbox. This is where the trouble occurs.
I want to create a function that runs the "addtopath" function for every
table item, that is checked, as if the user clicked the "Add" button.
Hope it makes sense.

Processing mod_wsgi.input

Processing mod_wsgi.input

I am newbie in python and mod_wsgi development. When I want to get data
from POST i read envron['wsgi.input'] and as a result I get
name=username&fullname=name&pass=password. Now my question is how to split
it to get that input as array. For example to read like name =
arraypost[0]?

SQLAlchemy/Pyramid tutorial: attempt to write to readonly database

SQLAlchemy/Pyramid tutorial: attempt to write to readonly database

I am banging my head over this one. I have successfully completed the
SQLAlcemy + URL Dispatch tutorial in the past. Now whatever I do, the
attempts to write to the sqlite db file all fail, throwing:
OperationalError: (OperationalError) attempt to write a readonly database
u'INSERT INTO pages (name, data) VALUES (?, ?)' (u'NewPage', u'A new page
is dawning.')
The variations in my current configuration are:
I am running through the tutorial under mod_wsgi, not the pserve.
this system is running python 2.6.5 vs 2.7.5
The datafile initializes fine. The ownership is the same as the wsgi
process owner. I'm baffled.
Here's the models.py:
from sqlalchemy import (
Column,
Index,
Integer,
Text,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
DBSession =
scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Page(Base):
__tablename__ = 'pages'
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
data = Column(Text)
def __init__(self, name, data):
self.name = name
self.data = data
Index('page_index', Page.name, unique=True, mysql_length=255)
Pretty straightforward out of the tutorial.
Any thoughts greatly appreciated.

Get td values with loadHTML and DOMXPath

Get td values with loadHTML and DOMXPath

I'm trying to get the td values from a table, using loadHTML and DOMXPath,
but even though there are no errors, the nodes always return empty on both
"textContent" and "nodeValue".
The table id is "akas", but nothing else inside the table has id's or
classes.
Here's my code:
$xml = new DomDocument();
$xml->validateOnParse = true;
libxml_use_internal_errors(true);
$xml->loadHTML($data); //$data contains all the HTML
$xpath = new DOMXPath($xml);
$table = $xpath->query('//table[@id="akas"]')->item(0);
$rows = $table->getElementsByTagName("tr");
foreach($rows as $row)
{
$cells = $row -> getElementsByTagName('td');
foreach ($cells as $cell) print $cell->nodeValue;
}
There are no errors, but I can't get anything from the nodes, if I do a
var_dump every attribute returns empty, except for the [tagName] and
[nodeName]. "Length" of the table returns the correct value (the number of
tr's and/or td's inside).
What could be wrong? Can anyone shed some light on this?

How can I solve this git access rules: any one can create new branch, only admin can merge into "master"?

How can I solve this git access rules: any one can create new branch, only
admin can merge into "master"?

We are using git for our codes control, and I have some question on it.
I want this in a repo, using git it self or tools such as "gitolite": 1,
only specified persion can merge code to specified branch. 2, somebody(
such as a group called "admin") can create new branch, and have full
permission "RW+", maybe all development group menber should have this
access permission *3, all persion can create new branch with a specified
prefix, such as a prefix called "bug", will allow all persion create
branches called bug001, bug123...
I don't know if I missunderstanded the usage of "git", or maybe I should
actualize this access rules via "repo", not branch?
Look forward to someone can answer my question eagerly, any solution will
be ok, such as gitolite, Thanks!

Saturday, 14 September 2013

internet explorer, modernizr.js, respond.js, html5shiv.js, ie-7.js compatibility

internet explorer, modernizr.js, respond.js, html5shiv.js, ie-7.js
compatibility

I have updated my code to latest Twitter Bootstrap v3, and it has dropped
support for older (ie7 or less) browsers, even ie8 / ie9 are not fully
supported, so I am trying to use some third party plugin / scripts so I
don't have to write IE specific css unless it's critical or necessary (not
worried about css3 shadows, rounded corners etc).
modernizr.js I will be using this, respond.js (I think I will be using it
as well for media queries support in older browsers)
now tell me if modernizr.js and respond.js can work together
also
I think *html5shiv.js is not required as modernizr.js covers it (tell me
if it does)? and also can I load alongside respond.js if modernizr.js
doesn't provide html5 enhancement?
tell me if I still need to use ie9.js? if yes with which combination?
As I want
a) Media queries support b) Browser detection for css3 features support
(which modernizr.js does well) c) Would like my website(s) to work in IE
browsers (not worried about shadows, rounded corners etc, just bug's
layout, float, etc)
so help me with this situation, oh and I also use
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en-US">
<![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en-US">
<![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en-US"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-US"> <!--<![endif]-->
<!--<html class="js">-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
so tell me I need to do something with these as well to achieve my desired
result (specially chrome-1 should I be using it?
Thanks

I'm Looking for a Simple Tutorial on Saving a Text File from a URL to my Android Device

I'm Looking for a Simple Tutorial on Saving a Text File from a URL to my
Android Device

I need to save a text file from my website to my Android device. I can't
seem to find something that explains this process well to a newbie like
me. Can someone please point me in the right direction?

Write into console while debugging. Eclipse

Write into console while debugging. Eclipse

i cannot to see what i write to the console (Eclipse C++) during debugging
for (int i=0; i<5; i++) {
cout << i;
}
How to configure Eclipse writting on console while debuging ?

C ignores "if" instructions

C ignores "if" instructions

I'm having a problem with a program I have made recently. Basically, it's
a simple version of the John Conway's game of life, but it's not working
properly. The problem is in the code that reads the state of a cell and
its neighbours and decides the future state of that cell. Here's that part
of the code (it's a bit long):
#include<stdio.h>
#include<conio.h>
//Game grid size
#define SIZE 15
//Cell state (wall is a special state. It protects the other cells from
garbage data of the heap memory)
enum cellState {dead,alive,wall};
//Function prototypes
int** load(int**);
void process(int**);
int main(){
//Game grid (2-D matrix) and its memory allocation
int** grid;
grid=(int**)calloc(SIZE+2,sizeof(int*));
for(int cont=0;cont<SIZE+2;cont++){
*(grid+cont)=(int*)calloc(SIZE+2,sizeof(int));
}
load(grid);
getch();
process(grid);
getch();
}
//Grid loading function
int** load(int** grid){
int type;
srand(12345);
for(int cont=0;cont<SIZE+2;cont++){
for(int cont2=0;cont2<SIZE+2;cont2++){
if(cont==0||cont==TAMANO+1||cont2==0||cont2==TAMANO+1){
*(*(grid+cont)+cont2)=wall;
}
else{
//Cell type decision
type=(int)((rand()*2+1)/32767);
if(type==dead){
*(*(grid+cont)+cont2)=dead;
}
else if(type==alive){
*(*(grid+cont)+cont2)=alive;
}
}
}
}
//Grid impression
for(int cont=0;cont<SIZE+2;cont++){
for(int cont2=0;cont2<SIZE+2;cont2++){
if(*(*(grid+cont)+cont2)==wall){
printf("W ");
}
else if(*(*(grid+cont)+cont2)==dead){
printf(". ");
}
else if(*(*(grid+cont)+cont2)==alive){
printf("C ");
}
}
printf("\n");
}
return(grid);
void process(int** grid){
//Temporary grid that saves the next state of a cell
int** gridTemp;
//Generations (turns) counter and live neighbours counter
int generations=0,liveNeighbours=0;
gridTemp=(int**)calloc(SIZE+2,sizeof(int*));
for(int cont=0;cont<SIZE+2;cont++){
*(gridTemp+cont)=(int*)calloc(SIZE+2,sizeof(int));
}
for(int cont=0;cont<SIZE+2;cont++){
for(int cont2=0;cont2<SIZE+2;cont2++){
if(cont==0||cont==SIZE+1||cont2==0||cont2==SIZE+1){
*(*(gridTemp+cont)+cont2)=wall;
}
}
}
//Processing loop
while(generations<100){
system("cls");
for(int cont=1;cont<SIZE+1;cont++){
for(int cont2=1;cont2<SIZE+1;cont2++){
for(int comp1=-1;comp1<2;comp1++){
for(int comp2=-1;comp2<2;comp2++){
if(comp1==0&&comp2==0) continue;
else{
//Here, we read the state of the
neighbour cells of a certain cell
if(*(*(grid+cont)+cont2)==dead){
if(*(*(grid+cont+comp1)+cont2+comp2)==alive){
liveNeighbours+=1;
}
}
else
if(*(*(grid+cont)+cont2)==alive){
if(*(*(grid+cont+comp1)+cont2+comp2)==alive){
liveNeighbours+=1;
}
}
}
}
}
//Future state calculation. Here is where the
code fails. This if compares the state of a
certain cell and the "dead" enumeration
if(*(*(grid+cont)+cont2)==dead){
if(liveNeighbours==3){
*(*(gridTemp+cont)+cont2)==alive;
}
else{
*(*(gridTemp+cont)+cont2)==dead;
}
}
if(*(*(grid+cont)+cont2)==alive){
//It also fails here. This if checks the
value of the liveNeighbours variable
if(liveNeighbours>=2&&liveNeighbours<=3){
*(*(gridTemp+cont)+cont2)==alive;
}
//And here too
if(liveNeighbours<2||liveNeighbours>3){
*(*(gridTemp+cont)+cont2)==dead;
}
}
liveNeighbours=0;
}
}
//Here, the program copies the temporary grid onto the normal grid
for(int cont=0;cont<SIZE+2;cont++){
for(int cont2=0;cont2<SIZE+2;cont2++){
*(*(grid+cont)+cont2)=*(*(gridTemp+cont)+cont2);
if(*(*(grid+cont)+cont2)==wall){
printf("W ");
}
else if(*(*(grid+cont)+cont2)==dead){
printf(". ");
}
else if(*(*(grid+cont)+cont2)==alive){
printf("A ");
}
}
printf("\n");
}
generations++;
getch();
}
return;
}
Using the Dev-C++ debugging tool, I was able to see that the code fails at
the points I have marked. Simply, it ignores the code in those "if"
instructions, even if the condition is met.
I also rebuild this code a couple times and tried it in another compiler,
and it also fails. Turbo-C++ says that the code in the bad if instructions
has no effect.
If you need some more info, please tell me.
Thank you very much.

Why does jQuery submit screw up this click function?

Why does jQuery submit screw up this click function?

I've been using this throughout my code with no issue:
// alerts
window.cAlert = function (msg) {
// insert
align.append("<div id=\"alert\">" + msg + "</div>");
// object
alertBody = $("#alert");
// css values
alertTop = (wh - alertBody.outerHeight()) / 2;
alertLeft = (ww - alertBody.outerWidth()) / 2;
// alert css
alertBody.css({
top: alertTop,
left: alertLeft
}).transition({
opacity: 1
}, 300);
// delete alert
$(window).on("click scroll touchstart resize", function (e) {
alertBody.transition({
opacity: 0,
x: -(ww / 2),
rotate: "-360deg"
}, 600, function () {
alertBody.remove();
});
});
}
But inside my submit function, it doesn't work as expected:
$(document).on("submit", "#twigForm", function (e) {
// fix
e.preventDefault();
// object
var twigObj = $(this);
// the file data
var file = ($("#upload"))[0].files[0];
// checks
if(!file) {
cAlert("You didn't select an image, silly");
} else if(file.size >= 2097152) {
cAlert("Filesize cannot exceed 2 MB");
} else if(file.type !== "image/jpeg" && file.type !== "image/jpg" &&
file.type !== "image/gif" && file.type !== "image/png") {
cAlert("Are you sure that's an image?");
}
});
Expected behavior: the alert message should dissapear when the user clicks
(anywhere), scrolls, touches, or resizes the window, which it does.
However, if the user has made an error in the form a second time, the
alert message instantly fades out, even though I haven't
scrolled/resized/clicked/etc. I didn't even catch what the error read. Any
help is appreciated.

TwitterSDK for iOS

TwitterSDK for iOS

Is there any SDK for Twitter.like Facebook ? I Need to create login into
MyApp with Twitter or Facebook.I got SDK for Facebook and completed.but
now I am searching Twitter SDK for iOS.is there any or alternatives ?
Thanks in Advance.

Can anyone explain me this for AdMob?

Can anyone explain me this for AdMob?

I just updated my ANDROID game with AdMob "SMART BANNER" ads & StartApp
exit ads.My game is only available in India. It is a quiz game with 4
options.My banner ad is updated every time when user gives a true answer
and goes for next question.I am using SMART BANNER. I just got 20,000 ad
requests with 97% fill rate.But earning are just $0.13 and eCPM is just
$0.01. Can any one help me,what should be wrong here ?

Friday, 13 September 2013

Random complex numbers

Random complex numbers

I'm placing some "critters" on a complex plane by assigning the positions
that are complex numbers. Then I would like them to make a random move on
the plane between 0 and some distance that creature can move. This would
be easy if there were the equivalent of randInt(a, b), e.g. randComplex(a,
b), where a and b are complex numbers. But I can't find this capability
anywhere. Anyone know of something that does this?
(I know I could break out the parts and do random processing on the parts,
but I'd prefer not to have to calculate the complex distances myself!)

JavaScript-Random Greek Letters Not Working

JavaScript-Random Greek Letters Not Working

So I have this absolutely fantastic javascript random stuff generator,
except for one thing. You see, I have it set so that if it brings up a
certain random value, it throws in a Greek letter too. It worked great
until I worked on it some and now that part is broken. The rest of it
works, but that one part is necessary for it to make sense to those using
it. Here is the code:
<div id="unitInfo"></div>
<script type="text/javascript">
var pre = ["Research", "Storage", "Containment", "Mobile", "Biological",
"Armed", "Dimensional", "Reliquary"];
var types = ["Command", "Site", "Sector", "Area", "Unit", "Task Force"];
var greek = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta",
"Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi",
"Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega"];
var update = ["online", "offline", "classified", "under repair",
"experiencing containment breach", "under attack", "[CONNECTION
SEVERED]", "[DATA EXPUNGED]", "terminated", "rogue", "secure",
"secure", "secure", "secure", "secure", "secure", "secure", "secure",
"secure", "secure", "secure", "secure", "secure", "secure", "secure",
"secure", "secure", "secure", "secure", "secure", "secure", "secure",
"secure", "secure", "secure", "secure", "secure", "secure", "secure",
"secure", "secure", "secure", "secure", "secure", "secure", "secure"];
var info = pre[Math.floor(Math.random() * pre.length)];
info += " " + types[Math.floor(Math.random() * types.length)];
if ( types == "Task Force" )
{
info += " " + greek[Math.floor(Math.random() * greek.length)];
info += "-" + ( 1 + Math.floor(Math.random() * 50) );
info += " is " + update[Math.floor(Math.random() * update.length)];
}
else
{
info += "-" + ( 1 + Math.floor(Math.random() * 50) );
info += " is " + update[Math.floor(Math.random() * update.length)];
}
document.getElementById("unitInfo").innerHTML = info;
</script>

How do you return multiple types from calling a new instance of a class?

How do you return multiple types from calling a new instance of a class?

From calling a new instance of the class
package main;
public class Word implements EditableTokenInterface{
String token, tokenreadonly;
public Word(String input){
token = input;
}
public void setToken(String input){token = input;}
public String getToken(){return token;}
public String getTokenReadOnly(){
tokenreadonly = token.toLowerCase();
return tokenreadonly;
}
}
using
`BOTH OUTPUT TYPES = new Number(input.substring(start,end));`
where BOTH OUTPUT TYPES are the token and tokenreadonly values. How do
return these values?

field values getting changed in awk

field values getting changed in awk

This is quite confusing, so I am going to show all my steps in building to
to issue:
awk 'BEGIN { FS == /\s\s\s\s/ } ;
{
if ( NF == 0 )
next
else
{{ print "-------------NR = " NR "-----------------------NF = " NF }
for (i = 0; i <= NF; i++)
{{ print ( i, $i )} }
}
}' 200_Undercounter_Series.txt > new.txt
Produces the desired results (I have only included the records that are
relevant):
-------------NR = 9-----------------------NF = 7
0 1. 3510090 Shelf
Guard (See SN Breaks)
1 1.
2 3510090
3 Shelf
4 Guard
5 (See
6 SN
7 Breaks)
-------------NR = 10-----------------------NF = 6
0 3515980 Shelf Guard
(See SN Breaks)
1 3515980
2 Shelf
3 Guard
4 (See
5 SN
6 Breaks)
Notice the values for fields 1 and 2 of record 9, and field 1 for record
10. My desire is to separate these 2 records from the rest of the file, so
I zone in on the value of field 2 for record 9 as such:
if ( NF == 0 )
next
else
{{ print "-------------NR = " NR "-----------------------NF = " NF }
for (i = 0; i <= NF; i++)
{if ( $2 = /[0-9][0-9][0-9][0-9][0-9][0-9][0-9]/)
{ print ( ">>", i, $i)}
else
{ print ( i, $i )}
}
}
}' 200_Undercounter_Series.txt > new.txt
And I receive these results:
-------------NR = 9-----------------------NF = 7
>> 0 1. 1 Shelf Guard (See SN Breaks)
1 1.
2 0
3 Shelf
4 Guard
5 (See
6 SN
7 Breaks)
-------------NR = 10-----------------------NF = 6
>> 0 3515980 1 Guard (See SN Breaks)
>> 1 3515980
>> 2 1
>> 3 Guard
>> 4 (See
>> 5 SN
>> 6 Breaks)
Notice not only that the '>>' indicators are on the record NOT specified
($2 = /regex/), but field 2 in record 9 is now = 0!!!
There is no other code in my program at this point. What am I missing here?
Thanks

Vim: Quickly select rectangular blocks of text in visual-block mode

Vim: Quickly select rectangular blocks of text in visual-block mode

I'm looking for a fast way to select a block of text in visual-block mode.
I deal with files of this nature:
aaaa bbbb cccc
aaaa bbbb cccc
aaaa bbbb cccc
dddd Xeee ffff
dddd eeee ffff
dddd eeee ffff
gggg hhhh iiii
gggg hhhh iiii
gggg hhhh iiii
My goal is to select the middle block in visual-block mode. I would do:
Navigate to the corner (where the X is)
Ctrl-V
'e' to extend selection to the end of block
'jj' or '2j' to extend the selection downward to the bottom of the block.
I'm looking for an alternative to (4) that, similar to 'e', would move to
the last row of the block. In this simple example 'jj' is not too
inconvenient, but sometimes these are large blocks.
There's a similar question here , but that involves jumping a
pre-determined number of lines. Is there a way to do this, again an analog
to 'e', but moving row-wise instead of column-wise? Thanks!

Difference between "is not reachable" and "unknown host"

Difference between "is not reachable" and "unknown host"

I've a small java code which test a bunch of hosts which is not reachable.
The important part is this:
for (String host : hosts) {
try {
if (!InetAddress.getByName(host).isReachable(5000)) {
System.err.println(host + " is not reachable!");
}
} catch (UnknownHostException e) {
System.err.println(host + " is unknown");
} catch (IOException e) {
System.err.println(host + "throws IOException!");
}
}
hosts is a String[]-Array full of URL's to test. When I run it, some URL's
comes "... is not reachable!" and sometimes it comes "... is unknown".
But what is the difference between these two?
Not reachable -> No answer after 5sec to the ping
Unknown -> No host found to ping
These are only my thoughts and I can't find any confirmations or
improvements in google.

If yield is a closure inside a layout, then how does layouts are rendered within?

If yield is a closure inside a layout, then how does layouts are rendered
within?

In Rails, if yield is a closure inside a layout, then how does controller
can dictate which layout to render?
layout :render => "myLayout"

Thursday, 12 September 2013

Pasting into web form from selected cell only

Pasting into web form from selected cell only

Total newbie here with what is (probably) a super easy question. I'm
working off of a sample code I found on another forum and have hit a wall.
What I'm trying to do is create an order-tracking macro that does the
following after I have selected a specific cell:
Opens the order-tracking webpage (eg. FedEx)
Enters the value of the cell into the appropriate search box
Clicks submit
I'm using the following code which accomplishes everything EXCEPT pasting
the value of a GIVEN cell. In other words, I can assign a numerical value
or specific cell value to be entered, but I need a universal macro that I
can use for any given cell.
I've tried using some basic copy paste functions with the active cell.
I've managed to get it to select and copy the active cell, but not to
paste it into the search box. This is the point where, to an expert, I'd
imagine that I start looking like an idiot. Again, I'm a complete newbie
so please forgive me!
Here is the code with problem sections identified. Thanks in advance for
the help!
Dim IE As Object
Sub submitFeedback3()
Application.ScreenUpdating = False
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "OrderTrackingWebsite"
Application.StatusBar = "Submitting"
' Wait while IE loading...
While IE.Busy
DoEvents
Wend
' **********************************************************************
delay 3
IE.Document.getElementById("appReceiptNum").**Value =**
delay 3
IE.Document.getElementById("submit").Click
'**********************************************************************
End Sub
Private Sub delay(seconds As Long) Dim endTime As Date endTime =
DateAdd("s", seconds, Now()) Do While Now() < endTime DoEvents Loop End
Sub

RESTFul WCF service to run at specific intervals?

RESTFul WCF service to run at specific intervals?

I need to implement one RESTful WCF service which should do Foo() at
regular intervals of time. Apart from hosting in the windows service what
are all the different alternatives or different hosting options that I can
consider?
Any pointers would be really helpful.
Adding some comments. Yes I need 'something' to host this REST service. So
that 'something' should invoke the REST service in regular intervals of
time.
Thanks,

Can I manually create database channel for rattle?

Can I manually create database channel for rattle?

I just got rattle to play around in and the first thing I wanted to do was
get some data from ODBC. There's an input for DSN which I entered but it
doesn't work. Specifically I get [RODBC] ERROR: state 28000, code 18456,
message [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for
user '' indicating that its trying to login with a blank username field.
I'm using Windows and in the ODBC control panel the user name I need is
already specified so I'm not sure how else I can get rattle to recognize
the correct user name.
I either need a way to create the ODBC channel myself with odbcConnect or
a way to specify the username in rattle. Can this be done?

Regular Expression for Pattern Checking

Regular Expression for Pattern Checking

How to write the Regular expression for my input. my input is
1-10,11-25,26-32,46-83 or 1-24,28,25-27
Condition:
Must start and end with number. no comma or Hyphen.
no two ,, or -- present
Thanks Advance

Top Bar issue in iOS 7

Top Bar issue in iOS 7

status bar of iPhone Overlapping with my View. I don't want to remove top
bar. Please refer image

Wednesday, 11 September 2013

Opening an HTA file from Powershell

Opening an HTA file from Powershell

I am trying to create a powershell script that will open an HTA file, but
only if it can see an html file in the same folder.
I have the following script from another question on stackoverflow, but
cannot seem to get it to work - can someone please point me in the right
direction?
The first part determines the name of the html file (called
Textbox1.html). The next part sets the file path as \network
location\Textbox1.html Then the final part says that if Textbox1.html
exists, open \network location\HTA3.hta
function GetTextboxExists
{
$TextboxExists = "$Textbox1.html"
return $TextboxExists
}
$filename = TextboxExists
$filePath = "\\*****path to file" + $filename
if ([IO.File]::Exists($filePath) -ne $true)
{
& "\\*****path to file\HTA3.hta"
}
Thanks, Roy

Difference between using 'dynamic' vs base type when instantiating object

Difference between using 'dynamic' vs base type when instantiating object

I am somewhat confused as to what the best approach would be when it comes
to creating a new object when the type of this object is unknown until run
time. Suppose I have a base class called Animals in the following manner:
public class Store
{
public Store()
{
Inventory = new List<Inventory>()
}
public string Title { get; set;}
public ICollection<Inventory> Inventory { get; set; }
}
Now suppose that I have another class which implements the Store class,
let's call it, PetStore. In PetStore, I define a constructor, which is
called whenever the StoreFactory creates an object:
PetStore
public PetStore(Store store)
: base(store)
{
Title = ((PetStore)store).Title;
}
Using StoreFactory and reflection to instantiate an object:
public static Store FromTemplate(Store store)
{
Type type = Type.GetType(store.StoreType.ClassName);
Store newstore = Activator.CreateInstance(type, store) as Store;
return newstore;
}
To get to the heart of the question now; what is the difference in
instantiating and object by doing the following:
Store newStore = StoreFactory.FromTemplate(existingPetStore);
and
dynamic newStore = StoreFactory.FromTemplate(existingPetStore);
I am not sure if I'm wording the question properly or might be a bit
confusing, I apologize if that's the case. Otherwise, I am looking to
understand how MVC differentiates between these two and ultimately, which
is the best approach to use in this case.
Thank you!

how to use AngularJS routes with Haml templates in a Rails app

how to use AngularJS routes with Haml templates in a Rails app

I have app/assets/templates/api-list.haml that I want to use as an
AngularJS template. I followed this tutorial to create a templates.js file
that inserts all my compiled Haml AngularJS templates into $templateCache.
However, I can't seem to make these cached templates work with my
AngularJS routes:
api_app.config(['$routeProvider', ($routeProvider) ->
$routeProvider.when '/',
templateUrl: 'api-list'
controller: api_app.ApiListController
$routeProvider.otherwise
redirectTo: '/'
])
When I load my app, I see a 404 error in the browser console because it
tried to do a request to http://localhost:3000/api-list. I can look at
/assets/templates.js in the browser and see that
$templateCache.put("api-list" is defined, so there should be a template
called "api-list". I am loading templates.js in my page before defining
routes.
I also tried injecting $templateCache in my route config like so:
api_app.config(['$routeProvider', ($routeProvider, $templateCache) ->
$routeProvider.when '/',
template: $templateCache.get('api-list')
controller: api_app.ApiListController
$routeProvider.otherwise
redirectTo: '/'
])
This causes an Uncaught TypeError: Cannot call method 'get' of undefined
from ApiApp error though. If I change the first line to
api_app.config(['$routeProvider', '$templateCache', ($routeProvider,
$templateCache) ->, I instead get the error Uncaught Error: Unknown
provider: $templateCache from ApiApp.
How can I convince my routes to use the template from $templateCache
instead of trying to load it via a new request?

Alter Procedure does not update departmentID

Alter Procedure does not update departmentID

I altered the following procedure to display item inventory by department.
However, this does not seem to be updating the department. I am unsure
what is wrong with the procedure. Any help?
ALTER PROCEDURE [dbo].[GetWHInventoryValue]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @loccode char(3)
declare @locationID char(10)
DELETE FROM DailySummaries WHERE Item = 119;
declare activeLocations cursor for SELECT warehouseid,whcode FROM
warehouse WHERE inactive != 'T';
open activeLocations
fetch next from activeLocations into @locationID,@loccode
while(@@FETCH_STATUS = 0)
begin
INSERT INTO
DailySummaries(Item,Location,Amount,DepartmentID,[Date])
VALUES(119,@loccode,0,0,GETDATE());
declare @whTotal numeric(13,2)
declare @itemID char(10)
declare @itemCost numeric(11,2)
declare @departmentID char(12)
declare whItems cursor for SELECT mst.masterid,
mst.replacementcost, mv.inventorydepartmentid
FROM masterwh as wh, [master] as mst,masterview mv WHERE
mst.masterid = wh.masterid AND wh.warehouseid = @locationid and
mv.masterid=mst.masterid and mv.warehouseid=wh.warehouseid
open whItems;
fetch next from whItems into @itemID,@itemCost,@departmentID
while(@@FETCH_STATUS = 0)
begin
declare @itemQty numeric(11,2)
declare itemQty cursor for SELECT SUM(mw.qty) FROM masterwhqty
mw, masterview mv WHERE mw.warehouseid = @locationid AND
mw.masterid = @itemID AND mw.qty > 0 and
mv.masterid=mw.masterid and mv.warehouseid=mw.warehouseid and
mv.inventorydepartmentid=@departmentID;
open itemQty;
fetch next from itemQty into @itemQty;
UPDATE DailySummaries SET amount = amount +
(isnull(@itemQty,0) * @itemCost), DepartmentID=@departmentID
WHERE Location = @loccode AND Item = 119 and
DepartmentID=@departmentID;
deallocate itemQty;
fetch next from whItems into @itemID,@itemCost, @departmentID
end
deallocate whItems;
fetch next from activeLocations into @locationID,@loccode
end
deallocate activeLocations;
END

Encryption and Decryption of Video

Encryption and Decryption of Video

We are building a Kiosk application, which keeps downloading videos from a
web app using a secure SSH tunnel.
The Kisoks can get stolen, and the customer wants the video files
encrypted so that no one can steal them. This is because some of the video
content is copyrighted from third parties and there are some license
obligations which the client has.
The Kiosk has only a web browser, and through a touch screen different
users play video.
We would like the video to be encrypted in normal course, but decrypted
while playing on the web video player.
We have not decided on any of these things, and are flexible
1) The browser video player 2) The file format
The operating system on Kiosk is a stripped down version of Ubuntu 12.04.
And the web application and the application that downloads and updates
content from the remote server is Django/Python.
Can you advise the right strategies to go about the encryption/decryption
on the fly

RGB to Grayscale, bmp image in java

RGB to Grayscale, bmp image in java

My teacher gave us a task to make a class that takes an 640x480 bmp
colored image, to convert it in grayscale image, I found some sources with
ideas so i did it. But there's a problem because it seems that it makes it
cause it doesn't give me error, but the output doesn't appear. I think
it's my code. My code is
import java.io.*;
public class Grayscale{
FileInputStream image;
FileOutputStream img;
byte[] datos;
int gray;
public Grayscale(String nombre)throws Exception{
this.image = new FileInputStream(nombre);
this.img = img;
this.datos = new byte[image.available()];
this.gray = gray;
}
public void gray()throws Exception{
image.read(datos);
img = new FileOutputStream("grayscaleprueba.bmp");
for (int i = 0; i<datos.length; i++){
gray = (byte)(datos[i]*0.3 + datos[i+1]*0.59 + datos[i+2]);
datos[i] = (byte)gray;
datos[i+1] = (byte)gray;
datos[i+2] = (byte)gray;
}
img.write(datos);
}
}

ASP.NET windows authentication across multiple domains or forests guidelines and explanation

ASP.NET windows authentication across multiple domains or forests
guidelines and explanation

Our client requested windows authentication for our asp.net application.
We finished it, deployed it and it works... BUT the problem we face is
that users from another domain cannot authenticate. Now our client blames
us. We also lack additional (critical) information from our client
(security...). We don't know if both domains are in the same forest or not
and what are the trust relationships between domains etc. Apparently only
users which are on the same domain as IIS can be authenticated via windows
authentication. Users from other domains always get popup to enter
credentials with which they cannot be authenticated.
We are using HttpContext.Current.User.Identity.Name inside application to
parse user name without domain and we then try to authenticate that user
against our application's database.
What I would like to know is which rules must be satisfied in order to
make windows authentication working properly across different domains in
different scenarios (same forest, different forest etc). What needs to be
done to make authentication working in each possible scenario. Trust
relationships, adding users explicitly ? I'm a developer not administrator
so my knowledge in this area is fairly limited. Please provide me with
info (link, direct answer, else) which thoroughly covers asp.net windows
authentication in multiple domains or forests scenarios.

Tuesday, 10 September 2013

Page Views Counter in PHP is giving the Wrong Results

Page Views Counter in PHP is giving the Wrong Results

I am using the following code to count the unique page views of my posts.
$thread_id = 4554; // thread_id is the unique page id
$sess_key = "page_id_" . $thread_id;
if(!isset($_SESSION[$sess_key]))
{
$_SESSION[$sess_key] = 0;
}
if($_SESSION[$sess_key]==0)
{
$query = "UPDATE tbl_threads SET views = (views + 1) WHERE id =
{$thread_id}";
mysqli_query($connection,$query,MYSQLI_STORE_RESULT);
$_SESSION[$sess_key] = 1;
}
But the Problem is, when I add a new post and click it to view it, it
adds, some times 3 views to database and some time 2 views to database.
When I open the post second time, it adds 1 to database. I am about to
pull my hairs, because I did not see any error in this code. It is also
not giving me the unique page views. Please analyse my code and tell me
where is the problem.
Note: I have pasted this code at the end of the webpage before </body> tag.

get width of transformed: scaled element

get width of transformed: scaled element

I have 2 elemenets. One is scaled down in the CSS
.firstElement{
-webkit-transform:scale(.5,.5);
}
and the other is scaled inline by jQuery's
secondElement.animate({scale:.2, origin:[0,0])}
I need to get the width and height of the secondElement and the
firstElement in pixels after they are scaled down, and its needs to be
compatible cross browser. I tried everything, Im really not sure why I
cant get this. Anyone have any ideas? Thanks

Form fields function call and variable output

Form fields function call and variable output

Hello this is a task of complex form fields processing that I'm trying to
pass to variable and trigger with onclick call - so the result of each
form should be string output within variable :
onsubmit="cartadd(this,detail);"
Any help with this script is really appreciated as this output everything
correctly except final action above that returns undefined..
<script>
var order = function (form) {
var fields = form.querySelectorAll('input');
alert(fields[0].value + ', ' + fields[1].value + ', ' + fields[2].value +
', ' + fields[3].value);
var details = fields[0].value + ', ' + fields[1].value + ', ' +
fields[2].value + ', ' + fields[3].value;
details.toString();
cartadd(details);
}
function cartadd(details) {
var detail= details;
}
</script>

JAVA ODBC scroll error despite TYPE_SCROLL_SENSITIVE

JAVA ODBC scroll error despite TYPE_SCROLL_SENSITIVE

I have a JAVA project involving a ODBC database query in which I need to
move the cursor in the result set. I've declared the type of ResultSet to
be TYPE_SCROLL_SENSITIVE, but when I execute the script I get an exception
stating the ResultsSet type is TYPE_FORWARD_ONLY. I've pasted my
(simplified) project code below, and would appreciate any help.
import java.util.InputMismatchException; //Necessary package for basic
Java utilities
import java.sql.*; //Necessary packages for SQL
routines
public class test {
public static void main(java.lang.String[] args) throws Exception {
// declare variables & create database connection
System.out.println("Open ODBC Connection....");
Connection dataConnection = DriverManager.getConnection("jdbc:odbc:DSN");
Statement stmt =
dataConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
int i = 0;
int N = 0;
//loading JDBC-ODBC Bridge driver into memory
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// create SQL query string
String sql = "SELECT ObjRef, IDX, DateListDateAsString FROM
ARRAY_BAC_CAL_DateList WHERE DEV_ID=10000 AND INSTANCE=1";
// run the query
ResultSet rs = stmt.executeQuery(sql);
// determine number of date entries
rs.last();
N = rs.getInt("IDX");
// close connection
rs.close();
dataConnection.close();
System.out.println ("Connection closed\n");
}
}
The error I receive is:
"Exception in thread "main" java.sql.SQLException: Result set type is
TYPE_FORWARD_ONLY at
sun.jdbc.odbc.JdbcOdbcResultSet.last(JdbcOdbcResultSet.java:2290) at
test.main(test.java:26)
Line 26 is where I try to move the result set cursor.
Again, any help would be appreciated.

Unfortunately app has stopped. What does java.lang.NullPointerException mean?

Unfortunately app has stopped. What does java.lang.NullPointerException mean?

When I press run an my app I get this message. CAnanyone help me please? I
am posting my LogCat here:
09-10 21:40:54.102: E/AndroidRuntime(11894): FATAL EXCEPTION: main
09-10 21:40:54.102: E/AndroidRuntime(11894): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.example.shoppingapp/com.example.shoppingapp.CurrencyConverter}:
java.lang.NullPointerException
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.ActivityThread.access$700(ActivityThread.java:143)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.os.Looper.loop(Looper.java:137)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.ActivityThread.main(ActivityThread.java:4963)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
java.lang.reflect.Method.invokeNative(Native Method)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
java.lang.reflect.Method.invoke(Method.java:511)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
dalvik.system.NativeStart.main(Native Method)
09-10 21:40:54.102: E/AndroidRuntime(11894): Caused by:
java.lang.NullPointerException
09-10 21:40:54.102: E/AndroidRuntime(11894): at
com.example.shoppingapp.CurrencyConverter.onCreate(CurrencyConverter.java:36)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.Activity.performCreate(Activity.java:5184)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
09-10 21:40:54.102: E/AndroidRuntime(11894): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)
09-10 21:40:54.102: E/AndroidRuntime(11894): ... 11 more