Saturday, 31 August 2013

JSF 2 : Status-Description selectonemenu

JSF 2 : Status-Description selectonemenu

I have 2 selectonemenu elements, one that contains the status of the
request, and the other contains a description of that status.
Im trying to implement it as follows :
I have a class called status that has 2 fields : status & description.
the selectonemenu would be :
<h:outputText id="requestStatusH" value="Status : " />
<h:selectOneMenu id="statusDD" value="#{exApp.status}">
<f:selectItems value="#{exApp.statusList}" />
</h:selectOneMenu>
and my bean would be :
private RequestStatus status;
private List<RequestStatus> statusList;
//Getters + Setters
when i select a status in one selectonemenu i want the corresponding
description to appear in another disabled selectonemenu.
The problem is that im not able to even get the selected value in to the
backing bean variables. after i submit the page, nothing is happening.
I tried to look into the stackoverflow selectonemenu guide, and i couldnt
find anything about converters.
any help would be highly appreciated.

How to echo multiple rows with data based on checkbox input?

How to echo multiple rows with data based on checkbox input?

Got stuck trying to echo out multiple rows with data based on checkbox
input. As of current code it processes data from only one checkbox, no
matter how many checkboxes are ticked. Please help!
while($row = mysql_fetch_assoc($r))
{
$pals .= '<input type="checkbox" name="pal_num[]"
value="'.$row['pal_num'].'">'.$row['pal_num'].'<br>';
}
if($pal == '') {
echo '';
} else {
echo '<form name="get_pal" action="post2.php" method="POST">';
echo $pals;
echo '<input type="submit" name="post" value="Go!">';
echo '</form>';
}
post2.php:
$w = $_POST['pal_num'];
$rrr = mysql_query("SELECT * FROM pl_tab WHERE pal_num".$w[0]);
while($row = mysql_fetch_array($rrr))
{
echo '<tr><td>'.'&nbsp'.'</td>';
echo '<td rowspan="5">'.$row['descr'].'</td>';
echo '<td><b>'.'Total weight'.'<b></td>';
echo '<td>'.'&nbsp'.'</td><td>'.'&nbsp'.'</td></tr>';
echo '<td>'.'&nbsp'.'</td>';
echo '<td colspan="3">'.'&nbsp'.'</td>';
//this part should multiple based on how many checkboxes are ticked.
echo '<tr><td>'.$row['l_num'].'</td>';
echo '<td>'.$row['pal_num'].'</td>';
echo '<td>'.$row['weight 1'].'</td><td>'.$row['weight 2'].'</td></tr>';
}
echo "</table>";}

Making/Initializing Array of Struct Like Objects in Java

Making/Initializing Array of Struct Like Objects in Java

I am using Java SE on NetBeans 7.3.1.
I would like to form a Java array similar to the following in C
typedef struct sNewStruct{
int min;
int max;
} NewStruct;
NewTruct nsVar[19];
I tried the following
class IntRange{
int min, max;
}
IntRange[] rangeNodes = new IntRange[19];
My problem is that, while rangeNodes is successfully allocated, all of its
elements are nulls.

Jquery pagination - Applying class to items

Jquery pagination - Applying class to items

I am trying to design a pagination system in Jquery. The bit I am stuck on
is when I click on different page number links, I want it to move the
"active" class to the newly clicked page.
In the example page "1" has the active class. When I click "2" I want the
active class to move to "2" and be removed from "1".
http://jsfiddle.net/qKyNL/24/
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
$('#content').fadeTo(500, 1);
}
});
});
I'm quite new to Jqeury and could do with some help. Can anyone please
give me some guidance on how to do this?

access elements in Ruby nested hash

access elements in Ruby nested hash

I am trying to access the elements in a nested hash where keys are similar
symbols.
favs = {
:art => "painters",
:survey1 => [
{:name=>"Josh", :painter=>"Dali" },{:name=>"Mona", :painter=>"Monet"}
],
:survey2 => [
{:name => "Leon", :answer => "None"},
{:name=>"Port", :answer => "Picasso"},
]
}
Q1: Delete Leon-
I came up with this:
favs[:survey2].each { |hash|
hash.delete_if { |k,v|
v=="Leon"
}
}
but I couldn't figure out how to tie the second key value pair in (the
answer/painter) after removing just the name.
Q2 Return Josh's favorite painter - same problem, I can find :name=>Josh
but not sure how to return corresponding painter.
Thanks in advance

Would a partial index be used on a query?

Would a partial index be used on a query?

Given this partial index:
CREATE INDEX orders_id_created_at_index ON orders(id) WHERE created_at <
'2013-12-31';
Would this query use the index?
SELECT * FROM orders WHERE id = 123 AND created_at = ''2013-10-12';
As per the documentation, "&#65279;a partial index can be used in a query
only if the system can recognize that the WHERE condition of the query
mathematically implies the predicate of the index". Does that mean that
the index will or will not be used?

Load images in jar file

Load images in jar file

I'm trying to load an image from an executable JAR file.
I've followed the information from here, then the information from here.
This is the function to retrieve the images:
public static ImageIcon loadImage(String fileName, Object o) {
BufferedImage buff = null;
try {
buff = ImageIO.read(o.getClass().getResource(fileName));
// Also tried getResourceAsStream
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (buff == null) {
System.out.println("Image Null");
return null;
}
return new ImageIcon(buff);
}
And this is how it's being called:
logo = FileConverter.loadImage("/pictures/Logo1.png", this);
JFrame.setIconImage(logo.getImage());
With this being a simple Object. I'm also not getting a
NullPointerException unless it is being masked by the UI.
I checked the JAR file and the image is at:
/pictures/Logo1.png
This current code works both in eclipse and when it's been exported to a
JAR and run in a terminal, but doesn't work when the JAR is double
clicked, in which case the icon is the default JFrame icon.
Thanks for you're help. It's probably only me missing something obvious.

Css working no more , once javascript starts execution on the ticker

Css working no more , once javascript starts execution on the ticker

I am new to Javascript and css. I just made a simple ticker application
using Jquery css and Html. Below is the code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Kshitij 2013 </title>
<title>jQuery Ticker</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.9.1.js "></script>
<style>
.ticker {
width: 400px;
height: 200px;
overflow: hidden;
border: 1px solid #DDD;
border-radius: 5px;
box-shadow: 0px 0px 5px #DDD;
background-color: #F5F3E5;
text-align: left;
}
.ticker h3 {
padding: 0 0 10px 10px;
border-bottom: 1px solid #A7A7A7;
}
ul {
list-style: none;
padding: 0;
margin: 0;
font-style: italic;
}
ul li {
list-style: none;
height:50px;
padding:7px;
border-bottom: 1px solid #D6CFB8;
}
</style>
</head>
<body>
<script type="text/javascript">
function ticker() {
$('#ticker li:first').slideUp(function() {
$(this).appendTo($('#ticker')).slideDown();
});
}
setInterval(ticker, 3000);
</script>
<div id="ticker">
<h3>Latest News</h3>
<ul id="ticker">
<li>Dummy data is benign information that does not contain
any useful data, but serves to reserve spac...</li>
<li>For testing, dummy data can also be used as stubs or pad
to avoid software testing iss...</li>
<li>In operational use, dummy data may be transmitted for
OPSEC purposes.</li>
<li>Dummy data must be rigorously evaluated and documented to
ensure that it does no...</li>
<li>The topic of this article may not meet Wikipedia's
general notability guideline.</li>
<ul>
</div>
</body>
</html>
Problem is that, Css works in the starting. But once the ticker starts to
move up after certain time intervals, Css effects are not working anymore.
Should I load this css somehow when each time this ticker moves up ?

Friday, 30 August 2013

apache camel sql component - how to execute only once

apache camel sql component - how to execute only once

I've created/creating a simple Apache Camel program to move data from a
source db to a target db. I have configured a route to do this and it
works! The problem is that it just keeps executing the root every second
or so. I only want it to execute once.
I've been playing around with the timer repeatCount but can't quite get
the root right. Can anyone help me to try and re-word what i have below so
that it only executes once.
<bean id="sourceSql" class="org.apache.camel.component.sql.SqlComponent">
<property name="dataSource" ref="sourceDataSource"/>
</bean>
<bean id="targetSql" class="org.apache.camel.component.sql.SqlComponent">
<property name="dataSource" ref="targetDataSource"/>
</bean>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<propertyPlaceholder location="classpath:sql.properties"
id="placeholder"/>
<route id="processProduct-route">
<description>route that process the orders by picking up new rows
from the database
and when done processing then update the row to mark it as
processed</description>
<from uri="sourceSql:{{sql.selectProduct}}"/>
<to uri="targetSql:{{sql.insertProduct}}"/>
<log message="${body}"/>
</route>
Thanks in advance

Thursday, 29 August 2013

How to modify the zones width inside a sharepoint site

How to modify the zones width inside a sharepoint site

I have a team site page and I am using the "One Column with sidebar" Text
layout. But I need to minimize the width of the Side bar and expand the
width of the One column. I tried accessing the zone html info from the
SharePoint designer but cannot locate where I can find the Zones info
inside SharePoint designer 2013.
The sidebar contain Useful links only and it is consuming a lot of unused
space as follow:-

Internationalization jsp page?

Internationalization jsp page?

I have below jsp code.
<section class="loginform cf">
<form name="login" action="index_submit" method="get"
accept-charset="utf-8">
<ul>
<li><label for="usermail">Email</label>
<input type="email" name="usermail"
placeholder="yourname@email.com" required></li>
<li><label for="password">Password</label>
<input type="password" name="password" placeholder="password"
required></li>
<li>
<input type="submit" value="Login"></li>
</ul>
</form>
</section>
Here i want to externalize all label names and label names will be shown
based on the locale. Basically i need i18n for jsp labels. How can i do
that?
Thanks!

ng-model table show data angularjs

ng-model table show data angularjs

I ma very beginner in Angularjs and pardon my silly mistakes. I have a
table which shows data in three columns and i want to filter this table
based on a condition and hide unnecessary data in one column which
contains integers. I have used ng-show with some condition linked to
ng-model and this is working perfect if i enter data in my ng-model only
after loading total form. But, i want to show all the table data in the
beginning and then hide unnecessary data based on ng-show condition.
How can i do this? I am struggling!
<tr ng-show= "change > val1 " ng-repeat="change in montlyProjection();" >
<td>some data</td>
<td class="number">some data</td>
<td class="number"
ng-class="positiveNegative(convertToNumber(startBalance) +
change)">some data</td>
</tr>
</strong><input type="text" ng-model="val1" placeholder="Enter Amount" />

