Monday, 30 September 2013

Fortigate bandwidth monitoring

Fortigate bandwidth monitoring

I have a Fortigate 200B with Forti OS 5.0.
How can I watch the total bandwidth being used by my unit both incoming
and outgoing?
Thanks

What seems wrong with this bash script?

What seems wrong with this bash script?

I found an initscript that for some reason insists on starting the
specified application as the root user. I can't wrap my head around why it
is doing this, any hints? The script runs on Redhat Enterprise Linux 5.9.
#!/bin/bash
#
# Start/Stop apfe.
#
# chkconfig: - 62 38
# description: apfe
# Start script for an apfe process.
# Apfe does not normally run as root, so we change user
# and call the real script in $USERDIR.
STARTUSER=apfe
USERDIR=/app/apfe/apps/apfeutils/bin
PROGNAME=apfe
su - $STARTUSER -c "$USERDIR/$PROGNAME $*"

How can I check if website is already opened in a webbrowser?

How can I check if website is already opened in a webbrowser?

I'm doing this:
Process.Start("http://www.google.com");
After the default webbrowser is opened the website i want to check somehow
that the website is opened by the webbrowser and close the specicif tab
with this website.
To make a button click event that will check that if the website is
already opened then close it.

What does y scaling mean in svm-scale

What does y scaling mean in svm-scale

Does it mean to scale the value of the target(class),which is the first
column of every instance?
Regards,
amber@cent64 libsvm-3.17]$ svm-scale Usage: svm-scale [options]
data_filename options: -l lower : x scaling lower limit (default -1) -u
upper : x scaling upper limit (default +1) -y y_lower y_upper : y scaling
limits (default: no y scaling) -s save_filename : save scaling parameters
to save_filename -r restore_filename : restore scaling parameters from
restore_filename

Sunday, 29 September 2013

responsive navigation links wont react to class

responsive navigation links wont react to class

I am working on a website simplemedia.dk
i have a responsive menu that works, but when i am trying to define the
in responsive mode the browsers does not recognize the style ..
in responsive mode i get a class called "responsified" and i tried adding
the class .responsified in front of my navigation style but it doesnt
react to it.
.responsive-menus .responsive-menus-0-0 .absolute .responsified
.responsive-toggled #navigation ul.menu{display:block; float:left; }
.responsive-menus .responsive-menus-0-0 .absolute .responsified
.responsive-toggled #navigation ul.menu li{display:block; float:left;}
In normal mode i want it to display table-cell which it does, but in
responsive i want it to show block.

How do I make a Time Conversion program on java?

How do I make a Time Conversion program on java?

![Its a Project im working on at school][1]
How do i make it go from Minutes-Hours? 135mins-2:15hours I just started
programming help me please!!

How remap CTRL-key to Alt right (tried everything)

How remap CTRL-key to Alt right (tried everything)

My specs: Xubuntu 13.04, which uses (what I believe) Xorf as X Window
Manager.
Intro: some weeks ago I switched to Linux (Xubuntu). I configured
everything to work only with my keyboard without ever using the mouse.
Works like a charm. But recent, I wanted to remap the [ctrl] to
[capslock]. ~/.xmodmap seems not working. I found the answer here:
**/usr/bin/setxkbmap -option "ctrl:nocaps"** does the trick. I putted the
command as autostart.
Works fine until I got RSI-like issues with my left pink the last days. My
pink tingles weird and causes much pain at the end of day (even I'm using
ergonomic keyboard!). I tried everything to avoid this, like the correct
posture and taking breaks, weight lifting. Nothing helps. Then I looked
closer to my keyboard flow. I noticed I use the spacebar most, on second
the [Capslock]-button that behaves like [ctrl]. But I have no pain in my
thumbs. I dont use the right [Alt], so it would be better if I remap the
[ctrl]-key to [alt-key], so I can activate [ctrl] with my thumb.
What have I done?
Tried this: /usr/bin/setxkbmap -option "ctrl:alt_R" Not working.
Tried this: /usr/bin/setxkbmap -option "ctrl:Meta_R" Not working.
Tried the .xmodmap configuration. I start xev, pressed the right [alt] key
and it gives me keycode 108. [ctrl] gives me 37. So i create up ~/.Xmodmap
and map: keycode 108 = Control_L and reboot. Not working.
I've searched through the forums a lot, but have not found a solution. Any
suggestions how manage the right Alt+key behave as [ctrl]-key?
Thanks in advance for your appreciated help.
================== Edit: found the answer! Without the open source spirit,
I would never able to find my way here. And everyone benefits too!
The answer is..... bumbumbrrrrr...
setxkbmap -option ctrl:ralt_rctrl :D

Text alignment issue in a quote banner

Text alignment issue in a quote banner

