Monday, 30 September 2013

Photo storage / sort

Photo storage / sort

I'm wondering what the best practice is for photo storage. I'm in the
business of storing photos with a user. Each user can have up to 35 photos
and we currently have around a 100k users. I currently reference the
photo's from a database.
My proposed solution is a hash of the photo name like so.
f56c0de1c61fdb926e79e8a0a65bd12930c9.jpg
broke out into directories like so
Photo 1
f5/6c/0d/e1c61fdb926e79e8a0a65bd12930c9.jpg
f5/6c/0d/e1c61fdb926e79e8a0a65bd12930c9_thumb.jpg
Photo2
ec/1c/55/bfb660548a6770238668c4b117d92f.jpg
ec/1c/55/bfb660548a6770238668c4b117d92f_thumb.jpg
database Stored in the database as a comma separated array like so for
sort ordering.
ec1c55bfb660548a6770238668c4b117d92f,ec1c55bfb660548a6770238668c4b117d92f
Is this the most efficient way to do this? and is it scalable? I'm not
sure if the photo hash is to large and I'm also not sure if the directory
size is correct.
I created a more detailed post over on stackoverflow, just not sure where
this question belongs.
http://stackoverflow.com/questions/19106596/how-to-store-photo-on-file-system-and-store-sort-order-in-database

Making XMonad redetect two monitors [migrated]

Making XMonad redetect two monitors [migrated]

I accidentally pressed Meta-Q and xmonad restarted. Now, it has mirrored
the same thing on both of my monitors. How do I get it go back to treating
them as two separate screens?
Things I have tried: - Pressing Meta-Q again - Turning one of the monitors
off and back on
This has happened before, and logging out and back in again worked. But I
don't want to do that every time I accidentally press Meta-Q. This has
started happening since I started using dmenu_run to launch apps.
Previously, Meta-Q would restart xmonad harmlessly (without going into
mirrored mode).

Toggling a absolute DIV is not working after firsttime

Toggling a absolute DIV is not working after firsttime

$('.pallete').hide();
$(document).delegate('.pick', 'click', function () {
var pos = $(this).offset();
var x = pos.left - $(window).scrollLeft() + $(this).width();
var y = pos.top - $(window).scrollTop() + $(this).height();
$('.pallete').css({
top: y + "px",
left: x + "px",
}).show();
});
$(document).delegate('.col', 'click', function () {
var pos = $(this).css('background-color');
$('.pick').css('background-color', pos);
$(this).parents('div').fadeOut();
});
Here is the fiddle, http://jsfiddle.net/zPNk3/5/. The problem is when I
click first time on .pick element the '.palette' element is shown
properly. But when I click next time the same is not working.

How to get a TextView at the bottom of the screen under a listview?

How to get a TextView at the bottom of the screen under a listview?

I'm making a settings screen in my android app. This list of course has a
pre defined set of options (notifications/colors/log out/etc.). So I
decided to create the list statically in xml. Because the list should
equally well display if it has more content than the screen I nested my
LinearLayout within a ScrollView (couldn't use a ListView because I want
to statically define the items in it).
This works fine with the following code now:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/black" >
<TextView
android:layout_width="fill_parent"
android:layout_height="80dp"
android:paddingTop="30dp"
android:text="@string/account_notifications"
android:background="@color/white"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="80dp"
android:text="@string/colors"
android:background="@color/white"
android:layout_marginBottom="1dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="80dp"
android:text="@string/log_out"
android:background="@color/white"
android:layout_marginBottom="1dp" />
</LinearLayout>
</ScrollView>
As you can see I set the background of the LinearLayout to black and the
items to white, with a marginBottom of 1dp, so that there is a separator
between the list items. I now want the logout TextView always at the
bottom of the screen. In case there are more items than the screen can
hold, the Logout should simply be situated at the end of the list.
To get the logout to the bottom of the screen I found some solutions in
this SO question. I first use the first suggestion like so:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/black" >
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/account_notifications"
android:background="@color/white"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/colors"
android:background="@color/white"
android:layout_marginBottom="1dp" />
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/log_out"
android:background="@color/white"
android:layout_marginBottom="1dp"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</ScrollView>
This surprisingly makes the logout TextView totally disappear. So I tried
the second suggestion like so:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/black" >
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:layout_weight="1"
android:text="@string/account_notifications"
android:background="@color/white"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:layout_weight="1"
android:text="@string/colors"
android:background="@color/white"
android:layout_marginBottom="1dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/log_out"
android:background="@color/white"
android:layout_marginBottom="1dp" />
</LinearLayout>
</ScrollView>
But this unfortunately doesn't do anything either. No clue why not.
So my question, does anybody know how I can get my logout to the bottom of
the screen, or in case the list is to long for the screen, to the bottom
of the list.
All tips are welcome!

Sunday, 29 September 2013

Store the line break from textarea , store to database and show on frontend?

Store the line break from textarea , store to database and show on frontend?

Currently I am working on storing textarea paragraph
<textarea rows="10"></textarea>
I can save the whole content but the problem is it does not include line
breaks. I wonder what is the best practice of storing the space/line break
from the textarea to database. Also, I need to prevent the user from
inserting the inside the textarea.
Is it good parctice ?
e.g.
text=replace(text,"/n","<br>")
text=replace(text," ","&nbsp;")
text=replace(text,"<script>","")
text=replace(text,"</script>","")
Thanks

Repeating after wrong answer

Repeating after wrong answer

Today I was messing around and I was trying to create a multiple choice
test. I got this far and it works. I was wondering though, how would I
make it repeat the question if the user got the answer wrong? If anyone
could help me out that would be fantastic! Thanks!
import java.util.Scanner;
public class multipleChoiceTest {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("What color is the sky?");
System.out.println("A. Blue");
System.out.println("B. Green");
System.out.println("C. Yellow");
System.out.println("D. Red");
String userChoice = myScanner.nextLine();
if (userChoice.equalsIgnoreCase("a")) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong! Try Again.");
}
}

Boolean value is set to true from the start

Boolean value is set to true from the start

