Click on NSBezierPath
I'm drawing a NSBezierPath line on my NSImageView. I'm creating
NSBezierPath object, setting moveToPoint, setting lineToPoint, setting
setLineWidth: and after that in drawRect of my NSImageView subclass I'm
calling [myNSBezierPath stroke]. It all works just like I want, but I
can't seem to use containsPoint: method... I tried implementing
if([myNSBezierPath containsPoint:[theEvent locationInWindow]]{
//do something
}
in -(void)mouseUp:(NSEvent*)theEvent of my NSImageView subclass but it's
never reacting and I'm sure I'm hitting that line... Am I doing something
wrong? I just need to detect if NSBezierPath is being clicked.
Cheers.
Saturday, 31 August 2013
How to free Watch Henderson vs Pettis live streaming UFC?
How to free Watch Henderson vs Pettis live streaming UFC?
Watch UFC live Fighting Click Here To: Watch Henderson vs Pettis
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
Henderson vs Pettis Live Fight DETAILS Date : Saturday, August 31, 2013
Competition: UFC MMA Major Events live Live / Repeat:Live 10:00pm ET
Watch UFC live Fighting Click Here To: Watch Henderson vs Pettis
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
ufc-live-show.blogspot.com/
Henderson vs Pettis Live Fight DETAILS Date : Saturday, August 31, 2013
Competition: UFC MMA Major Events live Live / Repeat:Live 10:00pm ET
Simple fields Wordpress
Simple fields Wordpress
I am trying to use simple fields in my theme but I cant put it in the
theme, I tried everything.
I have made this in my new post to show up:
http://pokit.org/get/?1cbbe77cc829c2c875e11d9a58ac5866.jpg
How can I make simple fields generate this in my single.php :
simple fileds content (value)
and when i go add+ go generate another
simple fileds content (value)
Thanks !
I am trying to use simple fields in my theme but I cant put it in the
theme, I tried everything.
I have made this in my new post to show up:
http://pokit.org/get/?1cbbe77cc829c2c875e11d9a58ac5866.jpg
How can I make simple fields generate this in my single.php :
simple fileds content (value)
and when i go add+ go generate another
simple fileds content (value)
Thanks !
SQL Error: Every derived table must have its own alias
SQL Error: Every derived table must have its own alias
I know there are many questions that deal with this error but I've done
what they have asked to fix the issue I thought. Below is what I have done
but I'm still getting the error. The goal of this script is to display all
the zipcodes within a certain radius.
$zip = 94550; // "find nearby this zip code"
$radius = 15; // "search radius (miles)"
$maxresults = 10; // maximum number of results you'd like
$sql = "SELECT * FROM
(SELECT o.zipcode, o.city, o.state,
(3956 * (2 * ASIN(SQRT(
POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
COS(z.latitude*0.017453293) *
COS(o.latitude*0.017453293) *
POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
)))) AS distance
FROM zipcoords z,
zipcoords o,
zipcoords a
WHERE z.zipcode = ".$zip." AND z.zipcode = a.zipcode AND
(3956 * (2 * ASIN(SQRT(
POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
COS(z.latitude*0.017453293) *
COS(o.latitude*0.017453293) *
POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
)))) <= ".$radius."
ORDER BY distance)
ORDER BY distance ASC LIMIT 0,".$maxresults;
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
while ($ziprow = mysql_fetch_array($result)) {
$zipcode = $ziprow['zipcode'];
echo "$zipcode<br>";
}
All my columns in the database are varchar. zipcode is the primary and I
would make it INT but it doesn't allow there to be 0's at the beginning of
the zipcodes. So I changed it to varchar and it allowed it. Thanks for the
help!
I know there are many questions that deal with this error but I've done
what they have asked to fix the issue I thought. Below is what I have done
but I'm still getting the error. The goal of this script is to display all
the zipcodes within a certain radius.
$zip = 94550; // "find nearby this zip code"
$radius = 15; // "search radius (miles)"
$maxresults = 10; // maximum number of results you'd like
$sql = "SELECT * FROM
(SELECT o.zipcode, o.city, o.state,
(3956 * (2 * ASIN(SQRT(
POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
COS(z.latitude*0.017453293) *
COS(o.latitude*0.017453293) *
POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
)))) AS distance
FROM zipcoords z,
zipcoords o,
zipcoords a
WHERE z.zipcode = ".$zip." AND z.zipcode = a.zipcode AND
(3956 * (2 * ASIN(SQRT(
POWER(SIN(((z.latitude-o.latitude)*0.017453293)/2),2) +
COS(z.latitude*0.017453293) *
COS(o.latitude*0.017453293) *
POWER(SIN(((z.longitude-o.longitude)*0.017453293)/2),2)
)))) <= ".$radius."
ORDER BY distance)
ORDER BY distance ASC LIMIT 0,".$maxresults;
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
while ($ziprow = mysql_fetch_array($result)) {
$zipcode = $ziprow['zipcode'];
echo "$zipcode<br>";
}
All my columns in the database are varchar. zipcode is the primary and I
would make it INT but it doesn't allow there to be 0's at the beginning of
the zipcodes. So I changed it to varchar and it allowed it. Thanks for the
help!
passing bool array to a function
passing bool array to a function
I am passing a bool array to function and doing some modifications in the
passed array inside the function, the changes that I do in the function
are reflected in the original array that I passed to the function.For
example ,in the code below the output is 1 .Why am I getting this output ?
When we pass an integer variable for example ,the local variable maintains
its local value .How can I retain local copy of the original bool array
locally in the code below.
#include<iostream>
using namespace std;
void fun(bool A[30])
{
A[0]=true;
}
int main()
{
bool used[3];
used[0]=used[1]=used[2]=0;
fun(used);
cout<<used[0];
}
I am passing a bool array to function and doing some modifications in the
passed array inside the function, the changes that I do in the function
are reflected in the original array that I passed to the function.For
example ,in the code below the output is 1 .Why am I getting this output ?
When we pass an integer variable for example ,the local variable maintains
its local value .How can I retain local copy of the original bool array
locally in the code below.
#include<iostream>
using namespace std;
void fun(bool A[30])
{
A[0]=true;
}
int main()
{
bool used[3];
used[0]=used[1]=used[2]=0;
fun(used);
cout<<used[0];
}
How to move Primefaces-Upload-Temp-Files instead of a time intensive copy process?
How to move Primefaces-Upload-Temp-Files instead of a time intensive copy
process?
I want to upload files larger than 2 GB with Java EE with the use of
primefaces. In general that it's not that big deal, but I have a little
problem. The usually way with PrimeFaces is to upload a file, have that
UploadedFile-Object, obtain the InputStream from that and then write it to
disk.
But writing to disk large files is a time intensive task. Instead I would
like to find the uploaded file in the file system and then move it to the
folder, where I store all the files, because moving files is not wasting
time.
So, according to this question here I figured out to set
PrimeFaces-Tmp-folder and the size-limit, when files will put there. Now
every uploaded file just goes directly into that folder. The point is,
that I now have a file on disk, while the user is uploading - and not
creating it afterwards.
So far, so good. I could identify the file and just move it (although it
has a strange name). But pointing to Primefaces Userguide (Page 187), this
Tmp-Folder is just used internally. And I even would steal the contents of
the UploadedFile-Object from Primefaces. Seems not to be a clean solution
to me.
Any hints how to achieve this ?
I also saw this question. Could also be my title, but it's not what I am
looking for.
process?
I want to upload files larger than 2 GB with Java EE with the use of
primefaces. In general that it's not that big deal, but I have a little
problem. The usually way with PrimeFaces is to upload a file, have that
UploadedFile-Object, obtain the InputStream from that and then write it to
disk.
But writing to disk large files is a time intensive task. Instead I would
like to find the uploaded file in the file system and then move it to the
folder, where I store all the files, because moving files is not wasting
time.
So, according to this question here I figured out to set
PrimeFaces-Tmp-folder and the size-limit, when files will put there. Now
every uploaded file just goes directly into that folder. The point is,
that I now have a file on disk, while the user is uploading - and not
creating it afterwards.
So far, so good. I could identify the file and just move it (although it
has a strange name). But pointing to Primefaces Userguide (Page 187), this
Tmp-Folder is just used internally. And I even would steal the contents of
the UploadedFile-Object from Primefaces. Seems not to be a clean solution
to me.
Any hints how to achieve this ?
I also saw this question. Could also be my title, but it's not what I am
looking for.
Sort rows and columns of a matrix by another list with numpy
Sort rows and columns of a matrix by another list with numpy
I have a square NxN matrix. This matrix is often quite large (N around
5000), and I want to aggregate parts of this matrix to make a smaller
matrix.
Therefore, I have a list with N elements, and these elemenets denote which
rows/columns should be grouped together in the new matrix.
To make the algorithm a bit easier and faster, I want to sort the rows and
columns based on the above list.
Example:
Input 5x5 matrix:
row/col | 1 | 2 | 3 | 4 | 5 |
1 | 5 | 4 | 3 | 2 | 1 |
2 | 10 | 9 | 8 | 7 | 6 |
3 | 15 | 14 | 13 | 12 | 11 |
4 | 20 | 19 | 18 | 17 | 16 |
5 | 25 | 24 | 23 | 22 | 21 |
To be clear: the first row is [5 4 3 2 1] and the first column is [5, 10,
15, 20, 25].
The list containing the 'labels' which denote which rows and columns
should be grouped together in the new matrix:
[2 2 1 3 3]
This means the new matrix will be 3x3 (we have 3 distinct values).
The matrix with the labels:
labels 2 1 3
--------- ---- ---------
row/col | 1 | 2 | 3 | 4 | 5 |
2 | 1 | 5 | 4 | 3 | 2 | 1 |
2 | 2 | 10 | 9 | 8 | 7 | 6 |
1 | 3 | 15 | 14 | 13 | 12 | 11 |
3 | 4 | 20 | 19 | 18 | 17 | 16 |
3 | 5 | 25 | 24 | 23 | 22 | 21 |
Expected sorted matrix:
row/col | 3 | 1 | 2 | 4 | 5 |
3 | 13 |15 | 14 | 12 | 11 |
1 | 3 | 5 | 4 | 2 | 1 |
2 | 8 |10 | 9 | 7 | 6 |
4 | 18 |20 | 19 | 17 | 16 |
5 | 23 |25 | 24 | 22 | 21 |
And with this matrix I can easily sum the grouped elements to form a new
element in the 3x3 matrix.
The question: how to sort a matrix in this way with numpy? I've searched
other questions and found lexsort, record arrays and other things, but as
someone with not a lot of experience with numpy, I found it hard to
accomplish the sorting I wanted.
Thanks in advance!
I have a square NxN matrix. This matrix is often quite large (N around
5000), and I want to aggregate parts of this matrix to make a smaller
matrix.
Therefore, I have a list with N elements, and these elemenets denote which
rows/columns should be grouped together in the new matrix.
To make the algorithm a bit easier and faster, I want to sort the rows and
columns based on the above list.
Example:
Input 5x5 matrix:
row/col | 1 | 2 | 3 | 4 | 5 |
1 | 5 | 4 | 3 | 2 | 1 |
2 | 10 | 9 | 8 | 7 | 6 |
3 | 15 | 14 | 13 | 12 | 11 |
4 | 20 | 19 | 18 | 17 | 16 |
5 | 25 | 24 | 23 | 22 | 21 |
To be clear: the first row is [5 4 3 2 1] and the first column is [5, 10,
15, 20, 25].
The list containing the 'labels' which denote which rows and columns
should be grouped together in the new matrix:
[2 2 1 3 3]
This means the new matrix will be 3x3 (we have 3 distinct values).
The matrix with the labels:
labels 2 1 3
--------- ---- ---------
row/col | 1 | 2 | 3 | 4 | 5 |
2 | 1 | 5 | 4 | 3 | 2 | 1 |
2 | 2 | 10 | 9 | 8 | 7 | 6 |
1 | 3 | 15 | 14 | 13 | 12 | 11 |
3 | 4 | 20 | 19 | 18 | 17 | 16 |
3 | 5 | 25 | 24 | 23 | 22 | 21 |
Expected sorted matrix:
row/col | 3 | 1 | 2 | 4 | 5 |
3 | 13 |15 | 14 | 12 | 11 |
1 | 3 | 5 | 4 | 2 | 1 |
2 | 8 |10 | 9 | 7 | 6 |
4 | 18 |20 | 19 | 17 | 16 |
5 | 23 |25 | 24 | 22 | 21 |
And with this matrix I can easily sum the grouped elements to form a new
element in the 3x3 matrix.
The question: how to sort a matrix in this way with numpy? I've searched
other questions and found lexsort, record arrays and other things, but as
someone with not a lot of experience with numpy, I found it hard to
accomplish the sorting I wanted.
Thanks in advance!
Autovectorization alignment
Autovectorization alignment
From Intel's Compiler Autovectorization Guide there's an example related
to alignment that I don't understand. The code is
double a[N], b[N];
...
for(i = 0; i < N; i++)
a[i+1] = b[i] * 3;
And it says
If the first element of both arrays is aligned at a 16-byte boundary, then
either an unaligned load of elements from b or an unaligned store of
elements into a, has to be used after vectorization. However, the
programmer can enforce the alignment shown below, which will result in two
aligned access patterns after vectorization (assuming an 8-byte size for
doubles)
_declspec(align(16, 8)) double a[N];
_declspec(align(16, 0)) double b[N];
How to see where the misalignment comes after vectorization? Wouldn't the
alignment depend on the size of the arrays?
From Intel's Compiler Autovectorization Guide there's an example related
to alignment that I don't understand. The code is
double a[N], b[N];
...
for(i = 0; i < N; i++)
a[i+1] = b[i] * 3;
And it says
If the first element of both arrays is aligned at a 16-byte boundary, then
either an unaligned load of elements from b or an unaligned store of
elements into a, has to be used after vectorization. However, the
programmer can enforce the alignment shown below, which will result in two
aligned access patterns after vectorization (assuming an 8-byte size for
doubles)
_declspec(align(16, 8)) double a[N];
_declspec(align(16, 0)) double b[N];
How to see where the misalignment comes after vectorization? Wouldn't the
alignment depend on the size of the arrays?
Friday, 30 August 2013
how to select single column data in infragistics igniteui grid
how to select single column data in infragistics igniteui grid
how to select data of single column from a grid data. The grid data is
passed as following:
var url = "/Main/Grid?tbname="+parameter;
var jsonp = new $.ig.JSONPDataSource({
dataSource: url, paging: {
enabled: true, pageSize: 10,
type: "remote"
}
});
$("#listingGrid").igGrid("dataSourceObject", jsonp).igGrid("dataBind");
I have to retrieve data in another page from this grid and select one
column from this data.
and i have retrieved data like this
var ds = window.parent.$("#listingGrid").igGrid("option", "dataSource");
but not able to access one column data.
how to select data of single column from a grid data. The grid data is
passed as following:
var url = "/Main/Grid?tbname="+parameter;
var jsonp = new $.ig.JSONPDataSource({
dataSource: url, paging: {
enabled: true, pageSize: 10,
type: "remote"
}
});
$("#listingGrid").igGrid("dataSourceObject", jsonp).igGrid("dataBind");
I have to retrieve data in another page from this grid and select one
column from this data.
and i have retrieved data like this
var ds = window.parent.$("#listingGrid").igGrid("option", "dataSource");
but not able to access one column data.
Thursday, 29 August 2013
SQL Select - Some Rows Won't Display
SQL Select - Some Rows Won't Display
I have two tables. One of them named files and there is al list of all
files. the second table called payments, and there is in there a list of
payments for some files.
Payments:
id | fileid | {...}
1 2
2 3
3 2
Files:
id | {...}
1
2
3
I want to select all files, and join the table payments to order by count
of this table.
In this case, the first row will be file #2, because it repeats the most
in the payments table.
I tried to do it, but when I do it - not all of the rows are shown!
I think it happens because not all of the files are in the payments table.
So in this case, I think that it won't display the first row.
Thanks, and sorry for my English
P.S: I use mysql engine
** UPDATE ** My Code:
SELECT
`id`,`name`,`size`,`downloads`,`upload_date`,`server_ip`,COUNT(`uploadid`)
AS numProfits
FROM `uploads`
JOIN `profits`
ON `uploads`.`id` = `profits`.`uploadid`
WHERE `uploads`.`userid` = 1
AND `removed` = 0
ORDER BY numProfits
I have two tables. One of them named files and there is al list of all
files. the second table called payments, and there is in there a list of
payments for some files.
Payments:
id | fileid | {...}
1 2
2 3
3 2
Files:
id | {...}
1
2
3
I want to select all files, and join the table payments to order by count
of this table.
In this case, the first row will be file #2, because it repeats the most
in the payments table.
I tried to do it, but when I do it - not all of the rows are shown!
I think it happens because not all of the files are in the payments table.
So in this case, I think that it won't display the first row.
Thanks, and sorry for my English
P.S: I use mysql engine
** UPDATE ** My Code:
SELECT
`id`,`name`,`size`,`downloads`,`upload_date`,`server_ip`,COUNT(`uploadid`)
AS numProfits
FROM `uploads`
JOIN `profits`
ON `uploads`.`id` = `profits`.`uploadid`
WHERE `uploads`.`userid` = 1
AND `removed` = 0
ORDER BY numProfits
How to apply arithmetic operations to objects
How to apply arithmetic operations to objects
I am programming a vector class (in the mathematical sense), and it would
be nice if I could do
vector1 + vector2
instead of
vector1.add(vector2)
Is this possible in java? Can I assign a behaviour to an arithmetic
operation like the String class is able to? Or is this hardcoded in the
compiler?
I am programming a vector class (in the mathematical sense), and it would
be nice if I could do
vector1 + vector2
instead of
vector1.add(vector2)
Is this possible in java? Can I assign a behaviour to an arithmetic
operation like the String class is able to? Or is this hardcoded in the
compiler?
Wednesday, 28 August 2013
converting .live() to .on() or .click() functions jquery
converting .live() to .on() or .click() functions jquery
Im currently following a tutorial that uses an old version of jquery to
create and mvc with a built in todo list using ajax calls . . . now the
original code went as follows :
$(function() {
$.get('dashboard/xhrGetListings', function(o) {
for (var i = 0; i < o.length; i++)
{
$('#listInserts').append('<div>' + o[i].text + '<a class="del"
rel="'+o[i].id+'" href="#">X</a></div>');
}
$('.del').live('click', function() {
delItem = $(this);
var id = $(this).attr('rel');
$.post('dashboard/xhrDeleteListing', {'id': id}, function(o) {
delItem.parent().remove();
}, 'json');
return false;
});
}, 'json');
$('#randomInsert').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(o) {
$('#listInserts').append('<div>' + o.text + '<a class="del"
rel="'+ o.id +'" href="#">X</a></div>');
}, 'json');
return false;
});
});
when I updated the jquery version it threw a hissy fit and wouldnt work so
i looked up the error and it didnt like up the .live() function and so a
suggestion was to use .on()
and so i changed the .live into
$(document).on("click", ".del", function()
and now the code does delete from the database but doesn;t update until
the page is refreshed . . . am I missing something
Im currently following a tutorial that uses an old version of jquery to
create and mvc with a built in todo list using ajax calls . . . now the
original code went as follows :
$(function() {
$.get('dashboard/xhrGetListings', function(o) {
for (var i = 0; i < o.length; i++)
{
$('#listInserts').append('<div>' + o[i].text + '<a class="del"
rel="'+o[i].id+'" href="#">X</a></div>');
}
$('.del').live('click', function() {
delItem = $(this);
var id = $(this).attr('rel');
$.post('dashboard/xhrDeleteListing', {'id': id}, function(o) {
delItem.parent().remove();
}, 'json');
return false;
});
}, 'json');
$('#randomInsert').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(o) {
$('#listInserts').append('<div>' + o.text + '<a class="del"
rel="'+ o.id +'" href="#">X</a></div>');
}, 'json');
return false;
});
});
when I updated the jquery version it threw a hissy fit and wouldnt work so
i looked up the error and it didnt like up the .live() function and so a
suggestion was to use .on()
and so i changed the .live into
$(document).on("click", ".del", function()
and now the code does delete from the database but doesn;t update until
the page is refreshed . . . am I missing something
Refactoring same loop with different properties
Refactoring same loop with different properties
I've been refactoring some of my code, and I ran into a situation I wasn't
sure on how to refactor, I can tell it should be done, just not sure how.
Here it is:
foreach(var item in list)
{
sum = 0;
foreach(var cost in item.data)
{
sum += cost.value;
}
ListObject[count].Sum = sum;
count++
}
Then I have the exact same loop below this one, with the only difference
being the ListObject property. Like ListObject[count].Average = sum;
They are different datasources, so I can't put the Average in the sum.
How can I put this in a method that I could specify what property to use?
I've been refactoring some of my code, and I ran into a situation I wasn't
sure on how to refactor, I can tell it should be done, just not sure how.
Here it is:
foreach(var item in list)
{
sum = 0;
foreach(var cost in item.data)
{
sum += cost.value;
}
ListObject[count].Sum = sum;
count++
}
Then I have the exact same loop below this one, with the only difference
being the ListObject property. Like ListObject[count].Average = sum;
They are different datasources, so I can't put the Average in the sum.
How can I put this in a method that I could specify what property to use?
Counties are scrambled in R
Counties are scrambled in R
I'm using ggplot2 to create a population density choropleth. It's
currently working for single states, but not for multiples. It appears
that the densities of various counties (that often have the same name) get
mixed up, and sometimes even non-name matching counties are mixed up
between states. For example, "New Jersey" gives the correct densities, but
"New Jersey", "New York" tells me that the very populous Essex County in
NJ has a density <30p/mi^2. Why is this?
library(stringr)
library(ggplot2)
library(scales)
library(maps)
popdensitymap <- function(...){
path <- "U:/maps-county2011.csv"
states <- list(...)
countydata <- read.csv(path, sep=",")
countydata <- data.frame(countydata$X, countydata$Population.Density)
names(countydata) <- c("fips", "density")
data(county.fips)
cdata <- countydata
cdata$fips <- gsub("^0", "", cdata$fips)
countyinfo <- merge(cdata, county.fips, by.x="fips", by.y="fips")
countyinfo <- data.frame(countyinfo, str_split_fixed(countyinfo$polyname,
",", 2))
names(countyinfo) <- c('fips', 'density', 'polyname', 'state', 'county')
countyshapes <- map_data("county", states)
countyshapes <- merge(countyshapes, countyinfo, by.x="subregion",
by.y="county")
choropleth <- countyshapes
choropleth <- choropleth[order(choropleth$order), ]
choropleth$density_d <- cut(choropleth$density,
breaks=c(0,30,100,300,500,1000,3000,5000,100000))
state_df <- map_data("state", states)
density_d <- choropleth$density_d
choropleth <- choropleth[choropleth$state %in% tolower(states),]
p <- ggplot(choropleth, aes(long, lat, group=group))
p <- p + geom_polygon(aes(fill=density_d), colour=alpha("white", 1/2),
size=0.2)
p <- p + geom_polygon(data = state_df, colour="black", fill = NA)
p <- p + scale_fill_brewer(palette="PuRd")
p
}
To use,
popdensitymap("New Jersey")
popdensitymap("New York", "New Jersey")
Here is the csv. It is very ugly, but I do not have access to file sharing
system right now.
Here is an example of the output. As you can see, the extremely populous
Essex County by New York City is inaccurately represented.
I'm using ggplot2 to create a population density choropleth. It's
currently working for single states, but not for multiples. It appears
that the densities of various counties (that often have the same name) get
mixed up, and sometimes even non-name matching counties are mixed up
between states. For example, "New Jersey" gives the correct densities, but
"New Jersey", "New York" tells me that the very populous Essex County in
NJ has a density <30p/mi^2. Why is this?
library(stringr)
library(ggplot2)
library(scales)
library(maps)
popdensitymap <- function(...){
path <- "U:/maps-county2011.csv"
states <- list(...)
countydata <- read.csv(path, sep=",")
countydata <- data.frame(countydata$X, countydata$Population.Density)
names(countydata) <- c("fips", "density")
data(county.fips)
cdata <- countydata
cdata$fips <- gsub("^0", "", cdata$fips)
countyinfo <- merge(cdata, county.fips, by.x="fips", by.y="fips")
countyinfo <- data.frame(countyinfo, str_split_fixed(countyinfo$polyname,
",", 2))
names(countyinfo) <- c('fips', 'density', 'polyname', 'state', 'county')
countyshapes <- map_data("county", states)
countyshapes <- merge(countyshapes, countyinfo, by.x="subregion",
by.y="county")
choropleth <- countyshapes
choropleth <- choropleth[order(choropleth$order), ]
choropleth$density_d <- cut(choropleth$density,
breaks=c(0,30,100,300,500,1000,3000,5000,100000))
state_df <- map_data("state", states)
density_d <- choropleth$density_d
choropleth <- choropleth[choropleth$state %in% tolower(states),]
p <- ggplot(choropleth, aes(long, lat, group=group))
p <- p + geom_polygon(aes(fill=density_d), colour=alpha("white", 1/2),
size=0.2)
p <- p + geom_polygon(data = state_df, colour="black", fill = NA)
p <- p + scale_fill_brewer(palette="PuRd")
p
}
To use,
popdensitymap("New Jersey")
popdensitymap("New York", "New Jersey")
Here is the csv. It is very ugly, but I do not have access to file sharing
system right now.
Here is an example of the output. As you can see, the extremely populous
Essex County by New York City is inaccurately represented.
grep exact word match (-w) does not work with file paths in a text file
grep exact word match (-w) does not work with file paths in a text file
Im trying to grep for a filename with fullpath in a file which contains
something like 'ls -l' output, but it fails to match it correctly.
Line in the shell script which does the string search
pcline=`grep -w "$file1" $file2` # grep for file1 in file2 contents
if i echo the command, the output of command looks like below
grep -w run /home/rajesh/rootfs.layout
Expected
lrwxrwxrwx 1 root root 3 Aug 28 run
Actual
lrwxrwxrwx 1 root root 7 Aug 28 bin/run-parts
lrwxrwxrwx 1 root root 3 Aug 28 run
-rwxr-xr-x 1 root root 303 Aug 28 tests/aes/run.sh
-rwxr-xr-x 1 root root 445 Aug 28 tests/auto_ui/run.sh
-rwxr-xr-x 1 root root 320 Aug 28 tests/available_memory/run.sh
-rwxr-xr-x 1 root root 308 Aug 28 tests/fonts/run.sh
-rwxr-xr-x 1 root root 309 Aug 28 tests/html_config_page/run.sh
-rwxr-xr-x 1 root root 361 Aug 28 tests/ipc/run.sh
-rwxr-xr-x 1 root root 304 Aug 28 tests/JSON/run.sh
-rwxr-xr-x 1 root root 303 Aug 28 tests/log4cplus_cpp/run.sh
-rwxr-xr-x 1 root root 301 Aug 28 tests/log4cplus_c/run.sh
-rwxr-xr-x 1 root root 751 Aug 28 tests/msm_basic/run.sh
-rwxr-xr-x 1 root root 472 Aug 28 tests/res_man_dependency/run.sh
-rwxr-xr-x 1 root root 465 Aug 28 tests/res_man_ipc/run.sh
-rwxr-xr-x 1 root root 789 Aug 28 tests/res_man_multi_process/run.sh
-rwxr-xr-x 1 root root 469 Aug 28 tests/res_man_private_client/run.sh
-rwxr-xr-x 1 root root 492 Aug 28 tests/res_man_public_client/run.sh
-rwxr-xr-x 1 root root 311 Aug 28 tests/virt_mem_config/run.sh
lrwxrwxrwx 1 root root 6 Aug 28 var/run]
The trick i tried is to add a white space, which is guaranteed in my input
file, this works in console, but not when it is assigned to a variable.
grep " tests/aes/run.sh" /home/rajesh/rootfs.layout
Line in the script
pcline=`grep \"" $file1"\" $file2` # grep for file1 in file2 contents
Please let me know if i have committed any errors in this script.
Im trying to grep for a filename with fullpath in a file which contains
something like 'ls -l' output, but it fails to match it correctly.
Line in the shell script which does the string search
pcline=`grep -w "$file1" $file2` # grep for file1 in file2 contents
if i echo the command, the output of command looks like below
grep -w run /home/rajesh/rootfs.layout
Expected
lrwxrwxrwx 1 root root 3 Aug 28 run
Actual
lrwxrwxrwx 1 root root 7 Aug 28 bin/run-parts
lrwxrwxrwx 1 root root 3 Aug 28 run
-rwxr-xr-x 1 root root 303 Aug 28 tests/aes/run.sh
-rwxr-xr-x 1 root root 445 Aug 28 tests/auto_ui/run.sh
-rwxr-xr-x 1 root root 320 Aug 28 tests/available_memory/run.sh
-rwxr-xr-x 1 root root 308 Aug 28 tests/fonts/run.sh
-rwxr-xr-x 1 root root 309 Aug 28 tests/html_config_page/run.sh
-rwxr-xr-x 1 root root 361 Aug 28 tests/ipc/run.sh
-rwxr-xr-x 1 root root 304 Aug 28 tests/JSON/run.sh
-rwxr-xr-x 1 root root 303 Aug 28 tests/log4cplus_cpp/run.sh
-rwxr-xr-x 1 root root 301 Aug 28 tests/log4cplus_c/run.sh
-rwxr-xr-x 1 root root 751 Aug 28 tests/msm_basic/run.sh
-rwxr-xr-x 1 root root 472 Aug 28 tests/res_man_dependency/run.sh
-rwxr-xr-x 1 root root 465 Aug 28 tests/res_man_ipc/run.sh
-rwxr-xr-x 1 root root 789 Aug 28 tests/res_man_multi_process/run.sh
-rwxr-xr-x 1 root root 469 Aug 28 tests/res_man_private_client/run.sh
-rwxr-xr-x 1 root root 492 Aug 28 tests/res_man_public_client/run.sh
-rwxr-xr-x 1 root root 311 Aug 28 tests/virt_mem_config/run.sh
lrwxrwxrwx 1 root root 6 Aug 28 var/run]
The trick i tried is to add a white space, which is guaranteed in my input
file, this works in console, but not when it is assigned to a variable.
grep " tests/aes/run.sh" /home/rajesh/rootfs.layout
Line in the script
pcline=`grep \"" $file1"\" $file2` # grep for file1 in file2 contents
Please let me know if i have committed any errors in this script.
How can I retrieve the namespace to a string C#
How can I retrieve the namespace to a string C#
I am writing a program which needs the namespace of the program but I cant
seem to figure out how to retrieve it. I would like the end result to be
in a string.
I was able to find an MSDN page about this topic but it proved to be
unhelpful to myself.
http://msdn.microsoft.com/en-us/library/system.type.namespace.aspx
Any help would be appreciated. The program is written in C#.
EDIT: Sorry guys, this is not a console application.
I am writing a program which needs the namespace of the program but I cant
seem to figure out how to retrieve it. I would like the end result to be
in a string.
I was able to find an MSDN page about this topic but it proved to be
unhelpful to myself.
http://msdn.microsoft.com/en-us/library/system.type.namespace.aspx
Any help would be appreciated. The program is written in C#.
EDIT: Sorry guys, this is not a console application.
How do I calculate the area of a polygon given its coordinates=?iso-8859-1?Q?=3F_=96_mathematica.stackexchange.com?=
How do I calculate the area of a polygon given its coordinates? –
mathematica.stackexchange.com
I have a polygon: Polygon[{{0, 200 }, {200, 100}, {500, 300}, {100, 700}}]
How can I figure out its area? The docs page does not have any example. So
far I've reached this point with no success: …
mathematica.stackexchange.com
I have a polygon: Polygon[{{0, 200 }, {200, 100}, {500, 300}, {100, 700}}]
How can I figure out its area? The docs page does not have any example. So
far I've reached this point with no success: …
Tuesday, 27 August 2013
ubuntu 13.04 mysql 5.6 clean installation
ubuntu 13.04 mysql 5.6 clean installation
I installed Mysql 5.5 on Ubuntu and wanted to then make a clean install of
5.6 which became available. Before installing 5.6, I deleted some files
and directories for Mysql assuming that they would be reinstalled when I
did the 5.6 installation. However it appears that that was not the case,
and I had to mess around for hours trying to recreate them, which I have
done, but I still cannot login to mysql other than using "root" IE. "mysql
-u root -p".
Is it possible on Ubuntu 13.04 32-bit to completely remove every last
trace of MySql and then install it? For example, I see that the data is
located in /etc/lib/mysql. is it safe to delete that?
There are various answers to some of these question, but I don't know how
up-to-date they are, and in addition, it appears from my recent experience
that all necessary data is not installed with a new install of 5.6. I've
spent a lot of time on this and used a lot of bandwidth, so I would be
good to get a definitive answer. The latest problem that I have is "error
1045 (28000) : access denied for user 'test3'@'localhost' (using password:
yes)". After creating users and granting privileges etc., I have stopped
the server and restarted it. I don't actually want to solve that problem,
because I want to do a completely fresh installation of 5.6. However,
after a fresh installation, if I have the problem again, I'll need to know
how to fix it. The reason that I want to completely delete everything is
so that I will know that any problems encountered by me are not
attributable to a previous installation.
In addition, there is another instruction I read that says to run the
following after the installation : "sudo mysql_install_db", and "sudo
mysql_secure_installation". I don't know whether that is still valid or
necessary, or what it actually achieves. I did come across what appeared
to be a good answer here, but in light of the problems that I have
encountered, I would like to be sure that what I do will work.
I installed Mysql 5.5 on Ubuntu and wanted to then make a clean install of
5.6 which became available. Before installing 5.6, I deleted some files
and directories for Mysql assuming that they would be reinstalled when I
did the 5.6 installation. However it appears that that was not the case,
and I had to mess around for hours trying to recreate them, which I have
done, but I still cannot login to mysql other than using "root" IE. "mysql
-u root -p".
Is it possible on Ubuntu 13.04 32-bit to completely remove every last
trace of MySql and then install it? For example, I see that the data is
located in /etc/lib/mysql. is it safe to delete that?
There are various answers to some of these question, but I don't know how
up-to-date they are, and in addition, it appears from my recent experience
that all necessary data is not installed with a new install of 5.6. I've
spent a lot of time on this and used a lot of bandwidth, so I would be
good to get a definitive answer. The latest problem that I have is "error
1045 (28000) : access denied for user 'test3'@'localhost' (using password:
yes)". After creating users and granting privileges etc., I have stopped
the server and restarted it. I don't actually want to solve that problem,
because I want to do a completely fresh installation of 5.6. However,
after a fresh installation, if I have the problem again, I'll need to know
how to fix it. The reason that I want to completely delete everything is
so that I will know that any problems encountered by me are not
attributable to a previous installation.
In addition, there is another instruction I read that says to run the
following after the installation : "sudo mysql_install_db", and "sudo
mysql_secure_installation". I don't know whether that is still valid or
necessary, or what it actually achieves. I did come across what appeared
to be a good answer here, but in light of the problems that I have
encountered, I would like to be sure that what I do will work.
R creating list
R creating list
what does Trainsetb over here signify? I don't think it is the list name,
but haven't been able to understand what it specifies or what is it's
purpose.
> z=as.integer(4,5, 6)
> class(z)
[1] "integer"
> a=list(z)
> class(a)
[1] "list"
> b=list(Trainsetb = z)
> class(b)
[1] "list"
> names(b)
[1] "Trainsetb"
> names(a)
NULL
> a
[[1]]
[1] 4
> b
$Trainsetb
[1] 4
> b$Trainsetb
[1] 4
> Trainsetb
Error: object 'Trainsetb' not found
I am learning data mining using the book. I am using caret package train
function. Within train function there is the trainControl argument and it
is defined as below:
ctrl <- trainControl(method = "LGOCV",
summaryFunction = twoClassSummary,
classProbs = TRUE,
index = list(TrainSet = pre2008),
savePredictions = TRUE)
I want to know why the author hasn't defined index as index = list(pre2008).
what does Trainsetb over here signify? I don't think it is the list name,
but haven't been able to understand what it specifies or what is it's
purpose.
> z=as.integer(4,5, 6)
> class(z)
[1] "integer"
> a=list(z)
> class(a)
[1] "list"
> b=list(Trainsetb = z)
> class(b)
[1] "list"
> names(b)
[1] "Trainsetb"
> names(a)
NULL
> a
[[1]]
[1] 4
> b
$Trainsetb
[1] 4
> b$Trainsetb
[1] 4
> Trainsetb
Error: object 'Trainsetb' not found
I am learning data mining using the book. I am using caret package train
function. Within train function there is the trainControl argument and it
is defined as below:
ctrl <- trainControl(method = "LGOCV",
summaryFunction = twoClassSummary,
classProbs = TRUE,
index = list(TrainSet = pre2008),
savePredictions = TRUE)
I want to know why the author hasn't defined index as index = list(pre2008).
Aligning div in responsive design
Aligning div in responsive design
I am trying to align the div when the browser is reduced to 480px,
I have the below code in html,
<body>
<div id="container">
<div id="leftcol"> left left left left left left left left left left
left left left </div>
<div id="rightcol"> right right right right right right right right
right right right right </div>
<div id="midcol"> mid mid mid mid mid mid mid mid mid mid mid mid mid
mid mid </div>
</div>
</body>
in css,
/* CSS Document */
*{
margin:0;
padding:0;
}
#container {
width: 100%;
height: 600px;
background-color:#FFFF00;
}
#leftcol {
float:left;
width:20%;
height: 600px;
background-color:#FF0000;
}
#rightcol {
float:right;
width:20%;
height: 600px;
background-color:#0099FF;
}
#midcol {
height: 600px;
background-color:#339900;
}
@media screen and (max-width:480px) {
#container {
width: 100%;
height: auto;
background-color:#FFFF00;
}
#leftcol {
width:100%;
height: auto;
background-color:#FF0000;
}
#rightcol {
width:100%;
height: auto;
background-color:#0099FF;
}
#midcol {
height: auto;
background-color:#339900;
}
}
![enter image description here][1]
http://jsfiddle.net/sztQR/
In the image, i have left right and middle. What i want is, middle left
and right
Is this possible?
I am trying to align the div when the browser is reduced to 480px,
I have the below code in html,
<body>
<div id="container">
<div id="leftcol"> left left left left left left left left left left
left left left </div>
<div id="rightcol"> right right right right right right right right
right right right right </div>
<div id="midcol"> mid mid mid mid mid mid mid mid mid mid mid mid mid
mid mid </div>
</div>
</body>
in css,
/* CSS Document */
*{
margin:0;
padding:0;
}
#container {
width: 100%;
height: 600px;
background-color:#FFFF00;
}
#leftcol {
float:left;
width:20%;
height: 600px;
background-color:#FF0000;
}
#rightcol {
float:right;
width:20%;
height: 600px;
background-color:#0099FF;
}
#midcol {
height: 600px;
background-color:#339900;
}
@media screen and (max-width:480px) {
#container {
width: 100%;
height: auto;
background-color:#FFFF00;
}
#leftcol {
width:100%;
height: auto;
background-color:#FF0000;
}
#rightcol {
width:100%;
height: auto;
background-color:#0099FF;
}
#midcol {
height: auto;
background-color:#339900;
}
}
![enter image description here][1]
http://jsfiddle.net/sztQR/
In the image, i have left right and middle. What i want is, middle left
and right
Is this possible?
How to get Paypal return URL parameters via POST
How to get Paypal return URL parameters via POST
I successfully get my token after using cURL to post the payment details
to: https://api-3t.sandbox.paypal.com/nvp
Then I redirect the user to complete the payment on:
https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=xxx.
But when when the user finishes the payment and is redirected to my
success URL, the parameters are sent back in the URL (using GET method)
and this screws my application logic a bit. I need these parameters to be
POSTed back to my success URL.
I understand that when you send the initial parameters via a hidden form
(as opposed to using cURL), you can add the rm=2 hidden parameter to
specify that the result will be sent back using POST method after a
successful payment. Nevertheless, I cant find any equivalent to the
parameter "rm" in the NVP API for express checkout.
I successfully get my token after using cURL to post the payment details
to: https://api-3t.sandbox.paypal.com/nvp
Then I redirect the user to complete the payment on:
https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=xxx.
But when when the user finishes the payment and is redirected to my
success URL, the parameters are sent back in the URL (using GET method)
and this screws my application logic a bit. I need these parameters to be
POSTed back to my success URL.
I understand that when you send the initial parameters via a hidden form
(as opposed to using cURL), you can add the rm=2 hidden parameter to
specify that the result will be sent back using POST method after a
successful payment. Nevertheless, I cant find any equivalent to the
parameter "rm" in the NVP API for express checkout.
Monday, 26 August 2013
Has anyone figured how how the create a user with the Admin Directory api?
Has anyone figured how how the create a user with the Admin Directory api?
I've been trying a few combinations but can't seem to come up with
something that works. I have a feeling I'm just not setting up the request
correctly. The following bit of code is known to work. I use it to set up
the client that is able to query all the users.
client = Google::APIClient.new(:application_name => "myapp", :version =>
"v0.0.0")
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => "https://www.googleapis.com/auth/admin.directory.user",
:issuer => issuer,
:signing_key => key,
:person => user + "@" + domain)
client.authorization.fetch_access_token!
api = client.discovered_api("admin", "directory_v1")
When I try to use the following code
parameters = Hash.new
parameters["password"] = "ThisIsAPassword"
parameters["primaryEmail"] = "tstacct2@" + domain
parameters["name"] = {"givenName" => "Test", "familyName" => "Account2"}
parameters[:api_method] = api.users.insert
response = client.execute(parameters)
I always get back the same error "code": 400, "message": "Invalid
Given/Family Name: FamilyName"
I've observed a few things while looking into this particular API. If I
print out the parameters for both the list and the insert functions e.g
puts "--- Users List ---"
puts api.users.list.parameters
puts "--- Users Insert ---"
puts api.users.insert.parameters
Only the List actually displays the parameters
--- Users List ---
customer
domain
maxResults
orderBy
pageToken
query
showDeleted
sortOrder
--- Users Insert ---
This leaves me wondering if the ruby client is unable to retrieve the api
and therefore unable to submit the request correctly or if I'm just doing
something completely wrong.
I'd appreciate any idea's or direction that might help set me on the right
path.
Thank you,
James
I've been trying a few combinations but can't seem to come up with
something that works. I have a feeling I'm just not setting up the request
correctly. The following bit of code is known to work. I use it to set up
the client that is able to query all the users.
client = Google::APIClient.new(:application_name => "myapp", :version =>
"v0.0.0")
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => "https://www.googleapis.com/auth/admin.directory.user",
:issuer => issuer,
:signing_key => key,
:person => user + "@" + domain)
client.authorization.fetch_access_token!
api = client.discovered_api("admin", "directory_v1")
When I try to use the following code
parameters = Hash.new
parameters["password"] = "ThisIsAPassword"
parameters["primaryEmail"] = "tstacct2@" + domain
parameters["name"] = {"givenName" => "Test", "familyName" => "Account2"}
parameters[:api_method] = api.users.insert
response = client.execute(parameters)
I always get back the same error "code": 400, "message": "Invalid
Given/Family Name: FamilyName"
I've observed a few things while looking into this particular API. If I
print out the parameters for both the list and the insert functions e.g
puts "--- Users List ---"
puts api.users.list.parameters
puts "--- Users Insert ---"
puts api.users.insert.parameters
Only the List actually displays the parameters
--- Users List ---
customer
domain
maxResults
orderBy
pageToken
query
showDeleted
sortOrder
--- Users Insert ---
This leaves me wondering if the ruby client is unable to retrieve the api
and therefore unable to submit the request correctly or if I'm just doing
something completely wrong.
I'd appreciate any idea's or direction that might help set me on the right
path.
Thank you,
James
Updating ArrayList with values from SQLite
Updating ArrayList with values from SQLite
Sorry if this question gets asked a lot, but I'm stumped and cannot find
anything that works for my issue. I am still new to Java programming, so
attempted to merge a tutorial into my existing project. I've got most of
it working, but I'm stumped on how to take string data from my SQLite
database and parse it into the ArrayList. So here's my code:
SQLView.java
//imports omitted
public class SQLView extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
ArrayList<SearchResults> searchResults = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResults));
// OnClickListener Omitted
}
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
sr1.setID("1");
sr1.setName("1");
sr1.setYear("1");
results.add(sr1);
sr1 = new SearchResults();
sr1.setID("2");
sr1.setName("2");
sr1.setYear("2");
results.add(sr1);
sr1 = new SearchResults();
sr1.setID("3");
sr1.setName("3");
sr1.setYear("3");
results.add(sr1);
return results;
}
}
MyCustomBaseAdapter.java
//imports omitted
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults>
results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtID = (TextView) convertView.findViewById(R.id.id);
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtYear = (TextView) convertView.findViewById(R.id.year);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtID.setText(searchArrayList.get(position).getID());
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtYear.setText(searchArrayList.get(position).getYear());
return convertView;
}
static class ViewHolder {
TextView txtID;
TextView txtName;
TextView txtYear;
}
}
SearchResults.java
//imports omitted
public class SearchResults {
private String id = "";
private String name = "";
private String year = "";
public void setID(String id) {
this.id = id;
}
public String getID() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setYear(String year) {
this.year = year;
}
public String getYear() {
return year;
}
}
And finally this is what I'm working with from my database:
MYDB db = new MYDB(this);
db.open();
String dataID = db.getDataID();
String dataName = db.getDataName();
String dataYear = db.getDataYear();
db.close();
When I try changing SQLView.java to use the following, I get no errors but
just a blank holder...
sr1 = new SearchResults();
sr1.setID(dataID);
sr1.setName(dataName);
sr1.setYear(dataYear);
results.add(sr1);
Sorry if this question gets asked a lot, but I'm stumped and cannot find
anything that works for my issue. I am still new to Java programming, so
attempted to merge a tutorial into my existing project. I've got most of
it working, but I'm stumped on how to take string data from my SQLite
database and parse it into the ArrayList. So here's my code:
SQLView.java
//imports omitted
public class SQLView extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
ArrayList<SearchResults> searchResults = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResults));
// OnClickListener Omitted
}
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
sr1.setID("1");
sr1.setName("1");
sr1.setYear("1");
results.add(sr1);
sr1 = new SearchResults();
sr1.setID("2");
sr1.setName("2");
sr1.setYear("2");
results.add(sr1);
sr1 = new SearchResults();
sr1.setID("3");
sr1.setName("3");
sr1.setYear("3");
results.add(sr1);
return results;
}
}
MyCustomBaseAdapter.java
//imports omitted
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults>
results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtID = (TextView) convertView.findViewById(R.id.id);
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtYear = (TextView) convertView.findViewById(R.id.year);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtID.setText(searchArrayList.get(position).getID());
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtYear.setText(searchArrayList.get(position).getYear());
return convertView;
}
static class ViewHolder {
TextView txtID;
TextView txtName;
TextView txtYear;
}
}
SearchResults.java
//imports omitted
public class SearchResults {
private String id = "";
private String name = "";
private String year = "";
public void setID(String id) {
this.id = id;
}
public String getID() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setYear(String year) {
this.year = year;
}
public String getYear() {
return year;
}
}
And finally this is what I'm working with from my database:
MYDB db = new MYDB(this);
db.open();
String dataID = db.getDataID();
String dataName = db.getDataName();
String dataYear = db.getDataYear();
db.close();
When I try changing SQLView.java to use the following, I get no errors but
just a blank holder...
sr1 = new SearchResults();
sr1.setID(dataID);
sr1.setName(dataName);
sr1.setYear(dataYear);
results.add(sr1);
Display picture only if textbox is blank
Display picture only if textbox is blank
My Program: I have a textBox and a pictureBox (which contains an error
picture, placed exactly next to textBox) in userControl in my program.
My Goal: I want to HIDE the picture in the pictureBox only if the user
types text in the textBox. If the textBox is left blank, the image in the
pictureBox should be shown.
I tried using errorProvider but I was totally lost because I am a newbie
in C# Programming. There are many errorProvider examples online but all
examples are using Form and I am trying to do it in UserControl. So, I
thought I should try this method. Please can you help me with the code?
Thanks for your help in advance.
My Program: I have a textBox and a pictureBox (which contains an error
picture, placed exactly next to textBox) in userControl in my program.
My Goal: I want to HIDE the picture in the pictureBox only if the user
types text in the textBox. If the textBox is left blank, the image in the
pictureBox should be shown.
I tried using errorProvider but I was totally lost because I am a newbie
in C# Programming. There are many errorProvider examples online but all
examples are using Form and I am trying to do it in UserControl. So, I
thought I should try this method. Please can you help me with the code?
Thanks for your help in advance.
Updating TextView In One Function
Updating TextView In One Function
I want to do something very simple. I have a progress-bar and a textView
that I want to dynamically update on a button click, but more than once
during the function call.
I want it to change to 'A' then wait a second, then switch to 'B' ... for
example.
I understand that my function blocks the UI/main thread, which is what if
I setText() ten times, I only see the tenth text appear when the function
completes.
So I've tried handlers/runnables in the UI thread, invalidating (and
postInvalidating) to encourage refreshing and runOnUiThread() and they all
just update when they've finished running leaving me only with the final
state.
public void requestPoint(View v) {
textProgress.setText("Requesting A Point");
waiting(200);
progressBar.setProgress(5);
textProgress.setText("Request Received!");
waiting(500);
....
}
Where waiting() is a function I made that waits without actually affecting
the thread.
I think I've turned nearly all the similar question links purple and
wasted way too much time on this simple thing (although I did learn a lot
about threading on Android) but I feel I must be missing something
crucial, this doesn't seem like that hard of task.
Any help would be greatly appreciated.
I want to do something very simple. I have a progress-bar and a textView
that I want to dynamically update on a button click, but more than once
during the function call.
I want it to change to 'A' then wait a second, then switch to 'B' ... for
example.
I understand that my function blocks the UI/main thread, which is what if
I setText() ten times, I only see the tenth text appear when the function
completes.
So I've tried handlers/runnables in the UI thread, invalidating (and
postInvalidating) to encourage refreshing and runOnUiThread() and they all
just update when they've finished running leaving me only with the final
state.
public void requestPoint(View v) {
textProgress.setText("Requesting A Point");
waiting(200);
progressBar.setProgress(5);
textProgress.setText("Request Received!");
waiting(500);
....
}
Where waiting() is a function I made that waits without actually affecting
the thread.
I think I've turned nearly all the similar question links purple and
wasted way too much time on this simple thing (although I did learn a lot
about threading on Android) but I feel I must be missing something
crucial, this doesn't seem like that hard of task.
Any help would be greatly appreciated.
How does energy loss work in Redstone Energy Conduits gaming.stackexchange.com
How does energy loss work in Redstone Energy Conduits –
gaming.stackexchange.com
In this situation you see I have my conduits linearly running along the
line of engines. It says on the wiki that the conduits have a 5% energy
loss, implemented at points where energy enters the …
gaming.stackexchange.com
In this situation you see I have my conduits linearly running along the
line of engines. It says on the wiki that the conduits have a 5% energy
loss, implemented at points where energy enters the …
C# + NUnit - Unit testing methods working on long binary arguments
C# + NUnit - Unit testing methods working on long binary arguments
I would like to write unit tests for some classes with methods having byte
array arguments. There are about 100 methods in total, and the array size
ranges from 5-10 to a few 100 bytes. How should I generate and store the
test arrays?
Should I generate them manually or by some generator code (which should be
unit tested, too)?
Should I generate them in memory during the test, or should I generate
them in advance and store them somewhere?
In the latter case, should I store them in files (even if unit tests
shouldn't touch the file system), or should I store them inside the test
code itself (for example, in strings in hexadecimal format, like this: "47
08 00 14 etc.")?
I started to create them manually and store them in the test code in hex
strings. I worked a lot with such binary strings, so I can read them
relatively easily ("I don't even see the code. All I see is blonde,
brunette, redhead.") The problem is, this approach is slow, and I think
using an automatic generator would result in more maintainable tests. But
how should I test that the output of the generator is correct? Sounds like
Catch-22...
I would like to write unit tests for some classes with methods having byte
array arguments. There are about 100 methods in total, and the array size
ranges from 5-10 to a few 100 bytes. How should I generate and store the
test arrays?
Should I generate them manually or by some generator code (which should be
unit tested, too)?
Should I generate them in memory during the test, or should I generate
them in advance and store them somewhere?
In the latter case, should I store them in files (even if unit tests
shouldn't touch the file system), or should I store them inside the test
code itself (for example, in strings in hexadecimal format, like this: "47
08 00 14 etc.")?
I started to create them manually and store them in the test code in hex
strings. I worked a lot with such binary strings, so I can read them
relatively easily ("I don't even see the code. All I see is blonde,
brunette, redhead.") The problem is, this approach is slow, and I think
using an automatic generator would result in more maintainable tests. But
how should I test that the output of the generator is correct? Sounds like
Catch-22...
Sunday, 25 August 2013
CSs gifting units?
CSs gifting units?
Earlier in the game, I received a few units from allied CS Valetta. The
odd part is that these units were H'wachas, a Korea only unit. There was
no Korea in this game to gift it to them either. How does this work, and
how did it happen?
Earlier in the game, I received a few units from allied CS Valetta. The
odd part is that these units were H'wachas, a Korea only unit. There was
no Korea in this game to gift it to them either. How does this work, and
how did it happen?
PUT requests and variables for API in PHP
PUT requests and variables for API in PHP
I'm currently building an API, and I want to separate updating (Which I am
using POST for) from creation (Which I want to use PUT for). This might
seem like a dumb question, but how do I retrieve variables sent through
PUT? There is no $_PUT array in PHP. I'm trying to send data with WFetch
this way:
Content-Type: application/x-www-form-urlencoded\r\n
\r\n
Name=Test\r\n
I've tried to look up how to use PUT, but I can't seem to figure it out.
I'm currently building an API, and I want to separate updating (Which I am
using POST for) from creation (Which I want to use PUT for). This might
seem like a dumb question, but how do I retrieve variables sent through
PUT? There is no $_PUT array in PHP. I'm trying to send data with WFetch
this way:
Content-Type: application/x-www-form-urlencoded\r\n
\r\n
Name=Test\r\n
I've tried to look up how to use PUT, but I can't seem to figure it out.
Xorg - ignore first click event when resuming from Screen Blanking
Xorg - ignore first click event when resuming from Screen Blanking
Is it possible to somehow configure xorg to ignore the first mouse click
when screen blanking is enabled ??
The reason is I have a touch screen in an embedded arch linux application
which remains active during screen blanking, and the first touch of a user
should disable screen blanking and the click / touch event itself needs to
be ignored as the user has no idea what button they are pressing since the
screen is blank ?
Or any clever hack / work around methods ??
Is it possible to somehow configure xorg to ignore the first mouse click
when screen blanking is enabled ??
The reason is I have a touch screen in an embedded arch linux application
which remains active during screen blanking, and the first touch of a user
should disable screen blanking and the click / touch event itself needs to
be ignored as the user has no idea what button they are pressing since the
screen is blank ?
Or any clever hack / work around methods ??
Add line breaks when changing array to json data
Add line breaks when changing array to json data
I want to convert my mutable array to JSON data. I have all ready done
this using
NSData *data = [NSJSONSerialization dataWithObject:myMutableArray
option:kNilOptions error:&error];
Later, I write the JSON to a .txt file, but it came as a clump of text
instead of each object in my array having a separate line when I emailed
it to myself and opened it. I added objects to my array by using the
following code:
for (int i=0; i < anotherArray; i++) {
NSSrring *s = [anotherArray objectAtIndex:i];
if ([s isEqualToString:anotherString] {
[myMutableArray addObject:s];
[myMutableArray addObject:@" "];
}}
I added the extra space to the array because I wanted the text file format
to be similar to this:
aString
anotherString
. . . .
what would I add to my array or JSON data to add the line breaks after
every line?
I want to convert my mutable array to JSON data. I have all ready done
this using
NSData *data = [NSJSONSerialization dataWithObject:myMutableArray
option:kNilOptions error:&error];
Later, I write the JSON to a .txt file, but it came as a clump of text
instead of each object in my array having a separate line when I emailed
it to myself and opened it. I added objects to my array by using the
following code:
for (int i=0; i < anotherArray; i++) {
NSSrring *s = [anotherArray objectAtIndex:i];
if ([s isEqualToString:anotherString] {
[myMutableArray addObject:s];
[myMutableArray addObject:@" "];
}}
I added the extra space to the array because I wanted the text file format
to be similar to this:
aString
anotherString
. . . .
what would I add to my array or JSON data to add the line breaks after
every line?
Which SIP stack/library is best for iOS? [on hold]
Which SIP stack/library is best for iOS? [on hold]
I am writing a VoIP/SIP dialer client for iPhone. But i am very confused
about which SIP stack should i use. I have searched all over the internet
and found about 6-7 SIP library which can be used for iOS. I have got the
following...
PJSIP(Most used. Open source C-based SIP stack. Could be good if we want
to go low-level)
idoubs (Not bad, updating continuously)
siphon (Not bad but hasn't been updated for a long time. Seems to be the
default option. Objective-c codebase with existing UI, It uses PJSIP
stack.)
miumiu (appears less mature than Siphon.) https://github.com/pzion/miumiu
linphone (Another Linux-oriented option. Rough UI but the audio engine
seems good.)
sofia-sip (Couldn't understand.)
So can someone please suggest me about which SIP library would be best for
iOS ? I will use G729 codec.
I am writing a VoIP/SIP dialer client for iPhone. But i am very confused
about which SIP stack should i use. I have searched all over the internet
and found about 6-7 SIP library which can be used for iOS. I have got the
following...
PJSIP(Most used. Open source C-based SIP stack. Could be good if we want
to go low-level)
idoubs (Not bad, updating continuously)
siphon (Not bad but hasn't been updated for a long time. Seems to be the
default option. Objective-c codebase with existing UI, It uses PJSIP
stack.)
miumiu (appears less mature than Siphon.) https://github.com/pzion/miumiu
linphone (Another Linux-oriented option. Rough UI but the audio engine
seems good.)
sofia-sip (Couldn't understand.)
So can someone please suggest me about which SIP library would be best for
iOS ? I will use G729 codec.
Saturday, 24 August 2013
What is the experimental reason to believe in a Unified Theory?
What is the experimental reason to believe in a Unified Theory?
Is there any experimental findings on behalf of the belief that all forces
can be unified to a single force? Or the idea has it's inspiration from
kind of thought experiment or philosophical belief.
Is there any experimental findings on behalf of the belief that all forces
can be unified to a single force? Or the idea has it's inspiration from
kind of thought experiment or philosophical belief.
postfix for loop in perl is not working as expected
postfix for loop in perl is not working as expected
The following line works perfectly
for(my $i=0; $i < ($max_size - $curr_size) ; $i++){
push (@{$_}, 0);
}
But this one doesn't.
push (@{$_}, 0) for (1 .. ($max_size - $curr_size));
It gives me an error message like this:
Can't use string ("1") as an ARRAY ref while "strict refs" in use at
coordReadEasy.pl line 124, <DATA> line 16.
Why? how can I solve this?
The following line works perfectly
for(my $i=0; $i < ($max_size - $curr_size) ; $i++){
push (@{$_}, 0);
}
But this one doesn't.
push (@{$_}, 0) for (1 .. ($max_size - $curr_size));
It gives me an error message like this:
Can't use string ("1") as an ARRAY ref while "strict refs" in use at
coordReadEasy.pl line 124, <DATA> line 16.
Why? how can I solve this?
Javascript : custom text on Confirm Ok Cancel button
Javascript : custom text on Confirm Ok Cancel button
I have a validation where i want to show 'Continue' and 'Return' instead
of OK and Cancel but I am not able to find accurate solution, can anyone
help me on this.
<input type="button" name="submit" value="Submit" style="font:10px;">
<xsl:attribute name="onclick">
javascript:
var amount =
document.getElementById('txtboxAdjustment14').value.trim();
if(amount == 0)
{
var cont =confirm("Have you considered amount?")
if (cont == true)
{
somemethod();
}
else if(cont == false)
{
return false;
}
}
else
{
somemethod();
}
</xsl:attribute>
</input>
I have a validation where i want to show 'Continue' and 'Return' instead
of OK and Cancel but I am not able to find accurate solution, can anyone
help me on this.
<input type="button" name="submit" value="Submit" style="font:10px;">
<xsl:attribute name="onclick">
javascript:
var amount =
document.getElementById('txtboxAdjustment14').value.trim();
if(amount == 0)
{
var cont =confirm("Have you considered amount?")
if (cont == true)
{
somemethod();
}
else if(cont == false)
{
return false;
}
}
else
{
somemethod();
}
</xsl:attribute>
</input>
How to copy styles of a cell into another one using Google Spreadsheet API
How to copy styles of a cell into another one using Google Spreadsheet API
I'm trying to fill data to a spreadsheet using Google Spreadsheet API.
What I do not understand is how can I copy styles from a row (e.g. the
first one) to the cells created by my software.
I'm unable to find a way...
I'm trying to fill data to a spreadsheet using Google Spreadsheet API.
What I do not understand is how can I copy styles from a row (e.g. the
first one) to the cells created by my software.
I'm unable to find a way...
Php cannot write to file in android [on hold]
Php cannot write to file in android [on hold]
I have developed a webserver which support php,mysql it runs fine but the
when i run a php script that writes text to a text file it can not write
to the file but the file size is diferrent but i cannot see the text.Do i
have to make a permission in it or any thing wrong with the conf file
Please help me..
I use fopen to open the text file and apped it:
fopen("log.txt","a");
I have developed a webserver which support php,mysql it runs fine but the
when i run a php script that writes text to a text file it can not write
to the file but the file size is diferrent but i cannot see the text.Do i
have to make a permission in it or any thing wrong with the conf file
Please help me..
I use fopen to open the text file and apped it:
fopen("log.txt","a");
Getting mysql syntax error using codeigniter LIKE active record
Getting mysql syntax error using codeigniter LIKE active record
this is my code
return $this->db
->select('organization')
->like('title',$this->db->escape_str($query))
->or_like('description',$this->db->escape_str($query))
->get('shop_search')
->num_rows();
every thing works well untill there is a ' and NOT " in the $query.
the error is : $query="d'"
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near '%' OR
`description` LIKE '%d\\\\\\'%'' at line 3
SELECT `organization` FROM `default_shop_search` WHERE `title` LIKE
'%d\\\\\\'%' OR `description` LIKE '%d\\\\\\'%'
What am I missing here?
UPDATE:
dump of passed query:
Debug #1 of 1: string(2) "d'"
this is my code
return $this->db
->select('organization')
->like('title',$this->db->escape_str($query))
->or_like('description',$this->db->escape_str($query))
->get('shop_search')
->num_rows();
every thing works well untill there is a ' and NOT " in the $query.
the error is : $query="d'"
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near '%' OR
`description` LIKE '%d\\\\\\'%'' at line 3
SELECT `organization` FROM `default_shop_search` WHERE `title` LIKE
'%d\\\\\\'%' OR `description` LIKE '%d\\\\\\'%'
What am I missing here?
UPDATE:
dump of passed query:
Debug #1 of 1: string(2) "d'"
Array of length bracket notation
Array of length bracket notation
If I want to make an array that is say of length 3 using bracket notation,
should I just write: var foo = [,,];
I was more used to writing: var foo = new Array(3);
I noticed that if I removed one , that my code still worked which is
surprising because I am accessing all 3 elements after assigning them. How
is it that it would still work?
If I want to make an array that is say of length 3 using bracket notation,
should I just write: var foo = [,,];
I was more used to writing: var foo = new Array(3);
I noticed that if I removed one , that my code still worked which is
surprising because I am accessing all 3 elements after assigning them. How
is it that it would still work?
Friday, 23 August 2013
How to programmatically search text in jar file?
How to programmatically search text in jar file?
I want to search my sources.jar for the occurrence of a certain search token.
In Bash, this will extract the jar to a stream and grep for the string:
unzip -p sources.jar | grep $SEARCH_TOKEN
In Java, reading all entries via JarInputStream looks rather tedious. Is
there a better/simpler way (for both, the looping and the grepping)?
I want to search my sources.jar for the occurrence of a certain search token.
In Bash, this will extract the jar to a stream and grep for the string:
unzip -p sources.jar | grep $SEARCH_TOKEN
In Java, reading all entries via JarInputStream looks rather tedious. Is
there a better/simpler way (for both, the looping and the grepping)?
Change default ssh port on Fedora EC2
Change default ssh port on Fedora EC2
I have changed my /etc/ssh/sshd_config adding multiple ports for it to
listen:
$ grep Port /etc/ssh/sshd_config
Port 22
Port 80
Port 443
However, after a service sshd restart (which shown no errors) I still
cannot connect into any of the non standard ports, neither the server
seems to be listening:
$ netstat -an |grep LISTEN| grep -e "22\|80\|443"
tcp 0 0 0.0.0.0:22 0.0.0.0:*
LISTEN
tcp 0 0 :::22 :::*
LISTEN
No firewall rules to bother either:
$ iptables -L -n -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source
destination
46012 61M ACCEPT all -- * * 0.0.0.0/0
0.0.0.0/0 state RELATED,ESTABLISHED
0 0 ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0
9 338 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0
187 11232 ACCEPT tcp -- * * 0.0.0.0/0
0.0.0.0/0 state NEW tcp dpt:22
79 4171 REJECT all -- * * 0.0.0.0/0
0.0.0.0/0 reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source
destination
0 0 REJECT all -- * * 0.0.0.0/0
0.0.0.0/0 reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT 25028 packets, 2107K bytes)
pkts bytes target prot opt in out source
destination
And just to be sure I even made a few tests after a service iptables stop,
to no effect.
Found some people here with similar issues, but not quite the problem:
Basic SSH port change not working on EC2 instance
My SO:
$ uname -a
Linux ip-xxx 2.6.32-358.el6.x86_64 #1 SMP Tue Jan 29 11:47:41 EST 2013
x86_64 x86_64 x86_64 GNU/Linux
Any idea?
I have changed my /etc/ssh/sshd_config adding multiple ports for it to
listen:
$ grep Port /etc/ssh/sshd_config
Port 22
Port 80
Port 443
However, after a service sshd restart (which shown no errors) I still
cannot connect into any of the non standard ports, neither the server
seems to be listening:
$ netstat -an |grep LISTEN| grep -e "22\|80\|443"
tcp 0 0 0.0.0.0:22 0.0.0.0:*
LISTEN
tcp 0 0 :::22 :::*
LISTEN
No firewall rules to bother either:
$ iptables -L -n -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source
destination
46012 61M ACCEPT all -- * * 0.0.0.0/0
0.0.0.0/0 state RELATED,ESTABLISHED
0 0 ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0
9 338 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0
187 11232 ACCEPT tcp -- * * 0.0.0.0/0
0.0.0.0/0 state NEW tcp dpt:22
79 4171 REJECT all -- * * 0.0.0.0/0
0.0.0.0/0 reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source
destination
0 0 REJECT all -- * * 0.0.0.0/0
0.0.0.0/0 reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT 25028 packets, 2107K bytes)
pkts bytes target prot opt in out source
destination
And just to be sure I even made a few tests after a service iptables stop,
to no effect.
Found some people here with similar issues, but not quite the problem:
Basic SSH port change not working on EC2 instance
My SO:
$ uname -a
Linux ip-xxx 2.6.32-358.el6.x86_64 #1 SMP Tue Jan 29 11:47:41 EST 2013
x86_64 x86_64 x86_64 GNU/Linux
Any idea?
How to force the proper order with my javascript submit
How to force the proper order with my javascript submit
Ok so I have this javascript/jquery
$('.next').click(function(e){
e.preventDefault();
var table = $('table.active');
var form = table.find('form');
form.submit();
window.location.href = '/some/location';
});
The problem is that in some browsers safari being one of them the
form.submit() never gets called. My guess is this is an async request and
never gets a chance to do that call. Any ideas on how to do this. I tried
the following
form.submit(function(){
window.location.href = '/some/location';
});
but that didnt work
Ok so I have this javascript/jquery
$('.next').click(function(e){
e.preventDefault();
var table = $('table.active');
var form = table.find('form');
form.submit();
window.location.href = '/some/location';
});
The problem is that in some browsers safari being one of them the
form.submit() never gets called. My guess is this is an async request and
never gets a chance to do that call. Any ideas on how to do this. I tried
the following
form.submit(function(){
window.location.href = '/some/location';
});
but that didnt work
Invalid request URI - Youtube API retrieve single user playlist
Invalid request URI - Youtube API retrieve single user playlist
I am working on a client site. They have a series of playlist set up on
there YouTube account, which all load in to the video player depending on
which page of the site the user is on.
For example -
homepage loads homepage playlist from his youtube account
culture loads the culutre playlist
and so on...
I had previously set up most of the playlists, and my client said they
needed to set up the rest of the playlists in their youtube account before
I could add the rest. Well they finally got around to creating the
playlists, and told me to add them to the respective pages.
Some of them work, and some dont. On the ones that do not I get an
'invalid request URI' error. The ones that do, just load and work as
expected. Both playlists were set up on the same day, both are being
called in the exact same way. Why would I be getting this error? I can get
the json response from each playlist, so I know the playlist url is
correct.
Site: <http://www.Scrapple.tv">
I'm sending a get request to this URL:
http://gdata.youtube.com/feeds/api/playlists/PLAYLISTID?start-index=1&max-results=50&v=2&format=5&alt=jsonc
where PLAYLISTID is the id of the playlist that I am retreiving. The ones
that my client has created today and work are on pages 'We The People' and
'Culture > Nitelife'.
Problem Pages: Culture - Fashion
Culture - People
Culture - Music
Example of a working query:
http://gdata.youtube.com/feeds/api/playlists/HUp1agCRK5kDdqh-RwTBaMmk0Fo-_IeL?start-index=1&max-results=50&v=2&format=5&alt=jsonc
Example of non-working query:
http://gdata.youtube.com/feeds/api/playlists/HUp1agCRK5npY3kR8CQ9SLteral-krG2?start-index=1&max-results=50&v=2&format=5&alt=jsonc
Why would one be giving me an error of 'Invalid Request URI'
whereas the other, created on the same day, implemented the exact same
way, is working.
I am working on a client site. They have a series of playlist set up on
there YouTube account, which all load in to the video player depending on
which page of the site the user is on.
For example -
homepage loads homepage playlist from his youtube account
culture loads the culutre playlist
and so on...
I had previously set up most of the playlists, and my client said they
needed to set up the rest of the playlists in their youtube account before
I could add the rest. Well they finally got around to creating the
playlists, and told me to add them to the respective pages.
Some of them work, and some dont. On the ones that do not I get an
'invalid request URI' error. The ones that do, just load and work as
expected. Both playlists were set up on the same day, both are being
called in the exact same way. Why would I be getting this error? I can get
the json response from each playlist, so I know the playlist url is
correct.
Site: <http://www.Scrapple.tv">
I'm sending a get request to this URL:
http://gdata.youtube.com/feeds/api/playlists/PLAYLISTID?start-index=1&max-results=50&v=2&format=5&alt=jsonc
where PLAYLISTID is the id of the playlist that I am retreiving. The ones
that my client has created today and work are on pages 'We The People' and
'Culture > Nitelife'.
Problem Pages: Culture - Fashion
Culture - People
Culture - Music
Example of a working query:
http://gdata.youtube.com/feeds/api/playlists/HUp1agCRK5kDdqh-RwTBaMmk0Fo-_IeL?start-index=1&max-results=50&v=2&format=5&alt=jsonc
Example of non-working query:
http://gdata.youtube.com/feeds/api/playlists/HUp1agCRK5npY3kR8CQ9SLteral-krG2?start-index=1&max-results=50&v=2&format=5&alt=jsonc
Why would one be giving me an error of 'Invalid Request URI'
whereas the other, created on the same day, implemented the exact same
way, is working.
How to make ipython default when you run python if ipython is installed?
How to make ipython default when you run python if ipython is installed?
I am looking for a make bash profile trick to make ipython default when
you run python from the command line, obvioulsly without damaging normal
python script executon.
Is this possible, how?
I am looking for a make bash profile trick to make ipython default when
you run python from the command line, obvioulsly without damaging normal
python script executon.
Is this possible, how?
Angularjs bootstrap WYSIHTML5 editor
Angularjs bootstrap WYSIHTML5 editor
I'm having trouble getting this directive to work:
https://gist.github.com/joshkurz/3300629
I keep on getting the Cannot read property 'Editor' of undefined error.
Here is my plunk: http://plnkr.co/edit/ezzDZy190ozvN1TQUt2d?p=preview
I'm having trouble getting this directive to work:
https://gist.github.com/joshkurz/3300629
I keep on getting the Cannot read property 'Editor' of undefined error.
Here is my plunk: http://plnkr.co/edit/ezzDZy190ozvN1TQUt2d?p=preview
Thursday, 22 August 2013
How to make a right-facing fleur-de-lis list item bullet
How to make a right-facing fleur-de-lis list item bullet
Does anyone know how to make a right-facing, correctly-sized (12pt),
nice-looking (crisp, maybe SVG or something), fleur-de-lis as a list item
bullet?
I found this, but it's not quite what I'm after because I'm having trouble
finding a correctly-sized, right-facing fleur-de-lis image and I don't
have the skills to draw one myself. When I try to scale one that I find
using GIMP then it gets ugly very quickly.
I found some fonts, but they all face up instead of to the right, and I'm
not sure how I could use a system font as a list item even with XeLaTeX.
There is a unicode fleur-de-lis, but my system (OS 10.6) doesn't seem to
render it correctly (difficult to explain), and anyway, it faces up; not
to the right.
The fleur de lis below faces upward. I'd like it rotated 90 degrees
clockwise so it looks a bit like an arrow facing right.
Does anyone know how to make a right-facing, correctly-sized (12pt),
nice-looking (crisp, maybe SVG or something), fleur-de-lis as a list item
bullet?
I found this, but it's not quite what I'm after because I'm having trouble
finding a correctly-sized, right-facing fleur-de-lis image and I don't
have the skills to draw one myself. When I try to scale one that I find
using GIMP then it gets ugly very quickly.
I found some fonts, but they all face up instead of to the right, and I'm
not sure how I could use a system font as a list item even with XeLaTeX.
There is a unicode fleur-de-lis, but my system (OS 10.6) doesn't seem to
render it correctly (difficult to explain), and anyway, it faces up; not
to the right.
The fleur de lis below faces upward. I'd like it rotated 90 degrees
clockwise so it looks a bit like an arrow facing right.
Import single csv file with one data field going to separate table
Import single csv file with one data field going to separate table
I know this one is probably a long shot but I thought I would at least
ask. Say I have a csv file with a list of Products with the following 4
columns/data fields (Product ID, Name, Alias, UOM) that I would like to
import into a database that has 2 tables. One table is the Product table
(Product ID, Name, UOM), second table is Product Alias table with these 2
columns(Product ID, Alias), where each Product ID may have 0 to many alias
names. Is there any way I could treat the Alias column different by the
fact it has a different separator between the comma's like ";" or a period
"." to separate the 0 to many alias names for a given Product ID.
Therefore during the csv import, when it gets the 3rd comma, it would
import that data into this 2nd table but import a new record with
repeating Product ID's for as many alias names are in that comma field.
Hopefully I explained that well enough, let me if I didn't. I'm more
interested in the possible processing of doing this regardless of what
code that is being using but python would be the preferred route.
ProductID, Name, Alias, UOM
122, Widget1, W1;Wid1;Wt1, Each
123, Widget2, , Each
124, Widget3, W3;Wt3, Each
I know this one is probably a long shot but I thought I would at least
ask. Say I have a csv file with a list of Products with the following 4
columns/data fields (Product ID, Name, Alias, UOM) that I would like to
import into a database that has 2 tables. One table is the Product table
(Product ID, Name, UOM), second table is Product Alias table with these 2
columns(Product ID, Alias), where each Product ID may have 0 to many alias
names. Is there any way I could treat the Alias column different by the
fact it has a different separator between the comma's like ";" or a period
"." to separate the 0 to many alias names for a given Product ID.
Therefore during the csv import, when it gets the 3rd comma, it would
import that data into this 2nd table but import a new record with
repeating Product ID's for as many alias names are in that comma field.
Hopefully I explained that well enough, let me if I didn't. I'm more
interested in the possible processing of doing this regardless of what
code that is being using but python would be the preferred route.
ProductID, Name, Alias, UOM
122, Widget1, W1;Wid1;Wt1, Each
123, Widget2, , Each
124, Widget3, W3;Wt3, Each
Segues not working programaticly
Segues not working programaticly
So, i migrated a project from using XIB's to Storyboard, acording to these
instructions: http://stackoverflow.com/a/9708723/2604030 It went good. But
i can't make the segues work programaticly, and i need to use them this
way, because i have 2 buttons that link to the same ViewController, with
different types, hope you understand why from this image.
There are 2 dificulty mode buttons. The code i use:
`- (IBAction)btnNormalAct:(id)sender {
LevelController *wc = [[LevelController alloc]
initWithNibName:@"LevelController" type:0];
[self.navigationController pushViewController:wc animated:YES];
}
- (IBAction)btnTimedAct:(id)sender {
LevelController *wc = [[LevelController alloc]
initWithNibName:@"LevelController" type:1];
[self.navigationController pushViewController:wc animated:YES];
}`
This worked when i used XIB's, and i am sure i linked everything correctly
in the storyboard's VCs. The seagues works if i make them from the
storyboard. But how can i manage this situation.
ALSO: are those lines good when changing from XIB's to Storyboard? Is that
the right way to do this change (the way shown in the link above)?
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}
Thanks a lot !
So, i migrated a project from using XIB's to Storyboard, acording to these
instructions: http://stackoverflow.com/a/9708723/2604030 It went good. But
i can't make the segues work programaticly, and i need to use them this
way, because i have 2 buttons that link to the same ViewController, with
different types, hope you understand why from this image.
There are 2 dificulty mode buttons. The code i use:
`- (IBAction)btnNormalAct:(id)sender {
LevelController *wc = [[LevelController alloc]
initWithNibName:@"LevelController" type:0];
[self.navigationController pushViewController:wc animated:YES];
}
- (IBAction)btnTimedAct:(id)sender {
LevelController *wc = [[LevelController alloc]
initWithNibName:@"LevelController" type:1];
[self.navigationController pushViewController:wc animated:YES];
}`
This worked when i used XIB's, and i am sure i linked everything correctly
in the storyboard's VCs. The seagues works if i make them from the
storyboard. But how can i manage this situation.
ALSO: are those lines good when changing from XIB's to Storyboard? Is that
the right way to do this change (the way shown in the link above)?
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}
Thanks a lot !
"Unknown" and "Invalid use of Null" errors when performing SQL queries
"Unknown" and "Invalid use of Null" errors when performing SQL queries
A customer of ours has encountered some strange behavior. Our software
uses a database and we connect to it by the JET engine 4.0. We retrieve
information by using SQL statements. So these commands are the same for
every installation/user. We have a lot of customers but there is only one
who encounters the following issue:
Some SQL statements cause strange errors:
SELECT * FROM Dimensions
=> Successful
SELECT * FROM Sections where true=false
=> Error : "Unknown"
SELECT Alpha, Ys, Zs FROM SectionProperties WHERE Id = 1
=> Error : "Invalid use of Null"
These statements run without a problem on any other machine.
A customer of ours has encountered some strange behavior. Our software
uses a database and we connect to it by the JET engine 4.0. We retrieve
information by using SQL statements. So these commands are the same for
every installation/user. We have a lot of customers but there is only one
who encounters the following issue:
Some SQL statements cause strange errors:
SELECT * FROM Dimensions
=> Successful
SELECT * FROM Sections where true=false
=> Error : "Unknown"
SELECT Alpha, Ys, Zs FROM SectionProperties WHERE Id = 1
=> Error : "Invalid use of Null"
These statements run without a problem on any other machine.
How to maintain page backgroud image zoom fixed? CSS
How to maintain page backgroud image zoom fixed? CSS
I know how to set page background like;
body{
background-color: blue;
background-image: url(imagename.ext);
background-repeat: no-repeat;
background-position: left;
}
The page is subject to zoom. Using the browser, user can zoom in and zoom
out. But the background image may not zoom-in or zoom-out. It may remain
as such, in it's default size. Is this possible?
I know how to set page background like;
body{
background-color: blue;
background-image: url(imagename.ext);
background-repeat: no-repeat;
background-position: left;
}
The page is subject to zoom. Using the browser, user can zoom in and zoom
out. But the background image may not zoom-in or zoom-out. It may remain
as such, in it's default size. Is this possible?
Eclipse android - Pixel collision between sprite sheet animation and sprite
Eclipse android - Pixel collision between sprite sheet animation and sprite
I got 2 classes SpriteSheet - this draws the sprite animations. Racheta -
this draws a normal bitmap.
I saw this - http://pastebin.com/KRX937jT
And i tried to use it like this:
public static boolean isCollisionDetected(SpriteSheet sprite1, Racheta
sprite2){
Rect bounds1 = sprite1.getBounds();
Rect bounds2 = sprite2.getBounds();
if( Rect.intersects(bounds1, bounds2) ){
Rect collisionBounds = getCollisionBounds(bounds1, bounds2);
Log.d("", String.valueOf(collisionBounds));
for (int i = collisionBounds.left; i < collisionBounds.right;
i++) {
for (int j = collisionBounds.top; j <
collisionBounds.bottom; j++) {
int sprite1Pixel = getBitmapPixel(sprite1, i, j);
int sprite2Pixel = getBitmapPixelRacheta(sprite2, i, j);
if( isFilled(sprite1Pixel) && isFilled(sprite2Pixel)) {
return true;
}
}
}
}
return false;
}
private static int getBitmapPixel(SpriteSheet sprite, int i, int j) {
return
sprite.getBitmap().getPixel((i-(int)sprite.getX())+(sprite.currentFrame-1)*(sprite.getBitmap().getWidth()/sprite.totalFrames),j-(int)sprite.getY());
// to get the pixel from the current frame in the sprite sheet. // the
sprite sheet is horizontal for the code to be easier }
public static int getBitmapPixelRacheta(Racheta sprite, int i, int j) {
int x = i - (int) sprite.getX();
int y = j - (int)sprite.getY();
return sprite.bitmap.getPixel(x, y);
}
Whenever i compile i get error 08-22 11:20:29.465: E/AndroidRuntime(1443):
java.lang.IllegalArgumentException: y must be >= 0
or 08-22 11:17:03.045: E/AndroidRuntime(1382):
java.lang.IllegalArgumentException: y must be < bitmap.height()
08-22 11:20:29.465: E/AndroidRuntime(1443): at
com.cartof.avionul.Util.getBitmapPixelRacheta(Util.java:31)
Can anyone help me?
I got 2 classes SpriteSheet - this draws the sprite animations. Racheta -
this draws a normal bitmap.
I saw this - http://pastebin.com/KRX937jT
And i tried to use it like this:
public static boolean isCollisionDetected(SpriteSheet sprite1, Racheta
sprite2){
Rect bounds1 = sprite1.getBounds();
Rect bounds2 = sprite2.getBounds();
if( Rect.intersects(bounds1, bounds2) ){
Rect collisionBounds = getCollisionBounds(bounds1, bounds2);
Log.d("", String.valueOf(collisionBounds));
for (int i = collisionBounds.left; i < collisionBounds.right;
i++) {
for (int j = collisionBounds.top; j <
collisionBounds.bottom; j++) {
int sprite1Pixel = getBitmapPixel(sprite1, i, j);
int sprite2Pixel = getBitmapPixelRacheta(sprite2, i, j);
if( isFilled(sprite1Pixel) && isFilled(sprite2Pixel)) {
return true;
}
}
}
}
return false;
}
private static int getBitmapPixel(SpriteSheet sprite, int i, int j) {
return
sprite.getBitmap().getPixel((i-(int)sprite.getX())+(sprite.currentFrame-1)*(sprite.getBitmap().getWidth()/sprite.totalFrames),j-(int)sprite.getY());
// to get the pixel from the current frame in the sprite sheet. // the
sprite sheet is horizontal for the code to be easier }
public static int getBitmapPixelRacheta(Racheta sprite, int i, int j) {
int x = i - (int) sprite.getX();
int y = j - (int)sprite.getY();
return sprite.bitmap.getPixel(x, y);
}
Whenever i compile i get error 08-22 11:20:29.465: E/AndroidRuntime(1443):
java.lang.IllegalArgumentException: y must be >= 0
or 08-22 11:17:03.045: E/AndroidRuntime(1382):
java.lang.IllegalArgumentException: y must be < bitmap.height()
08-22 11:20:29.465: E/AndroidRuntime(1443): at
com.cartof.avionul.Util.getBitmapPixelRacheta(Util.java:31)
Can anyone help me?
Wednesday, 21 August 2013
DataGridView.BeginEdit called but underlying DataRowView on new row is null
DataGridView.BeginEdit called but underlying DataRowView on new row is null
My DataGridView is bound to a DataTable.
I'm forcing a DataGridView cell into edit mode upon a certain key
combination and if I check the IsInEditMode property of the cell it
returns true. The issue I'm having is that the DataBoundItem is Null for
new rows.
Is there anyway I can force the same behaviour that you get when you start
typing into a cell on a new row i.e. a new DataRowView is created and
assigned to the DataBoundItem of the new row?
thanks
Matt
My DataGridView is bound to a DataTable.
I'm forcing a DataGridView cell into edit mode upon a certain key
combination and if I check the IsInEditMode property of the cell it
returns true. The issue I'm having is that the DataBoundItem is Null for
new rows.
Is there anyway I can force the same behaviour that you get when you start
typing into a cell on a new row i.e. a new DataRowView is created and
assigned to the DataBoundItem of the new row?
thanks
Matt
How to exchanging code for an access token[facebook]
How to exchanging code for an access token[facebook]
I have problem with exchanging code for access token I try like this:
https://graph.facebook.com/oauth/access_token?%20client_id={387747397993215}%20&redirect_uri={http://mysite.com}%20&client_secret={AQAPBlfsNZihs0Ve43IbaykccXNnGkqXYg0PnwaXQUfjxaU5_DezT9LZqoQ2ma6mO5miaOKAa7Cf0YPQRnco8f4k8rfxJOENaNiD8rtK152PXdtBYN86arwv5UCan3tCX4kG_UWDreRkeT6S_X2MsWLFs-}
I get this error:
{
"error": {
"message": "redirect_uri isn't an absolute URI. Check RFC 3986.",
"type": "OAuthException",
"code": 191
}
}
I have problem with exchanging code for access token I try like this:
https://graph.facebook.com/oauth/access_token?%20client_id={387747397993215}%20&redirect_uri={http://mysite.com}%20&client_secret={AQAPBlfsNZihs0Ve43IbaykccXNnGkqXYg0PnwaXQUfjxaU5_DezT9LZqoQ2ma6mO5miaOKAa7Cf0YPQRnco8f4k8rfxJOENaNiD8rtK152PXdtBYN86arwv5UCan3tCX4kG_UWDreRkeT6S_X2MsWLFs-}
I get this error:
{
"error": {
"message": "redirect_uri isn't an absolute URI. Check RFC 3986.",
"type": "OAuthException",
"code": 191
}
}
How do I counter the engineers in the engineer mission in the Cybran campaign
How do I counter the engineers in the engineer mission in the Cybran campaign
In the Cybran campaign of Supreme Commander 2, there's a mission with
hostile engineers. (I don't think it's a spoiler, since it's obvious
up-front what's going to happen, but to be on the safe side I won't say
which mission.) I've noticed that the unit AI makes it hard to deal with
them: the engis' capture beam outranges the tanks even with the range
upgrade, and the tanks won't close to retaliate. Missile tanks and arty
are pretty useless until the engis are stationary. Aircraft would be
useful, but there are too many AA towers to consider using them at the
start. Your own engis won't try to capture or reclaim the enemy ones
without specific orders.
It deeply irritates me that this situation is only hard to deal with
because of shortcomings in the unit AI. Is there a better way to start the
mission than pretending you're playing StarCraft and ordering your tanks
to attack each engi as it arrives?
In the Cybran campaign of Supreme Commander 2, there's a mission with
hostile engineers. (I don't think it's a spoiler, since it's obvious
up-front what's going to happen, but to be on the safe side I won't say
which mission.) I've noticed that the unit AI makes it hard to deal with
them: the engis' capture beam outranges the tanks even with the range
upgrade, and the tanks won't close to retaliate. Missile tanks and arty
are pretty useless until the engis are stationary. Aircraft would be
useful, but there are too many AA towers to consider using them at the
start. Your own engis won't try to capture or reclaim the enemy ones
without specific orders.
It deeply irritates me that this situation is only hard to deal with
because of shortcomings in the unit AI. Is there a better way to start the
mission than pretending you're playing StarCraft and ordering your tanks
to attack each engi as it arrives?
Is it possible to convert file_uri to data_uri with phonegap, if so how would I do so
Is it possible to convert file_uri to data_uri with phonegap, if so how
would I do so
I am trying to convert an image stored in the temp storage to DATA_URI. Is
this something you can do with phonegap. I tried the following but all i
get is "Undefined" in the xml:
var reader = new FileReader();
var imgData = reader.readAsDataURL(results.rows.item(i).PictureFile);
XML = XML + imgData;
I had originally stored the images as a DATA_URI when I took the photo and
it was "working" fine for me other than when I went on older devices and
had memory issues. If anyone has any advice to get the data_uri please let
me know.
Thanks
would I do so
I am trying to convert an image stored in the temp storage to DATA_URI. Is
this something you can do with phonegap. I tried the following but all i
get is "Undefined" in the xml:
var reader = new FileReader();
var imgData = reader.readAsDataURL(results.rows.item(i).PictureFile);
XML = XML + imgData;
I had originally stored the images as a DATA_URI when I took the photo and
it was "working" fine for me other than when I went on older devices and
had memory issues. If anyone has any advice to get the data_uri please let
me know.
Thanks
Watching changed in the service from the controller
Watching changed in the service from the controller
I am trying to listen to changes in my injected service (self-updating) in
the controller. In the below example you'll find two $watch cases - one
that works but I don't know exactly why and one that was obvious to me,
yet doesn't work. Is the second example the right way to do it? Isn't that
code duplication? What is the right way to do it?
Service:
app.factory("StatsService", [
'$timeout', 'MockDataService',
function ($timeout, MockDataService) {
var service, timeout;
timeout = 5000;
service = {
fetch: function () {
// Getting sample data, irrelevant, however this is what
updates the data
return this.data = MockDataService.shuffle();
},
grab: function () {
this.fetch();
return this.update();
},
update: function () {
var _this = this;
return $timeout(function () {
return _this.grab();
}, timeout);
}
};
service.grab();
return service;
}
]);
Controller:
app.controller("StatsController", [
'$scope', 'StatsService',
function ($scope, StatsService) {
var chart;
$scope.stats = StatsService;
$scope.test = function (newValue) {
if (arguments.length === 0) {
return StatsService.data;
}
return StatsService.data = newValue;
};
// This doesn't work
$scope.$watch('stats', function (stats) {
return console.log('meh');
});
// This works, don't know why
$scope.$watch('test()', function (stats) {
return console.log('changed');
});
}
]);
I am trying to listen to changes in my injected service (self-updating) in
the controller. In the below example you'll find two $watch cases - one
that works but I don't know exactly why and one that was obvious to me,
yet doesn't work. Is the second example the right way to do it? Isn't that
code duplication? What is the right way to do it?
Service:
app.factory("StatsService", [
'$timeout', 'MockDataService',
function ($timeout, MockDataService) {
var service, timeout;
timeout = 5000;
service = {
fetch: function () {
// Getting sample data, irrelevant, however this is what
updates the data
return this.data = MockDataService.shuffle();
},
grab: function () {
this.fetch();
return this.update();
},
update: function () {
var _this = this;
return $timeout(function () {
return _this.grab();
}, timeout);
}
};
service.grab();
return service;
}
]);
Controller:
app.controller("StatsController", [
'$scope', 'StatsService',
function ($scope, StatsService) {
var chart;
$scope.stats = StatsService;
$scope.test = function (newValue) {
if (arguments.length === 0) {
return StatsService.data;
}
return StatsService.data = newValue;
};
// This doesn't work
$scope.$watch('stats', function (stats) {
return console.log('meh');
});
// This works, don't know why
$scope.$watch('test()', function (stats) {
return console.log('changed');
});
}
]);
Change Text in dynamically added Row
Change Text in dynamically added Row
iam realy new in Android and got some question:
I have some TableLayout, in this i want to add some rows dynamically. The
rows have to look the same, so i wrote a template in xml and add this as
view to the row.
In this xml file, there are some TextViews, and now i want to change the
Text of these TextViews in every TableRow, so that every table row got
some other text, like Sunday, Monday etc.
Later i want to add this Text from an array.
The TableLayoute xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/SPone_RL1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/backrepeat"
android:layout_gravity="center_vertical">
<ImageView
android:id="@+id/SPone_RL_ImageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@drawable/logo"
android:layout_centerInParent="true"
/>
<ScrollView
android:id="@+id/SPone_RL_SV"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/SPone_RL_SV_RL"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout android:id="@+id/SPoneTable"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="10dip" android:stretchColumns="*">
</TableLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
The Row xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/SPone_RL_SV_RL_RL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
>
<LinearLayout
android:layout_width="30dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Sonntag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/SPone_RL_SV_RL_RL_LL1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="70dp" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="25.08.2013"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="15:00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/SPone_RL_SV_RL_RL_LL2"
>
<TextView
android:id="@+id/textView5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="FC Bergalingen - FC Binzgen I"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/SPone_RL_SV_RL_RL_LL3"
>
<TextView
android:id="@+id/textView6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0:6"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="30sp" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The Java Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fcbonespielplan);
/* Find Tablelayout defined in main.xml */
TableLayout tl = (TableLayout) findViewById(R.id.SPoneTable);
for(int i = 0; i < 10; i++) {
/* Create a new row to be added. */
TableRow tr = new TableRow(this);
tr.setLayoutParams(new
TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
/* Create a View to be the row-content. */
LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//das Layout das 10 mal rein soll
ViewGroup yourview =
(ViewGroup)layoutInflater.inflate(R.layout.spielplantablerow,
null);
/* Add View to row. */
tr.addView(yourview);
/* Add row to TableLayout. */
tr.setBackgroundResource(R.drawable.baggroundtable);
tl.addView(tr, new
TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
}
Can anybody help me how i can set every time an other text to, maybe one
of the TextViews? Without generate the whole TextView from the Java?
iam realy new in Android and got some question:
I have some TableLayout, in this i want to add some rows dynamically. The
rows have to look the same, so i wrote a template in xml and add this as
view to the row.
In this xml file, there are some TextViews, and now i want to change the
Text of these TextViews in every TableRow, so that every table row got
some other text, like Sunday, Monday etc.
Later i want to add this Text from an array.
The TableLayoute xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/SPone_RL1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/backrepeat"
android:layout_gravity="center_vertical">
<ImageView
android:id="@+id/SPone_RL_ImageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@drawable/logo"
android:layout_centerInParent="true"
/>
<ScrollView
android:id="@+id/SPone_RL_SV"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/SPone_RL_SV_RL"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout android:id="@+id/SPoneTable"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="10dip" android:stretchColumns="*">
</TableLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
The Row xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/SPone_RL_SV_RL_RL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
>
<LinearLayout
android:layout_width="30dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Sonntag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/SPone_RL_SV_RL_RL_LL1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="70dp" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="25.08.2013"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp" >
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="15:00"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/SPone_RL_SV_RL_RL_LL2"
>
<TextView
android:id="@+id/textView5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="FC Bergalingen - FC Binzgen I"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/SPone_RL_SV_RL_RL_LL4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/SPone_RL_SV_RL_RL_LL3"
>
<TextView
android:id="@+id/textView6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0:6"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/white"
android:textSize="30sp" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The Java Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fcbonespielplan);
/* Find Tablelayout defined in main.xml */
TableLayout tl = (TableLayout) findViewById(R.id.SPoneTable);
for(int i = 0; i < 10; i++) {
/* Create a new row to be added. */
TableRow tr = new TableRow(this);
tr.setLayoutParams(new
TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
/* Create a View to be the row-content. */
LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//das Layout das 10 mal rein soll
ViewGroup yourview =
(ViewGroup)layoutInflater.inflate(R.layout.spielplantablerow,
null);
/* Add View to row. */
tr.addView(yourview);
/* Add row to TableLayout. */
tr.setBackgroundResource(R.drawable.baggroundtable);
tl.addView(tr, new
TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
}
Can anybody help me how i can set every time an other text to, maybe one
of the TextViews? Without generate the whole TextView from the Java?
Discriminant of $\mathrm{Tr}(xy)$ is $p^2$ in a maximal order of discriminant p in a quaternion algebra
Discriminant of $\mathrm{Tr}(xy)$ is $p^2$ in a maximal order of
discriminant p in a quaternion algebra
I am trying to prove that $\mathrm{Tr}(xy)$ has discriminant $p^2$ in a
maximal order of discriminant $p$ in a quaternion algebra. Does anybody
have any hints to get a handle on this?
discriminant p in a quaternion algebra
I am trying to prove that $\mathrm{Tr}(xy)$ has discriminant $p^2$ in a
maximal order of discriminant $p$ in a quaternion algebra. Does anybody
have any hints to get a handle on this?
Tuesday, 20 August 2013
It is something... or is it?
It is something... or is it?
I'm curious about the sentences of that kind.
Shouldn't they end with a negation?
Like this:
It is something, somthing... or isn't it?
Also, how are they constructed when the first sentence is a negation?
I'm curious about the sentences of that kind.
Shouldn't they end with a negation?
Like this:
It is something, somthing... or isn't it?
Also, how are they constructed when the first sentence is a negation?
Different types of uncountability
Different types of uncountability
Do there exist different types of uncountability? I am well aware that
$o(\aleph_0) < o (\mathbb{R}) < o (\mathcal{P}(\mathbb{R}))$, and so on.
I have looked around to no avail, however; is there a stricter definition
for cardinality than "two cardinal numbers are the same if there exists a
1-1 correspondence between their sets"? That is, is there a rigorous
definition for uncountability?
Do there exist different types of uncountability? I am well aware that
$o(\aleph_0) < o (\mathbb{R}) < o (\mathcal{P}(\mathbb{R}))$, and so on.
I have looked around to no avail, however; is there a stricter definition
for cardinality than "two cardinal numbers are the same if there exists a
1-1 correspondence between their sets"? That is, is there a rigorous
definition for uncountability?
x raised to the power 0 does not evaluate to 1
x raised to the power 0 does not evaluate to 1
I created a class for doing unit conversions, specifically bytes to
kilobytes, megabytes, gigabytes, etc. I have an enum with B through PB,
but for some reason 1024^0 does not return 1 and it's not correctly
converting from bytes to bytes or bytes to kilobytes, etc.
Here's my class:
public static class UnitConversion
{
/// <summary>
/// 1024^n
/// </summary>
public enum ByteConversionConstant
{
B = 0,
KB = 1,
MB = 2,
GB = 3,
TB = 4,
PB = 5
}
public static string GetValueFromBytes(long bytes,
ByteConversionConstant constant)
{
int n = (int)constant;
long divisor = 1024^n;
return (bytes / divisor).ToString() +
Enum.GetName(typeof(ByteConversionConstant), constant);
}
}
The following statement should return exactly the same value as
fileInfo.Length, but since 1024^0 isn't returning 1, it's showing the
number of kilobytes. Note, I had the GetValueFromBytes method all in one
line, but I separated it out to see what could be causing the
miscalculation.
UnitConversion.GetValueFromBytes(fileInfo.Length,
UnitConversion.ByteConversionConstant.B)
I'm not sure if it's an issue with casting the enum to an int or if
something gets lost when raising an int to an int and assigning it to a
long, but this is strange behavior.
I created a class for doing unit conversions, specifically bytes to
kilobytes, megabytes, gigabytes, etc. I have an enum with B through PB,
but for some reason 1024^0 does not return 1 and it's not correctly
converting from bytes to bytes or bytes to kilobytes, etc.
Here's my class:
public static class UnitConversion
{
/// <summary>
/// 1024^n
/// </summary>
public enum ByteConversionConstant
{
B = 0,
KB = 1,
MB = 2,
GB = 3,
TB = 4,
PB = 5
}
public static string GetValueFromBytes(long bytes,
ByteConversionConstant constant)
{
int n = (int)constant;
long divisor = 1024^n;
return (bytes / divisor).ToString() +
Enum.GetName(typeof(ByteConversionConstant), constant);
}
}
The following statement should return exactly the same value as
fileInfo.Length, but since 1024^0 isn't returning 1, it's showing the
number of kilobytes. Note, I had the GetValueFromBytes method all in one
line, but I separated it out to see what could be causing the
miscalculation.
UnitConversion.GetValueFromBytes(fileInfo.Length,
UnitConversion.ByteConversionConstant.B)
I'm not sure if it's an issue with casting the enum to an int or if
something gets lost when raising an int to an int and assigning it to a
long, but this is strange behavior.
How can I set up logging for node-mongod-native?
How can I set up logging for node-mongod-native?
I am trying to set up logging for the native mongo driver for node. I've
got the following snippet set up as a demonstration for what I am trying
to do. Unfortunately nothing is being emitted on the console. Any ideas?
var express = require('express') ;
var app = express();
var http = require('http');
var mongod = require('mongodb');
var server_conf = new mongod.Server('localhost', 27017,
{auto_reconnect:true});
//dummy logger
var logger = {
error:function(message, object) {console.log('anything')},
log:function(message, object) {console.log('anything')},
debug:function(message, object) {console.log('anything')}}
var db_container = {db: new mongod.Db('test', server_conf,
{w:1,journal:true, native_parser:true, logger: logger})}
app.use(express.bodyParser());
app.use(app.router);
db_container.db.open(function(err, index_info){
if(err) throw err;
var testcol = db_container.db.collection('testcol');
app.get('/', function(request, res){
testcol.insert({hello:"moto"}, function(err,doc){
if(err){
throw err;
}
testcol.find({}).toArray(function(err,docs){
res.send(docs);
});
});
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
});
I am trying to set up logging for the native mongo driver for node. I've
got the following snippet set up as a demonstration for what I am trying
to do. Unfortunately nothing is being emitted on the console. Any ideas?
var express = require('express') ;
var app = express();
var http = require('http');
var mongod = require('mongodb');
var server_conf = new mongod.Server('localhost', 27017,
{auto_reconnect:true});
//dummy logger
var logger = {
error:function(message, object) {console.log('anything')},
log:function(message, object) {console.log('anything')},
debug:function(message, object) {console.log('anything')}}
var db_container = {db: new mongod.Db('test', server_conf,
{w:1,journal:true, native_parser:true, logger: logger})}
app.use(express.bodyParser());
app.use(app.router);
db_container.db.open(function(err, index_info){
if(err) throw err;
var testcol = db_container.db.collection('testcol');
app.get('/', function(request, res){
testcol.insert({hello:"moto"}, function(err,doc){
if(err){
throw err;
}
testcol.find({}).toArray(function(err,docs){
res.send(docs);
});
});
});
http.createServer(app).listen(3000, function () {
console.log('Express server listening on port ' + '3000');
});
});
Media Query on Mobile Device
Media Query on Mobile Device
Media Querys for Browser-View on a Samsung young will not be found using
following code in html-file i have two lines für the styles. Any ideas?
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1">
<link href="style.css" type="text/css" rel="stylesheet" media="all" />
css-file:
// ---- MEDIA QUERY
$break-smallest: 240px;
$break-small: 320px;
$break-smart: 480px;
$break-middle: 768px;
$break-large: 1024px;
@mixin respond-to($media) {
@if $media == handhelds {
@media only screen and (max-device-width: $break-smallest) { @content; }
}
@else if $media == small-screens {
@media only screen and (min-device-width: $break-smallest + 1) and
(max-device-width: $break-small - 1) { @content; }
}
@else if $media == smart-screens {
@media only screen and (min-device-width: $break-small + 1) and
(max-device-width: $break-smart - 1) { @content; }
}
@else if $media == medium-screens {
@media only screen and (min-device-width: $break-smart + 1) and
(max-device-width: $break-middle - 1) { @content; }
}
@else if $media == wide-screens {
@media only screen and (min-device-width: $break-large) { @content; }
}
}
targets with
@include respond-to(handhelds) { width: 240px; }
@include respond-to(small-screens) { width: 320px; }
@include respond-to(smart-screens) { width: 480px; }
@include respond-to(medium-screens) { width: 768px; }
Media Querys for Browser-View on a Samsung young will not be found using
following code in html-file i have two lines für the styles. Any ideas?
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1">
<link href="style.css" type="text/css" rel="stylesheet" media="all" />
css-file:
// ---- MEDIA QUERY
$break-smallest: 240px;
$break-small: 320px;
$break-smart: 480px;
$break-middle: 768px;
$break-large: 1024px;
@mixin respond-to($media) {
@if $media == handhelds {
@media only screen and (max-device-width: $break-smallest) { @content; }
}
@else if $media == small-screens {
@media only screen and (min-device-width: $break-smallest + 1) and
(max-device-width: $break-small - 1) { @content; }
}
@else if $media == smart-screens {
@media only screen and (min-device-width: $break-small + 1) and
(max-device-width: $break-smart - 1) { @content; }
}
@else if $media == medium-screens {
@media only screen and (min-device-width: $break-smart + 1) and
(max-device-width: $break-middle - 1) { @content; }
}
@else if $media == wide-screens {
@media only screen and (min-device-width: $break-large) { @content; }
}
}
targets with
@include respond-to(handhelds) { width: 240px; }
@include respond-to(small-screens) { width: 320px; }
@include respond-to(smart-screens) { width: 480px; }
@include respond-to(medium-screens) { width: 768px; }
coding different in xcode 4.5 and xcode 4.6?
coding different in xcode 4.5 and xcode 4.6?
so i was implementing some code that i was learning from this tutorial.
the guy was using Xcode 4.5 and i'm using Xcode 4.6.At one point he
pressed run and so did i, his one was fine but mine came up with 12
errors. let me remind you that there were no errors before and i wrote
exactly what he wrote. Also he implemented this code.. view controller *vc
and when i did it, it said, "unused variable". is this because of
different versions or am i doing something wrong personally?
If this isn't enough information, let me know, so i can post the link.
so i was implementing some code that i was learning from this tutorial.
the guy was using Xcode 4.5 and i'm using Xcode 4.6.At one point he
pressed run and so did i, his one was fine but mine came up with 12
errors. let me remind you that there were no errors before and i wrote
exactly what he wrote. Also he implemented this code.. view controller *vc
and when i did it, it said, "unused variable". is this because of
different versions or am i doing something wrong personally?
If this isn't enough information, let me know, so i can post the link.
Monday, 19 August 2013
How to get a HashMap value and compare it to a number
How to get a HashMap value and compare it to a number
I have a list of entries in a HashMap, a String as a Key, and a Long as a
Value. I'm trying to check if the Value is greater than a certain number,
but I'm not sure how I can get the value and check it.
I know this is incorrect, but this may show what I mean better than I can
explain:
long offlineTimeLimit = (offlineTimeLimitConfig*1000);
long limit = (offlineTimeLimit + System.currentTimeMillis());
Long playerName = playerTimeCheck.get(p);
if (playerTimeCheck.containsValue( > limit)) {
}
This gets the amount of time a player is allowed offline,
offlimeTimeLimitConfig, then multiplies by 1000 (so it's in milliseconds),
then adds the current time. I want to check if any of the values in the
hashmap are greater than the current time plus the time limit, then
execute a code.
I've been doing research, and I've found other ways to store my data (like
a TreeMap) and I'm not sure if that may be a better way to store the data.
Here's the rest of the code:
String p = event.getPlayer().getName();
HashMap<String, Long> playerTimeCheck = new HashMap<String, Long>();
ConfigurationSection section =
getConfig().getConfigurationSection("PlayerTime");
long currentTime = System.currentTimeMillis();
String playerCheck = getConfig().getString("PlayerTime");
for (String key : section.getKeys(false)) {
playerTimeCheck.put(key, section.getLong(key));
}
Thanks for the help, Colby
I have a list of entries in a HashMap, a String as a Key, and a Long as a
Value. I'm trying to check if the Value is greater than a certain number,
but I'm not sure how I can get the value and check it.
I know this is incorrect, but this may show what I mean better than I can
explain:
long offlineTimeLimit = (offlineTimeLimitConfig*1000);
long limit = (offlineTimeLimit + System.currentTimeMillis());
Long playerName = playerTimeCheck.get(p);
if (playerTimeCheck.containsValue( > limit)) {
}
This gets the amount of time a player is allowed offline,
offlimeTimeLimitConfig, then multiplies by 1000 (so it's in milliseconds),
then adds the current time. I want to check if any of the values in the
hashmap are greater than the current time plus the time limit, then
execute a code.
I've been doing research, and I've found other ways to store my data (like
a TreeMap) and I'm not sure if that may be a better way to store the data.
Here's the rest of the code:
String p = event.getPlayer().getName();
HashMap<String, Long> playerTimeCheck = new HashMap<String, Long>();
ConfigurationSection section =
getConfig().getConfigurationSection("PlayerTime");
long currentTime = System.currentTimeMillis();
String playerCheck = getConfig().getString("PlayerTime");
for (String key : section.getKeys(false)) {
playerTimeCheck.put(key, section.getLong(key));
}
Thanks for the help, Colby
How to change Terminator title terminal title, ZSH on Debian?
How to change Terminator title terminal title, ZSH on Debian?
I don't know if I should ask it here or on unix.stackexchange.com, I found
this question here.
My question is similar, I want to change the title of a terminal, I'm
using a Debian based distro, Terminator and ZSH, oh-my-zsh the title was
fine with bash, but when I moved to ZSH, it shows /bin/zsh as title.
I don't know if I should ask it here or on unix.stackexchange.com, I found
this question here.
My question is similar, I want to change the title of a terminal, I'm
using a Debian based distro, Terminator and ZSH, oh-my-zsh the title was
fine with bash, but when I moved to ZSH, it shows /bin/zsh as title.
How to test Net::HTTP::Post request in ruby and minitest
How to test Net::HTTP::Post request in ruby and minitest
I'm trying to make sure a callback json object is properly sent by
Net::HTTP::Post, how do I test it in minitest? What I wanted is to compare
the POST body to the JSON object that I want to be sent when I call the
#perform method of a delayed_job class. I also want to make sure a target
URL actually received this POST request.
I looked at fakeweb, but it looks like it doesn't do POST requests. The
closest I could do seems to be http://requestb.in/, but it seems to be a
bit manual.
I'm trying to make sure a callback json object is properly sent by
Net::HTTP::Post, how do I test it in minitest? What I wanted is to compare
the POST body to the JSON object that I want to be sent when I call the
#perform method of a delayed_job class. I also want to make sure a target
URL actually received this POST request.
I looked at fakeweb, but it looks like it doesn't do POST requests. The
closest I could do seems to be http://requestb.in/, but it seems to be a
bit manual.
How to structure friend relation in cassandra
How to structure friend relation in cassandra
I have a user table in Cassandra currently.
I want To create a friend relation table but i am not sure what is the
best way to do it. First i thought put like key as current user and column
as friend but than i wanted to achieve the functionality of sending friend
request so i think there should be another object called accepted which
takes care of that two persons are real friends or not or eather the other
person accepted the friend request or not. I think it will be Many to Many
table. For example in a friendship relation.
Friendship: {
John Dow: {
10: Mark Seldon,
8: Julian Hendrix,
...
},
Mark Seldon: {
9: John Dow,
...
},
...
}
Any directions is appreciated.
I have a user table in Cassandra currently.
I want To create a friend relation table but i am not sure what is the
best way to do it. First i thought put like key as current user and column
as friend but than i wanted to achieve the functionality of sending friend
request so i think there should be another object called accepted which
takes care of that two persons are real friends or not or eather the other
person accepted the friend request or not. I think it will be Many to Many
table. For example in a friendship relation.
Friendship: {
John Dow: {
10: Mark Seldon,
8: Julian Hendrix,
...
},
Mark Seldon: {
9: John Dow,
...
},
...
}
Any directions is appreciated.
Sunday, 18 August 2013
111-222-1933email@adress.tst hacker
111-222-1933email@adress.tst hacker
I am learning website languages, and i am still a beginner. I am building
a website that uses registrations, logins, adds, and so on... First I used
PDO in my php in order to prevent mysql injections. Anyway I was hacked,
they did not delete the database but it is full of this e-mail
111-222-1933email@adress.tst, and a strange code. I think that they used
acunetix to see the leaks of mine website.
My question is: Do you know whats he hacker did, and what measures
(besides PDO) can i use in my website to have a little bit more of
security?
Thank You
I am learning website languages, and i am still a beginner. I am building
a website that uses registrations, logins, adds, and so on... First I used
PDO in my php in order to prevent mysql injections. Anyway I was hacked,
they did not delete the database but it is full of this e-mail
111-222-1933email@adress.tst, and a strange code. I think that they used
acunetix to see the leaks of mine website.
My question is: Do you know whats he hacker did, and what measures
(besides PDO) can i use in my website to have a little bit more of
security?
Thank You
SQL Query Builder Javascript UI
SQL Query Builder Javascript UI
I'm looking for a UI tool to help users generate SQL queries.
Red Query Builder has some of the features I'd like, but the source
doesn't seem to be available in an easily-editable format and it lacks an
interface for manipulating group or order commands.
Digging around the internet didn't reveal any other palatable candidates,
so I'm asking here.
I'm looking for a UI tool to help users generate SQL queries.
Red Query Builder has some of the features I'd like, but the source
doesn't seem to be available in an easily-editable format and it lacks an
interface for manipulating group or order commands.
Digging around the internet didn't reveal any other palatable candidates,
so I'm asking here.
Shear stress in directions other than the flow direction
Shear stress in directions other than the flow direction
I already asked this question here
http://physics.stackexchange.com/questions/74310/shear-stress-in-directions-other-than-the-flow-direction,
but Ii am not getting a response. I think applied mathematicians should be
able to answer the question.Thus, I don't think the question is off-topic.
Consider the flow of a newtonian fluid in a rectangular pipe. Consider a
3D coordinate system with the property that.that the flow of the fluid in
the pipe is parallel to the x-axis. Let $V:\mathbb{R}^3\rightarrow
\mathbb{R}^3$ return the velocity vector at each point of the 3D space.
Assume that $V$ is differentiable with continuous partial derivatives.
Consider a cuboid inside the fluid filling the pipe: $[x_0,x_0+\triangle
x]\times [y_0,y_0+\triangle y]\times [z_0,z_0+\triangle z]$ . I am trying
to compute the shear force on the face $\{(x_0,y,z)|y_0\leq y\leq
y_0+\triangle y,z_0\leq z\leq z_0+\triangle z\}$ of the cuboid. My guess
that it would be:
$$\int_{y_0}^{y_0+\triangle y}\int_{z_0}^{z_0+\triangle z}
\mu[v_x(x_0,b,c)+v_z(x_0,b,c)]dc
\,db\,\mathbf{j}+\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\int_{y_0}^{y_0+\triangle
y}\int_{z_0}^{z_0+\triangle z} \mu[w_x(x_0,b,c)+w_y(x_0,b,c)]dc
\,db\,\mathbf{k}$$ (Note about the notation:
$V(x,y,z)=u(x,y,z)\mathbf{i}+v(x,y,z)\mathbf{j}+w(x,y,z)\mathbf{k}$)
Am I right? If I am not right could you please give the correct shear
force on the face I am talking about.
Sorry if the question is naive. If the question is naive it would probably
be because I only had an engineering course in fluid mechanics and the
course considered only shear stress parallel to the direction of flow. I
don't know if this is because shear stress only acts in the direction of
shear flow or because the book was assuming (without mentioning) that some
components of $V$ are zero or have zero partial derivatives. Thus the only
equation for shear stress I saw in the course is $\tau=\mu \frac{\partial
v}{\partial y}$. I am looking for the most general case.
Thank you
I already asked this question here
http://physics.stackexchange.com/questions/74310/shear-stress-in-directions-other-than-the-flow-direction,
but Ii am not getting a response. I think applied mathematicians should be
able to answer the question.Thus, I don't think the question is off-topic.
Consider the flow of a newtonian fluid in a rectangular pipe. Consider a
3D coordinate system with the property that.that the flow of the fluid in
the pipe is parallel to the x-axis. Let $V:\mathbb{R}^3\rightarrow
\mathbb{R}^3$ return the velocity vector at each point of the 3D space.
Assume that $V$ is differentiable with continuous partial derivatives.
Consider a cuboid inside the fluid filling the pipe: $[x_0,x_0+\triangle
x]\times [y_0,y_0+\triangle y]\times [z_0,z_0+\triangle z]$ . I am trying
to compute the shear force on the face $\{(x_0,y,z)|y_0\leq y\leq
y_0+\triangle y,z_0\leq z\leq z_0+\triangle z\}$ of the cuboid. My guess
that it would be:
$$\int_{y_0}^{y_0+\triangle y}\int_{z_0}^{z_0+\triangle z}
\mu[v_x(x_0,b,c)+v_z(x_0,b,c)]dc
\,db\,\mathbf{j}+\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\int_{y_0}^{y_0+\triangle
y}\int_{z_0}^{z_0+\triangle z} \mu[w_x(x_0,b,c)+w_y(x_0,b,c)]dc
\,db\,\mathbf{k}$$ (Note about the notation:
$V(x,y,z)=u(x,y,z)\mathbf{i}+v(x,y,z)\mathbf{j}+w(x,y,z)\mathbf{k}$)
Am I right? If I am not right could you please give the correct shear
force on the face I am talking about.
Sorry if the question is naive. If the question is naive it would probably
be because I only had an engineering course in fluid mechanics and the
course considered only shear stress parallel to the direction of flow. I
don't know if this is because shear stress only acts in the direction of
shear flow or because the book was assuming (without mentioning) that some
components of $V$ are zero or have zero partial derivatives. Thus the only
equation for shear stress I saw in the course is $\tau=\mu \frac{\partial
v}{\partial y}$. I am looking for the most general case.
Thank you
What are the best practices when designing restricted areas in rails?
What are the best practices when designing restricted areas in rails?
being newish to rails I wanted to get some advice from the community on
how to setup restricted areas. I just started using Devise and have read
about a few different methods for redirecting/rendering views based on if
a user is logged in or not and I'm wondering what the best way to go about
it is.
Currently, when I want a logged in user to have a different view of a page
then a non-logged in user I've been handling it in the controller. For
instance:
class CollectionsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
def index
@collections = Collection.all
if current_user
render :admin
else
render :index
end
end
end
In which case :admin and :index correspond to
views/collections/admin.html.haml and views/collections/index.html.haml
respectively. The admin view is similar in layout to the index view but
has links to the edit, update, create, etc.
Is this the best way going about it?
EDIT: I was also considering trying out an authorization gem like CanCan
but wasn't sure if that would be overkill.
being newish to rails I wanted to get some advice from the community on
how to setup restricted areas. I just started using Devise and have read
about a few different methods for redirecting/rendering views based on if
a user is logged in or not and I'm wondering what the best way to go about
it is.
Currently, when I want a logged in user to have a different view of a page
then a non-logged in user I've been handling it in the controller. For
instance:
class CollectionsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
def index
@collections = Collection.all
if current_user
render :admin
else
render :index
end
end
end
In which case :admin and :index correspond to
views/collections/admin.html.haml and views/collections/index.html.haml
respectively. The admin view is similar in layout to the index view but
has links to the edit, update, create, etc.
Is this the best way going about it?
EDIT: I was also considering trying out an authorization gem like CanCan
but wasn't sure if that would be overkill.
Excel VBA - Search certain column for a #N/A, copy entire row to new sheet and delete row
Excel VBA - Search certain column for a #N/A, copy entire row to new sheet
and delete row
This is what I have already. It searches column B in sheet 1 for #N/A and
deletes the row.
Sub DeleteErrorRows()
On Error Resume Next
Range("B:B").SpecialCells(xlCellTypeConstants, 16).EntireRow.Delete
On Error GoTo 0
End Sub
What I would like is for it to copy that row onto sheet 2 and then delete?
So I can have a record of what was deleted.
Any help would be much appreciated. Thanks!
and delete row
This is what I have already. It searches column B in sheet 1 for #N/A and
deletes the row.
Sub DeleteErrorRows()
On Error Resume Next
Range("B:B").SpecialCells(xlCellTypeConstants, 16).EntireRow.Delete
On Error GoTo 0
End Sub
What I would like is for it to copy that row onto sheet 2 and then delete?
So I can have a record of what was deleted.
Any help would be much appreciated. Thanks!
How to get menu item id on action bar when other menu item clicked
How to get menu item id on action bar when other menu item clicked
pSo I have menu items on action bar. on onOptionsItemSelected, I want to
change the menu items images. /p pHere's my code/p precode @Override
public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on
the action bar items switch (item.getItemId()) { case R.id.todaySched:{
viewTodaySched(); item.setIcon(R.drawable.calendarselected);
infoLog=(MenuItem)findViewById(R.id.infoLog);
infoLog.setIcon(R.drawable.book); return true;} case R.id.infoLog:{
viewInfoLog(); item.setIcon(R.drawable.bookselected);
todaySched=(MenuItem)findViewById(R.id.todaySched);
todaySched.setIcon(R.drawable.calenderselected); return true;} default:
return super.onOptionsItemSelected(item); } } /code/pre pBut the icon
won't change when I clicked it, and I got run time error. e.g: When I
click todaySched icon, It seems like I can't get the infoLog item id. /p
pMy LogCat: a href=https://www.dropbox.com/s/0wfz0ogkh57vbtz/log.txt
rel=nofollowLogCat/a/p
pSo I have menu items on action bar. on onOptionsItemSelected, I want to
change the menu items images. /p pHere's my code/p precode @Override
public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on
the action bar items switch (item.getItemId()) { case R.id.todaySched:{
viewTodaySched(); item.setIcon(R.drawable.calendarselected);
infoLog=(MenuItem)findViewById(R.id.infoLog);
infoLog.setIcon(R.drawable.book); return true;} case R.id.infoLog:{
viewInfoLog(); item.setIcon(R.drawable.bookselected);
todaySched=(MenuItem)findViewById(R.id.todaySched);
todaySched.setIcon(R.drawable.calenderselected); return true;} default:
return super.onOptionsItemSelected(item); } } /code/pre pBut the icon
won't change when I clicked it, and I got run time error. e.g: When I
click todaySched icon, It seems like I can't get the infoLog item id. /p
pMy LogCat: a href=https://www.dropbox.com/s/0wfz0ogkh57vbtz/log.txt
rel=nofollowLogCat/a/p
Saturday, 17 August 2013
Match snippets in an HTML document
Match snippets in an HTML document
Somebody has presented me with a very large list of copyedits to make to a
long HTML document. The edits are in the format:
"religious" should be "religions"
"their" should be "there"
"you must persistent" should be "you must be persistent"
The copyedits were typed by hand; in some cases, the "actual" value on the
left is not an exact match for the content on the right. The order of
edits is usually correct, but even that is not guaranteed.
It's a straightforward but very large task to apply these edits by hand to
the document. I'd like to automate the process as much as possible, e.g.
by automatically searching for the snippets.
In a long document like this, I can't just search for all instances of
"their" and replace them with "there." Sometimes "their" was used
correctly, just not in one particular instance.
In other words, I'm looking for a fuzzy text match, where the order of the
edits influences the search.
What's a good approach to a problem like this? I'm hoping that there's
some off-the-shelf open source project that can search for the snippets in
a fuzzy order.
Somebody has presented me with a very large list of copyedits to make to a
long HTML document. The edits are in the format:
"religious" should be "religions"
"their" should be "there"
"you must persistent" should be "you must be persistent"
The copyedits were typed by hand; in some cases, the "actual" value on the
left is not an exact match for the content on the right. The order of
edits is usually correct, but even that is not guaranteed.
It's a straightforward but very large task to apply these edits by hand to
the document. I'd like to automate the process as much as possible, e.g.
by automatically searching for the snippets.
In a long document like this, I can't just search for all instances of
"their" and replace them with "there." Sometimes "their" was used
correctly, just not in one particular instance.
In other words, I'm looking for a fuzzy text match, where the order of the
edits influences the search.
What's a good approach to a problem like this? I'm hoping that there's
some off-the-shelf open source project that can search for the snippets in
a fuzzy order.
Are the Reliable Raid issues from 2009 still present?
Are the Reliable Raid issues from 2009 still present?
This wiki article details some problems with using LUKS on a md RAID.
It appears most of the problems are around assembling the raid on boot.
Are these issues still a problem on Ubuntu?
This wiki article details some problems with using LUKS on a md RAID.
It appears most of the problems are around assembling the raid on boot.
Are these issues still a problem on Ubuntu?
Html Utility Pack not reading non-ASCII text correctly
Html Utility Pack not reading non-ASCII text correctly
When I parse a html document instead of getting Japanese text I get
something like:
�͂��߂܂��āB���̓C�t�T�[���ł��A21�΂ł��A�����b�R�ɂ���ł��܂��A���͓��{�̕��������������A�N�������ɓ��{�������邱�Ƃ��ł��܂����A����3�N�ԓ��{���׋����܂����A���̓t��
5533;��X���p���A���r�A�������邱�Ƃɂ��������������邱�Ƃł��傤
^^���͓��{�l�̗F�B�ɉ�����A���������ɂ��闝�R�ł��A�ł́A�܂��B�C�t�T�[��
(^^)\r\n\t\t\t
The encoding in HtmlDocument is set to iso-2022-jp, which seems correct. I
also tried
HtmlWeb web = new HtmlWeb();
web.OverrideEncoding = Encoding.UTF8;
Any ideas?
When I parse a html document instead of getting Japanese text I get
something like:
�͂��߂܂��āB���̓C�t�T�[���ł��A21�΂ł��A�����b�R�ɂ���ł��܂��A���͓��{�̕��������������A�N�������ɓ��{�������邱�Ƃ��ł��܂����A����3�N�ԓ��{���׋����܂����A���̓t��
5533;��X���p���A���r�A�������邱�Ƃɂ��������������邱�Ƃł��傤
^^���͓��{�l�̗F�B�ɉ�����A���������ɂ��闝�R�ł��A�ł́A�܂��B�C�t�T�[��
(^^)\r\n\t\t\t
The encoding in HtmlDocument is set to iso-2022-jp, which seems correct. I
also tried
HtmlWeb web = new HtmlWeb();
web.OverrideEncoding = Encoding.UTF8;
Any ideas?
Modifying Laravel 4 resource controller routes
Modifying Laravel 4 resource controller routes
I just started developing with Laravel and I really understand why it's
such a popular framework. Having been a PHP-developer for many years now
I've been bothered with how loose the language is. Using Laravel fixes
many of those issues and helps me create structured code.
Today I began working with resource controllers and resource routes and it
works great. Although, I'd like to modify some of the automatically
generated routes and I'm not certain if this is in fact possible or not.
This is the scenario, I have a model called Workspace (using Eloquent) and
I created a resource controller using artisan.
php artisan controller:make WorkspaceController
And I also added the routes using this command in my routes.php file.
Route::resource('workspace',
'PROJECT\Controllers\Workspaces\WorkspaceController');
Now to my issue. Since I want to use getIndex to list the available
resources I'd like the index route to be workspaces and not workspace,
whereas I'd like to keep the structure for other scenarios like
workspace/{id}/edit and so on.
Do you guys know how I can modify the default routes that Route::resource
creates?
I'd be very grateful if anyone cares to help me with this one :)
Thanks in advance! // Jonathan
I just started developing with Laravel and I really understand why it's
such a popular framework. Having been a PHP-developer for many years now
I've been bothered with how loose the language is. Using Laravel fixes
many of those issues and helps me create structured code.
Today I began working with resource controllers and resource routes and it
works great. Although, I'd like to modify some of the automatically
generated routes and I'm not certain if this is in fact possible or not.
This is the scenario, I have a model called Workspace (using Eloquent) and
I created a resource controller using artisan.
php artisan controller:make WorkspaceController
And I also added the routes using this command in my routes.php file.
Route::resource('workspace',
'PROJECT\Controllers\Workspaces\WorkspaceController');
Now to my issue. Since I want to use getIndex to list the available
resources I'd like the index route to be workspaces and not workspace,
whereas I'd like to keep the structure for other scenarios like
workspace/{id}/edit and so on.
Do you guys know how I can modify the default routes that Route::resource
creates?
I'd be very grateful if anyone cares to help me with this one :)
Thanks in advance! // Jonathan
Passing value of an input control to controller
Passing value of an input control to controller
I have the following:
@Html.BeginForm("AddComment", "Shared", new { guid = Model.VideoGuid,
content="", userid = authenticatedUserId.ToString()}){
<div class="input-group">
<input name="txtCommentContent" type="text"
class="form-control"><span class="input-group-btn">
<button class="btn btn-default">
<img src="~/Content/images/Message-Add.png"
/></button>
</span>
</div>
}
I need to pass the text input inside the input control to the control as
part of the routeValues. The above content="" is going to do that.
How can this be done?
I have the following:
@Html.BeginForm("AddComment", "Shared", new { guid = Model.VideoGuid,
content="", userid = authenticatedUserId.ToString()}){
<div class="input-group">
<input name="txtCommentContent" type="text"
class="form-control"><span class="input-group-btn">
<button class="btn btn-default">
<img src="~/Content/images/Message-Add.png"
/></button>
</span>
</div>
}
I need to pass the text input inside the input control to the control as
part of the routeValues. The above content="" is going to do that.
How can this be done?
mysql timediff where condition
mysql timediff where condition
I have to use a condition in the time diff of mysql. I have to modify the
following query:-
select
bugs_team_user_view.bug_id,
bugs_team_user_view.creation_ts
from
bugs_team_user_view, bugs_activity
where
bugs_team_user_view.team like "Red%"
and
timediff(
(select bugs_activity.bug_when from bugs_activity where
bugs_activity.added = "RESOLVED"),
bugs_team_user_view.creation_ts) > "00:30:00"
and
bugs_team_user_view.bug_id=bugs_activity.bug_id
and bugs_team_user_view.creation_ts < "2013-08-17 00:00:00"
and bugs_team_user_view.creation_ts >"2013-08-01 00:00:00";
Getting error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
usenear 'bugs_team_user_view.creation_ts < "2013-08-17 00:00:00" and
bugs_team_user_view.' at line 1
Please help
I have to use a condition in the time diff of mysql. I have to modify the
following query:-
select
bugs_team_user_view.bug_id,
bugs_team_user_view.creation_ts
from
bugs_team_user_view, bugs_activity
where
bugs_team_user_view.team like "Red%"
and
timediff(
(select bugs_activity.bug_when from bugs_activity where
bugs_activity.added = "RESOLVED"),
bugs_team_user_view.creation_ts) > "00:30:00"
and
bugs_team_user_view.bug_id=bugs_activity.bug_id
and bugs_team_user_view.creation_ts < "2013-08-17 00:00:00"
and bugs_team_user_view.creation_ts >"2013-08-01 00:00:00";
Getting error:-
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
usenear 'bugs_team_user_view.creation_ts < "2013-08-17 00:00:00" and
bugs_team_user_view.' at line 1
Please help
superfast ssd (PCIe connector) to MBP mid2012?
superfast ssd (PCIe connector) to MBP mid2012?
is it possible to put one of these new generation ssd to my MBP with pci
express connector?
PCIe SSD
is it possible to put one of these new generation ssd to my MBP with pci
express connector?
PCIe SSD
Friday, 16 August 2013
Why does procedural background slow down UIScrollView?
Why does procedural background slow down UIScrollView?
My problem code is in a procedural background that I am drawing in a
UIView (drawRect:) which I am then adding as a subview to UIScrollView.
The procedural code is below. It draws box shapes, which look sort of like
a skyline. Any Ideas why this is slowing down the my UIScrollView? It
seems to only be slow on the first scroll, then its as if it is cached.
The background can be as much as a thousand pixels wide or more at times.
See image...
- (void)drawRect:(CGRect)rect
{
UIBezierPath *vertLine = [[UIBezierPath alloc] init];
[vertLine moveToPoint:CGPointMake(0,self.frame.size.height)];
int detail = 10;
int ranNum = 0;
int count = self.bounds.size.width/detail;
CGFloat heightIncrement = 0.0;
CGFloat minHeight = self.frame.size.height;
CGFloat xPos = 0;
CGFloat yPos = self.frame.size.height-20;
for (int i =0; i<count; i++)
{
ranNum += (arc4random() % 9)-5;
yPos -= (arc4random() % 30);
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
xPos += (arc4random() % 20)+10;
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
yPos += (arc4random() % 30);
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
xPos += (arc4random() % 30);
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
if (yPos>self.frame.size.height-10) {
yPos = self.frame.size.height-10;
}
if (yPos<self.frame.size.height-50) {
yPos = self.frame.size.height-50;
}
}
[vertLine addLineToPoint:CGPointMake(count*20,(self.frame.size.height))];
[[UIColor colorWithRed:0.0/255.0 green:38.0/255.0 blue:51.0/255 alpha:1]
setFill];
[vertLine fill];
}
My problem code is in a procedural background that I am drawing in a
UIView (drawRect:) which I am then adding as a subview to UIScrollView.
The procedural code is below. It draws box shapes, which look sort of like
a skyline. Any Ideas why this is slowing down the my UIScrollView? It
seems to only be slow on the first scroll, then its as if it is cached.
The background can be as much as a thousand pixels wide or more at times.
See image...
- (void)drawRect:(CGRect)rect
{
UIBezierPath *vertLine = [[UIBezierPath alloc] init];
[vertLine moveToPoint:CGPointMake(0,self.frame.size.height)];
int detail = 10;
int ranNum = 0;
int count = self.bounds.size.width/detail;
CGFloat heightIncrement = 0.0;
CGFloat minHeight = self.frame.size.height;
CGFloat xPos = 0;
CGFloat yPos = self.frame.size.height-20;
for (int i =0; i<count; i++)
{
ranNum += (arc4random() % 9)-5;
yPos -= (arc4random() % 30);
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
xPos += (arc4random() % 20)+10;
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
yPos += (arc4random() % 30);
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
xPos += (arc4random() % 30);
[vertLine addLineToPoint:CGPointMake(xPos,yPos)];
if (yPos>self.frame.size.height-10) {
yPos = self.frame.size.height-10;
}
if (yPos<self.frame.size.height-50) {
yPos = self.frame.size.height-50;
}
}
[vertLine addLineToPoint:CGPointMake(count*20,(self.frame.size.height))];
[[UIColor colorWithRed:0.0/255.0 green:38.0/255.0 blue:51.0/255 alpha:1]
setFill];
[vertLine fill];
}
Subscribe to:
Comments (Atom)