Thursday, 3 October 2013

Starting Glassfish without Sudo

Starting Glassfish without Sudo

I am currently having a problem starting Glassfish inside Eclipse on OS X.
It just hangs whilst trying to start the domain.
I think the problem may lie with the permissions of Glassfish - When I use
the 'start-domain domain1' command even in terminal, I must use 'sudo'
otherwise I get a 'permissions denied' error. If I use 'sudo', then the
server starts successfully from terminal.
I think this error may be carrying over into Eclipse - that is, the server
is trying to start but is timing out because Eclipse is not starting the
server with the correct permissions etc.
Is there any way to start the server via Eclipse by giving it root
permissions? Or another solution, is there any way to change the Glassfish
permissions so that it can be started without the 'sudo' command?
Thanks.

Wednesday, 2 October 2013

Navbar issue in Bootstrap 3.0

Navbar issue in Bootstrap 3.0

I want to create a collapsable, floating navbar to the right hand side of
the Jumbotron in my page. I am using Bootstrap 3.0.
My navbar collapses but the site name disappears when the navbar
collapses. Also the navbar is pinned to the top of my screen rather than
on the right hand side. What am I doing wrong? Thanks for the help.
<section>
<div class="navbar">
<nav class="navbar navbar-inverse" role="navigation">
<a class="navbar-brand" href="index.html">DD Portfolio</a>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</section>
<div class="jumbotron">
<div class="container">
<h1>Who Am I?</h1>
<p>I am a student and content writer</p>
<p><a href="#" class="btn btn-primary btn-large">Learn
More</a></p>
</div>
</div>
</div>

Change Base Url CodeIgniter and Ionauth

Change Base Url CodeIgniter and Ionauth

