Monday, 30 September 2013

Extracting a zip file in my machne givs me CRC error?

Extracting a zip file in my machne givs me CRC error?

I have a large zip that contain hundreds of file. I've unzip'ed it in more
than one machine and didn't have any problem before. However, for this
particular machine (Ubuntu Server 12.04) I keep getting CRC error for some
of the files inside my zip. I've unzip'ed the same file it on anther
machine just to and its fine.
Any clue?

How to stop reusing uitableviewCell?

How to stop reusing uitableviewCell?

Hi in my app i have to load images to UITableViewCell .which are coming
from the server.so the problem is when ever i scroll the tableview images
are loading every time and its loading lazy so i tried to stop reusing
cells but its not working ,How to stop reusing the cells in UITableView.
my code is
-(UITableViewCell*)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=@"Cell";
RestaurantCustomCell *cell =(RestaurantCustomCell*) [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *topLevelObjects ;
topLevelObjects= [[NSArray alloc]init];
if(cell==nil)
{
topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:@"RestaurantCustomCell" owner:self options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[UITableViewCell class]])
{
cell = (RestaurantCustomCell *) currentObject;
break;
}
}
}
NSDictionary *dict=[restauarantsArr objectAtIndex:indexPath.row];
NSString *imgStr=[dict valueForKey:@"Img"];
[self processImageDataWithURLString:imgStr andBlock:^(NSData *imageData) {
if (self.view.window)
{
UIImage *img = [UIImage imageWithData:imageData];
if(img!=nil)
{
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
[img drawInRect:CGRectMake(0,0,100,100)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
cell.restaurantImg.image=newImage;
UIGraphicsEndImageContext();
}
}
}];
cell.nameLbl.text=[dict valueForKey:@"Restaurants"];
cell.typeLbl.text=[dict valueForKey:@"Rest_Cuisine"];
cell.timingsLbl.text=[dict valueForKey:@"Rest_Timings"];
cell.categoryLbl.text=[dict valueForKey:@"Rest_Category"];
cell.addressLbl.text=[dict valueForKey:@"Address"];
return cell;
}

JavaScript onkeypress delayed trigger

JavaScript onkeypress delayed trigger

I have an html input for an optional phone number, along with 2 radio
inputs (Leave Message, Dont Leave Message):
<input type="text" class="input-medium phoneNum2" name="secondaryPhone"
id="secondaryPhone" onkeypress="toggleRadio(this)"
onblur="toggleRadio(this)" placeholder="703-555-1010"
value="<cfoutput>#session.secondaryPhone#</cfoutput>" />
Notice I have two events running (deleting one of them yields the same
issue, having both helps out, but I'd rather have only 1 event unless
necessary).
The scenario here is: The second somebody starts typing into the input, it
checks to see if one of the radio buttons is already checked. If not,
default select yes. If for some reason they delete the phone number as
they do not want to give it, both radio buttons should be de-selected
(only the onblur works there). And if the "Don't Leave Message" is
selected BEFORE the user starts typing, it should not default to yes.
Here is the JavaScript:
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
if (x.value.length > 0 && !z.checked) y.checked = true;
}
Now for the issue: The default option yes is only triggered when I type in
2 characters, instead of the desired 1 (almost like a delay in the code?).
If I have "No" Selected before I start typing, it defaults to yes once I
type in the 2 characters. Likewise for reverse, nothing is "de-selected"
when there are 0 characters during the onkeypress event, only when the
input loses focus during the onblur event.
Am I using the wrong events? Is there a logic flaw? There are no error
messages, and no, I cannot use jQuery here, so please don't give me jQuery
answers or the usual "Why no jQuery?" (I love jQuery I simply have reasons
I cannot use it).
Edit: I also tried ordering the JavaScript like this, to no avail.
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length > 0 && !z.checked) y.checked = true;
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
}
Basically I want to know why the code is acting like there is a delay, and
is there a way to fix it?

Cannot git clone android source code from remote server

Cannot git clone android source code from remote server

Firstly I
$ git clone https://android.googlesource.com/platform/frameworks/base
Cloning into 'base'...
remote: Sending approximately 1.04 GiB ...
remote: Counting objects: 43200, done
remote: Finding sources: 100% (3713/3713)
remote: Getting sizes: 100% (1738/1738)
remote: Compressing objects: 99% (27152/27153)
Receiving objects: 4% (36212/787666), 16.81 MiB | 183 KiB/s
For a while, the git hung and didn't go ahead, So I break git and
$ git clone http://android.googlesource.com/platform/frameworks/base
Cloning into 'base'...
remote: Sending approximately 1.04 GiB ...
remote: Counting objects: 43200, done
remote: Finding sources: 100% (3713/3713)
remote: Getting sizes: 100% (1738/1738)
remote: Compressing objects: 99% (27152/27153)
error: RPC failed; result=56, HTTP code = 20075 MiB | 186 KiB/s
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
Now it failed as above, I tried several times and every time got same
error as above.
How to resolve or workaround?

Sunday, 29 September 2013

Apperently Simple Puzzle

Apperently Simple Puzzle

So a picture appeared on FB asking for the answer to the picture below, to
which many people responded "14".

Everywhere I looked, people answered 14. However, I stood out because I
was the only one who said that the answer is 11.25.
The problem can be represented algebraically like this:
4x = 5
x = 1.25
9x = ?
9(1.25) = 11.25
So my question is..how the heck did people get 14? Am I using the wrong
approach?

"Yum Update" reinstalling removed packages

"Yum Update" reinstalling removed packages

On my Fedora 19 system, yum update attempts to reinstall a large number
packages I have previously removed. This should not happen, as the
packages listed are not installed and should not be suggested by yum. How
can I make yum work in the expected manner - with updates suggesting only
upgrades to preinstalled packages.
Background: I have been trying out new DEs - installing and removing them
as I go. Currently, I'm in a DE-less state, booting directly into a tty
terminal. My system has no (or a few hidden) xfce or cinnamon packages to
"upgrade", yet the package manager is suggesting 300 packages to install,
totaling 600M of new install.

Wrong resource folder being chosen by Android system

Wrong resource folder being chosen by Android system

I've been having problems with my app on a 7 inch device. For debugging
purposes I've added a toast message that displays after the app loads, to
tell me which resource folder the app is using, ie. which qualifiers. I
have strings.xml files in each of the following resource folders:
values
values-normal
values-large
values-xlarge
values-sw600dp
values-sw720dp
The content of the string used by the toast message is based on the folder
in which the string is located. I also have six layout folders with the
same qualifiers as above, and I have valid layout xml files in all six of
the layout folders. My app works perfectly on 'normal' screens and 10 inch
tablet screens.
The troublesome 7 inch device (my mate's) is a cheap 'Audiosonic' running
Android 4.1.1. Apparently the resolution is 800x480, and the physical
smallest width of the screen is 86mm, or 3.4 inches. This means 142dpi.
Given the equation dp = (pixels x 160) / dpi The smallest width should be
541dp.
Now here comes the crazy part, and my question...why on earth are the
sw720dp resources being used by my app on this 7 inch device?!

How to get the value of radio button in Zend Form

How to get the value of radio button in Zend Form

This is my form, I have a radio button from 1 to 5 (very bad to very good)
parent::__construct($name);
$this->setAttribute('method', 'post');
$this->add(array(
'type' => 'Zend\Form\Element\Radio',
'name' => 'rate_box',
'options' => array(
'label' => 'Please choose your rate',
'value_options' => array(
'1' => ' Very Bad',
'2' => ' Bad',
'3' => ' Fine',
'4' => ' Good',
'5' => ' Very Good',
),
),
'attributes' => array(
'value' => '1' //set checked to '1'
)
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'id' => 'submit',
'class' => 'btn btn-primary',
),
));
This is the related part of my controller
$form = new VoteForm();
$request = $this->getRequest();
if ($request->isPost())
{
$form->setData($request->getPost());
if ($form->isValid())
{
$formdata = $form->getData();
$vote = new Vote();
$data = $vote->getArrayCopy();
$data['user_id'] = $user_id;
$data['voted_user_id'] = $voted_user_id;
$data['ratescore'] = $formdata['rate_box']; //Here I take
the value of radion button
$vote->populate($data);
try
{
$this->getEntityManager()->persist($vote);
$this->getEntityManager()->flush();
return
$this->redirect()->toRoute('home',array('user_id' =>
$user_id,
'action' =>
'home',
));
}
catch(DBALException $e){
}
}
}
Why I can't retrieve the value of "rate_box" and save to my
$data['ratescore']? Thank you!

Saturday, 28 September 2013

extended initializer lists being seen as functions

extended initializer lists being seen as functions

