Monday, 30 September 2013

Sufficient and necessary conditions to get an infinite fiber $g⁻©รถ(w)$

Sufficient and necessary conditions to get an infinite fiber $g⁻©ö(w)$

I want to verify the proof of this result and get some start ideas to
overcome the different steps of this proof.
Lemma: Let $g$ be a real analytic function. Then we have the equivalence
$((a)¡ü(b))¢¢(c)$, where the statements $(a),(b)$ and $(c)$ are given by:
(a) $g$ has infinitely many real zeros.
(b) $g$ assumes arbitrarily large and arbitrarily small values, i.e., for
all $K>0$, there are $s©û,s©ü$ with $g(s©û)<-K$ and $g(s©ü)>K$,
(c) The fiber $g&#8315;©ö(w)$ is infinite for all $w¡ô&#8477;$.
Proof: (1) To prove that $(a)¡ü(b)¢¡(c)$, assume by contraduction that the
equation $g(s)=w$ has only finitely many solutions $(b_{j})_{1¡Âj¡Âi}$.
That means there are $z©û<z©ü$ such that $g(s)¡Áw$ for $w<z©û$ or $w>z©ü$.
Let $z©ý$ be the largest zero of $g$ smaller than $z©û$, and $z©þ$ the
smallest zero larger than $z©ü$. The exitence of $z©ý$ and $z©þ$ is
guaranteed by the premises that $g$ has infinitely many zeros and the fact
that $g$ is analytic, so $g$ has only finitely many zeros in the compact
interval $[z©û,z©ü]$ (or $g$ is identically $0$, but that has been ruled
out by the premise that it take arbitrarily large values), hence there
must be infinitely many outside the interval. Let
$K=max({|g(s)|:z©ý¡Âs¡Âz©þ})+|w|$. By assumption, there are $s©û,s©ü$ with
$ g(s©û)<-K$ and $g(s©ü)>K$. By the intermediate value theorem, there is
an $s_{w}$ between $z©ý$ or $z©þ$ and $s©û$ or $s©ü$ with $g(s_{w})=w$.
Contradiction.
We note that if $g$ is not analytic then it satisfies conditions (a) and
(b) but does not satisfy (c).
(2) To prove that $(c)¢¡(a)¡ü(b)$, we note first that $g$ has infinitely
many zeros because the fiber $g&#8315;©ö(0)$ is infinite. This proves item
(a). To prove item (b), let $K>0$ and $w=K+¥å,¥å>0$. The fiber
$g&#8315;©ö(K+¥å)$ is nonempty because it is infinite, hence there is
$s©ü$ such that $g(s©ü)=w=K+¥å>K$. By the same method, $g&#8315;©ö(-K-¥å)$
is nonempty, so there is $s©û$ such that $g(s©û)=-K-¥å<-K$.

What is the most elegant way to load a string array into a List=?iso-8859-1?Q?=3F_=96_stackoverflow.com?=

What is the most elegant way to load a string array into a List? –
stackoverflow.com

Say you have a array of strings containing numerical values: string[]
intArray = {"25", "65" , "0"}; What is the most elegant way to load the
numbers into a List<int> without using a for or …

mechanize: first form works, then "unknown GET form encoding type 'utf-8'"

mechanize: first form works, then "unknown GET form encoding type 'utf-8'"

I am trying to fill out 2 forms from the EUR-Lex website in order to
record some data from the generated webpage. I am stuck at form #2. I get
the feeling this should be easy and I've researched a bit, but no luck.
import mechanize
froot = '...'
f = open(froot + 'text.html', 'w')
br = mechanize.Browser()
br.open('http://eur-lex.europa.eu/RECH_legislation.do')
br.select_form(name='form2')
br['T1'] = ['V112']
br['T3'] = ['V2']
br['T2'] = ['V1']
first_page = br.submit()
f.write(first_page.get_data())
up until here everything seems to work, because I get the source of the
correct page saved to the file. But then...
br.select_form(name='form2')
br['typedate'] = ['PD']
br['startaaaa'] = '1960'
br['startmm'] = '01'
br['startjj'] = '01'
br['endaaaa'] = '1960'
br['endmm'] = '12'
br['startjj'] = '31'
next = br.submit()
here everything stops:
ValueError: unknown GET form encoding type 'utf-8'
I checked br.enctype before selecting the first and second forms. What I
get is:
after the first form: application/x-www-form-urlencoded
after the second form: utf-8
I don't know what is going on here.

out of memory exception when reading image from folder

out of memory exception when reading image from folder

i need to read all image files from folder ans save it to another folder
with compressed size.However my code compresses this images very well but
it give error after 695 image files "out of memory exception". This my
code.there are around 2000 images
List<string> files = new List<string>();
files = Directory.GetFiles(Server.MapPath("../imgres") + "\\products\\",
"*.jpg").ToList();
for (int k = 0; k < files.Count; k++)
{
if (File.Exists(files[k].ToString()))
{
string SaveLocation1 = "";
System.Drawing.Image thumbnail;
System.Drawing.Image smallsize;
System.Drawing.Image originalimg;
originalimg = System.Drawing.Image.FromFile(files[k].ToString());
thumbnail = originalimg.GetThumbnailImage(110, 110, new
System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
smallsize = originalimg.GetThumbnailImage(47, 47, new
System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
SaveLocation1 = Server.MapPath("../imgres/products") + "\\Thumbnail\\"
+ Path.GetFileName(files[k].ToString());
thumbnail.Save(SaveLocation1);
thumbnail.Dispose();
SaveLocation1 = Server.MapPath("../imgres/products") + "\\smallsize\\"
+ Path.GetFileName(files[k].ToString());
smallsize.Save(SaveLocation1);
smallsize.Dispose();
}
}

Sunday, 29 September 2013

I want to insert to database multiple data codeigniter

I want to insert to database multiple data codeigniter

This is my VIEW:
for ($i=1; $i < $loop_count ; $i++) {
echo $this->formbuilder->text( 'dates[]', 'Set Date '.$i);
}
This is my model:
function add_pm($data) {
$this->db->insert($this->table, $data);
$this->session->set_flashdata("message", "Contract record
successfully created.");
}
And now my question is what will i put in controller and how can i insert
it in database in loop? I wish someone will help me!

Is there a way to show max amount items in masonry?

Is there a way to show max amount items in masonry?

Is there a way to show a max amount of items in jQuery Masonry?
http://masonry.desandro.com/#jquery
We want to show max 12 items on http://denimjacket.nl/voorbeeld-pagina/,
so we would like to hide the rest. We can show max 12 items with a
Wordpress function, but ofcourse the Masonry will then only work on those
12 items, which is not correct. It has to work on all items, but still
show max 12 items.

In UCP, Is SCTS Field is really consistent between ot-51 ack and ot-53 request?

In UCP, Is SCTS Field is really consistent between ot-51 ack and ot-53
request?

I've been trying to implement a mechanism that communicates with smsc
using the ucp(emi) protocol. on top og that, i was trying to implement a
CDR mechanism, based on three steps: tcp ack, ot-51 ack message and ot-53
notification message. According to the EMI documentation, the SCTS field
should be consistent with the timestamp recieved in the ot-51 ack. i've
noticed that those values are not always consistent, did anyone else came
by this problem? can it be an smsc configuration problem?
thanx in advance :)

fix the position of a div inside body

fix the position of a div inside body

<body>
<div id="container">
<div id="inside">
</div>
</div>
<div id="special-div">
</div>
<body>
I need to have my special-div outside container for some js considerations
#inside{
margin:auto;
width:760px;
}
#special-div{
position:relative;
top:200px;
left:300px
}
With the above CSS,the position of the special-div changes with change in
browser size change? So,how do i fix the position of the special-div
irrespective of the browser size?

Saturday, 28 September 2013

How should I communicate with a server?

How should I communicate with a server?

Imagine some fellow wants to query a pizza server for the list of pizzas.
This individual would do simply
GET /pizzas
;=> ["cheese", "extra cheese", "broccoli"]
With pedestal-app's data model and messages, I am not sure how to design
client-server communication. Here are the possibilities some minutes of
hammocking brought:
An effect-consumer that
transforms a message into an HTTP request
transforms back the results (to e.g. [{:type :add :topic [:pizzas] :value
"cheese"} ...])
puts the messages in the queue
A dedicated resource on the server (e.g. "/edn") that
accepts pedestal messages
dispatches to the right function
responds with the raw data (i.e. ["cheese", "extra cheese", "broccoli"])
has the effect-consumer transform back the results to messages
A dedicated resource that uses the routes. Just like #2, but
altering the request
forwarding it to another entry in route table
Messages on both sides, with
the server transforming messages into function calls
the server transforming results back into messages
the client just adding these messages to the queue
It seems to me that with approaches #2 and #4, I'd bypass and lose all the
benefit of the interceptors. With approach #2, I'd need to redouble the
routing logic. With approach #4, I'd also need to generate a lot of code
to accommodate the pedestal client.
Options #1 and #3 seem better, but #3 smells hacky and #1, misdirected.
How are you guys doing it?
Thanks!

java socket buffer and string

java socket buffer and string

For a homework i try to send a file and some parameter corresponding to
this file. So, i send my file and after my string. The problem is my
paramater go to my file and not in my variable. I understand the problem,
my loop while continue to write in the file as long as he receives
something, but i want to stop it and have my parameter outside from my
file.
Here my code client:
public static void transfert(InputStream in, OutputStream out) throws
IOException{
PrintWriter printOut;
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
printOut = new PrintWriter(out);
printOut.println("add");
System.out.println("envoie !!!");
printOut.println("1");
printOut.println("3");
// out.write(getBytes("add"),0,0);
printOut.flush();
}
and here my server code :
public static void transfert(InputStream in, OutputStream out, boolean
closeOnExit) throws IOException
{
byte buf[] = new byte[1024];
int n;
while((n=in.read(buf))!=-1)
out.write(buf,0,n);
buffIn = new BufferedReader (new InputStreamReader(in));
String nom_methode = buffIn.readLine();
String param1 = buffIn.readLine();
String param2 = buffIn.readLine();
System.out.println("methode:"+nom_methode+"param1:"+param1+"param2:"+param2);
if (closeOnExit)
{
in.close();
out.close();
}
}