as you can see on this JSFiddle and on picture below, I'm struggling to
get the signature placed as I want in my banner (I want it at the bottom
right of the blue banner without interfering with the quote text
alignment). The issue that I have is that with my current code the second
line of the text is not perfectly aligned horizontally to the middle of
the block (there's more space to the right than to the left). How could I
fix this and have full control on the signature position? Many thanks,

HTML:
<div class="block blueback center">
<h2 class="white">dfjdsjdklj dsjfdslfjldsjf ldsjfdlsjflkdsfjdlskjf
dljfdslfjkldsj dljfsdljfdklsj lkdjflkdsjdlks dsfjsdlkfjkls
dsjflkdsfjdkl</h2><p class="signature">John Dupont</p>
</div>
CSS:
.block {
display: block;
margin-right: auto;
margin-left: auto;
clear: both;
box-sizing: border-box;
padding-left: 20px;
padding-right: 20px;
width: 100%;
overflow: hidden;
}
h2 {
color: #2165CB;
font-weight: 600;
font-size: 18px;
}
.white { color: #fff;
letter-spacing: 1px;
font-style: italic;
font-weight: 300;
display: inline;
}
.center {
vertical-align: middle;
text-align: center;
padding-bottom: 5px;
padding-top: 5px;
}
.signature {
display: inline;
margin-top: 20px;
margin-bottom: 0px;
padding-top: 0px;
font-size: 12px;
color: #fff;
float: right;
font-weight: 700;
}
.blueback {
background: #0064C4;
}

Saturday, 28 September 2013

In PHP would this be deemed correct?

In PHP would this be deemed correct?

I already wrote a post about an issue I had before about this but I had
that issue taken care of. Like my last post I have a form, text-box and a
button. I have everything done with this including Printing the original
word, Printing the number of characters in the word, Printing the word in
all caps and Printing the word in reverse order. My only issue I'm having
is trying to get whatever text I enter and then click the button to output
to Print the first letter of the word and Print the last letter of the
word. I've been doing a lot of looking around of PHP.net and I found that
substr is used to return a part of a string that I could use. The only
issue is when I write the code for it and try to execute my program it
errors out on that specific line. I'm not looking for the answer but could
someone just take a look and see what I'm doing wrong because I understand
everything completely but this is the only thing I'm hung up on.
$first = substr($_POST['entertext']);
echo "The first letter of the word is " . $first. "<br />\n";
$last = substr($_POST['entertext']);
echo "The first letter of the word is " . $last. "<br />\n";

Jersey framework override contoller methods or REST request filtering

Jersey framework override contoller methods or REST request filtering

I need to implement a controller for processing requests whith filter use
Jersey framework. For example:
.../myservice/book - display a list of all books.
.../myservice/book?chapter=1,5 - display 1 and 5 books chapters.
.../myservice/book?page=10,50 - display 10 and 50 books pages.
.../myservice/book?chapter=1,5&page=10,50 - display 1 and 5 books chapters
and only 10 and 50 book pages.
I can't use .../myservice/book/chapter/1,5/page/10,50, because possible
situation: .../myservice/book/7 - display book 7 and filters described
above can be applied here. Is it possible to implement it in this way:
public class TestController {
@Path("/book")
@GET
public Object getBook() {
// return a list of all books
}
public Object getBook(@QueryParam("chapter") String chapter) {
// return books chapters
}
public Object getBook(@QueryParam("chapter") String page) {
// return books pages
}
public Object getBook(@QueryParam("chapter") String page,
@QueryParam("page") String page) {
// return books chapters and pages
}
}
Or to add all kinds of filters in one method and verify the presence of a
large number of conditions?

How to make Intro Section visible on mobile device (Wordpress Responsive Theme)

How to make Intro Section visible on mobile device (Wordpress Responsive
Theme)

I need some help to custom my site. You can take a look to my site first
http://next.coupleshops.com
You can see the first intro section, "We proudly present, ...." (it's a
Image file)
The problem is when I open it from mobile device like iphone or samsung
galaxy, the intro section won't show up. it skipped to the "News" section.
Anyone know how to make it visible and responsive on mobile device?

Friday, 27 September 2013

Postgresql: how to correctly create timestamp with timezone from timestamp, timezone fields

Postgresql: how to correctly create timestamp with timezone from
timestamp, timezone fields

I have a table with a timestamp without time zone. YYYY-MM-DD HH:MM:SS
and a field "timezone" that is either "P" for Pacific or "M" for Mountain.
I need to create a field of type "timestamp with time zone"
Given the two fields I have, is there a way to do this that correctly
accounts for Daylight Saving Time?
Specifically: timestamp: 2013-11-03 01:00:00 timezone: "P" would become:
2013-11-03 01:00:00-07
and timestamp: 2013-11-03 03:00:00 timezone: "P" would become: 2013-11-03
01:00:00-08

MySQL - given multiple associations, how to get latest association for several records?

MySQL - given multiple associations, how to get latest association for
several records?

Let's say I have two tables (non-essential rows omitted):
Table `pages`
page_id | page_key
1 | home
2 | about
and
Table `page_versions`
page_id | page_version | page_title | page_content
1 | 2 | Home | Lorem Ipsum...
1 | 4 | Home | Dolor Sit...
2 | 3 | About | Nunc Nisl...
2 | 5 | About | Proin Alt...
If each page has multiple page_versions, how do I query the database such
that I get all pages associated to their latest page_version?
Essentially:
page_id | page_key | page_version | page_title | page_content
1 | home | 4 | Home | Dolor Sit...
2 | about | 5 | About | Proin Alt...

global operator + override clash detection

global operator + override clash detection

My code is is clashing with a 3rd party library. I define this:
inline __m128 operator + (__m128 a, __m128 b)
{
return _mm_add_ps(a, b);
}
but get
error C2084: function '__m128 operator +(const __m128,const __m128)'
already has a body
I can't change the 3rd party library and they don't #define anything which
identifies this operator as having been defined. Is there a way (perhaps
using SFINAE) that anyone knows of to allow their definition to prevail?

Thread start in main method

Thread start in main method

I am attempting to start a thread inside of the main method, but it will
not call the run method when i start the thread. I think it may have
something to do with starting a thread in a thread:
package com.audiack.theForest;
public class theForestThread implements Runnable {
private static int theBeginningTimes = 0;
private static TheBeginning theBeginning = new TheBeginning();
public static void main(String args[]){
Thread thread = new Thread();
thread.start();
}
@Override
public void run() {
theBeginning.start(theBeginningTimes);
theBeginningTimes++;
}
}

How to create EF in scosta smartcard

How to create EF in scosta smartcard

I m writing into scosta smartcard card by using APDU commands. I am able
to create MF and DF but when I am creating EF i am getting 6A80 error.
Command which i m using for creating the EF, 00 E0 00 00 09 62 07 82 01 00
83 02 4004 00
Please provide me the command for creating EF.
Thanks in advance.

Thursday, 26 September 2013

jQuery datetimepicker option minDateTime bug?

jQuery datetimepicker option minDateTime bug?

<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
/* css for timepicker */
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { float: left; clear:left; padding: 0 0 0 5px; }
.ui-timepicker-div dl dd { margin: 0 10px 10px 45%; }
.ui-timepicker-div td { font-size: 90%; }
.ui-tpicker-grid-label { background: none; border: none; margin: 0;
padding: 0; }
.ui-timepicker-rtl{ direction: rtl; }
.ui-timepicker-rtl dl { text-align: right; padding: 0 5px 0 0; }
.ui-timepicker-rtl dl dt{ float: right; clear: right; }
.ui-timepicker-rtl dl dd { margin: 0 45% 10px 10px; }
</style>
<script
src="http://trentrichardson.com/examples/timepicker/jquery-ui-timepicker-addon.js"></script>
<script>
$(function() {
$( "#datetimepicker" ).datetimepicker({
minDateTime:new Date("2015/03/04 20:15"),
controlType:'select'
});
});
</script>
</head>
<body>
Date: <input type="text" id="datetimepicker" />
</body>
</html>
I set a minDateTime as "2015/03/04 20:15" for #datetimepicker,when I click
it ,For each hour of the day can not select the number of minutes less
than 15. jQuery datetimepicker option minDateTime bug?or my way is wrong?

Wednesday, 25 September 2013

Error moving jQuery slider with iScroll5 beta

Error moving jQuery slider with iScroll5 beta

I'm working on iScroll5 Beta. I want to make a magazine style mobile webpage.
http://bit.ly/1b7FQco
When I swipe left or right, it works well and slider would move to right
position. But there is a problem. When I drag a slider point on bottom
bar, "scrollTo(-320 * e.target.value, 0, 500);" is works well. And then I
swipe up and down on color page, unsuspected page would be shown. I'm not
good at writing English. So I made a movie when I swipe it.
Swipe Error You Tube File
http://www.youtube.com/watch?feature=player_detailpage&v=4P5N0r_dKyg
After watching this video, you would know what the problem is.
Here's codes.
Script
var myScroll;
function loaded () {
myScroll = new IScroll('#wrapper', {
scrollX: true,
scrollY: false,
momentum: false,
snap: true,
snapSpeed: 400,
tap: true,
click: true
});
myScroll.on("scrollEnd", function() {
$('#slider-1').val(myScroll.currentPage.pageX);
});
$('#slider-1').bind('mouseup', function(e) {
myScroll.scrollTo(-320 * e.target.value, 0, 500);
myScroll.x = -320 * e.target.value;
myScroll.currentPage.x = -320 * e.target.value;
myScroll.currentPage.pageX = e.target.value;
});
}

Thursday, 19 September 2013

Enable Firebug lite to edit HTML

Enable Firebug lite to edit HTML

The little sister of Firebug is a standalone Javascript tool -> Firebug lite
Source
or hosted
https://getfirebug.com/firebug-lite.js
There are some options to set: https://getfirebug.com/firebuglite#Options
so i included the js into my index.html and users without Firebug can now
inspect my page.
But how do we edit the html with firebug lite?

how to save the html form data into a text file?

how to save the html form data into a text file?

i have a html form layout, i want to retrieve the input data entered by
the user in this form and save it in a text file, how to do this ?
HTML:
<form method="post" action="welcome.php">
Name: <input type="text" name="name" id="name" />
Email: <input type="text" name="email" id="email" />
<input type="submit" name="submit" value="Send Form" />
</form>
i have tried this php code for welcome.php, but it is not working, can you
indicate any mistakes in this code, PHP:
<?php
$file = $_POST['name'];
$email = $_POST['email'];
$ex = ".txt";
$write = fopen("$file$ex","w");
fwrite($write,$email);
fclose($write);
$data = "/localhost/";
rename ("$file","$data$file$ex");
header('Location: http:localhost/welcome.php');
exit;
?>

Excel VBA Copying Sheets to a New Workbook and emailing the New Workbook in Outlook

Excel VBA Copying Sheets to a New Workbook and emailing the New Workbook
in Outlook

I have a segment of code that attaches the current file to an e-mail
addressed to our sales rep y is equal to the sales rep email. and to the
orders email for our company.
Instead of attaching the whole document to this email I want to copy tabs
from the document and paste them into a new document. Then send only the
new document (thereby reducing file size and hopefully changing it from a
.xlsm attachment to a .xls attachment).
If ShapesAfter > ShapesBefore Then
MsgBox "Please Repair Invalid Equipment Selection", , "Invalid
Selections _
Have Been Made"
ElseIf ShapesAfter = ShapesBefore Then
Sheets("inputs").Select
Dim y As String
y = Cells(61, 5).Value
Sheets("config").Select
Application.Dialogs(xlDialogSendMail).Show "" & y & "; " &
"orders@domainname.com"

C++ Delete a pointer using delete []?

C++ Delete a pointer using delete []?

Here is the sample code piece in C++:
Foo *ptr;
ptr = new Foo;
delete [] ptr;
Could this run into problem? What should be the correct way to delete such
a pointer and free the memory?
Thank you

Calculate the qty of items that were purchased more than once by a customer - but need to exclude the first order qty

Calculate the qty of items that were purchased more than once by a
customer - but need to exclude the first order qty

SELECT TOP 100 PERCENT soheader.custid,SOHeader.OrdNbr,
SOLine.InvtID, SOLine.Descr,SOLine.QtyOrd
FROM SOHeader INNER JOIN
SOLine ON SOHeader.OrdNbr = SOLine.OrdNbr
WHERE (SOHeader.OrdDate >= CONVERT(DATETIME, '2013-06-01 00:00:00',
102)) AND (SOHeader.OrdDate <= GETDATE()) AND (SOHeader.CustID = '69065')
ORDER BY SOLine.InvtID, SOHeader.OrdNbr
here is my sample data
69065 WO0175279 69407 Jazzy Laces White 3
69065 WO0175393 69407 Jazzy Laces White 6
69065 WO0175393 69407 Jazzy Laces White 9
Now I want to know how to get the total qty of this item ordered after the
first order. I do not want to include the qty of 3 in the first record
above. I just want to include the qty of 6 in the first reorder and the
qty 9 of the second reorder which equals the qty of 15.
69065 is the customer ID
WO##### is the order ID
69407 is the inventory ID

Flash builder: datagrid remove item - index out of bound

Flash builder: datagrid remove item - index out of bound

I have an issue wich i can't solve atm, a little helo would be much
appreciated. A local XML file is loaded into a HTTPservice and load the
data into a Datagrid. The local file cotains information about locally
stored files.
Just to be secure and sure, when the AIR app loads, i want to run through
the loaded datagrid and check if the local file exists. If it doens't
exist, i want to detele the row in the datagrid.
Doing that i get this annoying error: The supplied index is out of bounds.
I know that, deleting an element in the datagrid will result in new
indexes wich causes this error.
Thanks for your advice!
public function checkiffileislocal(event:Event):void{
var i:int;
var count:Number = (dgUserRequest.dataProvider as
ICollectionView).length;
for (i=0;i < count;i++)
{
dgUserRequest.selectedIndex = i;
if
(File.applicationStorageDirectory.resolvePath(dgUserRequest.selectedItem.id).exists
== false)
{
dgUserRequest.removeChildAt(dgUserRequest.selectedIndex);
}
}
}

@media screen not working

@media screen not working

I have difficulties with changin styles for links inside row of Foundation
Framework 4. This is my code:
<div class="row career-nav">
<div class="large-1 columns text-left"><h3><a href="{{
path('job_offer_list')}}">All</a> </h3></div>
<div class="large-2 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Students"})}}">Students</a></h3></div>
<div class="large-3 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Young
Professionals"})}}">Young Professionals</a></h3></div>
<div class="large-6 columns text-left"><h3><a href="{{
path('job_offer_listgroup',{'type':"Professionals"})}}">Professionals</a></h3></div>
</div>
and CSS settings:
.career-nav a:link{
color:#58595B;
}
@media only screen and (min-width: 48em) {
.columns.text-left a:link {color:#58595B;}
}
First I tried to solve the problem with CSS settings, created new div
class after div "row", with the name ".career-nav", but it didnt work,
then I commented that and started to write mediaqueries. But as I am new
in Foundation Framework I am not sure that I did the right query,
therefore I want to know, which method is the best one for such
adjustement and what I missed in my code. Thank you!

How to make reference/pointer in clojure?

How to make reference/pointer in clojure?

I would like to change normal behavior of code
(def a 5)
(def b a)
(def a 1)
b
5
To this behavior
(def a 5)
(*something* b a)
(def a 1)
b
1
It is just for learning purposes so please do not try any deep sense in this.

Wednesday, 18 September 2013

JAXB: how to declare a variable as class in xsd

JAXB: how to declare a variable as class in xsd

how to specify the variable type as class?
i tried with type as MyClass but in converted java class,getting the
object of MyClass. but i want to have myclass.class type

Java Enum Methods

Java Enum Methods

I would like to declare an enum Direction, that has a method that returns
the opposite direction (the following is not syntactically correct, i.e,
enums cannot be instantiated, but it illustrates my point). Is this
possible in Java?
Here is the code:
public enum Direction {
NORTH(1),
SOUTH(-1),
EAST(-2),
WEST(2);
Direction(int code){
this.code=code;
}
protected int code;
public int getCode() {
return this.code;
}
static Direction getOppositeDirection(Direction d){
return new Direction(d.getCode() * -1);
}
}

Magento Admin Create Order not showing Custom Options

Magento Admin Create Order not showing Custom Options

I have simple products with custom options in my store. They work
perfectly from the front end, but if I try to add an order from the admin
section, The custom options do not show up.
I only have this problem if the type of custom option is a dropdown, multi
select, radio buttons, or check boxes. If it is a text field, date or
anything else, it works fine.
I am assumming i need to make some changes to something in the
/www/app/design/adminhtml/default/default/template/sales/order/create
area, but no clue what i should try.

Looking a bit further, I found this
/www/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/grid.php
file controls the configure window at about line 320 which calls the
configure window up. Not sure if this helps any
/**
* Return html button which calls configure window
*
* @param $item
* @return string
*/
public function getConfigureButtonHtml($item)
{
$product = $item->getProduct();
$options = array('label' => Mage::helper('sales')->__('Configure'));
if ($product->canConfigure()) {
$options['onclick'] =
sprintf('order.showQuoteItemConfiguration(%s)', $item->getId());
} else {
$options['class'] = ' disabled';
$options['title'] = Mage::helper('sales')->__('This product does
not have any configurable options');
}
return $this->getLayout()->createBlock('adminhtml/widget_button')
->setData($options)
->toHtml();
}

Change This Method to Generic (Without Collection)

Change This Method to Generic (Without Collection)

I have the following method, which clones an object using gson to do a
deep copy. Is there a way to make this method generic, or do generics only
pertain to objects that belong to a Collection?
private Order gsonClone(Order t) {
Gson gson = new Gson();
String json = gson.toJson(t);
return gson.fromJson(json, t.getClass());
}

Left menu disappears from screen

Left menu disappears from screen

The problem I'm having is as follows:
This website I'm working on has a left menu, then content. The menu on the
left should be visible at all times. On my screen this works just fine,
but on smaller screens (<=1280pxx720px) the menu will disappear partially.
So what I would like is that either the menu stays there somehow, or some
sort of scroll bar appears (just the vertical scroll bar), so you can
scroll to the menu.
I hope there's someone out there with an answer!
The link to the website is: http://2xthuis.dev.xsbyte.net/mediation/index

Assigning an int name to selct a word from a string array

Assigning an int name to selct a word from a string array

Here's a class i made to create random names but one line keeps getting an
error (not a main class)
public class nameGenerator {
String [] namesFirst= {"Micheal","Stewart","Robbinson","Tang"};
String [] namesMiddle= {"Jordan","James","Stanly","Choo" };
String [] namesLast= {"IV","Lee","Persson"};
int a = namesFirst.length;
int b = namesMiddle.length;
int c = namesLast.length;
int x = (int) (Math.random()* a);
int y = (int) (Math.random()* b);
int z = (int) (Math.random()* c);
System.out.println(namesFirst[x] + namesMiddle[y] + namesLast[z]);
//the error is here /\
}

Getting linking errors when running C project in VS 2010 Professional on Windows

Getting linking errors when running C project in VS 2010 Professional on
Windows

I am getting errors of the following type :
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_first_attribute@12
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_first_attribute@12
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_value_free@4
1>authenticate.obj : error LNK2001: unresolved external symbol
_ldap_err2string@4
I have already added the header file folder to Project ->
Properties->C/C++->General->Additional Include Directories.
Any ideas

remove all options from select jquery but only one

remove all options from select jquery but only one

I have a select that contain this values:
<select id="lstCities" class="valid" name="City">
<option value="OSNY">OSNY</option>
<option value="dd">dd</option>
<option value="OSffNY">OSffNY</option>
<option value="ANTONY">ANTONY</option>
<option value="0">Autre...</option>
</select>
How can I delete all options but i would like to keep only
<option value="0">Autre...</option>
My problem is my list is dynamic sometimes I have 3,5,7,.... select + the
last one <option value="0">Autre...</option>

Tuesday, 17 September 2013

Handling mouse events on a QQuickItem

Handling mouse events on a QQuickItem

I have created a basic QML application which uses QQuickView for creating
a view, and has custom QQuickItems in it. I want to handle mouse events on
one such QQuickItem by reimplementing the mousepressevent(QEvent *)
method. However, when I run the application and click on the QQuickItem,
no call is made to mousepressevent(QEvent *) method.
The header file of the QQuickItem looks like this:
#include <QQuickItem>
#include <QSGGeometry>
#include <QSGFlatColorMaterial>
class TriangularGeometry: public QQuickItem
{
Q_OBJECT
public:
TriangularGeometry(QQuickItem* parent = 0);
QSGNode* updatePaintNode(QSGNode*, UpdatePaintNodeData*);
void mousePressEvent(QMouseEvent *event);
private:
QSGGeometry m_geometry;
QSGFlatColorMaterial m_material;
QColor m_color;
};
Note: I am making use of scenegraph to render the QuickItem.
This is a snippet from the cpp file:
void TriangularGeometry::mousePressEvent(QMouseEvent *event)
{
m_color = Qt::black;
update(); //changing an attribute of the qquickitem and updating the
scenegraph
}
I can handle mouse events from the application but, as per my
requirements, I need to handle it by overriding the method
mousePressEvent(QMouseEvent *event).

How do I create a prefix like jQuery does?

How do I create a prefix like jQuery does?

How do I create a prefix like the one jQuery uses? For example, in jQuery
I can use:
$(".footer").css('display', 'none');
and I'd like to enable a similar syntax, like this:
google('.footer').chrome('display', 'none');
I have searched Google for an answer, but couldn't find it.

java client send class and server execute a method from this files

java client send class and server execute a method from this files

Im working on a little project.
My client send a java file :
public class Calc {
public int add(String a, String b){
int x = Integer.parseInt(a);
int y = Integer.parseInt(b);
return x + y;
}
}
My server receive this file in his package. There is no problem for this.
What i want its to excecute 'public int add' in my server with parameter
send by client. For example: my client connects to server. He send
Calc.java and with a String add("1","2") My server receive this and
execute the function to finnaly return the result.
But i dont know how to do this... i just find "execute" but ihavent a main
method in Calc.java
Is this possible to do that ? With what method ?

Why not directly instantiate services in Android?

Why not directly instantiate services in Android?

I was wondering why the direct instantiation of a service class through a
constructor is not recommended. I couldn't find anything related to it.
Here is a very basic example:
Service class:
public class SomeRandomClass extends Service {
private final Context mContext;
public SomeRandomClass(Context context) {
this.mContext = context;
}
}
And inside main Activity/Service:
SomeRandomClass class = new SomeRandomClass(this);
class.someMethod();
The post here states that it is not a good idea to instantiate services
directly and one should use startService() instead but why? If I
instantiate my service like this I have a variable directly to the service
and I can call methods instead of having to bind to it to be able to call
methods on my service.
The only advantage I can see by using startService() is that Android keeps
track of my service but the disadvantage that I have to bind to the
Service to communicate with it. On the other hand by calling the
constructor directly I have easy communication but if my activity/service
get's killed/terminated the "sub" service is killed as well (I'm not using
a activity but other service).
Anything else why it is discouraged?

How to make an array list of objects in Java

How to make an array list of objects in Java

Having this:
static class girl{
public String age;
public String name;
public String id;
}
static girl[] girl;
Then i am unable to do this in my main function:
ResultSet r = s.executeQuery("select count(*) from children");
r.next();
girl_count=r.getInt(1);
girl = new girl[girl_count];
r = s.executeQuery("select * from children");
while(r.next()){
int i = r.getString("id");
ifgirl[i]==null)girl[i]=new girl();
girl[i].age=r.getString("age");
girl[i].name=r.getString("name");
girl[i].id=r.getString("id");
}
The above code is not working, what i would like to acheive is:
System.out.println(girl[3]);
especially this line:
girl = new girl[girl_count];
Can anyone help me correct this code ? - or find out what i'm missing here?