Hey i have been trying to make this work, but i can't figure out what the
problem is.
I want the stopValue to be false when i start the app, and then it is
gonna be set by my actions in the app. I have found out boolean values are
false from the start and therefore my start intent is set to false.
This is not my only problem, when i have entered the start kilometers and
my stop kilometers it give me the stop kilometers only. and the result
should have been start - stop kilometers.
I don't know if these problems have a connection. Maybe i don't get the
sharedpreferences part right or maybe it's the putextra or getIntent part.
Thanks for your time.
My main class
public class Main extends Activity{
Button bStart, bStop;
TextView tvView;
Spinner spinner1;
boolean stopValue;
int startkilometer;
String date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bStart = (Button) findViewById(R.id.bStart);
tvView = (TextView) findViewById(R.id.tvView);
spinner1 = (Spinner) findViewById(R.id.spinner1);
date = getIntent().getStringExtra("datoen");
startkilometer = getIntent().getIntExtra("startkm", 0);
SharedPreferences sp =
getApplicationContext().getSharedPreferences("stopValue", 0);
stopValue = sp.getBoolean("stopper", stopValue);
SharedPreferences sp1 = getSharedPreferences("startkilometer",
Activity.MODE_PRIVATE);
startkilometer = sp1.getInt("startkm", startkilometer);
SharedPreferences sp2 = getSharedPreferences("date",
Activity.MODE_PRIVATE);
date = sp2.getString("datoen", date);
stopValue = getIntent().getBooleanExtra("stopper", stopValue);
if(stopValue){
bStart.setText("Start");
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent start = new Intent("com.uniqueapps.runner.START");
startActivity(start);
}
});
}
if(stopValue == false){
bStart.setText("Stop");
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent stop = new Intent("com.uniqueapps.runner.STOP");
stop.putExtra("startkm", startkilometer);
stop.putExtra("datoen", date);
startActivity(stop);
}
});
}
KilometerSQL info = new KilometerSQL(this);
info.open();
String data = info.getData();
info.close();
tvView.setText(data);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
SharedPreferences sp =
getApplicationContext().getSharedPreferences("stopValue", 0);
Editor edit = sp.edit();
edit.putBoolean("stopper", stopValue);
edit.commit();
SharedPreferences sp1 =
getApplicationContext().getSharedPreferences("startkilometer", 0);
Editor edit1 = sp1.edit();
edit1.putInt("startkm", startkilometer);
edit1.commit();
SharedPreferences sp11 =
getApplicationContext().getSharedPreferences("date", 0);
Editor edit11 = sp11.edit();
edit11.putString("datoen", date);
edit11.commit();
super.onPause();
}
My start class
public class Start extends Main implements OnClickListener {
Button bStartTur;
EditText etDate, etKm;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
bStartTur = (Button) findViewById(R.id.bStartTur);
bStartTur.setOnClickListener(this);
etDate = (EditText) findViewById(R.id.etdate);
etKm = (EditText) findViewById(R.id.etKm);
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
etDate.setText(format.format(new Date()));
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String date = etDate.getText().toString();
int startkilometer;
switch (v.getId()) {
case R.id.bStartTur:
startkilometer = Integer.valueOf(etKm.getText().toString());
Intent menu = new Intent("com.uniqueapps.runner.MENU");
menu.putExtra("stopper", false);
menu.putExtra("startkm", startkilometer);
menu.putExtra("datoen", date);
startActivity(menu);
break;
}
}
}
My stop class
public class Stop extends Main implements OnClickListener {
Button bStop;
EditText sqllocations, kilometer;
int startkilometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.stop);
bStop = (Button) findViewById(R.id.bstopTur);
bStop.setOnClickListener(this);
sqllocations = (EditText) findViewById(R.id.locations);
kilometer = (EditText) findViewById(R.id.kilometer);
sqllocations.setText("Unknown");
}
@Override
public void onClick(View v) {
int startkilometer;
int slutkilometer;
startkilometer = getIntent().getIntExtra("startkm", 0);
date = getIntent().getStringExtra("datoen");
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bstopTur:
slutkilometer = Integer.valueOf(kilometer.getText().toString());
int kortekm = (slutkilometer - startkilometer);
try{
String locations = sqllocations.getText().toString();
KilometerSQL entry = new KilometerSQL(this);
entry.open();
entry.createEntry(date, kortekm, locations);
entry.close();
}catch(Exception e){
e.printStackTrace();
}
Intent menu = new Intent("com.uniqueapps.runner.MENU");
menu.putExtra("stopper", true);
startActivity(menu);
break;
}
}
}
My SQL class
public class KilometerSQL {
public static final String KEY_ROWID = "date";
public static final String KEY_KILOMETER = "kilometer";
public static final String KEY_LOCATIONS = "locations";
private static final String DATABASE_NAME = "Kilometerdb";
private static final String DATABASE_TABLE = "kilometertable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " TEXT NOT NULL, " +
KEY_KILOMETER + " INTEGER, " +
KEY_LOCATIONS + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public KilometerSQL (Context c){
ourContext = c;
}
public KilometerSQL open(){
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String date, int kortekm, String locations) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID, date);
cv.put(KEY_KILOMETER, kortekm);
cv.put(KEY_LOCATIONS, locations);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String [] columns = new String []{ KEY_ROWID, KEY_KILOMETER,
KEY_LOCATIONS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = "";
int iDate = c.getColumnIndex(KEY_ROWID);
int iKilometer = c.getColumnIndex(KEY_KILOMETER);
int iLocations = c.getColumnIndex(KEY_LOCATIONS);
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iDate) + " " +
c.getString(iKilometer) + " " + c.getString(iLocations) + "\n";
}
return result;
}
}

jQuery does not delete user info

jQuery does not delete user info

I have a php page that uses a jQuery to confirm before deleting data,
Infact when I click delete it doesnt do anything the link doesnt do
anything, I tried my efforts still nothing happens, please assist me
my code teacher.php
<?php
require_once('../auth.php');
?>
<html>
<head>
<title>Silay Institute</title>
<link rel="stylesheet" href="../css/main.css" type="text/css"
media="screen" />
<!--sa poip up-->
<link href="src/facebox.css" media="screen" rel="stylesheet"
type="text/css" />
<script src="lib/jquery.js" type="text/javascript"></script>
<script src="src/facebox.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox({
loadingImage : 'src/loading.gif',
closeImage : 'src/closelabel.png'
})
})
</script>
<link rel="stylesheet" href="febe/style.css" type="text/css"
media="screen" charset="utf-8">
<script src="argiepolicarpio.js" type="text/javascript"
charset="utf-8"></script>
<script src="js/application.js" type="text/javascript"
charset="utf-8"></script>
<style>
#mainhhh {
background: none repeat scroll 0 0 #FFFFFF;
border: 8px solid #EEEEEE;
border-radius: 5px 5px 5px 5px;
box-shadow: 0 0 10px #4E707C;
font: 11px "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;
margin: 5em auto;
position: relative;
text-align: left;
width: 1000px;
}
#mainhhh h1 {
background: none repeat scroll 0 0 #0092C8;
border-bottom: 1px solid #007DAB;
color: #FFFFFF;
font-size: 14px;
margin: 0;
padding: 5px 10px;
text-shadow: 0 1px 0 #007DAB;
}
</style>
</head>
<body>
<div id="mainhhh">
<h1>
<a id="addq" href="index.php" title="click to enter homepage"
style="background-image:url('../images/out.png');
background-repeat:no-repeat; padding: 3px 12px 12px; margin-right:
10px;"></a>
<label for="filter">Filter</label> <input type="text" name="filter"
value="" id="filter" />
<a rel="facebox" href="addteacher.php" id="addq">Add Teacher</a>
</h1>
<table cellpadding="1" cellspacing="1" id="resultTable">
<thead>
<tr>
<th style="border-left: 1px solid #C1DAD7"> Name </th>
<th>ID Number</th>
<th>Work</th>
<th>Gender</th>
<th>Status</th>
<th>Birthday</th>
<th>Advisory</th>
<th> Action </th>
</tr>
</thead>
<tbody>
<?php
include('../connect.php');
$result = mysql_query("SELECT * FROM teacher");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
echo '<td style="border-left: 1px solid
#C1DAD7">'.$row['fname'].' '.$row['mname'].'
'.$row['lname'].'</td>';
echo '<td><div
align="left">'.$row['idnumber'].'</div></td>';
echo '<td><div
align="left">'.$row['work'].'</div></td>';
echo '<td><div
align="left">'.$row['gender'].'</div></td>';
echo '<td><div
align="left">'.$row['status'].'</div></td>';
echo '<td><div
align="left">'.$row['bday'].'</div></td>';
echo '<td><div align="left">';
$sdsd=$row['idnumber'];
$results = mysql_query("SELECT * FROM advisory
WHERE tid='$sdsd'");
while($rows = mysql_fetch_array($results))
{
echo $rows['level'].' section
'.$rows['section'];
}
echo '</div></td>';
echo '<td><div align="center"><a rel="facebox"
href="editprofile.php?id='.$row['id'].'"
title="Click To Edit">Edit Profile</a> | <a
href="#" id="'.$row['id'].'" class="delbutton"
title="Click To Delete">delete</a></div></td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "deleteteacher.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7"
}, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
</body>
</html>
deleteteacher.php
<?php
// This is a sample code in case you wish to check the username from a
mysql db table
include('../connect.php');
if($_GET['id'])
{
$id=$_GET['id'];
$sql = "delete from teacher where id='$id'";
mysql_query( $sql);
}
?>

Saturday, 28 September 2013

Apache: redirect if host doesn't start with www or cdn

Apache: redirect if host doesn't start with www or cdn

My goal is to redirect to domain with www. if both these conditions are met:
current host is not www.example.com
current host is not cdn.example.com
I'm using a .htaccess file with this code, but the second condition is not
honoured:
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^cdn\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
Thank you

PHP using iconv to convert large files

PHP using iconv to convert large files

I need to convert text files' character encodings without hogging the
server's memory, while the input file is user configured and its size
isn't limited.
Would it be more efficient to wrap an unix's iconv command using exec()
(which I'd rather avoid, although I already use it in the application for
other file operations), or should I read the file line by line and output
it into another file?
I'm thinking working this way:
$in = fopen("in.txt", "r");
$out = fopen("out.txt", "w+");
while(($line = fgets($in, 4096)) !== false) {
$converted = iconv($charset["in"], $charset["out"], $line);
fwrite($out, $converted);
}
rename("out.txt", "in.txt");
Is there any better approach to convert the file fast and efficiently? I'm
thinking this might be rather CPU intensive, but then I believe iconv
itself is an expensive task so I'm not sure if I can make it actually not
eat the server much at all.
Thanks!

