Monday, 30 September 2013

Icons on the desktop do not state the name of the file/directory?

Icons on the desktop do not state the name of the file/directory?

How do I fix the desktop icon which don't show the file/directory names
they are associated with and has an icon size which is to small to be on
the desktop?
I scanned through unity-tweak-tool but found no option option relevant to
this.
Ubuntu 13.04 it is.
Screenshot:

Does case carry into an appositive=?iso-8859-1?Q?=3F_=96_german.stackexchange.com?=

Does case carry into an appositive? – german.stackexchange.com

I'll ask this question in English, because I'm not sure I could articulate
it well enough in German. So this question too is about my essay. The
relevant part of the original sentence was «...die …

Placing numeric value into an Array range

Placing numeric value into an Array range

I have an array that has numeric values stored. like this:
$ranges = array(1=> '33', 2=> '66', 3=> '99');
i have a variable called $result that gives me a dynamic value between 0-100.
for example:
If $result is equal to or greater than 33 AND less than 66, then the
returned key should be 1
If $result is equal to or greater than 66 AND less than 99, then the
returned key should be 2
If $result is equal to or greater than 99, then the returned key should be 3
Any ideas on how this can be achieved?

How to use profilling for Mac OS X Applications?

How to use profilling for Mac OS X Applications?

I am looking forward to do some profiling to find cpu usage of my
application. Also in which part of the code its taking more cpu time. I am
fresh to the profiling. I need help regarding this,

Sunday, 29 September 2013

Jquery Form plugin : dynamic target/multiple forms

Jquery Form plugin : dynamic target/multiple forms

I am using the form plugin from http://malsup.com/jquery/form/
I am trying to set the target div to be updated dynamically. At the moment
this is what the code looks like but instead I want to pas a different
value for target through a hidden form field, so the #target2 can be
dynamically changed to #target20, #target40 etc. Thanks.
<script type="text/javascript">
$(document).ready(function() {
$('.htmlForm').ajaxForm({
target: '#target2',
success: function() {
$('#target2').fadeIn('slow');
}
});
});
</script>
and the form html
<form class="htmlForm" action="ajax-data.php" method="post">
<input type="hidden" name="target" value="ztest" />
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
and the div to be updated
<div id="ztest"></div>
another form
<form class="htmlForm" action="ajax-data.php" method="post">
<input type="hidden" name="target" value="ztest2" />
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
and another div to be updated
<div id="ztest2"></div>

How to differentiate between pipe and interactive stdin

How to differentiate between pipe and interactive stdin