How can I solve for the points of an arbitrary trapezoid inscribed inside of a triangle?

How can I solve for the points of an arbitrary trapezoid inscribed inside
of a triangle?

Given the following coordinate points:

Write an algorithm (in pseudocode) to solve for x1, x2, x3, and x4.
This is what I have so far:
var y1, y2, y3, y4 = 50, 50, 75, 75;
var offset1 = tan(60) * y1;
var offset2 = tan(60) * (y2 - y1);
var x1 = 200 + offset1;
var x3 = 200 + offset1 + offset2;

Sunday, 15 September 2013

Calling nc/netcat in python with variable

Calling nc/netcat in python with variable

I am attempting to call netcat/nc from inside a loop, passing the lcv as
the last octet in the command. I am seem to be running into an issue due
to the fact that the variable is in the middle of the command. What I
would like to do is:
for i in 1 to 50
print i
nc -nvv 192.168.1.i 21 -w 15 >> local_net.txt
So far I have tried:
os.system("nc -nvv 192.168.1.",i,"21 -w 15 >> local_net.txt")
and
subprocess.call(["nv","-nvv 192.168.1.",i,"21 -w 15 >> local_net.txt")
Is there an easier way to reference an LVC from within a command executing
a system command?

Seperating intergers from a string properly (no regex)

Seperating intergers from a string properly (no regex)

I need to isolate all integers from a string, list them, and print their
sum and the # of integers. My issue is that my current code will split,
for example, 456 into 4, 5, and 6, and treat them as separate integers.
Unfortunately regex is not an option.
What i have so far:
def tally(text):
s = ','.join(x for x in text if x.isdigit())
numbers = [int(x) for x in s.split(",")]
num=len(numbers)
t=sum(numbers)
print ('There are', num, 'integers in the input summing up to', t)
..
What i need: input:'34 ch33se 34e8 3.4'
output: [34 33 34 8 3 4 ]
im getting now is [3 4 3 3 8 3 4]

Why can't the complier find this operator

Why can't the complier find this operator

I'm trying to write overloads of operator<< for specific instantiations of
standard library containers that will be stored in a boost::variant.
Here's a small example that illustrates the problem:
#include <iostream>
#include <vector>
std::ostream & operator<<( std::ostream & os, const std::vector< int > & ) {
os << "Streaming out std::vector< int >";
return os;
}
std::ostream & operator<<( std::ostream & os, const std::vector< double >
& ) {
os << "Streaming out std::vector< double >";
return os;
}
#include <boost/variant.hpp>
typedef boost::variant< std::vector< int >, std::vector< double > >
MyVariant;
int main( int argc, char * argv[] ) {
std::cout << MyVariant();
return 0;
}
Clang's first error is
boost/variant/detail/variant_io.hpp:64:14: error: invalid operands to
binary expression ('std::basic_ostream<char>' and 'const std::vector<int,
std::allocator<int>>')
out_ << operand;
~~~~ ^ ~~~~~~~
I realize that the #include <boost/variant.hpp> is in an odd place. I'm
pretty sure the problem had to do with two-phase name lookup in templates,
so I moved the #include in an attempt to implement fix #1 from the clang
documentation on lookup. Fix #2 from that documentation isn't a good
option because I believe adding my overloaded operator<< to the std
namespace would lead to undefined behavior.
Shouldn't defining my operator<<s before the #include allow the compiler
to find the definitions?

Replace empty method with method from a class where it is used

Replace empty method with method from a class where it is used

In the following scenario, I want to replace Class B's (similarly D, E, F,
etc.) method doSomething() with the method in Class A where it will be
used. How would I go about this? Made up some example, hope it gets the
message across
public class B implements GetNames{
public void getNameA(){ return "NameA"; }
public void getNameB() { return "NameB"; }
public void doStuff(){
//print names
doSomething(getNameA(), getNameB());
//print names
}
public void doSomething(String a, String b){}
}
public class A{
public void someMethod(){
B b = new B();
b.doStuff(); //*So I want it to call the method in B but somehow
replace the doSomething method in B with the doSomething method in
A
}
public void doSomething(String a, String b){
//print 'blabla' + a
//print 'blablabla' + b
//concatenate and print
}
}

Finding prominent frequencies from FFT

Finding prominent frequencies from FFT

Im trying to find the prominent peaks in an audio signal (piano recording)
using STFT. This is what Ive done so far 1. Obtain the envelope of the
time domain signal 2. Determine the peaks in the enveloped signal and use
them as note onsets 3. perform FFT for the samples between each 2
consecutive onsets.
Now that I have the FFT, I want to find the peaks corresponding to the
notes played... when i try using the findpeaks function at some points it
says its an empty matrix. Im not sure how exactly to do this so need some
help urgently...... Thank you
clear all;
clear max;
clc;
[song,FS] = wavread('C major.wav');
sound(song,FS);
P = 20000;
N=length(song); % length of song
t=0:1/FS:(N-1)/FS; % define time period
song = sum(song,2);
song=abs(song);
%windowing = hamming(32768); %Windowing function
% Plot time domain signal
figure(1);
subplot(2,1,1)
plot(t,3*song)
title('Wave File')
ylabel('Amplitude')
xlabel('Length (in seconds)')
%ylim([-1.1 1.1])
xlim([0 N/FS])
%----------------------Finding the envelope of the signal-----------------%
% Gaussian Filter
x = linspace( -1, 1, P); % create a vector of P
values between -1 and 1 inclusive
sigma = 0.335; % standard deviation used in
Gaussian formula
myFilter = -x .* exp( -(x.^2)/(2*sigma.^2)); % compute first derivative,
but leave constants out
myFilter = myFilter / sum( abs( myFilter ) ); % normalize
% Plot Gaussian Filter
subplot(2,1,2)
plot(myFilter)
title('Edge Detection Filter')
% fft convolution
myFilter = myFilter(:); % create a column vector
song(length(song)+length(myFilter)-1) = 0; %zero pad song
myFilter(length(song)) = 0; %zero pad myFilter
edges =ifft(fft(song).*fft(myFilter));
tedges=edges(P:N+P-1); % shift by P/2 so peaks line
up w/ edges
tedges=tedges/max(abs(tedges)); % normalize
%---------------------------Onset Detection-------------------------------%
% Finding peaks
maxtab = [];
mintab = [];
x = (1:length(tedges));
min1 = Inf;
max1 = -Inf;
min_pos = NaN;
max_pos = NaN;
lookformax = 1;
for i=1:length(tedges)
peak = tedges(i:i);
if peak > max1,
max1 = peak;
max_pos = x(i);
end
if peak < min1,
min1 = peak;
min_pos = x(i);
end
if lookformax
if peak < max1-0.01
maxtab = [maxtab ; max_pos max1];
min1 = peak;
min_pos = x(i);
lookformax = 0;
end
else
if peak > min1+0.05
mintab = [mintab ; min_pos min1];
max1 = peak;
max_pos = x(i);
lookformax = 1;
end
end
end
% % Plot song filtered with edge detector
figure(2)
plot(1/FS:1/FS:N/FS,tedges)
title('Song Filtered With Edge Detector 1')
xlabel('Time (s)')
ylabel('Amplitude')
ylim([-1 1.1])
xlim([0 N/FS])
hold on;
plot(maxtab(:,1)/FS, maxtab(:,2), 'ro')
plot(mintab(:,1)/FS, mintab(:,2), 'ko')
max_col = maxtab(:,1);
peaks_det = max_col/FS;
No_of_peaks = length(peaks_det);
song = detrend(song);
%---------------------------Performing FFT--------------------------------%
for i = 2:No_of_peaks
song_seg = song(max_col(i-1):max_col(i)-1);
% song_seg = song(max_col(6):max_col(7)-1);
L = length(song_seg);
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
seg_fft = fft(song_seg,NFFT);%/L;
N=5;Fst1=50;Fp1=60; Fp2=1040; Fst2=1050;
% d = fdesign.bandpass('N,Fst1,Fp1,Fp2,Fst2');
% h = design(d);
% seg_fft = filter(h, seg_fft);
% seg_fft(1) = 0;
%
f = FS/2*linspace(0,1,NFFT/2+1);
seg_fft2 = 2*abs(seg_fft(1:NFFT/2+1));
L5 = length(song_seg);
figure(1+i)
plot(f,seg_fft2)
title('Frequency spectrum of signal')
xlabel('Frequency (Hz)')
%xlim([0 2500])
ylabel('|Y(f)|')
ylim([0 300])
%[B, IX] = sort(seg_fft2)
%[points loc] = findpeaks(seg_fft);
%STFT_out(:,i) = seg_fft2;
%P=max(seg_fft2)
[points, loc] = findpeaks(seg_fft2,'THRESHOLD',20)
end

ExpandableListView throwing InflateException when setting an adapter

ExpandableListView throwing InflateException when setting an adapter

My app is throwing a android.view.InflateException when I try to set an
adapter to a ListView. The code runs fine doing the last line of onCreate
where I call setAdapter(...) but then it fails in the next line at the end
of onCreate. The code runs without errors when I do comment out the
setAdapter method.
Here are some of the logs.
09-15 17:38:20.986: W/dalvikvm(26497): threadid=1: thread exiting with
uncaught exception (group=0x40cf8438)
09-15 17:38:21.136: E/AndroidRuntime(26497): FATAL EXCEPTION: main
09-15 17:38:21.136: E/AndroidRuntime(26497):
android.view.InflateException: Binary XML file line #10: Error inflating
class <unknown>
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.createView(LayoutInflater.java:613)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.onCreateView(LayoutInflater.java:660)
09-15 17:38:21.136: E/AndroidRuntime(26497): at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
FavoritesActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
setTitle("Favorites");
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader,
listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}//END OF ONCREATE
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
//Get current data
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", PRIVATE_MODE);
Set<String> listDataHeaderSet = pref.getStringSet(LIST_DATA_HEADER,
null);
if(!(listDataHeaderSet == null)){
listDataHeader.addAll(listDataHeaderSet);
}
for(int i = 0; i < listDataHeader.size(); i++){
listDataChild.put(listDataHeader.get(i), addChildren());
}
}
/**
* Returns a list of the children in the listview
* @return
*/
private List<String> addChildren(){
List<String> locationChildren = new ArrayList<String>();
locationChildren.add("set perm start");
locationChildren.add("set start");
locationChildren.add("set perm end");
locationChildren.add("set end");
return locationChildren;
}
ExpandableListAdapter.java
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
@Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
@Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
activity_favorites.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ExpandableListView
android:id="@+id/lvExp"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</RelativeLayout>
list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:background="#000000">
<TextView
android:id="@+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="30sp"
android:textColor="@android:style/Holo.ButtonBar" />
</LinearLayout>
list_item.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="55dip"
android:orientation="vertical" >
<TextView
android:id="@+id/lblListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
/>
</LinearLayout>