Why double is not allowed in in-class intializer

Why double is not allowed in in-class intializer

I have been reading Exceptional C++ by Herb Shutter Item 1 : #define or
const and inlining..
Its said that the in-class initialization is allowed only for integral
types(integers,chars,bools) and only for constants..
I just want to know why double/float cannot be initialized in class
declaration .. Are there any specific reasons.
class EngineeringConstants { // this goes in the class
private: // header file
static const double FUDGE_FACTOR;
...
};
// this goes in the class implementation file
const double EngineeringConstants::FUDGE_FACTOR = 1.35;
I just want to know the reason why the below declaration is not allowed.:,,
class EngineeringConstants { // this goes in the class
private: // header file
static const double FUDGE_FACTOR = 1.35;
...
};

Shebang executable not found because of UTF-8 BOM (Byte Order Mark)

Shebang executable not found because of UTF-8 BOM (Byte Order Mark)

For some reason the shebang in one of my scripts does not work:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
print "Hello World"
When I execute this file, I get an error
% ./test.py
./test.py: 1: &#65279;#!/usr/bin/env: not found
There is no problem with the content of my /usr/bin/ directory: both env
and python are there, with correct execution rights.
I have lost some time on this problem, so I figured the solution belongs
here.

Friday, 27 September 2013

How to use a php restful api-centric design internal instead of with http request

How to use a php restful api-centric design internal instead of with http
request

Lang: php
Servers: Amazon e2/lamp
Database: MySQL
I am wanting to create a php restful api-centric web application/website.
Where as I have the data/api that gets called from my front end code.
Besides making HTTP/curl request calls each time I load a page, what can I
do for internal API calls using frameworks like slim.
I'm not sure of a way to include the api for internal use in my front end
code and still keep it apart.
My thoughts was something like this:
"example.com/api/story/todays-weather/"
pulls in the json formatted story with a http request with curl or Ajax
But instead could I do something like:
require("/api/internal.php");
$uri = "/story/todays-weather/";
$call = api::getStory($uri);
$result = json_decode($call);
.....
I'm a headed in the right direction or am I way off. =/
The api and front code are on the same cloud box and I am planing on using
memcached for the api.

Accordion on Sharepoint 2010 content query

Accordion on Sharepoint 2010 content query

I am now trying to implement the accordion function for a content query
webpart.
Basically, the content query structure looks like this: Title Content I
want to expand collapse <li class="dwft-item">
<div class="link-item"> Title </div>
<div class="description"> Content I want to expand collapse </div>
</li>
<li class="dwft-item">
<div class="link-item"> Title </div>
<div class="description"> Content I want to expand collapse </div>
</li>
<li class="dwft-item">
<div class="link-item"> Title </div>
<div class="description"> Content I want to expand collapse </div>
</li>
and I have 3-5 of them.
What I want to do now is to expand collapse the description div whenever I
click on the corresponding link-item (title) div.
Here is my JS code:
$(document).ready(function () {
//ACCORDION BUTTON ACTION
$('#MSOZoneCell_WebPartWPQ3 .link-item').click(function () {
//MAKE THE ACCORDION CLOSE ON THE SECOND CLICK
if ($('#MSOZoneCell_WebPartWPQ3 .description').hasClass('openDiv')) {
$('#MSOZoneCell_WebPartWPQ3 .description').toggle('normal');
$(this).next().removeClass('openDiv');
} else {
$('#MSOZoneCell_WebPartWPQ3 .description').toggle('normal');
$(this).next().toggle('normal');
$(this).next().addClass('openDiv');
}
});
//HIDE THE DIVS ON PAGE LOAD
$("#MSOZoneCell_WebPartWPQ3 .description").hide();
});
The problem I have now is that whenever I click on any one of the titles,
ALL the description div expands, which is not what I want because I want
only that particular description under the title I clicked to expand.
Any help here will be much appreciated here ! Thanks!!

Client Specific Localization

Client Specific Localization

Looking for advice for this tricky kind(for me!) of localization. We have
different client in our project and we are making localization for client
wise. Condition if client specific resx file is not available then it
should take the default resx language wise.
We have folder structure like this :-
LocalizationFolder
en-us folder
Client1Folder :- en-us client specific resx file
default resx file
We have tried using getglobalresourceobject and getlocalresourceobject
methods. These methods will go to till the last/deepest path in folder
structure. But it is not picking up the client specific resx file. We have
kept naming convention of resx file same for default and client specific
resx file.
Thats why it giving error as 'default.en-us.resx file already exist OR it
conflicts with other file'.
So my question how can i pick up the resx file based on client name and if
it is not present the pick up the default resx file.
Is this possible Or any different approach needs to be follow.

Not able to configure hadoop

Not able to configure hadoop