So far, I have that if the filename argument (fname) is left empty, the
program reads stdin automatically.
if (!strcmp(fname, ""))
fin = stdin;
But I need to know whether that stdin was piped in, or interactive,
because I could possibly get something like:
rsm: reading from (stdin)
^Z
rsm:(stdin):1: not an attribute: `&#8730;&#9496;2ç&#8745;'
if interactive input was used. Is there some sort of library function I
could use?

How to correctly extend a class in C++ and writing its header file?

How to correctly extend a class in C++ and writing its header file?

I'm pretty new to C++ and I'm trying to create my first little project. I
encounter some problems during compilation. It says C2504 Person: base
class undefined. I know that, in a header file, I need to declare or
include tha class that I'm extending in the correspondent *.cpp file. I'll
write the code to understand better.
main.cpp
#include <Windows.h>
#include "client.h"
using namespace person;
using namespace std;
int __stdcall WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int cmdShow)
{
try
{
Person *p = new Client;
// DO STUFF
}
catch(Exception &e)
{
//Error, so let's exit 1
return 1;
}
//No errors, so we return with 0
return 0;
}
client.cpp
#include <time.h>
#include <ctype.h>
#include <string>
#include "client.h"
using namespace person;
using namespace std;
class Client : public Person {
public:
Client()
{
//DO STUFF
}
void onMessage(const char * const message)
throw(Exception &)
{
//DO STUFF
}
private:
void gen_random(char *s, const int len) {
//DO STUFF
}
};
client.h
#ifndef CLIENT_H
#define CLIENT_H
#include "person.h"
class Client : public Person {
public:
Client();
void onMessage(const char * const message) throw(Exception &);
private:
void gen_random(char *s, const int len);
};

Insert from back : Linked List

Insert from back : Linked List

I read the code from this site:
http://www.codeproject.com/Articles/24684/How-to-create-Linked-list-using-C-C,
but it gave me segmentation fault and I don't quite get it.
*I modified it to my struct
struct Node
{
int type;
char cmd[256];
struct Node *next;
};
void insert(int val, char arr[])
{
struct Node *temp1 = (struct Node*)malloc(sizeof(struct Node));
struct Node *temp2 = (struct Node*)malloc(sizeof(struct Node));
temp1 = head;
while(temp1->next != NULL)
temp1 = temp1->next;
temp2->type = val;
strcpy(temp2->cmd, arr);
temp2->next = NULL;
temp1->next = temp2;
}
What is wrong with this code?

Saturday, 28 September 2013

How apex get executed in Salesforce

How apex get executed in Salesforce

i write a Batch apex.i write an execute method .which is using a static
variable of another class.because it is shhared.any one can use it and
change it.
public void execute(Database.BatchableContext BC, List<sObject> scope){
x=GMirror.x;
...........
...........
.........
y =GMirror.x;
}
i want to know each batch of 5 in my case will run in transaction or means
at this time only this method is running nothing else or in other words i
want to know if using another class's method execution in between time
first statement execute x=GMirror.x;
and second statement y =GMirror.x;
its possible by another parallel execution of another class's method that
these value of GMirror.x get changed ?? these execution this necessary
that no one changed value of GMirror.x or value of GMirror.x can be
changed by another parallel execution.Please clarify .

how to prevent going back to previous page

how to prevent going back to previous page

For a windows phone 8 app I'm developing, I had to load some data at the
starting of the app. For that matter I designed a page called
SplashScreen.xaml that loads the data and after all the loading is done I
navigate to the MainPage.xaml using:
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
Now when the user is in the main page and taps the back button on the
phone instead of going out of the app(which is the default gesture) goes
back to the SplashScreen.xaml, making them unable to go out of the
app(except for taping the start button which take's the app to background)
and of course giving them a bad impression. The question is How to prevent
going back to the previous page Thank you all.

Getting similar pattern sub strings (python)

Getting similar pattern sub strings (python)

I have a large string and I want to get all the patterns
str = "name":"temp1","class":"temp2""name":"temp3","class":"temp4"
Now I want the name and class values how can I take those from the above
string.

Friday, 27 September 2013

Android GPS not working in service

Android GPS not working in service

Im trying to get my GPS working in a service but its not working. The GPS
bit works on its own but not in the service.
I have tried debugging with System.out.println() and fond where it stops
working but cant work out why it all looks good.
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("test 1");
LocationManager lm =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
System.out.println("test 2");
LocationListener lli = new myLocationListener();
System.out.println("test 3");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
lli);
System.out.println("test 4");
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
class myLocationListener implements LocationListener{
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null){
pet.setMeter();
}
}
It gets to Test 4 then dies. I am lost at why so if anyone can help that
would be awesome thanks.

combobox insert text and value gives error

combobox insert text and value gives error

I want to insert each row in SQL into combobox, where EmployeeID will be
combobox Value, and EmployeeFirstName EmployeeLastName will be text of
combobox item. However this line



comboBox1.Items.Insert(dr.GetString(1) + dr.GetString(2), dr.GetInt32(0));



gives me this error:
Error 1 The best overloaded method match for
'System.Windows.Forms.ComboBox.ObjectCollection.Insert(int, object)' has
some invalid arguments
C:\Users\bilgisayar\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs
45 21 WindowsFormsApplication1



void comboboxrefresh()
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT
EmployeeID,EmployeeFirstName,EmployeeLastName FROM Employees",
cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
comboBox1.Items.Insert(dr.GetString(1) + dr.GetString(2),
dr.GetInt32(0));
}
}
cnn.Close();
}

How can i find the ETA of an event in javascript using simple variables

How can i find the ETA of an event in javascript using simple variables

I am developing a javascript game and would like to display an ETA telling
the user how long they have left until they lose the game. This figure is
dependent on 3 variables,
var max = 1000000 /* 1 million */
var current = 50 /* 50 currently */
var persec = 10 /* 10 new ones created every second */
How using javascript can I calculate an estimate of the number of seconds
till current >= max using the rate of change provided using persec?
Things I have tried
var eta = (max - current / persec) / 60;
eta = Math.round(eta);
but this did not work as I am expecting it to.

Tagging only with existing tags and view with select

Tagging only with existing tags and view with select

I have a model CuisineTag that stores tags names in :title And Restaurant
that has many cuisine_tags
class CuisineTag < ActiveRecord::Base
attr_accessible :title
has_and_belongs_to_many :restaurants
end
class Restaurant < ActiveRecord::Base
has_and_belongs_to_many :cuisine_tags
# ...
end
How to make possible to add cuisine_tags to restaurant only via selecting
it through select box? Also i need add/remove cuisine_tags when editing
restaurant.
Please, provide some sample code.

Create new record with change in one value

Create new record with change in one value

Suppose my record (with large number of fields) is defined like this:
data Sample_Record = Sample_Record { record_field1 :: Int,
record_field2 :: Int,
record_field3 :: Float
}
a = Sample_Record { record_field1 = 4,
record_field2 = 5,
record_field3 = 5.4
}
Can I make a new record of the type Sample_Record from a which has one of
it's field modified ?

autocomplete jQuery display data

autocomplete jQuery display data

I'm learning jQuery and i would like to use autocomplete. But i don't know
why my data don't display in my html. Can you explain me what's wrong in
this source code please.
<?php
// receive data
if(isset($_GET['q'])) {
$q = addslashes(htmlspecialchars($_GET['q'])); // protection
require_once('../required.php');
//our request
$rslt= $pdoSearch->findCity($q);
$tab=array();
foreach ($rslt as $data){
array_push($tab,
array(
"label" => $data['fistname']." ".$data['lastname']."
".$data['login']." ".$data['mdp']." ".$data['city'],
"value" => $data['id']
)
);
}
echo json_encode($tab);
} ?>
My autocomplete file :
$(function(){
$('#search').autocomplete({
source: 'fichier.php',
select: function (event, ui) {
$("#search").val(ui.item.label);
$("#id").val(ui.item.value);
}
});
$('#button').click(function() {
$("#id").val();
});
});
And my HTML file :
<fieldset id="field" >
<legend>Fonctionnalit&eacute;s</legend><br />
<form class="icon" method="get">
<label for="search">Recherche: </label>
<input id="id" name="id" hidden="hidden" />
<input type="text" id="search" style="width: 600px;"/>
<input type="submit" id="button"/>
</form>
</fieldset>
Thanks in advance for your help. Best regards,

Thursday, 26 September 2013

How do you programmatically do initial setup to a UITableViewCell created as a storyboard prototype?

How do you programmatically do initial setup to a UITableViewCell created
as a storyboard prototype?

I have a bunch of different cells created as prototypes in a storyboard,
but I have changes that apply to all cells of that type, so I only want to
do them once. But I don't think I can apply these changes in storyboard,
so I have to do them programmatically.
e.g. modifications to the CALayer of an image view in the cell, setting a
custom font on a label etc etc,.
Seems wasteful to have to redo this every time the cell recycles, but
there doesn't seem to be a good way to check if the cell is new or
recycled anymore, because the cell is never nil.
I suppose you could add a manual flag that indicates whether the cell is
new or not, seems like a hack though. Any other options?

Wednesday, 25 September 2013

How do I write a code in Java which allows the user to input words and the app says which is the longest? [on hold]

How do I write a code in Java which allows the user to input words and the
app says which is the longest? [on hold]

I need to write a code that asks the user how many words the user wants
and then the user types what those words are. The program will then
display all the words and then separately display the longest word.

Thursday, 19 September 2013

Netcat - port range only working for scanning, not listening

Netcat - port range only working for scanning, not listening

For instance:
nc -l -n -v -p 2999-3000
Can only connect to 2999.
nc -l -n -v -p 3000-3001
Can only connect to 3000.
Can't you listen on a port range with netcat? are there any obvious
workarounds I am missing?

what is the best android layout

what is the best android layout

I used both RelativeLayout and Linearlayout to achieve this.(in the image)
Using relative layout, I positioned the buttons with fixed width, and with
marginLeft and marginRight. The problem is, if the device has bigger
screen, the left, right margins don't expand much, also the button width
is fixed.
<!-- Row1 -->
<Button1
alignParentTop = "true"
marginLeft = "5dip"
marginRight="5dip"
width="80dip"/>
<button2
alignParentTop ="true"
center="@id/Button1"
marginLeft = "5dip"
marginRight="5dip"
width="80dip" />
<button2
alignParentRight="true"
marginLeft = "5dip"
marginRight="5dip"
width="80dip"/>
<!-- Row2 -->
<Button3
below="button1"
marginLeft = "5dip"
marginRight="5dip"
width="80dip"/>
<Button4
below="button2"
marginLeft = "5dip"
marginRight="5dip"
width="80dip"/>
</RelativeLayout>
Using RelativeLayout parent, created 2 horizontal linearlayout with
buttons. Now buttons have 0dip width with weight 1. However, I cannot
create the 2nd row.

<RelativeLayout>
<linearLayout orientation="horizontal">
<!-- Row1 -->
<Button1
width="0dip"
weight="1"/>
<button2
width="0dip"
weight="1"/>
<button2
width="0dip"
weight="1"/>
<!--Row2-->
</RelativeLayout>
Couldn't using this approach

Deleting an option value from a select box

Deleting an option value from a select box

I need your help.
I am still relatively new to javascript, and would like to accomplish the
following:
Using the 'delete' key on my keyboard, I would like to able to delete the
highlighted value from the drop down list depicted in this picture here:
and;
Using the delete key in the input box, I would like it to search for the
value given in the input box and delete the option from out of the drop
down box (as depicted in this picture here):
Here is the HTML markup:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getvalue(x) {
document.getElementById('input').value = x
}
</script>
</head>
<body>
<input type="text" id="input">
<br>
<select id="list" onchange="getvalue(this.value)">
<option value=""></option>
<option value="ABC">ABC</option>
<option value="DEF">DEF</option>
<option value="GHI">GHI</option>
<option value="JKL">JKL</option>
<option value="MNO">MNO</option>
</select>
</body>
</html>

Animations for Android? Wich Ways

Animations for Android? Wich Ways

im grafik designer and work mutch too in layouting/Screendesign for
android apps.
I like Animation add on our Applikation. Wich the best ways without coding
to add Animations.
For example i mean datas like:
gif
apng
apng
webP
canvas/mp4
Or can html 5 and java in same applikation mixed?
what is for you coder best to way (gif are bad quality i will pref apng)
webP is fine but in Development and no programms/plugin for us designer
available.
Here is so support on people and i found already many help on other stuff
now i try me problem to fix XD
Thanks for help!

Importing CSV to SQL Server with text column > 8000 characters

Importing CSV to SQL Server with text column > 8000 characters

I'm trying to import a csv file with two columns (sku, description) into
SQL Server 2008 using the SQL Server management studio 2012 import/export
wizard. Because the description column definitely has rows greater than
8000 characters, I go to the advanced tab when choosing the csv data
source and click on the description column and click "Suggest Types". It
then puts in 16718 for the OutPutColumnWidth property. Apparently there is
a description in there somewhere that is THAT long.
The sql it generates is:
CREATE TABLE [dbo].[mag-prod-descriptions1] (
[sku] varchar(7),
[descrip] varchar(16718)
)
However, when I execute the import, I get the error "Could not connect
source component. Error 0xc0204016: SSIS.Pipeline: The "Source -
mag-prod-descriptions1_csv.Outputs[Flat File Source Output].Columns[Column
1]" has a length that is not valid. The length must be between 0 and
8000."
If I change the OutputColumnWidth property to 8000 then I get an error
saying the column was truncated. I can't win.
How do I get the thing to allow me to import cells that are greater than
8000 characters?

Block user registration by country ip range

Block user registration by country ip range

I have the following table in MYSQL
CREATE TABLE IF NOT EXISTS `countryip` (
`ip_from` bigint(10) unsigned NOT NULL DEFAULT '0',
`ip_to` bigint(10) unsigned NOT NULL DEFAULT '0',
`country_iso2` varchar(2) COLLATE utf8_bin NOT NULL DEFAULT '',
`country_iso3` varchar(3) COLLATE utf8_bin NOT NULL DEFAULT '',
`country_name` varchar(32) COLLATE utf8_bin NOT NULL,
KEY `ip_from` (`ip_from`,`ip_to`))
ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
And here i have added the entire ip ranges of all countries in the world.
I want to make in php a script that will compare the user ip with the ip
range from this database and after that echo a message. From what i
undestood i need to start by declaring
<?php
mysql_select_db("database_name") or die(mysql_error());
$ip = $_SERVER['REMOTE_ADDR'];
$query = mysql_query("SELECT `IP` FROM `ban_ip` WHERE `IP` = '$ip'");
// this works only if i have the single static ip in the dbs, but now
i have the ip range
if (mysql_num_rows($query) > 0)
{
echo ' <!DOCTYPE html> <html> <head> <script type="text/javascript">
alert("You are not allowed to access this website");
window.location.replace("index.php"); </script> </head> <body> </body>
</html>';
}
What can i do instead of this query
$query = mysql_query("SELECT `column` FROM `table` WHERE `column` = '$ip'");
in order to make possible the comparison between the User IP and the ip
range.
And the IP FROM column, TO IP column looks like this 16777216, 16777471,
In order to find out the ip there was a formula similar with ip = 256 +
CLASS B * 256 + CLASS C * 256 * 256 + CLASS D * 256 * 256 * 256

javascript regex to allow at least one special character and one numeric

javascript regex to allow at least one special character and one numeric

Im beginer about regex...I need to create a regular expression to check if
a string has got at least one special character and one numeric. Im using
([0-9]+[!@#$%\^&*(){}[\]<>?/|\-.:;_-]+|[!@#$%\^&*(){}[\]<>?/|\-.:;_-]+[0-9]+),
but is not working. Help please.

How I use post method in Ruby on Rails

How I use post method in Ruby on Rails

when I submit one page to another, the sites shows the information!
Someone told me to use post to avoid it. however, when I use post method
it doesn't work.
<form action="\look\at", method="post">
Select your new car's color.
<br>
<input type="radio" name="radios1" value="red">red
<input type="radio" name="radios1" value="green">green
<input type="radio" name="radios1" value="blue">blue
<br>
<br>
<input type="submit"/>
</form>
When I submit I can not see "\look\at" page. but I delete method="post" It
works well. How I use post method?

Wednesday, 18 September 2013

How to close the program after the user enters a character and presses the enter key?

How to close the program after the user enters a character and presses the
enter key?

I just started learning C++ programming. My program runs perfectly but i
also need it to close when the user enter s a character and presses the
enter key. I have no idea how that is supposed to be done. any help will
be really appreciated. My code so far is(runs fine) :
#include <iostream>
using namespace std;
int main()
{
int money_spent, money_tendered;
cout << "Enter the total amount spent: \n";
cin >> money_spent;
cout << "Enter the amount tendered: \n";
cin >> money_tendered;
int balance = money_tendered - money_spent;
int ten_bills = balance / 1000;
balance = balance % 1000;
int five_bills = balance / 500;
balance = balance % 500;
int dollar_coins = balance / 100;
balance = balance % 100;
int quater_coins = balance / 25;
balance = balance % 25;
int dimes = balance / 10;
balance = balance % 10;
int nickels = balance / 5;
balance = balance % 5;
int pennies = balance;
cout << " \n \n"
<< "Your change is: \n"
<< ten_bills << " tenn dollar bill(s). \n"
<< five_bills << " five dollar bill(s). \n"
<< dollar_coins << " one dollar coin(s). \n"
<< quater_coins << " quater(s). \n"
<< dimes << " dime(s). \n"
<< nickels << " nickel(s). \n"
<< pennies << " pennie(s). \n";
return 0;
}

How do I add foundation with grunt to a ember.js app kit project

How do I add foundation with grunt to a ember.js app kit project

I'm trying to setup my first Ember.js app with Ember AppKit, grunt, and
compass. The appkit ships with support of compass out of the box via
grunt-contrib-compass but I can't figure out for the life of me how to
install Zurb-Foundation, or at least not "properly."
As far as I can tell, grunt-contrib-compass doesn't provide a wrapper
around compass's install method. I could duplicate the compass.js task
settings for a compass config file but it seems like there should be a way
to do this without duplicating the data.
Alternatively, I guess I could just copy everything over manually but that
cuts off my path for easy upgrades.
Any help would much much appreciated.

How to use more arguments when calling functions?

How to use more arguments when calling functions?

Sorry, I know this is really basic, but I don't know how to search it the
proper way, so here we go. I'm trying to call MessageBoxA, and I want the
message to replace '%s' with something else. Example:
MessageBoxA(0, TEXT("You have %s items"), "title", 0);
Can anyone help me? And once again, I know this is really basic, sorry.

Why this program is not running?

Why this program is not running?

Hello is printed zero times. Why?
#include<stdio.h>
int main()
{
int x;
for(x=-1; x<=10; x++)
{
if(x < 5)
continue;
else
break;
printf("hello");
}
return 0;
}

How do you use AWS elastic transcoder in RoR

How do you use AWS elastic transcoder in RoR

I am working on RoR website and uploading the videos on S3 using
carrierwave gem and now i want to implement Elastic transcode for videos,
but i have know idea how to proceed it.
Please could any one guide me?
Thanks

Tuesday, 17 September 2013

how to use the log sequence number

how to use the log sequence number

How to use the lsn in sqlserver ? when i executed a query enabling cdc the
output was
start_lsn tran_begin_time tran_end_time tran_id tran_begin_lsn
0x0000004000000108002D 2013-09-18 09:51:53.263 2013-09-18 09:51:53.263
0x00 0x00000000000000000000 0x00000045000000500001 2013-09-18 09:51:53.140
2013-09-18 09:51:54.533 0x000000000767 0x00000040000001000001
0x00000045000000600037 2013-09-18 09:56:26.130 2013-09-18 09:56:26.130
0x00 0x00000000000000000000 0x00000049000000B0001A 2013-09-18 09:56:26.113
2013-09-18 09:56:26.410 0x0000000007B5 0x00000045000000600001
0x00000049000000D8000F 2013-09-18 09:57:26.723 2013-09-18 09:57:26.723
0x0000000007EE 0x00000049000000D8000D 0x00000049000000E00003 2013-09-18
09:57:42.833 2013-09-18 09:57:42.833 0x0000000007EF 0x00000049000000E00001
0x00000049000000E80003 2013-09-18 09:59:44.167 2013-09-18 09:59:44.167
0x0000000007F0 0x00000049000000E80001

HTML tag stored in ModelMap not interpreted as HTML by the browser

HTML tag stored in ModelMap not interpreted as HTML by the browser

I have a spring controller with the following code :
@RequestMapping(value="/getMessage.htm", method=RequestMethod.POST)
protected String uploadFile(ModelMap model){
//... other codes
model.addAttribute("theMessage", "Hello world <b>how are you</b>
today?");
return "the-view";
}
In the client side (JavaScript), I show this message using the following
code :
document.getElementById('theMessageSpan').innerHTML = '<c:out
value="${theMessage}"/>';
But when it is displayed, it shows a string literal
Hello world <b>how are you</b> today?
I need to show the message as :
Hello world how are you today?
I tried using apache commons' StringEscapeUtils.unescapeHtml before
putting the text in the ModelMap, but the result is just the same.
Any thoughts?

Performance of pixel transformation using clojure and quil

Performance of pixel transformation using clojure and quil

Let's assume I'd like to wright an ocr algorithm. Therefore I want to
create a binary image. Using clojure and quil I came up with:
(defn setup []
(load-pixels)
(let [pxls (pixels)
]
(letfn [(pxl-over-threshold? [idx] (if (> (red (aget pxls idx)) 128)
true false))
]
(time (dotimes [idx 25500] (aset pxls idx (color (rem idx 255)))))
(time (dotimes [idx 25500] (if (pxl-over-threshold? idx)
(aset pxls idx (color 255))
(aset pxls idx (color 0)))))))
(update-pixels))
(defn draw [])
(defsketch example
:title "image demo"
:setup setup
:draw draw
:size [255 100]
:renderer :p2d)
;"Elapsed time: 1570.58932 msecs"
;"Elapsed time: 2781.334345 msecs"
The code generates a grayscale and afterwards iterates over all pixels to
set them black or white. It performs the requested behavior, but takes
about 4.3 sec to get there (1.3 dual core). I don't have a reference to
put the 4.3 sec in context. But thinking of processing a larger image,
this must become incredibly slow.
Am I doing something terribly wrong or is there a way to fasten up things?
Is the combination of clojure and quil even capable of doing pixel
transformations faster or should I choose a different
language/environment?
Please also let me know if I'm doing something weird in the code. I'm
still new to clojure.
Thanks in advance.

How do I implement a join with a between in Hive?

How do I implement a join with a between in Hive?

I have a Hive table with the numeric version of an IP address. I have
another table with start, end, location where start and end define a range
of numeric IPs associated with a location.
Example
Numeric: 29
start | end | location
----------------------
1 | 11 | 666
12 | 30 | 777
31 | 40 | 888
Output: 29 - 777
I need to use the IP from table 1 to lookup the location from table 2. I'm
new to Hive and have discovered that I can't use BETWEEN or < > in join
statements. I've been trying to figure out some way of making this happen
using Hive SQL and can't figure it out. Is there a way? I'm somewhat
familiar with UDFs as well if one of those is needed. I'm open to the idea
that this isn't possible in Hive and I need to do with Pig or a Java
Map/Reduce job, I just don't know enough about things at this point to
say.
Any help is appreciated. Thanks.

Environment NewLine Not Working In Text File

Environment NewLine Not Working In Text File

I am instantiating a StringBuilder and trying to write to a text file. My
code writes to the text file fine but the StringBuilder is not creating
carriage returns for me.
Ive tried..
Environment.NewLine
\n
.AppendLine()
and nothing seems to work with the StringBuilder object
Here is some code I am using to create the string that gets inserted into
the flat file
'ErrorLog is a new StringBuilder object
_mErrInfo.ErrorLog.Append("Start Validiting Detail....." +
Environment.NewLine)

How to use Jackson to deserialise a 2D Array

How to use Jackson to deserialise a 2D Array

I am passing a 2D array JSON to a spring controller, but getting jackson
error.
org.codehaus.jackson.map.JsonMappingException:
Can not deserialize instance of java.lang.String[] out of
VALUE_NUMBER_INT token
My javascript 2D array looks like this.
[ ["John", "Doe", "worker", "fulltime"],
["Adam", "Smith", "nonworker", "temp"],
["Jane", "Doe", "worker", "fulltime"] ]
The bean class it gets mapped to 2D array like this.
public class MyBean implements java.io.Serializable {
private static final long serialVersionUID = -3948256457L;
String[][] workInfo = null;
public String[][] getWorkInfo() {
return workInfo;
}
public void setWorkInfo(String[][] workInfo) {
this.workInfo = workInfo;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
}
In the spring controller, I am using something like this.
public ModelAndView addData(@RequestBody MyBean tempForm) throws
Exception{
ModelAndView model = new ModelAndView(new
org.springframework.web.servlet.view.json.MappingJacksonJsonView());
try{
myService.addData(tempForm);
model.addObject("mesage", "success");
}
catch(Exception e)
{
model.addObject("mesage", "error");
log.error("error:"+e);
}
}
Can anyone suggest how can i resolve this issue.

Sunday, 15 September 2013

Basic Matlab tables contaning text

Basic Matlab tables contaning text

I need to type some matrix containing both letters and numbers. Something
like list=["a" 1;" b" 2; "c" 3; "d" 4; "e" 5; "f" 6; "g" 7]
¿Can anybody give me some tip? Thank you very much

Sublime Text 3 getting Less-Build not working

Sublime Text 3 getting Less-Build not working

I'm trying to get Less-Build to work in Sublime Text 3. As documented I
went to the package, unzipped it, changed the
LESS-normal.sublime-build-choice to LESS.sublime.build, and ran the .bat
file choosing 1, but I don't know either how to force a build or it isn't
working. The .bat said the symlink was good, anyone else have a better
idea of how to install or build using Less-Build?
Thanks

Bind an event to a dynamic loading elements on page

Bind an event to a dynamic loading elements on page

I got lot of divs on my page with the class of prodct-item-info. I've
wrote a code in jQuery that trigger some code whenever the user click on
an element that has this class.
Problem is, the page is loading more of this class dynamically, and when
that happens, it's like when I press on this class of the new loaded
class, nothing happens, but if i'm clicking on the classes that were
created before the dynamic load, it still works.
for instance, x is what I loaded at the first time when the page loaded,
and y is what I added dynamically:
the page has this:
x x x x x x x x x x x x x x x x x x
when I click on those its all fine.
now I loaded
y y y y y y y y
When I click on those, it doesnt do anything.
Any idea how to fix it?
Thanks in advance!

Database design suggestions for inventory management project

Database design suggestions for inventory management project

I had assigned a project named inventory management.the project is
developed by using jsf .While designing the database i'm stucked with a
problem... the problem is a)whether to maintain a individual data base for
each company or b) maintaining a single data base and managing records of
each company by using the company identification number.
The problem with second option is as each company contains thousands of
records ,searching through those records will consume more time.
Can anyone please give me suggestion in designing data base..
Thanks in advance.......

jquery fancybox add submit button image in title

jquery fancybox add submit button image in title

Is is possible to use the JQuery Fancybox 'Image Gallery' type, and place
a form inside the 'title' , or I've read in an HTML area? The latter, I'm
struggling to figure out.
I need a gallery of images, which I have working, and also a submit button
below the gallery in Fancybox - it's like an 'add to cart'.
I've tried dropping my form submit button inside the #fancy-two div, but
it's not showing. I've also tried playing with the title="" but not
showing either.
My code is:
Here is my submit button code:
Your help is appreciated!
Dan

Support for Older Versions

Support for Older Versions

I am designing an app with minimum SDK as 9 and target SDK as 18. I want
to display a clock on the screen. So I added a DigitalClock to the layout.
I got a warning saying that Digital Clock was deprecated in API 17. So I
added Text Clock. But TextClock is supported by only API 17 and above.
What should I do to make the digital clock appear if SDK found on device
is < 17 and make the Text Clock appear if SDK found is >= 17?
I am adding the DitialClock/TextClock through XML and not in the code behnd.

Saturday, 14 September 2013

Sample Code and Environment Setup for JMS

Sample Code and Environment Setup for JMS

How do I install JMS into my desktop? I can't seem to find an installer
for it. Basically I want to practice coding on JMS like a hello world, but
without it installed, how to do?
Most code in the internet already start with code, without telling how
even to prepare the local system for JMS.... pls help!

regular expression using lookahead negative assertion

regular expression using lookahead negative assertion

Using php I would like to detect something in a string depending on
whether the part immediately after the matched part does not contain
certain characters. I think I may need to use a lookahead negative
assertion but it is not working as I would expect so not sure. So for
example:
$string = 'test somerandomURL><b>apple</b> peach orange';
I want an expression that will detect everything up to the first > so long
as <b>apple</b> does not immediately follow the first >
I tried
if(preg_match("/test(.*)>(?!<b>apple</b>)(.*))/i",$string)){
echo 'true since <b>apple</b> does not follow > in string';
}else{
echo 'false since <b>apple</b> follows > in string';
}
When the string contains <b>apple</b> after the > it returns false as I
expect and need but when I change the string to have <b>peach</b> after
the > instead of <b>apple</b> it still returns false and I need it to
return true. Without the bold tags it seems to work as I would expect. Any
ideas what I am doing wrong?

removing the ' ' and the spaces in the return output python3

removing the ' ' and the spaces in the return output python3

i am trying out a function where you have to use def function(a,b,c,d) a
is a string so i did
a = str(a)
b is an integer so i did
b= int(b)
c is also a string;
c = str(c)
and d is a boolean (all i know about boolean is True or False); so
d = True
i wanted to change the order of the elements into
[c,a,b,d]
and i assigned this to result = [c,a,b,d] when i used the return function
return str(result), (because i want to return a string)
i ended up with
"[ 'c', 'a', b, d]"
i have tried everything to get rid of the ' ' and also the spacing because
it should really look like
'[c,a,b,d]'
what can i do to remove it?

Creating Pinterest like layout in ASP.NET webform

Creating Pinterest like layout in ASP.NET webform

I am creating a Pinterest like layout in ASP.NET webform and I followed
following two tutorials
Creating Pinetrest like Layout in ASP.NET
How to use Masonry
However, I made changes in the first tutorial based on second and I am
getting below output

Clearly, this isn't what I was looking. The gap between two rows and
columns is high.
Below is my code:
<
style type="text/css">
body
{
background-color:#EEEEEE;
}
#imgLoad
{
position:fixed;
bottom:0;
left:40%;
display:none;
}
.item {
width: 220px;
margin: 10px;
float: left;
background-color:honeydew;
}
</style>
<div id="container" class="transitions-enabled infinite-scroll clearfix">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="item">
<img src="<%# Eval("Url") %>" />
<p><%# Eval("Description") %></p>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
How do I fix it?

knit to HTML button not working in Rstudio on Ubuntu 12.04

knit to HTML button not working in Rstudio on Ubuntu 12.04

I have recently installed the latest versions of R (3.0.1) and RStudio
(0.97.551) on Ubuntu 12.04, and I find that whereas the knit2html function
work just fine on an Rmd document, the button Knit HTML does not (neither
does RStudio's keyboard shortcut). This seems to be the opposite of the
problem that some people have reported (not on Ubuntu, though) hwere the
button works and the function doesn't.
Has anyone encountered and/or fixed this issue?
Thanks, Homer White

MATLAB : display 3 or more spectrograms side by side

MATLAB : display 3 or more spectrograms side by side

For the sake of visualisation, i need to randomly display from 3 to 6
spectrograms in Matlab. I have an array of 800 vectorized wav files, i am
randomly picking 3 of them, and want them to pop up in a figure showing
the spectrograms of each side-by-side:
load('training_set.mat');
m = size(X, 1);
% Randomly select 3 wavs
rand_indices = randperm(m);
sel = X(rand_indices(1:3), :);
I am very new to Matlab and i did try to write a for loop which takes each
sample out of "sel" and generates a spectogram for it, but i didn't
achieve any result. ( i use the specgram function).

File path image directory

File path image directory

My site display articles , some of them includes many images (Hundreds).
The content field in MYSQLcontain HTML tags like /
My directories Hierarchy Myproject (root) -Site files o Config o Include o Js
o ... -CMS files (admin) -Images (tree)
How can save image file path (dynamically - not absolute), If I change the
place of any directory (CMS, Site or Images), and still view the images in
the site and the CMS system

Friday, 13 September 2013

Ask a chain/multiple questions together (Voice/Speech Recognition)

Ask a chain/multiple questions together (Voice/Speech Recognition)

I need help asking my program a series of questions. For example:
I may say "hi computer" and I want my computer to respond saying "Hi, Sir.
How are you?" Then the computer would say "Fine and yourself?" and my
computer would say something else.
As of now I'm using Case statements. An example of my code below:
//Kindness
case "thank you":
case "thank you jarvis":
case "thanks":
case "thanks jarvis":
if (ranNum <= 3) { QEvent = ""; JARVIS.Speak("You're Welcome
Sir"); }
else if (ranNum <= 6) { QEvent = ""; JARVIS.Speak("Anytime"); }
else if (ranNum <= 10) { QEvent = ""; JARVIS.Speak("No problem
boss"); }
break;

Send function being called twice

Send function being called twice

I've tried searching the above and found similar results, but non that
could fix my issue. I have a WP theme which includes a function to send
private messages between users, the receivers get email notification that
a private message was received. The problem is that the message is being
sent twice, so is the email. I can see the message in the inbox and outbox
twice as well.
here's the code, not sure what's causing the issue:
<?php }
elseif($third_page == 'send') { ?>
<?php
$pid = $_GET['pid'];
$uid = $_GET['uid'];
$user = get_userdata($uid);
if(!empty($pid))
{
$post = get_post($pid);
$subject = "RE: ".$post->post_title;
}
if(isset($_POST['send']))
{
$subject = strip_tags(trim($_POST['subject']));
$message = strip_tags(trim($_POST['message']));
$to = $_POST['to'];
if(!empty($to))
{
$uid = auctionTheme_get_userid_from_username($to);
}
if($uid != false && $current_user->ID != $uid):
global $current_user;
get_currentuserinfo();
$myuid = $current_user->ID;
global $wpdb; $tm = current_time('timestamp',0);
$s = "insert into ".$wpdb->prefix."auction_pm (subject,
content, datemade, pid, initiator, user)
values('$subject','$message','$tm','$pid','$myuid','$uid')";
//mysql_query($s) or die(mysql_error());
// $wpdb->show_errors = true;
$wpdb->query($s);
//echo $wpdb->last_error;
//-----------------------
$user = get_userdata($uid);
AuctionTheme_send_email_on_priv_mess_received($myuid, $uid)
//-----------------------
?>
<div class="my_box3">
<div class="padd10">
<?php _e('Your message has been sent.','AuctionTheme'); ?>
</div>
</div>
<?php
elseif($current_user->ID == $uid):
?>
<div class="error">
<?php _e('Cant send messsages to yourself','AuctionTheme'); ?>
</div>
<?php
else:
?>
<div class="my_box3">
<div class="padd10">
<?php _e('The message was not sent. The recipient does not
exist.','AuctionTheme'); ?>
</div>
</div>
<?php
endif;
}
else
{
?>
<div class="my_box3">
<div class="padd10">
<div class="box_title"><?php echo sprintf(__("Send Private
Message to: %s","AuctionTheme"), $user->user_login); ?></div>
<div class="box_content">
<form method="post" enctype="application/x-www-form-urlencoded">
<table>
<?php if(empty($uid)): ?>
<tr>
<td width="140"><?php _e("Send To", "AuctionTheme"); ?>:</td>
<td><input size="20" name="to" type="text" value="" /></td>
</tr>
<?php endif; ?>
<tr>
<td width="140"><?php _e("Subject", "AuctionTheme"); ?>:</td>
<td><input size="50" name="subject" type="text" value="<?php
echo $subject; ?>" /></td>
</tr>
<tr>
<td valign="top"><?php _e("Message", "AuctionTheme"); ?>:</td>
<td><textarea name="message" rows="6" cols="50"></textarea></td>
</tr>
<tr>
<td width="140">&nbsp;</td>
<td></td>
</tr>
<tr>
<td width="140">&nbsp;</td>
<td><input name="send" type="submit" value="<?php _e("Send
Message",'AuctionTheme'); ?>" /></td>
</tr>
</table>
</form>
</div>
</div>
</div>
<?php } } ?>
</div>
I've tried playing around with the last bit of the code by removing/adding
the "//", some resulted in emails sent but not messages, some resulted in
messages sent 4 times, but none fixed the issue either.
Thanks guys

GTK user interface - best practice for text

GTK user interface - best practice for text

I look for tutorial GTK (text for object)
For example best practice to set text (lowercase, uppercase, etc) check box:
"Always ask me where to save files" or "Always Ask Me Where to Save Files"
lalels
etc
Thanks

Present Value Calculator php

Present Value Calculator php

The PHP script captures the values and calculates the future value.
working backwards from the last month to the first, how could I compute
the investment for the previous month and display the months number and
the value all the way back to the first investment (Unknown). I've already
figured out that I'll have to uses a formula like this "months value =
(months value)/(1 + rate)" but after that I hit a road block. basically
I'm trying how to figure how much do you invest today to have a balance
value of $XXX after xx years at a x% interest rate?
<?php
// get the data from the form
$investment = $_POST['investment'];
$interest_rate = $_POST['interest_rate'];
$years = $_POST['years'];
// calculate the future value
$future_value = $investment;
for ($i = 1; $i <= $years; $i++) {
$future_value = ($future_value + ($future_value * $interest_rate
*.01));
}
// apply currency and percent formatting
$investment_f = '$'.number_format($investment, 2);
$yearly_rate_f = $interest_rate.'%';
$future_value_f = '$'.number_format($future_value, 2);
?>

Javascript Unit Testing AutoComplete Functions

Javascript Unit Testing AutoComplete Functions

I am at a loss for how to start javascript unit testing this function. I
have a function that's called to set up a jQuery autocomplete field but
with in its 'source' and 'select' I make other function calls and there is
a success callback too.
It seems like it would be good practice to write some tests that essential
ensure those are being called correctly. However, is there a point to
testing these? In my other tests you just stub out the call to this
function so it's still showing up as not covered obviously.
What if any tests would make sense to write for this function?
self.setNameAutocomplete = function () {
$("#name").autocomplete({
minLength: 0,
source: self.NameArrayFromSuggestions,
select: function (event, ui) {
$("#name").val('');
NameSuggestion.getData(ui.item[2], self.AddName, function () {
$('#Message').text("Error Occured");
});
return false;
}
}).bind('focus', function () { $(this).autocomplete("search");
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a
class=\"name-type-ahead\">" + item[0] + "<br>" + item[1] +
"</a>").appendTo(ul);
};
};

hibernate mapping verify if an object is mapped

hibernate mapping verify if an object is mapped

How can I check if an object is mapped or not?
I get an error cause I have an object not mapped in Hibernate
org.hibernate.hql.ast.QuerySyntaxException: Product is not mapped [select
prod from com.neila.Product product
, I wanna test before executing the code if that object is already mapped.

Thursday, 12 September 2013

How can I add a custom method to auth_user model class? I need to return a calculated field along with results

How can I add a custom method to auth_user model class? I need to return a
calculated field along with results

I want to be able to write something like:
#extend user model with this method
def get_manager():
#call some api to get the manager
return user_manager
and to be able to display this in the template, like:
{{ user.get_manager }}

understanding how a view is set - android

understanding how a view is set - android

I am trying to understand the android bootstrap source code. So in some
activity : I found something like
pager.setAdapter(new BootstrapPagerAdapter(getResources(),
getSupportFragmentManager()));
indicator.setViewPager(pager);
pager.setCurrentItem(1);
where pager is referenced as @InjectView(R.id.some_id) ViewPager pager; and
public class BootstrapPagerAdapter extends FragmentPagerAdapter {
private final Resources resources;
// ...
public BootstrapPagerAdapter(Resources resources, FragmentManager
fragmentManager) {
super(fragmentManager);
this.resources = resources;
}
//...
and some methods latter
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
switch (position) {
case 0:
NewsListFragment newsFragment = new NewsListFragment();
newsFragment.setArguments(bundle);
return newsFragment;
//...
In fact, I noticed that the NewsListFragment fragment is the one (the view
of which is the first displayed) used at first when I launch the ADB, but
I can't understand how this method getItem is called (the same way I don't
understand where setCurrentItem() method is called). Could someone help ?

IE7 float bug in IE10 Compatability mode

IE7 float bug in IE10 Compatability mode

I'm trying to get a site working in IE10 for those people who've pressed
the compatibility mode button - usually by mistake!
Compatibility mode in IE10 renders the document for IE7
I have a container div with 1 to 4 columns of dives floated left inside
it, they are all cleared by a clearing div after the last column div.
It all works fine except in IE10 Compatability mode. I think it is an IE7
float bug but I could be wrong
You can see the issue here

Is there a clever way to use transient object in a singleton?

Is there a clever way to use transient object in a singleton?

I have a builder class which is stateful.
interface IFilterBuilder
{
AddFilter1();
AddFilter2();
//etc
IEnumerable<Filter> FilterList { get; }
}
class FilterBuilder : IFilterBuilder { //implementation }
For the moment I'm creating its instances with new keyword because it's
short lived and it's used inside a method of a singleton object.
I know I can inject a factory type like Func<IFilterBuilder> to singleton
and resolve it with the container but I really don't want to have a
filterBuilderFactory.
Is there a way to do some kind of magic with interception like this:
class SingletonClass
{
[TransientDependency]
public IFilterBuilder FilterBuilder
get
{
//magic.gif
}
set
{
//some stuff for testability
}
}
So when I need to use it in a method, I get a new instance.
IFilter filterBuilder = FilterBuilder;
filterBuilder.AddFilter1();
return filterBuilder.FilterList;
It will have to release the object when its out of scope and I should have
a way to replace it with a mock in my tests.

Installing new version of data.table (specifically 1.8.11 from Rforge)

Installing new version of data.table (specifically 1.8.11 from Rforge)

According to
https://r-forge.r-project.org/scm/viewvc.php/pkg/NEWS?view=markup&root=datatable
datatable now has melt.
I saw that and went to download data.table 1.8.11 and when I went to
install it I got an error that it is unavailable for R 2.15.3 (which is
the version I was on). Based on that I updated to R 3.0.1 and tried to
install it again...
> install.packages("C:/[path]/data.table_1.8.11.zip", repos = NULL)
Warning in install.packages :
package 'C:/[path]/data.table_1.8.11.zip' is not available (for R version
3.0.1)
package 'data.table' successfully unpacked and MD5 sums checked
if I do packageVersion("data.table") I get 1.8.11 but if I do
?melt.data.table I get there's no documentation for it.
If I uninstall data.table I can then reinstall data.table 1.8.10 from CRAN
without getting any errors.
Does anyone know why I'm getting these errors with the newer version of
data.table? As you can tell from the C drive path I'm on Windows.

What of lack this program? (sorting with qsort, struct array)

What of lack this program? (sorting with qsort, struct array)

I'm create Fraction Struct Array Sorting program.
a little number (slightly under 1000) my program have good answer
but big number (slightly over 100000) my program have wrong answer
what's the problem?
this is my source and input data
#include <cstdlib>
#include <iostream>
using namespace std;
struct Fraction {
long long denominator;
long long numerator;
};
int compare(const void *a, const void *b) {
const struct Fraction *x = (Fraction *)a;
const struct Fraction *y = (Fraction *)b;
long long val = x->numerator * y->denominator - x->denominator *
y->numerator;
if (val == 0) {
return x->numerator - y->numerator > 0 ? 1 : -1;
} else {
return val;
}
}
Fraction setOfData[100000];
int numOfData, numOfK;
int main() {
cin >> numOfData >> numOfK;
for (int i = 0; i < numOfData; ++i) {
long long denominator;
long long numerator;
cin >> numerator >> denominator;
setOfData[i].numerator = numerator;
setOfData[i].denominator = denominator;
}
qsort(setOfData, numOfData, sizeof(Fraction), compare);
cout<< setOfData[numOfK - 1].numerator << ' ' << setOfData[numOfK -
1].denominator;
return 0;
}
and this is my input data
input data
7 4
56783 9765493
56786 9765492
56788 9765491
8888888 9765464
56687 9765395
56789 9765497
56785 9765496
sorting standard is non-decreasing
over input data my program print
8888888 9765464
56687 9765395
56783 9765493
56785 9765496
56786 9765492
56788 9765491
56789 9765497
what's the lack of this program? is it long long? or int? help me plz...

Size of Text Area in java

Size of Text Area in java

I am writing a code for basic GUI. There i need a Text Area. But i can not
make the Text Area in my desirable size. i use setPreferredSize method to
set the dimension of the Text Area. But it did not work. I also tried
setSize method but did not work also. Here is my written code.
private void textArea() {
setTitle("TextArea");
setSize(700, 500);
setLayout(new BorderLayout());
JTextArea textArea = new JTextArea();
textArea.setPreferredSize(new Dimension(100,100));
System.out.println(textArea.getSize());
textArea.setBackground(Color.GREEN);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(false);
add(textArea,BorderLayout.CENTER);
}
Sorry for my bad English. Thanks in advanced.

Getting NullpointeException

Getting NullpointeException

Guys can you check it why i am getting a null pointer exception in this line,
cl = Class.forName(myClass);
Here's the code:
private void addBookmark(String[] values_array) {
LayoutInflater vi = (LayoutInflater)
getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.single_bookmark, null);
TextView text = (TextView) v.findViewById(R.id.bookmark_text);
Button button = (Button) v.findViewById(R.id.bookmark_button);
text.setText(values_array[1]);
final String myClass = values_array[0];
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Class<?> cl = null;
try {
cl = Class.forName(myClass); // <--- this is where i am
getting a null pointer exception
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Intent myIntent = new Intent(mContext, cl);
startActivity(myIntent);
}
});
how should I fix that? Or is there something I need to replace?

Wednesday, 11 September 2013

Sublime Text 3 plugin development: access own files

Sublime Text 3 plugin development: access own files

The porting guide states that:
Packages in Sublime Text 3 are able to be run from .sublime-package (i.e.,
renamed .zip files) files directly, in contrast to Sublime Text 2, which
unzipped them prior to running.
While in most changes this should lead to no differences, it is important
to keep this in mind if you are accessing files in your package.
So how do I access files in my own package? My plugin comes with some
static files that it must use.

how to move scene position in cocos2d on iPhone 5

how to move scene position in cocos2d on iPhone 5

I have made a game on cocos2d-iphone for iPhone 4, to make it compatible
on iPhone 5 wide screen I want to move cocos2d's scene a little bit on
right on the iPhone 5 screen. I am trying to move scene by 50 points but
after few seconds it gets back to its original position.
scene.position = CGPointMake(50, 0);
I have also set Default-568h@2x.png image in the cocos2d project

Exception ORA-08103: object no longer exists on using setfetchsize of Hirabenate

Exception ORA-08103: object no longer exists on using setfetchsize of
Hirabenate

I'm using Hibernate. I need to fetch around 1000000 records and it will
cause timeout exception. So I'm using setfetchsize for 6000 records, so
that it will distribute the operation in multiple transactions each of
6000 records.
It will take around 21 hours to fetch all.
But meanwhile retrieving records if somebody deletes one of the record
which was to be fetched then I get ORA-08103: object no longer exists.
Now I want to skip that object which is deleted while retrieving. How can
I do this?

How to process and parse a string from user input

How to process and parse a string from user input

For example, an user entered a string "a + a = b". The program needs to
find two numbers, one for each unique letter, to make the string true. And
let's assume we already have had an algorithm to enumerate all possible
combinations of number zero to nine. However, for example, when the
program wants to test if 0 and 1 can be solutions for a and b, how do I
translate the string "a + a = b" to some java code that can be used to
test if 0 + 0 = 1 (when a = 0, b = 1)? To deal with the string, I know I
need to extract the plus and equal sign and translate the letter to
number(maybe?). But if the input is "abc + bc = def". I need a way to know
how many letters there are before or after the plus sign and equal sign. I
hope this is not too confusing. Thanks!

Activate windows authentification in asp.net mvc

Activate windows authentification in asp.net mvc

I'd like to specify the users' profiles how can access to my asp.net mvc
application so i put
<authentication mode="Windows" />
<authorization>
<allow users="Afif"/>
<deny users="?"/>
</authorization>
but the windows authentification didn't work. after googling , i find that
i have to activate the windows authentification in IIS Manager

But i don't find the windows authentification as in the screenshot. How
can i fix it?

How is load balancing achieved while sending data to the reducers in Hadoop

How is load balancing achieved while sending data to the reducers in Hadoop

As we know, that during the copy phase of hadoop, each of the reduce
worker processes read data from all mapper nodes and perform a merge of
the already sorted data (was sorted during in-memory sorting on the mapper
side) and work on their share of keys and their values.
Now, we also know that all the data corresponding to a particular will go
to only one reducer.
My question is : How is the data split to be transferred to the reducers
i.e. how is the partition size decided and by what process is it decided
as the data is transferred using a pull mechanism instead of a push
mechanism. An interesting challenge to counter here would have been to
determine the overall size of the data as the data resides on multiple
nodes (I am guessing that the job tracker/master process may be aware of
the size and location of data for all the nodes, but I am not sure on that
too).
Wouldn't it be a performance penalty in terms of parallel processing if
the data is highly skewed and most of it belongs to a single key where
there are 10 or more reducers. In this case, only one reducer process
would be processing most of the data in a sequential fashion. Is this kind
of a situation handled in Hadoop? If yes, how?

Tuesday, 10 September 2013

mongoose model inheritance within javascript prototypal object

mongoose model inheritance within javascript prototypal object

Suppose you have a route initialization like this required in your main:
module.exports = function(app) {
for (var name in names) {
var schema = new Schema({}) // schema that accepts anything
, m = mongoose.model(name, schema)
, controller = TextController(m)
app.get('/path', controller.list.bind(controller))
// etc, etc
And TextController is defined externally as:
var TextController = function(Model) {
this.Model = Model
}
TextController.prototype.create = function(req, res) {
var aDoc = this.Model({ // this is the problematic bit
title: req.body.title
, content: req.body.content})
aDoc.save(function(err) {...})
}
For some reason, mongo saves this as an empty document even though the
title and content params are the expected strings. As expected, this.Model
is some sort of mongoose object, but it seems to be rejecting the save or
the instantiation. Any ideas or suggestions?
Note: I added the controller.method.bind(controller) because it was the
only way (I knew of) to get access to this.Model.

Cocos 2d-x Finding coordinates of child of sprite when layer has moved with CCFollow

Cocos 2d-x Finding coordinates of child of sprite when layer has moved
with CCFollow

I haven't been able to figure this out and it's driving me crazy.
I have a CCSprite that is followed by the camera with CCFollow. Calling
get position on the sprite gives me the expected coordinate, the
coordinate of the layer, such that if I click on any part of the layer,
the sprite moves to this position. The sprite itself has CCSprite children
(turrets), anchored at different positions, that should track a particular
position or enemy when clicked.
Like so
CCPoint turretPos =
m_turret->getParent()->convertToWorldSpace(m_turret->getPosition());
CCPoint targetPos = m_target->position();
CCPoint trackVector = ccpSub(turretPos, targetPos);
But now that the Layer moves, this does not work as the screen coordinates
and the layer coordinates do not line up. Without CCFollow, this works
perfectly.
If I call the sprite's parent sprite:
CCPoint pos = m_turret->getParent()->getPosition();
It gives me the expected value. But I can't get the child of that sprite
in that coordinate frame. I tried
m_turret->getParent()->getParent()->convertToNodeSpace but that fails as
well. What am I missing?
EDIT:
Figured an (annoying) way to do this. First convert the child's
coordinates to world
(m_turret->convertToWorldSpaceAR(m_turret->getPosition()), then, on the
parent's parent (the layer, in this case, not the parent sprite) call the
convertToNodeSpace method to place them in the proper coordinate frame. I
don't know of any easier method to do this so anyone with a better method,
please, contribute!

Fixed Sized Eigen types as parameters

Fixed Sized Eigen types as parameters

I am trying to write a function that takes fixed size Eigen Types (but
templated on Scalar type e.g. float/double). I have read
http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html but I am
not able to make it work perfectly.
Here is the function definition:
template <typename T>
inline Matrix<T, 3, 3> makeSkewSymmetric(const Matrix<T, 3, 1>& v)
{
Matrix<T, 3, 3> out;
out << 0, -v[2], v[1],
v[2], 0, -v[0],
-v[1], v[0], 0;
return out;
}
Now I am using this as following:
Vector3d a(1,2,3);
Matrix3d ass = makeSkewSymmetric(a); // Compiles
Matrix3d ass = makeSkewSymmetric(a + a); // does NOT compile
I guess, I need to use some sort of MatrixBase<Derived>, but then how do I
restrict the size, as the function only makes sense for vectors of length
3.


Edit: I redefined the function as following. It works, but is there a
better way?
template <typename Derived>
inline Matrix<typename Derived::Scalar, 3, 3> makeSkewSymmetric(const
MatrixBase<Derived>& v)
{
BOOST_STATIC_ASSERT(Derived::RowsAtCompileTime == 3 &&
Derived::ColsAtCompileTime == 1);
Matrix<typename Derived::Scalar, 3, 3> out;
out << 0, -v[2], v[1],
v[2], 0, -v[0],
-v[1], v[0], 0;
return out;
}

How can make my MainForm refresh?

How can make my MainForm refresh?

I have a MainForm and some components on it (RichTextBox, button, 2
textBoxes).
When I click my button, my application writes some text in the
richtextbox. After making some changes in the richtextBox and clicking
again on the button, I still see the old text on the richtextbox.
How can I make my MainForm refresh and also clear richtextBox each time I
click on the button?
I tried MainForm.Refresh(); and richtextBox.Clear(); but no luck!

IE8 Errors On chart.destroy()

IE8 Errors On chart.destroy()

Under IE9, FF, Chrome this presents no problems. However, under IE8 we get:
Object doesn't support this property or method
The offending line is:
chartMain.destroy();
We defined chartMain as:
chartMain = new Highcharts.Chart(optionsChartMain);
I can find no dangling commas or other js detritus that would make IE
choke. How can I fix this issue?

Need help to open popup in new window

Need help to open popup in new window

I am running an educational website, there is one query, I want to open a
popup on website load.
<script type="text/javascript">
$(document).ready(function() {
$.fn.colorbox({href:"http://www.governmentjobs-examresults-admitcard.in/",
open:true});
});
</script>

CSS selectors How to get the index of a particular element

CSS selectors How to get the index of a particular element

I am trying to use a css selector to select and item but only work for
xpath. What would be the equivalent of this xpath to css.
driver.findElement(By.xpath("(//img[@alt='Authorise this row'])[2].click();
If I use the css
img[alt='Authorise this row']
I get a lot of results through say firefinder.
Is there a way like xpath where you can get a particular index of the result?

using selector to enable/disable input text with jquery

using selector to enable/disable input text with jquery

I have problem with below code:
HTML
<table cellpadding="0" cellspacing="0" width="100%" class="table"
id="addtable" border="1">
<thead>
<tr>
<th width="4%"><b>Date</b></th>
<th width="4%"><b>Cut Number</b></th>
<th width="4%"><b>Content</b></th>
<th width="4%"><b>Others</b></th>
<th width="5%"><b>Customer name</b></th>
<th width="4%"><b>Customer code</b></th>
<th width="5%"><b>Address</b></th>
<th width="5%"><b>Owe amount</b></th>
<th width="4%"><b>Executive</b></th>
<th width="6%"><b>Obtain Amount</b></th>
<th width="9%"><b>Obtain Room</b></th>
</tr>
</thead>
<tbody>
<tr id="addrow">
<td><input name="date[]" id="mask_dm1" type="text" size="1"
value=""></td>
<td><input name="cutno[]" type="text" size="6" ></td>
<td>
<select name="cutcontent[]" id="selector">
<option value="0">Please select</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="other">Other</option>
</select>
</td>
<td><input name="cutother[]" type="text" size="4" id="cutother"
disabled /></td>
<td><input name="cusname[]" type="text" size="4" ></td>
<td><input name="cuscode[]" type="text" size="2" ></td>
<td><input name="cusaddress[]" type="text" size="4" ></td>
<td><input name="owe[]" type="text" size="2" id="cutowe" disabled
/></td>
<td><input name="executive[]" type="text" size="1" /></td>
<td><input name="obtainamount[]" type="text" size="2"
id="obtainamount" disabled /></td>
<td><input name="obtainroom[]" type="text" size="2" id="obtainroom"
disabled /></td>
</tr>
</tbody>
Javascript:
$(document).ready(function(){
var clonedRow = ' <td><input name="date[]" id="mask_dm1" type="text"
size="1" value=""></td>';
clonedRow += ' <td><input name="cutno[]" type="text" size="6" ></td>';
clonedRow += ' <td>';
clonedRow += ' <select name="cutcontent[]" id="selector">';
clonedRow += ' <option value="0">Please select</option>';
clonedRow += ' <option value="1">Value 1</option>';
clonedRow += ' <option value="2">Value 2</option>';
clonedRow += ' <option value="3">Value 3</option>';
clonedRow += ' <option value="other">Other</option>';
clonedRow += ' </select>';
clonedRow += ' </td>';
clonedRow += ' <td><input name="cutother[]" type="text" size="4"
id="cutother" disabled /></td>';
clonedRow += ' <td><input name="cusname[]" type="text" size="4" ></td>';
clonedRow += ' <td><input name="cuscode[]" type="text" size="2" ></td>';
clonedRow += ' <td><input name="cusaddress[]" type="text" size="4"
></td>';
clonedRow += ' <td><input name="owe[]" type="text" size="2"
id="cutowe" disabled /></td>';
clonedRow += ' <td><input name="executive[]" type="text" size="1"
/></td>';
clonedRow += ' <td><input name="obtainamount[]" type="text" size="2"
id="obtainamount" disabled /></td>';
clonedRow += ' <td><input name="obtainroom[]" type="text" size="2"
id="obtainroom" disabled /></td>';
var appendRow = '<tr id="addrow">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
$('#addtable tr:last').after(appendRow);
$('select#selector').change(function(){
var theVal = $(this).val();
switch(theVal){
case '1':
$('input#cutowe').removeAttr('disabled');
$('input#obtainamount').removeAttr('disabled');
$('input#obtainroom').removeAttr('disabled');
break;
case '2':
$('input#cutother').removeAttr('disabled');
break;
default:
$('input#cutowe').attr('disabled', 'disabled');
$('input#obtainamount').attr('disabled', 'disabled');
$('input#obtainroom').attr('disabled', 'disabled');
$('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
$('select#selector').change(function(){
var theVal = $(this).val();
switch(theVal){
case '1':
$('input#cutowe').removeAttr('disabled');
$('input#obtainamount').removeAttr('disabled');
$('input#obtainroom').removeAttr('disabled');
break;
case '2':
$('input#cutother').removeAttr('disabled');
break;
default:
$('input#cutowe').attr('disabled', 'disabled');
$('input#obtainamount').attr('disabled', 'disabled');
$('input#obtainroom').attr('disabled', 'disabled');
$('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
When I press "Add more row" button, the selector named "Content" at row#2
has effect on the all input. how to resolve it? see example
http://jsfiddle.net/N2jyy/6/

Connection String on IP

Connection String on IP

i have a problem with my connection string... i want to connect to
172.16.0.253,8887 but i cannot access it in ASP.NET but I can access it in
SQL SERVER... what seems to be the problem with my script
code:
<connectionStrings>
<add name="DBCS"
connectionString="Data Source=172.16.0.253,8887; database = webloan;
User ID=sa; Password=12345; integrated security = SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>

Monday, 9 September 2013

Run android project even if .xml file is visible in editor

Run android project even if .xml file is visible in editor

I am using Eclipse Juno . In that whenever I tried to run my android
project while .xml file is visible it is not able to run but if .java file
is visible then i am able to run my project.
Why this is happen. Is this the new functionality of IDE? If I want to run
my application even if xml is visible on editor how can I do that?

Mount a TrueCrypt container on Ubuntu using CryptSetup

Mount a TrueCrypt container on Ubuntu using CryptSetup

I have a truecrypt container which I created on Windows, I moved it now to
an Ubuntu machine which has cryptsetup already installed. How can I mount
the truecrypt container as Read/Write using cryptsetup?
Please advise. Thank you in advance.

how to put two variables together

how to put two variables together

Noob question. I'm checking if a file exists in perl, but I'm not sure how
to put two variables together when I have a sourceFile predetermined, and
a path that must be passed in as argument. In other words, how do I concat
an argument passed in with another variables so that I could use perl's
file test -X function?
$sourceFile = 'somefile';
if ( $ARGV[0] && -e ($ARGV[0] + '\' + $sourceFile) )
I've also tried:
if ( $ARGV[0] && -e ($ARGV[0]\\$sourceFile) )

C++ declare platform independent 32-bit float

C++ declare platform independent 32-bit float

Is there a way to declare 32-bit floating point value in C++ - ensuring
that it will always be 32 bits regardless of platform/compiler?
I can do that for integers like that:
#include <stdint.h>
uint32_t var; //32 bit unsigned integer
uint64_t var1; //64 bit unsigned integer
is there a way to do something like that for floats? As far as I know,
float var; //Usually is 32 bit, but NOT GUARANTEED to be 32 bit
is implementation specific, and is not necessarily 32 bit.. (Correct me if
I am wrong).
I am using qt, so if there is any solution using it I would accept it - I
couldn't find anything like quint16 for floats (qreal changes size
depending on platform).

Javascript - Highcharts - input data array of arrays

Javascript - Highcharts - input data array of arrays

I am trying to feed the hghcharts diagram with input data but face one
problem. I get the data via json and then add them to data just like this:
function getGraphValues() {
period.deviceID = user.deviceID;
var postData = JSON.stringify(period);
var postArray = {json:postData};
$.ajax({
type: 'POST',
url: "getData.php",
data: postArray,
success: function(data)
{
data1 = JSON.parse(data);
if (data1.status == "ok" )
{
var stats = data1.metrics.split("/");
$(function () {
$('#container').highcharts(
{
chart: {type: 'bubble',zoomType: 'xy'},
title: {text: 'Highcharts Bubbles'},
series: [{data: [getData(stats)]}]
});});
}
else
{
alert("error");
}}
});}
function getData(stats)
{
var data;
var stats;
for (var j = 0; j < stats.length; j++)
{
data += "[" + j + "," + stats[j] + "," + stats[j]*8 + "],";
}
stats = data.split(",");
return stats;
}
So, in a way like this I do get the stats in this form:
[47,47,21],[20,12,4],[6,76,91],[38,30,60],[57,98,64],[61,17,80],[83,60,13],[67,78,75]
stored in string variable. My problem is that I can't pass this string for
the data input as it waits number and not string. How should I feed the
data attribute in an accpetable way ? How can I create an array of array
in the getData function if this is needed ? Thank you.

Pickadate.js: how to render the widget via another element

Pickadate.js: how to render the widget via another element

By default http://amsul.ca/pickadate.js/index.htm render the widget when
the user click on the input.
I created an icon and I want, when the user click on it, to show the
widget. I tried with:
$('#my-icon').on('click', function(){
$("input.dateFormat").pickadate();
$("input.dateFormat").click(); // Tried also with trigger
});
But the calendar does not show.
There is a way?

Set the correct zoom in a UIMapView

Set the correct zoom in a UIMapView

I made a count-steps app, I count the steps with the iPhone accelerometer
and now I want to display the path I made on a mapView. I can easily show
the map and catch the right position with the iPhone GPS, I can display
the start and the end point and I can to draw a polyline to show the path
I made. Now my problem is how to set a correct zoom on the map? When I
open the ViewController with map the zoom it's too far and I've to zoom to
see the path I made. So my question is how to set a correct zoom? I post
here the code of the View Controller with the mapView:
ResultViewController.m
#import "ResultViewController.h"
#import "MapAnnotation.h"
@interface ResultViewController ()
@property (nonatomic, strong)NSMutableArray *mapAnnotation;
@property (nonatomic) BOOL needUpdateRegion;
@end
@implementation ResultViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.labelResult.text = self.totalSteps;
[self.mapView setDelegate:self];
self.needUpdateRegion = YES;
self.mapAnnotation = [[NSMutableArray alloc]initWithCapacity:2];
CLLocation *startLocation = [self.locationArray objectAtIndex:0];
CLLocation *stopLocation = [self.locationArray lastObject];
NSString *startLatitude = [NSString stringWithFormat:@"%f",
startLocation.coordinate.latitude];
NSString *startLongitude = [NSString stringWithFormat:@"%f",
startLocation.coordinate.longitude];
NSString *stopLatitude = [NSString stringWithFormat:@"%f",
stopLocation.coordinate.latitude];
NSString *stopLongitude = [NSString stringWithFormat:@"%f",
stopLocation.coordinate.longitude];
MapAnnotation *startPlace = [[MapAnnotation
alloc]initWithCoordinate:startLatitude andLong:startLongitude];
MapAnnotation *stopPlace = [[MapAnnotation
alloc]initWithCoordinate:stopLatitude andLong:stopLongitude];
[self.mapAnnotation insertObject:startPlace atIndex:0];
[self.mapAnnotation insertObject:stopPlace atIndex:1];
if (self.mapAnnotation) {
[self.mapView removeAnnotations:self.mapView.annotations];
}
[self.mapView addAnnotation:self.mapAnnotation[0]];
[self.mapView addAnnotation:self.mapAnnotation[1]];
[self updateRegion];
[self createMKpolylineAnnotation];
}
- (void)updateRegion
{
self.needUpdateRegion = NO;
CGRect boundingRect;
BOOL started = NO;
for (id <MKAnnotation> annotation in self.mapView.annotations) {
CGRect annotationRect = CGRectMake(annotation.coordinate.latitude,
annotation.coordinate.longitude, 0, 0);
if (!started) {
started = YES;
boundingRect = annotationRect;
} else {
boundingRect = CGRectUnion(boundingRect, annotationRect);
}
}
if (started) {
boundingRect = CGRectInset(boundingRect, -0.2, -0.2);
if ((boundingRect.size.width < 20) && (boundingRect.size.height <
20)) {
MKCoordinateRegion region;
region.center.latitude = boundingRect.origin.x +
boundingRect.size.width / 2;
region.center.longitude = boundingRect.origin.y +
boundingRect.size.height / 2;
region.span.latitudeDelta = boundingRect.size.width;
region.span.longitudeDelta = boundingRect.size.height;
[self.mapView setRegion:region animated:YES];
}
}
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id
<MKOverlay>)overlay {
MKPolylineView *polylineView = [[MKPolylineView alloc]
initWithPolyline:overlay];
polylineView.strokeColor = [UIColor blueColor];
polylineView.lineWidth = 5.0;
return polylineView;
}
- (void)createMKpolylineAnnotation {
NSInteger numberOfSteps = self.locationArray.count;
CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D)
* numberOfSteps);
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [self.locationArray objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coords[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coords
count:numberOfSteps];
[self.mapView addOverlay:polyLine];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)restart:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
What's wrong with this code? There's someone that can help me to zoom the
map correctly?
Thank you

Asynchronous server and client with named pipes

Asynchronous server and client with named pipes

I've came up with the follwing piece of code:
class IPCServer
{
private Thread ipcServerThread;
private NamedPipeServerStream pipeServer;
public IPCServer()
{
pipeServer = new NamedPipeServerStream("iMedCallInfoPipe",
PipeDirection.Out, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous);
}
public void SendMessage (String message) {
ThreadStart ipcServerThreadInfo = () => WriteToPipe(message);
ipcServerThread = new Thread(ipcServerThreadInfo);
ipcServerThread.Start();
}
private void WriteToPipe(String message)
{
if (pipeServer.IsConnected)
{
byte[] bytes = Encoding.UTF8.GetBytes(message);
pipeServer.Write(bytes, 0, bytes.Length);
pipeServer.WaitForPipeDrain();
pipeServer.Flush();
}
}
}
class ICPClient
{
public void Read(int TimeOut = 1000)
{
try
{
NamedPipeClientStream pipeStream = new
NamedPipeClientStream(".", "iMedCallInfoPipe",
PipeDirection.In, PipeOptions.None);
pipeStream.Connect(TimeOut);
using (StreamReader sr = new StreamReader(pipeStream))
{
string _buffer;
while ((_buffer = sr.ReadLine()) != null)
{
Console.WriteLine("Received from server: {0}", _buffer);
}
}
}
catch (TimeoutException)
{
}
}
}
and this is the client server for pipe-communicating solutiuon. But I need
the server to write messages asynchronously and client to read them
whenever they pop up, also asynchronously. How can I achieve this? There
is number of samples but most of them consider client writing to server
and i'm not sure how to achieve my goal, especially with my
already-written code...

Sunday, 8 September 2013

config.active_record.default_timezone = :local ... Doesn't seem to have any effect

config.active_record.default_timezone = :local ... Doesn't seem to have
any effect

The configuration for active_record.default_timezone does not seem to work
as advertised. I expected that after setting:
config.active_record.default_timezone = :local
(in config/application.rb) that outputting a time retrieved from the db
would show an offset in the local timezone.
2.0.0p247 :016 > user = User.new name: "Tom", email: "tom@gmail.com"
=> #<User id: nil, name: "Tom", email: "tom@gmail.com", created_at: nil,
updated_at: nil>
2.0.0p247 :017 > user.save
(0.3ms) SAVEPOINT active_record_1
SQL (0.8ms) INSERT INTO "users" ("created_at", "email", "name",
"updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["created_at",
Sun, 08 Sep 2013 23:38:22 UTC +00:00], ["email", "tom@gmail.com"],
["name", "Tom"], ["updated_at", Sun, 08 Sep 2013 23:38:22 UTC +00:00]]
(0.7ms) RELEASE SAVEPOINT active_record_1
=> true
2.0.0p247 :018 > puts user.created_at
2013-09-08 23:38:22 UTC <----------+
=> nil |
|---- WHY DON'T THESE HAVE THE SAME
OFFSET???
2.0.0p247 :019 > Time.now |
=> 2013-09-08 17:38:36 +0200 <------+
2.0.0p247 :020 > Rails.application.config.active_record.default_timezone
=> :local
2.0.0p247 :021 >
2.0.0p247 :022 > Rails.application.config
=> #<Rails::Application::Configuration:0x00000100af1508
@root=#<Pathname:/Users/7stud/rails_projects/test_postgres>,
@generators=#<Rails::Configuration::Generators:0x00000100ff3128
@aliases={}, @options={:rails=>{:orm=>:active_record,
:test_framework=>:rspec, :integration_tool=>:rspec,
:stylesheet_engine=>:scss, :javascript_engine=>:coffee,
:scaffold_controller=>:jbuilder_scaffold_controller,
:json_template_engine=>:jbuilder}, :active_record=>{:migration=>true,
:timestamps=>true}, :test_unit=>{:fixture=>true,
:fixture_replacement=>nil}}, @fallbacks={}, @templates=[],
@colorize_logging=true, @hidden_namespaces=["sass"]>, @encoding="utf-8",
@allow_concurrency=nil, @consider_all_requests_local=true,
@filter_parameters=[:password], @filter_redirect=[],
@helpers_paths=["/Users/7stud/rails_projects/test_postgres/app/helpers"],
@serve_static_assets=true, @static_cache_control=nil, @force_ssl=false,
@ssl_options={}, @session_store=:cookie_store,
@session_options={:key=>"_test_postgres_session", :cookie_only=>true},
@time_zone="UTC", @beginning_of_week=:monday, @log_level=:debug,
@middleware=#<ActionDispatch::MiddlewareStack:0x00000100fa5158
@middlewares=[ActionDispatch::Static, Rack::Lock,
#<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x00000102a2e6c8>,
Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId,
Rails::Rack::Logger, ActionDispatch::ShowExceptions,
ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp,
ActionDispatch::Reloader, ActionDispatch::Callbacks,
ActiveRecord::Migration::CheckPending,
ActiveRecord::ConnectionAdapters::ConnectionManagement,
ActiveRecord::QueryCache, ActionDispatch::Cookies,
ActionDispatch::Session::CookieStore, ActionDispatch::Flash,
ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet,
Rack::ETag]>, @cache_store=[:file_store,
"/Users/7stud/rails_projects/test_postgres/tmp/cache/"],
@railties_order=[:all], @relative_url_root=nil,
@reload_classes_only_on_change=true,
@file_watcher=ActiveSupport::FileUpdateChecker, @exceptions_app=nil,
@autoflush_log=true,
@log_formatter=#<ActiveSupport::Logger::SimpleFormatter:0x00000100af8c18
@datetime_format=nil>, @eager_load=false, @secret_token=nil,
@secret_key_base="123f640f8d665d9a20bc49ae045b1a0edd41972db82091ec8bd3ff0836d805698fbe70ca75d2a78c3cd088774412b67f789d74b7a2422ad30acc589487f49ce7",
@assets={:enabled=>true, :paths=>[],
:precompile=>[#<Proc:0x00000100b02970@/Users/7stud/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/application/configuration.rb:54>,
/(?:\/|\\|\A)application\.(css|js)$/], :prefix=>"/assets",
:version=>"1.0", :debug=>false, :compile=>true, :digest=>false,
:cache_store=>[:file_store,
"/Users/7stud/rails_projects/test_postgres/tmp/cache/assets/development/"],
:js_compressor=>nil, :css_compressor=>nil,
:initialize_on_precompile=>true, :logger=>nil},
@paths=#<Rails::Paths::Root:0x00000100b1b6a0 @current=nil,
@path=#<Pathname:/Users/7stud/rails_projects/test_postgres>,
@root={"app"=>#<Rails::Paths::Path:0x00000100b1b2e0 @paths=["app"],
@current="app", @root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>,
@glob="*", @autoload_once=false, @eager_load=true, @autoload=false,
@load_path=false>, "app/assets"=>#<Rails::Paths::Path:0x00000100b1aef8
@paths=["app/assets"], @current="app/assets",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*",
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"app/controllers"=>#<Rails::Paths::Path:0x00000100b1ac50
@paths=["app/controllers"], @current="app/controllers",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=true, @autoload=false,
@load_path=false>, "app/helpers"=>#<Rails::Paths::Path:0x00000100b1a840
@paths=["app/helpers"], @current="app/helpers",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=true, @autoload=false,
@load_path=false>, "app/models"=>#<Rails::Paths::Path:0x00000100b1a110
@paths=["app/models"], @current="app/models",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=true, @autoload=false,
@load_path=false>, "app/mailers"=>#<Rails::Paths::Path:0x00000100b19da0
@paths=["app/mailers"], @current="app/mailers",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=true, @autoload=false,
@load_path=false>, "app/views"=>#<Rails::Paths::Path:0x00000100b19940
@paths=["app/views"], @current="app/views",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"app/controllers/concerns"=>#<Rails::Paths::Path:0x00000100b193a0
@paths=["app/controllers/concerns"], @current="app/controllers/concerns",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=true, @autoload=false,
@load_path=false>,
"app/models/concerns"=>#<Rails::Paths::Path:0x00000100b19058
@paths=["app/models/concerns"], @current="app/models/concerns",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=true, @autoload=false,
@load_path=false>, "lib"=>#<Rails::Paths::Path:0x00000100b18978
@paths=["lib"], @current="lib",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=true>, "lib/assets"=>#<Rails::Paths::Path:0x00000100b181a8
@paths=["lib/assets"], @current="lib/assets",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*",
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "lib/tasks"=>#<Rails::Paths::Path:0x00000100b238a0
@paths=["lib/tasks"], @current="lib/tasks",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="**/*.rake",
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "config"=>#<Rails::Paths::Path:0x00000100b22f90
@paths=["config"], @current="config",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"config/environments"=>#<Rails::Paths::Path:0x00000100b22090
@paths=["config/environments"], @current="config/environments",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="development.rb",
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"config/initializers"=>#<Rails::Paths::Path:0x00000100b21bb8
@paths=["config/initializers"], @current="config/initializers",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="**/*.rb",
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"config/locales"=>#<Rails::Paths::Path:0x00000100b212a8
@paths=["config/locales"], @current="config/locales",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*.{rb,yml}",
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"config/routes.rb"=>#<Rails::Paths::Path:0x00000100b20d58
@paths=["config/routes.rb"], @current="config/routes.rb",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "db"=>#<Rails::Paths::Path:0x00000100b20858
@paths=["db"], @current="db", @root=#<Rails::Paths::Root:0x00000100b1b6a0
...>, @glob=nil, @autoload_once=false, @eager_load=false,
@autoload=false, @load_path=false>,
"db/migrate"=>#<Rails::Paths::Path:0x00000100b20510
@paths=["db/migrate"], @current="db/migrate",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "db/seeds.rb"=>#<Rails::Paths::Path:0x00000100b20088
@paths=["db/seeds.rb"], @current="db/seeds.rb",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "vendor"=>#<Rails::Paths::Path:0x00000100b2bf78
@paths=["vendor"], @current="vendor",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=true>, "vendor/assets"=>#<Rails::Paths::Path:0x00000100b2b8e8
@paths=["vendor/assets"], @current="vendor/assets",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob="*",
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"config/database"=>#<Rails::Paths::Path:0x00000100b2b320
@paths=["config/database.yml"], @current="config/database",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"config/environment"=>#<Rails::Paths::Path:0x00000100b2add0
@paths=["config/environment.rb"], @current="config/environment",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "lib/templates"=>#<Rails::Paths::Path:0x00000100b2a1c8
@paths=["lib/templates"], @current="lib/templates",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "log"=>#<Rails::Paths::Path:0x00000100b29f70
@paths=["log/development.log"], @current="log",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "public"=>#<Rails::Paths::Path:0x00000100b299a8
@paths=["public"], @current="public",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"public/javascripts"=>#<Rails::Paths::Path:0x00000100b29390
@paths=["public/javascripts"], @current="public/javascripts",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>,
"public/stylesheets"=>#<Rails::Paths::Path:0x00000100b28af8
@paths=["public/stylesheets"], @current="public/stylesheets",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>, "tmp"=>#<Rails::Paths::Path:0x00000100b28418
@paths=["tmp"], @current="tmp",
@root=#<Rails::Paths::Root:0x00000100b1b6a0 ...>, @glob=nil,
@autoload_once=false, @eager_load=false, @autoload=false,
@load_path=false>}>, @autoload_paths=[],
@eager_load_paths=["/Users/7stud/rails_projects/test_postgres/app/assets",
"/Users/7stud/rails_projects/test_postgres/app/controllers",
"/Users/7stud/rails_projects/test_postgres/app/helpers",
"/Users/7stud/rails_projects/test_postgres/app/mailers",
"/Users/7stud/rails_projects/test_postgres/app/models",
"/Users/7stud/rails_projects/test_postgres/app/controllers/concerns",
"/Users/7stud/rails_projects/test_postgres/app/models/concerns"],
@autoload_once_paths=[], @cache_classes=false>
config/application.rb:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module TestPostgres
class Application < Rails::Application
# Settings in config/environments/* take precedence over those
specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record
auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
config.active_record.default_timezone = :local
# The default locale is :en and all translations from
config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales',
'*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end