Saturday, 14 September 2013

content assist/intellisence support for android devolopment using phonegap in android

content assist/intellisence support for android devolopment using phonegap
in android

i am beginning development for android using applaud phonegap plugin for
eclipse. while writing javascript code for index.js , i donot see content
assist working for me when it comes to working with javascript api
provided by cordova.js.I have include cordova.js in javascript build path
but still i donot see any content assist. How to enable content assist for
phonegap in eclipse?

character array of bitstring

character array of bitstring

for(i = 0; bitstr[i] != '\0'; i++){
if(!(bitstr[i]=='0' || bitstr[i]=='1')){
printf("Not a valid bitstring!");
exit(0);
}
else{
sum = sum*2+bitstr[i];
}
}
printf("%d", sum);
When I enter 101 for instance, it prints 339, when it should print 3 as
the answer. I am not sure what I am doing wrong. Any help would be much
appreciated.

vuforia augmented reality Unity app export to eclipse

vuforia augmented reality Unity app export to eclipse

i have create a simple app in vuforia augmented reality using unity i have
Follow here! that Allows me to Extending Unity Android Activity and Adding
Custom Views in Eclipse but when i run the project the splash screen
shows(black screen) up of unity but after a while it closes
so any one can help me here thank you

php resize image on upload

php resize image on upload