list of english sentences?

list of english sentences?

I'm making a very weak python ai where the user inputs a sentence and the
computer answers, just a proof of concept type idea, using the Stanford
POST tagger, and I'd like a txt file of a bunch of random sentences to
test it. Random lines from books, wikipedia, etc. it doesn't really
matter, but preferably grammatically correct and sentences that people
actually use.
If anyone knows of such a file that would be awesome.

java.lang.NullPointerException in Queue

java.lang.NullPointerException in Queue

I have this error when i call the function enqueue to enqueue a stack into
a queue. This the code where the problem is:
ladder.push(start);
ladder.push(helpWord);
this.wordLadders.enqueue(ladder); <--Here is the problem(The code above is
given)
(start and helpWord are string)
where:
private Queue<Stack<String>> wordLadders;
and costractor is:
this.wordLadders = new Queue<Stack<String>>();
Also the function of enqueue is working using stacks, this the code where
A is a stack:
public void enqueue(AnyType value) {
A.push(value);
}
thank you!

Friday, 27 September 2013

new import with imports pre-def

new import with imports pre-def

how to import foo module like this example.
main.py :
import time
from foo import main
return main()
foo.py :
def main()
print 'hello', time.time()
I tried to explain, there are two or more files, I wanted to upload a
import already defined by another file without defining in what will be
loaded, like my example

Django template does not render CSS and Javascript

Django template does not render CSS and Javascript

I have the following folder structure for my project.
-App1
-App2
-App3
-App4
-static
-css
-bootstrap.css
-js
-bootstrap.js
-jquery.js
-tempaltes
-base.html
Now, in my base.html file i have
But, when i view the file the css and javascript does not seem to be
loaded on the page. In my, i have
settings.py
TEMPLATE_DIRS = "Absolute-path-to-base.html"
STATIC_URL = '/static'
STATICFILES_DIRS = 'Absolute-path-to-the above static folder'
As per all the docs and posts what i understood was, we need to keep all
the staticfiles in one place, viz, static folder in my case...and all the
templates (including base.html) in one place. After doing so, i open the
base.html in my browser to view the page...and it does not display the CSS
and the javascript. Instead when i place the file (base.html) in the
static folder things work fine.
Can someone point me in the right direction!

parse "deep" JSON

parse "deep" JSON

I have a multi-level JSON:
{
"1":{
"name":"PHP",
"slug":"/tag/php",
"type":"Tag"
},
"2":{
"name":"JavaScript",
"slug":"/tag/javascript",
"type":"Tag"
},
"3":{
"name":"X-Browser Shadow",
"slug":"/post/x-browser-shadow",
"type":"Post"
}
}
I would like to know what is the best way to parse this JSON, pure JS of
jQuery, i don't care which of them.
Thanks :)

Confused about setting the value of @transactional

Confused about setting the value of @transactional

Can anybody explain me that when I should put readOnly value as true and
when I should set it as false when using it with @Transactional ?

Implementing CSS in jQuery

Implementing CSS in jQuery

Assuming that one is developing a web application which is sufficiently
non-intensive that overhead is not a concern. Is it reasonable to
implement CSS solely in Javascript/jQuery and completely abandon external
css files?
$('<div/>').attr({'id':'special_box'}).addClass('little_box').appendTo('body')
$('<div/>').addClass('little_box').appendTo('body')
$('<div/>').addClass('little_box').appendTo('body')
...
$('.little_box').css({'color':'red'})
$('#special_box').css({'color':'blue'})
Is there anybody advocating this complete conflation? Is there anything
that completely prevents it or makes it evidently unreasonable?

Capacity of textarea

Capacity of textarea

What is the maximum capacity of a textarea that it can accept some
text.The html page is working fine when the text limits to about 130-140
words.But when the text exceeds that limit it doesn't do anything(just
hangs). This text is passed through javascript for some manipulations and
displayed in another textarea. If there is a limit how to make it accept
large amount of text?

Thursday, 26 September 2013

is this linkedlist code a good practice?

is this linkedlist code a good practice?

Hi everyone I am a newbie in C and trying to learn it. I have a simple
query regarding this linkedlist implementation which I found at many
places:
void addNode(node **listhead, int data, int pos){
if(pos<=0 || pos > length(*listhead)+1){
printf("Invalid position provided, there are currently %d
nodes in the list \n", length(*listhead));
return;
}else{
node *current = *listhead;
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
printf("Memory allocation error\n");
return;
}
newNode->data = data;
newNode->next = NULL;
if (current == NULL){
*listhead = newNode;
return;
}else{
int i = 0;
while(current->next != NULL && i < pos-1){
++i;
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
if(i == pos-1){
newNode->next = current->next;
current->next = newNode;
}
}
}
}
int main(){
node *head = NULL;
node **headref = &head;
addNode(headref, 1, 1);
addNode(headref, 2, 2);
addNode(headref, 3, 3);
printList(head);
return 0;
}
my query is here we are creating a pointer to a pointer which is pointing
to NULL. This code works, however I wanted to know if this is a good
practice. If it is not, how should I create my head pointer and pass its
reference to the addNode function.

Wednesday, 25 September 2013

Python script to copy data from an external drive

Python script to copy data from an external drive

I am in the process of writing a a python program to move user profile
data from an externally attached HD to a new computer. I am currently
having trouble getting the python script to recognize the external drive.
The file path seems accurate, but I am getting an error:
Traceback (most recent call last):
File "C:\Users\Eric\Documents\KoelCopy\KoelCopy.py", line 9, in <module>
distutils.dir_util.copy_tree(source, destination)
File "C:\Python33\lib\distutils\dir_util.py", line 124, in copy_tree
"cannot copy tree '%s': not a directory" % src)
distutils.errors.DistutilsFileError: cannot copy tree 'F:\Users\Nick\My
Documents': not a directory
My code is as follows:
import distutils.core
input_source = input('Enter User Name: ')
source_drive = input('Enter source drive letter: ')
directories = ["\\My Documents", "\\Favorites", "\\Desktop"]
for directory in directories:
source = source_drive + ':\\Users\\' + input_source + directory
destination = 'C:\\Users\\' + input_source + directory
distutils.dir_util.copy_tree(source, destination)
I have also noticed if I get this to work coping from the C drive to C
drive I am getting access denied errors. Would this be caused by windows
security or should I be using a different copy command? I also noticed
when I tested just copying the Desktop is was getting an access denied
error on just the desktop.ini file. How would I exclude such files? I know
I have a lot of questions, I appreciate your time.
Thanks!

Thursday, 19 September 2013

How to wrap the jQuery function

How to wrap the jQuery function

Question
I'd like to know the best way I can wrap the jQuery function while
retaining all functionality. Essentially I want to call $('#someId') but
have it operate as $('#' + id + 'someId') by wrapping the function,
modifying the arguments, and passing it through to the original jQuery
function.
Motivation
I have a section of JS that will reuse the same variable winId which is
concatenated and passed to jQuery. Instead of writing
$('#' + winId + 'someId').html();
$('#' + winId + 'someOtherId').css();
...
$('#' + winId + 'someThirdId').text();
throughout the whole file, I want to wrap the jQuery function so I can
just call
$('#someId').html();
$('#someOtherId').css();
...
$('#someThirdId').text();
and and have winId added in before passing through to $.



My attempt
Here's what I'm thinking as a wrapper:
(function(){
var fn = $;
return $ = function(){
for(var i = 0; i < arguments.length; i++){
if(typeof arguments[i] == 'string'){
arguments[i] = /* code to add in winId, omitted */
}
}
return fn.apply(this, arguments);
}
})();
This works great, except that obviously none of the methods like $.ajax
are available:
Uncaught TypeError: Object function (){
for(var i = 0; i < arguments.length; i++){
if(typeof arguments[i] == 'string'){
arguments[i] = /* code to add in winId, omitted */
}
}
return fn.apply(this, arguments);
} has no method 'ajax'
Note: I know I could copy the object over using jQuery.extend($, jQuery),
but I'm interested in a more elegant solution than that if possible.