How to get back an attribute of Resource in tastypie

How to get back an attribute of Resource in tastypie

Details :
@localhost:8000/api/v1/user/1/
Gives :
{
"date_joined": "2013-08-28T04:20:36.704342",
"email": "a@a.com",
"first_name": "",
"id": 1,
"is_active": true,
"is_staff": true,
"is_superuser": true,
"last_login": "2013-08-29T01:18:07.163345",
"last_name": "",
"password":
"pbkdf2_sha256$10000$EVKt9xEHWSaD$S/ipn3mqoSMBjo98D9wconcloape1eFvsu9mVoIm+KA=",
"resource_uri": "/api/v1/user/1/",
"username": "admin"
}
Now if i wanna get only firstname How can i do that in tasty pie??

Wednesday, 28 August 2013

Does a TCP peer reset the connection after exhaust the send retry counter?

Does a TCP peer reset the connection after exhaust the send retry counter?

Supose a Windows TCP peer sending a TCP packet and the remote peer not
ACK'ing it neither reseting the connection (kernel crash, power/hardware
failure,etc.)
Does the windows peer reset the connection after exhaust the send retry
counter?
Does the TCP RFC say something about it?
My doubt arises after reading the following sentence (in "Re-transmission
Behavior" paragraph of this page
http://support.microsoft.com/kb/169292/en-us):
After computer "X's" retries are exhausted, you may not see a "Reset"
right away. If computer "Y" finally responds, computer "X" may then reset
the connection.
Thanks in advance and forgive me for my rudimentary english.
Regards

How to pass an array of checkbox value From one JSP page to another

How to pass an array of checkbox value From one JSP page to another

I am a beginner. I want to pass an array of check box values from one JSP
page to another. The page getting data is
<%
ResultSet rs=s.notapprovedqns();
%>
<%
while(rs.next())
{ %>
<tr><td><input name="qns[]" type="checkbox" value="<%
out.println(rs.getInt("question_id")); %>"
/></td><td><center><%=rs.getString("question_id")
%></center></td><td><%=rs.getString("question") %></td></td></tr>
<%
}
%>
How can i receive check box values in JSP another page. I have tried the
following code but its not working properly
String[] h=null;
h=request.getParameterValues("qns[]");
But its passing the value
[Ljava.lang.String;@a0a595
Please somebody help me to solve this problem.

Troubles using jquery on a form

Troubles using jquery on a form

I'm trying to use Jquery in order to validate a form's input. On top of
that, I want to auto-fill some fields if they are left blank. Here is how
I proceed :
$(form).submit(function () {
var result = true;
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
if ($("#newStartTime").val().length == 0)
$("#newStartTime").val("00:00");
if (!timeRegex.test($("#newStartTime").val())) {
$("#newStartTime").wrap("<div class='error' />");
result = false;
}
return result;
});
What's happening here is that the input is set to 00:00, but the submit is
rejected (and the field wrapped as an error). If I re-click on submit, it
works fine.
The way I see things, Jquery doesn't treat the modifications made after
the 'submit' was called. If that's the case, is there a way to achieve
what I want without using ".submit()" twice ? If I'm mistaken, what's
wrong ?

How can I use a macro for collecting variable names?

How can I use a macro for collecting variable names?

I would like to simplify the following
class A {
int a;
int b;
int c;
std::vector<int*> addrs;
public:
A() : addrs{ &a, &b, &c } {}
};
so that I don't have the write the list of fields in two places, i.e. the
declarations and the initializer for addrs. Is there some way to use a
macro to collect the declarations and use them later. E.g.,
class A {
VAR_DECL(a);
VAR_DECL(b);
VAR_DECL(c);
std::vector<int*> addrs;
public:
A() : addrs{ VAR_ADDRESSES } {}
};
For context this is intended for implementing some kind of property
introspection system.

Tuesday, 27 August 2013

What does "source" the bin/activate script mean?

What does "source" the bin/activate script mean?

This is in reference to a response I received that said I need to source
this script in order to active the virtualenv.
No idea what that means, beginner here trying to figure out virtualenv.

Power series $\sum n^3a=?iso-8859-1?Q?=5Fnz^n$_=96_math.stackexchange.com?=

Power series $\sum n^3a_nz^n$ – math.stackexchange.com

If $f(z)=\sum a_nz^n$, what is $\sum n^3a_nz^n$? The desired sum is
$a_1z+8a_2z^2+27a_3z^3+\cdots$. I can't see how to write the desired sum
in terms of $f$. For example, I could substitute $kz$ …

blueimp/jQuery-File-Upload & jquery tree traversal methods on input element

blueimp/jQuery-File-Upload & jquery tree traversal methods on input element

I'm trying to implement file uploading with the help of
https://github.com/blueimp/jQuery-File-Upload and have come across some
weird behavior that I hope somebody can explain to me, or it might
actually be a bug, I don't know.
I followed the minimal setup guide
(https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin) and
setup a new project where I change this (only the script):
<body>
<input id="fileupload" type="file" name="files[]" multiple>
</body>
-
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
</script>
to this (to illustrate the issue I have). I introduce a variable and
assign $('#fileupload') to it and work with the variable from there on:
<script>
$(function () {
var $elem = $('#fileupload');
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
$elem.on('change', function(e) {
console.log($elem.parent());
console.log($elem.next());
console.log($elem.prev());
console.log($elem.siblings());
});
</script>
Int the second example for some reason jQuery's tree traversal methods
like parent(), next(), prev() or sibling() won't work with
$elem
any more after clicking the input button and loading some random image. Is
this a bug or am I simply missing something here?
thx for the help

What does the standard say about how calling clear on a vector changes the capacity?

What does the standard say about how calling clear on a vector changes the
capacity?

This website implies that clearing a vector MAY change the capacity:
http://en.cppreference.com/w/cpp/container/vector/clear
"Many implementations will not release allocated memory after a call to
clear(), effectively leaving the capacity() of the vector unchanged."
But according to @JamesKanze this is wrong and the standard mandates that
clear will not change capacity.
What does the standard say?

Shadow of the hidden window when minimize the parent window

Shadow of the hidden window when minimize the parent window

I am working with wpf c#, I set the visibility of the child window to
hidden on closing. But when I minimized the parent window, or clicked on
the parent window from taskbar, there comes a shadow like window of the
hidden child window.How can I avoid this.

No module named zlib in python 2.6?

No module named zlib in python 2.6?

I tried to install Python2.6(built from source) in my Debian 7 system, but
when installation finished and tried use it , I was told No module named
zlib.
I have installed both zlib1g and zlib1g-dev, and built it again but still
failed. Also, I have tried ./configure --with-zlib and ./configure
--with-zlib=/usr/include, failed.
I really got zlib.h in /usr/include/zlib.h which version is 1.2.7.

And I found this in setup.py under Python 2.6 source code:
I tried to debug to figure out why.When I jump to line 1131, it was False
and jump to line 1140. So, I was told I didn't have zlib! (Why?)

Monday, 26 August 2013

Setting Sql Query Output to a list in ASP.NET

Setting Sql Query Output to a list in ASP.NET

I'm working on a project for work, and this issue has been holding me up
all day. My database consists of 9 Columns that are used to identify a
specific row based on user inputs and 7 columns that contain the relevant
data for that user given their inputs match the first 9 columns of the row
match. This may not be the most efficient way of structure the database,
but it's an artifact of the prototype and I'd really rather not change it.
I have a SQL Query that selects the correct row based on the user's
inputs, and now I want to assign a variable to each of the remaining 7
columns (called OA5,OA10,OA15,OA20,OA25,OA30,and OALife), so that I can
graph them for the user. I haven't been able to figure out how to do this
given the way I have my sql query structured below.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:cs_test website %>"
SelectCommand="SELECT * FROM [OARiskData$] WHERE Age = @myAge AND Sex
= @mySex AND Race = @myRace AND FamHx = @myFamRisk AND OccEx =
@myOccRisk AND HxInj = @myHxInj AND BMI = @myBMI AND UnderCost = 1 AND
RiskProg = 0">
<SelectParameters>
<asp:Parameter Name="myBMI" Type="String" />
<asp:Parameter Name="myAge" Type="String" />
<asp:FormParameter DefaultValue="" Name="mySex"
FormField="inputSex" Type="String" />
<asp:FormParameter DefaultValue="" Name="myRace"
FormField="inputRace" Type="String" />
<asp:Parameter Name="myFamRisk" Type="String" />
<asp:FormParameter DefaultValue="" Name="myOccRisk"
FormField="occRisk" Type="String" />
<asp:FormParameter DefaultValue="" Name="myHxInj"
FormField="hxInj" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

Scroll textfield up when keyboard popsup

Scroll textfield up when keyboard popsup

I am using html5/javascript/jQuery/css for mobile app development. I have
multiple textareas in the app. When I click on that to input, keyboard
popup (android tab). But the textarea stays where it's on that page. How
can I scroll page when keyboard pops up.

Upgrade to 13.04 breaks wireless

Upgrade to 13.04 breaks wireless

After upgrading to 13.04 the Intel Pro Wireless 4965 does not connect to
wireless network. I can run iwlist scan and it can see the wireless
network from the wireless card. Network Manager is not managing the
wireless or wired. Everything in network manager is showing greyed out.
Has a check by "Enable Networking" and a check by "Enable Wi-Fi" but
unable to select anything. I can get a direct hardwired network
connection.
Edited org.freedestop.NetworkManager.conf file changed all deny to allow
and rebooted.
Wireless is present but unable to use it.

How to stream screen from Android device to another Android

How to stream screen from Android device to another Android

I have a game implemented with OpenGl 1.x. I'd like to create multiplayer
mode that requires streaming from one's screen to another device's screen
(and vice versa). Can anyone direct me to find the best solution for
getting the whole screen, stream it to the other device and show the
stream on a part of the other device?
I was thinking about using Java Sockets for this, but I don't know how to
screen the stream that I currently being shown on the GLSurfaceView. And
I'm not even sure the Sockets are the most efficient solution for this (Is
there any other?)

Extraction Of Face From a Bitmap

Extraction Of Face From a Bitmap

After being given suggestions to use circular crop i implemented it in my
application to use to extract face from the bitmap but its too inefficient
i mean its of no use and similar to cropping from the rectangular face.
Now here is what i have done up til now:
Launched Camera
Taken Picture
Detected The face in the Picture
Painting a rectangular window in the area face has been detected
Now the serious issue am facing is getting face from that bitmap. I just
want to get the face. Ignore all the other details that were in the face
detection window. If it was matlab it could have been too simpler with the
help of edge detection techniques and segmentation algorithms and
function. I want to know how can i do the same process in android
application? plz do share the code snippets if u know of any. This is
taking too much of my time and i just want to get over with this face
extraction part.
Code i did till now:
public class Makeover extends Activity {
private static final int TAKE_PICTURE_CODE = 100;
private static final int MAX_FACES = 5;
private Bitmap cameraBitmap = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.take_picture)).setOnClickListener(btnClick);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(TAKE_PICTURE_CODE == requestCode){
processCameraImage(data);
}
}
private void openCamera(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE_CODE);
}
private void processCameraImage(Intent intent){
setContentView(R.layout.detectlayout);
((Button)findViewById(R.id.detect_face)).setOnClickListener(btnClick);
ImageView imageView = (ImageView)findViewById(R.id.image_view);
cameraBitmap = (Bitmap)intent.getExtras().get("data");
imageView.setImageBitmap(cameraBitmap);
}
private void detectFaces(){
Bitmap bmFace = null;
if(null != cameraBitmap){
int width = cameraBitmap.getWidth();
int height = cameraBitmap.getHeight();
FaceDetector detector = new FaceDetector(width,
height,Makeover.MAX_FACES);
Face[] faces = new Face[Makeover.MAX_FACES];
Bitmap bitmap565 = Bitmap.createBitmap(width, height,
Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();
//jo bhi krna hai ab bitmap565 k sath krna hai apse wo image hai main
ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
canvas.drawBitmap(cameraBitmap, 0, 0, ditherPaint);
int facesFound = detector.findFaces(bitmap565, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;
Log.i("FaceDetector", "Number of faces found: " + facesFound);
if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();
Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ",
" + midPoint.y + ")");
canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y -
eyeDistance ,
(int)midPoint.x +
eyeDistance,
(int)midPoint.y +
eyeDistance,
drawPaint);
}
}
for(int count=0;count<detector.findFaces(bitmap565, faces);count++)
{
float left;
float top;
PointF midPoints=new PointF();
faces[count].getMidPoint(midPoint);
eyeDistance=faces[count].eyesDistance();
left = midPoint.x - (float)(1.4 * eyeDistance);
top = midPoint.y - (float)(1.8 * eyeDistance);
bmFace = Bitmap.createBitmap(cameraBitmap, (int) left, (int)
top, (int) (2.8 * eyeDistance), (int) (3.6 * eyeDistance));
}
String filepath = Environment.getExternalStorageDirectory() +
"/facedetect" + System.currentTimeMillis() + ".jpg";
try {
FileOutputStream fos = new
FileOutputStream(filepath);
bitmap565.compress(CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView imageView =
(ImageView)findViewById(R.id.image_view);
imageView.setImageBitmap(bmFace);
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.take_picture: openCamera();
break;
case R.id.detect_face: detectFaces();
break;
}
}
};
}