I got a form where the user is inserting some data and also uploading an
image.
To deal with the image, I got the following code:
define ("MAX_SIZE","10000");
$errors=0;
$image =$_FILES["fileField"]["name"];
$uploadedfile = $_FILES['fileField']['tmp_name'];
if($image){
$filename = stripslashes($_FILES['fileField']['name']);
$extension = strtolower(getExtension($filename));
if (($extension != "jpg") && ($extension != "jpeg") &&
($extension != "png") && ($extension != "gif")){
echo ' Unknown Image extension ';
$errors=1;
} else{
$newname = "$product_cn."."$extension";
$size=filesize($_FILES['fileField']['tmp_name']);
if ($size > MAX_SIZE*1024){
echo "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" ){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}else if($extension=="png"){
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}else{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,
$width,$height);
$filename = "../products_images/".$newname;
$filename1 = "../products_images/thumbs/".$newname;
imagejpeg($tmp,$filename,100); //file name also indicates
the folder where to save it to
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
getExtension function:
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
I've wrote some notation in the code since im not really familiar with
those functions.
for some reason, it doesn't work.
when I'm going to the folder "product_images" OR "product_images/thumbs" I
can't find any image uploaded.
Any idea what's wrong with my code? there should be 60px width image, and
25px width image.
NOTE:
variables that you don't know where they were declared such as $product_cn
were declared before that block of code which works prefectly fine(tested
it). If you still want a glance at it, feel free to ask for the code.
Thanks in advance!

Eclipse: Examine classloading problems/how to inspect deeply nested variables in debug view

Eclipse: Examine classloading problems/how to inspect deeply nested
variables in debug view

I am trying to fix some class loading problems that I ran into by
examining why class loaders fail to find the respective offending class
(here: org.eclipse.jdt.internal.compiler.env.INameEnvironment). However,
Eclipse (GGTS to be more precise) fails to show/determine the variable
contents I am interested in in this regard ("path" & "res", see attached
screenshot).
Is it possible to determine them somehow? I was unable to see them in the
variables and watch view (other variables like ucp are inspectable). I
downloaded a SDK from here https://jdk7.java.net/download.html (hoping
that it is a fast debug build) but that does not seem to make a
difference. Maybe there are other means to figure out this sort of class
loading (Class Not Found) problems?
Btw. I am using Groovy/Grails if that matters.

attachEvent is not a function - Using Module Pattern

attachEvent is not a function - Using Module Pattern

I am trying to build a JavaScript module to better understand the pattern.
I am trying to attach click events to a button with addEventListener and
attachEvent but I can not get my console.log to register.
I am also getting an error that says "TypeError: element.attachEvent is
not a function"
Here is a fiddle that I have at the moment: http://jsfiddle.net/rL5xp/
Here is the HTML:
<p>The color is <span class="js-print">green</span>.</p>
<button class="js-button">Click Here</button>
Here is the JavaScript:
var settings = [
{color : 'green'},
{color : 'blue'},
{color : 'red'}
];
var $ele = {
span : $('.js-print'),
button : $('.js-button')
};
var ChangeColor = (function(s, $element) {
var init = function() {
bindBrowserActions();
}
var bindBrowserActions = function() {
addClick($element.button, 'click', function() {
console.log('click');
});
}
var addClick = function(element, evnt, funct) {
if (element.addEventListener) {
return element.addEventListener(evnt, funct, false);
}
//addEventListener is not supported in <= IE8
else {
return element.attachEvent('on'+evnt, funct);
}
}
return {
init : init
}
})(settings, $ele);
(function() {
ChangeColor.init();
})();

firefox's strange behavior using jQuery animate method and absolute position

firefox's strange behavior using jQuery animate method and absolute position

I have a problem when I'm using jQuery's(jQuery1.9.1) animate method. Here
is my code in jsfiddle: http://jsfiddle.net/AySas/3/ I want to make the
div wider using the relative percentage, ie:
html:
<div id="h_divCenter">
<div id="h_divIETodos" >
<div id="h_divIIEodoList" class="quadContent">
<ul id="h_ulIETodoList">
<li>itemC 3</li>
</ul>
</div>
</div>
css:
#h_divCenter {
position:absolute;
top:0;
left:20px;
right:100px;
bottom:0;
margin: 5px;
background: #0FF;
}
.quadContent {
position: absolute;
top: 41px;
bottom: 2px;
padding: 1px 1% 2px 1%;
width: 98%;
}
#h_ulIETodoList,#h_ulIUTodoList,#h_ulUETodoList,#h_ulUUTodoList {
width: 100%;
height: 100%;
list-style-type: none;
overflow: auto;
}
#h_divIETodos {
position: absolute;
margin: 2px;
top: 0;
left: 0;
right: 50%;
bottom: 50%;
color: #DE3C3C;
border: 1px solid #DE3C3C;
-webkit-box-shadow: 0px 0px 10px #DE3C3C;
-moz-box-shadow: 0px 0px 10px #DE3C3C;
box-shadow: 0px 0px 10px #DE3C3C;
}
javascript:
$('#btnTest').on("click", function(){
$("#h_divIETodos").animate({
right: "+=20%"
},500);
});
And this div has a absolute position and I have set the
top,right,bottom,left properties of css. It works fine in chrome. But in
firefox, you can see the right edge of the div cannot move by "20%". Has
someone else encountered with the similar problem before? I really
appreciate your help. Many thanks!