How to fill an ArrayList from a file while formatting the information at the same time? [on hold]

How to fill an ArrayList from a file while formatting the information at
the same time? [on hold]

I am working on this project here for school and I really am stuck at this
point. Basically I have to take this trivia.txt file that he supplied and
fill an ArrayList with it, that i have somewhat of a clue how to do. But
then I have to format the output so that my program will recognize the
different categories and be able to output them correctly. Here is what he
has written,
"In this assignment you will write an application that simulates a trivia
game. You will be given a text file that contains a set of questions and
answers in six different categories. Your program will select a random
question from each category to be answered by the player. The score will
be displayed at the end of each run.
Input data format: The input file contains questions and answers in
different categories. For each category, the first line indicates the name
of the category. This line will be followed by a number of pairs of lines.
The first line of the pair is the question, and the second line is its
corresponding answer. A blank line separates the categories. Technical
requirements:
„h Create a class called TriviaQuestion that represents a typical question
object.
„h After reading the data, store the information inside ArrayList(s).
„h Be user friendly in your input/output. Ignore cases. Accept partially
correct answers if possible."
Right now as my code will show I am stuck on how to add the info to the
ArrayList in the format that he has specified. I don't want anyone to do
my work for me. I just need nudged in the proper direction. I dont know if
I need many arraylists for each category and if I do, do I need them to be
in seperate classes? This is only my second semester so I'm still pretty
perplexed by these things. There are other jave trivia games online and on
this forum but I can't find any that work in this fashion. Anyway, here is
the code and the text file afterwards....
import java.io.File;
import java.util.ArrayList;
public class TriviaGame {
/**
* I want to make several array lists and then use a random question for
each category. Then compare the user
* answer to the real answer to see if they won. Keep a count of the
correct answers. Ignore case.
*/
//instance fields
private String player; // The player
private int points; // Player's number of points
private String currentAnswer; // Current typed answer
private File gameFile = new File ("trivia.txt");
//constructors
public TriviaGame(String playerName)
{
playerName = player;
points = 0;
}
public TriviaGame(String player, int points, String currentAnswer,
File gameFile, ArrayList<String> triviaQuestion) {
super();
this.player = player;
this.points = points;
this.currentAnswer = currentAnswer;
this.gameFile = gameFile;
}
//Getters and Setters
/**
* @return the player
*/
public String getPlayer() {
return player;
}
/**
* @param player the player to set
*/
public void setPlayer(String player) {
this.player = player;
}
/**
* @return the points
*/
public int getPoints() {
return points;
}
/**
* @param points the points to set
*/
public void setPoints(int points) {
this.points = points;
}
/**
* @return the currentAnswer
*/
public String getCurrentAnswer() {
return currentAnswer;
}
/**
* @param currentAnswer the currentAnswer to set
*/
public void setCurrentAnswer(String currentAnswer) {
this.currentAnswer = currentAnswer;
}
/**
* @return the gameFile
*/
public File getGameFile() {
return gameFile;
}
/**
* @param gameFile the gameFile to set
*/
public void setGameFile(File gameFile) {
this.gameFile = gameFile;
}
//To String Method
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TriviaGame [player=" + player + ", points=" + points
+ ", currentAnswer=" + currentAnswer + ", gameFile=" +
gameFile
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
+ ", toString()=" + super.toString() + "]";
}
}
followed by the tester.....
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TriviaGamePlayer {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File gameFile = new File ("trivia.txt");
ArrayList<String> triviaQuestion = new ArrayList<String>();
Scanner infile = new Scanner(gameFile);
String line;
while(infile.hasNext()){
line = infile.nextLine();
triviaQuestion = line.split();
}
}
}
finally the text file that accompanied it..... note that after the
category it goes to the next line for the question, then the next line for
the answer, the blank line goes in between the categories. It doesnt seem
to format that way on here when I pasted it.
Arts & Literature
What are bongo drums traditionally held between for playing?
The knees
The Hugo Awards are given for the best literature in which genre?
Science fiction
What four-letter girl's name gave Jane Austen the title of a comic novel?
Emma
Andy Warhol was born in what US city?
Pittsburgh
Who wrote the novel "The Chocolate War"?
Robert Cormier
What surname for John in "The Importance of Being Earnest" did Oscar Wilde
take from the seaside town he vacationed at?
Worthing
Geography
What is the modern day equivalent of Dacia?
Romania
What is the capital of Ontario?
Toronto
Which island boasts of being Napoleon's birthplace?
Corsica
What nationality is a Breton?
French
A person from North Carolina is properly known as a what?
North Carolinian
In which country would you find St. Basil's cathedral?
Russia
Entertainment
How old was Marilyn Monroe when she died?
36
Who created the TV series "Twin Peaks"?
David Lynch and Mark Frost
Who was Charlie's roommate in the 1989 movie "Dead Poets Society"?
Richard
What country singer recorded a popular album at Folsom Prison?
Johnny Cash
In a 2003 movie, Diane Lane plays a writer who buys a villa in what region
of Italy?
Tuscany
What country singer recorded a popular album at Folsom Prison?
Johnny Cash
History
What was John F. Kennedy called by his friends?
Jack
In which country do parts of Hadrian's Wall still remain?
Great Britain
How many dogs survived the sinking of the Titanic?
Two
What were the first words Edison spoke into the phonograph he had just
invented?
Mary had a little lamb
When did construction of the Berlin Wall begin?
1961
What did Benjamin Franklin do on April 17, 1790?
He died
Science & Nature
What is February's birthstone?
Amethyst
What occurs when the Sun and the Moon are in conjunction as viewed from
Earth?
A solar eclipse
What is February's birthstone?
Amethyst
What potentially fatal disease is also known as "rabbit fever"?
Tularemia
How many eyelids does a cat have on each eye?
Three
What kind of poisoning is known as plumbism?
Lead poisoning
Hyperopia is the scientific name for what eye condition?
Farsightedness
Miscellaneous
"Lorgnette" is the proper term for a pair of glasses with what?
A handle
What is a Dubbel?
A Belgian beer style
For what game were two jokers originally included in a standard deck of
playing cards?
Euchre
As what type of beans are chickpeas also known as?
Garbanzo
What do you get when you mix scotch, sweet vermouth and angostura bitters?
A Rob Roy
What cut of steak got its name from the New York City coach stop where it
was first served?
Porterhouse

Validation in javascript

Validation in javascript

this is the scenario, I have this form HTML
<form class="mainForm" name="eform" id="eform"
action="/itg/sc_cust_maint_pkg.cust_dml" method="get">
<div id="tab1" class="tab_content">
<div class="rowElem noborder"><label>Customer ID:</label>
<div class="formRight240">
<input type="text" name="p_cust_id_c" id="req"
class="validate[required,maxSize[30]]"/>
</div></span><div class="fix"></div>
What I have to do is validate the required input, and add asterisk to the
label,the working mode is to fix the problems using what we have, so I
have to find a solution using just this. the million question is, how to
validate if p_cust_id_c is required using that class, and once do that
then add an asterisk to the label.

reinitialize an app after reopen it

reinitialize an app after reopen it

I am wondering for a background running app, is there a way to
reinitialize the app (like terminate the app and start the app from the
beginning) when I reopen the app after a long time of suspension? I think
the OS would kill the app when the device is out of memory, so can I do
this manually?

Hibernate: Extra queries, many to many relation

Hibernate: Extra queries, many to many relation