This is probably a really simple question but I am entirely new to
codeigniter. I am using ionauth for a secure account system but I would
like to change the url path, simply changing the class name is not
working, it simply gives me a 404 whenever I try access it. I am trying to
change the /auth/ location to /account/ but when I try it by just renaming
class Auth extends CI_Controller { to class Account extends CI_Controller
{ it does not work as expected.
Any suggestions are greatly appreciated, Again I am new to this so please
go easy it's probably a simple fix and me not know code igniter very well.
Thanks, Simon

return code of 256 from python

return code of 256 from python

This is a reposted question from raspberrypi.stackexchange.com. While I am
trying to get something to work on python on the raspberry pi, since it
doesn't involve any pi-specific things, it was suggested by someone I post
here instead. Original post is here.



I am trying to make a web ui to change the date in the rapsberry pi, but I
keep getting a return code of 256.
Currently what I have goes like this:
web page -> submits an ajax request to a python script python checks what
type of command (a time/date command in this case) and pieces together a
string looking like:
sudo date --set="20130901 20:10"
and stores it in a variable commandString. Then python goes:
os.system(commandString)
and the return value is passed all the way up to the web ui where it is
printed out.
I also currently return the commandString value to the web ui too to
verify it and it looks okay.
The problem is that every time I test, I keep getting back 256 as the
error return code. The date on the raspberry pi of course doesn't change
as I manually check it before and after.
However, if I manually go in to python on the raspberry pi and try:
commandString = 'sudo date --set="20130901 20:10"'
os.system(commandString)
It works with no issues. If I try it without sudo then I get a return
value of 256 as well, so I thought maybe it was a permissions issue with
my original script. I tried this link to check my script's permissions and
it seems to be okay? (os.geteuid() is 0)
If it matters, I am using lighttpd and fastcgi to run python from a web
ui. My lighttpd config is currently:
fastcgi.server = (
".py" => (
"python-fcgi" => (
"socket" => "/tmp/fastcgi.python.socket",
"bin-path" => "/var/www/command.py",
"check-local" => "disable",
"max-procs" => 1)
)
)
Any ideas on what I'm missing?



On the original post, it was also suggested I try something like:
echo <password> | sudo -S date --set="20130829 02:02
While it's probably not a good idea to put in my root password like that,
I tried it and got the same result: it works when doing in the
terminal/shell and within the python interpreter, but not via the web ui
to python.

Tuesday, 1 October 2013

How to pixelate an image with canvas and javascript

How to pixelate an image with canvas and javascript

I've been experimenting a bit with the canvas element and was curious how
to pull off an effect. I've somewhat got what I'm looking for from a
collection of tutorials and demos, but I need some assistance getting the
rest of the way there. What I'm looking for is to pixelate an image on
mouseover, then refocus/un-pixelate it on mouseout. You can see a good
example of the effect at http://www.cropp.com/ when mousing over the
blocks that are below the main carousel.
Here is a link to a fiddle I started. The fiddle won't work because you
can't use cross domain images (womp womp), but you can still see my code
thus far. When mousing over my canvas object I'm able to pixelate the
image, but it's kind of backwards to what I'm attempting to get. Any help
or advice would be greatly appreciated.
var pixelation = 40,
fps = 120,
timeInterval = 1000 / fps,
canvas = document.getElementById('photo'),
context = canvas.getContext('2d'),
imgObj = new Image();
imgObj.src = 'images/me.jpg';
imgObj.onload = function () {
context.drawImage(imgObj, 0, 0);
};
canvas.addEventListener('mouseover', function() {
var interval = setInterval(function () {
context.drawImage(imgObj, 0, 0);
if (pixelation < 1) {
clearInterval(interval);
pixelation = 40;
} else {
pixelate(context, canvas.width, canvas.height, 0, 0);
}
}, timeInterval);
});
function pixelate(context, srcWidth, srcHeight, xPos, yPos) {
var sourceX = xPos,
sourceY = yPos,
imageData = context.getImageData(sourceX, sourceY, srcWidth,
srcHeight),
data = imageData.data;
for (var y = 0; y < srcHeight; y += pixelation) {
for (var x = 0; x < srcWidth; x += pixelation) {
var red = data[((srcWidth * y) + x) * 4],
green = data[((srcWidth * y) + x) * 4 + 1],
blue = data[((srcWidth * y) + x) * 4 + 2];
for (var n = 0; n < pixelation; n++) {
for (var m = 0; m < pixelation; m++) {
if (x + m < srcWidth) {
data[((srcWidth * (y + n)) + (x + m)) * 4] = red;
data[((srcWidth * (y + n)) + (x + m)) * 4 + 1] =
green;
data[((srcWidth * (y + n)) + (x + m)) * 4 + 2] =
blue;
}
}
}
}
}
// overwrite original image
context.putImageData(imageData, xPos, yPos);
pixelation -= 1;
}

Creating a long precision number in C#

Creating a long precision number in C#

I have a bunch of code written by someone else for a statistics package,
like so:
float myValue = 0.0f;
That makes myValue a single point precision number. Is there a way to make
it go to five decimal places?
Is this the correct way:
float myValue = 0.00000f;

Mosaic and using VLC with axis cameras

Mosaic and using VLC with axis cameras

this is my code for the mosaic
new channel1 broadcast enabled
setup channel1 input
rtsp://root:pass@192.168.1.76/axis-media/media.amp?resolution=cif&codec=h264
setup channel1 option network-caching=600
setup channel1 output #mosaic-bridge{id=1,width=352,height=288}
new channel2 broadcast enabled
setup channel2 input
rtsp://root:pass@192.168.1.76/axis-media/media.amp?resolution=cif&codec=h264
setup channel2 option network-caching=600
setup channel2 output #mosaic-bridge{id=2,width=352,height=288}
new channel3 broadcast enabled
setup channel3 input
rtsp://root:pass@192.168.1.76/axis-media/media.amp?resolution=cif&codec=h264
setup channel3 option network-caching=600
setup channel3 output #mosaic-bridge{id=3,width=352,height=288}
new channel4 broadcast enabled
setup channel4 input
rtsp://root:pass@192.168.1.76/axis-media/media.amp?resolution=cif&codec=h264
setup channel4 option network-caching=600
setup channel4 output #mosaic-bridge{id=4,width=352,height=288}
new test broadcast enabled
setup test input "file://home/background.jpg"
setup test option image-duration=-1
setup test option image-fps=0
setup test output
#transcode{sfilter=mosaic,vcodec=mp4a,vb=8500,fps=25}:display
control channel1 play
control channel2 play
control channel3 play
control channel4 play
control test play
However when using the following vlc command in the terminal to run the
mosaic_config.conf
vlc --vlm-conf /etc/mosaic_config.conf
I get the following error
VLC media player 2.0.8 Twoflower (revision 2.0.8a-0-g68cf50b)
Fontconfig warning: FcPattern object size does not accept value "0"
[0x9c91188] main libvlc: Running vlc with the default interface. Use
'cvlc' to use vlc
without interface.
[0x9d244d8] [Media: test] main input error: open of
`file://home/background.jpg' failed
[0x9d244d8] [Media: test] main input error: Your input can't be opened
[0x9d244d8] [Media: test] main input error: VLC is unable to open the MRL
'file://home
/background.jpg'. Check the log for details.
"sni-qt/4246" WARN 21:35:23.637 void
StatusNotifierItemFactory::connectToSnw() Invalid
interface to SNW_SERVICE
[0xb5036a30] [Media: channel3] main decoder error: cannot create
packetizer output (mp4a)
[0xb4e02818] [Media: channel4] main decoder error: cannot create
packetizer output (mp4a)
[0x9cbb8b8] [Media: channel2] main decoder error: cannot create packetizer
output (mp4a)
[0xb500a6b8] [Media: channel1] main decoder error: cannot create
packetizer output (mp4a)
[0x9d1d228] [Media: channel3] main input error: ES_OUT_RESET_PCR called
[0x9d20bd8] [Media: channel4] main input error: ES_OUT_RESET_PCR called
[0x9d20bd8] [Media: channel4] main input error: ES_OUT_RESET_PCR called
[0x9d2a268] [Media: channel2] main input error: ES_OUT_RESET_PCR called
[0x9d1d228] [Media: channel3] main input error: ES_OUT_RESET_PCR called
[0x9d2a268] [Media: channel2] main input error: ES_OUT_RESET_PCR called
Anyone got anyway to resolve this or maybe i should be asking this in the
videolan forum

When is a convex polygon inscribable?

When is a convex polygon inscribable?

Defining the diameter of a convex polygon as the maximum possible distance
between all pairs of vertices, can we conclude that the convex polygon is
inscribable (i.e has all its sides as chords of a circle) if the diameter
isn't the diameter of the minimum bounding circle, in which case the
circumscribed circle is the minimum bounding circle?

Monday, 30 September 2013

Awesome WM - running lua rc.lua gives an error

Awesome WM - running lua rc.lua gives an error

I install awesome using sudo apt-get install awesome
I copied my rc.lua to ~/.config/awesome and ran
lua rc.lua
I got the following error:
lua: rc.lua:2: module 'awful' not found:
no field package.preload['awful']
no file '/usr/local/share/lua/5.2/awful.lua'
no file '/usr/local/share/lua/5.2/awful/init.lua'
no file '/usr/local/lib/lua/5.2/awful.lua'
no file '/usr/local/lib/lua/5.2/awful/init.lua'
no file './awful.lua'
no file '/usr/share/lua/5.2/awful.lua'
no file '/usr/share/lua/5.2/awful/init.lua'
no file './awful.lua'
no file '/usr/local/lib/lua/5.2/awful.so'
no file '/usr/lib/x86_64-linux-gnu/lua/5.2/awful.so'
no file '/usr/lib/lua/5.2/awful.so'
no file '/usr/local/lib/lua/5.2/loadall.so'
no file './awful.so'
stack traceback:
[C]: in function 'require'
rc.lua:2: in main chunk
[C]: in ?
I'm using ubuntu 12.04. I'm not sure what i'm doing wrong or what is
missing. help please.

Says that my computer is running in low-graphics mode, but cannot run failsafe x. How do I fix this?

Says that my computer is running in low-graphics mode, but cannot run
failsafe x. How do I fix this?

When I start up my computer it tells me I am running in low graphics mode.
I've read tutorials on how to fix this and they all say I need to run
failsafe x. When I try to run failsafe x nothing happens. My screen starts
out black and sort of fades to a bluish and then to an orangeish and then
to black, but nothing else happens. What the heck is going on and how do I
fix it?

Accessing Photo File

Accessing Photo File

I use the standard TTakePhotoFromCameraAction in my application in order
to take a photo.
What I would like to do, is when the user closes the application and then
open it again, the last taken photo to be uploaded.
I know how to use SharedPreference in delphi, but I don't know what is the
filename & path of the photo it self!
Any clues?

ngcontroller in Angular JS

ngcontroller in Angular JS

I'm having some trouble understanding how to use ng-controller. I've a
form controller in eventController.js.
<html ng-app>
<head>
<script src="angular.js"></script>
<script src="eventController.js"></script>
</head>
<body>
<div>
<h3>My Event:<i>{{event.name}}</i></h3>
</div>
<div ng-controller="formController">
<form >
<label>Event Name:</label>
<input type="text" ng-model="event.name" placeholder="Event Name">
</form>
</div>
</body>
</html>
Now the heading even.name is not getting displayed when I'm using
ng-controller="formController" in that division otherwise its working
fine. When I use ng-controller on the whole page as a division then I get
{{event.name}} and not the content.
How can I display the content of event.name and also use the controller on
form together ?
What mistake am I making ?

Sunday, 29 September 2013

parsing a JSON fails with missing element in javascript

parsing a JSON fails with missing element in javascript

I am trying to use Youtube's Gdata JSON response in javascript. My code
iterates through the playlist and extract the item data.but for few videos
the rating is not there which throws
"TypeError: item.gd$rating is undefined"
is there a way to check before accessing the element.
this is the code with with i fetch the json response.
var avgrating = item['gd$rating']['average'];
var maxrating = item['gd$rating']['max'];
var minrating = item['gd$rating']['min'];
var numRaters = item['gd$rating']['numRaters'];

Hide Navigation Bar in Interface Builder w/ Storyboards

Hide Navigation Bar in Interface Builder w/ Storyboards

I have a pretty basic storyboard based app, with a UINavigationController,
a main view and a secondary view, both of which are in the navigation
hierarchy. I'm currently hiding the navigation bar on the main view by
using setNavigationBarHidden: as appropriate in viewWillAppear and
viewWillDisappear. It seems like there should be a way to do this in
Interface Builder, rather than in code. Essentially I'd like the options
available in the Simulated Metrics options, but not simulated. Does that
exist?

Algorithm:Sort using Median and Just 1 comparison in $ O(n \log n) $

Algorithm:Sort using Median and Just 1 comparison in $ O(n \log n) $

I am trying to write an sorting algorithm which takes an input array and
produces the sorted array. Following are the constraints for an algorithm.
Time complexity = $O(n \log n)$
Only one comparison operation throughout the algorithm.
We have a function which can provide an median for a set of three elements.
I have tried finding a solution and following is my result.
we use the median function to get the smallest and the largest pair.
Example: Give an array A[1..n], we get the median of the first three
elements, lets call it a set and we receive a $Median$. In next Iteration
we remove the received median from the set and add next element to the set
and again call Median function. This step when repeated over the length
produces a pair of the largest and the smallest element for the entire
array.
We use this pair, use the comparison operation and place them at position
A[0] & A[n-1].
We repeat the same operation over the array A[1..n-2] to get another pair
of the largest and smallest.
We take the median with the A[0] and newly received pair.
Median Value is placed at the A[1].
We take the median with the A[n-1] and newly received pair.
Median Value is placed at the A[n-2].
Step 3~7 are repeated to get a sorted array.
This algorithm satisfies the condition 2 & 3 but not the time complexity.
I hope if someone can provide some guidance how to proceed further.

Saturday, 28 September 2013

Javascript: onclick does not call function

Javascript: onclick does not call function

When I run the following code, the alert messages shows up but this.test()
does not run.
document.onclick = function(e) {
alert("Hi");
this.test();
};
However when I try this:
document.onclick = this.test();
this.test() will run.

Easiest to use C API to render utf8 text in OpenGL, outline rendering prefered [on hold]

Easiest to use C API to render utf8 text in OpenGL, outline rendering
prefered [on hold]

What is the easiest C API to render utf8 text in OpenGL.
I would prefer to use outline rendering.
Need to handle non ASCII characters
Huge dependencies would be nice to avoid
My ideal api would be init(),setFont(char*name),drawText(char*text,int
boxWidth,int boxHeight)
I have looked at
http://paulbourke.net/oldstuff/glf/ but this can't handle non ASCII in my
tests
http://quesoglc.sourceforge.net/ looks nice but seems unmaintained and I
get segfaults from it in debian stable
using Freetype directly does not support outline fonts as far as I
understand and freetype seems complicated to use
needs to be cross platform (linux, osx, windows)
So what would you recommend, I do not want C++ libraries as I intend to
use it from D and C bindings are much easier to write.

NSDateFormatter dateFromString conversion

NSDateFormatter dateFromString conversion

I am having problems with conversion of NSString object to NSDate. Here is
what I want to do: I am downloading an RSS Message from the internet. I
have the whole message parsed by NSXMLParser. After that, I have parts
like , or saved to particular NSStrings. I want to convert element (that
includes publication date of RSS Message) to NSDate so that I could
perform some operations on it like on a date object (e.g. sorting, showing
on a clock etc.). Here is the way my looks like:
"Wed, 25 Sep 2013 12:56:57 GMT"
I tried to convert it to NSDate in this way:
*//theString is NSString containing my date as a text
NSDate *dateNS = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss ZZZ"];
dateNS = [dateFormatter dateFromString:theString];*
However, after doing above code, dateNS always appear to be (null).
My question is simple: what is the right way to convert NSString with date
formatted like this to NSDate object?
By the way, I have seen the website
http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns It
seems that there are many ways to format particular date, but I could not
find what I am doing wrong.

DataView and get a bigger image

DataView and get a bigger image

I am applying this
sample.http://examples.ext.net/#/DataView/Basic/Overview/ it is basic
dataview implimentation.what I wanna do with this sample ,when click the
image inside dataview,show the imahe as a bigger picture.how I can do
that,is there a method related to the iamge which fire

Friday, 27 September 2013

A variable of which a part is variable

A variable of which a part is variable

I have variables that look something like this:
$INFOMonday
$INFOTuesday
In my Bash script, I would like to use the value of todays variable, so to
say. I extracted the day with:
dayofweek=$(date --date=${dateinfile#?_} "+%A")
What I need help with, is doing the following:
echo $INFO$dayofweek
Is there any way of adding a variable as part of a variables name? For
example, if it's monday, the echo would return the value of $INFOMonday.

MVC EditorFor TimeSpan.Hours not binding

MVC EditorFor TimeSpan.Hours not binding

I have model with a TimeSpan (TimeWorked), I want to bind a text box to
the Hours and Minutes fields of the TimeSpan.
@Html.EditorFor(model => model.TimeWorked.Hours)
...
@Html.EditorFor(model => model.TimeWorked.Minutes)
But in the controller post method the values are not part of the posted
model.
How do I achieve this?

Customizing Parsley.js

Customizing Parsley.js

How do I change font size, location, etc. of the Parsley errors? I have
tried adding the following to my stylesheet but it has no effect:
ul.parsley-list-error li {
color: red;
font-size: 9px;
padding: 2px;
left: 10px;
}
I can change the inputs just fine by using the following:
input.parsley-error, textarea.parsley-error {
border: 2px;
border-style: solid;
border-color: #f15d5e;
}

MS ACCESS, how to create unique incrementing ID?

MS ACCESS, how to create unique incrementing ID?

I'm trying to create a database which its ID will get the first 3 letters
of the name then add up with the number. For example, the name is
Administrator, the id should be ADM0001.

Some doubts related to the use of the BorderLayout object

Some doubts related to the use of the BorderLayout object

I am studying Java Swing and I have a doubt related to the use of the
BorderLayout object.
I have this simple example program that create a ToolBar:
package com.andrea.menu;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class ToolBar extends JFrame {
public ToolBar() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar(); // The menu bar containing
the main menu voices
JMenu file = new JMenu("File"); // Creo un menu a tendina
con etichetta "File" e lo aggiungo
menubar.add(file);
setJMenuBar(menubar); // Sets the menubar for
this frame.
JToolBar toolbar = new JToolBar();
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
JButton exitButton = new JButton(icon);
toolbar.add(exitButton);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
add(toolbar, BorderLayout.NORTH);
setTitle("Simple toolbar");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ToolBar ex = new ToolBar();
ex.setVisible(true);
}
});
}
}
So it create a JToolBar object by the line:
JToolBar toolbar = new JToolBar();
and then it put it in the NORTH position of the BorderLayout object by the
line:
add(toolbar, BorderLayout.NORTH);
Reading the documentation I know that:
A border layout lays out a container, arranging and resizing its
components to fit in five regions: north, south, east, west, and center
My doubt is: the BorderLayout object whom it refers? At the external
JFrame container?
It means that it put the toolbar object in the NORTH position of my
JFrame? Or what?
Tnx
Andrea

How can I get the number of rows in the image in Objective-C

How can I get the number of rows in the image in Objective-C

I have a TIFF image as an input to me, which I can transform to NSData,
CGImageRef, etc. So, from any of these objects, is there method present to
extract the number of rows present in the image. I need this information
for my project (in MAC OS X).
Also, I don't think that number of rows in the image would be the same as
height of the image.

Thursday, 26 September 2013

How to retrieve user's input of label in drop down list in rails 3.2?

How to retrieve user's input of label in drop down list in rails 3.2?

The following simple form takes user input with a drop down list of zone.
The zone_id of user input could be retrieved with
params[:controller][:zone_id].
<%=f.input :zone_id, :label => t('Zone'), :collection =>
Zone.where(:active => true).order('ranking_order'), :label_method =>
:zone_name, :value_method => :id, :include_blank => true %>
In our rails 3.2 app however, we also need to retain the label of user's
input which is zone_name here. Is there a way to retrieve label
(zone_name) of user's input in controller? Thanks.

Wednesday, 25 September 2013

phone gap menu Drawer/slide out menu

phone gap menu Drawer/slide out menu

As i want to implement slide out menu/menu drawer with Phonegap
technology. I'm getting that with android but we want to implement it in
Phonegap(java script, CSS, HTML)i.e, when he taps on the menu button the
menu drawer should appear on the mobile screen

Thursday, 19 September 2013

How to ensure node.js child_process.spawn will write error messages to the console

How to ensure node.js child_process.spawn will write error messages to the
console

I'm having a lot of trouble running child processes and getting their
output written to the console. In this episode, I'm trying to use spawn to
run a windows mklink command. The error is the that I don't have
permission to write the file.
My problem, though, is that the error isn't told to me in any way.
The following prints You do not have sufficient privilege to perform this
operation. to the console:
mklink /D C:\some\path\to\my\intended\link C:\path\to\my\folder
But running this in node.js only gives me Error: spawn ENOENT - which is a
highly useless error message:
require('child_process').spawn('mklink',
['/D', 'C:\\some\\path\\to\\my\\intended\\link',
'C:\\path\\to\\my\\folder'],
{stdio:'inherit'})
I get nothing on the console, despite the stdio:'inherit'. I've also tried
the following:
var x = require('child_process').spawn('mklink',
['/D', 'C:\\some\\path\\to\\my\\intended\\link',
'C:\\path\\to\\my\\folder'])
x.stdout.pipe(process.stdout)
x.stderr.pipe(process.stderr)
But no dice. No console output at all. Note that I do get console output
with exec:
var x = require('child_process')
.exec('mklink /D C:\\some\\path\\to\\my\\intended\\link
C:\\path\\to\\my\\folder')
x.stdout.pipe(process.stdout)
x.stderr.pipe(process.stderr)
This shouldn't need any special knowledge of how windows mklink works - my
problem is simply with error reporting with node.js spawn.
What am I doing wrong here?

How to select all elements that don't have a class or id?

How to select all elements that don't have a class or id?

If I want to select the elements that don't have a class (but may have an
ID), the following
$(".entry-container ul:not([class])").addClass("list type-1"); works fine.
If I want to select the elements that don't have an ID (but may have a
class) the following
$(".entry-container ul:not([id])").addClass("list type-1"); works fine.
But what if I want to select all the elements that don't have a class AND
and an ID?

Bad gateway 502 after small load test on fastcgi-mono-server through nginx and ServiceStack

Bad gateway 502 after small load test on fastcgi-mono-server through nginx
and ServiceStack

I am trying to run a webservice API with ServiceStack under nginx and
fastcgi-mono-server.
The server starts fine and the API is up and running. I can see the
response times in the browser through ServiceStack profiler and they run
under 10ms.
But as soon as I do a small load test using "siege" (only 500 requests
using 10 connections), I start getting 502 Bad Gateway. And to recover, I
have to restart the fastcgi-mono-server.
The nginx server is fine. The fastcgi-mono-server is the one that stops
responding after this small load.
I've tried using both tcp and unix sockets (I am aware of a permissions
problem with the unix socket, but I already fixed that).
Here are my configurations:
server {
listen 80;
listen local-api.acme.com:80;
server_name local-api.acme.com;
location / {
root /Users/admin/dev/acme/Acme.Api/;
index index.html index.htm default.aspx Default.aspx;
fastcgi_index Default.aspx;
fastcgi_pass unix:/tmp/fastcgi.socket;
include /usr/local/etc/nginx/fastcgi_params;
}
}
To start the fastcgi-mono-server:
sudo fastcgi-mono-server4
/applications=local-api.acme.com:/:/Users/admin/dev/acme/Acme.Api/
/socket=unix:/tmp/fastcgi.socket /multiplex=True /verbose=True
/printlog=True

Entity Framework Bug, extra decimal places

Entity Framework Bug, extra decimal places

I think I have found a bug in EF5, but I want to verify that this isn't
some weird behavior there is a known fix for (nothing on Google or Bing as
far as I can see).
I'm doing a select on a database value that is 0.06 in a field that is
decimal(18,2). I ran the query I expected EF to generate and got .06 back,
I took the sql profiler query that ef ran an also got .06 back. In my code
however, I got .0675. I checked the EDMX field and it has a matching
precision/scale of 18,2.
My data is "1 version with 4 sets" so my query does a where clause on the
version number and then gets 4 rows back, but only row 3 gets the weird
value. Row 1, 2, and 4 are .03, .04, and .12 and they return as such, but
row 3 is .06 but returns as .0675.
Last thing that could be useful is the EF proxies are the only part that
is wrong. If I select the EF Proxies, that is when this pops up, but if I
do the select into my viewmodel the correct value is returned.
_entities.Sets.Where(x => x.VersionID == versionID) // ---> returns bad value
_entities.Sets.Where(x => x.VersionID == versionID).Select(x => new VM {
Rate = x.Rate}) // ---> returns correctly
Any ideas on this behavior?

Music listen and download App for Android

Music listen and download App for Android

Hi,
is there any source code of Android application(ex. MusicManic, etc) for
listening and downloading music? I want to understand architecture of that
sort applications.

jQuery send more then one formdata

jQuery send more then one formdata

Currently my code is
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
// The example input, doesn't have to be part of the upload form:
var adultinput = $('#adult');
data.formData = {adult: adultinput.val()};
if (!data.formData.adult) {
input.focus();
return false;
}
});
Which works just fine to send a post data with adult value from the html code
However there's another input form called thumbsize which i want to send
as well,
I tried
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
// The example input, doesn't have to be part of the upload form:
var adultinput = $('#adult');
var thumbsize = $('#thumbsize');
data.formData = {adult: adultinput.val()};
data.formData = {thumbsize: thumbsize.val()};
if (!data.formData.adult) {
input.focus();
return false;
}
});
But it doesn't seem to work, is there anyway i can go about sending
another parameter?
Thanks!

Websocket Server with Python and Tornado. Always "Connection Closed"

Websocket Server with Python and Tornado. Always "Connection Closed"

I've tried to create a Websocket-Server with Python and Tornado in the
same steps as you can see in this tutorial:
http://mbed.org/cookbook/Websockets-Server
The Server is running and I can see acitvations in the shell. But the main
problem is, that I only get the message "connection closed" when I open
the HelloWorld.html. The same message i can see in the server log and the
websocket handshake is not running. I do not understand the problem and
need help.
The OS is Ubuntu and webserver is Apache2.
many thanks!
Chris

Wednesday, 18 September 2013

Jekill pages on GitHub: how does it work?

Jekill pages on GitHub: how does it work?

I have my gh-pages branch for my project. I am trying to create some
documentation for it. In GitHub, I read that every time I push things onto
the GitHub server, the page is actually fed through to Jakill.
I haven't installed Jakill locally. For now, I just want to use GitHub's,
and essentially act as a "user".
But... how does it actually work? I created a page .markdown, and saw that
the equivalent .html is created -- and marked up. Like this:
---
title: This will be used as the title-tag of the page head
---
Now, let's see.
# Is this working?
But... how do I find out how to actually use Jekill?
I am aware of http://jekyllrb.com/docs/ but I still can't quite figure out
what else I can do, and -- more importantly -- how to simply place a
markdown file that will be "templated" with the current template?
Thank you!

Entity framework and using composite primary keys?

Entity framework and using composite primary keys?

I don't seem to be able to get the following relationship done. MyEvent
has composite primary key on UserId and LocationId. It also has a virtual
property that is based on these 2 primary keys.
public class MyEvent
{
public string UserId {get; set;}
public string LocationId {get; set;}
public virtual EventDescription EventDescription {get; set;}
}
public MyEventConfiguration()
{
HasKey(a => new { a.UserId, a.LocationId});
HasRequired(a => a.EventDescription).WithMany().HasForeignKey(a => new
{ a.UserId, a.LocationId }).WillCascadeOnDelete(false);
}
I get the following error:
One or more validation errors were detected during model generation:
System.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in
Role 'MyEvent_EventDescription_Source' in relationship
'MyEvent_EventDescription'. Because the Dependent Role refers to the key
properties, the upper bound of the multiplicity of the Dependent Role must
be '1'.

how do I add settings to wordpress add page

how do I add settings to wordpress add page

I am working with Wordpress 3.6
I've seen some plugins that add settings to the page you use to add/edit
pages on your site.
How can I add my own settings to this page as well?

The theory behind frameworks like Prism [on hold]

The theory behind frameworks like Prism [on hold]

I am learning Microsoft's framework Prism and I feel like I am missing
some theoretical stuff. This is not just another library, this is a whole
new way of doing software engineering. Creating flexible and modular big
apps is a big thing, I assume there is something behind.
I don't know what is the theory behind, I just know there is one. Can you
please recommend books or any resources? Or even topic names, then I could
find resources on those myself.
The way I got myself into Prism is I am working on a WPF project that will
grow big after a while, and people recommended Prism as MVVM framework and
much more.

What is cache in C++ programming?

What is cache in C++ programming?

Firstly I would like to tell that I come from a non-Computer Science
background & I have been learning the C++ language. I am unable to
understand what exactly is a cache? It has different meaning in different
contexts. I would like to know what would be called as a cache in a C++
program? For example, if I have some int data in a file. If I read it &
store in an int array, then would this mean that I have 'cached' the data?
To me this seems like common sense to use the data since reading from a
file is always bad than reading from RAM. But I am a little confused due
to this article. It says that reading data from cache is much faster than
from RAM. I thought RAM & cache were the same. Can somebody please clear
my confusion?

TextBox error with large string inside Updatepanel

TextBox error with large string inside Updatepanel

I am getting an error when trying to load more then 2000 characters in
asp:TextBox inside update-panel.
I am loading text-box with simple button click.
But if I try to load for example 50 characters, it is working just fine.
Dont really know how to solve this issue.

Mysql select query bug with '7.56'

Mysql select query bug with '7.56'

This seems to be a very strange issue and I can't seem to get to the
bottom of the cause. When running a mysql select statement we keep getting
no results returned but only when the value comes to a quoted '7.56'. if
we run the same query without the quotes or using a different number it
works as expected. Example queries and results below:
SELECT * FROM orders WHERE itemsTotal = '7.56' LIMIT 0 , 30
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0334
sec )
SELECT * FROM orders WHERE itemsTotal = 7.56 LIMIT 0 , 30
Showing rows 0 - 0 ( 1 total, Query took 0.0297 sec)
Now if you change the items total to 7.57:
SELECT * FROM orders WHERE itemsTotal = '7.57' LIMIT 0 , 30
Showing rows 0 - 0 ( 1 total, Query took 0.0280 sec)
SELECT * FROM orders WHERE itemsTotal = 7.57 LIMIT 0 , 30
Showing rows 0 - 0 ( 1 total, Query took 0.0284 sec)
This is running mysql 5.5.24 for testing on local host and mysql 5.0.95 in
live environment. Same results when running this query from a PHP file and
phpmyadmin. If anyone can spot an obvious error, please let me know!

Tuesday, 17 September 2013

Is there no difference between a function address and the function address' address?

Is there no difference between a function address and the function
address' address?

void f()
{}
void test()
{
auto fn_1 = f;
auto fn_2 = &f;
assert(fn_1 == fn_2); // OK
fn_1(); // OK
fn_2(); // OK
(*fn_1)(); // OK
(*fn_2)(); // OK
}
Are these behaviors explicitly defined by the C++ standard?

Is there a bottleneck here

Is there a bottleneck here

I have run some tests on an IIS (on EC2 @ 7GB RAM + 20 ECUs + ~600MBit
upload) server using JMeter and I'm unsure if there is a bottleneck. It is
serving static content only (images, javascript). JMeter is set to emulate
browser behaviour which downloads all static in parallel (7 per user).
Test 1:
Set to simulate 10 users (7 concurrent connections each)
Averages
Connections = 32
Get requests / sec = 237
CPU = 1%
Bytes sent / sec= ~ 8.5 million
Test 2:
Set to simulate 50 users (7 concurrent connections each)
Averages Connections = 82
Get requests / sec = 236
Bytes sent / sec = ~ 8.5 million
CPU = 1%
The connections average increases yet the requests don't so I suspect
there is something causing a bottleneck. Should the server be able to
handle more requests per second?

composer laravel create project

composer laravel create project

I'm trying to use laravel, when I start a project and type composer
create-project /Applications/MAMP/htdocs/test_laravel in terminal it shows
[InvalidArgumentException]
Could not find package /applications/mamp/htdocs/test_laravel with stabilit
y stable.
and
create-project [-s|--stability="..."] [--prefer-source] [--prefer-dist]
[--repository-url="..."] [--dev] [--no-dev] [--no-plugins]
[--no-custom-installers] [--no-scripts] [--no-progress] [--keep-vcs]
[package] [directory] [version]
How to fix it ?
and is this step equal to create folder and file like I download from
laravel git laravel-master.zip ?

Modify File Contents based on starting element/string

Modify File Contents based on starting element/string

I have a HL7 File like:
MSH|^~\&|ABC|000|ABC|ABC|0000||ABC|000|A|00
PID|1|000|||ABC||000|A||||||||||
PV1|1|O||||||||||||||||||||||||||||||||||||||||||
OBR|1|||00||00|00|||||||||||ABC|00|0|0||||A|||||00||ABC|7ABC||ABC
OBX|1|ABC|ABC|1|SGVsbG8=
OBX|2|ABC|ABC|1|XYTA
OBX|3|ABC|ABC|1|UYYA
I have to read only OBX segments and get the text after 5th pipe (|).
Currently I am doing this with:
StreamReader reader = new
StreamReader(@"C:\Users\vemarajs\Desktop\HL7\Ministry\HSHS.txt");
string strTest = reader.ReadToEnd();
string OBX1 = strTest.Split('\n')[3];
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\OBX.txt", OBX1 +
Environment.NewLine);
List<string> list = new List<string>();
using (reader)
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
if (line.StartsWith("OBX|") == true)
{
string txt = line.Split('|')[5];
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\test.txt",
txt+Environment.NewLine);
}
else
{
//string x = line + Environment.NewLine + OBX1.Distinct();
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt",
line + Environment.NewLine);
File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\OBX.txt",
OBX1.Distinct().ToList() + Environment.NewLine);
}
This extracts the contents of each OBX segment at element 5 (after 5
pipes) and writes out a file called test.text, in my else statement I am
trying to modify the original HL7 file by deleting OBX|2 and OBX|3 to have
only One OBX|1 as we expect the number of OBX segments inside the HL7 file
to reach 40 or more and we don't wan't to keep those many while returning
the message to its messagebox.
My current code is trying to do this, but adds OBX|1 for each segment that
is not starting with OBX| (this is due my logic), how do I avoid this ?

Python - % Symbol and Invalid Syntax

Python - % Symbol and Invalid Syntax

I'm creating a Python script for my Raspberry Pi Radio. The Pi used
mpd/mpc to play music, and I can type in the following command in Terminal
to see information about the currently playing station:
mpc current -f "[%position%]"
This will show me:
11
As the 11th radio station is playing.
My problem is, when I put this in Python to extract this number to use as
part of my code, it gives me this: (I get a ^ under the first % symbol)
f=os.open("mpc current -f "[%position%]"")
SyntaxError: invalid syntax
This seems odd as I have already used similar commands in a Python script
which have worked, however they have not had the % symbol in them. Such
as:
f=os.popen("mpc current")
I am still learning Python so would appreciate it if someone could correct
me here, as the command seems legit to me, especially with the "" either
side. I even tried using ' instead of ", but if I do, the command doesn't
work.
Many thanks

Access Id of parent entity without actually loading it in EntityFramework code first

Access Id of parent entity without actually loading it in EntityFramework
code first

I have two entities:
public class Parent
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Child
{
public Guid Id { get; set; }
public string Name { get; set; }
public Parent Parent { get; set; }
}
I can query Child entity with or without parent by using Include.
public void Test()
{
var child = context.Set<Child>().Include(x => x.Parent)
.FirstOrDefault(x => x.Id == Guid.Parse("<some_id>"));
}
But in some cases I have all Parent entities already cached in memory, And
i want to skip join and query Child entity with only Id propery loaded.
And then get actual Parent from cache by Id:
public void Test()
{
var cachedParents = new List<Parent>();
var child = context.Set<Child>()
.FirstOrDefault(x => x.Id == Guid.Parse("<some_id>"));
var parent = cachedParents.FirstOrDefault(x => x.Id == child.Parent.Id);
}
But child gets loaded with child.Parent == null.
Is there some way to have child.Parent to be loaded or just access
child.Parent.Id (ParentId column) property?

Sunday, 15 September 2013

Windows Script to restart remote windows tomcat service

Windows Script to restart remote windows tomcat service

Please could you share some script to restart windows tomcat services
remotely? Script should contain the list of IP address that should go and
restart the tomcat services on remote windows machine. Please help
Thanks Reyaz

UIActivityViewController rotation problems

UIActivityViewController rotation problems

I am having problem with the UIActivityViewController, I instantiate a new
instance each time user presses the 'share' button, but it will not rotate
properly. Is my code lacking something essential?
When I rotate only the status bar and the UIActivityViewController will
rotate (not the view in the background) and also sometimes the
activityView´s size will be wrong.
UIActivityViewController *activityVC;
// Init sharing items and View Controller
NSString *message = [NSString stringWithFormat:@""];
UIImage *imageToShare = [UIImage imageNamed:@"imageName"];
NSArray *postItems = @[message, imageToShare];
activityVC = [[UIActivityViewController alloc]
initWithActivityItems:postItems
applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:^() {
[activityVC setCompletionHandler:^(NSString *activityType, BOOL
completed) {
// Completed
}];
}];

Naming Convention for ViewModel Child Objects

Naming Convention for ViewModel Child Objects

I am building an ASP.Net MVC application using a ViewModel approach to
keep my domain entities separate from the "models" used by my UI. I am
using the following convention for naming my ViewModel classes.
ViewModelName = ViewName + "ViewModel". For example:
Index + ViewModel = IndexViewModel
So far, so good, this is a fairly common pattern and there is a lot of
guidance on this topic on StackOverflow and elsewhere. My question
concerns child objects used by my ViewModels. If my ViewModel requires a
class with properties identical to my a domain model object, I simply
include the domain model within my ViewModel. For example:
public class PersonViewModel
{
public int PersonID { get; set; }
public Address Address { get; set; }
public string SomeOtherProperty { get; set; }
}
However, I am not sure what naming convention to use when I need a child
object with different properties from my domain model. For example if
Address needed a few additional properties besides what is in the Address
domain model, what should I call it? I considered AddressViewModel like
so:
public class PersonViewModel
{
public int PersonID { get; set; }
public Address AddressViewModel { get; set; }
public string SomeOtherProperty { get; set; }
}
but that just doesn't feel right to me. My gut instinct is that the
ViewModel suffix should only be for the top level ViewModel.
I am looking for suggestions from other developers on what naming
conventions they use in this scenario, specifically what would you call
the child object in this case?

Wired behavior of ExecutorService

Wired behavior of ExecutorService

I have application that pings several IPs at same time. To do that I used
ExecutorService to create threads. Problem is when I call function that is
performing pinging, application ping twice same IP address. When I call
PING function first time, all IPs are pinged correctly and program works
fine but problem is when I submit PINGing again. On second testing
(pinging) each IP address is pinged twice. Here is code that I am using
Here I call function PING:
TimeToPing = new PingTime(7000, IPS, maxScans, NUMTHREADS, ttl, this,
InsertedSQLID, ID_IP, 1);
Thread runThread = new Thread(TimeToPing);
TestingISRunningOrNot=true;
runThread.start();
Here is TimeToPing class (that invoke ExecutorService)
public void run(){
String time;
while (CurrentPingNumber<=maxScans){
try {
Thread.sleep(frequency);//frequency is 7000
} catch (InterruptedException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null,e.getMessage(),"ERROR",JOptionPane.ERROR_MESSAGE);
}
for (String IP : IPS)
exec.submit((new
PingThemAll(IP,ttl,serverGUI,sqlInsertedID,CurrentPingNumber)));
}
CurrentPingNumber++;
}
exec.shutdown();
}
And here is function that PING IPs:
PingThemAll(String IP, int ttl, PingServerGUI PingServerGUI, int
sqlInsertedID, int CurrentPingNumber){
this.IP=IP;
this.ttl=ttl;
pingServerGUI = PingServerGUI;
this.sqlInsertedID=sqlInsertedID;
this.CurrentPingNumber=CurrentPingNumber;
}
public void run(){
InetAddress address;
System.out.println("Pinging: "+IP);
try {
address = InetAddress.getByName(IP);
try {
if (address.isReachable(ttl)) {
pingServerGUI.appendLogs(sdf.format(new Date())+": "+IP +
" reachable\n");
} else {
pingServerGUI.appendLogs(sdf.format(new Date())+":
"+IP + " is not reachabld\n");
}
} catch (IOException e) {
return;
}
} catch (UnknownHostException e) {
return;
}
}
HERE IS PROGRAM OUTPUT:
When I call function for first time:
Pinging 192.168.1.1
Pinging 192.168.111.1
Pinging 192.168.196.1
Pinging 192.168.1.2
And here is output when I call function for second time:
Pinging 192.168.1.1
Pinging 192.168.111.1
Pinging 192.168.196.1
Pinging 192.168.1.2
Pinging 192.168.1.1
Pinging 192.168.111.1
Pinging 192.168.196.1
Pinging 192.168.1.2

access public variables of a class from another class of an application C#

access public variables of a class from another class of an application C#

I have a public partial class XYZ: Form. I want to use some public data
(lists etc.) of this class in other class(different file) within same
assembly. XYZ is connected to Database, so it has data, whereas the other
class can get data only from class XYZ.
The other class, let say ABC is a COM visible class library, which has 2
interfaces and 2 classes that implement them. ABC is invoked by Perl and
needs data from XYZ.
How should that be done.
When I try
List<a> lst;
XYZ objxyz= new XYZ();
lst= objxyz.lstxyz;
int count= lst.count();
I get count=0; even though lstxyz has some rows. This happens because when
i create an object through 'new' keyword, it doesnt have any data, so
lstxyz count=0.
How can I get data from other class?
Please help me.Thanks a lot.

How To Remove Object from NSMutableArray After Switching Tab View

How To Remove Object from NSMutableArray After Switching Tab View

So I am trying to remove all objects in an array, [myMutableArray
removeAllObjects], whenever a button is pushed or the tab view changes. I
know that for a button, I can use prepareForSegue:(UIStoryboardSegue
*)segue sender:(id)sender, and it works. But how do I do the same with a
tab?
I am doing this because I am using Parse, a web backend service, and I am
querying for the user's friends and putting it on a tableview, but unless
I remove all the objects from the array, I get duplicates of the names.
Any help is greatly appreciated!!

What to use instead of Deprecated GetFNum in OS X SDK 10.8

What to use instead of Deprecated GetFNum in OS X SDK 10.8

I have the following code, which I want to convert from MacOS SDK 10.6 to
SDK 10.8:
short theFontNum;
Str255 fontType = "Helvetica";
::GetFNum(fontType, &theFontNum);
::SetMenuFont (newMenu, theFontNum, 11);
GetFNum is deprecated in SDK 10.8. Can someone suggest what can I use
instead?
Thanks!

Saturday, 14 September 2013

How to make ServiceStack work with existing MVC/Service/Repository pattern

How to make ServiceStack work with existing MVC/Service/Repository pattern

I am trying to wrap my head around ServiceStack and utilizing it to expose
RESTful services.
I am currently using a MVC/Service/Repository/UnitOfWork type pattern
where a basic operation to get customers might look like this:
MVC Controller Action --> Service Method --> Repository --> SQL Server
My questions are:
What do my SS services return? Domain objects? Or do I return a DTO that
has a collection of customers? And if so, what are the customers? Domain
objects or view models or ??
Should the SS services replace my service layer?
Am I taking the totally wrong approach here?
I guess I am a little confused how to make all of this live side-by-side.
Domain Object
public class Customer
{
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
}
View Model
public class CustomerViewModel
{
public int Id {get;set;}
public string FirstName {get;set;}
....
}
Controller
public class CustomersController : Controller
{
ICustomerService customerService;
public CustomersController(ICustomerService customerService)
{
this.customerService = customerService;
}
public ActionResult Search(SearchViewModel model)
{
var model = new CustomersViewModel() {
Customers =
customerService.GetCustomersByLastName(model.LastName); //
AutoMap these domain objects to a view model here
};
return View(model);
}
}
Service
public class CustomerService : ICustomerService
{
IRepository<Customer> customerRepo;
public CustomerService(IRepository<Customer> customerRepo)
{
this.customerRepo = customerRepo;
}
public IEnumerable<Customer> GetCustomersByLastName(string lastName)
{
return customerRepo.Query().Where(x =>
x.LastName.StartsWith(lastName));
}
}

How to maintain the custom methods while using generated classes using RIA services and entity models?

How to maintain the custom methods while using generated classes using RIA
services and entity models?

How to maintain the custom methods while using generated classes using RIA
services and entity models ?
Everytime the model changes, the only way to generate methods for these
entities is to regenerate the DomainService class. But if we do that, the
custom methods that we have created in the DomainService class gets
overwritten. Is there a better way to do this?

Null Pointer Exception for Java Assignment

Null Pointer Exception for Java Assignment

I have an assignment that I must take URLs in from a file (or standard
input if no file is given) and then count the number of times the scheme
is equal to certain things and when the domain is equal to certain things.
This is a part of my code that takes the input, splits it into the scheme
and domain, and then increases variables if certain words are found.
However, I keep getting NullPointerExceptions and I cannot find out why.
Right now, this code comes with an error at line 16. Any help would be
appreciated.
File file = new File("input");
Scanner scan = new Scanner("input");
Scanner scan2 = new Scanner(System.in);
while (!scan.next().equals("end") || !scan2.next().equals("end")){
if (scan.hasNext() == true)
url = scan.nextLine();
String[] parts = url.split(":");
scheme = parts[0];
schemeSP = parts[1];
if (scheme == "http")
httpCt++;
if (scheme == "https")
httpsCt++;
if (scheme == "ftp")
ftpCt++;
else otherSchemeCt++;
for (int j=0; j<schemeSP.length(); j++)
if (schemeSP.charAt(j) == '.')
domain = schemeSP.substring(j);
if (domain == "edu")
eduCt++;
if (domain == "org")
orgCt++;
if (domain == "com")
comCt++;
else otherDomainCt++;
fileLinesCt++;
totalLinesCt++;
}

Sketchup API for navigating around a model (eventually to integrate with Leap Motion)

Sketchup API for navigating around a model (eventually to integrate with
Leap Motion)

I'm trying to use to SketchUp API to navigate around 3D models (zoom, pan,
rotate, etc). My ultimate aim is to integrate it with a Leap Motion app.
However, right now I think my first step would be to figure out how to
control the basic navigation gestures via the Sketchup API. After a bit of
research, I see that there are the 'Camera' and the 'Animation'
interfaces, but I think they would be more suited to 'hardcoded' paths and
motions within the script.
Therefore I was wondering - does anyone know how I can write a plugin that
is able to accept inputs from another program (my eventual Leap Motion App
in this case) and translate it into specific navigation commands using the
Sketchup API (like pan, zoom, etc). Can this be done using the 'Camera'
and the 'Animation' interfaces (in some sort of step increments), or are
there other interfaces I should be looking at.
As usual, and examples would be most helpful.
Thanks!

BPEL conflicting Receive

BPEL conflicting Receive

I have a scenario where a BPEL process with a parallel flow is calling an
asynchronous process in parallel and waits for their callbacks. I added
two correlation sets one to correlate to the calling BPEL process instance
and one to correlate to the Receive in which flow path. But I am receiving
a conflictingReceive fault response. And the error:
ERROR [PICK] org.apache.ode.bpel.common.FaultException: {Selector
plinkInstnace= {PartnerLinkInstance
partnerLinkDecl=OPartnerLink#41,scopeInstanceId=9601},ckeySet=[{CorrelationKey
setId=AsynchCorr, values=[hello]}, {CorrelationKey setId=FlowCorr,
values=[flow
2:]}],opName=onResult,oneWay=yes,mexId=<null>,idx=0,route=one}
I am using Apache ODE with Tomcat. Can you help me find a solution for
this problem, it is driving me mad!! I can send you sample projects if you
can help.

How to select various Task Continuation strategies in TPL

How to select various Task Continuation strategies in TPL

Consider the following continuation:
Task.Factory.StartNew(()=>
{
MethodA();
})
.ContinueWith((t)=>
{
MethodB();
})
.ContinueWith((t)=>
{
MethodC();
});
As I know the execution will be like this:
MethodA executes.
MethodB executes after MethodA completes.
MethodC executes after MethodB completes.
What if I wanted the MethodC to continue after MethodA completes.(instead
of waiting for MethodB)
I'm looking for a solution other than manually declaring the task
variables, instead I want to use the method sequencing by the fluent
factory.

How powerful is "ASP.NET Web Pages - Web Matrix" introduced in .NET 4.5?

How powerful is "ASP.NET Web Pages - Web Matrix" introduced in .NET 4.5?

I want to know how powerful is "ASP.NET Web Pages - Web Matrix" introduced
in .NET 4.5 comparing MVC 4? Is it suitable for develop a large scale web
application and would it prefer to other web development technologies? if
not, what is the purpose Microsoft introduce it?

Friday, 13 September 2013

How change and blink the title of the browser when the user goes to other tab or minimizes the browser?

How change and blink the title of the browser when the user goes to other
tab or minimizes the browser?

I want to know that how to change the title of the browser and set it to a
blinking text when user opens other tab or just minimizes the browser.

HTML5 Generating 3D content to display on iPhone

HTML5 Generating 3D content to display on iPhone

How can I render 3D objects representing contents (pics, movies) with
HTML5 so I can see them in safari or chrome on my iPhone? I am trying some
options with CSS3 but I was wondering if I can use some other
alternatives.
Thank you. Cyrus

Pregmatch not matching correctly in php

Pregmatch not matching correctly in php

Having trouble understanding what's going on here. Comments within the
code explain. Thanks in advance. To make it easier to read some code bits
are missing like the writing to the DB part. But the problem is isolated
to these lines.
if (filter_var($email, FILTER_VALIDATE_EMAIL) == TRUE and
preg_match("/^[\w ]+$/", $address_one) == TRUE and
preg_match("((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})",
$password) == TRUE) {
//When given a valid email/address/password the code successfully gets to
this point and inserts into a DB
} else {
//When it fails validation with an invalid email/password/address it
drops in here
//but then it doesn't change error code variable...
$errorcode = "IHAVENOTCHANGED";
if (filter_var($email, FILTER_VALIDATE_EMAIL) == FALSE) {
$errcode = " email,";
}
if (preg_match("/^[\w ]+$/", $address_one) == FALSE) {
$errcode = " address line 1,";
}
if (preg_match("((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})",
$password) == FALSE) {
$errcode = " password,";
}
writetolog("LoginCreation", "Login failed due to invalid input: " .
$errorcode . " - user: " . $email);
echo "Invalid data for $errorcode please try again --
ADDRESS=$address_one -- EMAIL=$email -- PASS=$password";
}

Recursive method in Java that calculates factorials not working

Recursive method in Java that calculates factorials not working

Coding a recursive method in Java that calculates factorials.
Unfortunately it's not working, and I suspect it's because of the 2
parameters that I wasn't too sure about -- which I surrounded with
asterisks. Are those the correct parameters that belong there? Or do I
need to change them to something else and why? Thanks in advance!
public fact(n)
{
return this.factHelp(n, ***n+1*** );
}
private factHelp(n, result)
{
if (n == 0)
return result;
else
return this.factHelp(n – 1, ***result***);
}

How to format a tring with thousands separation and decimal comma?

How to format a tring with thousands separation and decimal comma?

I have some strings:
string amount = "123456";
string amount2 = "123456.78";
I want the output to be:
amount: 123.456,00
amount2: 123.456,78
I already looked here, but this does not work for my example.

php - access folder on another site on the same server

php - access folder on another site on the same server

I have a dedicated server running centos, I have serval sites on this
server and all of them are mine. I want use php to upload files -videos-
where the file exit on the other site.
let me explain /home/user1/public_html/uploads => the videos are here =>
domain.com
/home/user2/public_html/upload.php => the php file to upload on another
site on the same server => domain.net
how can I let the other site upload a video from my other website that on
the same server.
I wish that was clear

Thursday, 12 September 2013

Placing small image button on right corner of a image

Placing small image button on right corner of a image

I am able to take the pictures and put it grid view but, Has a picture is
taken i want to place small image button on right corner of a image.

Why does VC++ 2013 not support non-static data member initializers as promised

Why does VC++ 2013 not support non-static data member initializers as
promised

According to
http://msdn.microsoft.com/en-us/library/vstudio/hh567368%28v=vs.120%29.aspx,
VC++ 2013 now supports non-static data member initializers.
However, the following code is rejected by VC++ 2013:
struct A
{
const int n = 0; // error C2864
};
error C2864: 'A::n' : only static const integral data members can be
initialized within a class
What's the root cause? Is it a compiler bug?

How to use multiple Input Dialogs (New to Java)

How to use multiple Input Dialogs (New to Java)

I am trying to create a program that asks a user for a sentinel value (a
value to enter when they want to end the list). It then asks the user to
enter numbers until they re-enter the sentinel value. It then figures out
the max number in the list. I'm very new to Java, and whenever I run the
program is just asks for the sentinel value then does nothing else (never
pops up the second input dialog). I'm sure it's something simple that I'm
doing wrong, but I can't figure it out. Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class HW1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int max;
int sentinel;
int count=0;
JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel=input.nextInt();
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel
+" to end.");
number = input.nextInt();
max = number;
while (number!=sentinel){
count +=1;
if (number>max)
max=number;
JOptionPane.showInputDialog("Please enter numbers. Enter" +
sentinel +" to end.");
number = input.nextInt();
}
if (count!=0){
JOptionPane.showMessageDialog(null, "The max is:" + max);
}
}
}

git: can I checkout a hotfix branch in a dev environment(with an unmerged dev branch) or will that cross branches?

git: can I checkout a hotfix branch in a dev environment(with an unmerged
dev branch) or will that cross branches?

I'm new to having git set up for multiple users. I typically used it by
myself with only one branch. I have a questions that I couldn't find safe
answer to via Google:
If I'm currently pulling a feature development branch into my dev server
to test the feature and I suddenly discover the need for a hotfix can I
re-branch(checkout) the hotfix branch (part of master not dev), pull the
files in and start working on/testing a hotfix or will my next "git add ."
add the files from the feature branch(which are still on the server) to
the hotfix branch therefore mixing the two branches?

jdk 1.7.25 doesn't work for my project over windows server 2003

jdk 1.7.25 doesn't work for my project over windows server 2003

I have a jdk version updated from jdk 1.7.21 to jdk 1.7.25, build on
Solaris 10 and production runs over windows server 2003. I have not
updated any java code this time, since build was a success, I would update
java code if compile hits an error, e.g on jdk from 1.6.45 to jdk 1.7.xx,
I have to update a few files to match jdk 1.7 API changes, then it's
running fine, there was a few updates from jdk 1.7.xx to jdk1.7.21, each
time updated was fine. But this time, after build jdk 1.7.25 from 1.7.21
source code, compile was ok, but run time the server runs up ok, but
client is stuck in the middle - there is a SESSION_ADAPTER build failed,
we used OPNORG 1.2 which is over 10 years old, and a 3rd party binary code
only. Wondering where is the really problem on jdk 1.7.25?
I used "old school" skills to print out which line was broken, it looks
stuck in the function of narrow(orb), got an Exception of "BAD_PARAM":
Here is the java file(It's generated by CORBA IDL, we do not have source
of OPNORG):
package DPEM.src.presentation.adaptation.adaptationIfc;
//
// Helper class for : SessionAdapter
//
// @author OpenORB Compiler
//
public class SessionAdapterHelper
{
//
// Insert SessionAdapter into an any
// @param a an any
// @param t SessionAdapter value
//
public static void insert( org.omg.CORBA.Any a,
DPEM.src.presentation.adaptation.adaptationIfc.SessionAdapter t )
{
a.insert_Object( t , type() );
}
//
// Extract SessionAdapter from an any
// @param a an any
// @return the extracted SessionAdapter value
//
public static
DPEM.src.presentation.adaptation.adaptationIfc.SessionAdapter extract(
org.omg.CORBA.Any a )
{
if ( !a.type().equal( type() ) )
throw new org.omg.CORBA.MARSHAL();
try {
return
DPEM.src.presentation.adaptation.adaptationIfc.SessionAdapterHelper.narrow(
a.extract_Object() );
}
catch ( org.omg.CORBA.BAD_PARAM ex ) {
throw new org.omg.CORBA.MARSHAL();
}
}
//
// Internal TypeCode value
//
private static org.omg.CORBA.TypeCode _tc = null;
//
// Return the SessionAdapter TypeCode
// @return a TypeCode
//
public static org.omg.CORBA.TypeCode type()
{
if ( _tc == null ) {
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
_tc = orb.create_interface_tc(id(),"SessionAdapter");
}
return _tc;
}
//
// Return the SessionAdapter IDL ID
// @return an ID
//
public static String id()
{
return _id;
}
private final static String _id =
"IDL:adaptation.presentation.src.DPEM/adaptationIfc/SessionAdapter:1.0";
//
// Read SessionAdapter from a marshalled stream
// @param istream the input stream
// @return the readed SessionAdapter value
//
public static
DPEM.src.presentation.adaptation.adaptationIfc.SessionAdapter read(
org.omg.CORBA.portable.InputStream istream )
{
return( DPEM.src.presentation.adaptation.adaptationIfc.SessionAdapter
)istream.read_Object(
DPEM.src.presentation.adaptation.adaptationIfc._SessionAdapterStub.class
);
}
//
// Write SessionAdapter into a marshalled stream
// @param ostream the output stream
// @param value SessionAdapter value
//
public static void write( org.omg.CORBA.portable.OutputStream ostream,
DPEM.src.presentation.adaptation.adaptationIfc.SessionAdapter value )
{
ostream.write_Object((org.omg.CORBA.portable.ObjectImpl)value);
}
//
// Narrow CORBA::Object to SessionAdapter
// @param obj the CORBA Object
// @return SessionAdapter Object
//
public static SessionAdapter narrow( org.omg.CORBA.Object obj )
{
if ( obj == null )
return null;
if ( obj instanceof SessionAdapter )
return ( SessionAdapter)obj;
if ( obj._is_a( id() ) )
{
_SessionAdapterStub stub = new _SessionAdapterStub();
stub._set_delegate(
((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate() );
return stub;
}
throw new org.omg.CORBA.BAD_PARAM();
}
//
// Unchecked Narrow CORBA::Object to SessionAdapter
// @param obj the CORBA Object
// @return SessionAdapter Object
//
public static SessionAdapter unchecked_narrow( org.omg.CORBA.Object obj )
{
if ( obj == null )
return null;
if ( obj instanceof SessionAdapter )
return ( SessionAdapter)obj;
_SessionAdapterStub stub = new _SessionAdapterStub();
stub._set_delegate(
((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate() );
return stub;
}
}
I have no idea for the past a 2 weeks, hopefully can borrow a little of
java/IDL skills from you gurus.
Thanks, Curtis

Registration script not working?

Registration script not working?

I created a registration script from bits and pieces that I have learned
from books on PHP. Unfornately, when testing it on local host (after
submitting test registration page), it displays the source of the PHP
script in browser. Is there something I'm doing wrong? Does any know any
open-source registration scripts?
Thanks
<?php
$submitted = $_POST["submitted"];
if ($submitted == 'yes') {
$firstName = mysql_real_escape_string($_POST["firstName"]);
$lastName = mysql_real_escape_string($_POST["lastName"]);
$eMail = mysql_real_escape_string($_POST["eMail"]);
$password = mysql_real_escape_string($_POST["password"]);
$confirmPassword = mysql_real_escape_string($_POST["confirmPassword"]);
// Kill script if input fields are blank
if ($firstName == '' or $lastName == '' or $eMail == '' or $password ==
'' or $confirmPassword == '')
{
die();
}
// Check if passwords match
if ($password != $confirmPassword)
{
die();
}
// Check if password is appropriat length
$passwordLength = strlen($password);
if ($passwordLength < 6 or $passwordLength > 30) {
die();
}
//////////////////////////
// Insert into database //
//////////////////////////
// Signup time in Unix Epoch
$time = time();
// Human readable date
$date = date("F jS, Y g:i:s A");
$sql = "INSERT into userInfo (firstName, lastName, password, eMail,
time, date) VALUES ('$firstName', '$lastName', '$password', '$eMail',
'$time', '$date')";
$sqlserver = "localhost";
$sqluser = "xxxxxx";
$sqlpassword = "xxxxxx";
mysql_connect($sqlserver, $sqluser, $sqlpassword) or die(mysql_error());
mysql_select_db("store");
// Check database if username already exists
$newEmail = $eMail;
$checkUsername = mysql_query("SELECT eMail FROM userinfo WHERE eMail =
'$newEmail'");
$numRows = mysql_num_rows($checkUsername);
if ($numRows > 0) {
die();
}
mysql_query($sql) or die(mysql_error());
mysql_close();
header("Location: http://store.viddir.com/login/");
exit;
}
else {
die();
}
?>

Displaying the day on the calendar from the textbox generated

Displaying the day on the calendar from the textbox generated

may i ask on how to display the day (Monday, tuesday,etc) from the textbox
which had a datepicker javascript, into the textbox which would echo the
day from the datepicker.
example: textbox1(datepicker, when the user selects september 12 2013, it
would echo Thursday to textbox2) textbox2 = Thursday. Thank you.

SQLite3 in Embedded Linux NOR MTD Flash

SQLite3 in Embedded Linux NOR MTD Flash

The embedded system has M68K Architecture (MCF547x based), with colilo and
linux kernel 2.6.10 it used MTD (memory Type Device) NOR Flash (Spansion
make). There is around 32 MB of data to be managed (all in forms of
records) and memory available is 40MB as an MTD partition (JFFS2
filesystem). I wanted to understand the performance related problems or
any other memory related problems which i can encounter while doing this
exercise of using SQlite3 (amalgamation version).
By Memory related problem i meant frequent defrag operaton of memory
partition (since that 32 MB of database will be modified almost every
second).
Any experience/insights on this requirement will be very much helpful.
Please share your experience on what has to be taken care.

Hoe to show largest digit from a number - javascript

Hoe to show largest digit from a number - javascript

I have this function that calculates the largest digit from a number:
function maxDigit(n){
if(n == 0){ return 0;}
else{
return Math.max(n%10, maxDigit(n/10));
}
}
console.log(maxDigit(16984));
and the returned value is 9.840000000000003
How can I modifiy this code in order to return just the value 9 ?

Wednesday, 11 September 2013

How can I use function return val as left val in Python?

How can I use function return val as left val in Python?

I want to make the below c code work in Python, how can I make it?
// low level
typedef int* (*func)(int);
// high level
int a[2];
// high level
int* foo(int i) { return &a[i]; }
// low level
void goo(func f) {
int i = 0;
for(; i < 2; ++i) *f(i) = 7;
}
int main(void)
{
goo(foo);
return 0;
}
When I write a low level function such s goo I want to use the pointer
returned by high level user-defined function foo.
It is really easy in c and I want to make it in Python, How? Thanks!!

Insert HTML from SQL into textarea?

Insert HTML from SQL into textarea?

I would like to know why I am getting a "Parse error: syntax error,
unexpected T_VARIABLE, expecting T_STRING" in my code, which pulls HTML
off an MySQL database, replaces < and > with the entity (<, >) and inputs
it into a textarea (CKEditor). Here is that section of the code:
<textarea name="editor1">
<?php
//QUERY DATABASE
$query1 = "SELECT * FROM users WHERE ID = '" . $id . "'";
$resource1 = mysql_query($query1, $database);
$result1 = mysql_fetch_assoc($resource1);
$rawcode = $result['code'];\
$code1 = str_replace("<", "&lt;", "$rawcode");
$code = str_replace(">", "&gt;", "$code1");
echo $code1;
?>
<!--&lt;p&gt;Create your page here.&lt;/p&gt;-->
</textarea>

How abbrev pattern parameter works?

How abbrev pattern parameter works?

This code from https://github.com/rubinius/rubinius/blob/master/lib/abbrev.rb
def abbrev(words, pattern = nil)
table = {}
seen = Hash.new(0)
if pattern.is_a?(String)
pattern = /^#{Regexp.quote(pattern)}/ # regard as a prefix
end
words.each do |word|
next if (abbrev = word).empty?
while (len = abbrev.rindex(/[\w\W]\z/)) > 0
abbrev = word[0,len]
next if pattern && pattern !~ abbrev
case seen[abbrev] += 1
when 1
table[abbrev] = word
when 2
table.delete(abbrev)
else
break
end
end
end
words.each do |word|
next if pattern && pattern !~ word
table[word] = word
end
table
end
I'm not sure how pattern parameter is working, Can someone please explain
it to me with an example?

Google Chart API and AdoDB PHP

Google Chart API and AdoDB PHP

I wonder if anyone knows a way to integrate the class for PHP ADODB with
the Google Chart API. I've tried several ways, but have not found
something practical, I wanted to create a class where I could connect to
the database (using PostgreSQL), and have underlying functions in this
class to convert data and / or array in requests for graphics google...
thanks!!

compare time() with timestamp

compare time() with timestamp

Currently I'm storing timestamps in the database like such 1378852898
How can I check this against the current time() to see if it's within the
last 10mins with PHP?

multiple threads using same value fetched by database DAO class method

multiple threads using same value fetched by database DAO class method

Status: unsolved mistery
This is really deep and n*eeds patience* to help. Help is highly
regarded!!!!!!
I know following would be a mess but I couldn't find a better description
to ask. apologies for that.
I had to make a pastebin as I had to point out line numbers.
main app, http://pastebin.com/i9rVyari logs, http://pastebin.com/2c4pU1K8
I am starting many threads (10) in a for loop with instantiating a
runnable class but it seems I am getting same result from db (I am geting
some string from db, then changing it) but with each thread, I get same
string (despite each thread changed it.) . using jdbc for postgresql what
might be the usual issues ?
line 252
and line 223
the link is marked as processed. (true) in db. other threads of crawler
class also do it. so when line 252 should get a link. it should be
processed = false. but I see all threads take same link.
when one of the threads crawled the link . it makes it processed = true.
the others then should not crawl it. (get it) is its marked processed =
true.



getNonProcessedLinkFromDB() returns a non processed link
public String getNonProcessedLink(){ 645
public boolean markLinkAsProcesed(String link){ 705
getNonProcessedLinkFromDB will see for processed = false links and give
one out of them . limit 1 each thread has a starting interval gap of 20
secs.
within one thread. 1 or 2 seconds (estimate processing time for crawling)
line 98 keepS threads from grabbing the same url
if you see the result. one thread made it true. still others access it.
waaaay after some time.
all thread are seperate. even one races. the db makes the link true at the
moment the first thread processes it

Errorhandling Bash Script

Errorhandling Bash Script

I'm not a master in Scripting, so I have to ask here :)
How can I implement an errorhandling for this:
find . -type f|sed 's_\.\/__' > $PATH
i.e. abort when this was not successfull.
Thank you very much in advance Thomas

if else condition not working for jquery

if else condition not working for jquery

here the scenario is , i have created tooltip, and for all the div tag i
have given different id's , based on their id's it should generate
different tool tip.. for that i am using if else condition under
javascript and checking for div's id, but here code is not going in else
if condition: you can check the live example on this link .. guys plz help
me out, and thanks in advance.. :)

Tuesday, 10 September 2013

How to fetch Data from Json object in javascript?

How to fetch Data from Json object in javascript?

I am working on SpringMVC in my controller i am create one Json object and
i passed that object to javascript But How can i read that object in
javascript any One help me Please check My code
My Map object
Map<String rootNode,List<String>> map = new HashMap<String
rootNode,List<String>();
String rootNode = "bhanu";
ArrayList<String> al = new ArrayList<String>();
for(int i=0;i<UserProfile.size;i++)
{
al.add(userProfile.get(i));
}
map.put(userProfile,al);
At last my Map object have this Data
{"Bhanu":["hari@gmail.com","balu@gmail.com","santha@gmail.com"],"root":["bhanu@gmail.com","anu@gmail.com","apar@gmail.com"],"hari":["bhanuprasad@gmail.com","sravya@gmail.com","mahesh@gmail.com"],"balu":["rama@gmail.com"]}
Now i convert this object into GSon
Gson gson = new GSon();
String orgChartUsers = gson.toJson(map);
Now i passed this String into my javascript
Because this is my Ajax Response.. function orgUsers(result) {
var orgObject = JSON.parse(result);
//Here i can i fetch my List<String> data
}
Any one help me how can i do this...

Select distinct values of distinct group in mysl, PHP

Select distinct values of distinct group in mysl, PHP

id title year ------------- 1 abc 1999 2 abc 2000 3 abc 2000 4 abc 1998 5
bce 1999 6 bce 1999 7 def 1999 8 def 1999 9 def 2000
I have a table similar to above
I am trying to get an array similar to
OUTPUT:
array('abc' => 'array(1999,2000,1998)', 'bce' => 'array(1999)', 'def' =>
'array(1999, 2000)');
I know a long way and I assume its time consuming way..
PHP:
$rid = mysql_query("SELECT DISTINCT title from table_name ORDER BY ASC);
while($arr = mysql_fetch_array($qr)){
$title = $arr
$rid = mysql_query("SELECT DISTINCT title from table_name ORDER BY ASC);
$yearArr = array();
while($arr2 = mysql_fetch_array($qr)){
$yearArr[] = $arr2['year'];
}
$finalArr = array(title => $yearArr);
}
finally i am getting the array I was looking for. but from the above code
if I have 1000 distinct titles then the whole process will executest 1001
queries.
Is there any short way of doing I also found one similar one but, I
couldnot go further
SELECT DISTINCT year,title FROM table_name WHERE title IN (SELECT DISTINCT
title FROM papers_scanned_01) ORDER BY title ASC, year DESC
using the above query i am getting an array as below
array( [0] => 'abc', [1] => '1999', [2] => '2000', [3] => '1998', [4] =>
'bce' and so on..
please help me. thanks in advance friends..

Html.ActionLink Action Straggler

Html.ActionLink Action Straggler

I have a nav menu with links structured like so:
<div class="childLinkGroup">
<div
class="headerLink">@Html.ActionLink("Engine
Products", null, "EngineProducts", null,
null)</div>
<ul>
<li>@Html.ActionLink("Perkins
Engines", "PerkinsEngines",
"EngineProducts", null, null)</li>
<li>@Html.ActionLink("Isuzu Engines",
"IsuzuEngines", "EngineProducts",
null, null)</li>
<li>@Html.ActionLink("FPT PowerTrain",
"FPTPowerTrain", "EngineProducts",
null, null)</li>
<li>@Html.ActionLink("Mitsubishi
Engines", "MitsubishiEngines",
"EngineProducts", null, null)</li>
</ul>
</div>
These all work fine when accessed from the homepage.
If you're already on a child page like /EngineProducts/IsuzuEngines and
try to access a different parent level link like /TransmissionProducts the
IsuzuEngines is left on the link resulting in a page that can't be found.
There's a bunch of overrides for Html.ActionLink and while I looked though
them I don't see a different set of params that looks better.

what is 'this' constructor, what is it for

what is 'this' constructor, what is it for

I'm in the learning process and I have a question I havent been able to
find a satisfactory answer for.
this I need a rundown on it. I keep seeing it and people have suggested
fixes for my code that use it. I really have no idea what exactly it does.
If someone would be so kind as to give me a basic rundown on it I would be
really happy.

Find epoch timestamp of Accurev file in my stream OR backing stream?

Find epoch timestamp of Accurev file in my stream OR backing stream?

I'm trying to find the epoch timestamp of whatever version of a file I get
in my stream.
I tried "accurev hist -s stream_name -fx -t highest filename"
That only seems to work if the filename is in the default group of
stream_name. If stream_name inherits the file from a higher stream, I see
"No history corresponding to selection."
I also tried "accurev stat -s stream_name -fe filename" to get the EID,
and then used "-e EID" in the "accurev hist" command. Again, this only
works if the file is in the default group of stream_name, otherwise I get
"No history corresponding to selection."
How can I get the timestamp regardless of whether the file is in my
default group or in the default group of a parent stream?
Thanks.

Vertical scrollbar position in a table

Vertical scrollbar position in a table

I need your help.
The following javascript coding, that works flawlessly when it is
executed, however, the coding starts off the scroll position to the bottom
of my data table.
How can the javascript coding be modified so as to start at the top instead?
var table = document.getElementById("data");
var rows = table.getElementsByTagName("tr");
if (table.parentNode.scrollTop + table.parentNode.offsetHeight -
rows[0].offsetHeight < rows[i].offsetTop + rows[i].offsetHeight ||
rows[i].offsetTop < table.parentNode.scrollTop + rows[0].offsetHeight) {
table.parentNode.scrollTop = rows[i].offsetTop -
table.parentNode.offsetHeight / 2;
}

jQuery if input text equals var do something

jQuery if input text equals var do something

I have a form that calculates the sum of several input values (checkboxes
and dropdowns - not user entered values). At the bottom of the form I have
a "Discount Code" box, I want to be able to enter a code and it takes a
set amount off the total.
With my code I am trying to say, if text entered = discount code, change
the value of the input to 50. Here is what I have so far
var discountCode = 'DISTR50';
var codeEntered = $("input[name='discount']");
if (discountCode = codeEntered) {
$('#discount input').attr('value',50);
}
and for the html:
<input type="text" id="discount" name="discount" class="txt"/>

Sortable and selectable

Sortable and selectable

Is there a way to use both sortable and selectable on same element? I
found this solution, but it is based on 'handle', which I would like to
avoid, since I want whole li to be both selectable and sortable. I'm
working with Angular, so if there is an angular solution, even better.

i want sales report in blocks

i want sales report in blocks

hello i have two table 'sales_person' and 'sales'
sales_person id|sales person|email|username|password|
sales
id|company name|contact person|email|phone|sold by|booth number|date|
i want the sales report of the each sales persons in blocks how can i do this
SELECT company_name , contact_person , phone_number , booth_number FROM
registration WHEREsold_by='$username'";

Monday, 9 September 2013

App opens with Rear Facing Camera launched

App opens with Rear Facing Camera launched

What's the best method of having the rear facing camera run when the app
successfully launches?
I'd like my app to open with a modal view controller first that way the
user can dismiss the camera if they do not wish to take a photo at that
time.
Thanks!

Get part of a string in C#

Get part of a string in C#

Alright so I have something like HDKLFKEHR######LDKFRLEK. The outside
portions (Meaning: HDKLFKEHR and LDKFRLEK) will never change, but ######
will always change. So how can I extract ###### from the string? Thanks a
lot for the help in advance

Creating dynamic filters in Access 2010 Macros

Creating dynamic filters in Access 2010 Macros

In VBA I can build filter strings like
Me.Filter = "[" & Me!cmb_select_field & "] Like " & Chr(34) & "*" &
Me.txt_find_this & "*" & Chr(34)
Which produce a filter [Vendor_name] Like "Vancouver"
Given that cmb_select_field was selected as [Vendor Name] and
txt_find_this had Vancouver entered.
I am working with Access 2010 web pages on sharepoint so I can only use
macros. Is there a way to dynamically create filter strings in Macros. I
can get the string as a Local Variable but when I setfilter I get the
local variable name instead of the string

Strange( not PC) language, please help to translate

Strange( not PC) language, please help to translate

Please, help me to translate. It is urgent! Look here: http://db.tt/MZz15sJX

spyne generates bad WSDL/XSD schema for ComplexModels with ComplexModel children

spyne generates bad WSDL/XSD schema for ComplexModels with ComplexModel
children

I'm trying to use spyne to implement a SOAP service in Python. My client
sends SOAP requests like this:
<ns1:loadServices xmlns:ns1="dummy">
<serviceParams xmlns="dummy">
<header>
<user>foo</user>
<password>secret</password>
</header>
</serviceParams>
</ns1:loadServices>
But I have difficulties putting that structure into a spyne model.
So far I came up with this code:
class Header(ComplexModel):
__type_name__ = 'header'
user = Unicode
password = Unicode
class serviceParams(ComplexModel):
__type_name__ = 'serviceParams'
header = Header()
class DummyService(ServiceBase):
@rpc(serviceParams, _returns=Unicode)
def loadServices(ctx, serviceParams):
return '42'
The problem is that spyne generates and XSD like this:
...
<xs:complexType name="loadServices">
<xs:sequence>
<xs:element name="serviceParams" type="tns:serviceParams"
minOccurs="0" nillable="true"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="serviceParams"/>
...
which is not what I want because essentially it says that "serviceParams"
is just an empty tag without children.
Is that a bug in spyne? Or am I missing something?

Get request parameters in controller's constructor Zend Framework 2

Get request parameters in controller's constructor Zend Framework 2

I have 10 actions in one Controller. Every action required ID from
request. I want to check ID in constructor for every action, so I want
avoid to write the same code 10 times in every action.
obviously, In constructor I can not use functions like:
$this->params()->fromQuery('paramname'); or
$this->params()->fromRoute('paramname');
So, the question is how to get request params in controller's constructor?

IBM Worklight: No SessionManager in calling Worklight adapter

IBM Worklight: No SessionManager in calling Worklight adapter

Sometimes when Worklight adapter is invoked, the following error "No
SessionManager" is encountered in server log. When the adapter is invoked
again, result is returned. I have checked that the session ID remains the
same.
May I know what is the possible reason to have this kind of error? Thanks!
Environment: Worklight 5.0.6.1
[2013-09-09 17:55:38] FWLSE0099E: An error occurred while invoking
procedure TestAdapter/getTestDataFWLSE0100E: parameters:{
"arr": [
]
}
No SessionManager
FWLSE0101E: Caused by: null

R issue: How to introduce tags from dataframe to specific tag documents inside a corpus

R issue: How to introduce tags from dataframe to specific tag documents
inside a corpus

Is it possible to add an additional tag to a corpus document which has
another tag with a specific value?
I have a corpus with 20 docs. The docs have a character ID set. On the
other hand I have a dataframe with some of the 20 docs. Beside the ID the
dataframe has a tag column. This tags have to be set to all corresponding
docs inside the corpus. How would you find the right doc in the corpus for
all elements inside the dataframe and set the corresponding tag?
Example: library("tm") data(crude) # a corpus with 20 docs meta(crude,
type="local", tag="alphanumID") <- letters[1:20] # adding some additional
IDs to the corpus
mydf <- data.frame(cbind(SomeTag=sample.int(1e8, size = 15, replace =
FALSE, prob = NULL),
alphanumID=paste(letters[1:15], 16:30, sep="")))
# Creating a dataframe with similar IDs
mydf <- mydf[sample(nrow(mydf)),] # permutation of elements (rows)
rownames(mydf) <- 1:15 # overwriting the rownames
mydf
> mydf
SomeTag alphanumID
1 42381006 e20
2 69493835 l27
3 26159062 d19
4 44461050 n29
5 83040006 c18
6 30317343 g22
7 33704495 a16
8 64416661 k26
9 56907735 m28
10 96524612 f21
11 23311778 h23
12 81621392 o30
13 41966863 b17
14 94132818 j25
15 46272404 i24
## This is the ISSUE
## How to introduce the "SomeTag"-values to the corespondent alphanumID
docs inside the corpus?
for (i in mydf){
meta(crude[at the position crude$alphanumID==mydf2$alphanumID[i]],
tag="SomeTag", type=local) <- mydf2$SomeTag[i]
}