Friday, 13 September 2013

Drop an index in postgresql

Drop an index in postgresql

I had created an index wrongly and now im trying to drop that index. Since
the datas are large for my table, dropping index is taking lot of time. Is
there any other way to drop the index quickly?
Thanks, Karthika

Passing an array of ints as an argument in C++?

Passing an array of ints as an argument in C++?

I made a function in C++ to find the length of an array. I find the sizeof
the array passed in the argument and divide it by the sizeof the variable
type. This should work but it always returns 1! Am I missing something
obvious? Or does this have to do with pointers and memory? This is my
code:
#include <iostream>
using namespace std;
int lengthOf(int arr[]);
int main() {
int x[] = {1,2,3,0,9,8};
int lenX = lengthOf(x);
cout << lenX;
return 0;
}
int lengthOf(int arr[]) {
int totalSize = sizeof arr;
cout << totalSize << endl;
int elementSize = sizeof(int);
return totalSize/elementSize;
}
Output (should be 6 instead of 1):
4
1
I am fairly new so excuse me if this is a bad question.

Does my node server need to manually end the response before the function ends?

Does my node server need to manually end the response before the function
ends?

I have a node server and I'm using express to process POST requests to it.
My question is, do I have to call response.end() before my processing
function ends or will that happen automatically?
Why I'm asking is because my server works as expected for the first few
requests, then it starts throwing "request timeout" errors, so I'm trying
to track down the issue.
I should also note that I always send something in the response using
response.send() if that makes any difference.

Distance of two Rectangle Center's Connecting Line Outside of the Rectangles

Distance of two Rectangle Center's Connecting Line Outside of the Rectangles

Well excuse me for the long title, i dont really know how to call it.

I would like you to explain me how to calculate the image's red line's
length, knowing the rectangles position and dimensions.
Context: I need this for a 2d game collision response since when the
length is negative it means not only they are intersecting but also that
length is the distance they have to repel each other to stop being
collided. If there's an easier way to do this, even better.

Calling perl script from perl

Calling perl script from perl

I have a perl script which takes 2 arguments as follows and calls
appropriate function depending on the argument. I call this script from
bash, but i want to call it from perl, is it possible?
/opt/sbin/script.pl --group="value1" --rule="value2";
Also the script exits with a return value that I would like to read.

Thursday, 12 September 2013

Move an image down

Move an image down

I am developing a webpage for images on a carousel. How can I move an
image down in a DIV, or even center it vertically?
Here is my CSS code:
.carousel .item {
height: 900px;
background-color: #777;
}
.carousel-inner > .item > img {
display: block;
margin-left: auto;
margin-right: auto
}
Here is a URL to the webpage in question to show you that the image is too
high: http://www.canninginc.co.nz/canluciddream/screenshots.html
EDIT
Ok, I have edited the code by changing the:
margin-top: 50px;
I am still after the image to be lower in the div. I can increase the top
margin, but this leaves a white background. What would be the best way to
move the image a little bit lower?

Smooth scroll for one page site

Smooth scroll for one page site

I'm working on a single page site that utilizes different section ids
instead of multiple pages. It's working fine, but I would like to have
scroll smoothly down to the section instead of just statically going to
the section on the page.
Jsfiddle: http://jsfiddle.net/schermerb/E9xuk/
#main
{
width:960px;
margin:auto;
}
#header {
margin:auto;
height:75px;
width:960px;
}
.nav {
width:auto;
float:right;
font:normal 16px Futura, sans-serif;
padding:15px;
}
.nav ul li {
list-style:none;
float:left;
margin-left:15px;
color:#000;
}
#zero {
width:auto;
}
#one {
width:auto;
}
#two {
width:auto;
}
#three {
width:auto;
}
#four {
width:auto;
}
<div id="header">
<div class="nav">
<ul> <a href="#zero"><li>About</li></a>
<a href="#one"><li>Mobile</li></a>
<a href="#two"><li>Print</li></a>
<a href="#three"><li>Web</li></a>
<a href="#four"><li>Contact</li></a>
</ul>
</div>
</div>
<div id="main">
<div id="zero">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="one">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="two">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="three">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
<div id="four">
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
<p>There are many variations of passages of Lorem Ipsum available,
but the majority have suffered alteration in some form, by
injected humour, or randomised words which don't look even
slightly believable. If you are going to use a passage of Lorem
Ipsum, you need to be sure there isn't anything embarrassing
hidden in the middle of text. All the Lorem Ipsum generators on
the Internet tend to repeat predefined chunks as necessary, making
this the first true generator on the Internet. It uses a
dictionary of over 200 Latin words, combined with a handful of
model sentence structures, to generate Lorem Ipsum which looks
reasonable. The generated Lorem Ipsum is therefore always free
from repetition, injected humour, or non-characteristic words
etc.</p>
</div>
</div>

Auto Layout with UITabBarController

Auto Layout with UITabBarController