I'm trying to compile an opensource project but I'm getting this problem
from g++
error: function definition does not declare parameters
the code is something like this
#include <iostream>
namespace hi {
class hello {
public:
bool first { true };
};
}
int main(int argc, char *argv[])
{
hi::hello h
std::cout << "output: " << h.first << std::endl;
return 0;
}
which produces the same compilation problem as the code of the opensource
project when compiled with
g++ -O2 bools.cpp -o bools -std=c++0x
however if I try to compile this code with the same options it compiles
and runs as it should
#include <iostream>
int main(int argc, char *argv[])
{
bool value { true };
std::cout << "output: " << value << std::endl;
return 0;
}
I'm using g++ 4.6.3 on Ubuntu 64bit.
thanks for your time.

"An unknown error occurred" when logging in in Visual Studio 2013 SPA template on IIS8 express

"An unknown error occurred" when logging in in Visual Studio 2013 SPA
template on IIS8 express

I have used the SPA template in VS2013 and try to host it in IIS8 on Win8.
When I try to Log In in the Todo list I get a An unknown error occurred.
When I run the solution in VS2013 (preview v.12.0.20623.01 update) through
the development webserver it runs alright.
But I want to use the real IIS and hence created an application in
IIS8express for the same folder.
When I try to register or log in to the todo list I get the error above.
Running aspnet development on the IIS is no problem, I have done it for
years.
Looking through the code it looks like it has something to do with the
Identity providers, like the code cannot enumerate them when running in
IIS. I just can't get my head around it.

show value percentages in excel pivot table

show value percentages in excel pivot table

I have this data table and created the pivot table underneath it. How can
I get the pivot table to show data like table no.3 , or even change values
to percentages even better

JNDI requires JDK?

JNDI requires JDK?

I try to configure Oracle datesource for Tomcat6 from SUSE Linux
Enterprise Server. I add datasource to context.xml file:
<Resource
name="jdbc/UCPPool"
auth="Container"
factory="oracle.ucp.jdbc.PoolDataSourceImpl"
type="oracle.ucp.jdbc.PoolDataSource"
description="Pas testing UCP Pool in Tomcat"
connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
minPoolSize="2"
maxPoolSize="5"
inactiveConnectionTimeout="20"
user="scott"
password="tiger"
url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=beast.au.oracle.com)(PORT=1523))(CONNECT_DATA=
(SERVICE_NAME=linux11gr2)))"
connectionPoolName="UCPPool"
validateConnectionOnBorrow="true"
sqlForValidateConnection="select 1 from DUAL" />
In my application in persistence.xml add non-jta-data-source property. But
each time when I want to start application, tomcat throw this exception:
Caused by: org.hibernate.service.jndi.JndiException: Unable to lookup
JNDI name [java:comp/env/jdbc/nameDB]
at
org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:68)
at
org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
at
org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
at
org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at
org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:78)
at
org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2283)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2279)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1748)
at
org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:920)
... 28 more
Caused by: javax.naming.NamingException: This context must be accessed
throught a java: URL
org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:65)
I tried the same configuration on OpenSuse and there it works. The only
difference I found is that SLSE has installed JAVA SE form IBM and
openSUSE use OpenJDK java as a defualt.
So JNDI require JDK or it is some bug in IBM java implmenetation?

Friday, 27 September 2013

Android - Save to a text file

Android - Save to a text file