I have a many to many relation with extra columns:
rol 0..* -------- 1..* permission
This are my models:
Rol:
@Table(name = "rol", uniqueConstraints = { @UniqueConstraint(columnNames =
"nombre") })
public class Rol implements Serializable{
@Id
@Column(name = "_id")
private String id;
@Column(name = "nombre")
@NotEmpty
private String nombre;
@Column(name = "descripcion")
private String descripcion;
@Column(name = "status")
private String status;
@NotEmpty
@OneToMany(fetch= FetchType.LAZY, mappedBy = "rolPermiso_pk.rol",
orphanRemoval = true, cascade=CascadeType.ALL)
private Set<Rol_Permiso> permisos = new HashSet<Rol_Permiso>(0);
Permiso:
@Entity
@Table(name = "permiso", uniqueConstraints = {
@UniqueConstraint(columnNames = "nombre") })
public class Permiso implements Serializable {
@Id
@Column(name = "_id")
private String id;
@Column(name = "nombre")
@NotNull
private String nombre;
@Column(name = "descripcion")
private String descripcion;
@Column(name = "status")
private String status;
@OneToMany(fetch = FetchType.LAZY, mappedBy =
"rolPermiso_pk.permiso", cascade = CascadeType.ALL)
private Set<Rol_Permiso> roles = new HashSet<Rol_Permiso>(0);
Rol_Permiso:
@Entity
@Table(name = "rol_permiso")
@AssociationOverrides({
@AssociationOverride(name = "rolPermiso_pk.rol", joinColumns =
@JoinColumn(name = "idRol")),
@AssociationOverride(name = "rolPermiso_pk.permiso", joinColumns =
@JoinColumn(name = "idPermiso"))
})
public class Rol_Permiso implements Serializable{
@EmbeddedId
private Rol_PermisoId rolPermiso_pk = new Rol_PermisoId();
@Column(name = "status")
private String status;
Rol_PermisoId:
@Embeddable
public class Rol_PermisoId implements Serializable{
@ManyToOne
private Rol rol;
@ManyToOne
private Permiso permiso;
Im trying to show a list of roles with their permissions. So I create this
query:
public List<Rol> findAllWithPermissions() {
return mySessionFactory.getCurrentSession().createQuery("select
distinct r from Rol r left join fetch r.permisos").list();
}
And this works, but extra queries are made:
DEBUG: org.hibernate.SQL - select distinct rol0_._id as column1_2_0_,
permisos1_.idPermiso as idPermis6_3_1_, permisos1_.idRol as idRol5_3_1_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_, permisos1_.fechaCreacion as fechaCre1_3_1_,
permisos1_.fechaModificacion as fechaMod2_3_1_,
permisos1_.fechaSincronizacion as fechaSin3_3_1_, permisos1_.status as
status4_3_1_, permisos1_.idRol as idRol5_2_0__, permisos1_.idPermiso as
idPermis6_3_0__, permisos1_.idRol as idRol5_3_0__ from rol rol0_ left
outer join rol_permiso permisos1_ on rol0_._id=permisos1_.idRol
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 1
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 1
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 3
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 5
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 7
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 8
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 9
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 2
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 2
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 6
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 3
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 4
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 10
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 4
For each rol I get extra queries. I still dont get how hibernate works.
How can I avoid this??

How to disable and enable the scrolling on android ScrollView?

How to disable and enable the scrolling on android ScrollView?

I am a android developer.I also want to use a ScrollView.This ScrollView
need to some time disable scrolling and Some time enable scrolling .But i
can no able to disable the scrolling .How to i implement it .Please help
to me.I also try to use the some code such a s
fullparentscrolling.setHorizontalFadingEdgeEnabled(false);
fullparentscrolling.setVerticalFadingEdgeEnabled(false);
or
fullparentscrolling.setEnabled(false);
But it does not work.

Highcharts - the third line is not displayed properly (jsfiddle included)

Highcharts - the third line is not displayed properly (jsfiddle included)

I have a Highcharts graph that consist of 3 lines - [fiddle here][1]. The
problem is, that the third line (the black one - New York) is not
displayed properly - the points with 0 value are not shown into the graph.
But the zero-points for those 2 previous lines are displayed properly.
Am I missing something or why is the third line incomplete?
Thanks
[1]: http://jsfiddle.net/hHJvq/

Wednesday, 18 September 2013

Interview type questions

Interview type questions

I have an interview coming up, and I was just wondering the easiest way to
explain the following questions:
What is object oriented programming? What is the difference between an
abstract and interface class? Describe an application lifecycle:
I know the "book" definitions, but not like a short interview type answer.
Any help would be appreciated!

Drupal Dropdown Menu

Drupal Dropdown Menu

I am having trouble with my drop down menus. I would like to have multiple
columns under one drop down.
http://jsfiddle.net/Ru3Zv/ here is what I am working with.
#navigation-primary > ul > li > h2, #navigation-primary > ul > li > a {
/* font-size of the first level */
font-size: 1em;
line-height: 40px;
}
#navigation-primary > ul > li > h2 > a, #navigation-primary > ul > li > a {
/* links of the first level */
/* text-transform: uppercase; */
color:white;
font-weight: bold;
text-decoration:none;
/* background: #156aa3; */
background: #1f1f1f;
}
#navigation-primary > ul > li > a.active, #navigation-primary > ul > li >
h2 > a.active {
/* active state of the first level */
background:#1f1f1f;
color:#fff;
}
#navigation-primary > ul > li > a:hover, #navigation-primary > ul > li >
h2 > a:hover, #navigation-primary > ul > li:hover > a, #navigation-primary
> ul > li:hover > h2 > a {
/* hover state of the first level */
background:#1f1f1f;
color:#fff;
}
#navigation-primary .mega a {
/* links color inside panel */
color:white;
}
#navigation-primary .mega a:hover {
/* :hover on links inside panel */
color:white;
/* text-decoration:underline; */
font-size:1.10em
}
#navigation-primary .mega ul.megamenu-2 a {
/* color:#4c4b4b;*/
/* This is the color of the submenu items */
color:#ffffff;
}
#navigation-primary h3, #navigation-primary li.menu-section-title > a {
/* primary links subsection titles */
font-size:1.0em;
/* text-transform:uppercase; */
font-weight: bold;
text-decoration:none
}
#navigation-primary li.menu-leaf-list {
/* child links inside the panel */
/* border-bottom: 1px dashed #e2e2e2;*/
}
.mega {
/* border-top: 10px solid #1f1f1f; */
border-bottom: 4px solid #1f1f1f;
border-left:1px solid #1f1f1f;
/* border-right:1px solid #ccc; */
background:#1f1f1f;
white-space:nowrap !important;
width:auto !important;
}
Under the Services menu I would like to have one column with Managed
Services then the underlined links below that then in a second column have
Consulting Services with the rest of the underlined links below that. This
is similar to http://www.workday.com/.
What would I have to change to get this?

Video Overlay for SMPTE 292m

Video Overlay for SMPTE 292m