I'm trying to shift to Auto Layout in my app, but I'm having some trouble
with my UITabBarController. Basically, I have two buttons on my home
screen, and I want them to have equal sizes, one 50 pixels from the top of
the screen and one 50 pixels from the bottom.
The issue is that when I do this:
NSArray* verticalConstraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-50-
[buttonOne(150)]" options:0 metrics:nil
views:NSDictionaryOfVariableBindings(buttonOne)];
[self.view addConstraints:verticalConstraints];
verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:
[buttonTwo(==buttonOne)]-50-|" options:0 metrics:nil
views:NSDictionaryOfVariableBindings(buttonOne, buttonTwo)];
[self.view addConstraints:verticalConstraints];
The bottom button is 50 pixels from the bottom of the view, which is 568
points tall, when the height of self.view should be the screen height
minus the tab bar's height (the navigation bar is hidden). The majority of
this padding is eaten up by the height of the tab bar.
My questions is: Why is my view controller's view not resizing so that it
doesn't count the space under my tab bar as part of its height?

How to fix UITableView on iOS 7?

How to fix UITableView on iOS 7?

UITableView draws with ragged lines on iOS 7:

How to fix it? The line between cells should be on the full width of the
screen.

Wednesday, 11 September 2013

gdb: Cast memory address to an STL object

gdb: Cast memory address to an STL object

I have a memory address that i know is an STL object. Say the address is
0x603340, and I know there is a map there
How do I display the contents of this memory as said object from gdb?
I tried this:
p ('std::map<std::string, std::string*, std::less<std::string>,
std::allocator<std::pair<std::string const, std::string*> > >'*) 0x603340
which gets me:
No symbol "std::map<std::string, std::string*, std::less<std::string>,
std::allocator<std::pair<std::string const, std::string*> > >" in current
context.
Any idea what am I doing wrong? Thanks.

How to replace all capture groups if it is generated dynamically?

How to replace all capture groups if it is generated dynamically?

Consider the following code:
function Matcher(source, search) {
var opts = search.split('');
for (var i = 0; i < opts.length; i++) {
opts[i] = '(' + opts[i] + ')';
}
opts = opts.join('.*');
var regexp = new RegExp(opts, 'gi');
source = source.replace(regexp, function () {
console.log(arguments);
return arguments[1];
});
return source;
}
You call the function passing the source as the first parameter and what
you need to match as the second one.
What i need is to replace all capture groups with a bold tag around the
coincidence.
As an example, consider the following:
var patt =
/m([a-z0-9\-_]*?)r([a-z0-9\-_]*?)i([a-z0-9\-_]*?)e([a-z0-9\-_]*\.[a-z]+)/gi;
var newFileName = fileName.replace(patt,
"<strong>m</strong>$1<strong>r</strong>$2<strong>i</strong>$3<strong>e</strong>$4");
This code is a response from Terry (thanks by the way) but the problem
here is that you need to know exactly what you want to replace, and i need
it dynamically.
Any thoughts?

Restriction of "new" keyword in Javascript

Restriction of "new" keyword in Javascript

I have this JS code:
var A = {};
A.new = function(n) { return new Array(n); }
It works well in all browsers, but when I try to obfuscate it with
obfuscator, it shows an error.
Is it a valid JS code? I looked into specification, but didn't find
anything. I know, that browsers sometimes accept syntactically wrong code,
but I want to write syntactically correct code.

Submit App for iOS 7 Now?

Submit App for iOS 7 Now?

Now that the GM is out, can we send the Binary compiled for iOS 7 only to
the App Store? Or Do we have to wait until September 18?
It seems that Review requires Apps to run iOS 7 now so I'm kinda in a
stump here. It took them 2 weeks to tell me that which is weird because up
to this point iOS 7 was still in Beta. I'm trying to communicate with them
about it though since iOS 6.1.3 is the only official iOS atm. Is this
another waiting game or can I just build against the GM release and try
submitting again?
From my recollection it should be the the Final Build that's allowed to be
submitted, correct?
Thanks!

How to change some symbols (e.t. "space") to other symbol in Bash/shell

How to change some symbols (e.t. "space") to other symbol in Bash/shell

I have some output from
ps -ef | grep apache
I need to change all spaces in that output to '@' symbol Is it possible to
use some bash script for this? Thanks

Looking for master thesis topics in neural networks

Looking for master thesis topics in neural networks

I'm looking for a thesis topic that satisfies the scope of a masters
thesis and is relevant to the current literature in Neural Networks.
I have knowledge inRestricted and Conditional Restricted Boltzmann
Machines, Extreme Learning Machines, Convolutional Neural Networks,
Recurrent Neural Networks, Multi-layer Perceptrons, Sparse Autoencoders,
Deep Belief Nets, and so on
It is difficult to choose one of these topics as they are very interesting
but broad in scope. However, I'm looking for something specific to work
on. To illustrate further my field of interest, I did some work on NLP,
time series, and object recognition research problems.
Thanks!

Checking result of EXPECT_* macros in GTest or run code when ASSERT_* failed

Checking result of EXPECT_* macros in GTest or run code when ASSERT_* failed

I have written C++ tests with GTest which basically work like this
MyData data1 = runTest(inputData);
MyData data2 = loadRegressionData();
compareMyData(data1,data2);
with
void compareMyData(MyData const& data1, MyData const& data2)
{
ASSERT_EQ(data1.count, data2.count);
//pseudo:
foreach element in data1/data2:
EXPECT_EQ(data1.items[i], data2.items[i]);
}
Now I would like to save the data1 contents to a file IFF the test fails
and I don't see an elegant solution yet.



First approach: Make compareMyData return the comparison result. This
can't work with the ASSERT_EQ which is fatal. Writing if (!EXPECT_EQ(...))
doesn't compile so the only way I found is
bool compareMyData(MyData const& data1, MyData const& data2)
{
EXPECT_EQ(data1.count, data2.count);
if (data1.count != data2.count)
return false;
//pseudo:
foreach element in data1/data2:
{
EXPECT_EQ(data1.items[i], data2.items[i]);
if (data1.items[i]!= data2.items[i])
return false;
}
}
Not very elegant :-(



Second idea: Run code when the test failed
I know I can implement ::testing::EmptyTestEventListener and get notified
if a test fails, but that doesn't give me the data I want to write to file
and it is "far away" from the place I'd like it to have. So my question
here is: Is there a way to run code at the end of a test if it failed
(e.g. catching an exception?).



To ask more general: how would you solve this?

Tuesday, 10 September 2013

list array get rondme number

list array get rondme number

I have layout infiltrator which has checkbox on every row .
I using the following code to get some text filed " Students id for each
row was checked "
and sends that to database .
but my problem when i check on student number 5 and click submit i found
that my Array-list contain number " 4 , 5 , 6 " and So on .
some time i checking on 2 then 6 i found that array has numbers ( 2
,3,4,5,6,7 ) i don't know why that array dose that .
my class code :
List<Integer> checkBoxState = new ArrayList<Integer>(50); // note here
: i want to remove this 50 but i can't
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
...........
...........
holder.checkbox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
holder.checkbox2.setChecked(false);
holder.checkbox3.setChecked(false);
holder.row.setBackgroundResource(R.drawable.green);
} else {
}
((Student) holder.checkbox.getTag()).setSelected(true);
if (((CheckBox) holder.checkbox).isChecked()) {
ViewGroup row1 = (ViewGroup) holder.checkbox
.getParent();
View view1 = ((ViewGroup) row1).getChildAt(4);
if (view1 instanceof TextView) {
holder.StudentId = (TextView) view1;
checkBoxState.add(Integer
.parseInt(holder.StudentId.getText()
.toString()));
}
}
}
});
sumbit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// getting each element from array list and send it to SOAP webservice
for (int i = 0; i < checkBoxState.size(); i++) {
Toast.makeText(context, checkBoxState.get(i).toString(),
Toast.LENGTH_SHORT).show();
try {
SoapObject request = new SoapObject(NAMESPACE,
METHOD_NAME);
HttpTransportSE androidHttpTransport = new
HttpTransportSE(
URL);
PropertyInfo pi = new PropertyInfo();
pi.setName("SID");
pi.setValue(checkBoxState.get(i));
pi.setType(Integer.class);
request.addProperty(pi);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (Exception ex) {
}
}
}
});

Remove Last instance of a character and rest of a string

Remove Last instance of a character and rest of a string

I'm sure this is easy and I know I can use split, pop and join for this.
If I have a string as follows:
foo_bar_one_two_three
Is there a cleaner way w/ regex's to return: foo_bar_one_two?
Thanks

Redirecting Console.WriteLine() to Textbox

Redirecting Console.WriteLine() to Textbox

I'm building this application in Visual Studio 2010 using C#.
Basically there are 2 files, form1.cs (which is the windows form) and
program.cs (where all the logic lies).
//form1.cs
public partial class Form1 : Form
{
//runButton_click function
}
//program.cs
class Program
{
static void Main()
{
while(blah-condition)
{
//some calculation
Console.WriteLine("Progress " + percent + "% completed.");
}
}
}
There is a Run button and a blank textbox.
When the user hits the Run button, program.cs will perform some task and
constantly printing out the progress using Console.WriteLine() onto the
console (command prompt).
Question: How can I print to the textbox on form1 instead of printing into
command prompt? I will need to print the progress constantly without any
user action.
Thanks in advance!
By the way, it doesn't have to be a textbox, it can be a label or
something else that can take text. I chose textbox because it makes more
sense to me.