Sunday, 25 August 2013

Horizontal centering in table

Horizontal centering in table

Consider the following example:
\documentclass{article}
\usepackage{booktabs,dcolumn}
\usepackage{siunitx}
\newcolumntype{d}[1]{D{.}{,}{#1}}
\newcommand*\mc[1]{\multicolumn{1}{c}{#1}}
\begin{document}
\begin{table}[htbp]
\centering
\caption{Something.}
\label{tbl:1}
\begin{tabular}{d{2.1} d{2.0} d{3.0} d{2.0} d{3.0}}
\toprule
\mc{S{\o}vnm{\ae}ngde} &
\multicolumn{2}{c}{Eleverne fra $9$.~A} &
\multicolumn{2}{c}{Eleverne fra $9$.~B}
\\
\midrule
& \mc{Abs.} & \mc{Rel.} & \mc{Abs.} &
\mc{Rel.} \\
\mc{\si{\hour}} & \mc{---} & \mc{\si{\percent}} & \mc{---} &
\mc{\si{\percent}} \\
\midrule
6.5 & 1 & 4 & 0 & 0
\\
7.0 & 4 & 16 & 2 & 10
\\
7.5 & 3 & 12 & 3 & 15
\\
8.0 & 8 & 32 & 9 & 45
\\
8.5 & 5 & 20 & 3 & 15
\\
9.0 & 2 & 8 & 3 & 15
\\
9.5 & 1 & 4 & 0 & 0
\\
10.0 & 1 & 4 & 0 & 0
\\
\midrule
\mc{I alt} & 25 & 100 & 20 & 100
\\
\bottomrule
\end{tabular}
\end{table}
\end{document}

Why are the second and third columns not horizontally centered relative to
"Eleverne fra 9. A" and the fourth and fifth columns not horizontally
centered relative to "Eleverne fra 9. B"? (They need to be pushed slightly
to the right.)
Update
I would like the width of the second and third column to be half the width
of the box containing "Eleverne fra 9. A", and the width of the fourth and
fifth column to be half the width of the box containing "Eleverne fra 9.
B".

[ Government ] Open Question : Which clause guarantees that any citizen, no matter where he or she lives, may use the courts in any state?

[ Government ] Open Question : Which clause guarantees that any citizen,
no matter where he or she lives, may use the courts in any state?

a- privileges and immunities clause b-necessary and proper clause c-full
faith and credit clause d-supremacy clause

Spring transactional dont rollback when exception is mapped by ExceptionMapper

Spring transactional dont rollback when exception is mapped by
ExceptionMapper

I have a RestFull service (implemented by jersey) . The service is marked
with @Transactional.
I declared an ExceptionMapper like this:
@Provider public class ThrowableMapper implements ExceptionMapper {
private static final Logger log = Logger.getLogger(ThrowableMapper.class);
public Response toResponse(Throwable ex) {
log.error("throwable", ex);
return Response.status(500).entity("Internal
Error").type("text/plain").build();
}
}
when exceptionmapper is not declared than transaction is rollback.
However, when i have an ExceptionMapper transaction is commit without
rollback.
I assume that since exception is caught by ExceptionMapper than spring
transaction proxy dosnt detect that exception was thrown ,so transaction
is not rollback.
Is there a way to overcome this?

Is a $CD(K,\infty)$ space a length space?

Is a $CD(K,\infty)$ space a length space?

Let $(X,d)$ be a complete and separable metric space endowed with a
nonnegative Borel measure $\mu$ with support $X$ and satisfying
\begin{eqnarray} \mu(B(x,r))<\infty,\quad\mbox{for every }x\in X\mbox{ and
}r>0, \end{eqnarray} where $B(x,r)$ is the ball of radius $r$ centered at
$x$ in $X$ w.r.t. the metric $d$.
Let $(X,d,\mu)$ be a $CD(K,\infty)$ space in the sense of Sturm. Is
$(X,d)$ a length space?
Many thanks.

Saturday, 24 August 2013

GD resize image and crop edges

GD resize image and crop edges

Basically if I have a 3400x3400 image and my target size is 340x200 then I
would like to grab the respective 3400x2000 from the middle of the
original image and then scale it down to 340x200, I have a rough idea of
how it will look, here is what I have so far:
$RealWidth=164;
$RealHeight=126;
$org_img = imagecreatefromjpeg($newname);
list($width, $height) = getimagesize($newname);
$ratio2 = $height/$width;
$ratio = $RealHeight/$RealWidth;
$img = imagecreatetruecolor($RealWidth,$RealHeight);
$ims = getimagesize($newname);
imagecopyresized($img,$org_img, 0, 0, 0, 0, $RealWidth, $RealHeight,
$height*$ratio2, $height);
imagejpeg($img,$newname,90);
imagedestroy($img);
I am a bit confused with the math, I also want it to be able to crop a
region from the top/bottom if needed as well.

C++ or Cython memory leakage?

C++ or Cython memory leakage?

I am working on a python extension module written in cython, that wraps a
C++ class I have written.
The crash
I have a simple python code that imports this python module and process
some data with it. Now, about 1 time out of 4, the program segfaults just
before termination, after the calls to the module. This meaning as well
that all the data is correctly processed. It segfaults like this:
/Users/axe/anaconda/bin/python.app: line 2: 73168 Segmentation fault: 11
debugging with gdb, running gdb python and then run code.py, I get
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: 13 at address: 0x0000000000000000
0x00000001000894ae in PyObject_ClearWeakRefs ()
the output of backtrace is
#0 0x00000001000894ae in PyObject_ClearWeakRefs ()
#1 0x00000001010edae4 in array_dealloc ()
#2 0x000000010007503e in tupledealloc ()
#3 0x00000001000559b7 in insertdict_by_entry ()
#4 0x0000000100059177 in PyDict_SetItem ()
#5 0x000000010005d286 in _PyModule_Clear ()
#6 0x00000001000df8cd in PyImport_Cleanup ()
#7 0x00000001000f0027 in Py_Finalize ()
#8 0x0000000100107e1b in Py_Main ()
#9 0x0000000100000f54 in start ()
So the segfault happens outside of my python code. I mention that the
problem persists if I run the code from within ipython, or change
interpreter/ipython to the one from the Enthought distribution, or if I
downgrade Cython from 1.9.1 to 1.6.
Memory leakage in C++ (?)
Since this could look like a memory leak (please let me know if there are
other possible explanations) in the C++ code, I ran Valgrind on some C++
test code of the C++ class, but it didn't find any problems. (I am not
100% sure it is free of problems, because I am on OSX Mountain Lion, and
despite having used the latest trunk version of Valgrind, it is known to
have problems. I am using a OSX10.8 suppression file, with the one
suggested here as a start). Anyway, the C++ class doesn't use
new/delete/malloc/free, so it SHOULD be fine.
Memory leakage in Cython (?)
I tried running valgrind on the python code that crashes. I have added a
python suppression file in addition to the OSX suppression file mentioned
above. Valgrind generates a lot of output and then crashes. In the output
there isn't any reference to my source codes. This is the incriminated
cython code:
def split_props(np.ndarray[fptype, ndim=1, mode="c"] x,
np.ndarray[fptype, ndim=1, mode="c"] y,
np.ndarray[fptype, ndim=1, mode="c"] ylines):
cdef np.ndarray[fptype, ndim = 1, mode = "c"] areas =
np.zeros((ylines.shape[0] + 1), dtype=np.float64, order="c")
cdef np.ndarray[fptype, ndim = 1, mode = "c"] static_moments_x =
np.zeros((ylines.shape[0] + 1), dtype=np.float64, order="c")
cdef np.ndarray[fptype, ndim = 1, mode = "c"] inertia_moments_xx =
np.zeros((ylines.shape[0] + 1), dtype=np.float64, order="c")
cdef SplitPolygon * SPINSTANCE = new SplitPolygon(100, 100)
SPINSTANCE.split_props(& x[0], # = <fptype *> x.data
& y[0],
x.shape[0],
& ylines[0],
ylines.shape[0],
& areas[0],
& static_moments_x[0],
& inertia_moments_xx[0]
)
del SPINSTANCE
return areas, static_moments_x, inertia_moments_xx
Above, the C++ class is SplitPolygon. In the python code, I import from
the cython module only the function split_props above, so the memory leak
must be in this part of the code or in the C++ code. Moreover, the
functionality of the python code is the same of the C++ test code.
I report below also another part of the module, that is very similar, but
does NOT cause any memory leakage
def SplitCirc(np.ndarray[fptype, ndim=1, mode="c"] ycenters,
np.ndarray[fptype, ndim=1, mode="c"] radii,
np.ndarray[fptype, ndim=1, mode="c"] ylines):
cdef np.ndarray[fptype, ndim = 1, mode = "c"] areas =
np.zeros((len(ylines) + 1), dtype=np.float64, order="c")
cdef np.ndarray[fptype, ndim = 1, mode = "c"] static_moments_x =
np.zeros((len(ylines) + 1), dtype=np.float64, order="c")
cdef np.ndarray[fptype, ndim = 1, mode = "c"] inertia_moments_xx =
np.zeros((len(ylines) + 1), dtype=np.float64, order="c")
split_circles(& ycenters[0], & radii[0], len(ycenters),
& ylines[0], len(ylines),
& areas[0], & static_moments_x[0], & inertia_moments_xx[0])
return areas, static_moments_x, inertia_moments_xx
Now, I am really stuck at this point. Does the cython code look good to
you? Is there any test case I can code to check that the C++ class
SplitPolygon is really leak-free? Can the crash happen for some other
reasons?

What is the little golden up-arrow in the tank crew part of Garage UI?

What is the little golden up-arrow in the tank crew part of Garage UI?

The second crew member has this little golden thing next to "91%". I
didn't notice anything unusual on his card, nor anything to change or
upgrade... I checked the guide and it wasn't mentioned. What am I missing?

Position:fixed not working

Position:fixed not working

I have a HTML page with the following content -
<div class="sidebar">
Some content here....
</div>
<div class="content">
content here too...
</div>
I want the .sidebar to be position:fixed, But not the .content. Here is
what I have tried in CSS -
.sidebar{
background:rgb(24, 33, 61);
text-align: right;
height: 100% !important;
width:30%;
postion:fixed;
left:0px;
top:0px;
bottom:0;
padding:1em;
color:white;
}
.content{
width:70%;
font-size:1.1em;
font-weight:normal;
position: absolute;
top:0;
right:0;
padding:2em;
}
Basically, I want to reproduce this. But what I'm getting now looks
perfect at first glance, but when you scroll down, the .sidebar doesn't
move with you, it stays at the same place.
How can I make it work?

Why does my Android OS state that there's, "Not enough free space to install the program", when there's plenty of free space?

Why does my Android OS state that there's, "Not enough free space to
install the program", when there's plenty of free space?

My hard drive on my smartphone has 100 MB free, and the app I'm trying to
install is 2 MB.
I just recently deleted apps totalling to about 88.3 MB, and the computed
size has already been adjusted, and is displayed on the screen.
However, I have to wait 10 or 15 minutes to install it.
It's as if the updated, computed space is not registered in some way to
the operating system immediately.
It's Android 2.3.4 Gingerbread, no root, no unlocked; factory pre-set all
the way(not for long though).
So, basically, is that the problem? Why do I have to wait a while after
uninstalling apps, and re-computing space availability to above par to
install a new, extremely small app, to actually work?
Is this all the OS's fault, or is something else at play here(e.g., hard
drive or circuit-level operations reigning outside the control of just the
OS software)?
Because if the re-computed size is what it's going to be, at least let the
end-user know that rather than give the impression that you have the
available space, but it won't install anything.

Friday, 23 August 2013

Packed structure reading from EFS giving strange result

Packed structure reading from EFS giving strange result

I have created one EFS item, that has the following structure struct {
uint8 version; // uint8 - 1 byte data type, uint16 - 2 byte uint16 y1;
uint16 y2; uint16 y3; uint8 reserved[9]; } Now the EFS file size comes out
to be 16 byte, so I think it is packed.
Now I have same structure, on which on power up I read the values from
EFS, But the Size of the structure returned by my compiler comes out to be
18 byte( Compiler doesn't support Packing, so EFS reading was failing).
I read only 16 byte and It passed.
Questions: 1. If I read only 16 byte, isn't there a risk of data loss, as
After the first member there will be one byte padded space in my
structure( as my compiler doesn't support Packed structure and I cannot
use it) I wrote the following values to the EFS, version -0 y1 -6 y2 -10
y3 -60
I read only 16 byte, and every member of my structure was assigned correct
values. is there any scenario where my structure will have wrong values.
Due to confusion at step one, i created one temporary struture like below
struct { uint8 version; uint8 y1_a; uint8 y1_b; uint8 y2_a; uint8 y2_b;
uint8 y3_a; uint8 y3_b; uint8 reserved[9]; }
Now both the EFS and structure size is 16 byte, Now when I give the input
to EFS as version =0, y1=6, y2=10, y3=60,
The members are assigned values like this :version=0,y1_a = 6, y1_b =0,
y2_a = 10, y2_b =0, y3_a =60, y3_b =0;
can someone help in understanding this? My idea is to read in temp
structure( so that both the size of EFs and my structre comes out to be
same) and then assign values to my original struture from temp struture

Rename terms in fitted model object

Rename terms in fitted model object

I have a list of regression models which all the same number of terms
(that is, the same number of predictive variables). Substantively, that
they all have different model terms is right. But when it comes to putting
them in a regression table, I want them all the models to share a single
formula, simply for the sake of presentation.
Some indicative data
library(plyr)
d1 <- data.frame(y = rnorm(100),
x1 = runif(100),
x2 = runif(100),
x3 = runif(100),
x4 = runif(100))
Fit the models
mods.form <- paste("y ~ x", 1:4, sep = "")
mod.list <- llply(mods.form, function(i) lm(i, d1))
Here are the terms I want to modify
llply(mod.list, function(i) attr(terms(i), "variables"))
[[1]]
list(y, x1)
[[2]]
list(y, x2)
[[3]]
list(y, x3)
[[4]]
list(y, x4)
I want every model in the list to have the same variable names as the
first model, so I tried:
mod.list2 <- llply(mod.list, function(i) attr(terms(i), "variables") =
list("y", "x1"))
which provides this error
Error in attr(terms(i), "variables") = list("y", "x1") :
could not find function "terms<-"
Is there a simple solution here?

Best network file system for live development

Best network file system for live development

I used to have a local development server (nginx+php-fpm+mysql) on my
workstation.
But then I got problems and had to reformat and found out that
reconfiguring everything right on OS X can be a pain in the butt
sometimes. So now I'm configuring my local server as my new development
server.
Now I need to know what network file system would be the most appropriate
for live development? I'm developing on OS X so that needs to be fast
using OS X. For example using NFS is a bad idea when using OS X since it's
slow.
I thought of maybe using AFP which is Apple's own network file system but
I wanted to have advice before doing so as in my memory configuring AFP is
kinda complex.
Any suggestion is welcome!
Thanks and have a nice day

C# Can I make a namespace accessible everywhere in my dot net web site for code-behind and classes

C# Can I make a namespace accessible everywhere in my dot net web site for
code-behind and classes

I have an extension method for String that I want to be available on every
code behind and class in my solution. The method is sitting in a
particular namespace. I'd like everywhere to have access to that namespace
without me having to include it in every class.
I've used the "namespaces" tag in the web config to successfully include
it on every aspx page, but this does not make it accessible on code behind
or elsewhere.
So, is there a similar way to include a namespace everywhere?

How to find out which backported packages are available, and avoid losing packages when manually upgrading?

How to find out which backported packages are available, and avoid losing
packages when manually upgrading?

I was surprised to see that since Natty 11.04, even when we have enabled a
backports repository, updated packages aren't automatically installed from
that repository. We have to install individual updates manually, e.g. via
apt-get install ipython/precise-backports
as explained at UbuntuBackports - Community Ubuntu Documentation. I guess
I just didn't get the memo....
First question: how do we find out what our options are for upgrades via
backports? I'm surprised that even if I ask for status, e.g. via
wajig status ipython
it doesn't tell me there is a new version available. I'd like a list of
all upgrades for packages which I've already installed.
Next, how do I avoid losing existing packages just because I upgrade via a
backport?
E.g. the above ipython install tells me:
The following packages will be REMOVED:
ipython-notebook ipython-qtconsole
How do I say I want the latest backported ipython, as well as any other
packages for which updates are available that depend on it, without
manually figuring them all out and installing them also?
I know I can change the pinning so that I get all updates, but I'm
hesitant to go against the general advice not to. But if a user asks for
one package to be updated, wouldn't it be natural to update all the
dependencies, like you'd get from a ppa?

Thursday, 22 August 2013

Overlay 2 PDF documents within a C/C++ application

Overlay 2 PDF documents within a C/C++ application

Been trying to figure this problem out for quite a while and haven't had
much luck. So I have this program that outputs a PDF file (1.3 version).
The Outputted PDF is basically a plain text PDF so the idea is to have the
user open another PDF which has graphics and have the text PDF overlay the
other.
However I haven't been able to find any way to do this for C/C++. Is there
a API that I could use? Would need to work for both Mac/Windows OS.
Any assistance would be greatly appreciated. Thank you.

Slow file transfer with VM EXSi 4.0: I tried everything but it's still slow

Slow file transfer with VM EXSi 4.0: I tried everything but it's still slow

I was asked to setup an older HP server with VMware and some Virtual
machine window servers.
File transfer from another machine on the network to the Win 2008 server
VM is ultra slow(under 70kbs usually). What's really strange is that it
occasionally is much fast(7MB+) but usually reverts back later.
Hardware:
Corsair SSD
Nvidia 10/100 mbs onboard NIC(set for auto negotiation)
Netgear Gigabyte switch(the higher end models for server rooms)
HP Proliant DL385 running Vmware 4.0.0 ESXi(NIC also set for auto
negotiation)
Other info:
The VM has it's own separate AD and Domain since it's intended to be
installed in a new office but the DNS/DCHP server isn't configured yet.
So far I've tried:
Disabling all TCP offloading options on both NIC cards: in the card menu
and via the registry
Tried the E1000 and VMXnet3 NIC on the VM...no difference
Removed a dying hard drive from the RAID array
Various network configurations
Disabling firewalls on both
Installed VMtools
Monitored the server stats; memory, cpu, etc. aren't being stressed
greatly at all by the VM.
Moving files on the same disk to another location via another
computer(accessed as a shared network folder) moves just as slowly. If I
connect and do the same thing via RDP the speed is 7-10mb moving them on
the same disk.
I'm completely befuddled....any ideas? Could it be some security
rule/configuration that I need to remove? Upgrade to the lastest VM?

return value only when it is not null else recheck it..... c#

return value only when it is not null else recheck it..... c#

Return the value only when it is set. if I use a condition to check the
null condition it is throwing a exception. "saying not all code paths
return a value"
private void HandlePinsAvailable(byte[] pinBytes)
{
pinmesssage = Encoding.ASCII.GetString(pinBytes);
}
internal string GetPinMessage(string AccoutNumber)
{
string pinstring = string.Empty;
obj.SendPinRequest(AccoutNumber);
pinstring = pinmesssage;
return pinstring;
}
private string _pinMessafe;
public string pinmesssage
{
get//Not all Code paths return a value
{
if (_pinMessafe != null)
return _pinMessafe;
}
set { _pinMessafe = value; }
}

MPMoviePlayer Lock Screen Play/Pause for Audio

MPMoviePlayer Lock Screen Play/Pause for Audio

I am running streamed audio through MPMoviePlayer. I can send remote
events to the lock screen and dock so that I am able to see the titles and
authors, and the audio plays in background mode, but I can not for the
life of me make the lock screen/dock play button start and stop audio. Am
I completely missing something?
Here's my code:
#import "teachingsDetailViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "RSSItem.h"
#import "RSSLoader.h"
@implementation teachingsDetailViewController
@synthesize moviePlayerController;
-(void)viewDidLoad:(BOOL)animated
{
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance]
setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
NSLog(@"The System ran this");
//Load the audio into memory
[moviePlayerController prepareToPlay];
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated {
[super loadView];
RSSItem* item = (RSSItem*)self.detailItem;
self.title = item.title;
moviePlayerController = [[MPMoviePlayerController alloc]
initWithContentURL:item.link];
NSLog(@"The url is %@", item.link);
[self.view addSubview:moviePlayerController.view];
moviePlayerController.movieSourceType = MPMovieSourceTypeUnknown;
moviePlayerController.fullscreen = YES;
if ([[UIApplication sharedApplication]
respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:NULL];
NSLog(@"The System ran this");
[self becomeFirstResponder];
NSLog(@"Responds!");
}
[moviePlayerController play];
//here
Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
if (playingInfoCenter) {
NSError *error= nil;
if ([[AVAudioSession sharedInstance] setCategory:
AVAudioSessionCategoryPlayback error:&error]) {
NSLog(@"Error setting audio session: %@", error);
}
NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] init];
[songInfo setObject:self.title forKey:MPMediaItemPropertyTitle];
[songInfo setObject:@"AU One Place" forKey:MPMediaItemPropertyArtist];
[songInfo setObject:@"Teachings" forKey:MPMediaItemPropertyAlbumTitle];
[songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
}
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//End recieving events
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
NSLog(@"Stopped receiving remote control events");
[self resignFirstResponder];
}
-(void)viewDidDisappear:(BOOL)animated
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidUnload {
[super viewDidUnload];
}

Bind slave records are unreadable

Bind slave records are unreadable

I noticed that a month or two ago that my bind records for the slave
server became unreadable. The consequence of having an unreadable record
is that it appears as though Webmin cannot read the record. I used to be
able to go into Webmin on the slave machine to validate that the record
was updated there, I can no longer do that.
It appears to still be a valid record because I can query the server
itself and it returns the same data (NSLOOKUP, etc). So it appears as
though Bind can read the file fine.
I would like this resolved, but I'm not sure where to look. Any thoughts?
Here is are the the master and slave records:
===MASTER===
BIND version 9.8.4
Debian Linux 7
$ttl 38400
servertest.com. IN SOA testdns.com. foobar.testdns.com. (
1377180224
7200
3600
1209600
38400 )
servertest.com. IN NS ns1.testdns.com.
servertest.com. IN NS ns2.testdns.com.
===SLAVE===
BIND version 9.9.2
Ubuntu Linux 13.04
^@^@^@^B^@^@^@^AR^V^Z_^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@[^@^A^@^F^@^@^@^@~
V^@^@^@^@^A^@^P
servertest^Ccom^@^@5^Gtestdns^Ccom^@^Ffoobar^Gtestdns^Ccom^@R^V^Z@^@^@
^\ ^@^@^N^P^@^Ru^@^@^@~V^@^@^@^@J^@^A^@^B^@^@^@^@~V^@^@^@^@^B^@^P
servertest^Ccom^@^@^Q^Cns1^Gtestdns^Ccom^@^@^Q^Cns2^Gtestdns^Ccom^@
All the details are there, but the slave is unreadable. (copy and pasted
from PuTTy

JQuery get id from $(this) not working, but getting another attribute does

JQuery get id from $(this) not working, but getting another attribute does


I've searched the web and tried every proposed method I can find, but
nothing seems right for my case.
The problem is this: I need to get the id of the checked element so I know
which element to change/manipulate later.
My problem is most curious because I do a $(this).attr("tag"); and get the
right value returned for later use.
But then I try $(this).attr("id") and when I alert it, it's just an empty
alert. I have also tried alternate methods.
I've done this.id and var $this = $(this); $this.id/$this.attr("id");
I cannot for the life of me figure out why it works on one attribute, but
not another when they're both within the same method, right after one
another.
$('.jq-toggleExternal').click(function () {
var refNo = $(this).attr("tag");
var checked = $(this).find(':checkbox').is(':checked');
var controls = getReferenceContolsByRefNo(refNo);
var id = $(this).attr('id');
alert(id);
<asp:CheckBox ID="r_chkRef1External" runat="server"
CssClass="jq-toggleExternal"
tag="1" Text="Ekstern" onClick="changed(this)" />
I've also tried changing the ID to id, but same result and if I change the
attr search to attr("ID") it says undefined.
Any possible solutions/alternative ways to get the id is highly appreciated.

Getting diffrent type of alert in chrome

Getting diffrent type of alert in chrome

I am working with some web application..Some times My chrome alert is
worning normal..But some times its acting differently ( Means UI) .. What
kind of chages have made for this.
Thanks..

Wednesday, 21 August 2013

Does YouTube's upload page prevents Windows from entering sleep mode while uploading?

Does YouTube's upload page prevents Windows from entering sleep mode while
uploading?

If I set Windows to suspend the computer after 30 min of inactivity in the
Control Panel and leave a video uploading in Google Chrome, will the
computer suspend or will the upload page prevent the windows from
suspending? (like Windows Media Player does when playing a movie)

How to deploy a simple Drools application?

How to deploy a simple Drools application?

How to deploy a simple Drools application?
Please note that this is not a web-application. It's just a simple rules
engine application that evaluates a set of facts pertaining to a set of
POJO variables.
I couldn't find any specific information on the official Drools website or
in Google search results/stack overflow.
I'm working my way through the Drools examples
(http://docs.jboss.org/drools/release/5.5.0.Final/drools-expert-docs/html_single/#d0e8772)
on Eclipse and would like to deploy a simple example on a Linux machine -
as a stepping stone to deploying a more complex application.
Shouldn't this be straightforward as in exporting a runnable JAR from
Eclipse, copying out this JAR to a Linux machine and then invoking this
JAR by way of # java -jar .jar ?
Help appreciated. Thanks.

Use "appId|appSecret" as access_token

Use "appId|appSecret" as access_token

I've found in documentation that it is possible to use appId and appSecret
pair as access_token in the format "appId|appSecret".
The problem, when I'm using this technique with graph API, I don't receive
the full information, only some of the fields (permissions are set in the
app settings). When I'm trying to use it with FQL I get "A user access
token is required to request this resource." exception.
Could somebody route me on the right track how to perform API requests?
My application is running on the server-side, that's why I've chosen these
method.

Can you write a c# decorator function that can take any number of arguments?

Can you write a c# decorator function that can take any number of arguments?

I currently have code which acts much like a python decorator, it takes a
function as argument and returns the same function wrapped by another (in
this case opening and closing a perforce connection).
public Func<TArg, TReturn> EnableP4<TReturn, TArgs>(Func<TArg,
TReturn> function)
{
Func<TArg, TReturn> p4Wrapper = (TArg funcArg) =>
{
try
{
if (con.Status.Equals(ConnectionStatus.Disconnected)) {
con.Connect(options); }
return function(funcArg);
}
finally { con.Disconnect(); }
};
return p4Wrapper;
}
At the moment this only works for functions with one argument and I was
wondering if it could be made more general (maybe if there is a way of
unpacking an array into a method?).
(Something along the lines of this?)
public Func<TArgs, TReturn> EnableP4<TReturn, TArgs>(Func<TArgs,
TReturn> function)
{
Func<TArgs, TReturn> p4Wrapper = (TArgs args) =>
{
try
{
if (con.Status.Equals(ConnectionStatus.Disconnected)) {
con.Connect(options); }
return function(*args);
}
finally { con.Disconnect(); }
};
return p4Wrapper;
}
where TArgs is a TArg[].

Javascript - Get LONG* from COM/ActiveX

Javascript - Get LONG* from COM/ActiveX

I'm using an embedded ActiveX media player which I'm calling from
JS/JQuery. I can call functions and set properties in the player without
issue. However, one of the properties I need from the ActiveX control is a
LONG* pointer, which has the signature....
get_CurrentPlaybackTime_Sec(LONG* pVal)
..and I'm not really sure where to start. I've done some Googling and
found some loose references to BSTR in Javascript, but I'm unsure how to
implement it. I need an equivilent of an 'out' that I use in C# I suppose.
Here is where I am so far...
$("#fooBtn").click(function(){
var currTime;
o.get_CurrentPlaybackTime_Sec(currTime);
$("#fooDiv").text(currTime);
});
Can someone point me in the right direction please? Any help much
appreciated.

Tuesday, 20 August 2013

Custom UITableViewCell Indentation Issue

Custom UITableViewCell Indentation Issue

I've got an interesting problem (please forgive me if this was asked... I
searched Google, actually Bing since I don't use Google, and stack with no
results).
I am creating a custom UITableViewCell with UIIMageView (310 x 310) inside
of the content view of the cell. When everything is said and done and I
actually set the image of the imageView in my controller using cellForRow:
[feedCell.imageView setImage:[UIImage imageNamed:@"image-placeholder"]];
I get this result:

^ Not what I want.
When I get the image view from the tableView using viewWithTag method and
then set the image of the imageView directly, I get the desired result:
UIImageView *imageView = (UIImageView *)[tableView viewWithTag:1];
[imageView setImage:[UIImage imageNamed:@"image-placeholder"]];

So the question is, what is it that I am missing? Why would setting the
imageView via custom cell class be so off while it works otherwise? I
would love to use custom subclass.
P.S. Don't mind Batman stuff. Although I am kind of a fan... liked the 2nd
one the best.

Finding path, the sum of whose numbered edges is 48

Finding path, the sum of whose numbered edges is 48

Let $G$ be a graph with vertices $\{1,...,10\}$. Two vertices $a,b$ have
an edge if $a|b$ or $b|a$. Find a path in $G$ so that the sum of the
corners in the path equals 48.
I solved this using "brute force", $9-3-6-2-8-4-1-10-5$, but is there a
more efficient way? In particular one that doesn't rely on drawing the
graph in a clever way.

Data structure with fast contiguous ranges retrieval

Data structure with fast contiguous ranges retrieval

Imagine data structure, that manipulates some contiguous container, and
allows quick retrieval of contiguous ranges of indices, within this array,
that contains data (and probably free ranges too). Let's call this ranges
"blocks". Each block knows its head and tail index:
struct Block
{
size_t begin;
size_t end;
}
When we manipulating array, our data structure updates blocks:
array view blocks [begin, end]
--------------------------------------------------------------
0 1 2 3 4 5 6 7 8 9 [0, 9]
pop 2 block 1 splitted
0 1 _ 3 4 5 6 7 8 9 [0, 1] [3, 9]
pop 7, 8 block 2 splitted
0 1 _ 3 4 5 6 _ _ 9 [0, 1] [3, 6] [9, 9]
push 7 changed end of block 3
0 1 _ 3 4 5 6 7 _ 9 [0, 1] [3, 7] [9, 9]
push 5 error: already in
0 1 _ 3 4 5 6 7 _ 9 [0, 1] [3, 7] [9, 9]
push 2 blocks 1, 2 merged
0 1 2 3 4 5 6 7 _ 9 [0, 7] [9, 9]
Even before profiling, we know that blocks retrieval speed will be
cornerstone of application performance. Basically usage is: - very often
retrieval of contiguous blocks - quite often write - quite rare
insertions/deletions
What we have already tried:
std::vector<bool> + std::list<Block*>. On every change: write true/false
to vector, then traverse it in for loop and re-generate list. On every
query of blocks return list. Slower than we wanted.
std::list<Block*> update list directly, so no traversing. Return list.
Much code to debug/test.
Questions:
Is that data structure has some generic name?
Is there already such data structures implemented (debugged and tested)?
If no, what can you advice on fast and robust implementation of such data
structure?
Sorry if my explanation is not quite clear.

Passing a cursor to an Oracle stored procedure via MyBatis

Passing a cursor to an Oracle stored procedure via MyBatis

I have a stored procedure which takes a list of records as a cursor. I
would like to call it from a MyBatis mapper. I assumed that this would be
similar to reading a cursor as an output parameter, but this does not
appear to be the case. Below is the mapper entry:
@Select({CALL pkg_transaction_info.pr_transaction_add("
+ "#{pcur_trx_info, mode=IN, jdbcType=CURSOR,
javaType=java.sql.ResultSet, resultMap=txnInfoRM})
@ResultMap("txnInfoRM")
@Options(statementType = StatementType.CALLABLE)
public void addTransactionInfo(Map<String, Object> params);
... where txnInfoRM describes the mapping between my Java objects and the
columns that the stored procedure expects. In the parameter map I've tried
passing in a list of objects, hoping that the translation to a ResultSet
would happen implicitly, as it does when receiving a cursor as an output
parameter, but to no avail. Is it even possible to pass in a Cursor in
this manner? Do I need to write a custom typehandler to open it for me
using the Oracle api?

Getting wrong value when multiplying

Getting wrong value when multiplying

I am writing an Android app and I have an algorithm to calculate some
score out of several variables but when computing, I get wrong answer:
I get 10300 when I set mv, ptv, txtv to 10 whereas I should get 100. When
I set it to 1, I get 300 as answer.
int f;
f = (((mv*ptv*txtv)/10^3)*100);
int finalScr = f;
TextView scoreView = (TextView)findViewById(R.id.textView3);
scoreView.setText(Integer.toString(finalScr));
All the variables are integers and the maximum value of all the variables
is 10 and minimum is 1.
Please help.. I don't think I am mathematically wrong :P

Remove timestamp from NSString

Remove timestamp from NSString

I have a NSString filled with the following from my json parser.
"2013-08-22 00:00:00";
How i can i remove the timestamp from this? "00:00:00";
Thanks.
P.s i tried using the substringWithRange:NSMakeRange function.

Formatting Decimal Number

Formatting Decimal Number

I am formatting decimal number and I have the following criteria to format
it:
Number should be atmost two decimal places (10.1234=>10.12)
If there is only one digit after decimal then it will ends up with 0
(10.5=>10.50)
Thousand separator will be comma (12345.2345 => 12,345.23)
I have written following logic:
double x = Double.parseDouble(value.toString());
String dec = x % 1 == 0 ? new
java.text.DecimalFormat("###,###.##").format(x) : new
java.text.DecimalFormat("###,###.00").format(x);
Now it is printing:
11111111111110.567=>11,111,111,111,110.57
111111111111110.567=>111,111,111,111,110.56
1111111111111110.567=>1,111,111,111,111,110.60
11111111111111110.567=>11,111,111,111,111,110
111111111111111110.567=>111,111,111,111,111,104
1111111111111111110.567=>1,111,111,111,111,111,170
I don't understand why the behavior changes. If I what to print
1111111111111111110.567 as 1,111,111,111,111,111,110.57 what should I do?

Monday, 19 August 2013

Failed to create writable database

Failed to create writable database

I stored some images in my server. And try to get this images from JSON
URL and store to local database then try to access. But the images are not
storing to database. Im getting this error: Failed to create writable
database file with message 'The operation couldn't be completed. (Cocoa
error 516.)'.
code:
- (void)viewDidLoad
{
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSError *err;
NSString *bundlePath = [[NSBundle mainBundle]
pathForResource:@"db1" ofType:@"sqlite"];
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//NSLog(@"docs dir is %@", documentsDirectory);
NSString *appFile = [documentsDirectory
stringByAppendingPathComponent:@"db1.sqlite"];
// [fileMgr copyItemAtPath:bundlePath toPath:appFile error:&err];
BOOL success = [fileMgr copyItemAtPath:bundlePath toPath:appFile
error:&err];
if (success) {
NSLog(@"success");
}else{
NSLog(@"Failed to create writable database file with message
'%@'.", [err localizedDescription]);
}
NSURL *URL = [NSURL
URLWithString:@"http://myserver.net/projects/mobile/jsonstring.php"];
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:URL
encoding:NSUTF8StringEncoding
error:&error];
NSString *path = [documentsDirectory
stringByAppendingPathComponent:@"db1.sqlite"];
NSArray *userData = [stringFromFileAtURL JSONValue];
[stringFromFileAtURL release];
}

Terminal Command Fails because of Space in Path

Terminal Command Fails because of Space in Path

I tried setting up a Ruby on Rails project on my nice safe volume "Data
RAID". The set up with some strange that I eventually tracked down to the
space in the path name. It works if I execute it on another volume. I
tried setting up a symlink to the directory, which works fine with the CD
command, but doesn't help with the set up. Is it possible to get an
application to use a symlink or other method that avoids the pathname with
a space?
The command I'm running that error out is
Rails new projectnamae
One other twist is something I set up to specify the location of the gems:
mkdir ~/.bundle
touch ~/.bundle/config
echo 'BUNDLE_PATH: vendor/bundle' >> ~/.bundle/config
It is with the gems that I'm getting the error.

java.lang.OutOfMemoryError: GC overhead limit

java.lang.OutOfMemoryError: GC overhead limit

I have a program that reads a large list of sequences from a file and does
a calculation among all of the pairs in that list. It then stores all of
these calculations into a hashset. When running this program about halfway
through, I get a GC overhead limit error.
I realize this is because the garbage collector is using up 98% of the
computation time and is unable to recover even 2% of the heap. Here is the
code I have:
ArrayList<String> c = loadSequences("file.txt"); // Loads 60 char DNA
sequences
HashSet<DNAPair,Double> LSA = new HashSet<DNAPair,Double>();
for(int i = 0; i < c.size(); i++) {
for(int j = i+1; j < c.size(); j++) {
LSA.put(new
DNAPair(c.get(i),c.get(j)),localSeqAlignmentSimilarity(c.get(i),c.get(j)));
}
}
And here's the code for the actual method:
public static double localSeqAlignmentSimilarity(String s1, String s2) {
s1 = " " + s1;
s2 = " " + s2;
int max = 0,h = 0,maxI = 0,maxJ = 0;
int[][] score = new int[61][61];
int[][] pointers = new int[61][61];
for(int i = 1; i < s1.length(); i++) {
pointers[i][0] = 2;
}
for(int i = 1; i < s2.length(); i++) {
pointers[0][i] = 1;
}
boolean inGap = false;
for(int i = 1; i < s1.length(); i++) {
for(int j = 1; j < s2.length(); j++) {
h = -99;
if(score[i-1][j-1] + match(s1.charAt(i),s2.charAt(j)) > h) {
h = score[i-1][j-1] + match(s1.charAt(i),s2.charAt(j));
pointers[i][j] = 3;
inGap = false;
}
if(!inGap) {
if(score[i-1][j] + GAPPENALTY > h) {
h = score[i-1][j] + GAPPENALTY;
pointers[i][j] = 2;
inGap = true;
}
if(score[i][j-1] + GAPPENALTY > h) {
h = score[i][j-1] + GAPPENALTY;
pointers[i][j] = 1;
inGap = true;
}
} else {
if(score[i-1][j] + GAPEXTENSION > h) {
h = score[i-1][j] + GAPEXTENSION;
pointers[i][j] = 2;
inGap = true;
}
if(score[i][j-1] + GAPEXTENSION > h) {
h = score[i][j-1] + GAPEXTENSION;
pointers[i][j] = 1;
inGap = true;
}
}
if(0 > h)
h = 0;
score[i][j] = h;
if(h >= max) {
max = h;
maxI = i;
maxJ = j;
}
}
}
double matches = 0;
String o1 = "", o2 = "";
while(!(maxI == 0 && maxJ == 0)) {
if(pointers[maxI][maxJ] == 3) {
o1 += s1.charAt(maxI);
o2 += s2.charAt(maxJ);
maxI--;
maxJ--;
} else if(pointers[maxI][maxJ] == 2) {
o1 += s1.charAt(maxI);
o2 += "_";
maxI--;
} else if(pointers[maxI][maxJ] == 1) {
o1 += "_";
o2 += s2.charAt(maxJ);
maxJ--;
}
}
StringBuilder a = new StringBuilder(o1);
b = new StringBuilder(o2);
o1 = a.reverse().toString();
o2 = b.reverse().toString();
a.setLength(0);
b.setLength(0);
for(int i = 0; i < Math.min(o1.length(), o2.length()); i++) {
if(o1.charAt(i) == o2.charAt(i)) matches++;
}
return matches/Math.min(o1.length(), o2.length());
}
I thought that this was because of all the variables I declare inside the
method (the two int arrays and the stringbuilders etc.) creating more and
more objects every time the method is run so I changed them all to static
fields and cleared them everytime (ex. Arrays.fill(score,0);) instead of
creating a new object.
However this didn't help at all and I still got the same error.
Could it be that the hashset that stores all of the calculations is
getting too big and is unable to be stored by java? I'm not getting an out
of heap space error so it seems kind of strange.
I also changed the command line argument to give more space to the JVM but
that didn't seem to help.
Any insight on this problem would be helpful. Thanks!

fadeout after 5 secs jquery

fadeout after 5 secs jquery

I have the below jquery function to hide DIV on click. How can I add
fadeout effect after 5 secs if the user doesn't click? I would like to
have both.
$(".fadeOutbox").click(function () {
$(this).fadeOut('slow');
});

submit form with enter key that has button in it

submit form with enter key that has button in it

I need to submit the form with the enter key, but it is not like the other
questions in this website in my case. I do not have a
input[type="submit"], but I have a button (<button id=""></button>).
The full code of my form:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/my_script.js" type="text/javascript"></script>
<form id="myForm" action="userInfo.php" method="post">
<textarea name="mesazhi" cols="35" rows="4"></textarea>
<?php $idiperdoruesit = $_SESSION['id']; ?>
<input type="hidden" name="idiperdoruesit" value="<?php echo
$idiperdoruesit; ?>" />
<br /><button id="sub" style="border-radius:0px; border-size:2px;
border-style:solid; border-color:#ffffff; border-width:thin;
background-color:#000000; color:#ffffff; height:26px; width:60px;
font-size:16px;">Send</button>
</form>
When the user clicks the button Send, then a jquery function sends the
message to the database without reloading the page. Below is the jquery
function:
$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#myForm").submit( function() {
return false;
});
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
How can I make to send the message by pressing the enter key?

Sunday, 18 August 2013

Unable to run MVC 4 Razor C# solution with test

Unable to run MVC 4 Razor C# solution with test

My solution is in MVC 4 Razor C# with Test module. When I press F5 it just
runs MySolution.Test Module and gives me test results only.
Can anyone help me hoe do i run my solution.?

MySQL sort varchar as number issue

MySQL sort varchar as number issue

I have seen lots of question like this on SO and I tried to implement the
answers into my particular situation but I am having no luck. Some help
would be greatly appreciated.
Query
SELECT `avatar` from `users` ORDER BY ABS(`avatar`) ASC;
Result
+--------------------------------+
| avatar |
+--------------------------------+
| 0/1_default.jpg |
| 1/3_483487-1440x900_qp8a5a.jpg |
| 1/122_default.jpg |
| 1/321_default.jpg |
| 1/25_wefvvv.jpg |
| 1/1000_latest.jpg |
| 2/12_wefwefwef.jpg |
| 2/1_default.jpg |
+--------------------------------+
I tried to sort by ABS and columns but unless I made a new column or a
dedicated table, I cannot find a way to sort this the way I want it to.
Essentially, I want to sort it numerically and a desired outcome would be
something like:
Desired result
0/1
1/3
1/25
1/122
1/321
2/1
2/12
From the searches on SO, I know there is the SUBSTR function but with the
'/' in the middle, I am not sure how I can get it to sort properly.

HTML form will not submit

HTML form will not submit

This is my form
<html>
<head><title>Hawkins Car Records</title></head>
<body><h1>Add New Car</h1></body>
<form action="carNewBack.php" method="POST">
Car Name: <input type="text" name="carName"/>
<br>
Make: <input type="text" name="make"/>
<br>
Model: <input type="text" name="model"/>
<br>
Year: <input type="text" name="year"/>
<br>
Last 5 digits of VIN: <input type="text" name="lastVIN"/>
<br>
Plate: <input type="text" name="plate"/>
<br><br>
<input type="submit" value="Submit"/>
</form>
</html>
When I hit the submit button, nothing happens. No white screen, no 404,
nothing. It doesn not execute carNewBack.php. Can someone share any ideas?
Here is the action file. Im trying to build a data base of service records
of my family's cars and this is the form that takes input and creates a
new car record.
<?php
$carconnect = mysqli_connect("localhost", "carUser", "caps271:snows",
"cars");
if (mysqli_connect_errno()) {
printf("connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$carName = mysqli_real_escaped_string($carconnect, $_POST['carName']);
$make = mysqli_real_escaped_string($carconnect, $_POST['make']);
$model = mysqli_real_escaped_string($carconnect, $_POST['model']);
$year = mysqli_real_escaped_string($carconnect, $_POST['year']);
$lastVIN = mysqli_real_escaped_string($carconnect, $_POST['lastVIN']);
$plate = mysqli_real_escaped_string($carconnect, $_POST['plate']);
$sql = "INSERT INTO cars (carName, make, model, year, lastVIN, plate)
VALUES ('". $carName."', '".$make."', '".$model."',
'".$year."', '".$lastVIN."', '". $plate."')";
$res = mysqli_query($carconnect, $sql);
if ($res === TRUE) {
echo "Car added";
} else {
printf ("Could not insert car: %s\n", mysqli_error($carconnect));
}
mysqli_close($carconnect);
}
?>

Windows C Drive --(transfer to)--> Mac OS Extended (Case-Sensitive, Journaled, Encrypted) : Within Windows

Windows C Drive --(transfer to)--> Mac OS Extended (Case-Sensitive,
Journaled, Encrypted) : Within Windows

I have an external hard drive whose format is Mac OS Extended
(Case-Sensitive, Journaled, Encrypted), and I would like to copy my
friend's entire computer--it's running Windows 7 Home Premium--to the free
space on this external drive. How can I do this, and once I have a method
of transferring Windows files to a drive with Mac OS Extended format can I
just drag and drop the C drive of the Windows machine into the external
drive?

How to bind a dynamically created object to the document ready event?

How to bind a dynamically created object to the document ready event?

I have a function that dynamically creates a slider element using the
following code:
function NewDiv(){
for (var count=0; count < parseFloat(sessvars.storey_count); count++)
{
var string="<br><div id='my-slider"+count+"'
class='dragdealer'><div class='red-bar handle'><span
id='drag-button"+count+"'>drag me</span></div></div>";
$("body").append(string);
var slider_id ="my-slider"+count;
var drag_button_id = "drag-button"+count;
//OBJECT GETS CREATED BELOW
new Dragdealer(slider_id,{horizontal:
true,x:Math.random(),animationCallback: function(x, y){
document.getElementById(drag_button_id).innerHTML =
x.toFixed(2);
}
});
}
}
However, the animationCallback function which is invoked everytime the
slider is moved has to be embedded within a function listener, and I have
to somehow bind it to maybe the ready event. Is this the best way to make
the slider update when its value changes? And if so, how do I go about
doing this?

How do I add a posted by 'user.email' to my app index?

How do I add a posted by 'user.email' to my app index?

So, the index I'm referring to is in songs#index.html.erb.
I'd like to add a line like this:
posted by <%= song.user.email %> <%= time_ago_in_words(song.created_at) +
" ago" %>
which at the moment is returning:
undefined method `email' for nil:NilClass
Song.rb snippit
class Song < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
acts_as_voteable
belongs_to :user, class_name: User, foreign_key: :user_id
has_many :comments, :dependent => :destroy
has_many :genre_songs
has_many :genres, through: :genre_songs
User.rb snippit
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable
has_many :songs
has_many :comments
schema snippits
create_table "users", id: false, force: true do |t|
t.integer "id", null: false
t.string "email", default: ""
t.string "encrypted_password", default: ""
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "admin"
t.string "provider"
t.string "uid", null: false
t.string "username"
end
add_index "users", ["reset_password_token"], name:
"index_users_on_reset_password_token", unique: true, using: :btree
create_table "songs", force: true do |t|
t.string "title"
t.string "artist"
t.text "url"
t.string "track_file_name"
t.string "track_content_type"
t.integer "track_file_size"
t.datetime "track_updated_at"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "plusminus"
t.string "slug"
end
add_index "songs", ["slug"], name: "index_songs_on_slug", unique: true,
using: :btree

Issue with masked input

Issue with masked input

I made this test code to test this plugin, but can't seem to get it to
work, any ideas why? It does not add the -'s in like masked input should.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript"
src="http://digitalbush.com/wp-content/uploads/2013/01/jquery.maskedinput-1.3.1.min_.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$("#dater").mask("9999-99-99");
});
</script>
</head>
<body>
<input name="dater" type="text" id="dater" value="" />
</body>
</html>
This is all that is on the page. https://coyoteridgezion.com/manage/test.php

Saturday, 17 August 2013

Layering UIImageView and UIBezierPath

Layering UIImageView and UIBezierPath

I have a an array of UIBezierPaths which I drew and also a UIImageView all
put on a UIView. When I draw a UIBezierPath and save it to the array, then
add a UIImageView, then draw another path, the second path will appear
behind the image. Is there something such as a bringSubViewToFront sort of
thing for UIBezierPath?

Pyglet window will not redraw on resize

Pyglet window will not redraw on resize

I have a class that is subclassed to pyglet.window.Window, and I need it
to be a resizable window. I figured out how to enable it to be resized,
but I need to make it redraw everything on the screen when I actually do
resize it. Here's what I have so far:
if __name__ == '__main__':
window = Application()
@window.event()
def on_resize(x,y):
window.label.x = window.WindowSize[0]/2
window.label.y = window.WindowSize[1]*15/16
@window.event()
def on_draw():
window.clear()
window.label.draw()
for control in window.controls:
control.draw()
pyglet.app.run()
so we make our window and then have those two window events. I hope I did
that right--I'm fairly new to pyglet. As I said, the main problem is that
when I resize the window it doesn't actually change anything unless I
press one of the buttons on the window which changes the positions.

Cocos2d - scheduled selector never called

Cocos2d - scheduled selector never called

For some reason one of the methods I'm scheduling isn't getting called.
The class's parent's parent inherits from CCNode. The class's parent has a
method called resetCoolDown like this:
- (void) resetCoolDown:(ccTime)dt {
_onCoolDown = false;
}
I schedule like this:
[self scheduleOnce:@selector(resetCoolDown:) delay:1];
There are no issues scheduling the selector, but for some reason
resetCoolDown is never called.
Am I doing something wrong?

Flyway seems to not be overriding properties

Flyway seems to not be overriding properties

I have my standard flyway config in my pom file and I am trying to
override in through system properties, as mentioned here.
Here is my configuration in the pom file:
<plugin>
<groupId>com.googlecode.flyway</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<url>dbUrl</url>
<user>dbUser</user>
<password>dbPass</password>
<schemas>
<schema>core</schema>
<schema>public</schema>
</schemas>
</configuration>
</plugin>
And following is the command line that I'm running:
mvn clean compile flyway:migrate -Dflyway.url=anotherDbUrl
-Dflyway.user=anotherDbUser -Dflyway.password=anotherDbPass
The documentation in the above link says System properties > Maven
properties > Plugin configuration. Am I missing something?