I'm trying to find a way to add an overlay to SMPTE 292 video as it is
being transmitted.
I've never really worked with video so I'm trying to avoid making
assumptions that will ruin my day in the future.
The system is essentially like this:
A device(let's say a laptop) generates the video and sends it out on a
wire. Another device is connected at the end(a monitor) that shows the
video. The device I'm looking at making will cut into that wire and
attempt to add an overlay to the video. To be clear, I don't have access
to the source device or the receiving device, so I'll just be playing man
in the middle and manipulating the video after it has been sent out.
Now, in my mind the easiest way to do this would be to read in one frame
of the video, add on the overlay, and send the frame out.
Is this an overly naive approach? The things I've read so far seem to
indicate that video is more complicated than that, and I can understand
that on the lowest levels that it can be more complicated, but are there
software libraries that can be used to accomplish this? I'd prefer
libraries for any high level language like C++, Java, C#, etc but it
doesn't really make a difference.
Also, is there better terminology that I can use to learn more about this?
My only search terms right now are video and overlay which are pretty
ambiguous.

access 2000, sql server not in dropdown when linking

access 2000, sql server not in dropdown when linking

I have a windows 7 machine with access 2000 installed to support legacy
apps. When I try to link a table "SQL Server" is not shown in the
dropdown. I tried to link through code but the driver isn't present. I
forgot how to fix this. I did a fresh install of Office 2000 selecting
only access. Please help. Thanks

Sleeping thread when using Mono Evaluator

Sleeping thread when using Mono Evaluator

I'm doing on the fly compilation using Mono Evaluator, almost everything
is ok but I'm having an issue with Sleep in side evaluated code.
here is piece of sample code:
public class TestClass
{
public static void TestMethod()
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine("Test finish."));
}
}
and here is the code I'm using to execute C# on the fly using Mono Evaluator:
var reportWriter = new StringWriter();
var consoleReport = new ConsoleReportPrinter(reportWriter);
var context = new CompilerContext(new CompilerSettings(), consoleReport);
var eval = new Evaluator(context);
eval.Run(code);
eval.Run(@"
var output = new System.IO.StringWriter();
Console.SetOut(output);
TestClass.TestMethod();");
Then doing:
string result = (string)eval.Evaluate("output.ToString();");
i'm having in "result" the return of executed code. If I dont use Sleep()
inside executed code, everything is ok. But when I do Sleep() then the
line to get "result" is executed without waiting the 5000 miliseconds.
I'm expecting that the code passed to Evaluator.Run sleep as it is
sleeping inside. why it is not happening ?
How can I achive the wait for executed code finish before evaluate result ??
thanks a lot

Extjs: Setting an object's data to be shown in a form

Extjs: Setting an object's data to be shown in a form

I currently have an object with various fields (mostly date fields) as
shown from the console log below. There are more fields than this but all
are similar. Also I am aware that they are all 1970 this is how we set
them on the .net side.
Object {
gasSafeLicenseNo: "3132571",
ngDomesticPipework: "1970-01-01T00:00:00",
lpgDomesticPipework: "1970-01-01T00:00:00"
lpgCentralHeating: "1970-01-01T00:00:00"
lpgDomesticBoats: "1970-01-01T00:00:00"
lpgDomesticCaravans: "1970-01-01T00:00:00"
I have a view with a form in holding all the date fields etc etc..
{
xtype: 'datefield',
labelWidth: 50,
name: 'ngDomesticPipework',
fieldLabel: 'NG'
},
All fields have identical names in the model, view and data object but
will not load into my form ready for editing. I am simply getting the form
element with a component query setting the data to be the object I want to
load and calling load record.
var data = record.get('engineer').gasSafeCard;
gasSafeFormCmp.loadRecord(data);
Thanks folks massive help as always.

button:gravity="right" is not working

button:gravity="right" is not working

i am desinging a xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:background="#000000"
android:orientation="horizontal" >
<Button
android:id="@+id/btncancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center"
android:background="#CCCCCC"
android:text="Cancel" />
<Button
android:id="@+id/btnadd"
android:layout_width="82dp"
android:layout_height="wrap_content"
android:gravity="right"
android:background="#3399FF"
android:text="Add" />
</LinearLayout>
</LinearLayout>
for button "Add" android:gravity=right is not working.i have give a
layout:margin,then only its moving right.can anyone help me out.

Concat the resulting value in mysql

Concat the resulting value in mysql

Can i concat result value and then send the final value as output.
WHILE(LENGTH(totalexpenseamount )>0) DO
BEGIN
SET totalshipmentexpenseamount =
CONCAT(totalshipmentexpenseamount,',',indshipmentexpenseamount);
END;
END WHILE;
but at end totalshipmentexpenseamount does not have any value in it.

Tuesday, 17 September 2013

How to concatenate data from a SQL Server XML query?

How to concatenate data from a SQL Server XML query?

I have a SQL query that returns me the XML below
<row>
<urlSegment>electronics</urlSegment>
<shortenedUrlSegment>0x58</shortenedUrlSegment>
</row>
<row>
<urlSegment>phones</urlSegment>
<shortenedUrlSegment>0x5AC0</shortenedUrlSegment>
</row>
<row>
<urlSegment>curvy-simplicity</urlSegment>
<shortenedUrlSegment>65546</shortenedUrlSegment>
</row>
etc
The output that I want is is a table with two columns (Url and
ShortenedUrl) with the data concatenated in a url fashion as shown below.
Url | ShortenedUrl
electronics/phones/curvy-simplicity | 0x58/0x5AC0/65546
etc
Can anyone help?
Best of regards

MYSQL view not ordering as expected

MYSQL view not ordering as expected

I have a table of cocktail recipes and other stuff. I have another table
that shows the recipes that have been liked. I want to make a view of the
mentioned recipes in the last day, and if that result is <1000, fill in
the remaining 1000 with random recipes NOT on the FEED table.
Example
Feed: Recipe 1 liked today (1 min ago) (cocktail), Recipe 2 liked
yesterday (not cocktail), recipe 3 liked today (1 hour ago)(cocktail),
recipe 4 liked today (3 minutes ago) (not cocktail).
Recipe table: self explanatory
Category table:
recipe 1, cocktail
recipe 2, juice
recipe 3, cocktail
recipe 4 juice
recipe 3333 cocktail
recipe 4444 cocktail
recipe nnnn cocktail
My View needs to show:
Recipe 1, recipe 4,Recipe 3 (liked in most recent order). THEN to fill the
rest of the 1000, get random from the recipe table: Recipe 4444, recipe
3333, recipe nnnn.
Final result: Recipe 1, recipe 4,Recipe 3, Recipe 4444, recipe 3333,
recipe nnnn
The code below attempts to do this, but the order is wrong (the top
doesn't have recipe 1, 4, 3 in that order. They are mixed around...
CREATE
ALGORITHM = UNDEFINED
DEFINER = `XXXX`
SQL XXXX
VIEW `cocktails` AS
(select
`r`.`name` AS `name`,
`r`.`myId` AS `myId`
from
((`recipe` `r`
join `feed` `f` ON ((`r`.`myId` = `f`.`recipe_id`)))
join `category` `c` ON ((`r`.`myId` = `c`.`recipe_id`)))
where
(`c`.`name` like '%cocktails%')
group by `r`.`name`
order by (max(`f`.`timeStamp`) >= (now() - interval 1 day)) desc ,
(`r`.`myId` is not null) desc)
union
(select
`r`.`name` AS `name`,
`r`.`myId` AS `myId`
from
((`recipe` `r`
join `category` `c` ON (`r`.`myId` = `c`.`recipe_id`)))
where
(`c`.`name` like '%cocktails%')
)
limit 0,1000

Prism How to bind Module View to app wide property

Prism How to bind Module View to app wide property

I know this may seem silly but, what is the best way to bind to
Application Wide properties using MVVM and Prism?
Problem: ConnectionStatus Status {...} (Implements INotifyPropertyChanged
etc..)
How do I go about accessing this property in specific modules? I want to
be able to use the Status property across different modules?
What is the best way of getting this data across different modules?
Solutions
Currently I am leaning towards having the following view model in the
infrastructure project (shared across modules)
namespace Project.Infrastructure
{
public class AppViewModel
{
public ConnectionStatus Status {...}
}
}
And in IoC define AppViewModel as Singleton, and pass this in the
constructor of ModuleViewModel
namespace Project.ModuleA
{
AppViewModel _appViewModel;
public class ModuleViewModel
{
public ModuleViewModele(AppViewModel appViewModel)
{
....
}
}
}
Question
Is this the best way to do this or is there a better way of doing this?
E.g.
Using EventAggregator and ConnectionStatusChangeEvent to subscribe and
publish to changes in the connection? But in this case if someone
subscribes to the event after it got pubblished (such as online) they will
not get any starting value, so a IStatusService could be used at the
start?
Using RegionContext and binding that to the Status property in the Shell?
But this seems to defeat the purpose of Shell not knowing what the Modules
use etc..
Or is there something that I have completely missed?
I have read the whole Prism(v4) documentation and just not 100% sure of
which is the best way of implementing this.

How do I apply a function in R to certain columns of a data frame grouped by another column?

How do I apply a function in R to certain columns of a data frame grouped
by another column?

I've been looking at the help page for tapply and by and I'm not sure if
they are the right tool for this. For example, if I have a dataframe where
the columns are Name,Value1,Value2 and I want to apply a function, say
function f(x,y) { do_something } to Value1 and Value2 grouped by Name and
get as a result a dataframe with the columns Name,f(Value1,Value2) how
should I go about that?
I can get tapply to work in a simple case like this:
tapply(df$Name, df$value1, mean)
but what if my function takes as input df$value2 as well? and is not as
simple as mean? In other words, pseudo-notation for what I'm trying to do
would be:
tapply(df$Name, c(df$value1,df$value2), function f(x,y) { x+y+bla...})

Unable to understand a c code

Unable to understand a c code

I am studying c programming book by dennis M.Ritchie.I unable to
understand this code. please can any explain me this code?
#include <stdio.h>
main()
{
int c,i,nwhite,nother;
int ndigit[10];
nwhite=nother=0;
for(i=0;i<10;++i)
ndigit[i]=0;
while((c=getchar())!=EOF)
if(c>='0' && c<='9')
++ndigit[c-'0'];
else if(c==' ' || c=='\n' || c=='\t')
++nwhite;
else
++nother;
printf("digits =");
for(i=0;i<10;++i)
printf("%d",ndigit[i]);
printf(",white space=%d, other = %d\n",nwhite,nother);
}

How to fix "Not in GZIP format"?

How to fix "Not in GZIP format"?

I have the following code:
final remote = new HTTPBuilder("http://example.com")
final text = remote.request(GET) { req ->
uri.path = "/path"
requestContentType = TEXT
uri.query = ['name': 'value']
response.success = { resp, text ->
text
}
response.failure = { resp ->
println "Rest failure (${req.getURI()}): ${resp.status}:
${resp.statusLine.reasonPhrase}"
}
}
and it's throwing:
java.io.IOException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:143)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:58)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:67)
at
groovyx.net.http.GZIPEncoding$GZIPDecompressingEntity.getContent(GZIPEncoding.java:73)
at org.apache.http.util.EntityUtils.consume(EntityUtils.java:83)
at
org.apache.http.conn.BasicManagedEntity.ensureConsumed(BasicManagedEntity.java:99)
at
org.apache.http.conn.BasicManagedEntity.consumeContent(BasicManagedEntity.java:112)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:515)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:441)
at groovyx.net.http.HTTPBuilder.request(HTTPBuilder.java:373)
at groovyx.net.http.HTTPBuilder$request.call(Unknown Source)
at
org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
How can this be fixed?