I am not able to configure hadoop for stand alone operation. When i am
doing cp conf/*.xml input, i am getting these errors: cp: cannot create
regular file input/capacity-scheduler.xml': Permission denied cp: cannot
create regular fileinput/core-site.xml': Permission denied cp: cannot
create regular file input/fair-scheduler.xml': Permission denied cp:
cannot create regular fileinput/hadoop-policy.xml': Permission denied cp:
cannot create regular file input/hdfs-site.xml': Permission denied cp:
cannot create regular fileinput/mapred-queue-acls.xml': Permission denied
cp: cannot create regular file `input/mapred-site.xml': Permission denied
And after that when i am doing bin/hadoop jar hadoop-examples-*.jar grep
input output 'dfs[a-z.]+',i am getting these errors:
/cygdrive/d/hadoop-1.2.1/libexec/../conf/hadoop-env.sh: line 55: $'\r':
command not found Error: JAVA_HOME is not set. I have edited the env.sh
file and have set the JAVA_HOME.
Can anyone suggest me something?

Dynamicaly alter django model's field return value

Dynamicaly alter django model's field return value

Let's say I have a setup similar to this:
class UnitsOfMeasure(models.Model):
name = models.CharField(max_length=40)
precision = models.PositiveIntegerField()
class Product(models.Model):
name = models.CharField(max_length=100)
uom = models.ForeignKey(UnitsOfMeasure)
qty_available = models.DecimalField(max_tigits=10, decimal_places=10)
Now lets say we have a product related to Units of measure instance with
precision = 2. How can I do that qty_available would return 5.50 instead
of 5.5000000000?
I know I can use property decorator, but this does not solve my problem,
since I want to use qty_available as a field in forms.
Custom Field type? How can I pass and access related model instance then??
Your ideas are very appreciated!

How i decrypt my password in sunbeen_V1

How i decrypt my password in sunbeen_V1

I encrypt my password in EncryptionAlgorithm algorithm =
EncryptionAlgorithmFactory.getEncryptionAlgorithm(EncryptionAlgorithmFactory.SUNBEEN_V1);
String encryptedPassword = algorithm.encrypt(password); Input : 123 output
: QL0AFWMIX8NRZauqi4sKCKuhiiIynqH/XF7L277vIQGDCwgjAQCpAA== use Jar File
common.jar in this jar file has two class
1)EncryptionAlgorithmFactory.class and 2)EncryptionAlgorithm.class file
and another file is SunbeenEncryption.class file.
but my question is how i decrypt my password using SUNBEEN_V1 i also
search in google did not get any search regading sunbeen_V1.

Thursday, 26 September 2013

which is best option to publish android app with local database?

which is best option to publish android app with local database?

I am developing an app in which i would need a local database.
So as per my knowledge there are two ways to do it:
First is to add pre filled database file in assets folder & make copy of
local database from it the very first time app is started.
Second is using script to download it from Server for first time of app use?
First way have been pretty well answered by this guy Using your own sqlite
database in android application
Can someone help how can i go with second way of download data from Server?
Should i use JSON/XML for getting that data from my Server?
Or should i go with first option since my app has only around 150 to 200
rows in the db file?

Thursday, 19 September 2013

How to show JavaScript errors using JSHint?

How to show JavaScript errors using JSHint?

I am trying to build a simple JavaScript validator, something like JSHint.
I want to write a JavaScript code and click a "Validate" button, and the
errors should show up. Here's what I am trying to build.
http://jsbin.com/AZEpOHi/1/edit

PHP User Based Templating

PHP User Based Templating

Hi I'm creating a system where users can create their own themes, styles,
and templates. I'm storing their page templates in a mysql db and
currently I've written a small replace script that uses tags so the user
can define where content should go in their template elements. The script
replaces their tags with their content during when the page is rendered.
What I want to do now is add the ability for them to define a section
conditionally - so for example they might have an element in their
template that looks like this:
<h1 class="entry-title">
<span class="top-left-ribbon"></span>
@titlebar>heading
<span class="sub-heading">@titlebar>subheading</span>
<span class="right-ribbon"></span>
</h1>
Replacing the titlebar heading and subheading with the required values is
no problem, but I can't figure out how to do the following and replace the
conditionals with php if statements and have it process.
<h1 class="entry-title">
<span class="top-left-ribbon"></span>
@titlebar>heading
@titlebar?subheading
<span class="sub-heading" >@titlebar>subheading</span>
<span class="right-ribbon"></span>
@end?
</h1>
Basically I would want to replace
@titlebar?subheading
@end?
With...
if($titlebar->subheading){ }
And process through php appropriately.
Any suggestions would be appreciates.

Capturing global keystrokes in Objective C (OS X)

Capturing global keystrokes in Objective C (OS X)

I am quite new to Objective C and Xcode, and so I have experienced some
difficulty understanding how to implement advanced functionalities.
Requirements: Detect key presses (whether application window is in focus
or running in background) and execute some code depending on which keys
were pressed. Meant to function as hotkeys/shortcut keys.
KeyEvents in Cocoa and XCode appeared to contain potential solutions, but
I am uncertain as to whether the suggestions there are capable of
capturing key presses which occur outside of the application. I am also
not sure how exactly one would subclass the default NSView object created
by Interface Builder and tie it back to my NSWindow (also magically
created by Interface Builder) -- assuming something like this is required
at all. Not really sure how to refer from code to objects created by the
.xib, but that may be a separate question.
So, bottom line... if this is possible (without hackish OS security
overrides to enable keylogging), I would be interested to know exactly how
to go about it from the point of creating a new project in Xcode and
immediately trying to capture keystrokes.
Thanks

jQuery: Hide a field and mark it as valid

jQuery: Hide a field and mark it as valid

I have the following scenario:
I have a radio-group that hides or shows some input fields onchange which
works fine:
view.selectFormerHRInsurance.change(function() {
if ($(this).val() == true) {
view.sectionHRInsuranceName.show();
view.sectionHRInsuranceNumber.show();
view.sectionHRInsuranceSum.show();
view.sectionHRInsuranceStatus.show();
view.sectionHRInsuranceTerminationDate.show();
} else {
view.sectionHRInsuranceName.hide();
view.sectionHRInsuranceNumber.hide();
view.sectionHRInsuranceSum.hide();
view.sectionHRInsuranceStatus.hide();
view.sectionHRInsuranceTerminationDate.hide();
}
});
When a field is validated and there is an error, the error message appears
on the field and i show a global error message.
My problem is, that the global error message is still present, when i hide
the fields and as you can guess: i don't want that!
I want to "mark" the fields i hide as validated and validate it, when i
show them. How can i achieve this?

Console App that scans for changes in a directory past 24 hours

Console App that scans for changes in a directory past 24 hours

I'm creating a program that scans for changes, not create or delete, in
ALL the files in a given directory, and all of his sub directories, in the
past 24 hours. I've seen lots of other examples/tutorials but not all of
them do what I'm looking for.
This is my code so far:
using System.IO;
public static void Main(string[] args)
{
string myDirectory =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
@"C:\Path");
var directory = new DirectoryInfo(myDirectory);
DateTime from_date = DateTime.Now.AddDays(-1);
DateTime to_date = DateTime.Now;
var files = directory.GetFiles().Where(file =>
file.LastWriteTime >= from_date && file.LastWriteTime <=
to_date).ToArray();
Console.WriteLine();
}
The problem is that the code above only tells me the last change in the
directory. What I want is a log of all the changes in the directory.
I am a learning student, so lots of explanation would be great! :)
I am NOT, I repeat NOT, looking for FileSystemWatcher, I don't want my
server to stay on for 24 hours straight. I want to start this program once
every 24 hours, make a log, close it. If anyone can help me out with this,
or at least give me something to start with, I would very much appreciate
it!

Why are spurious SAX warnings appearing in my compilation?

Why are spurious SAX warnings appearing in my compilation?

I have a modest-sized multi-project solution written in C# which I am
developing using Microsoft Visual Studio 2010 on Windows XP. In the last
few days it has taken to reporting scores of warnings like the following:-
At least one of the arguments for 'ISAXXMLReader.getBaseURL' cannot be
marshaled by the runtime marshaler. Such arguments will therefore be
passed as a pointer and may require unsafe code to manipulate.
Similar warnings are produced for ISAXLocator, ISAXAttributes,
ISAXXMLFilter, and other apparently SAX related classes. I'm not using XML
at all anywhere in the project.
While this isn't a crippling problem, genuine warnings are getting lost in
the noise.
Does anyone know what the problem is, and what I can do about it?

icreated a table in migration and given a column_name as :name, but it not created in schema, so how to add the column name in that existing...

icreated a table in migration and given a column_name as :name, but it not
created in schema, so how to add the column name in that existing...

manish@manish:~/workspace/depot$ rake db:migrate rake aborted! Multiple
migrations have the name CreateUsers
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/migration.rb:608:in
block in migrations'
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/migration.rb:600:inmap'
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/migration.rb:600:in
migrations'
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/migration.rb:701:inmigrations'
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/migration.rb:656:in
migrate'
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/migration.rb:549:inup'
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/migration.rb:530:in
migrate'
/home/manish/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.1.3/lib/active_record/railties/databases.rake:161:inblock
(2 levels) in '
/home/manish/.rvm/gems/ruby-1.9.3-p448/bin/ruby_noexec_wrapper:14:in eval'
/home/manish/.rvm/gems/ruby-1.9.3-p448/bin/ruby_noexec_wrapper:14:in'
Tasks: TOP => db:migrate (See full trace by running task with --trace)

Wednesday, 18 September 2013

mysql orderby on column after groupby

mysql orderby on column after groupby

I have a table with the following fields: season, collection, product_key,
aggregated_sale. following query is not giving expected output
select t.* from (SELECT * FROM rank_processing.aggregate_season_product
order by aggregated_sale) t group by
t.collection,t.forecast_name,t.product_key;

Year() function and Month() function

Year() function and Month() function

Good Day Every one Currently im using this codes to get the data that are
with in a specific month
SELECT * from Table1 d
where
MONTH(d.fld_ExpiryDate)=@month
AND YEAR(d.fld_ExpiryDate)=@year
some of my colleagues told me to use the duration eg.
d.fld_LoanDate >= '2009-11-01' and
d.fld_LoanDate < '2009-12-01'
the question is would it be better to use the range?? and how would i
compute the start of the month and start of next month? if the users input
where just @month int and @year int?
any help would be greatly appreciated im new in tsql that's why i do not
know the work arounds and whats good or not in coding..
Thank You :)

jQuery Hide Class with Slide Transition

jQuery Hide Class with Slide Transition

I'm trying to collapse a vertical left bar with a slide transition. I
start with a larger width (250px), down to a smaller width (50px) toolbar
size.
I can hide/show the wide bar completely with a nice slide transition using:
$("#pnlLeftSide").hide('slide', {direction:'left'}, 300);
$("#pnlLeftSide").show('slide', {direction:'left'}, 300);
Or I can add a class to go from wide to mini, which basically hides a lot
of inner content and then displays a few smaller toolbar type things
using:
$("#pnlLeftSide").toggleClass("min");
But I can't go from wide to mini, with a nice smooth slide transition as
it collapses in size (width).
If I try this, it jerks at the end
$("#pnlLeftSide").hide('slide', {direction:'left'}, 300, function() {
$(this).addClass("min"); });
$("#pnlLeftSide").show('slide', {direction:'left'}, 300, function() {
$(this).removeClass("min"); });
Any ideas?

Prestashop 1.5 sort product in catgory page by price lowest to heighest by default

Prestashop 1.5 sort product in catgory page by price lowest to heighest by
default

this question can be silly to you, but i am having trouble to find a
solution. I want to sort product in category page by price lowest to
highest, i know there is drop by which i can see products by price but i
want to set it by default so that page loads with sorted. can you tell
which file i should modify? and how can i achieve this?
here is the url so you can check which things i am talking about:
http://goo.gl/8t0pNv
Thanks for help

regex to reorder text with MS Word 2010 or Notepad++

regex to reorder text with MS Word 2010 or Notepad++

I'm trying to figure out how to convert a long document, styles as a
dictionary.
I have this:
÷H1.
John.
walks,
drives,
eats,
drinks,
flies,
travels,
÷H2.
Peter.
flies,
rides,
swims,
÷H3.
James.
laughs,
cries,
I need it like this:
÷H1. John. walks,
÷H1. John. drives,
÷H1. John. eats,
÷H1. John. drinks,
÷H1. John. flies,
÷H1. John. travels,
÷H2. Peter. flies,
÷H2. Peter. rides,
÷H2. Peter. swims,
÷H3. James. laughs,
÷H3. James. cries,
Thank you! Alex

Need to retrieve product descriptor string from USB device on WinXP

Need to retrieve product descriptor string from USB device on WinXP

I have used the code in this post to successfully read the USB product
string in the descriptor for a RNDIS device on Windows 7. I really need
the string from the original USB descriptor and not the one supplied in
the driver INF file. For example, I need to make a user-mode application
able to determine two slightly different products which are identical in
every way except the iProduct - indexed string descriptor. I know that
different products should have different idProduct fields but I have no
control over this.
However, I also need this to work on Windows XP, which apparently does not
support 'DEVPKEY_Device_BusReportedDeviceDesc'.
I believe it may be possible on XP by starting with the usbview project in
the driver development kit, but that looks like tons of work compared to
the relatively simple code referenced above. Does anybody know the easiest
way to get the product string from the USB device's descriptor for a
device which already has a driver installed which works on Windows XP?
The application is unmanaged C++.

In Biztalk Mapping Remove Empty Child record

In Biztalk Mapping Remove Empty Child record

plz find my map below.

where in my first script file i am checking if my reference type is equal
to A,B,C,D,E then only the rest of the elements should map to destination
schema, by doing that i am getting below output.

However i don't want to generate empty child tags. Could you please
suggest. I have checked some blogs where suggesting xslt, I have no idea
of xslt so want to do with functoid.

wordpress bloginfo() outside wordpress

wordpress bloginfo() outside wordpress

I want to use bloginfo() of wardpress out side wordpress directory. I have
tried this:
<?php require( $_SERVER['DOCUMENT_ROOT'] . '/KPR
website/updates/wp-includes/general-template.php' ); ?>
<script src="<?php bloginfo('wpurl'); ?>/js/jquery.min.js"></script>
But I have got this error:
Fatal error: Call to undefined function add_action() in
C:\xampp2\htdocs\website\updates\wp-includes\general-template.php on line
1315
Since I have not modified general-template.php, so I think I need to add
more require phps, Can anyone help?

username and password verification

username and password verification

" <div id="mainlogin" class="login_box">
<html:form action="login" method="post" onsubmit=" return
frmValidate();">
<div class="login-box-name">User Name:<span
class='star'>*</span></div><div
class="login-box-field">
<input id="id" name="id" class="form-login"
title="User Name" value="" size="25"
maxlength="20" oncopy="return false"
onpaste="return false" autocomplete="off"/>
</div>
<br/>
<br/>
<div class="login-box-name">Password:<span
class='star'>*</span></div><div
class="login-box-field">
<input id="password" name="password"
type="password" class="form-login"
title="Password" value="" size="25" maxlength="15"
oncopy="return false" onpaste="return false"
autocomplete="off"/>
</div>
<br/> <br/>
<!-- <span class="forgot"><a id ="resetpwd"
href="javascript:void(0)">Forgot Password</a></span>-->
<br/>
<span class="forgot"><input type="submit"
value="Login" /></span>
</html:form>
</div>"
i am trying to login but when i am entering the username and password and
click on the submit button then i am not getting moved to the next page .
well i am not sure whther i have to modify my "" line so that i can get
the database verification.. if yes please help me

Tuesday, 17 September 2013

Javascript: Need to proceed to another page

Javascript: Need to proceed to another page

I'm using Javascript for deleting a record. But my problem is, when I
click the image button its not redirecting to the page I want instead it
will remain on the page...
Here's my code:
echo "<button type='submit' name='deletePlaylist[]' value='" .
$row['id']."' onClick='myFunction()' style='border: 0; background:
transparent; cursor: pointer;'><img src='image/delete.png' /></button> ";
I'm using the button because I'm using an image if I used the input its
not working... So I decided to use button
Here's my code in my javascript:
function myFunction()
{
var Xcancel;
var Rokay=confirm("Are you sure you want to delete?");
if (Rokay==true)
{
window.location = 'delete.php';
}
else
{
Xcancel="You pressed Cancel!";
}
}
</script>
I already tried the window.navigate("delete.php"); or the
window.location.href='delete.php' also not working...
The confirmation message is displaying already but my main problem its not
going to the delete.php where in that form is my deleting function...
NOTE:
The button is under of the <form name='form' method='post' action="">, the
delete.php is in the same folder... Before there is no confirmation
message and its going to the delete.php but now I tried to insert a
confirmation message then its not going to the delete.php
Thank you in advance,!

PHP string goes empty unless echoed

PHP string goes empty unless echoed

I have the following test program:
#!/usr/bin/php
<?php
echo "Starting\n";
# Now read the file.
#
$file_pn = "contact.txt";
$fh = fopen($file_pn, 'r');
while (!feof($fh)) {
$line = fgets($fh);
$trimmed = trim($line);
echo "trimmed = <" . $trimmed . ">\n";
if (preg_match('/^\s*$/', $trimmed)) {
echo "Looks blank: trimmed = <" . $trimmed . ">\n";
#continue;
}
}
fclose($fh);
?>
The file being read has some blank lines and some non-blank lines. As
shown here, it acts as one would expect: only the lines that are actually
blank receive the "Looks blank" message, and trimmed = <>. But if I
comment out the echo statement in line 12 and run the script again,
$trimmed always appears to be the empty string when we get to the if
statement. It is as if $trimmed gets clobbered unless it has been echoed.
How can this be?

Eclipse crashes when it's starting

Eclipse crashes when it's starting

I try to launch my Eclipse, it starts window with logo but while loading
workbench it crashes.
Log is very long, so I put a link: http://textuploader.com/?p=6&id=TXieq

haskell FFI - using dll on non-windows os?

haskell FFI - using dll on non-windows os?

Can be a windows dll used interfaced with Haskell's FFI(Foreign Function
Interface) on a non windows OS? For example if I have OSX, can I interface
a .dll with FFI (use the dll functions) ?

How to run Dunnett C post hoc test in R?

How to run Dunnett C post hoc test in R?

I ran a two-way anova in r with my data set (unequal sample sizes, unequal
variance): 1 variable measured across 3 species (with males and females in
each species). This produces a significant result between species, so I
want to know which pairwise comparisons produce the significance. I know
that there are functions in packages for performing post hoc tests in R:
e.g.
Dunnett's post hoc test from
http://www.uwlax.edu/faculty/toribio/math305_fall09/multiple.txt
library(multcomp)
?glht
test.dunnett=glht(anova_results,linfct=mcp(method="Dunnett"))
confint(test.dunnett)
plot(test.dunnett)
But Dunett's test is designed to compare all groups to a control. Instead
I want to compare all groups to each other, the Dunnett C. Does anyone
know of a package that performs Dunnett C or knows how to code it?
(equation at:
http://pic.dhe.ibm.com/infocenter/spssstat/v21r0m0/index.jsp?topic=%2Fcom.ibm.spss.statistics.help%2Falg_posthoc_unequalvar.htm)

Sunday, 15 September 2013

Will the JVM detect orphaned cycles?

Will the JVM detect orphaned cycles?

"Orphaned cycles" may not be exactly the correct term for what I'm trying
to describe; I heard it from a co-worker, but it may have just been a
casual term. Here is an example of what I'm trying to describe in code:
public class Container {
private Container otherContainer;
public Container(Container otherContainer) {
this.otherContainer = otherContainer;
}
public void setContainer(Container otherContainer) {
this.otherContainer = otherContainer;
}
}
public class Main {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
Container c1 = new Container(null);
Container c2 = new Container(c1);
c1.setContainer(c2);
// c1 and c2 now each hold a reference to each other; can they be
garbage-collected
// once this method exits?
}
}
Essentially, the question boils down to this - given a graph of references
containing a cycle, can the JVM collect the references once it would be
safe to do so, or is this a memory leak?

Social Plug-in and like button not working on Blogger

Social Plug-in and like button not working on Blogger

My blog is www.pqed.org
The social plugin was working fine until a couple of months ago. Now, it
says the data can't be scraped, the like button doesn't work, when I share
on Facebook, it doesn't give the title or the post image (just the URL and
sometimes a random image from the site). I removed it, but when I put it
in, sometimes it doesn't even show up.
I suspect there is a corrupt image but I can't find it. I have removed all
the widgets, reset the template, and tried everything.
If may also be an an absolute URL problem after the migration. Or it could
be both.
Please help. Will someone look at the code and see what's up?
I have spent maybe 100 hours on this and I think I've made it all worse
instead of better.
Thanks

This is one of the problems with cookie says the book

This is one of the problems with cookie says the book

The book says "A user often opens many tabs in the same browser window. If
the user browses the same site from multiple tabs, all of the site's
cookies are shared by the pages in each tab. this could be problematic in
web applications that allow the user to parchase in each tab."
Can somebody explain what the book is trying to say because I don't really
understand it.
//tony

Colossal memory usage/stack problems with ANTLR lexer/parser

Colossal memory usage/stack problems with ANTLR lexer/parser

I'm porting over a grammar from flex/bison, and mostly seem to have
everything up and running (in particular, my token stream seems fine, and
my parser grammar is compiling and running), but seem to be running into
problems of runaway stack/memory usage even with very small/moderate sized
inputs to my grammar. What is the preferred construct for chaining
together an unbounded sequence of the same nonterminal? In my Bison
grammar I had production rules of the form:
statements: statement | statement statements
words: | word words
In ANTLR, if I maintain the same rule setup, this seems to perform
admirably on small inputs (on the order of 4kB), but leads to stack
overflow on larger inputs (on the order of 100kB). In both cases the
automated parse tree produced is also rather ungainly.
I experimented with changing these production rules to have an explicitly
additive (rather than recursive form):
statements: statement+
words: word*
However this seems to have lead to absolutely horrific blowup in memory
usage (upwards of 1GB) on even very small inputs, and the parser has not
yet managed to return a parse tree after 20 minutes of letting it run.
Any pointers would be appreciated.

Incrementing list items in jinja2 templates (appengine)

Incrementing list items in jinja2 templates (appengine)

I have a list of values in my template, which I need to increment based on
some conditions. Something like this:
{% set samplelist=[0,0,0] %}
{% if condition %}
<p>some text</p>
{% set samplelist[0]=samplelist[0]+listpassedbymainfile[0]
{% endif %}
I keep getting this error when I try to run the above code:
TemplateSyntaxError: expected token '=', got '['
Is this not supported, if so, is there a work around ?

How to get a correct marked image using ROI with javacv

How to get a correct marked image using ROI with javacv

I have run this code and This code give the black image instead of the ROI
marked image,can I please know the wrong with this code please.
public class ROITest {
private static final String OUT_FILE = "img\\ROI.jpg";
public static void main(String[] args)
{
opencv_core.CvRect r =new opencv_core.CvRect();
args[0]="img\\2.jpg";
if (args.length != 1) {
System.out.println("Usage: run FaceDetection <input-file>");
return;
}
// preload the opencv_objdetect module to work around a known bug
// Loader.load(opencv_objdetect.class);
Loader.load(opencv_core.class);
// load an image
System.out.println("Loading image from " + args[0]);
IplImage origImg = cvLoadImage(args[0]);
// IplImage ROIimg = CvSetImageROI(origImg, opencv_core.cvRect(0, 0,
640, 480));
cvSetImageROI(origImg, cvRect(1,1, origImg.width(), origImg.height()));
IplImage ROIimg = IplImage.create(cvGetSize(origImg),origImg.depth(),
origImg.nChannels());
cvCopy(ROIimg,origImg);
cvSaveImage(OUT_FILE, ROIimg);
final IplImage image = cvLoadImage(OUT_FILE);
CanvasFrame canvas = new CanvasFrame("Region of Interest");
cvResetImageROI(image);
canvas.showImage(image);
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
}
It gives a completely black image instead of marked image..

Big image on smaller JFrame/Applet

Big image on smaller JFrame/Applet

I have a pretty big image that I want to display on my JFrame and applet,
the JFrame/Applet is 765x503 in size but the image is way larger. I need a
way to display the image in real size. How can I make it so I can move the
screen around to display some of the image and be able to move around the
image?
I want to be able to drag the screen around, not use Scrollbars.

Saturday, 14 September 2013

(Java) Looking for advise on the layout and process I have chosen for this task?

(Java) Looking for advise on the layout and process I have chosen for this
task?

I hope this is in the right place, if not my apologies but could someone
point me in a better direction? I've been working on this problem for 3
days now, Only 6 weeks into my first university class for any programming
at all and the first language we're learning is Java.
The problem is as follows:
Exercise Two (Another algorithm with sub modules)
Design an algorithm which will:
-Input the cost of a product and the amount the customer has tendered for
payment. you may assume that the payment is always > cost. You may also
assume that the cost and the amount paid are always in increments of 5
cents.
The algorithm should:
-Calculate the amount of change required.
-Determine the notes and coins to be given to the customer. -Output both
to the user.
I have made multiple attempts at this and scrapped my code multiple times,
I'm not looking for a solution from anyone, I've put enough into this to
hold out for that, but I am after some commentary on whether or not I am
going in right direction or if not a pointer as to where, also any comment
on the comments I've added to the code would be greatly appreciated.
Thanks for even taking the time to read this and a huge thanks to anyone
that can give me a hand. Cheers everyone
import io.*;
public class CoinChange
{
public static void main (String [] args)
{
double tenderValue;
// How do I make tenderValue and tenderValueInCents equal to multiple
variables and then allow these variables to be added into submodule as I
require?
// Do I need to create a submodule just for this? I attempted to make
multiple lines all equalling the variable name but it didnt seem to like
that either.
tenderValue = int (100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05);
tenderValueInCents = int (10000, 5000, 2000, 1000, 500, 200, 100, 50,
20, 10, 5);
change = calcChange(cashPayed, itemCost);
System.out.println(+change +"total change back");
changeInCents = calcChangeInCents(cashPayed, itemCost);
noteFinder (100, 10000); //Is this enough information required to feed
the variable required into this specific submodule?
noteFinderTemp (50, 5000); //Have a feeling I need to add in all the
variables used in the submodules as well?
noteFinderTemp (20,2000);
noteFinderTemp (10,1000);
noteFinderTemp (5,500);
coinFinder (2,200);
coinFinder (1,100);
coinFinder (0.5,50);
coinFinder (0.2,20);
coinFinder (0.1,10);
coinFinder (0.05,5);
}
private static calcChange(double cashPayed, double itemCost, double
change);
{
// I am not actually required to add in the checking to see if the
values are valid lines I just wanted to see if i could but after two
days at this its starting to drive me up the wall and if theres a
lot more that needs to be done for this bit i can take it out and
come back to trying this after getting the program to compile.
cashPayed=ConsoleInput="Enter cash payed in dollars and cents (xx.xx)";
itemCost=ConsoleInput="Enter cost of item xx.xx)";
if cashPayed>itemCost;
change=cashPayed-itemCost;
return change;
else if cashPayed<itemCost;
requiredMoney=itemCost-cashPayed;
System.out.println("Please provide" +requiredMoney +"to complete
transaction.");
system.exit;
else if cashPayed==itemCost;
System.out.println("Thankyou, payment complete.");
system.exit;
}
private static calcChangeInCents(double cashPayed, cashPayedInCents
double itemCost, itemCostInCents double changeInCents);
{
cashPayedInCents=cashPayed*100;
itemCostInCents=itemCost*100;
changeInCents=cashPayedInCents-itemCostInCents;
return changeInCents;
}
private static noteFinder ( double tenderValue, tenderValueInCents,
changeInCents, tenderValueQuantity, tempChangeInCents);
{
tenderValueQuantity=changeInCents/tenderValueInCents;
tempChangeInCents=changeInCents%tenderValue;
if (tenderValueQuantity=0 && tempChangeInCents=0);
system.exit; //is this an adequete way to say if these values are
zero then end program?
else if tenderValueQuantity=>1;
//DO I NEED TO PUT THIS IN? maths.RoundDown(tenderValueQuantity); OR
ANOTHER WAY? LIKE *1000 AND /1000 OR TAKING THE RESULT OF % FROM ORIGINAL?
System.out.println(+tenderValueQuantity +"x $" +tenderValue
+"Notes Change");
else system.out.println("No $" +tendervalue +"Notes required");
if temptChangeInCents=!0;
return tempChangeInCents;
else system.exit;
}
private static noteFinderTemp ( double tenderValue,
tenderValueInCents, changeInCents, tenderValueQuantity,
tempChangeInCents);
{
tenderValueQuantity=tempChangeInCents/tenderValueInCents;
tempChangeInCents=tempChangeInCents%tenderValue;
// This above line^ is the one I am most concerned about, will the
tempChangeInCents override itself in order or will it cause all sorts of
random problems set out like this? If so I'm guessing that I will not be
able to complete this with general submodules subbing in multiple
variables and will have to create a submodule for every tendervalue? This
was my initial thought but hoped there would be a more elegant way to do
it.
if (tenderValueQuantity=0 && tempChangeInCents=0);
system.exit;
else if tenderValueQuantity=>1
System.out.println(+tenderValueQuantity +"x $" +tenderValue
+"Notes change")
else system.out.println("No $" +tendervalue +"Notes required")
if temptChangeInCents=!0 THEN
return tempChangeInCents
else system.exit;
}
private static coinFinder ( double tenderValue, tenderValueInCents,
changeInCents, tenderValueQuantity, tempChangeInCents);
{
tenderValueQuantity=tempChangeInCents/tenderValueInCents;
tempChangeInCents=tempChangeInCents%tenderValue;
if (tenderValueQuantity=0 && tempChangeInCents=0);
system.exit;
else if tenderValueQuantity=>1
System.out.println(+tenderValueQuantity +"x $" +tenderValue
+"Coins change")
else system.out.println("No" +tendervalue +"c coins required")
if temptChangeInCents=!0 THEN
return tempChangeInCents
else system.exit;
}
}'

Which is more efficient recursion or loops?

Which is more efficient recursion or loops?

I am curious which is more efficient for iteration. I am using one to
break up a parse a string into a List. Is recursion more CPU efficient or
is looping? Is either more memory efficient? By looping, I am referring to
for, for each, do while, while, and any other types. Out of these loops
which are more efficient? Or are they all equally? Just curious.

Why it's the best way to implement the image list, the same image list of the gallery apps

Why it's the best way to implement the image list, the same image list of
the gallery apps

I want to implement a list composed of images with 3 columns and multiple
rows,
according to the number of available images. I'm searching in many places
and not found anything about it yet. What better way to make this?

Using Selenium Webdriver how to connect remote database and run test cases from local machine through eclipse

Using Selenium Webdriver how to connect remote database and run test cases
from local machine through eclipse

I am using selenium web driver java built , editor is eclipse. For testing
one of our website I am using Data driven testing by fetching data from
MySQL database.
I dumped the development server database to my local machine and installed
that dumped data in my machine xampp and able to connect to database and
proceed through the testing process.
To connect to my local machine database i am using this connection string
String url1 ="jdbc:mysql://localhost:3306/databasename";
String dbClass = "com.mysql.jdbc.Driver";
Class.forName(dbClass).newInstance();
Connection con = DriverManager.getConnection(url1, "root", "");
Statement stmt = (Statement) con.createStatement();
Now I need to connect to connect to our original development server
database which is in remote server.
Can any one suggest me how to connect to the remote server database and
what changes are needed to be done in the connection string ? what to put
in the host name ? and how I can run my test cases from my local machine
while connecting to remote server database.
Please provide some suggestion

Bitwise memmove

Bitwise memmove

Is their any implementation available for performing a bitwise memmove?
The method should take an additional destination and source bit-offset and
the count should be in bits too.
I saw that ARM provides a non-standard _membitmove, which does exactly
what I need, but I couldn't find it's or any similar method's source.

heroku restart via new API

heroku restart via new API

I'm a bit confused, as there used to be a method in heroku API to restart
processes of an app. Now this API seems to be deprecated and all links are
leading to https://devcenter.heroku.com/articles/platform-api-reference
where I cannot find any information about restart (even the word restart
itself).
Can someone shed some light on it? This is, I believe, along with showing
logs, one of the most important API commands for a dev, as you can do most
of other tasks via heroku webui.

thread synchronised confused by lock(this)

thread synchronised confused by lock(this)

I hava a class:
public class LockTest
{
public void LockThis()
{
lock (this)
{
Console.WriteLine("lock this test");
System.Threading.Thread.Sleep(5000);
}
}
}
in Main:
static void Main(string[] args)
{
LockTest lockTest = new LockTest();
lock (lockTest)
{
//lockTest.LockThis();
System.Threading.Thread thread = new Thread(lockTest.LockThis);
thread.Start();
}
Console.Read();
}
I thought the invoking lockTest.LockThis() will cause a dead lock but it
didn't. I don't konw why.

Friday, 13 September 2013

HTML CSS draw angular side

HTML CSS draw angular side

Need to draw angular sides of menubar as

inner content may be the some labels or links.
Thanks verymuch

Dynamic Div Content with just clicking one link/button

Dynamic Div Content with just clicking one link/button

I need help here please.
I want to show dynamic content to a div. I already have the code below:
<script type="text/javascript"><!--
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
//--></script>
<div id="example1div" style="padding:10px; text-align:left;">
<p>Content 1</p>
</div>
<p align="center"><a
href="javascript:ReplaceContentInContainer('example1div','<p>Content
2</p>')">View another</a></p>
What it does is, when click the "View another" it replace the 'Content 1'
to 'Content 2' but what I want here is that, when 'Content 2' is already
shown, I want to click the "View another" link again and replace the div
content again with the new content like 'Content 3'.
Anyone please help me solve this.
Thanks in advance :)

understanding javascript functions and var

understanding javascript functions and var

I just went through my class note and not really understood
var x = 1;
function func1() {
x+= 10; }
func2= function( x )
{ x += 5;
}
what does the line func2= function( x ) means? does x will be 15?

One notification work and cancel the other notifications

One notification work and cancel the other notifications

I am having a problem here guys which is I'm trying to do three
notification with sounds and what i want to do is when the S1 button or S2
or S3 one of them pressed i want to cancel the other two notification
help please with details because im confused
}
-(void)scheduleLocalNotificationWithDate:(NSDate *)fireDate
{
UILocalNotification *notifiction = [[UILocalNotification alloc]init];
notifiction.FireDate = fireDate;
notifiction.AlertBody = @" ";
notifiction.soundName = NSUserDefaultsDidChangeNotification;
notifiction.repeatInterval= NSMinuteCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification: notifiction];
NSLog(@" ");
}
(IBAction)SetBtn:(id)sender
{
NSDateFormatter *dateFormatter =[ [NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
NSString *dateTimeString = [dateFormatter stringFromDate:
dateTimePicker.date];
[self scheduleLocalNotificationWithDate:dateTimePicker.date];
}
(IBAction)S1:(NSDate *) fireDate;
{
soundNumber = 1; [[NSUserDefaults standardUserDefaults] setObject:@"S1"
forKey:@"UserSoundChoice"]; UILocalNotification *localNotification1 =
[[UILocalNotification alloc] init]; [localNotification1
setFireDate:[NSDate date]]; [localNotification1 setTimeZone:[NSTimeZone
defaultTimeZone]]; [localNotification1 setAlertBody:@"Wake up!!"];
[localNotification1 setAlertAction:@"View"]; [localNotification1
setHasAction:YES]; localNotification1.repeatInterval=
NSMinuteCalendarUnit; localNotification1.soundName= [[NSUserDefaults
standardUserDefaults] objectForKey:@"UserSoundChoice"]; [[UIApplication
sharedApplication] scheduleLocalNotification:localNotification1];
}
(IBAction)S2:(NSDate *) fireDate;
{
soundNumber = 2; [[NSUserDefaults standardUserDefaults] setObject:@"S2"
forKey:@"UserSoundChoice"]; UILocalNotification *localNotification2 =
[[UILocalNotification alloc] init]; [localNotification2
setFireDate:[NSDate date]]; [localNotification2 setTimeZone:[NSTimeZone
defaultTimeZone]]; [localNotification2 setAlertBody:@"Wake up!!"];
[localNotification2 setAlertAction:@"View"]; [localNotification2
setHasAction:YES]; localNotification2.repeatInterval=
NSMinuteCalendarUnit; localNotification2.soundName= [[NSUserDefaults
standardUserDefaults] objectForKey:@"UserSoundChoice"]; [[UIApplication
sharedApplication] scheduleLocalNotification:localNotification2];
}
-(IBAction)S3: (NSDate *) fireDate;
{
soundNumber = 3;
[[NSUserDefaults standardUserDefaults] setObject:@"S3"
forKey:@"UserSoundChoice"];
UILocalNotification *localNotification3 = [[UILocalNotification alloc] init];
[localNotification3 setFireDate:[NSDate date]];
[localNotification3 setTimeZone:[NSTimeZone defaultTimeZone]];
[localNotification3 setAlertBody:@""];
[localNotification3 setAlertAction:@"View"];
[localNotification3 setHasAction:YES];
localNotification3.repeatInterval= NSMinuteCalendarUnit;
localNotification3.soundName= [[NSUserDefaults standardUserDefaults]
objectForKey:@"UserSoundChoice"];
[[UIApplication sharedApplication]
scheduleLocalNotification:localNotification3];
}

Cakephp Upload plugin allows any file extension to be uploaded despite validation rules

Cakephp Upload plugin allows any file extension to be uploaded despite
validation rules

'model' => array(
'rule' => array('isValidExtension', array('xls')),
'message' => 'File does not have a stl extension'
),
Allows absolutely any file to be uploaded. I have this is as my first
validation rule. Other validation rules like notEmpty, and isUnique work
fine on the same form element.
Tried adding stl to the array found in the main behavior: 'extensions' =>
array('xls') - also did not work.
Any idea on what I'm doing wrong here?
Also: This appears to happen regardless of the file extension I pick. No
matter what, it doesn't call the file invalid. The same issue appears to
happen with Mime types as well.
The plugin URL is: https://github.com/josegonzalez/upload

Display Image on Mouseover

Display Image on Mouseover

How do I display an image on mouse over? I also need to underline the text
next to the image on mouse over? On mouseout I have to hide the image and
make the text normal again.
This is my html field
<img src="img.jpg"> Name
Now when I load the page I want not to display the image unless I have the
mouse over the place it should appear.

How to catch argv null exception?

How to catch argv null exception?

In my program I pass an argument from console and save it to a variable.
Let's say
const string FileName= argv[1];
If there is no argument passing I get this
terminate called throwing an exception
How can I catch an exception and show proper error to user that there is
no arguments passed?

Thursday, 12 September 2013

How to exit SurfaceView?

How to exit SurfaceView?

I draw something on canvas using SurfaceView. How can I define a way to
cancelling the surfaceView once the user is done? Below is my SurfaceView
implementation. The DrawOnTop class has the onDraw() but I initialize all
the variables in Preview class.
public class Preview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
DrawOnTop mDrawOnTop;
boolean mFinished;
Preview(Context context, DrawOnTop drawOnTop) {
super(context);
mDrawOnTop = drawOnTop;
mFinished = false;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
//I set the bitmaps etc here
mDrawOnTop.mBitmap = Bitmap.createBitmap(mDrawOnTop.mImageWidth,
mDrawOnTop.mImageHeight, Bitmap.Config.ARGB_8888);
mDrawOnTop.mBitmap.setPixels(mDrawOnTop.mRGBData, 0,
mDrawOnTop.mImageWidth, 0, 0, mDrawOnTop.mImageWidth,
mDrawOnTop.mImageHeight);
mDrawOnTop.invalidate();
}
public void surfaceDestroyed(SurfaceHolder holder) {
mFinished = true;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w,
int h) {
}
}

Matching numbers inside nested numbered groups

Matching numbers inside nested numbered groups

I am trying to find and capture all numbers inside ( and ) separately in
my data, ignoring the rest of the numbers.
My data looks like this
21 [42] (12) 19 25 [44] (25 26 27) 17 (14 3) 8 1 6 (19)
So I want to find matches for 12, 25, 26, 27, 14, 3 and 19
I tried doing \((\d+)\)* but this only gives me 12, 25, 14, 19
Any help is appreciated.

How many times does this code run?

How many times does this code run?

I'm testing some code and I assume the code below will run the
'somefunction()' every 2 seconds. However, it only runs once..... why is
this?
$(document).ready(function () {window.setInterval(somefuntion(),
2000);});

Apache/WordPress Cache Not Refreshing On My IP

Apache/WordPress Cache Not Refreshing On My IP

So I was trying out a caching plugin on my WP site. I had installed it
after my home page never changed (forever static). Uninstalled the plugin,
tried moving the WP files to another sub-domain, and my frontpage still
was static. Even on another sub-domain. This only had happened when I
changed some .htaccess settings for it, but I had already reverted these.
I've tried emptying my local cache. Page is still static. Does anyone know
what is going on?
I also figured out, it only is that page on my IP. And only that page.
Doesn't matter if the file exists, still makes the same old page show up.
Any help?

How to find n+n/2+n/3+.....+n/n in C efficiently?

How to find n+n/2+n/3+.....+n/n in C efficiently?

how to find sum n+n/2+n/3+....+n/n in C efficiently???
I need an algorithm better than O(n).
Can we calculate it better than ?
Any help is appreciated.

Micro-optimization of IF statement

Micro-optimization of IF statement

I always look into how to optimize the code more and more every day, and
how I can learn to code faster code.
Looking at some minified JS online I notice the change of a few IF into a
statement and I thought that it might be a very good idea to start using
it in PHP as well.
<?php
if(!isset($myVar) || $myVar == 'val'){
$myVar = 'oldVal';
}
if(isset($myVar) && $myVar == 'oldVal'){
$myVar = 'newVal';
}
?>
into
<?php
(!isset($myVar) || $myVar == 'val') && $myVar = 'oldVal';
isset($myVar) && $myVar == 'oldVal' && $myVar = 'newVal';
?>
As I like the new syntax, I started to use it more and more thinking to
save processing time, but do I really save any or there is no difference
internally between the two ?
(The example code is just an EXAMPLE to only show the technique)

Load JPEG image into a BlobField

Load JPEG image into a BlobField

I would like load JPEG image into a blob field, is it possible? I search a
lot but I don't find a clear answer.
I use this code:
var
BlobField : TBlobField;
Stream : TMemoryStream;
begin
BlobField := ClientDataSet1.FieldByName('image');
// Img is TImage and contain a JPEG image
Img.Picture.Graphic.SaveToStream(Stream);
Stream.Position := 0;
BlobField.LoadFromStream(Stream); // <-- Error: "Bitmap image is not
valid"
I have to use bitmap image?

Wednesday, 11 September 2013

jquery background image url failed

jquery background image url failed

This is not working ....
$("#news_all ul li").css("background", "transparent
url('../images/01.png') no-repeat");
but this is working
.news_all_item li {
background: url("../images/01.png") no-repeat scroll 0 0 transparent;
margin-bottom: 2%;
}
My html
<div class="news_all_item" id="news_all">
<ul>
<li><div class="news_item">Lorem Ipsum is simply dummy text of the
printing and typesettiLorem Ipsum is simply dummy
textlt;/divgt;lt;/ligt;
lt;ligt;lt;div class=news_itemgt;Lorem Ipsum is simply dummy text of
the printing and typesettiLorem Ipsum lt;/divgt;lt;/ligt;
lt;ligt;lt;div class=news_itemgt;Lorem Ipsum is simply dummy text of
the printing and typesettilt;/divgt;lt;/ligt;
lt;/ulgt;
lt;/divgt;
/code/pre

Is `a

Is `a

I was curious to see if I could use this a<b<c as a conditional without
using the standard a<b and b<c. So I tried it out and my test results
passed.
a = 1
b = 2
c = 3
assert(a<b<c) # In bounds test
assert(not(b<a<c)) # Out of bounds test
assert(not(a<c<b)) # Out of bounds test
Just for good measure I tried more numbers, this time in the negative
region. Where a, b, c = -10, -9, -8. The test passed once again. Even the
test suit at a higher range works a, b, c = 10, 11, 12. Or even a, b, c =
10, 20, 5.
And the same experiment done in C++. This was my mentality going into it:
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
a=10;
b=20;
c=5;
cout << ((a<b<c)?"True":"False") << endl; // Provides True (wrong)
cout << ((a<b && b<c)?"True":"False") << endl; // Provides False
(proper answer)
return 0;
}
I originally though that this implementation would be invalid since in
every other language I have come across would evaluate a boolean before it
would reach c. With those languages, a<b would evaluate to a boolean and
continuing the evaluation, b<c, would be invalid since it would attempt to
evaluate a boolean against a number (most likely throwing a compile time
error or falsifying the intended comparison). This is a little unsettling
to me for some reason. I guess I just need to be reassured that this is
part of the syntax. It would also be helpful to provide a reference to
where this feature is provided in the Python documentation so I can see to
what extent they provide features like this.

Does cout object remain a single instance, i.e. it never gets copied?

Does cout object remain a single instance, i.e. it never gets copied?

Is cout ever copied implicitly?
For example, is the cout object passed to the second overloaded operator
in the code below, and the cout object inside its implementation are the
same objects or is one a copy of cout?
My understanding is that the first implementation is correct because the
<< operator works for any ostream object, e.g. it will work for ofstream
objects for writing to files.
//First implementation
ostream& operator<<(ostream& os, const Date& dt)
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
//Second implementation
ostream& operator<<(ostream& os, const Date& dt)
{
cout << dt.mo << '/' << dt.da << '/' << dt.yr;
return cout;
}
//using second implementation on object date
cout<<date;

Creating reusable Django models

Creating reusable Django models

Having some trouble designing an application using Django models. More
specifically, I am trying to decide in which application a given model
should go.
A good example would be with a model where different analyses would be
performed on an object. For example, if I were doing an analysis on the
efficiency of a prostitution ring, I would have three models: Pimp, Whore,
and Client:
The pimp object would have a "stable" attribute which represents the
one-to-many relationship between the Pimp and his whores.
The Whore object would have a many-to-many relationship with the Client
object, or, there would be an additional "Trick" object, representing the
relationship between Whores and Clients.
If I wanted to analyze these objects in one way, i.e. seeing each whore's
percent time "occupied", this would be one simple application. But what if
I wanted to do additional analysis on these objects, i.e. see what whores
are the most "in demand"? It would make sense to me that each kind if
analysis belongs to an individual app, but then to which app do these
common objects belong?
Is there a common place where these common models should be stored? Should
all analyses be contained in one app?

Java Networking Console Spam

Java Networking Console Spam

I am trying to make a plugin for Bukkit, that will allow multiple servers
to talk to each other (send data over ip:port). I have got the basic code
working but when I reload the plugin the console gets spammed with this
java.net.SocketException: Socket is closed 2013-09-11 19:56:19 [SEVERE] at
java.net.ServerSocket.accept(Unknown Source) 2013-09-11 19:56:19 [SEVERE]
at com.github.dcsoftgit.multiserver.ReadThread.run(ReadThread.java:14)
This is my code for server1:
package com.github.dcsoftgit.multiserver;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class MultiServer extends JavaPlugin {
public static ServerSocket sock;
ReadThread t;
public void onEnable() {
t = new ReadThread();
try {
sock = new ServerSocket(4571);
} catch (IOException e) {
e.printStackTrace();
}
t.start();
getServer().getScheduler().scheduleSyncDelayedTask(this, new
Runnable() {
@Override
public void run() {
sendDataToSocket("Hello server 2");
}
});
}
public void onDisable() {
try {
sock.close();
} catch (IOException e) {
}
}
public static void sendDataToSocket(String data) {
Socket client;
try {
client = new Socket("127.0.0.1", 4572);
DataOutputStream ds = new
DataOutputStream(client.getOutputStream());
ds.writeUTF(data);
ds.close();
client.close();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
and this is server2:
package com.github.dcsoftgit.multiserver;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class MultiServer extends JavaPlugin {
public static ServerSocket sock;
ReadThread t;
public void onEnable() {
t = new ReadThread();
try {
sock = new ServerSocket(4572);
} catch (IOException e) {
e.printStackTrace();
}
t.start();
getServer().getScheduler().scheduleSyncDelayedTask(this, new
Runnable() {
@Override
public void run() {
sendDataToSocket("Hello server 1");
}
});
}
public void onDisable() {
try {
sock.close();
} catch (IOException e) {
}
}
public static void sendDataToSocket(String data) {
Socket client;
try {
client = new Socket("127.0.0.1", 4571);
DataOutputStream ds = new
DataOutputStream(client.getOutputStream());
ds.writeUTF(data);
ds.close();
client.close();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
this is the ReadThread class:
package com.github.dcsoftgit.multiserver;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class ReadThread extends Thread {
public void run(){
while (!isInterrupted()){
try {
//init the client
Socket client = MultiServer.sock.accept();
//Read the data
DataInputStream dis = new
DataInputStream(client.getInputStream());
String data = dis.readUTF();
System.out.println(data);
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public synchronized void start() {
super.start();
}
}
Using this code when I reload the plugin it calls onDisable() and then
onEnable(). When the server starts it only calls onEnable().

Print osm using mapfish printservlet war file in tomcat

Print osm using mapfish printservlet war file in tomcat

I have downloaded the war file of the mapfish print osm and deployed it in
the tomcat, and used the js files from
http://api.geoext.org/1.1/examples/print-preview-osm.html, but i'm having
an exception
org.mapfish.print.InvalidJsonValueException: spec.layers[0].type has an
invalid value: OSM
is it the right way to do to print the map or can anybody point me in
right direction..my code is:
Ext.onReady(function() {
// The PrintProvider that connects us to the print service
var printProvider = new GeoExt.data.PrintProvider({
url: "http://localhost:8000/print-servlet-1.1/pdf/print.pdf",
method: "GET", // "POST" recommended for production use
capabilities: printCapabilities, // provide url instead for lazy loading
customParams: {
mapTitle: "OSM Printing",
comment: "This demo shows how to use GeoExt.PrintMapPanel with OSM"
}
});
var map = new OpenLayers.Map();
map.addLayer(new OpenLayers.Layer.OSM());
var lonLat = new OpenLayers.LonLat( userLon ,userLat ).transform(
new
OpenLayers.Projection("EPSG:4326"), //
transform from WGS 1984
map.getProjectionObject() // to
Spherical Mercator Projection
);
var zoom=10;
var markers = new
OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
markers.addMarker(new
OpenLayers.Marker(lonLat));
map.setCenter (lonLat, zoom);
// A MapPanel with a "Print..." button
mapPanel = new GeoExt.MapPanel({
renderTo: "content",
width: 1000,
height: 800,
map: map,
zoom: 10,
bbar: [{
text: "Print...",
handler: function(){
// A window with the PrintMapPanel, which we can use to adjust
// the print extent before creating the pdf.
printDialog = new Ext.Window({
title: "Print Preview",
width: 500,
autoHeight: true,
items: [{
sourceMap: mapPanel,
printProvider: printProvider,
xtype: "gx_printmappanel",
// use only a PanPanel control
map: {controls: [new OpenLayers.Control.PanPanel()]}
}],
bbar: [{
text: "Create PDF",
handler: function(){ printDialog.items.get(0).print(); }
}]
});
printDialog.show();
}
}]
});
I have tried using without ext.js but was not able to get how to pass the
map div as parameter,so i used the geoext but that was giving the above
exception.
My config File:
hosts:
- !localMatch
dummy: true
- !ipMatch
ip: http://localhost:8000/print-servlet-1.1/
- !dnsMatch
host: localhost
port: 8000
- !dnsMatch
host: demo.mapfish.org
port: 8000
layouts:
mainPage:
rotation: true
pageSize: A4
header:
height: 50
items:
- !text
font: Helvetica
fontSize: 30
align: right
text: '${mapTitle}'
items:
- !map
spacingAfter: 30
width: 440
height: 483
- !text
text: '${comment}'
spacingAfter: 30
footer:
height: 30
items:
- !columns
items:
- !text
backgroundColor: #FF0000
align: left
text: Copyright Juventus Techonologies
- !text
align: right
text: 'Page ${pageNum}'
anybody help me out with please..

Any help on Mail.log file analysis appplications, graph representation of queues?

Any help on Mail.log file analysis appplications, graph representation of
queues?

once you start receiving about 5-10 emails/sec it becomes painful the
detailed analysis of mail.log. Out setup is quite standard: Ubuntu
12.04+postfix+postscreen+dovecot+postgrey+amavisd-new+rbl
Are there any software that facilitates the detailed mail.log analysis?
The perfect panel would be the graphical application that permits to
search among millions of email.log lines in the decent way, that is the
result can be represented in the form of a client-server handshake
procedure similar to TCP protocol

or by means of some sort of Graph, similar to git-gui

So I repeat we're not looking for packages which collects the statistics.
We're looking for the instrument that helps to make a fast insight on some
queue happened in the past to understand what was an obstacle in one
particular session.

Can I get audio data from microphone in background task of Windows Phone 8?

Can I get audio data from microphone in background task of Windows Phone 8?

I want to implement a feature in Windows Phone 8, let it calculate decibel
by using the audio data from microphone in background task. Is it
possible?

Tuesday, 10 September 2013

Android ExpandableListView or List Adaptor

Android ExpandableListView or List Adaptor

Android phone app. I will describe the situation and then pose my question
afterwards.
I want to give the user the ability to pick an option from an expandable
list, but when an option that has sub options (children), I want to just
display those child's option(s). So.. not the normal functionality for the
Expandable ListView list.
So... instead of "expanding" and showing a list, only the items from the
sub-menu/list would be displayed.
Example list
Item 1
Item 2
Item 3 >
---- Sub Item 1 for Item 3 (Item 6)
---- Sub Item 2 for Item 3 (Item 7)
---- Sub Item 3 for Item 3 (Item 8) >
-------- Item 9
-------- Item 10
Item 4
Item 5
In the above example, the user would initially see Items 1 to 5. If any of
an items from this top list are selected (user touches it).. except for
Item 3, you are done... selection made.
If Item 3 is selected... then a Sub list of items for item 3 is shown...
just Items 6,7,8.. I want Items 1 through 5 to no longer show on the
screen.
If Item 8 is then chosen, only Items 9 and 10 would be on the screen for
the choices.
Is an Expandable ListView the way to go or maybe a List Adaptor? or
something else.?
I have searched for hours to see something similar. Any possible solutions
are appreciated. I do not mind doing hours of legwork, just stuck and need
direction.
A bonus would be to show a ">" symbol to the right of a choice that has
sub choices under it. I have tried to show this for items 3 and 8.
I appreciate your time in reading this.
Thanks.

BadPaddingException : Data must start with zero

BadPaddingException : Data must start with zero

I implemented data encryption/decryption with RSA. It works if I just
encrypt/decrypt locally, however if I send my encrypted data I get
BadPaddingException: Data must start with zero.
In order to send my data over network I need to change it from byte array
to String (I'm sending it in a header) on the client side and then
retrieve it and change it back to byte array on the server side.
Here's my code for local encryption/decryption (I'm using private key to
encrypt and public key do decrypt):
// Encryption:
String message = "HELLO";
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, privateKey); // privateKey has type
java.security.PrivateKey
byte [] encryptedBytes = rsa.doFinal(message.getBytes());
// Decryption:
rsa.init(Cipher.DECRYPT_MODE, publicKey); // type of publicKey:
java.security.PublicKey
byte [] ciphertext = rsa.doFinal(encryptedBytes);
String decryptedString = new String(ciphertext, "UTF-8");
DecryptedString and message are the same and everything works fine.
Then I use the same code on the client side just for encryption plus I
change ciphertext to a String using:
String encryptedString = new String(ciphertext, "UTF-8");
And on the server side I do:
String message = request.getHeader("Message");
byte [] msgBytes = message.getBytes("UTF-8");
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, publicKey);
byte [] decryptedMsg = rsa.doFinal(msgBytes);
String decryptedString = new String(decryptedMsg, "UTF-8");
This doesn't work and I get BadPaddingException.
I have tried using different instance of cipher, e.g.
"RSA/ECB/PKCS1Padding" or "RSA/ECB/NoPadding" but this didn't help. I also
tried converting Strings using BASE64 but then I get a different
exception: IllegalBlockSizeException.
I know I probably do sth wrong with converting Strings into byte arrays
and vice versa, but I just can't figure out the correct way of doing that.
Please help!

Python - setattr function without self parameter, 2 parameters instead of 3

Python - setattr function without self parameter, 2 parameters instead of 3

I have the following code where I need to use setattr to generate the
variable from the string and set it equal to amn.
for i in amenities:
if i in request.GET:
amn = request.GET.getlist(i)
propertiesList = Property.objects.filter(setattr(i+"__title__in",
amn))
It seems setattr takes 3 parameters, how can I do it with just these 2
parameters?

WPF Display of PDF Options (Print, Save, etc)

WPF Display of PDF Options (Print, Save, etc)

I'm creating a WPF application that has viewing of PFDs built into it.
I've noticed that when I view some files (such as electronic version of
books), the options and tools such as print, save, etc. will appear top as
such:

However, some other files that are.. let's say created from a Word
Document or sent to print to PDF will not have those options, but rather
will display them towards the bottom if you hover your mouse in that area:

I like the second better than the first; however, due to the fact that
some users might not know that hovering towards the bottom will display
those options, I want to be able to force those options to display. Is
there a way? Or will have I have to design a new set of buttons on top of
the PDF viewing control to do that....?

How can you tell if an android service is running in the foreground from code?

How can you tell if an android service is running in the foreground from
code?

From within a particular service I want to know if I'm already in the
foreground. I looked at:
ActivityManager.RunningServiceInfo
specifically RunningServiceInfo.foreground, but the documentation says,
"Set to true if the service has asked to run as a foreground process."
So can I rely on RunningServiceInfo.foreground? Or should I go about this
another way?

Play nice, node-formidable and express.bodyParser

Play nice, node-formidable and express.bodyParser

I used to do app.use(express.bodyParser()); to allow me to get POST bodies
in my ordinary (non-file) routes.
I then had to implement multi-file uploads, so I introduced
node-formidable. For the the only single route for which I need
node-formidable's functionality, I instantiate it explicitly and use it
from there:
var form = new formidable.IncomingForm({ uploadDir:__dirname +
'/public/uploads' });
What I now need is to get back to being able to parse textual POST data
without having formidable interfere with that. Sadly, as soon as I
reintroduce app.use(express.bodyParser()); into my script, then attempts
to parse images using node-formidable as described above, will fail.
Is there any easy way to get around this? Can I not use node-formidable's
bodyParser to deal with everything? If so, how would I do that?

Why not working to write into a txt file with PHP

Why not working to write into a txt file with PHP

I am trying to write some simple text into a text file but writing is not
working, Below is the code I am using: what is the wrong with the code
please??
<?php
// create short variable names
$tireqty = 24;
$oilqty = 34;
$sparkqty = 12;
echo "<p>Your order is as follows: </p>";
echo $tireqty." tires<br />";
echo $oilqty." bottles of oil<br />";
echo $sparkqty." spark plugs<br />";
@ $fp=fopen("/order.txt","w");
if(!$fp){
echo "The file is not exists";
exit;
}
$outputstring = $date.'\t'.$tireqty.' tires \t'.$oilqty.' oil\t'
.$sparkqty.' spark plugs\t\$'.$totalamount.'\t'. $address.'\n';
fwrite($fp, $outputstring);
fclose($fp);
echo "Order have written into order.txt";

refreshing the action bar spinner after database changes

refreshing the action bar spinner after database changes

I have an action bar spinner in one activity that gets populated using
data from a database. I have a second activity that modifies the database
(including data for the action bar spinner that is used in the first
activity). How do I refresh the spinner once database changes ? I tried
notifyDataSetChanged();, doesn't work. Also when I restart the app after
doing the changes, they are reflected in the spinner so I can see
modifying works, but only when I run the app again, not as the changes are
being made
// this is inside the onCreate()
// return a List<String> used to populate action bar spinner
listUniqueCat = mDbHelper.getUniqueCategories();
// create an array adapter to popluate dropdown list
adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, listUniqueCat);
// enable dropdown list naaavigation in action bar
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// defining navigation listiner
ActionBar.OnNavigationListener navigationListener = new
OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
selectedPos = getActionBar().getSelectedNavigationIndex();
selectedSpinnerItem = listUniqueCat.get(selectedPos);
Toast.makeText(getBaseContext(),
"you selected " + selectedSpinnerItem,
Toast.LENGTH_LONG).show();
return false;
}
};
// setting dropdown items and item navigation listener for action bar
getActionBar().setListNavigationCallbacks(adapter, navigationListener);

Monday, 9 September 2013

how do i insert a huge amount of data rows from a CSV to MYSQL?

how do i insert a huge amount of data rows from a CSV to MYSQL?

I have an Excel document (15KB) extracted as .CSV from a monitoring
platform that uses 1 column ip address but contains 1048576 Rows.
how do i insert all this data on my MYSQL database?
also, i have 10 of these excel documents each document maximizes the excel
total rows. so i have a total of 10485760 rows to use.
does MYSQL the appropriate database to use?
i needed to check these data from time to time, but im not sure where to
store them and look/search for a specific row easily when i needed to.
p.s: i dont work for the NSA

DiscoverMeteor: Commit 2-2

DiscoverMeteor: Commit 2-2

Right after adding bootstrap (after commit 2-1), the font of the main page
changed, even though microscope.css is still empty. I could not find any
other stylesheets in the microscope directory. How was the style applied?

Urgent help required

Urgent help required

I'm trying to do the following but it is not working properly:
In my project I have several forms. In some forms I have a lookup button.
What I'm trying to do is- when the lookup button is clicked, another form
with a datagrid is openned and some records are displayed on the grid
(from SQL Server). Up to this point there is no problem. The next what I
want is- when a record on the grid is clicked, the relevant record will be
displayed in a text box in the from. This only works inone form. It does
not work in any other form. Here is the code I'm using-
Private Sub dtGrid_Click(sender As Object, e As EventArgs) Handles
dtGrid.Click Dim i As Integer
i = dtGrid.CurrentRow.Index
Try
frmServicing.txtRego.Text = dtGrid.Item(0, i).Value
frmVehicle.txtcCode.Text = dtGrid.Item(0, i).Value
frmVehicle.txtAllocation.Text = dtGrid.Item(1, i).Value
Catch ex As Exception
End Try
It only works for frmVehicle. I tried all possible ways but no luck. Any
idea?
End Sub

Java Scanner do-while Lack of Recognition Issue

Java Scanner do-while Lack of Recognition Issue

I have created a do-loop to continue iterating until the user enters a
word starting with Y or N, originally using a primitive check on a char
and now using the methods outlined below to check strings for equality.
With both comparison media, I found that even with 'y' or 'n' entered, the
loop would not exit. I cannot explain why, and hope that you can:
The following is the code:
do{
System.out.println("Please Enter a Valid y/n Reply:");
eraseOr_no = histScanner.next();
if(histScanner.hasNext()){
(eraseOr_no.replaceAll("\\s+", "")).toLowerCase();
character = Character.toString(eraseOr_no.charAt(0));
//DEBUGGING
System.out.println("CHECKPOINT 5" + "----" + character);
//DEBUGGING
}
}while(!(character.equals("n")) || !(character.equals("y")));
As is clear I have used a simply system to inform me of the value of the
String character, and as you may be able to see it is successfully
displaying the 'y' or 'n' meaning that my first-letter-retrieval code is
functioning, though the entire do structure is not.
Continue
Answer:
CHECKPOINT 4.0.
PLACEHOLDER
Please Enter a Valid y/n Reply:
y
y
CHECKPOINT 5----y
Please Enter a Valid y/n Reply:
y
CHECKPOINT 5----y
Please Enter a Valid y/n Reply:
n
CHECKPOINT 5----y
Please Enter a Valid y/n Reply:
y
CHECKPOINT 5----n
Please Enter a Valid y/n Reply:
Should I try to remove all whitespace? Am I missing something more
fundamental?