How to save score on server side with different Id's?

How to save score on server side with different Id's?

I am working on android quiz game and dont know how to write code that
save score of every user at the end of game with differnt id on server
side. So that i can check the winner with highscore after some days. I
prefer to use sqlite database but dont know much about this. If someone
know about this problem plz help me with example of some code.
Thanks in advance!
Anyone have better answer than this?

How to close the ADO connection if the database connection fails while inside a transaction

How to close the ADO connection if the database connection fails while
inside a transaction

I am using ADO via C++, and let's suppose that I have begun a transaction
via ADO when the connection drops out.
I wish to abandon my database changes and close my ADO database connection
object, in order to return to another code module which can display an
error message (without leaving this module in a dodgy state).
The problem is:
1) I cannot close the database connection because the error
adErrInTransaction (0x800a0cae) is thrown (connection object cannot be
explicitly closed while in a transaction)
2) I cannot rollback the transaction because the error 0x8000ffff is
thrown (catastrophic failure, .... connection failure)
This appears to be a catch 22 situation. Had it been that the transaction
was not started then calling Close on the ADO connection succeeds, but
unfortunately with the transaction open I appear to be stuck!
Is the only solution to record the fact that it's failed within a
transaction, so that when the database connection is restored, I can
complete the rollback before attempting anything else?
This was tested with SQLServer 2008 if it's relevant, though I don't
really want a SQLServer-specific solution.

To get Date and time from Timestamp Android

To get Date and time from Timestamp Android

I want to get time and date separately from timestamp.Please help me in
these. My example of timestamp is 1378798459.
Thanks

How do I list the files having particular strings from group of directories in bash?

How do I list the files having particular strings from group of
directories in bash?

I want to list files having strings like "hello", "how" and "todo" from a
directory (which is having multiple directories). Also I want to list only
c(.c) and cpp (.cpp) files only. I have tried with grep -R but not
satisfied. Please suggest me an alternate way. Thanks in advance.

Monday, 9 September 2013

Div appear on mouse coordinates

Div appear on mouse coordinates

I've created a simple list. I'd like to make the div img appear when one
of the li is hovered. I would like to make that img div appear at the
current mouse coordinates.
I can make it all work, but not at the coordinates:
http://jsfiddle.net/tmyie/fwgRE/2/

MySQL query based on time range, group users, and sum values over a sliding window

MySQL query based on time range, group users, and sum values over a
sliding window

I want to create a new Table B based on the information from another
existing Table A. I'm wondering if MySQL has the functionality to take
into account a range of time and group column A values then only sum up
the values in a column B based on those groups in column A.
Table A stores logs of events like a journal for users. There can be
multiple events from a single user in a single day. Say hypothetically I'm
keeping track of when my users eat fruit and I want to know how many fruit
they eat in a week (7days) and also how many apples they eat.
So in Table B I want to count for each entry in Table A, the previous 7
day total # of fruit and apples.
EDIT:
I'm sorry I over simplified my given information and didn't thoroughly
think my example.
I'm initially have only Table A. I'm trying to create Table B from a query.
Assume:
User/id can log an entry multiple times in a day.
sum counts should be for id between date and date - 7 days
fruit column stands for the total # of fruit during the 7 day interval (
apples and bananas are both fruit)
The data doesn't only start at 2013-9-5. It can date back 2000 and I want
to use the 7 day sliding window over all the dates between 2000 to 2013.
The sum count is over a sliding window of 7 days
Here's an example:
Table A:
| id | date-time | apples | banana |
---------------------------------------------
| 1 | 2013-9-5 08:00:00 | 1 | 1 |
| 2 | 2013-9-5 09:00:00 | 1 | 0 |
| 1 | 2013-9-5 16:00:00 | 1 | 0 |
| 1 | 2013-9-6 08:00:00 | 0 | 1 |
| 2 | 2013-9-9 08:00:00 | 1 | 1 |
| 1 | 2013-9-11 08:00:00 | 0 | 1 |
| 1 | 2013-9-12 08:00:00 | 0 | 1 |
| 2 | 2013-9-13 08:00:00 | 1 | 1 |
note: user 1 logged 2 entries on 2013-9-5
The result after the query should be Table B.
Table B
| id | date-time | apples | fruit |
--------------------------------------------
| 1 | 2013-9-5 08:00:00 | 1 | 2 |
| 2 | 2013-9-5 09:00:00 | 1 | 1 |
| 1 | 2013-9-5 16:00:00 | 2 | 3 |
| 1 | 2013-9-6 08:00:00 | 2 | 4 |
| 2 | 2013-9-9 08:00:00 | 2 | 3 |
| 1 | 2013-9-11 08:00:00 | 2 | 5 |
| 1 | 2013-9-12 08:00:00 | 0 | 3 |
| 2 | 2013-9-13 08:00:00 | 2 | 4 |
At 2013-9-12 the sliding window moves and only includes 9-6 to 9-12.
That's why id 1 goes from a sum of 2 apples to 0 apples.

Javascript Split String at First Numeric

Javascript Split String at First Numeric

I am trying to split a UK postcode string to only include the initial
letters. For example, 'AA1 2BB' would become 'AA.'
I was thinking something like the below.
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.split([0-9])[0];
This does not actually work, but can someone help me out with the syntax?
Thanks for any help.

String.format not completely working?

String.format not completely working?

TMP = String.format("%-25s %25s", STRING1, STRING2);
Whenever I print TMP, it doesn't seem to properly print the table the way
I'm looking for
For example:
STRING1 = Test1 & Test12 STRING2 = Hello
Print:
Test1 Hello
Test12 Hello
Why is that happening?

Unexpected behavior when extracting minima using turnpoints (Pastecs package in R)

Unexpected behavior when extracting minima using turnpoints (Pastecs
package in R)

So I have some data, height.
> print(height)
V3 V4 V5 V6 V7
V8 V9 V10 V11 V12
V13 V14 V15
0.0000000 -3.1486232 39.1502937 -2.8437808 -24.7633269
-35.4022061 -36.2401943 46.4133021 -19.1868097 0.4067331
22.6768200 -38.8550971 -41.3161054
V16 V17 V18 V19 V20
33.0446273 41.4934899 19.9558741 3.3477473 0.3611974
I then apply turnpoints(), and use extract() to get what looks like a
logical vector indicating the positions of the minima.
tp = turnpoints(height)
pitpositions = extract(tp, peak = FALSE, pit = TRUE)
print(pitpositions) # [1] 0 1 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0
I would expect that height[pitpositions] would give the values of the
minima, and that height[!pitpositions] would give the values of the
non-minima.
The latter works as expected:
> height[!pitpositions]
V3 V5 V6 V7 V8
V10 V12 V13 V14 V16
V17 V18 V19
0.0000000 39.1502937 -2.8437808 -24.7633269 -35.4022061
46.4133021 0.4067331 22.6768200 -38.8550971 33.0446273
41.4934899 19.9558741 3.3477473
V20
0.3611974
But the former doesn't, and I don't know how to interpret the results:
> height[pitpositions]
V3 V3 V3 V3
0 0 0 0
So my questions are:
Why is this happening?
How can I get the result that I'm looking for (basically the opposite of
height[!pitpositions]?
Thanks!
--Davis
Edit:
To answer question number 2, I can get what I'm looking for using
height[tp$pits]. tp$pits seems to have the same information as
pitpositions, but when I print out pitpositoins I get a series of TRUE
FALSE, whereas when I print out tp$pits I get a series of 0 1. I would
have thought these were equivalent, as 0 == FALSE and 1 == TRUE.

Rendering Problems - Can't manage certificates/identifiers in apple developer center

Rendering Problems - Can't manage certificates/identifiers in apple
developer center

since a couple of days I can't manage my certificates/identifiers/.. in
the developer center. Steps to reproduce: 1. Log on to developer.apple.com
2. navigate to "Member Center" 3. click on "Manage your certificates, App
IDs, devices, and provisioning profiles"
screenshot of my browser showing "manage your certificates.."
https://discussions.apple.com/servlet/JiveServlet/showImage/2-22930732-294327/appleDevCenterIdentifiersRenderingError.jpg
This appreas in different browsers: Latest Safari, Chrome, Firefox.
I am not behind an proxy server which might block some content. Any idea
what I can do?
Thanks