Sunday, 15 September 2013

C++ string/char and accents

C++ string/char and accents

I'm writing a text writer in C++, which I'll have a string of a phrase and
display the appropriate bitmap font for each char value.
For now, it's working for the regular characters, but I'm getting weird
values for accents and other characters such as À, Á, Â, Ã, etc
I'm doing this:
int charToPrint = 'a';
//use this value to figure which bitmap font to display
The bitmap font does have these characters, but on this line I'm not
getting the values I'm supposed to get, such as: 195 for Ã, 199 for Ç,
etc...
I tried changing my project's character set from Multi Byte to Unicode,
but I don't think that does anything for the char->int conversion...
How can I get this conversion with chars?

Confusion about ActiveRecord associations and foreign keys (Ruby/Rails)

Confusion about ActiveRecord associations and foreign keys (Ruby/Rails)

In the below example, do I have to create "employee_id" in the office
model, or is it created automatically by db:migrate?
class Employee < ActiveRecord::Base
has_one :office
end
class Office < ActiveRecord::Base
belongs_to :employee # foreign key - employee_id
end
Sorry, feels like I'm missing something fundamental. I'm trying to get a
basic one to many relationship working, where I can use a dropdown select
of objects from the one side. Are there any good basic tuts explaining how
this works?
I had to create "_id"s in all the models where I wanted this to work, but
it doesn't seem right from examples I've looked at.

Generic class type with dictionary in C#

Generic class type with dictionary in C#

I have a dictionary and I would like the key to be able to be different
classes. Right now I'm using:
public Dictionary<dynamic,int> CbList = new Dictionary<dynamic,int>();
This works but I lose the compile-time checking. Is there a better way?
EDIT:
Basically I was wondering if there was a way to have different classes in
a dictionary without losing compile-time checking....
The key classes are related in that they have the same contructors...

how do I see a downvote

how do I see a downvote

I've received a donwvote before but have no idea how to know who downvoted
me.
I've also seen post where people have accused someone of downvoting them
(and the accused acknowledged it). How did the accuser know?

check whether all elements of a list are in equal in R

check whether all elements of a list are in equal in R

I have a list of several vectors. I would like to check whether all
vectors in the list are equal. There's identical which only works for
pairwise comparison. So I wrote the following function which looks ugly to
me. Still I did not find a better solution. Here's my RE:
test_true <- list(a=c(1,2,3),b=c(1,2,3),d=c(1,2,3))
test_false <- list(a=c(1,2,3),b=c(1,2,3),d=c(1,32,13))
compareList <- function(li){
stopifnot(length(li) > 1)
l <- length(li)
res <- lapply(li[-1],function(X,x) identical(X,x),x=li[[1]])
res <- all(unlist(res))
res
}
compareList(test_true)
compareList(test_false)
Any suggestions? Are there any native checks for identical for more than
just pairwise comparison?

How to get the start parameter when app starts from custom url scheme for Android in Phonegap

How to get the start parameter when app starts from custom url scheme for
Android in Phonegap

I'm able to start the application, using the custom URL Scheme
<a href="myapp://customurl/?user_token=12345">Start My App</a>
The application lunches as usual, but i did need the key user_token=12345.
I had less experience with this framework, so don't get any work around.
Need help.
Secondly, Can i pass multiple keys using the Custom Schema ?

How to save asp files as asp format not sln

How to save asp files as asp format not sln

Problem with Visual Studio in the design of the asp pages save as .sln
files I am a Beginner in asp programming language and I have a problem in
Save projects : it always save as sln files and I want to save the pages
asp format Note I'm working on Facebook applications using asp.net c# Is
this a relationship with my problem?
I am a Beginner in English as well as you can see ^_^

Saturday, 14 September 2013

Understanding overall database design

Understanding overall database design

I have an interest in understanding database design, but I am unsure of
where to start or what I should be paying attention to.
For instance, if I am creating an application, let's use a blog for
simplicity, I know that I will need data. I know that the data I will need
is posts, comments, users, categories, images, etc. I know this "data"
will come in the form of models or tables.
What I have a hard time understanding is when I need a separate table vs.
adding another column in an existing table.
For instance, my Posts table may look like:
ID
Title
Author
Category
Image
Body
However, I want to manage the Categories, so I think I should have another
table just for Categories. What about Images? Should that be a separate
table?
I don't know when to break it out, or keep it together.
Can someone point more to some documentation that would help me learn this
concept? Some guidelines or rules per say.
Thanks!

get z standardized score within each group

get z standardized score within each group

Here is the data.
set.seed(23) data<-data.frame(ID=rep(1:12), group=rep(1:3,times=4),
value=(rnorm(12,mean=0.5, sd=0.3)))
ID group value
1 1 1 0.4133934
2 2 2 0.6444651
3 3 3 0.1350871
4 4 1 0.5924411
5 5 2 0.3439465
6 6 3 0.3673059
7 7 1 0.3202062
8 8 2 0.8883733
9 9 3 0.7506174
10 10 1 0.3301955
11 11 2 0.7365258
12 12 3 0.1502212
I want to get z-standardized scores within each group. so I try
library(weights)
data_split<-split(data, data$group) #split the dataframe
stan<-lapply(data_split, function(x) stdz(x$value)) #compute z-scores
within group
However, It looks wrong because I want to add a new variable following
'value' How can I do that? Kindly provide some suggestions(sample code).
Any help is greatly appreciated .