I am trying to write text to a file but i cant seem to get it to work.
public static void saveState(){
String data = age + "," ;
FileOutputStream fos;
Context con = getApplicationContext();
try {
fos = con.openFileOutput("state", 0);
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(fos);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have looked around and it seems i cant call openFileOutput() with out
the context but have no idea "Context con = getApplicationContext()" will
not work. it just tells me that getapplicationcontext is undefined for the
type. Can anyone help me out here?

How can i hide the form1 ? I want that the icon of the form only will be show in the taskbar in the bottom

How can i hide the form1 ? I want that the icon of the form only will be
show in the taskbar in the bottom

public Form1()
{
InitializeComponent();
this.Visible = false;
}
Didn't work so I tried this.Hide();, also didn't work. What am I missing ?

Matlab Plot 3d axis on a specifi point

Matlab Plot 3d axis on a specifi point

I want to plot the axis x,y,z as vectors from a specific point.x will
be(+-1,0,0) (if the point was the origin)y=(0,+-1,0) and z(0,0,+-1).How
can i plot them with different colors in an figure tha already contains
some informations
To be specific i have an animated 3D skeleton and i want to have the axes
showed in the root of the skeleton.
furthermore if anyone knows how to plot a plane in the same animated 3D
skeleton!i want the plane to be as a disc
Thanks in advance for any response

UIImageView is not updating

UIImageView is not updating

Hi iam using following code for loading image to uiimageview its working
when i loading that UIviewcontroller but if i open any other
uiviewcontroller from the existing one and came back to the old
uiviewcontroller and if i click a thumnail image its not not updating
UIimageview uiviewcontroller.
img contains image path (inside device) in viewdidload
[self setBookimage:img];
in setBookimage()
- (void)setBookImage:(UIImage *)bookImage{
book_cover_image.image=nil;
book_cover_image.image = bookImage;
CATransition *transition = [CATransition animation];
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction
functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[book_cover_image.layer addAnimation:transition forKey:nil];
}

Amazon s3 Metadata Tags

Amazon s3 Metadata Tags

I am trying to get my s3 bucket to serve gzipped assets as opposed to the
minified versions.
I have precompiled my assets, a gzip version has been created, all i need
to do know is serve it.
After reading some guides and blogs it seems i need to add
Content-Type text/html
Content-Encoding gzip
When i am in my s3 bucket management screen i should be able to find
metadata within properties, but it is not there...
Can i set this configuration in the CORS properties?
Does anyone know why this could be?

How to rename order status in frontend in magento?

How to rename order status in frontend in magento?

I need to rename order status in magento only for customers.
For exmaple:
Customer`s order has a status "fraud". In frontend(for cusntomer) it
should be displayed as "Open", but in backand it should stay "Suspected
fraud"
I use Magento 1.7. Thanks

Thursday, 26 September 2013

Pad - How to detect that multitasking gestures are disable in xcode 5?

Pad - How to detect that multitasking gestures are disable in xcode 5?

1.Disable Multitasking Gesture in ios 7 in my app not from setting screen
2.Is there any way so that Ican disable this feature for my app.?

Wednesday, 25 September 2013

get values from href link using jquery

get values from href link using jquery

I have to split values from href link.
my href link as follows
var val =location.href // outputs
http://localhost:8080/index.html?username=test@gmail.com&joid=68
i want to get username value and joid value separately.
I tried following but not working
var emailrogh= val.split("&");
email=emailrogh[0];
var idrough=emailrogh[1].split("=");
var id=idrough[1];
how can i extract test@gmail.com and 68

Thursday, 19 September 2013

xwindows working but not unity desktop

xwindows working but not unity desktop

I'm running Ubuntu 13.04 64 bit w/ unity desktop
What I'm experiencing: When I turn on my computer, the Ubuntu loading
screen appears but disappears in wake of a shell which I can log into.
Once logged in, I can start Unity via sudo start lightdm and subsequently
login via unity gui.
However, the desktop software doesnt seem to be running. There is now
tool-bar/menu-thing. I cannot use Alt+Tab to cycle between open windows,
and I cannot restore windows which I minimize.
In every respect, I would have the same experience issuing sudo startx
from an xterminal. I have reinstalled unity to no avail. installation
seems to go just fine.
Any ideas on where I might go about addressing this problem? Thanks

Duplicates in JSP's include directive

Duplicates in JSP's include directive

This code is not real, but is simpler and show the problem
Suppose that I have First File named Base.jsp
<%!
class Base{
public String Parm0 = "";
public String Parm1 = "";
}
javax.servlet.jsp.JspWriter Out;
void PrintMessage(String Msg){
try {
Out.print("<P style=\"color:rgb(255,0,0)\">"+Msg+"</P>");
}
catch (Exception e) {}
}
%>
Now I have a Second File that use the base file: Fil0.jsp
<%@ include file="Base.jsp" %>
<%!
class File0 {
public Base MyBase;
File0 () {
MyBase = new Base();
PrintMessage("Based Used!!");
}
%>
Now I have a Third File that use the base file: Fil1.jsp
<%@ include file="Base.jsp" %>
<%@ include file="Fil0.jsp" %>
<%!
class Fil1 {
public Base MyBase;
public Fil0 MyFil0;
File0 () {
MyBase = new Base();
MyFil0 = new Fil0();
PrintMessage("Based and Fil0 Created!!");
}
%>
As you can see... this code will produce messages like:
Duplicate field Fil1_jsp.Out
Duplicate method PrintMessage(String) in type Fil1_jsp
How solve this error Before I need to include Base in two files: File0 and
File1. And File1 have Base and File0...
The compiler find two declarations...

mysql access denied for only one IP on a multi-NIC system

mysql access denied for only one IP on a multi-NIC system

I'm having this strange problem. We have a ubuntu 12.04 server with 2
NICs. One public with 172.30.1.1, the other is private with 192.168.1.1.
We have a MySQL server running. In /etc/mysql/my.conf, we have
bind-address = 0.0.0.0.
A table is created and privilege granted.
CREATE DATABASE db;
GRANT ALL ON db.* TO 'user0'@'%' IDENTIFIED BY 'password';
GRANT ALL ON db.* TO 'user0'@'localhost' IDENTIFIED BY 'password';
The hostname is 'myhost', and it's in /etc/hostname. /etc/hosts has
127.0.0.1 localhost
127.0.1.1 myhost
192.168.1.1 myhost
When I connect with 172.30.1.1, it's fine. But when I use 192.168.1.1, the
access is denied. mysql -h 192.168.1.1 -uuser0 -ppassword ERROR 1045
(28000): Access denied for user 'user0'@'myhost' (using password: YES) I
have the user table like this.
mysql> SELECT user, host FROM mysql.user;
+------------------+-----------+
| user | host |
+------------------+-----------+
| user0 | % |
| root | 127.0.0.1 |
| root | ::1 |
| | localhost |
| debian-sys-maint | localhost |
| user0 | localhost |
| root | localhost |
| | myhost |
| root | myhost |
+------------------+-----------+
I observed the difference is that I have 192.168.1.1 myhost line in
/etc/hosts file; not 172.30.1.1. If I remove that line or change the
hostname after the IP, it will work fine. If I add 172.30.1.1 myhost to
/etc/hosts, then I can't connect with 172 IP. How to explain this?

xampp - SSL works on https://localhost, but not on https://127.0.0.1

xampp - SSL works on https://localhost, but not on https://127.0.0.1

I have changed the configuration on my XAMPP for SSL use, following this
tutorial:
https://avosapi.delicious.com/api/v1/posts/redirect?url=http%3A%2F%2Frobsnotebook.com%2Fxampp-ssl-encrypt-passwords
It works partially. I can access https://localhost/phpmyadmin and others
URLs that use the term localhost, but on https://127.0.0.1/magento it does
not recognize the certificate (it shows that message on the browser about
insecure certificates). How can I solve these differences between
localhost and 127.0.0.1?
Tks in advance.

How to combine node.js and Java buildpack in Heroku

How to combine node.js and Java buildpack in Heroku

We have an application that is a HTML5/JavaScript frontend that
communicates with a pure Java backend via REST. The JavaScript frontend
relies on Backbone.js rather than Node.js. For now, this is packaged as
one application, and deployed in Heroku using the standard Java buildpack.
But what we want to do now is to add Grunt to the build process, in order
to concatenate, minify, etc, the JavaScript. It works fine locally, but
how would we make it work with Heroku? We are not interested in committing
the Grunted files. We want it to be a part of the buildpack. Any
suggestions?

error in php Catchable fatal error: Object of class mysqli_result could not be converted to string in

error in php Catchable fatal error: Object of class mysqli_result could
not be converted to string in

this is query
SELECT room_id,stages FROM booked_room
this is error
Catchable fatal error: Object of class mysqli_result could not be
converted to string in
$query ="SELECT room_id,stages FROM booked_room";
$result2 =$mysqli->query($query);
echo $mysqli->error;
if($result2->num_rows > 0){echo"some thing";}

p:selectOneMenu not calling setter on form submit

p:selectOneMenu not calling setter on form submit

I'm kinda new to JSF and primefaces and I'm running into a very annoying
problem.
I'm making a very basic application to learn a bit more about primefaces.
I have a simple form that has several textual input fields, two
datepickers and one dropdown (selectOneMenu).
Everything works all values are put in the backing bean when I submit the
form, except for the value from the dropdown menu. The setter for that
item is never called. And the application does not call the public void
saveNewActivity(ActionEvent evt) method on the controller as defined on
the commandbutton. When I however remove or comment out the dropdown menu
in html it does call that method (but the field for the dropdown menu is
obviously null).
I've been trying things for nearly two days, and still can't get this to
work properly.
I have the following code (snippets):
My html/jsf code
<div id="newActivitycontent">
<h:form id="newActivityForm">
<h:messages id="messages"/>
<table>
<tr>
<td>Gebruiker:</td>
<td><p:selectOneMenu
value="#{plannedActivityController.newActivity.organiser}}"
converter="#{userConverter}">
<f:selectItem itemLabel="Kies een gebruiker"
itemValue=""/>
<f:selectItems
value="#{plannedActivityController.users}"
var="user"
itemLabel="#{user.firstname}
#{user.lastname}"
itemValue="#{user}"/>
</p:selectOneMenu></td>
</tr>
<tr>
<td>Titel:</td>
<td><p:inputText
value="#{plannedActivityController.newActivity.name}"/></td>
</tr>
<tr>
<td>Beschrijving:</td>
<td><p:inputText
value="#{plannedActivityController.newActivity.desctription}"/></td>
</tr>
<tr>
<td>Startdatum:</td>
<td><p:calendar
value="#{plannedActivityController.newActivity.startDateDate}"/></td>
</tr>
<tr>
<td>Einddatum:</td>
<td><p:calendar
value="#{plannedActivityController.newActivity.endDateDate}"/></td>
</tr>
</table>
<p:commandButton id="btnSaveNewActivity" value="Opslaan"
actionListener="#{plannedActivityController.saveNewActivity}"
update=":overviewForm:activityTable
messages"/>
<p:commandButton id="btnCancelNewActivity" value="Annuleren"
actionListener="#{plannedActivityController.cancelNewActivity}"
onclick="hideAddNewUI()"
update=":overviewForm:activityTable"
type="reset" immediate="true"/>
</h:form>
</div>
The controller that is used by that code:
@Named
@SessionScoped
public class PlannedActivityController implements Serializable {
@Inject
private ApplicationModel appModel;
@Inject
private SessionModel sessionModel;
@Inject
private ActivityMapper activityMapper;
@Inject
private UserMapper userMapper;
private ActivityBean newActivity;
private ActivityBean selectedActivity;
private List<ActivityBean> activities;
private List<UserBean> users;
public PlannedActivityController() {
}
@PostConstruct
public void onCreated() {
convertActivities();
onNewActivity();
users = userMapper.mapToValueObjects(appModel.getUsers());
}
public void convertActivities() {
List<PlannedActivity> originalActivities = appModel.getActivities();
this.activities =
activityMapper.mapToValueObjects(originalActivities);
}
public void onRowEditComplete(RowEditEvent event) {
System.out.println("row edited : " + event.getObject());
//TODO: save changes back to db!
}
public void onRowSelectionMade(SelectEvent event) {
System.out.println("row selected : " + event.getObject());
selectedActivity = (ActivityBean)event.getObject();
}
//Activity crud methods
public void onNewActivity() {
newActivity = new ActivityBean();
newActivity.setId(new Date().getTime());
}
public void saveNewActivity(ActionEvent evt) {
PlannedActivity newAct = activityMapper.mapToEntity(newActivity);
if(newAct != null) {
appModel.getActivities().add(newAct);
}
convertActivities();
}
public void cancelNewActivity() {
//TODO: cleanup.
}
public void deleteSelectedActivity() {
if(selectedActivity != null) {
activities.remove(selectedActivity);
appModel.setActivities(activityMapper.mapToEntities(activities));
convertActivities();
} else {
//TODO: show error or information dialog, that delete cannot
be done when nothing has been selected!
}
}
//Getters & Setters
public ApplicationModel getAppModel() {
return appModel;
}
public void setAppModel(ApplicationModel appModel) {
this.appModel = appModel;
}
public SessionModel getSessionModel() {
return sessionModel;
}
public void setSessionModel(SessionModel sessionModel) {
this.sessionModel = sessionModel;
}
public ActivityMapper getActivityMapper() {
return activityMapper;
}
public void setActivityMapper(ActivityMapper activityMapper) {
this.activityMapper = activityMapper;
}
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
public ActivityBean getNewActivity() {
return newActivity;
}
public void setNewActivity(ActivityBean newActivity) {
this.newActivity = newActivity;
}
public ActivityBean getSelectedActivity() {
return selectedActivity;
}
public void setSelectedActivity(ActivityBean selectedActivity) {
this.selectedActivity = selectedActivity;
}
public List<ActivityBean> getActivities() {
return activities;
}
public void setActivities(List<ActivityBean> activities) {
this.activities = activities;
}
public List<UserBean> getUsers() {
return users;
}
public void setUsers(List<UserBean> users) {
this.users = users;
}
}
My activitybean:
public class ActivityBean implements Serializable {
private Long id = 0L;
private String name;
private String desctription;
private UserBean organiser;
private Calendar startDate;
private Calendar endDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesctription() {
return desctription;
}
public void setDesctription(String desctription) {
this.desctription = desctription;
}
public UserBean getOrganiser() {
return organiser;
}
public void setOrganiser(UserBean organiser) {
this.organiser = organiser;
}
public Calendar getStartDate() {
return startDate;
}
public void setStartDate(Calendar startDate) {
this.startDate = startDate;
}
public Date getStartDateDate() {
if(this.startDate == null) {
return null;
}
return this.endDate.getTime();
}
public void setStartDateDate(Date startDate) {
if(this.startDate == null) {
this.startDate = new GregorianCalendar();
}
this.startDate.setTime(startDate);
}
public String getStartDateString() {
if(this.startDate == null) {
return null;
}
return startDate.get(Calendar.DAY_OF_MONTH) + "/" +
startDate.get(Calendar.MONTH) + "/" + startDate.get(Calendar.YEAR)
+ "";
}
public Calendar getEndDate() {
return endDate;
}
public void setEndDate(Calendar endDate) {
this.endDate = endDate;
}
public Date getEndDateDate() {
if(this.endDate == null) {
return null;
}
return endDate.getTime();
}
public void setEndDateDate(Date endDate) {
if(this.endDate == null) {
this.endDate = new GregorianCalendar();
}
this.endDate.setTime(endDate);
}
public String getEndDateString() {
if(this.endDate == null) {
return null;
}
return endDate.get(Calendar.DAY_OF_MONTH) + "/" +
endDate.get(Calendar.MONTH) + "/" + endDate.get(Calendar.YEAR) +
"";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActivityBean that = (ActivityBean) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
My userbean:
public class UserBean {
private Long id;
private String username;
private String firstname;
private String lastname;
private String email;
private String phone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserBean userBean = (UserBean) o;
if (id != null ? !id.equals(userBean.id) : userBean.id != null)
return false;
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
And the converter used by the selectOneMenu:
@Named
public class userConverter implements Converter{
@Inject
private PlannedActivityController activityController;
@Override
public Object getAsObject(FacesContext facesContext, UIComponent
uiComponent, String s) {
for (UserBean user : activityController.getUsers()) {
if(user.getId().toString().equals(s)) {
return user;
}
}
return null;
}
@Override
public String getAsString(FacesContext facesContext, UIComponent
uiComponent, Object o) {
if(o instanceof UserBean) {
UserBean user = (UserBean)o;
return user.getId().toString();
}
return "";
}
}

In which manner array of characters is allocated memory locally?

In which manner array of characters is allocated memory locally?

This is the code I've written,
char *foo();
void main()
{
char *str=foo();
strcpy(str,"Holy sweet moses! I blew my stack!!");
printf("%s",str);
}
char * foo()
{
char str[256];
return str;
}
When I use char array in function foo(), the strcpy in main() function
doesn't copy the string into str. But, when I use int array in function
foo(), main() strcpy copies successfully.
i.e.
int str[256]; //in funtion foo
output
Holy sweet moses! I blew my stack!!
if
char str[256]; //in foo()
output : nothing!

Wednesday, 18 September 2013

UIView animateWithDuration in Delphi FireMonkey

UIView animateWithDuration in Delphi FireMonkey

What is the best way to perform the same thing as UIView
animateWithDuration using Delphi and FireMonkey? I would like it to work
on iOS and Android (using Delphi XE5)

Elixir Dynamo start multiple apps

Elixir Dynamo start multiple apps

What is the best way to start multiple apps using Dynamo. When we create
the project dynamo generates a default app. I would like to add one more
app in lib and start it as soon as i start the server.
However, i tried putting it in lib folde, apps folder also modified
mix.exs but mix compile is not generating the app file.

I need to learn basic Unity with C# fast, I have a assignment due next week

I need to learn basic Unity with C# fast, I have a assignment due next week

I know how to program OOP (beginner/moderate). I have to make a simple
game in Unity based off any old Atari game system for class. I usually go
to new Boston to learn stuff fast but he does not cover anything about
unity. Anyone have any good links for basic tutorials in c# or javascript?

Activate subform for data entry using a button on main form

Activate subform for data entry using a button on main form

How can I reference a button click event on the main form to a subform,
similar to:
DoCmd.GoToRecord , , acNewRec
I want to use the subform both for viewing and entering new records but my
button is on the main form.

Pseudo-polynomial time dynamic programming solution from TWO sets with TWO limitations

Pseudo-polynomial time dynamic programming solution from TWO sets with TWO
limitations

I´ve read at wiki
http://en.wikipedia.org/wiki/Subset_sum_problem#Pseudo-polynomial_time_dynamic_programming_solution
about the sumsubsetproblem and wonder if i can adapt it to the following
problem:
I need all possible subsets ss1, ss2 restricted by n1, n2 being the number
of elements out of 2 sets s1,s2
I will use the elements of S1 as positive elements and the elements of s2
as negative elements to answer the question if the subsets of size n1 and
n2 have sum equal 0
My special problem here is that the sets can contain 0 itselfs and i
thought i solve this by setting these elements to 1 or -1 repectivly ( 1
is not a member of my input, which will be (0,10,50,100,200,500) ) and the
next problem is that this algorithm gives me yes or no only, but i know
this answer already ( its a precondition ) what i need is the results.
Is this still fast enough ? i ´ve read here about an perl implementation
where the OP posted a list with runtimes an 30 elements had a computation
time of 30-40 seconds wich is far too slow for my needs and i need to
implement in java, wich is, as far as i know even slower then perl
regards
dirk

Unable to replace HTML file in Web Application hosted by IIS 7.5 on Win Server 2008 R2 due to locking IIS Worker Process

Unable to replace HTML file in Web Application hosted by IIS 7.5 on Win
Server 2008 R2 due to locking IIS Worker Process

When attempting to delete/replace an entire .NET Web Application hosted by
IIS 7.5 on Windows Server 2008 R2, targeting .NET 4.5, programmatic
deletion of the landing page (an .html page) via VB.NET code results in
"System.IO.IOException: The process cannot access the file
'[filename].html'. because it is being used by another process"
Attempting to delete the HTML file using Windows Explorer results in
"The action can't be completed because file is open in IIS Worker Process."
This happens immediately after the landing page is served up by IIS. The
lock lasts for a while, approximately an hour or two. Recycling the App
Pool that hosts the application removes the lock immediately making
deletion possible. I can see the IIS Worker Process disappear via Process
Explorer after the recycle.
This is happening on multiple, redundant production servers but does not
happen on a comparable test server (very similar set up).
I've checked
Server setup and configuration (software installed, features installed,
.NET framework asp.config file, etc)
web.config file setups
IIS Application and App Pool configurations.
toggled application Output Caching Settings
There are a few similar questions to this posted but they have not helped
me resolve the issue.
Note that replacing the web application files is required as a business
need to host payment pages on behalf of customers. Because there are
multiple customers' web applications hosted on the same IIS instance,
restarting the instance is not an option. I'm not even comfortable
recycling the app pool in order to be able to publish one customer's
changes.
Thank you for taking the time to consider this post.

How to Validate users by SqlDataSource Control?

How to Validate users by SqlDataSource Control?

I make a Login page to validate user. I have a sql table like following:
table: tblUsers
userID (int is identity)
username (nvarchr (50))
password (nvarchr (50))
Login.ASPX
Username<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox><br />
Password <asp:TextBox ID="txtPassword"
runat="server"></asp:TextBox><br />
<asp:Button ID="cmdLogin" runat="server" Text="Login"
onclick="cmdLogin_Click" /><br />
<asp:Label ID="lblError" runat="server"
EnableViewState="False"></asp:Label><br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConStr %>"
SelectCommand="SELECT * FROM [tblUser] WHERE (([username] =
@username) AND ([password] = @password))">
<SelectParameters>
<asp:ControlParameter ControlID="txtPassword" Name="username"
PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="txtPassword" Name="password"
PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Validate users is in SelectCommand of SqlDataSource.
SELECT * FROM [tblUser] WHERE (([username] = @username) AND ([password] =
@password))
how to validate user by SqlDataSource? I want code for Login button.

how to develop Admin Panel in ASP.Net

how to develop Admin Panel in ASP.Net

I am developing an asp.net website in which i need to create admin panel.
So please tell me how to decide role and membership and also way of
development.
thanks

How do I expect and verify the same method in JMockit

How do I expect and verify the same method in JMockit

Having the following class:
class ToTest{
@Autowired
private Service service;
public String make(){
//do some calcs
obj.setParam(param);
String inverted = service.execute(obj);
return "<" + inverted.toString() + ">";
}
}
I'd like to add a test that asserts me that service.execute is called with
an object with the param X.
I'd do that with a verification. I want to mock this call and make it
return something testable. I do that with an expectations.
@Tested
ToTest toTest;
@Injected
Service service;
new Expectations(){
{
service.exceute((CertainObject)any)
result = "b";
}
};
toTest.make();
new Verifications(){
{
CertainObject obj;
service.exceute(obj = withCapture())
assertEquals("a",obj.getParam());
}
};
I get a null pointer on obj.getParam(). Apparently the verification does
not work. If I remove the expectation it works but then I get a null
pointer in inverted.toString().
How would you guys make this work?

Tuesday, 17 September 2013

Problems occurred when invoking code from plug-in: "org.eclipse.core.resources" when using eclipse

Problems occurred when invoking code from plug-in:
"org.eclipse.core.resources" when using eclipse

I am developing a J2EE application using Eclipse...and in that
application..i used a jquery Plugin "DataTable 1.9.4" to create a table
grid with all its functionality.
But in javascript file of DataTable plugin..an error occured like below :
!MESSAGE Problems occurred when invoking code from plug-in:
"org.eclipse.core.resources".
!STACK 0
java.lang.ClassCastException:
org.eclipse.wst.jsdt.internal.compiler.lookup.MethodBinding cannot be cast
to org.eclipse.wst.jsdt.internal.compiler.lookup.LocalVariableBinding
at
org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference.localVariableBinding(SingleNameReference.java:226)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Expression.checkNPE(Expression.java:320)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:67)
at
org.eclipse.wst.jsdt.internal.compiler.ast.SingleNameReference.analyseAssignment(SingleNameReference.java:84)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Assignment.analyseCode(Assignment.java:63)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FieldReference.analyseAssignment(FieldReference.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Assignment.analyseCode(Assignment.java:63)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.LocalDeclaration.analyseCode(LocalDeclaration.java:73)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:86)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MethodDeclaration.analyseCode(MethodDeclaration.java:91)
at
org.eclipse.wst.jsdt.internal.compiler.ast.AbstractMethodDeclaration.analyseCode(AbstractMethodDeclaration.java:110)
at
org.eclipse.wst.jsdt.internal.compiler.ast.FunctionExpression.analyseCode(FunctionExpression.java:74)
at
org.eclipse.wst.jsdt.internal.compiler.ast.Expression.analyseCode(Expression.java:184)
at
org.eclipse.wst.jsdt.internal.compiler.ast.MessageSend.analyseCode(MessageSend.java:65)
at
org.eclipse.wst.jsdt.internal.compiler.ast.CompilationUnitDeclaration.analyseCode(CompilationUnitDeclaration.java:155)
at org.eclipse.wst.jsdt.internal.compiler.Compiler.process(Compiler.java:609)
at org.eclipse.wst.jsdt.internal.compiler.Compiler.compile(Compiler.java:355)
at
org.eclipse.wst.jsdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:288)
at
org.eclipse.wst.jsdt.internal.core.builder.BatchImageBuilder.compile(BatchImageBuilder.java:86)
at
org.eclipse.wst.jsdt.internal.core.builder.AbstractImageBuilder.compile(AbstractImageBuilder.java:227)
at
org.eclipse.wst.jsdt.internal.core.builder.BatchImageBuilder.build(BatchImageBuilder.java:58)
at
org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder.buildAll(JavaBuilder.java:291)
at
org.eclipse.wst.jsdt.internal.core.builder.JavaBuilder.build(JavaBuilder.java:199)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at
org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
at
org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
at
org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
To resolve this error i explored about it..and below are links which i
explored :
Bug 391880 - javascript validator throws error, unable to build project
ClassCastException
but still i didn't get any proper solution to resolve this error.... So
please guide me to remove this error...its very urgent for me..
Thanks in advance..

Retrieve Session value in Javascript from Code behind file Aspx.cs

Retrieve Session value in Javascript from Code behind file Aspx.cs

I am storing some value in session through code behind file named
Index4.aspx.cs by using this code: Session[txtUsername.Text.ToUpper() +
"ChannelID_BC"] = 1111110;
But now how to retrieve it in Index$.aspx page through JavaScript

ideas reseting stats in class

ideas reseting stats in class

Hi I made a simple program but when my monster dies the stats dont
reset(hp mainly) I am lost In how to make it reset every time the monsters
hp reaches 0 and the xp is awarded. I know that I can wright the code over
again and again but I would like to be able to make it continue is as
little amount of code as possible. Im still learning python so I dont
really know as much as everyone else here. Ive gotten to classes but not
so much in depth here is the code:
import random
def title():
print"hello Hero, welcome to staghold"
print"you have traveld along way, and you find yourself"
print"surrounded by and army of monsters as far as the eye can see"
print"begin to draw your sword.....you run full speed towards the army"
print"how many monsters can you kill before the inevatable comes?"
raw_input("(press enter to continue)")
def stats():
print"you have 200 health"
print"your level is 1"
print"you have 0 exp"
raw_input("(press enter to continue)")
class monster:
hp=50
monsterattack=random.randint
xp=random.randint(20,50)
health=200
level=1
exp=0
wave=1
title()
stats()
print"you run into a wave"
while level==1:
if monster.hp<=0:
print"you have defeated this wave of monsters"
wave+=1
exp+=monster.xp
print" you get, "+str(monster.xp)+" exp from the monster"
print"you now have, "+str(exp)+" exp"
if exp>=300:
level+=1
if level==2:
print"CONGRADULATIONS YOU HAVE REACHED LEVEL 2"
elif monster.hp>=0:
choice=raw_input("Will you 'fight' or 'run' from this horde?")
if choice=='fight':
print"you swing your sword at the monster"
att=random.randint(2, 13)
health-=monster.monsterattack(2,15)
monster.hp-=att
hp=200-health
print"you do, "+str(att)+" damage to the monster"
print"the monster does, "+str(hp)+" damage to you"
print"you have, "+str(health)+" health left"
print"the monster has, "+str(monster.hp)+" health left"
elif choice=="run":
print"you got away from this wave safely"
else:
print"NOT A VALID CHOICE"

MIPS Assembly to C

MIPS Assembly to C

So I'm trying to translate this MIPS assembly code into C. I'm confused on
a certain part of what's going on. Here is the MIPS assembly code: Assume
we have variables f, g, h, i, j stored in $s0, $s1, $s2, $s3 and $s4,
respectively. Assume the base addresses of arrays A and B are at $s6 and
$s7 respectively and they contain 4 byte words. I have inserted comments
to show I understand most of this.
sll $t0, $s0, 2 # $t0 = f * 4
add $t0, $s6, $t0 # $t0 = &A[f]
sll $t1, $s1, 2 # $t1 = g * 4
add $t1, $s7, $t1 # $t1 = &B[g]
lw $s0, 0($t0) # f = A[f]
addi $t2, $t0, 4 <-- Here's where I am confused. Since $t0 contains the
address of A[f], what does adding 4 do to that?
lw $t0, 0($t2)
add $t0, $t0, $s0
sw $t0, 0($t1)

Read file in blocks

Read file in blocks

I'm having an issue which I'm currently stuck on.
I have a big file in the following format:
Block 1
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 2
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 3
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Block 4
Line 1: Type1/Type2
Line 2: Time
Line 3: Data we need
Line 4: 00.*
Line 5: Fix 100
Line 6: In..
Line 7: Ou..
Line 8: Data we need
Line 9: Next
Line 10: Multi_Exit
Etc
I want to read the first line of each block, to check if Type1 or Type2.
After this I want to print Line 3 and Line 8 of each block and keep on
doing that until file ends.
I have tried the following codes:
p = './file.txt'
fin = open(p, 'r')
for i, line in enumerate(fin):
if i%11 == 2 or i%11 == 7:
print line
fin.close()
I have noticed after this code is run on my big file the line changes. I
can only assume my block lengths isn't fixed to 10 lines (plus one line
space before the next block starts). So this method isn't ideal.
I have also tried regular expression but I'm having trouble storing my
results on the format I want such as:
For Type 1
File the output should be: Line 3: Data Line 8: Data
Single space between it.
This is the next code I have tried:
for line in fin:
if re.match("(Line 1|Line 3|Line 8)", line):
writeToFile(line)
Where writeToFile function does the following:
def writeToFile(filein):
p = './output.txt'
fo = open(p, 'a')
fo.write(filein)
fo.close()
This is how the output.txt file looks:
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Line 1: Type1/Type2
Line 3: Data we need
Line 8: Data we need
Which is not exactly the desired outcome. I don't even mind to play around
with this output file and check for Line 1 if Type 1. Then get Line 3 and
Line 8 put them in the same line. Keep on doing that, until Type 2 is
found and do the same with Line 3 and Line 8 and store it in different
output file.
I hope I haven't complicated things.

Cannot install CMake for Mac OS X 10.8

Cannot install CMake for Mac OS X 10.8

I do not have cmake in terminal, so I went to it's webpage download page,
downloaded the "Mac OSX 64/32-bit Universal (for Intel, Snow Leopard/10.6
or later)" item, and the installer does nothing! I tried all 3 of them!!!
can anyone help me install cmake ????? huge thanks in advance!

Do I need a temporary table?

Do I need a temporary table?

I have the following query and I need to add "and distance < 10" to the
where clause. Because 'distance' is computed variable it can't be used in
where clause. I have tried HAVING instead of where but that breaks the
replace part.
I think the answer is to use a temporary table for the distance
computation but i can't figure out the syntax as everything I have tried
doesn't work.
All help appreciated please. Thanks.
select
Contractor.contractorID,
Contractor.firstName,
Contractor.lastName,
Contractor.emailAddress,
Contractor.nationality,
Contractor.dateOfBirth,
Contractor.address1,
Contractor.address2,
Contractor.city,
Contractor.county,
Contractor.postcode,
Contractor.country,
Contractor.tel,
Contractor.mob,
postcodes.Grid_N Grid_N1,
postcodes.Grid_E Grid_E1,
(select Grid_N from postcodes where pCode='".$postcode."') Grid_N2,
(select Grid_E from postcodes where pCode='".$postcode."') Grid_E2,
( (select
sqrt(((Grid_N1-Grid_N2)*(Grid_N1-Grid_N2))+((Grid_E1-Grid_E2)*(Grid_E1-Grid_E2)))
))/1000*0.621371192 as distance
from
Contractor,
postcodes
where
postcodes.Pcode =
replace(substring(Contractor.postcode,1,length(Contractor.postcode)-3),'','')
order by
distance asc

Sunday, 15 September 2013

Impact of memory footprint on performance

Impact of memory footprint on performance

We have a .Net (VS 2012) 64 bit application, running on Windows Server
2012, which loads lots of data in memory to work with it for next 24 - 48
hours. As per our design we prefer to load the data upfront by connecting
to the Data source. Net memory footprint of the process goes up to 7-8 GB,
which is because we replicate the data for 4 independent threads, which
represent the parallel clients, so it like 2 GB of Data per client.
Hardware that we are using is having 128 GB of RAM, 4 CPU (24 Core) processor
I was wondering that does the memory footprint will have an impact on the
net performance of the process, like speed of execution, processor
utilization etc
Even when we have such a good RAM and the net usage never exceed 60%, will
there still be swapping of process pages to HD, thus making it slower,
when it is continuously used for 48 hours. Is there some server settings
or .Net c# code API, that will help us taking care of performance issues
occurring due to memory footprint. We can explicitly tell the system that
our process needs lots of memory

Problems in Java Hex Numbers

Problems in Java Hex Numbers

I was trying to implement Hex calculations on two hex numbers, I am facing
a weird problem
When I tried adding two positive hex numbers, it gave me a negative
result. Here delta =9e3779b9 and sum=0
Here the addition must be 9E3779B9 or 2654435769 in decimal, but the code
in Java makes it negative. Here is the code:
long delta = 0x9e3779b9;
long sum = 0;
sum = sum + delta;
System.out.println(sum);
sum = sum << 5;
System.out.println(sum);
having output as
-1640531527
-52497008864
I believe this is due to the first sign bit for long, how to solve this
problem so that it can ignore the negative?

e.preventDefault() not working

e.preventDefault() not working

Guys
I have a table which rows are generated with a click event of an element.
Now, this works perfectly, the problem is with the delete part. For
example I have already added 5 rows, when I click the delete button (the
delete button is created through JQuery too on the addRow() click event),
all rows added through the JQuery function are being deleted and the form
is submitting event though I have an e.preventDefault() method called.
Javascript/JQuery code:
var counter = 2;
window.addRow = function addRow() {
var newRow = $('<tr><td><label>'+ counter
+'</label></td><td><textarea name="txtActionStep' + counter +
'" style="width:300px; height: 50px;
word-wrap:break-word;"></textarea></td><td valign="top"><input
type="text" name="txtOwner' + counter + '"/></td><td><button
class="delete">delete</button></td></tr>');
counter++;
$('table.actionsteps-list').append( newRow );
}
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});
function postForm() {
var form = document.getElementById('actionStepsForm');
document.getElementById('rowCount').value = counter-1;
form.submit();
}
HTML Code (the form itself):
<form name="actionStepsForm" id="actionStepsForm"
action="add_reprocessing.php?action=add" method="post">
<table class="actionsteps-list" width="510">
<tr>
<th colspan="3" align="left">Action Steps</th>
</tr>
<tr>
<td>Step #</td><td>Action Step</td><td>Owner</td>
</tr>
<tr>
<td>
<label>1</label>
</td>
<td>
<textarea name="txtActionStep1" style="width:300px;
height: 50px; word-wrap:break-word;"></textarea>
</td>
<td valign="top">
<input type="text" name="txtOwner1" />
</td>
</tr>
</table>
<table width="510">
<tr>
<td align="right"><a href="#" title="" onclick="addRow();
return false;">Add Action</a></td>
</tr>
</table>
<input type="button" value="Create" onclick="postForm(); return
false;" />
<input type="hidden" value="" id="rowCount" name="rowCount" />
</form>
Believe it or not, I've been stuck here for almost 3 days now. I can't
find any fix online. I don't what's wrong.

File I/O python

File I/O python

I am trying to find few strings in a file but the line.find() doesn't
return true for any string in the file.Please have a look an suggest
something.The search has to be sequential and I need to hold the offset
value for every string which is found. and the search for next string
should start from that offset.
def CheckFile(*argv):
import os
Filename = argv[0]
Search = argv[1]
Flag = False
FileFlag = False
offset1 = 0
offset2 = 0
if os.path.exists(Filename) == 0:
return "File Doesn't exist", 1
else:
fh = open(Filename,"r")
for line in fh:
if line.find(Search):
print "Success"
print (line)
Flag = True
offset1 = fh.tell()
#offset1 = int(offset1)
break
else:
fh.close()
return "Could not find String %s"%(Search), 1
#fh.close()
if Flag:
fh = open(Filename,"r")
print(offset1)
fh.seek(offset1)
for line in fh:
if line.find("TestDir1\TestFile1.txt"):
print "Success"
print (line)
FileFlag = True
offset2 = fh.tell()
#offset2 = int(offset2)
break
else:
fh.close()
return "Couldn't Find File TestDir1\TestFile1.txt", 1
#fh.close()
if Flag and FileFlag:
fh = open(Filename,"r")
print(offset2)
fh.seek(offset2)
for line in fh:
if line.find("Persistent Handle: True"):
print "Success"
return "Success -- Found the strings", 0
else:
fh.close()
return "Failur -- Failed to find 'Persistent Handle: True'", 1

Ways to configure Log4j XML Configuration

Ways to configure Log4j XML Configuration

I am using log4j to log information in my web application. I have chosen
log4j.xml type of configuration instead of log4j.properties. I remember
that, for log4j.properties configuration, I did not write Java code lines
to find the log4j.property file location. However, for log4j.xml file
configuration I am specifying explicitly to find it like this
DOMConfigurator.configure("log4j.xml");//it reads file from classpath,
working!
Also, tested my application removing the above statement from source. It
doesn't see to work. None of the debug statements were printed except
System.out.println();
I have read that log4j by default looks for log4jproperties file or
log4j.xml file in the classpath. I checked in the deployed web
application, log4j.xml file is in web-inf/classes. Even though it can't
find log4j.xml.
Is it that, the above code line is mandatory for log4j xml configuration
in Java? In fact, can't Java source code doesn't pickup log4j.xml from the
classpath without explicit specification as above?

Efficient all purposes PDO query for all situation

Efficient all purposes PDO query for all situation

Rather than have different PHP functions for different interaction with
the database is it possible to have a one size fits all function. Below is
my attempt which works, but what are the limitations of this if any? And
will it unnecessarily lag the performance of the site?
function
fetch($field,$table,$where,$is,$limit,$offset,$order,$eqt,$function){
global $kdb;
if(!$eqt){ $eqt = "="; }
if(!$limit){ $limit = "1"; }
if(!$function){ $function = "SELECT"; }
$sql = "$function $field FROM $table";
$wheres = explode(',',$where); $is = explode(',',$is); $eqt =
explode(',',$eqt);
$eachcount = 0;
$eachby = "WHERE";
foreach($wheres as $where){
if(!$eqt[$eachcount]){
$eqt[$eachcount] = $eqt[0];
}
if($method == 'LIKE'){
$sql .= " $eachby $where $eqt[$eachcount] '%$is[$eachcount]%' ";
}
else {
$sql .= " $eachby $where $eqt[$eachcount] '$is[$eachcount]' ";
}
$eachby = "AND";
}
$stm = $kdb->prepare($sql);
$stm->execute();
if($function == 'count'){
$row = $stm->fetchColumn();
}
elseif($stm->rowCount() <= 1) {
$row = $stm->fetch();
}
else{
$row = $stm->fetchAll();
}
return $row;
}

Why isn't this an infinite loop?

Why isn't this an infinite loop?

Why doesn't the following loop run infinite times? I expect that upon
reaching 65535, i should overflow back to zero.
#include<stdio.h>
int main()
{
short int i = 0; //(assume short int is 2 bytes)
for(i<=5 && i>=-1; ++i; i>0)
printf("%u\n", i);
return 0;
}

Saturday, 14 September 2013

video shot detection method

video shot detection method

I wanted to get shots from a whole video. For example, if I give input as
a video, then output should be parts of video(video shots/clips).I have
tried a lot about this; but did not reach solution. So if anyone knows any
technique for splitting the video into different shots, let me know. Code
can be in mat lab or Open CV.

how to dynamically add $scope in Angular

how to dynamically add $scope in Angular

here is my HTML:
...
<table class="tickerTable">
<thead>
<th class="first">Symbol</th>
<th>Accts</th>
<th>Shares Bought</th>
<th>Shares Sold</th>
<th>Shares Own</th>
<th>Case Filed</th>
<th>Est. Losses</th>
<th>Case Status</th>
</thead>
<tbody ng-repeat="ticker in tickers | orderBy:'Status':true | filter:search">
<tr class="{{ticker.Status | status}}" ng-click="showTrades(ticker)">
<td class=" left link">{{ticker.Ticker}}</td>
<td class="middle link">{{ticker.TradeCount}}</td>
<td>{{ticker.TotalBought | number:2}}</td>
<td>{{ticker.TotalSold | number:2}}</td>
<td>{{ticker.TotalSharesNow | number:2}}</td>
<td>{{ticker.DateFiled}}</td>
<td>{{ticker.EstimatedLosses | currency}}</td>
<td class="link">{{ticker.Status | status}}</td>
</tr>
<tr ng-show="currentItem == ticker">
<td colspan="8">{{trades}}<div ng-include="loadTrades == ticker"></div>
</div></td>
</tr>
</tbody>
</table>
here is the controller:
$scope.showTrades = function(ticker){
var i = ticker.TickerID+ticker.AlertID;
$scope.trades = null;
$scope.currentItem = ticker;
return $scope.trades = Trades.query({SHFUserID:ticker.SHFUserID,
TickerID:ticker.TickerID, AlertID:ticker.AlertID});
};
the table is populated with many rows. then for each row i add a blank row
that is hidden by default. when the row is clicked the hidden row is
displayed and the $scope.trades is loaded and {{trades}} displays the
data. The problem is that since I am dynamically generating the empty TR
rows based on how many "ticker in Tickers" the {{trades}} data is
populated in each of them. even thought the data is hidden this is not the
desired result. I only want to load the {{trades}} data into the visible
TR exposed by ng-show.

How to query count with 0 rows

How to query count with 0 rows

My query is to get the count of total rows, along with the columns. An
example table, which has to be a temp table is:
temp(a1,a2)
I need to query a1,a2, and total number of rows.
SELECT COUNT(*) as TotalRow, a1, a2 from #temp group by a1,a2
The query works fine for table with rows >=1. However, for some special
case, this table has zero row. In that case, TotalRow does not return a
value (it should be zero). How can I get that query work for all cases
including zero row? Thanks.

DATE field covnersion to date+time with timezone

DATE field covnersion to date+time with timezone

I am trying to convert a date into date+time with timezone as below based
on the day light savings: INPUTDATE: 12/23/1990 OUTPUT DATE: 12-23-1990
00:00:00 -5:00
kindly help with the query conversion.

combinatorial optimization: multiple upgrade paths with inventory constraints

combinatorial optimization: multiple upgrade paths with inventory constraints

I'm playing a video game, and i want to make a program that calculates the
globally optimal build/upgrade path towards a fixed 6 item goal.
Time, Cost, Inventory constraints, and effectiveness (short/mid/long-term)
ratings are to be considered. Identifying local spikes in effectiveness
are also welcomed, but optional. I don't know how to classify this
problem, but i'm guessing its a type of graph search. The fact that
multiple criteria are being optimized is making things confusing for me.
Problem details:
There are 6 free slots in your bag to hold items.
There are 2 classes of items: basic items, and composite items.
Composite items are built/merged from basic items, and other composite items.
If you have enough gold, you can buy a composite item, and its missing sub
components, all at once, using only 1 inventory slot.
The build path for various composite items are fixed, and many basic
components are featured in more than one recipe.
Gold is earned at a fixed rate over time, as well as in small
non-deterministic bursts.
There exists no more than 50 items, maybe less.
So, thinking about the problem...
Tackling the gold/time issue first
We can either ignore the non-deterministic aspect, or use some statistical
averages. Let's make life easy, and ignore it for now. Since gold, and
time, are now directly related in our simplified version, they can be
logically merged.
Combinatorial expansion of feasible paths
A graph could be built, top down, from each of the 6 goal items,
indicating their individual upgrade hierarchies. Components that are
shared between the various hierarchies can be connected, giving branch
decisions. The edges between components can be weighted by their cost. At
this point, it sounds like a shortest path problem, except with multiple
parallel and overlapping goals.
Now the question is: how do inventory constraints play into this?
The inventory/cost constraints, add a context, that both disables (no free
slots; not enough gold), and enables (two items merged freeing a slot)
various branch decisions, based upon previous choices and elapsed time.
How does one expand all the feasible possibilities? Does it have to be
done at every given step? How many total combinations are there? Does this
fall under topological combinatorics?
Rating Effectiveness
If the above expansion produces less than a few billion possibilities, we
can just exhaustive search using OpenCL/CUDA. I'm not sure what other
options are available, since most graph search stuff seems to just solve
for one criteria.

Windows 8.1 app on Windows 8

Windows 8.1 app on Windows 8

I'm creating a windows 8 app and i need to update it to windows 8.1.
I have a tablet PC which i don't want to install windows 8.1. Is it
possible to run an app for windows 8.1 on windows 8?

how to extract portion of string in RegEx

how to extract portion of string in RegEx

I have a string "Standard delivery in 5 business days"
I want to extract "5 business days" from this string.
I wrote regex "(/[0-9]/*)"
But it does not works..
Help me out..
Thanks..

deleting the particular type of zip files in a target folder if they are created before seven days

deleting the particular type of zip files in a target folder if they are
created before seven days

I was moving a zip file from source directory to target directory but
since the target directory may also contain some other files like text
files , image , documents files , zip files also ,so the target folder
will be having different types of files now if I talk of zip files in the
target folder then there must be different types of zip files of different
name but my point is that I have to look the zip files which name is
starting with pattern abcd so I have to look the zip files of which name
is starting with abcd and after that it could be anything like
abcd4567fg.zip so I have to catch such zip files and also have to look
their creation time since my ultimate goal is not to keep the zip files
whose name is starting with abcd in the target directory if they are
created before seven days , I have come up with the below solution but it
is not appropriate please advise
long timeInEpoch = System.currentTimeMillis(); // slightly faster than
new Date().getTimeInMillis();
File f = new File("/tmp");
if (f.isDirectory()) {
final File[] files = f.listFiles();
for(int i =0; i < files.length ; i++ ) {
if( timeInEpoch - f.lastModifiedDate() > 1000*60*60*24*7 )
files[i].delete();
}
System.out.println(fileList);
}

Friday, 13 September 2013

How to add url link from java with css element?

How to add url link from java with css element?

Here is the code:
<span class='maincaptionsmall'>
Test
</span>
For some reasons of ajax and jquery codes in my page, I can't use HREF as
Link, I mean, I can't use something like this following code:
<span class='maincaptionsmall'><a href="http://google.com">Test</a></span>
So, How can i use jquery to get this css element maincaptionsmall and it
will set it to href link ?
Even I can't use <div> too, I should use everything as <span> Please give
me an example that how to use jquery to set css element as href link.
Thanks in advance

c++ macro for saving enum element names and values to file

c++ macro for saving enum element names and values to file

Normally I try to avoid the use of macros, so I actually don't know how to
use them beyond the very most basic ones, but I'm trying to do some
meta-manipulation so I assume macros are needed.
I have an enum listing various log entries and their respective id, e.g.
enum LogID
{
LOG_ID_ITEM1=0,
LOG_ID_ITEM2,
LOG_ID_ITEM3=10,
...
}
which is used within my program when writing data to the log file. Note
that they will not, in general, be in any order.
I do most of my log file post-processing in Matlab so I'd like to write
the same variable names and values to a file for Matlab to load in. e.g.,
a file looking like
LOG_ID_ITEM1=0;
LOG_ID_ITEM2=1;
LOG_ID_ITEM3=10;
...
I have no idea how to go about doing this, but it seems like it shouldn't
be too complicated. If it helps, I am using c++11.

Tomcat server will not start up with a filter

Tomcat server will not start up with a filter

Here is the web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>Projeto_joas</display-name>
<resource-ref>
<res-ref-name>jdbc/DiaDiaDev</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<servlet>
<display-name>FacesServlet</display-name>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<!-- <filter> -->
<!--<filter-name>FilterHibernate</filter-name> -->
<!--<filter-class>util.filter.ConexaoHibernateFilter</filter-class> -->
<!--</filter> -->
<!--<filter-mapping> -->
<!-- <filter-name>FilterHibernate</filter-name> -->
<!--<url-pattern>*.jsf</url-pattern> -->
<!--</filter-mapping> -->
</web-app>
The server runs just fine this way, if i remove the comments on the
filter, it won't start and will throw me those exceptions:
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException:
org.apache.catalina.LifecycleException: Failed to start component
[StandardEngine[Catalina].StandardHost[localhost]] Caused by:
org.apache.catalina.LifecycleException: Failed to start component
[StandardEngine[Catalina].StandardHost[localhost]] Caused by:
org.apache.catalina.LifecycleException: A child container failed during
start
and
WARNING: Failed to retrieve JNDI naming context for container
[StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Projeto_joas]]
so no cleanup was performed for that container
javax.naming.NamingException: No naming context bound to this class loader

How to detect scripts failed to load in firefox

How to detect scripts failed to load in firefox

I use firefox in my Windows7 PC. There are lot of websites around, which
use JavaScript files / libraries with inline script. Normally, a JS load
failure may be detected using <noscript> tag. But suppose, if a web page
(not mine) has 5 .js files from 5 different domains, and one failed to
load because of 404 or url blacklist in PC or something else. How can I
detect the script which failed to load using firefox? Is this possible
using firebug?

How I execute javascript multiple times without refreshing the page

How I execute javascript multiple times without refreshing the page

I want javascript to execute as many times I want to but it's only
executing once. The code below works perfectly fine but, after the
clicking of both the buttons, I have to refresh the page to make it work
again. Please help me out with this problem.
Just wanna execute it as many times I want to but without refreshing the
page.

Service not run again

Service not run again

i have windows service. The program jump to getFileList, after that jump
to DeleteOldBackupFiles and after that nothing...the program not run again
and I dont know why..Have you any idea? Example of my code:
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(getFileList);
timer.Interval = 10000;
timer.AutoReset = true;
timer.Start();
}
protected override void OnStop()
{
}
private void getFileList(object sender, EventArgs e)
{
if (!Directory.Exists(backup))
{
Directory.CreateDirectory(backup);
}
List<string> files = new List<string>();
try
{
FtpWebRequest request =
(FtpWebRequest)FtpWebRequest.Create(FtpNOHELZmeny);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(FtpNOHELJmeno,
FtpNOHELHeslo);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response =
(FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
files.Add(reader.ReadLine());
}
files.Remove(".");
files.Remove("..");
reader.Close();
responseStream.Close();
response.Close();
}
catch (Exception)
{
}
if (files.Count != 0)
{
foreach (string file in files)
{
//Work with XML file and give data to sql
}
}
DeleteOldBackupFiles();
}
private void DeleteOldBackupFiles()
{
string[] Oldfiles = Directory.GetFiles(backup);
foreach (string Ofile in Oldfiles)
{
FileInfo fi = new FileInfo(Ofile);
if (fi.LastWriteTime < DateTime.Now.AddMonths(-2))
{
fi.Delete();
}
}
}
I want after DeleteOldBackupFiles, run OnStart again...

Thursday, 12 September 2013

How can I find the code that's refreshing the page?

How can I find the code that's refreshing the page?

How can I find the specific code that's causing a web page to auto-refresh?
I've looked through the source for an HTML meta-refresh, to no avail. I
also can't find any Javascript "reload" in the main page, leading me to
think it's perhaps externally loaded through a link javascript file.
How would a "pro" track this down, like through Firebug (or other debugger)?
Note:
I'm more interested in the process of being able to debug and track down
something like this, rather than a "catch-all" solution that will stop it
cold (such as disabling the Firefox-wide ability for pages to auto-refresh
themselves).

permission denied with file_get_contents and file_put_contents on OS X

permission denied with file_get_contents and file_put_contents on OS X

I have a controller (using Symfony) and trying to write a file to a local
machine I have the code is as follows:
$file = '/Users/Aditya/Desktop/insta_user.txt';
$current = file_get_contents($file, FILE_USE_INCLUDE_PATH);
However I am getting an error:
Warning: file_get_contents(/Users/Aditya/Desktop/insta_user.txt): failed
to open stream: Permission denied in
/Users/Aditya/Sites/App/src/App/MainBundle/Controller/InstagramController.php
on line 58
Warning: file_put_contents(/Users/Aditya/Desktop/insta_user.txt): failed
to open stream: Permission denied in
/Users/Aditya/Sites/App/src/App/MainBundle/Controller/InstagramController.php
on line 72
I have chmod 777 to this insta_user.txt. What else do I need to do to make
this work?

Saxon 9B DTD locations

Saxon 9B DTD locations

I'm trying to configure locate the DTDs for Saxon extensions and java
types (IntelliJ editor configuration).
The namespaces:
http://saxon.sf.net http://saxon.sf.net/java-type
...have no DTDs available in the classpath. I've looked in the jars and
everywhere and can't find an explanation or references to such DTDs on the
web. I'm able to use extensions and java types, such as saxon:evaluate,
successfully.
I'm using Saxon 9B.

Linq SUM query not calculating sum of values in a column

Linq SUM query not calculating sum of values in a column

I have a IQueryable collection with a column called Amount and I want to
get the sum of values for Amount column for all the rows.
collection.Select(x => x.Amount).Sum();
collection.Sum(a => a.Amount);
Unfortunately, both the above queries are not working.

Redundant/Better Performance Code VS Optimized/Less Performance Code

Redundant/Better Performance Code VS Optimized/Less Performance Code

In my case, I'm using C#, but the concept of the question would apply to
Java as well. Hopefully the answer would be generic enough to cover both
languages. Otherwise it's better to split the question into two.
I've always thought of which one is a better practice.
Does the compiler take care of enhancing the 'second' code so its
performance would be as good as the 'first' code?
Could it be worked around to get a 'better performance' and 'optimized'
code at the same time?
Redundant/Better Performance Code:
string name = GetName(); // returned string could be empty
List<string> myListOfStrings = GetListOfStrings();
if(string.IsNullOrWhiteSpace(name)
{
foreach(string s in myListOfStrings)
Console.WriteLine(s);
}
else
{
foreach(string s in myListOfStrings)
Console.WriteLine(s + " (Name is: " + name);
}
Optimized/Less Performance Code:
string name = GetName(); // returned string could be empty
List<string> myListOfStrings = GetListOfStrings();
foreach(string s in myListOfStrings)
Console.WriteLine(string.IsNullOrWhiteSpace(name) ? s : s + " (Name
is: " + name);
Obviously the execution time of the 'first' code is less because it
executes the condition 'string.IsNullOrWhiteSpace(name)' only once per
loop. Whereas the 'second' code (which is nicer) executes the condition on
every iteration.
Please consider a long loop execution time not a short one because I know
that when it is short, the performance won't differ.

SharpSvn: RemoteLock and awaiting for it to become free? Blocking?

SharpSvn: RemoteLock and awaiting for it to become free? Blocking?

I have managed to lock a file using RemoteLock. What I am having an issue
with is if another thread enters my code and tries to lock the file it
throws an error as it is already locked.
Is there no blocking code for lock, i.e wait for the lock to become free ?
Maybe I am not using it correctly.
Any ideas?
Thanks

How to query multi 'or' and a and in SQL?

How to query multi 'or' and a and in SQL?

a table like this
table
|primary_key| project | tag |
| 1 | 2 | 3 |
| 2 | 2 | 0 |
| 3 | 2 | 4 |
| 4 | 2 | 5 |
| 5 | 3 | 0 |
| 6 | 2 | 0 |
I want to query project with tag '(3|0) and 4' , In this example, the
output should be project 2? how could I write this in a SQL? I tried using
phpmyadmin to generate several result, but not work as I expect.

why we are using $(document) instead of $("document") in jquery?

why we are using $(document) instead of $("document") in jquery?

in Jquery,
to select a div, we use $("div"). div is enclosed with quote symbols.
but why we are always using $(document) instead of $("document")?.
what is the reason?
Thanks in advance.

Wednesday, 11 September 2013

convert these string to number php

convert these string to number php

using php. I have the following number
4,564,454
454,454,454
54.54
65.43
I want to convert these into number for calculating. How can I do it?
Right now, the type of these number is string.
Thanks

What does an incorrectly overridden method do?

What does an incorrectly overridden method do?

Say if I'm trying to override a method but incorrectly put in a new sig,
such as public boolean equals(Circle o) - what does this method actually
do? How could I call it?

Fill in an array from a single formatted keyboard line in C

Fill in an array from a single formatted keyboard line in C

How can I fill in a double or int array from a single, arbitrarily long,
formatted (e.g. space delimited) keyboard line?
For instance:
Enter the elements of the array: 2 32 12.2 4 5 ...
should result in => array[0] = 2 => array[1] = 32 etc.
I know that I can use scanf as follows, but that does not solve my
problem, since each element should be entered one by one.
/* Input data from keyboard into array */
for (count = 1; count < 13; count++)
{
printf("Enter element : %d: ", count);
scanf("%f", &array[count]);
}
Thanks.