why does if(number

why does if(number

var way = 'up';
var m25 = {
'n': 10
};
for (var somelongnumber = 0; i < 10000; i++) {
if (way === 'up') {
m25.n = m25.n + 5;
if (m25.n >= 90) {
way = 'down';
}
} else {
m25.n = m25.n - 5;
if (m25.n <= 10) {
way = 'down';
}
}
console.log(way + m25.n);
}
this console.logs:
up15
up20
up25
up30
up35
up40
up45
up50
up55
up60
up65
up70
up75
up80
up85
down90
down85
down80
down75
down70
down65
down60
down55
down50
down45
down40
down35
down30
down25
down20
down15
down10
down5
down0
down-5
down-10
down-15
down-20
down-25
down-30
down-35
down-40
down-45
down-50
down-55
why does it go past zero? I am very confused!

Difference between these CSS reset methods

Difference between these CSS reset methods

I would like to know if there is any difference between these two methods.
body,ul,li,p,h1,h2,h3,h4,h5{padding:0; margin:0; list-style-type:none;}
and
body,ul,p,h1,h2,h3,h4,h5{padding:0; margin:0;}
li{list-style-type:none;}
without the need to use the global selector * The real issue here is that,
I have mentioned list-style-type:none; in the first example, even though
this attribute applies to the li tag on. But, I find myself something in
need to group all elements and just give them values , even if some values
don't apply to some elements.
So, is there a negative side to that aside from clarity issues?

Unix user created variables

Unix user created variables

I am going though some growing pains with Unix. My question:
I want to be able to print all my user defined variables in my shell. Let
say I do the following in the shell:
$x=9
$y="Help"
$z=-18
$R="My 4th variable"
How would I go about printing:
x y z R
Thanks

Can we profile per core with dtrace?

Can we profile per core with dtrace?

Is dtrace usable in multithreaded applications, and can I profile
individual cores? If so, would someone point me to an example?

How to hide the play/pause button and progress bar in youtube video embedded in html?

How to hide the play/pause button and progress bar in youtube video
embedded in html?

I have created on e HTML page with a you tube video link like -<object
width="456" height="230"> <param name="movie"
value="http://www.youtube.com/v/kitfFWmLFJ8" /> <param name="wmode"
value="transparent" /> <embed src="http://www.youtube.com/v/kitfFWmLFJ8"
type="application/x-shockwave-flash" wmode="transparent" width="456"
height="230" /> </object> How to hide the play/pause button and progress
bar in youtube video embedded in HTML?

Friday, 13 September 2013

How can text be so sharp & clear in Xfce4 compared to other desktops and window managers?

How can text be so sharp & clear in Xfce4 compared to other desktops and
window managers?

In the past 1 week i installed different window managers
and desktop environments.
out of these, gnome did not have text as clear and as
sharp as Xfce
but neither did anything else.
text is simply too clear in Xfce4
what is the secret behind this desktop environment ?
is it using special fonts ? or is it using a special setting
to achieve this much precision ?
i want to switch to OpenBox but i am stuck in Xfce due to
clear text , regardless if it is within firefox or outside of
firefox. text is always sharp and clear that it is extremely
easy to read.

Beginner's C++ program for a class

Beginner's C++ program for a class

the assignment is the basic "cin a full name" and then "retrieve First
Middle Last" bit, where you create a program that asks the user to type in
their full first name into a single string and the programs picks apart
the name and outputs it organized seperately. this is what i wrote:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int index;
index = name.find(' ');
cin >> name;
cout << "First name: " << name.substr(0, index) << endl;
name = name.substr(index+1, name.length()-1);
index = name.find(' ');
cout << "Middle Name: " << name.substr(1, index) << endl;
name = name.substr(index+1, name.length()-1);
cout << "Last name: " << name;
return 0;
}
the code just wont seperate them right, and will not redefine 'name'
correctly. It always just bounces back to the beginning of the string. any
help for a newbie? here's an example output: Teenage Wonder Land First
name: Teenage Middle Name: eenag Last name: Teena Process returned 0 (0x0)
execution time : 7.942 s Press any key to continue.

size of char is not consistent between an array and string

size of char is not consistent between an array and string

if you have
char test1[] = { 'a', 'b', 'c' };
char test2[] = "abc";
I understand sizeof(test1) is 3 since char is only 1 byte hence 1x3 = 3
BUT why isnt the sizeof(test2) 3? y is it 4?

DataTable.AsEnumerable().ToList(); min/max return invalid if data is int

DataTable.AsEnumerable().ToList(); min/max return invalid if data is int

var list = ProcessedInformationTable.AsEnumerable().ToList();
var minValue = list.Min(v => v["Rank"]);
var maxValue = list.Max(v => v["Rank"]);
In the code above if I had the values of
ColumnA|Rank
Heart|9
Lung|10
minValue will return as 10 and maxvalue will return as 9. My guess is
because it's treated as a string even though every value is an int. Is
there a way around this?

How do I take an entire columns worth of data and put it into anther column using a WHERE clause?

How do I take an entire columns worth of data and put it into anther
column using a WHERE clause?

I have two extremely similar tables in the same database. I want to take
the entire 'visual' column from the table p992_cq31n06-cm16-x and put it
into the 'visual' column of the table p992_cq31n06-cu67-x where the
columns 'print' and 'id3' match up.
Here is the query I was going to run:
UPDATE `p992_cq31n06-cu67-x`
SET visual = (
SELECT visual
FROM `p992_cq31n06-cm16-x`
WHERE
`p992_cq31n06-cu67-x`.print = `p992_cq31n06-cm16-x`.print
AND
`p992_cq31n06-cu67-x`.id3 = `p992_cq31n06-cm16-x`.id3);
Is this going to work the way I want it to?

Is PhD from UK a better option?

Is PhD from UK a better option?

I would like to ask if PhD from United Kingdom a good option for
International Students?
I would like to know from someone who has already experienced studying
from UK, like How much savings can be made from PhD funding or Research
assistant-ships ? And How does things work there?
I am Masters student in Computer Sciences here in Germany, though I'm
non-European, but still I find German universities to be good enough where
International Students don't need to pay any amount and can get like
1800-2200 Euros a month during PhD positions ! I don't know anything about
UK, can someone guide me through ?
With Best Wishes

Create paginated Drupal form. (Drupal 6)

Create paginated Drupal form. (Drupal 6)

I am trying to create a form which provide a checkbox element on each row.
Problem is that I have 2000 rows which takes some time to load and also it
is not easy to navigate through whole list.
Is there a way to create some kind of pagination in Drupal form ?

Thursday, 12 September 2013

How to use deferred.when with eventlistner and eventhandler?

How to use deferred.when with eventlistner and eventhandler?

I am trying to use one Deferred.when statement which can return an object
after the completion of an eventhandler. My code looks like something
below. Can someone guide me how to make it work? I am using dojo 1.7.
define(["dojo/_base/declare","dojo/_base/lang", "dojo/_base/xhr",
"dojo/_base/json","dojo/_base/Deferred","dijit/registry","dojo/_base/connect",
"dojo/query","dojo/on","dojo/dom-attr","dojo/dom","dojo/has","dojo/json","dojo/dom-style"],
function(declare,lang,xhr,json,Deferred,registry,connect,$,on,attr,dom,has,json,domStyle)
{
declare("model.Item", [],
{
deferred:null,
item:null,
Load: function(){
this.deferred = new Deferred();
var overlay = registry.byId("readFromStore");
overlay.show();
Deferred.when(connect.connect(registry.byId("storeReadOK"),"onClick",this,this.loadFromStorage),
(return (this.deferred)));
// I want modification for the above line.
}
loadFromStorage:function()
{
// Do something here
this.deferred.callback(this.item);
}
return model.Item;
}
);

How can I pagination when I use solr facet stats?

How can I pagination when I use solr facet stats?

I have select all records from solr by solr facet stats, but I can't
pagination them, How can I pagination by the pageSize and pageNum?

How to calculate the frame of a modal view on iPad?

How to calculate the frame of a modal view on iPad?

When a user taps a UITextField, the keyboard will come up. I scroll up the
UITextField to sit just above the keyboard. This is working fine on
iPhone:

- (void) someWhere
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(onKeyboardShow:)
name:UIKeyboardWillShowNotification
object:nil];
}
- (void) onKeyboardShow:(NSNotification *)notification
{
CGRect keyboardRect = [[[notification userInfo]
objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue
];
if (keyboardRect.size.height >= IPAD_KEYBOARD_PORTRAIT_HEIGHT) {
self.containerView.y = self.containerView.y -
keyboardRect.size.width;
} else {
self.containerView.y = self.containerView.y -
keyboardRect.size.height;
}
}
However, it is broken on iPad. On iPad, modal view controllers can be
presented as a sheet that takes up only a portion of the screen. You can
see that there is a gap between the last UITextField and the keyboard on
iPad.

UINavigationController* nav = [[UINavigationController alloc]
initWithRootViewController:someRootViewController];
nav.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:nav animated:YES completion:nil];
I need to detect the offset of the modal view from the bottom of the
screen and add that to the Y coordinate of the UITextField. This will make
the UITextField flush with the top of the keyboard. I attempted to get the
frame of the modal view by doing this:
- (void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// describe is a category function on UIView that prints out the frame
[self.viewController.view.superview.superview.superview.superview
describe];
}
I did indeed get the frame:
x: 114.000000,
y: 192.000000,
w: 540.000000,
h: 620.000000
But as you can see from my code, it is extremely fragile. Since the view
hierarchy of modal view controllers on iPad is not documented, I had to
reverse engineer the hierarchy by slower traversing up the tree to see
which would be the right one. Is there are less fragile way to get the
frame that I actually care about?