Sed : loop on an array of string
In a bash script I would like to loop on an array and execute a sed
command each times. Basically, I would like to do something like that :
names=( "Peter" "Juan Carlos" "Emily")
for name in ${names[*]}
do
sed 's/[[:space:]]*{'"$name"'}/'"$name"'/g' "$file"
done
What do I miss ?
Saturday, 31 August 2013
Read from word document line by line
Read from word document line by line
I'm trying to read a word document using C#. I am able to get all text but
I want to be able to read line by line and s*tore in a list and bind to a
gridview*. Currently my code returns a list of one item only with all text
(not line by line as desired). I'm using the Microsoft.Office.Interop.Word
library to read the file. Below is my code till now:
Application word = new Application();
Document doc = new Document();
object fileName = path;
// Define an object to pass to the API for missing parameters
object missing = System.Type.Missing;
doc = word.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
String read = string.Empty;
List<string> data = new List<string>();
foreach (Range tmpRange in doc.StoryRanges)
{
//read += tmpRange.Text + "<br>";
data.Add(tmpRange.Text);
}
((_Document)doc).Close();
((_Application)word).Quit();
GridView1.DataSource = data;
GridView1.DataBind();
Any help would be highly appreciated. Thanks.
I'm trying to read a word document using C#. I am able to get all text but
I want to be able to read line by line and s*tore in a list and bind to a
gridview*. Currently my code returns a list of one item only with all text
(not line by line as desired). I'm using the Microsoft.Office.Interop.Word
library to read the file. Below is my code till now:
Application word = new Application();
Document doc = new Document();
object fileName = path;
// Define an object to pass to the API for missing parameters
object missing = System.Type.Missing;
doc = word.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
String read = string.Empty;
List<string> data = new List<string>();
foreach (Range tmpRange in doc.StoryRanges)
{
//read += tmpRange.Text + "<br>";
data.Add(tmpRange.Text);
}
((_Document)doc).Close();
((_Application)word).Quit();
GridView1.DataSource = data;
GridView1.DataBind();
Any help would be highly appreciated. Thanks.
Ruby directory alias get original path
Ruby directory alias get original path
I'm working with a directory that's an alias with Ruby on Mac. This means
that this is a folder that just points to another folder. How can I
determine what the original directory that this alias points to?
So for example, in one of my Jenkins job, there is an alias called
lastStable, which points to the latest stable build folder.
path = /Users/steve/.Jenkins/jobs/MyApp/lastStable
lastStable actually points to a folder called 2013-08-06_10_50_49.
How can I get this info dynamically in Ruby?
I'm working with a directory that's an alias with Ruby on Mac. This means
that this is a folder that just points to another folder. How can I
determine what the original directory that this alias points to?
So for example, in one of my Jenkins job, there is an alias called
lastStable, which points to the latest stable build folder.
path = /Users/steve/.Jenkins/jobs/MyApp/lastStable
lastStable actually points to a folder called 2013-08-06_10_50_49.
How can I get this info dynamically in Ruby?
URGENT SOLUTION NEEDED !!! DECIMAL are left forgotten in calculation !!!! PLZ HELP ME
URGENT SOLUTION NEEDED !!! DECIMAL are left forgotten in calculation !!!!
PLZ HELP ME
I'm stuck for some hours now on the following problem:
1)Got a textfield for a number that has to be divided through 100 and
multiplied by a second number after hitting a calculate box 2)I can add A
Decimal number in the textfield... 3)The result comes out as a number with
decimals but does not seem to use all the decimals from the first number
in the calculation.
Example : 2033,33 /100 * 21 becomes : 426,93 (it only looked at 2033 tot
preform the calculation and forgot the remaining 0,33)
Im kinda new to scripting in xcode and have looked everywhere. I guess
there is a simple solution im not seeing anymore after neary 8 hours of
trying??? I need to get this fixed for my brother tomorrow if possible
This is part of my viewcontroller h script:
{
IBOutlet UITextField *numOne; // First number
IBOutlet UITextField *numTwo; // Second number
IBOutlet UITextField *answer; // First number divided by 100 and
multiplied by second number
}
-(IBAction)Calculate:(id)sender; //Calculationbox
And this is the part of my view controller m script :
-(IBAction)Calculate:(id)sender{
float x = ([numOne.text floatValue]/100.00);
float c = x*([numTwo.text floatValue]);
answer.text = [[NSString alloc] initWithFormat:@"%.2f", c];
PLZ HELP ME
I'm stuck for some hours now on the following problem:
1)Got a textfield for a number that has to be divided through 100 and
multiplied by a second number after hitting a calculate box 2)I can add A
Decimal number in the textfield... 3)The result comes out as a number with
decimals but does not seem to use all the decimals from the first number
in the calculation.
Example : 2033,33 /100 * 21 becomes : 426,93 (it only looked at 2033 tot
preform the calculation and forgot the remaining 0,33)
Im kinda new to scripting in xcode and have looked everywhere. I guess
there is a simple solution im not seeing anymore after neary 8 hours of
trying??? I need to get this fixed for my brother tomorrow if possible
This is part of my viewcontroller h script:
{
IBOutlet UITextField *numOne; // First number
IBOutlet UITextField *numTwo; // Second number
IBOutlet UITextField *answer; // First number divided by 100 and
multiplied by second number
}
-(IBAction)Calculate:(id)sender; //Calculationbox
And this is the part of my view controller m script :
-(IBAction)Calculate:(id)sender{
float x = ([numOne.text floatValue]/100.00);
float c = x*([numTwo.text floatValue]);
answer.text = [[NSString alloc] initWithFormat:@"%.2f", c];
Unexpected '=' in php
Unexpected '=' in php
I am getting a strange error in my php code, and I can't figure out why!
The error: Parse error: syntax error, unexpected '=' on line 9
<?php
session_start();
$name = $_POST['Contact-Name'];
$address = $_POST['Contact-address'];
$email = $_POST['Contact-Email'];
$phone = $_POST['Contact-Phone'];
$program = $_POST['Program-Name'];
$date-requested = $_POST['date-requested'];
$timestart = $_POST['program-start-time'];
$timeend = $_POST['program-end-time'];
$timestart-format = $_POST['starttime-format'];
$timeend-format = $_POST['endtime-format'];
$full-start-time = $timestart." ".$timestart-format;
$full-end-time = $timeend." ".$timeend-format;
//the book king hours
$mon-thurs-hours = array("10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM",
"2:00 PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM");
$friday-hours = array("10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM", "2:00
PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM", "7:00 PM", "8:00 PM");
$saturday-hours = array("10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM",
"2:00 PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM");
//find the day of the week and save to $dayofweek
$date = new DateTime();
$timestamp = date_timestamp_get($date-requested);
$dayofweek = date( "w", $timestamp);
//if sunday
if($dayofweek == 0){
echo "You choose Sunday!";
die('Sorry, the book king is closed on Sundays!');
}
//if monday, tues, wed, thurs
if(($dayofweek == 1)||($dayofweek == 2)||($dayofweek == 3)||($dayofweek ==
4)){
echo "You choose day ".$dayofweek."!";
//see if bk is open at the specified times
if (in_array($full-start-time, $mon-thurs-hours)) {
echo "Start time is okay!";
}
if (in_array($full-end-time, $mon-thurs-hours)) {
echo "End time is okay!";
}
}
//if friday
if($dayofweek == 5){
echo "You choose day ".$dayofweek."!";
//see if bk is open at the specified times
if (in_array($full-start-time, $friday-hours)) {
echo "Start time is okay!";
}
if (in_array($full-end-time, $friday-hours)) {
echo "End time is okay!";
}
}
//if saturday
if($dayofweek == 6){
echo "You choose day ".$dayofweek."!";
//see if bk is open at the specified times
if (in_array($full-start-time, $saturday-hours)) {
echo "Start time is okay!";
}
if (in_array($full-end-time, $saturday-hours)) {
echo "End time is okay!";
}
}
?>
I'm not sure if you need all that code, or just the first 9 lines, but I
posted it all just in case!
I really appreciate your help with this!
I am getting a strange error in my php code, and I can't figure out why!
The error: Parse error: syntax error, unexpected '=' on line 9
<?php
session_start();
$name = $_POST['Contact-Name'];
$address = $_POST['Contact-address'];
$email = $_POST['Contact-Email'];
$phone = $_POST['Contact-Phone'];
$program = $_POST['Program-Name'];
$date-requested = $_POST['date-requested'];
$timestart = $_POST['program-start-time'];
$timeend = $_POST['program-end-time'];
$timestart-format = $_POST['starttime-format'];
$timeend-format = $_POST['endtime-format'];
$full-start-time = $timestart." ".$timestart-format;
$full-end-time = $timeend." ".$timeend-format;
//the book king hours
$mon-thurs-hours = array("10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM",
"2:00 PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM");
$friday-hours = array("10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM", "2:00
PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM", "7:00 PM", "8:00 PM");
$saturday-hours = array("10:00 AM", "11:00 AM", "12:00 PM", "1:00 PM",
"2:00 PM", "3:00 PM", "4:00 PM", "5:00 PM", "6:00 PM");
//find the day of the week and save to $dayofweek
$date = new DateTime();
$timestamp = date_timestamp_get($date-requested);
$dayofweek = date( "w", $timestamp);
//if sunday
if($dayofweek == 0){
echo "You choose Sunday!";
die('Sorry, the book king is closed on Sundays!');
}
//if monday, tues, wed, thurs
if(($dayofweek == 1)||($dayofweek == 2)||($dayofweek == 3)||($dayofweek ==
4)){
echo "You choose day ".$dayofweek."!";
//see if bk is open at the specified times
if (in_array($full-start-time, $mon-thurs-hours)) {
echo "Start time is okay!";
}
if (in_array($full-end-time, $mon-thurs-hours)) {
echo "End time is okay!";
}
}
//if friday
if($dayofweek == 5){
echo "You choose day ".$dayofweek."!";
//see if bk is open at the specified times
if (in_array($full-start-time, $friday-hours)) {
echo "Start time is okay!";
}
if (in_array($full-end-time, $friday-hours)) {
echo "End time is okay!";
}
}
//if saturday
if($dayofweek == 6){
echo "You choose day ".$dayofweek."!";
//see if bk is open at the specified times
if (in_array($full-start-time, $saturday-hours)) {
echo "Start time is okay!";
}
if (in_array($full-end-time, $saturday-hours)) {
echo "End time is okay!";
}
}
?>
I'm not sure if you need all that code, or just the first 9 lines, but I
posted it all just in case!
I really appreciate your help with this!
MySQL Precison Issues in DECIMAL NUMERIC data type
MySQL Precison Issues in DECIMAL NUMERIC data type
In writing a function for scientific application, I ran into issues. I
traced it back to MySQL's lack of precison.
Here is the page from the official documentation which claims that The
maximum number of digits for DECIMAL is 65 -
http://dev.mysql.com/doc/refman/5.6/en/fixed-point-types.html . It also
describes how the value will be rounded if it exceeds the specified
precison.
Here is reproducible code (a mysql stored function) to test it -
DELIMITER $$
DROP FUNCTION IF EXISTS test$$
CREATE FUNCTION test
(xx DECIMAL(30,25)
)
RETURNS DECIMAL(30,25)
DETERMINISTIC
BEGIN
DECLARE result DECIMAL(30,25);
SET result = 0.339946499848118887e-4;
RETURN(result);
END$$
DELIMITER ;
If you save the code above in a file called test.sql, you can run it by
executing the following in mysql prompt -
source test.sql;
select test(0);
It produces the output -
+-----------------------------+
| test(0) |
+-----------------------------+
| 0.0000339946499848118900000 |
+-----------------------------+
1 row in set (0.00 sec)
As you can see, the number is getting rounded at the 20th digit, and then
five zeroes are being added to it to get to the required/specified
precison. That is cheating.
Am I mistaken, or is the documentation wrong?
In writing a function for scientific application, I ran into issues. I
traced it back to MySQL's lack of precison.
Here is the page from the official documentation which claims that The
maximum number of digits for DECIMAL is 65 -
http://dev.mysql.com/doc/refman/5.6/en/fixed-point-types.html . It also
describes how the value will be rounded if it exceeds the specified
precison.
Here is reproducible code (a mysql stored function) to test it -
DELIMITER $$
DROP FUNCTION IF EXISTS test$$
CREATE FUNCTION test
(xx DECIMAL(30,25)
)
RETURNS DECIMAL(30,25)
DETERMINISTIC
BEGIN
DECLARE result DECIMAL(30,25);
SET result = 0.339946499848118887e-4;
RETURN(result);
END$$
DELIMITER ;
If you save the code above in a file called test.sql, you can run it by
executing the following in mysql prompt -
source test.sql;
select test(0);
It produces the output -
+-----------------------------+
| test(0) |
+-----------------------------+
| 0.0000339946499848118900000 |
+-----------------------------+
1 row in set (0.00 sec)
As you can see, the number is getting rounded at the 20th digit, and then
five zeroes are being added to it to get to the required/specified
precison. That is cheating.
Am I mistaken, or is the documentation wrong?
Parsing a Zipped JSON file in PHP without Extracting
Parsing a Zipped JSON file in PHP without Extracting
With help from the guys on Stackoverflow I can now Parse JSON code from a
file and save a 'Value' into a database
However the real file I intend to read from is actually a massive 2GB
file. My web server will not hold this file. However it will hold a ZIPPED
version of it - ie 80MB.
I believe there is a way to PARSE JSON from a ZIPPED file without actually
having to save the 2GB version of the file on my web server only having to
save the ZIPPED 80MB version instead............Can anybody help?
I have found the below function which I believe will do this (I think) but
I don't know how to link it to my code
private function uncompressFile($srcName, $dstName) {
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w");
while ($string = gzread($sfp, 4096)) {
fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);
}
My current PHP code is below and works. It reads a basic small file, JSON
decodes it (The JSON is in a series of separate lines hence the need for
FILE_IGNORE_NEW_LINES) and then takes a value and saves to MySQL database.
However I believe I need to somehow combine these two bits of code so I
can read a ZIPPED file without exceeding my 100MB storage on my webserver
$file="CIF_ALL_UPDATE_DAILY_toc-update-sun";
$trains = file($json_filename, FILE_IGNORE_NEW_LINES |
FILE_SKIP_EMPTY_LINES);
foreach ($trains as $train) {
$json=json_decode($train,true);
foreach ($json as $key => $value) {
$input=$value['main_train_uid'];
$q="INSERT INTO railstptest (main_train_uid) VALUES ('$input')";
$r=mysqli_query($mysql_link,$q);
}
}
}
if (is_null($json)) {
die("Json decoding failed with error: ". json_last_error());
}
mysqli_close($mysql_link);
Many Thanks
With help from the guys on Stackoverflow I can now Parse JSON code from a
file and save a 'Value' into a database
However the real file I intend to read from is actually a massive 2GB
file. My web server will not hold this file. However it will hold a ZIPPED
version of it - ie 80MB.
I believe there is a way to PARSE JSON from a ZIPPED file without actually
having to save the 2GB version of the file on my web server only having to
save the ZIPPED 80MB version instead............Can anybody help?
I have found the below function which I believe will do this (I think) but
I don't know how to link it to my code
private function uncompressFile($srcName, $dstName) {
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w");
while ($string = gzread($sfp, 4096)) {
fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);
}
My current PHP code is below and works. It reads a basic small file, JSON
decodes it (The JSON is in a series of separate lines hence the need for
FILE_IGNORE_NEW_LINES) and then takes a value and saves to MySQL database.
However I believe I need to somehow combine these two bits of code so I
can read a ZIPPED file without exceeding my 100MB storage on my webserver
$file="CIF_ALL_UPDATE_DAILY_toc-update-sun";
$trains = file($json_filename, FILE_IGNORE_NEW_LINES |
FILE_SKIP_EMPTY_LINES);
foreach ($trains as $train) {
$json=json_decode($train,true);
foreach ($json as $key => $value) {
$input=$value['main_train_uid'];
$q="INSERT INTO railstptest (main_train_uid) VALUES ('$input')";
$r=mysqli_query($mysql_link,$q);
}
}
}
if (is_null($json)) {
die("Json decoding failed with error: ". json_last_error());
}
mysqli_close($mysql_link);
Many Thanks
.htaccess 403 redirects not working
.htaccess 403 redirects not working
I have this code in my .htaccess file:
Options All -Indexes
order deny,allow
deny from all
ErrorDocument 403 /www/landing.html
<Files landing.html>
allow from all
</Files>
<Files styles.css>
allow from all
</Files>
<Files prefixfree.min.js>
allow from all
</Files>
which is located on my server at /www. There is an index.html,
loading.html, and a .htaccess in this folder, then the css and js files
are in their respective subfolders. The site is hosted on Hostgator.
When I load up my site, I get this error:
Forbidden
You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an
ErrorDocument to handle the request.
So it's not finding the document. If I change my code to ErrorDocument 403
/loading.html then my site goes down entirely and the loading icon just
spins without loading anything. downforeveryoneorjustme.com also reports
that it is down. Is there something I'm doing wrong?
I have this code in my .htaccess file:
Options All -Indexes
order deny,allow
deny from all
ErrorDocument 403 /www/landing.html
<Files landing.html>
allow from all
</Files>
<Files styles.css>
allow from all
</Files>
<Files prefixfree.min.js>
allow from all
</Files>
which is located on my server at /www. There is an index.html,
loading.html, and a .htaccess in this folder, then the css and js files
are in their respective subfolders. The site is hosted on Hostgator.
When I load up my site, I get this error:
Forbidden
You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an
ErrorDocument to handle the request.
So it's not finding the document. If I change my code to ErrorDocument 403
/loading.html then my site goes down entirely and the loading icon just
spins without loading anything. downforeveryoneorjustme.com also reports
that it is down. Is there something I'm doing wrong?
Friday, 30 August 2013
Query Improvement for Open, Close, High, Low
Query Improvement for Open, Close, High, Low
I am trying to find the Open,Close,High,Low prices for a currency pair. I
got it working, but was wondering if there is an easier way to do it.
My source table looks like this:
CREATE TABLE [dbo].[RATES](
[SYSID] [bigint] IDENTITY(1,1) NOT NULL,
[Item] [nvarchar](255) NULL,
[Bid] [float] NULL,
[Ask] [float] NULL,
[Spread] [float] NULL,
[DT] [datetime] NULL
) ON [PRIMARY]
Here is some sample data
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04805,1.04828,0.000230000000000175,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04831,0.000230000000000175,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04802,1.04827,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04806,1.04831,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04801,1.04827,0.000259999999999927,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04806,1.04831,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04806,1.04832,0.000259999999999927,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04829,0.000210000000000043,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.0483,0.000210000000000043,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04832,0.000229999999999952,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04807,1.04833,0.000259999999999927,'8/29/2013 5:04')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04828,0.000190000000000135,'8/29/2013 5:04')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:04')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04829,0.000199999999999978,'8/29/2013 5:04')
My Query looks like this
DECLARE @OPENCLOSE AS TABLE (
GRP INT,
TF DATETIME,
DT DATETIME,
ASK FLOAT
)
DECLARE @CLOSE_ID AS TABLE (
TF DATETIME,
GRP INT
)
INSERT INTO @OPENCLOSE (GRP,TF,DT,ASK)
select
ROW_NUMBER() OVER (PARTITION BY dateadd(mi, datediff(mi, 0, r.DT), 0)
ORDER BY r.DT) AS GRP,
dateadd(mi, datediff(mi, 0, r.DT), 0) AS TF,
r.DT,
r.Ask
from dbo.RATES r
group by dateadd(mi, datediff(mi, 0, r.DT), 0), r.DT,r.Ask
ORDER BY dateadd(mi, datediff(mi, 0, r.DT), 0)
INSERT INTO @CLOSE_ID
SELECT
TF,
MAX(GRP) AS CLOSE_ID
FROM @OPENCLOSE
group by TF
SELECT X.TF,X.O,X.C,Y.HIGH,Y.LOW
FROM (
SELECT
oc1.TF,
oc2.ASK AS [O],
oc1.ASK AS [C]
FROM @OPENCLOSE oc1
JOIN @OPENCLOSE oc2
ON oc2.TF = oc1.TF
AND oc2.GRP = 1
JOIN @CLOSE_ID cid
ON cid.TF = oc1.TF
AND cid.GRP = oc1.GRP
GROUP BY oc1.TF,Oc2.ASK,oc1.ASK
) x
JOIN
(
SELECT
oc1.TF,
MAX(oc1.ASK) AS HIGH,
MIN(oc1.ASK) AS LOW
FROM @OPENCLOSE oc1
GROUP BY oc1.TF
) y ON y.TF = x.TF
I am trying to find the Open,Close,High,Low prices for a currency pair. I
got it working, but was wondering if there is an easier way to do it.
My source table looks like this:
CREATE TABLE [dbo].[RATES](
[SYSID] [bigint] IDENTITY(1,1) NOT NULL,
[Item] [nvarchar](255) NULL,
[Bid] [float] NULL,
[Ask] [float] NULL,
[Spread] [float] NULL,
[DT] [datetime] NULL
) ON [PRIMARY]
Here is some sample data
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04805,1.04828,0.000230000000000175,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04831,0.000230000000000175,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04802,1.04827,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04806,1.04831,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04801,1.04827,0.000259999999999927,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04806,1.04831,0.000250000000000083,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04806,1.04832,0.000259999999999927,'8/29/2013 5:02')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04832,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04829,0.000210000000000043,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04808,1.04833,0.000250000000000083,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.0483,0.000210000000000043,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04832,0.000229999999999952,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:03')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04807,1.04833,0.000259999999999927,'8/29/2013 5:04')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04828,0.000190000000000135,'8/29/2013 5:04')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04833,0.000240000000000018,'8/29/2013 5:04')
INSERT INTO dbo.RATES (ITEM,BID,ASK,SPREAD,DT) VALUE
('USD/CAD',1.04809,1.04829,0.000199999999999978,'8/29/2013 5:04')
My Query looks like this
DECLARE @OPENCLOSE AS TABLE (
GRP INT,
TF DATETIME,
DT DATETIME,
ASK FLOAT
)
DECLARE @CLOSE_ID AS TABLE (
TF DATETIME,
GRP INT
)
INSERT INTO @OPENCLOSE (GRP,TF,DT,ASK)
select
ROW_NUMBER() OVER (PARTITION BY dateadd(mi, datediff(mi, 0, r.DT), 0)
ORDER BY r.DT) AS GRP,
dateadd(mi, datediff(mi, 0, r.DT), 0) AS TF,
r.DT,
r.Ask
from dbo.RATES r
group by dateadd(mi, datediff(mi, 0, r.DT), 0), r.DT,r.Ask
ORDER BY dateadd(mi, datediff(mi, 0, r.DT), 0)
INSERT INTO @CLOSE_ID
SELECT
TF,
MAX(GRP) AS CLOSE_ID
FROM @OPENCLOSE
group by TF
SELECT X.TF,X.O,X.C,Y.HIGH,Y.LOW
FROM (
SELECT
oc1.TF,
oc2.ASK AS [O],
oc1.ASK AS [C]
FROM @OPENCLOSE oc1
JOIN @OPENCLOSE oc2
ON oc2.TF = oc1.TF
AND oc2.GRP = 1
JOIN @CLOSE_ID cid
ON cid.TF = oc1.TF
AND cid.GRP = oc1.GRP
GROUP BY oc1.TF,Oc2.ASK,oc1.ASK
) x
JOIN
(
SELECT
oc1.TF,
MAX(oc1.ASK) AS HIGH,
MIN(oc1.ASK) AS LOW
FROM @OPENCLOSE oc1
GROUP BY oc1.TF
) y ON y.TF = x.TF
Thursday, 29 August 2013
Load iCloud document from subFolder in iOS
Load iCloud document from subFolder in iOS
I have successfully created Folder named Note in iCloud.
I know the way to load files from iCloud Document directory.
But i don't know how to load from Notes Folders.
I only want to load all documents from Note Folder. not from Document
directory.
The directory path is like that : "iCloud>Documents>Notes"
Here is some of my codes that load data from iCloud Document Folder.
[self.notes removeAllObjects];
NSMutableArray* tmpFileList = [[NSMutableArray alloc] init];
for (NSMetadataItem *item in [query results])
{
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
Note *doc = [[Note alloc] initWithFileURL:url];
doc.lastModDate = [item
valueForAttribute:NSMetadataItemFSContentChangeDateKey];
[tmpFileList addObject:doc];
}
NSSortDescriptor *descriptor = [NSSortDescriptor
sortDescriptorWithKey:@"lastModDate" ascending:NO];
self.notes = [NSMutableArray arrayWithArray:[tmpFileList
sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]];
[self.tblMainTableView reloadData];
How can i load it?
I have successfully created Folder named Note in iCloud.
I know the way to load files from iCloud Document directory.
But i don't know how to load from Notes Folders.
I only want to load all documents from Note Folder. not from Document
directory.
The directory path is like that : "iCloud>Documents>Notes"
Here is some of my codes that load data from iCloud Document Folder.
[self.notes removeAllObjects];
NSMutableArray* tmpFileList = [[NSMutableArray alloc] init];
for (NSMetadataItem *item in [query results])
{
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
Note *doc = [[Note alloc] initWithFileURL:url];
doc.lastModDate = [item
valueForAttribute:NSMetadataItemFSContentChangeDateKey];
[tmpFileList addObject:doc];
}
NSSortDescriptor *descriptor = [NSSortDescriptor
sortDescriptorWithKey:@"lastModDate" ascending:NO];
self.notes = [NSMutableArray arrayWithArray:[tmpFileList
sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]];
[self.tblMainTableView reloadData];
How can i load it?
all dd copy do not work why whyyy?
all dd copy do not work why whyyy?
I try to copy one partition 500GB
sudo dcfldd if=/dev/sda12 of=/dev/sdb12
sudo dd if=/dev/sda12 of=/dev/sdb12
it do copy only 1GB it do it in to ram memory
after this /dev/sdb12 size is 1GB it is standard file not device
dd automatically is off and no count= is on in any command
all disks have no bad sectors smart is fully clean
md5sum /dev/sda and md5sum /dev/sdb is reading and thesame in
dcfldd if=/dev/sdb | md5sum
and all the time rebuildfstab script say can not stat device /dev/sdb
the sda 2TB disk is a boot disk
the sdb is also 2TB disk usb connected [in GUI after system start]
so all the same sizes the disk /dev/sdb is a raw copy of /dev/sda
did try to do this commands in frugal install linux:
xubunto=13.04
system rescuecd 2.8 and new one
parted magic 4.10
and others
in all linux cfdisk /dev/sdb show the same partition table
but gparted can not see /dev/sdb
and in sysrescuecd gparted can see blank 2TB /dev/sdb
no partitions I do not know why
all the changes is I did erase and encrypt one partition in /dev/sdb with
truecrypt 7.1a
why all linux can not stat /dev/sdb and what is it this stat ?
I try to copy one partition 500GB
sudo dcfldd if=/dev/sda12 of=/dev/sdb12
sudo dd if=/dev/sda12 of=/dev/sdb12
it do copy only 1GB it do it in to ram memory
after this /dev/sdb12 size is 1GB it is standard file not device
dd automatically is off and no count= is on in any command
all disks have no bad sectors smart is fully clean
md5sum /dev/sda and md5sum /dev/sdb is reading and thesame in
dcfldd if=/dev/sdb | md5sum
and all the time rebuildfstab script say can not stat device /dev/sdb
the sda 2TB disk is a boot disk
the sdb is also 2TB disk usb connected [in GUI after system start]
so all the same sizes the disk /dev/sdb is a raw copy of /dev/sda
did try to do this commands in frugal install linux:
xubunto=13.04
system rescuecd 2.8 and new one
parted magic 4.10
and others
in all linux cfdisk /dev/sdb show the same partition table
but gparted can not see /dev/sdb
and in sysrescuecd gparted can see blank 2TB /dev/sdb
no partitions I do not know why
all the changes is I did erase and encrypt one partition in /dev/sdb with
truecrypt 7.1a
why all linux can not stat /dev/sdb and what is it this stat ?
Wednesday, 28 August 2013
Python - Loop through list within regex
Python - Loop through list within regex
Right, i'm relatively new to Python, which you will likely see in my code,
but is there any way to iterate through a list within regex?
Basically, i'm looping through each filename within a folder, getting a
code (2-6 digits) from the filename, and i'm wanting to compare it with a
list of codes in a text file, which have a name attached, in the format
"1234_Name" (without the quotation marks). If the code exists in both
lists, I want to print out the list entry, i.e. 1234_Name. Currently my
code only seems to look at the first entry in the text file's list and i'm
not sure how to make it look through them all to find matches.
import os, re
sitesfile = open('C:/Users/me/My
Documents/WORK_PYTHON/Renaming/testnames.txt', 'r')
filefolder = r'C:/Users/me/My Documents/WORK_PYTHON/Renaming/files/'
sites = sitesfile.read()
site_split = re.split('\n', sites)
old = []
newname = []
for site in site_split:
newname.append(site)
for root, dirs, filenames in os.walk(filefolder):
for filename in filenames:
fullpath = os.path.join(root, filename)
filename_split = os.path.splitext(fullpath)
filename_zero, fileext = filename_split
filename_zs = re.split("/", filename_zero)
filenm = re.search(r"[\w]+", str(filename_zs[-1:]))#get only
filename, not path
filenmgrp = filenm.group()
pacode = re.search('\d\d+', filenmgrp)
if pacode:
pacodegrp = pacode.group()
match = re.match(pacodegrp, site)
if match:
print site
Hope this makes sense - thanks a lot in advance!
Right, i'm relatively new to Python, which you will likely see in my code,
but is there any way to iterate through a list within regex?
Basically, i'm looping through each filename within a folder, getting a
code (2-6 digits) from the filename, and i'm wanting to compare it with a
list of codes in a text file, which have a name attached, in the format
"1234_Name" (without the quotation marks). If the code exists in both
lists, I want to print out the list entry, i.e. 1234_Name. Currently my
code only seems to look at the first entry in the text file's list and i'm
not sure how to make it look through them all to find matches.
import os, re
sitesfile = open('C:/Users/me/My
Documents/WORK_PYTHON/Renaming/testnames.txt', 'r')
filefolder = r'C:/Users/me/My Documents/WORK_PYTHON/Renaming/files/'
sites = sitesfile.read()
site_split = re.split('\n', sites)
old = []
newname = []
for site in site_split:
newname.append(site)
for root, dirs, filenames in os.walk(filefolder):
for filename in filenames:
fullpath = os.path.join(root, filename)
filename_split = os.path.splitext(fullpath)
filename_zero, fileext = filename_split
filename_zs = re.split("/", filename_zero)
filenm = re.search(r"[\w]+", str(filename_zs[-1:]))#get only
filename, not path
filenmgrp = filenm.group()
pacode = re.search('\d\d+', filenmgrp)
if pacode:
pacodegrp = pacode.group()
match = re.match(pacodegrp, site)
if match:
print site
Hope this makes sense - thanks a lot in advance!
Design Pattern for separating a model from its graphical representation
Design Pattern for separating a model from its graphical representation
The Problem
I am looking for (hopefully) a design pattern I might be ignorant of that
can help be accomplish some code-separation for the problem I've defined
below:
I have a set of classes that represent various entities such as Point,
Vector, Arc, etc., that belong on a 2D Cartesian plane, represented by a
class Model. The Model class acts as a collection for these entities as
well as storing useful calculated values.
I also have a visual interface that should render a 2D image of the state
of the model, and can also interact with the model to a small degree by
adding entities to the model (for instance, the user can add a Point to
the model by clicking on the GUI somewhere.).
First Idea
At first, I had an interface Drawable that had one method, Draw, that
would accept a graphics context object, and the implementing entity would
draw itself to that context using the graphics libraries I am using (Java
Swing/AWT in this case).
This worked well in that the GUI portion of my application simply had to
loop through all of the entities in my model and run their Draw method to
generate the visualization. The big problem was that I was marrying my
model to its graphical representation, and I feel like this bad practice.
Second Idea
I created a EntityDrawer class that would accept an entity, choose a
correct drawing method based on the type of entity, then draw to my
graphics context.
This approach accomplished the code-separation I was looking for, but the
EntityDrawer class relied heavily on an instanceOf/isA approach to
determine how to draw the entity, which I have repeatedly seen described
as poor design. I tried redesigning this so that class used overloaded
methods to determine which drawing method to use, but I realized that this
was basically the same instanceOf/isA approach written in a nicer looking
way. Also, for every new entity class that I add, I would need to mirror
that in this EntityDrawer's code, which feels like a form of coupling to
me.
I would like to have as much decoupling between my model and its graphical
representation as possible, so that the model can focus on modeling a
problem and not on how to render itself to a graphics context.
Furthermore, it is likely that I will be adding more model entity types in
the future that will have drastically different drawing needs.
So, is there a pattern or design technique I can use to accomplish this? I
feel like the two solutions I came up with are sub optimal and that there
is probably a design pattern out there that can take care of exactly this
kind of problem.
The Problem
I am looking for (hopefully) a design pattern I might be ignorant of that
can help be accomplish some code-separation for the problem I've defined
below:
I have a set of classes that represent various entities such as Point,
Vector, Arc, etc., that belong on a 2D Cartesian plane, represented by a
class Model. The Model class acts as a collection for these entities as
well as storing useful calculated values.
I also have a visual interface that should render a 2D image of the state
of the model, and can also interact with the model to a small degree by
adding entities to the model (for instance, the user can add a Point to
the model by clicking on the GUI somewhere.).
First Idea
At first, I had an interface Drawable that had one method, Draw, that
would accept a graphics context object, and the implementing entity would
draw itself to that context using the graphics libraries I am using (Java
Swing/AWT in this case).
This worked well in that the GUI portion of my application simply had to
loop through all of the entities in my model and run their Draw method to
generate the visualization. The big problem was that I was marrying my
model to its graphical representation, and I feel like this bad practice.
Second Idea
I created a EntityDrawer class that would accept an entity, choose a
correct drawing method based on the type of entity, then draw to my
graphics context.
This approach accomplished the code-separation I was looking for, but the
EntityDrawer class relied heavily on an instanceOf/isA approach to
determine how to draw the entity, which I have repeatedly seen described
as poor design. I tried redesigning this so that class used overloaded
methods to determine which drawing method to use, but I realized that this
was basically the same instanceOf/isA approach written in a nicer looking
way. Also, for every new entity class that I add, I would need to mirror
that in this EntityDrawer's code, which feels like a form of coupling to
me.
I would like to have as much decoupling between my model and its graphical
representation as possible, so that the model can focus on modeling a
problem and not on how to render itself to a graphics context.
Furthermore, it is likely that I will be adding more model entity types in
the future that will have drastically different drawing needs.
So, is there a pattern or design technique I can use to accomplish this? I
feel like the two solutions I came up with are sub optimal and that there
is probably a design pattern out there that can take care of exactly this
kind of problem.
Django - Get string from ModelForm field label
Django - Get string from ModelForm field label
I've got the following: I want to add a string to my ModelForm field
labels. I want to do it in the form class.
I do this:
class MyForm(ModelForm):
class Meta():
model = MyEntity
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].label = "-- " + self.fields[key].label
I always get the following in my template:
-- django.utils.functional.proxy object at 0x04605E10>
The label contains in proxy___args under 0 the correct label. How can I
get this shitty label? Can't be that hard, can it?
Thanks!
I've got the following: I want to add a string to my ModelForm field
labels. I want to do it in the form class.
I do this:
class MyForm(ModelForm):
class Meta():
model = MyEntity
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].label = "-- " + self.fields[key].label
I always get the following in my template:
-- django.utils.functional.proxy object at 0x04605E10>
The label contains in proxy___args under 0 the correct label. How can I
get this shitty label? Can't be that hard, can it?
Thanks!
How to get div height 100% inside td of 100%
How to get div height 100% inside td of 100%
This question seems to have been asked at least 10 other times here on
stackoverflow but not one of them actually has an answer. This one is
slightly different in that the issue appears in Firefox.
I have a table height 100%, with a tr height 100%. I set the border of the
td to something I can see. I see that the td is 100% as expected. I put a
div in that td and set it to height 100%. It's 100% in Chrome. It's NOT
100% in Firefox.
How do I fix this?
Example
<!DOCTYPE html>
<html>
<head>
<style>
body, html {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
.full {
width: 100%;
height: 100%;
border: 10px solid red;
}
#content {
width: 100%;
height: 100%;
}
#content>table {
width: 100%;
height: 100%;
}
#content>table>tbody>tr>td {
border: 10px solid blue;
width: 50%;
}
#container {
width: 100%;
height: 100%;
border: 10px solid black;
}
</style>
</head>
<body>
<div id="content">
<table>
<tr>
<td>
<div id="container">
<div class="full">
foo
</div>
</div>
</td>
</table>
</div>
</body>
</html>
Here's a fiddle http://jsfiddle.net/greggman/F4ESJ/
You'll see
bbbbbbbbbbb
b#########b
b#rrrrrrr#b
b#r r#b
b#r r#b
b#r r#b
b#rrrrrrr#b
b#########b
bbbbbbbbbbb
In Chrome and
bbbbbbbbbbb
b b
b#########b
b#rrrrrrr#b
b#r r#b
b#rrrrrrr#b
b#########b
b b
bbbbbbbbbbb
where b = blue td. # = black div that should be 100%. r = red inner div
that should also be 100% (and apparently is in either case). It's the
black one that's wrong.
In Firefox. How do I get Firefox to behave like Chrome in this case?
PS: Yes I need a table. I'm displaying tabular data. The example above is
simplified to a single cell to simplify debugging.
This question seems to have been asked at least 10 other times here on
stackoverflow but not one of them actually has an answer. This one is
slightly different in that the issue appears in Firefox.
I have a table height 100%, with a tr height 100%. I set the border of the
td to something I can see. I see that the td is 100% as expected. I put a
div in that td and set it to height 100%. It's 100% in Chrome. It's NOT
100% in Firefox.
How do I fix this?
Example
<!DOCTYPE html>
<html>
<head>
<style>
body, html {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
.full {
width: 100%;
height: 100%;
border: 10px solid red;
}
#content {
width: 100%;
height: 100%;
}
#content>table {
width: 100%;
height: 100%;
}
#content>table>tbody>tr>td {
border: 10px solid blue;
width: 50%;
}
#container {
width: 100%;
height: 100%;
border: 10px solid black;
}
</style>
</head>
<body>
<div id="content">
<table>
<tr>
<td>
<div id="container">
<div class="full">
foo
</div>
</div>
</td>
</table>
</div>
</body>
</html>
Here's a fiddle http://jsfiddle.net/greggman/F4ESJ/
You'll see
bbbbbbbbbbb
b#########b
b#rrrrrrr#b
b#r r#b
b#r r#b
b#r r#b
b#rrrrrrr#b
b#########b
bbbbbbbbbbb
In Chrome and
bbbbbbbbbbb
b b
b#########b
b#rrrrrrr#b
b#r r#b
b#rrrrrrr#b
b#########b
b b
bbbbbbbbbbb
where b = blue td. # = black div that should be 100%. r = red inner div
that should also be 100% (and apparently is in either case). It's the
black one that's wrong.
In Firefox. How do I get Firefox to behave like Chrome in this case?
PS: Yes I need a table. I'm displaying tabular data. The example above is
simplified to a single cell to simplify debugging.
Magento REST API Error 500
Magento REST API Error 500
I am trying to get product information through Magento REST API; but
results an error starting " [message:protected] => Invalid auth/bad
request (got a 500, expected HTTP/1.1 20X or a redirect)
…...................." No idea why this occurs; can anybody please help me
on this ? My code follows:
$callbackUrl = "http://myhostcom/current_script.php";
$temporaryCredentialsRequestUrl =
"http://myhostcom/oauth/initiate?oauth_callback=" .
urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://myhostcom/oauth/authorize';
$accessTokenRequestUrl = 'http://myhostcom/oauth/token';
$apiUrl = 'http://myhostcom/api/rest';
$consumerKey = 'xxxxxx';
$consumerSecret = 'xxxxxxxxxxx';
echo '<pre/>';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) &&
$_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION
: OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret,
OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
$oauthClient->disableSSLChecks();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken =
$oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' .
$requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = $apiUrl."/products/465";
$oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e);
}
Thanks.
I am trying to get product information through Magento REST API; but
results an error starting " [message:protected] => Invalid auth/bad
request (got a 500, expected HTTP/1.1 20X or a redirect)
…...................." No idea why this occurs; can anybody please help me
on this ? My code follows:
$callbackUrl = "http://myhostcom/current_script.php";
$temporaryCredentialsRequestUrl =
"http://myhostcom/oauth/initiate?oauth_callback=" .
urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://myhostcom/oauth/authorize';
$accessTokenRequestUrl = 'http://myhostcom/oauth/token';
$apiUrl = 'http://myhostcom/api/rest';
$consumerKey = 'xxxxxx';
$consumerSecret = 'xxxxxxxxxxx';
echo '<pre/>';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) &&
$_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION
: OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret,
OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
$oauthClient->disableSSLChecks();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken =
$oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' .
$requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = $apiUrl."/products/465";
$oauthClient->fetch($resourceUrl);
$productsList = json_decode($oauthClient->getLastResponse());
print_r($productsList);
}
} catch (OAuthException $e) {
print_r($e);
}
Thanks.
Tuesday, 27 August 2013
Can't align image with text
Can't align image with text
I'm having problem aligning an image with text.
#content img{
border: 2px solid black;
vertical-align: middle;
}
<div id="content">
<h1><b>Company News 1</b></h1>
<img src="http://www.placehold.it/120x120">
<span style="">
A lot of text...
</span>
The result is this:
What am I doing wrong?
I'm having problem aligning an image with text.
#content img{
border: 2px solid black;
vertical-align: middle;
}
<div id="content">
<h1><b>Company News 1</b></h1>
<img src="http://www.placehold.it/120x120">
<span style="">
A lot of text...
</span>
The result is this:
What am I doing wrong?
Timeout Exception: Calling Soap API from Within a REST API
Timeout Exception: Calling Soap API from Within a REST API
I have a very odd problem. I have a REST API that does a few things like
save payment data etc. From withing that API I start building payment
object so I can fire off a payment to a Payment Gateway. This payment
gateway is a Soap API Using SoapHttpClientProtocol.
The problem I am having is that the Soap API Times out. I have a stack
trace that lead me to believe it is happening inside the framework
somewhere.
System.Net.WebException: Error: ConnectFailure (Connection timed out) --->
System.Net.Sockets.SocketException: Connection timed out
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP)
[0x00000] in <filename unknown>:0
at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request)
[0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult
asyncResult) [0x00000] in <filename unknown>:0
at System.Net.HttpWebRequest.GetRequestStream () [0x00000] in <filename
unknown>:0
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke
(System.String method_name, System.Object[] parameters) [0x00000] in
<filename unknown>:0
Above is the exception I got so I believe it is happening inside the
Invoke method. Here is the code which is in the proxy file.
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("paymenturl",
RequestNamespace="gatewayurl", ResponseNamespace="gatewayurl",
ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped,
Use=System.Web.Services.Description.SoapBindingUse.Literal)]
public string SubmitPayment(string trnXML) {
object[] results = this.Invoke("SubmitPayment", new object[] {
trnXML});
return ((string)(results[0]));
}
Does anyone know why this would happen?
Now the SOAP Payment API works though the UI. So if call it straight from
the UI I can make a payment and get a successful response back. When I do
it from the API it doesn't work.
Is this perhaps a Architectural problem which does not allow an API call
from within another API?
Has anyone come across anything like this before?
Any help will appreciated.
I have a very odd problem. I have a REST API that does a few things like
save payment data etc. From withing that API I start building payment
object so I can fire off a payment to a Payment Gateway. This payment
gateway is a Soap API Using SoapHttpClientProtocol.
The problem I am having is that the Soap API Times out. I have a stack
trace that lead me to believe it is happening inside the framework
somewhere.
System.Net.WebException: Error: ConnectFailure (Connection timed out) --->
System.Net.Sockets.SocketException: Connection timed out
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP)
[0x00000] in <filename unknown>:0
at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request)
[0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult
asyncResult) [0x00000] in <filename unknown>:0
at System.Net.HttpWebRequest.GetRequestStream () [0x00000] in <filename
unknown>:0
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke
(System.String method_name, System.Object[] parameters) [0x00000] in
<filename unknown>:0
Above is the exception I got so I believe it is happening inside the
Invoke method. Here is the code which is in the proxy file.
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("paymenturl",
RequestNamespace="gatewayurl", ResponseNamespace="gatewayurl",
ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped,
Use=System.Web.Services.Description.SoapBindingUse.Literal)]
public string SubmitPayment(string trnXML) {
object[] results = this.Invoke("SubmitPayment", new object[] {
trnXML});
return ((string)(results[0]));
}
Does anyone know why this would happen?
Now the SOAP Payment API works though the UI. So if call it straight from
the UI I can make a payment and get a successful response back. When I do
it from the API it doesn't work.
Is this perhaps a Architectural problem which does not allow an API call
from within another API?
Has anyone come across anything like this before?
Any help will appreciated.
time series regression data inputs
time series regression data inputs
I try to get a result in regression on LIBSVM I get the same problem on
single feature data or multivariate data
Suppose I try to find the price of sth, and I have the data for N days. I
give the day 1..N-1 price for X as independent variables, and i train it
with the day 2..N price as Dependent variables. So I try to get the next
day's price always.
When I get the solution (Y) on test data, surely I expect the data price
for the days (2..N for the test data). But i realized that the Y values
are always seems like the X values. When comparing the solution Y with X
values (1..N-1) days, results are more succesfull then (2..N) days.
In other words i expect the next day's values but the result is more
succesful on the same day again.
What's wrong with the approach?
I try to get a result in regression on LIBSVM I get the same problem on
single feature data or multivariate data
Suppose I try to find the price of sth, and I have the data for N days. I
give the day 1..N-1 price for X as independent variables, and i train it
with the day 2..N price as Dependent variables. So I try to get the next
day's price always.
When I get the solution (Y) on test data, surely I expect the data price
for the days (2..N for the test data). But i realized that the Y values
are always seems like the X values. When comparing the solution Y with X
values (1..N-1) days, results are more succesfull then (2..N) days.
In other words i expect the next day's values but the result is more
succesful on the same day again.
What's wrong with the approach?
Send growl message from linux to windows
Send growl message from linux to windows
Is there any way to send growl message from centos (command line) to
windows over network ,
I found this library https://github.com/mattn/gntp-send but I don't know
how to use it :(
Is there any way to send growl message from centos (command line) to
windows over network ,
I found this library https://github.com/mattn/gntp-send but I don't know
how to use it :(
Java GUI change location of a 'tile'
Java GUI change location of a 'tile'
I'm making an A* pathfinding application with a GUI. I have:
an enum TileType -
START(Color.GREEN), WALL(Color.BLACK), BLANK(new Color(240, 240, 240)),
END(Color.RED);
a Grid class -
public class Grid extends JPanel {
private final Color lineColour = new Color(200, 200, 200);
private Color defaultColour;
private final int pixelsPerTile;
private final int rows;
private final int columns;
private TileType[][] tiles;
public Grid(int rows, int columns, int pixelsPerTile) {
this.pixelsPerTile = pixelsPerTile;
this.rows = rows;
this.columns = columns;
this.tiles = new TileType[rows][columns];
this.setPreferredSize(new Dimension(rows * pixelsPerTile, columns *
pixelsPerTile));
setTile(rows / 2 - 5, columns / 2, TileType.START);
setTile(rows / 2 + 5, columns / 2, TileType.END);
}
public void resetBoard() {
for (int i = 0; i < tiles.length; i++) {
for (int j = 0; j < tiles[0].length; j++) {
if (getTile(i, j) != TileType.START && getTile(i, j) !=
TileType.END) {
tiles[i][j] = null;
}
}
}
}
public void removeTile(int x, int y) {
tiles[x][y] = TileType.BLANK;
}
public TileType getTile(int x, int y) {
return tiles[x][y];
}
public Point getTile(boolean start) {
for (int x = 0; x < tiles.length; x++) {
for (int y = 0; y < tiles[0].length; y++) {
if (tiles[x][y] == (start ? TileType.START : TileType.END)) {
return new Point(x, y);
}
}
}
return null;
}
public void setTile(int x, int y, TileType tile) {
if (getTile(x, y) != TileType.START && getTile(x, y) != TileType.END) {
tiles[x][y] = tile;
}
}
@Override
public void paint(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
for (int x = 0; x < columns; x++) {
for (int y = 0; y < columns; y++) {
if (getTile(x, y) != null) {
g.setColor(getTile(x, y).getColour());
g.fillRect(x * pixelsPerTile, y * pixelsPerTile,
pixelsPerTile, pixelsPerTile);
}
}
}
// have the grid appear on top of blank tiles
g.setColor(lineColour);
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
g.drawLine(x * pixelsPerTile, 0, x * pixelsPerTile, getHeight());
g.drawLine(0, y * pixelsPerTile, getWidth(), y * pixelsPerTile);
}
}
}
public int getPixelsPerTile() {
return pixelsPerTile;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
}
a Frame class - public class Frame extends JFrame {
private Grid grid;
public Frame() {
grid = new Grid(33, 33, 15); // odd so there is a definitive middle point
this.setAutoRequestFocus(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle("A* Path finder");
this.setBounds(new Rectangle((grid.getRows()) * grid.getPixelsPerTile(),
(grid.getColumns() + 2) * grid.getPixelsPerTile()));
this.setResizable(true);
this.add(grid);
this.setVisible(true);
this.getContentPane().addMouseListener(new MouseLsntr()); // fixes
alignment problems
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(5);
se.scheduleAtFixedRate(new RedrawGrid(), 0L, 20L, TimeUnit.MILLISECONDS);
}
private class RedrawGrid implements Runnable {
@Override
public void run() {
grid.repaint();
}
}
private class MouseLsntr implements MouseListener {
@Override
public void mouseClicked(MouseEvent me) {
int x = me.getX() / grid.getPixelsPerTile();
int y = me.getY() / grid.getPixelsPerTile();
switch (me.getButton()) {
case MouseEvent.BUTTON1:
if (grid.getTile(x, y) != TileType.WALL) {
grid.setTile(x, y, TileType.WALL);
System.out.println(String.format("(%d, %d) (%d, %d)
wall", x, y, x, y));
} else {
grid.removeTile(x, y);
System.out.println(String.format("(%d, %d) (%d, %d)
blank", x, y, x, y));
}
break;
}
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
}
}
When the user left clicks on a grid, they make a WALL at that location. If
it's already a WALL, it becomes BLANK. I want the user to be able to move
the START and END tile by clicking on it and then dragging to the location
they want to stop at, which I'm having trouble doing. Any help would be
appreciated since I've been stumped about this for a while now.
I'm making an A* pathfinding application with a GUI. I have:
an enum TileType -
START(Color.GREEN), WALL(Color.BLACK), BLANK(new Color(240, 240, 240)),
END(Color.RED);
a Grid class -
public class Grid extends JPanel {
private final Color lineColour = new Color(200, 200, 200);
private Color defaultColour;
private final int pixelsPerTile;
private final int rows;
private final int columns;
private TileType[][] tiles;
public Grid(int rows, int columns, int pixelsPerTile) {
this.pixelsPerTile = pixelsPerTile;
this.rows = rows;
this.columns = columns;
this.tiles = new TileType[rows][columns];
this.setPreferredSize(new Dimension(rows * pixelsPerTile, columns *
pixelsPerTile));
setTile(rows / 2 - 5, columns / 2, TileType.START);
setTile(rows / 2 + 5, columns / 2, TileType.END);
}
public void resetBoard() {
for (int i = 0; i < tiles.length; i++) {
for (int j = 0; j < tiles[0].length; j++) {
if (getTile(i, j) != TileType.START && getTile(i, j) !=
TileType.END) {
tiles[i][j] = null;
}
}
}
}
public void removeTile(int x, int y) {
tiles[x][y] = TileType.BLANK;
}
public TileType getTile(int x, int y) {
return tiles[x][y];
}
public Point getTile(boolean start) {
for (int x = 0; x < tiles.length; x++) {
for (int y = 0; y < tiles[0].length; y++) {
if (tiles[x][y] == (start ? TileType.START : TileType.END)) {
return new Point(x, y);
}
}
}
return null;
}
public void setTile(int x, int y, TileType tile) {
if (getTile(x, y) != TileType.START && getTile(x, y) != TileType.END) {
tiles[x][y] = tile;
}
}
@Override
public void paint(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
for (int x = 0; x < columns; x++) {
for (int y = 0; y < columns; y++) {
if (getTile(x, y) != null) {
g.setColor(getTile(x, y).getColour());
g.fillRect(x * pixelsPerTile, y * pixelsPerTile,
pixelsPerTile, pixelsPerTile);
}
}
}
// have the grid appear on top of blank tiles
g.setColor(lineColour);
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
g.drawLine(x * pixelsPerTile, 0, x * pixelsPerTile, getHeight());
g.drawLine(0, y * pixelsPerTile, getWidth(), y * pixelsPerTile);
}
}
}
public int getPixelsPerTile() {
return pixelsPerTile;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
}
a Frame class - public class Frame extends JFrame {
private Grid grid;
public Frame() {
grid = new Grid(33, 33, 15); // odd so there is a definitive middle point
this.setAutoRequestFocus(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle("A* Path finder");
this.setBounds(new Rectangle((grid.getRows()) * grid.getPixelsPerTile(),
(grid.getColumns() + 2) * grid.getPixelsPerTile()));
this.setResizable(true);
this.add(grid);
this.setVisible(true);
this.getContentPane().addMouseListener(new MouseLsntr()); // fixes
alignment problems
ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(5);
se.scheduleAtFixedRate(new RedrawGrid(), 0L, 20L, TimeUnit.MILLISECONDS);
}
private class RedrawGrid implements Runnable {
@Override
public void run() {
grid.repaint();
}
}
private class MouseLsntr implements MouseListener {
@Override
public void mouseClicked(MouseEvent me) {
int x = me.getX() / grid.getPixelsPerTile();
int y = me.getY() / grid.getPixelsPerTile();
switch (me.getButton()) {
case MouseEvent.BUTTON1:
if (grid.getTile(x, y) != TileType.WALL) {
grid.setTile(x, y, TileType.WALL);
System.out.println(String.format("(%d, %d) (%d, %d)
wall", x, y, x, y));
} else {
grid.removeTile(x, y);
System.out.println(String.format("(%d, %d) (%d, %d)
blank", x, y, x, y));
}
break;
}
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
}
}
When the user left clicks on a grid, they make a WALL at that location. If
it's already a WALL, it becomes BLANK. I want the user to be able to move
the START and END tile by clicking on it and then dragging to the location
they want to stop at, which I'm having trouble doing. Any help would be
appreciated since I've been stumped about this for a while now.
Will the constructor get called on orientation change?
Will the constructor get called on orientation change?
I have a simple class, where on my constructor i am calling a method. Will
the constructor be re-called on orientation change.
public class ClasName{
public ClassName(){
MethodCalled();
}
}
I have a simple class, where on my constructor i am calling a method. Will
the constructor be re-called on orientation change.
public class ClasName{
public ClassName(){
MethodCalled();
}
}
How to get result faster with MongoDB queries and index
How to get result faster with MongoDB queries and index
I am running a Rails App and using mongoid. I have created Account as a
Mongoid::Document in my rails app.
There is large amount of records in account document, I have added
compound index to fast the queries. but the performance of the application
is poor.
I tried to do explain on query the, but the indexOnly attribute is showing
as false value.
Can anyone please let me know what is the best way to create a compound
index.
How can I check that the query I have written is using the index properly?
Here is my Query
first_record = Account.where(column_1: 5, column_2: "xxxx", column_3:
"xxxxxx", column_4: "xxxxxxxxxxx", column_5: "xxxxxxxxx")
first_record.explain() => {"cursor"=>"BtreeCursor provider_5_params_idx",
"isMultiKey"=>false, "n"=>10320, "nscannedObjects"=>10320,
"nscanned"=>10320, "nscannedObjectsAllPlans"=>10320,
"nscannedAllPlans"=>10320, "scanAndOrder"=>false, "indexOnly"=>false,
"nYields"=>317, "nChunkSkips"=>0, "millis"=>222464,
"indexBounds"=>{"column_1"=>[[5, 5]], "column_2"=>[["xxxx", "xxxx"]],
"column_3"=>[["xxxxx", "xxxxx"]], "column_4"=>[["pxxxx", "xxxxxxx"]],
"column_5"=>[["xxxxxx", "xxxxxx"]]}, "allPlans"=>[{"cursor"=>"BtreeCursor
provider_5_params_idx", "n"=>10320, "nscannedObjects"=>10320,
"nscanned"=>10320, "indexBounds"=>{"column_1"=>[[5, 5]],
"column_2"=>[["xxxx", "xxxx"]], "column_3"=>[["xxxx", "xxxx"]],
"column_4"=>[["xxxx", "xxxxx"]], "column_5"=>[["xxxxx", "xxxxx"]]}}],
"oldPlan"=>{"cursor"=>"BtreeCursor provider_5_params_idx",
"indexBounds"=>{"column_1"=>[[5, 5]], "column_2"=>[["xxxx", "xxxx"]],
"column_3"=>[["xxxxx", "xxxxx"]], "column_4"=>[["xxxx", "xxxxx"]],
"column_5"=>[["xxxxx", "xxxxx"]]}}, "server"=>"xxxxxxxxx"}
Also I have created index with the following way.
db.account.ensureIndex({column_1:1,column_2:1,column_3:1,column_4:1,column_5:1},
{name:"provider_5_params_idx",background:true});
I am running a Rails App and using mongoid. I have created Account as a
Mongoid::Document in my rails app.
There is large amount of records in account document, I have added
compound index to fast the queries. but the performance of the application
is poor.
I tried to do explain on query the, but the indexOnly attribute is showing
as false value.
Can anyone please let me know what is the best way to create a compound
index.
How can I check that the query I have written is using the index properly?
Here is my Query
first_record = Account.where(column_1: 5, column_2: "xxxx", column_3:
"xxxxxx", column_4: "xxxxxxxxxxx", column_5: "xxxxxxxxx")
first_record.explain() => {"cursor"=>"BtreeCursor provider_5_params_idx",
"isMultiKey"=>false, "n"=>10320, "nscannedObjects"=>10320,
"nscanned"=>10320, "nscannedObjectsAllPlans"=>10320,
"nscannedAllPlans"=>10320, "scanAndOrder"=>false, "indexOnly"=>false,
"nYields"=>317, "nChunkSkips"=>0, "millis"=>222464,
"indexBounds"=>{"column_1"=>[[5, 5]], "column_2"=>[["xxxx", "xxxx"]],
"column_3"=>[["xxxxx", "xxxxx"]], "column_4"=>[["pxxxx", "xxxxxxx"]],
"column_5"=>[["xxxxxx", "xxxxxx"]]}, "allPlans"=>[{"cursor"=>"BtreeCursor
provider_5_params_idx", "n"=>10320, "nscannedObjects"=>10320,
"nscanned"=>10320, "indexBounds"=>{"column_1"=>[[5, 5]],
"column_2"=>[["xxxx", "xxxx"]], "column_3"=>[["xxxx", "xxxx"]],
"column_4"=>[["xxxx", "xxxxx"]], "column_5"=>[["xxxxx", "xxxxx"]]}}],
"oldPlan"=>{"cursor"=>"BtreeCursor provider_5_params_idx",
"indexBounds"=>{"column_1"=>[[5, 5]], "column_2"=>[["xxxx", "xxxx"]],
"column_3"=>[["xxxxx", "xxxxx"]], "column_4"=>[["xxxx", "xxxxx"]],
"column_5"=>[["xxxxx", "xxxxx"]]}}, "server"=>"xxxxxxxxx"}
Also I have created index with the following way.
db.account.ensureIndex({column_1:1,column_2:1,column_3:1,column_4:1,column_5:1},
{name:"provider_5_params_idx",background:true});
Monday, 26 August 2013
Find .gz file using original file
Find .gz file using original file
All,
I would like to retrieve a .gz file from a directory based on original
file name. Please let me know how to achieve the same.
Ex: In the below example, I know only original file name (02.txt), I need
to retrieve the file abc02.gz from that directory
GZ File Name Original File Name abc01.gz 01.txt abc02.gz 02.txt abc03.gz
03.txt
Regards, Praveen
All,
I would like to retrieve a .gz file from a directory based on original
file name. Please let me know how to achieve the same.
Ex: In the below example, I know only original file name (02.txt), I need
to retrieve the file abc02.gz from that directory
GZ File Name Original File Name abc01.gz 01.txt abc02.gz 02.txt abc03.gz
03.txt
Regards, Praveen
add element at run time in polymer component
add element at run time in polymer component
I am trying to create a ParagraphElement at run time and it to Div element
in a polymer component as follows:
<polymer-element name="my-element" extends="div">
<template>
<p>
<button on-click="updateMessage" data-msg="You clicked Show">Show
Message</button>
<button on-click="updateMessage" data-msg="You clicked Hide">Hide
Message</button>
<button on-click="addPelement" >Add P element</button>
</p>
<p id="message">{{ message }}</p> <!-- bind the message -->
<div id="mydiv"></div>
</template>
<script type="application/dart" src="my_element.dart"></script>
</polymer-element>
and dart file is as follows:
@CustomTag('my-element')
class MyElement extends PolymerElement with ObservableMixin {
@observable var message;
void updateMessage(Event e, var detail, Element target) {
message = target.attributes['data-msg']; // extract the data- attribute
}
void addPelement(Event e) {
var item = new ParagraphElement ();
item.text="new p element";
DivElement d = query("#mydiv");
d.children.add(item);
}
The line query("#mydiv") returns a null element.
I am trying to create a ParagraphElement at run time and it to Div element
in a polymer component as follows:
<polymer-element name="my-element" extends="div">
<template>
<p>
<button on-click="updateMessage" data-msg="You clicked Show">Show
Message</button>
<button on-click="updateMessage" data-msg="You clicked Hide">Hide
Message</button>
<button on-click="addPelement" >Add P element</button>
</p>
<p id="message">{{ message }}</p> <!-- bind the message -->
<div id="mydiv"></div>
</template>
<script type="application/dart" src="my_element.dart"></script>
</polymer-element>
and dart file is as follows:
@CustomTag('my-element')
class MyElement extends PolymerElement with ObservableMixin {
@observable var message;
void updateMessage(Event e, var detail, Element target) {
message = target.attributes['data-msg']; // extract the data- attribute
}
void addPelement(Event e) {
var item = new ParagraphElement ();
item.text="new p element";
DivElement d = query("#mydiv");
d.children.add(item);
}
The line query("#mydiv") returns a null element.
Puppy Linux cannot boot
Puppy Linux cannot boot
I have downloaded Puppy linux slacko-5.6-PAE.iso , then used Unetbootin to
burn it on my usb , when i am try to boot i am getting this message
puppy_slacko_5.6.0.sfs not found. Dropping out to initial-ramdisk
I have this file in my usb but I don't know why I am getting this.
I have downloaded Puppy linux slacko-5.6-PAE.iso , then used Unetbootin to
burn it on my usb , when i am try to boot i am getting this message
puppy_slacko_5.6.0.sfs not found. Dropping out to initial-ramdisk
I have this file in my usb but I don't know why I am getting this.
BreezeJS does not perform filtering ind database?
BreezeJS does not perform filtering ind database?
I am using the following query on the client:
var query =
breeze.EntityQuery.from("AllCustomers").where("CustomerId,"==",criteriaValue);
return this.manager.executeQuery(query)
which results in the following URL:
/breeze/myAPI/AllCustomers?$filter=CustomerId%20eq%2012
I have noticed that the filtering is not performed in the database (there
is no WHERE statemenet in dthe SQL executed by the database). I suspect,
that the reason for this is Breeze.WebApi.QueryHelper.WrapResult, which
calls Enumerable.ToList. The later converts IQueriable to list which
forces execution of the query before if is filtered by default Microsoft
OData implementation:
// if a select or expand was encountered we need to
// execute the DbQueries here, so that any exceptions thrown can be
properly returned.
// if we wait to have the query executed within the serializer, some
exceptions will not
// serialize properly.
queryResult = Enumerable.ToList((dynamic)queryResult);
queryResult = PostExecuteQuery((IEnumerable)queryResult);
Is this a bug in Breeze or am I doing something wrong?
I am using Oracle ODP.NET provider for entity framework.
I am using the following query on the client:
var query =
breeze.EntityQuery.from("AllCustomers").where("CustomerId,"==",criteriaValue);
return this.manager.executeQuery(query)
which results in the following URL:
/breeze/myAPI/AllCustomers?$filter=CustomerId%20eq%2012
I have noticed that the filtering is not performed in the database (there
is no WHERE statemenet in dthe SQL executed by the database). I suspect,
that the reason for this is Breeze.WebApi.QueryHelper.WrapResult, which
calls Enumerable.ToList. The later converts IQueriable to list which
forces execution of the query before if is filtered by default Microsoft
OData implementation:
// if a select or expand was encountered we need to
// execute the DbQueries here, so that any exceptions thrown can be
properly returned.
// if we wait to have the query executed within the serializer, some
exceptions will not
// serialize properly.
queryResult = Enumerable.ToList((dynamic)queryResult);
queryResult = PostExecuteQuery((IEnumerable)queryResult);
Is this a bug in Breeze or am I doing something wrong?
I am using Oracle ODP.NET provider for entity framework.
The sql connection worked in Visual Studio, but after while I can't connect
The sql connection worked in Visual Studio, but after while I can't connect
The sql connection worked in Visual Studio, but after while the connection
cannot be opened. I try web and windows connection. I can't connect in
both way
The sql connection worked in Visual Studio, but after while the connection
cannot be opened. I try web and windows connection. I can't connect in
both way
Running a public static void main in Groovy Eclipse
Running a public static void main in Groovy Eclipse
Here is my Groovy Class -
class MyClass {
static void main() {
println("Hello World");
}
...
How do I run this classin Eclipse STS?
Thanks
Here is my Groovy Class -
class MyClass {
static void main() {
println("Hello World");
}
...
How do I run this classin Eclipse STS?
Thanks
C# Convert mouse position to radiance
C# Convert mouse position to radiance
I have a "small" problem with my code that convert the mouse position to
radiance.
I need the mouse position to determine where the head of my robot must
point to. The code works and head turns ... but! It reaches max of pitch
too quickly.
As I am not exactly super sharp in radiance calculation or C#, I have to
resort to expert help. :)
My code:
maxcursory = Screen.PrimaryScreen.Bounds.Height;
cursory = Cursor.Position.Y;
pitch = (float) (((3 / maxcursory cursory *) - 1.5) * 1);
I have a "small" problem with my code that convert the mouse position to
radiance.
I need the mouse position to determine where the head of my robot must
point to. The code works and head turns ... but! It reaches max of pitch
too quickly.
As I am not exactly super sharp in radiance calculation or C#, I have to
resort to expert help. :)
My code:
maxcursory = Screen.PrimaryScreen.Bounds.Height;
cursory = Cursor.Position.Y;
pitch = (float) (((3 / maxcursory cursory *) - 1.5) * 1);
How to map a list of IDs into a lookup table with Automapper
How to map a list of IDs into a lookup table with Automapper
I have a DB tables called Departments, Users and DepartmentUsers
I want to allow the management of which Users belong to each Department.
I have a viewmodel which has
int DeptId
List<int> UserIds
and this helps show all users and whether they belong to this department
When I submit the form with the DeptId in the url, I want to update the
DepartmentUsers table with the newly selected users for this department
(some may have been de-selected)
How do I do this with AutoMapper? Prior to using AutoMapper, I'd have
cleared out the DepartmentUsers table for the selected DeptId and then
added them all back in again. I've been using AutoMapper for everything
else and would prefer to use it for this too
I have a DB tables called Departments, Users and DepartmentUsers
I want to allow the management of which Users belong to each Department.
I have a viewmodel which has
int DeptId
List<int> UserIds
and this helps show all users and whether they belong to this department
When I submit the form with the DeptId in the url, I want to update the
DepartmentUsers table with the newly selected users for this department
(some may have been de-selected)
How do I do this with AutoMapper? Prior to using AutoMapper, I'd have
cleared out the DepartmentUsers table for the selected DeptId and then
added them all back in again. I've been using AutoMapper for everything
else and would prefer to use it for this too
Server sends spam, how do I check what is spamming?
Server sends spam, how do I check what is spamming?
Recently we started with a new adminpanel, DirectAdmin. I've gotten a mail
this morning about one of domains sending spam. How do I check what is
sending it?
I've found an 'email usage' page, and there are alot of different senders,
which dont even exists (there are about 10 legit emailaccounts and alot
more are used for the spam).
I've checked /tmp, /var/tmp and /user/tmp for weird files, don't see
anything. I did top -s to see any weird processes, and psf afx to see
anything that looks odd.
The thing is im not very experienced with commandline and this type of
problem, the person who is, is on vacation. Any able to give me a push in
the right direction?
If it matters, it's a WordPress website, which I also dont have alot of
experience with (we normaly use our custom cms)
I just checked cronjobs because this seems to be a daily thing, no cronjobs
It is getting more every day, time to stop this:
Warning: 21005 emails have been sent yesterday by hfadmin Today at 00:10
Warning: 16479 emails have been sent yesterday by hfadmin 08/25/2013
Warning: 13305 emails have been sent yesterday by hfadmin 08/24/2013
Warning: 8663 emails have been sent yesterday by hfadmin 08/23/2013
Recently we started with a new adminpanel, DirectAdmin. I've gotten a mail
this morning about one of domains sending spam. How do I check what is
sending it?
I've found an 'email usage' page, and there are alot of different senders,
which dont even exists (there are about 10 legit emailaccounts and alot
more are used for the spam).
I've checked /tmp, /var/tmp and /user/tmp for weird files, don't see
anything. I did top -s to see any weird processes, and psf afx to see
anything that looks odd.
The thing is im not very experienced with commandline and this type of
problem, the person who is, is on vacation. Any able to give me a push in
the right direction?
If it matters, it's a WordPress website, which I also dont have alot of
experience with (we normaly use our custom cms)
I just checked cronjobs because this seems to be a daily thing, no cronjobs
It is getting more every day, time to stop this:
Warning: 21005 emails have been sent yesterday by hfadmin Today at 00:10
Warning: 16479 emails have been sent yesterday by hfadmin 08/25/2013
Warning: 13305 emails have been sent yesterday by hfadmin 08/24/2013
Warning: 8663 emails have been sent yesterday by hfadmin 08/23/2013
Sunday, 25 August 2013
How to store recorded data using Flash and store file in ASP.net
How to store recorded data using Flash and store file in ASP.net
I am recording sound in Flash Action script 3.0 and store data in php file
like this below code, I need to done this same task using ASP.net please
help me to do.
$recorder = file_get_cont`enter code here`ents('php://input');
$name = basename($recorder);
$status = move_uploaded_file($recorder,
'http://www.mysite.com/audiofiles/' . $name);
if($status){
echo 'WORK';
}
I am recording sound in Flash Action script 3.0 and store data in php file
like this below code, I need to done this same task using ASP.net please
help me to do.
$recorder = file_get_cont`enter code here`ents('php://input');
$name = basename($recorder);
$status = move_uploaded_file($recorder,
'http://www.mysite.com/audiofiles/' . $name);
if($status){
echo 'WORK';
}
Unable to upload "opencv_core242" after adding the files to application output directory
Unable to upload "opencv_core242" after adding the files to application
output directory
I am new to Emgu CV in C# and when I tried to set it up on my 64-bit
laptop, I added the required EmguCV .dll files as reference and the
related opencv .dll files to the project or put the opencv .dll files to
bin/debug folder in my project folder, I got the following error (I've
changed my targeted platform to x64 and downloaded the x64 package):
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=The type initializer for 'Emgu.CV.CvInvoke' threw an exception.
Source=Emgu.CV
TypeName=Emgu.CV.CvInvoke
InnerException: System.DllNotFoundException
HResult=-2146233052
Message=Unable to load DLL 'opencv_core242': The specified module
could not be found. (Exception from HRESULT: 0x8007007E)
Source=Emgu.CV
TypeName=""
StackTrace:
at Emgu.CV.CvInvoke.cvRedirectError(CvErrorCallback
errorHandler, IntPtr userdata, IntPtr prevUserdata)
at Emgu.CV.CvInvoke..cctor()
InnerException:
I've been stuck to this for a few days and really appreciate any help.
Thank you.
output directory
I am new to Emgu CV in C# and when I tried to set it up on my 64-bit
laptop, I added the required EmguCV .dll files as reference and the
related opencv .dll files to the project or put the opencv .dll files to
bin/debug folder in my project folder, I got the following error (I've
changed my targeted platform to x64 and downloaded the x64 package):
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=The type initializer for 'Emgu.CV.CvInvoke' threw an exception.
Source=Emgu.CV
TypeName=Emgu.CV.CvInvoke
InnerException: System.DllNotFoundException
HResult=-2146233052
Message=Unable to load DLL 'opencv_core242': The specified module
could not be found. (Exception from HRESULT: 0x8007007E)
Source=Emgu.CV
TypeName=""
StackTrace:
at Emgu.CV.CvInvoke.cvRedirectError(CvErrorCallback
errorHandler, IntPtr userdata, IntPtr prevUserdata)
at Emgu.CV.CvInvoke..cctor()
InnerException:
I've been stuck to this for a few days and really appreciate any help.
Thank you.
I need to encrypt video in vb.net 2010 and decry-pt it using adobe flash action script 3.. please help me
Best way to pass SDL objects in c++
Best way to pass SDL objects in c++
I started a small game in C++ using SDL. I have been looking into pointers
and references and I understand the differences. This question is similar
to others asked before but I had no luck finding exactly what I need.
int main(int argc, char* argv[])
{
SDL_Renderer* renderer = NULL;
TTF_Font* font = NULL;
renderer = SDL_CreateRenderer(window, -1, 0);
if(renderer == NULL)
{
return 1;
}
font = TTF_OpenFont("OpenSans.ttf", 12);
if(font == NULL)
{
return 1;
}
texture = renderText(...)
return 0;
}
SDL_Texture* renderText(...)
{
}
This is part of my program, now I need to pass the renderer and font
objects to the renderText() function. My question is, should I pass them
as pointers (which they already are), or as reference?
This is how I think it would look:
SDL_Texture* renderText(SDL_Renderer* renderer,...)
{
}
renderText(renderer,...)
or
SDL_Texture* renderText(SDL_Renderer &renderer,...)
{
}
renderText(*renderer,...)
Also later in renderText() func I have to pass pointer of the SDL_Renderer
into other SDL functions so I would have to use & again in the second
case. Thanks for help.
I started a small game in C++ using SDL. I have been looking into pointers
and references and I understand the differences. This question is similar
to others asked before but I had no luck finding exactly what I need.
int main(int argc, char* argv[])
{
SDL_Renderer* renderer = NULL;
TTF_Font* font = NULL;
renderer = SDL_CreateRenderer(window, -1, 0);
if(renderer == NULL)
{
return 1;
}
font = TTF_OpenFont("OpenSans.ttf", 12);
if(font == NULL)
{
return 1;
}
texture = renderText(...)
return 0;
}
SDL_Texture* renderText(...)
{
}
This is part of my program, now I need to pass the renderer and font
objects to the renderText() function. My question is, should I pass them
as pointers (which they already are), or as reference?
This is how I think it would look:
SDL_Texture* renderText(SDL_Renderer* renderer,...)
{
}
renderText(renderer,...)
or
SDL_Texture* renderText(SDL_Renderer &renderer,...)
{
}
renderText(*renderer,...)
Also later in renderText() func I have to pass pointer of the SDL_Renderer
into other SDL functions so I would have to use & again in the second
case. Thanks for help.
Does Android support different resolution on external HDMI display from the built-in LCD?
Does Android support different resolution on external HDMI display from
the built-in LCD?
Suppose the Galaxy Nexus just supports 1280X720 resolution on built-in
LCD. When I connect an external HDMI displayer, can I output full-HD
1920X1080 video/overlay to the HDMI?
I know in the UI mode, the real resolution just is as same as the built-in
LCD. The content was stretched to 1920X1080. But it is possible to display
video stream on it as real Full-HD?
Thank you very much!
the built-in LCD?
Suppose the Galaxy Nexus just supports 1280X720 resolution on built-in
LCD. When I connect an external HDMI displayer, can I output full-HD
1920X1080 video/overlay to the HDMI?
I know in the UI mode, the real resolution just is as same as the built-in
LCD. The content was stretched to 1920X1080. But it is possible to display
video stream on it as real Full-HD?
Thank you very much!
Saturday, 24 August 2013
Why is my jQuery function not being called correctly?
Why is my jQuery function not being called correctly?
I have this jQuery function that is using another jQuery library called
html5csv.js (which explains some of the CSV stuff you will see)
Here is it:
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
}
Here is how I am trying to call my function, from an onsubmit within my form:
<form method="post" action="createplay.php" onsubmit="return
validateNewQuiz();" enctype="multipart/form-data">
My function has been thoroughly tested, along with my regex to make sure
it was working. When I decided to implement it into my large document, and
wrap it around function validateNewQuiz(){ //my function here } , it
stopped working.
I did not make my tests with the onsubmit part within my form either.
Does anyone have any suggestions to why my form is always submitting, even
when my function should be returning false?
I have this jQuery function that is using another jQuery library called
html5csv.js (which explains some of the CSV stuff you will see)
Here is it:
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
}
Here is how I am trying to call my function, from an onsubmit within my form:
<form method="post" action="createplay.php" onsubmit="return
validateNewQuiz();" enctype="multipart/form-data">
My function has been thoroughly tested, along with my regex to make sure
it was working. When I decided to implement it into my large document, and
wrap it around function validateNewQuiz(){ //my function here } , it
stopped working.
I did not make my tests with the onsubmit part within my form either.
Does anyone have any suggestions to why my form is always submitting, even
when my function should be returning false?
Remove hex escape from string
Remove hex escape from string
I have the following hex as a string: "\xfe\xff". I'd like to convert this
to "feff". How do I do this?
The closest I got was "\xfe\xff".inspect.gsub("\\x", ""), which returns
"\"FEFF\"".
I have the following hex as a string: "\xfe\xff". I'd like to convert this
to "feff". How do I do this?
The closest I got was "\xfe\xff".inspect.gsub("\\x", ""), which returns
"\"FEFF\"".
Strings & Expressions in Plot Titles, Labels etc
Strings & Expressions in Plot Titles, Labels etc
I am trying to paste together user a user provided string and a fixed
string in a plot title.
A simple case that works, of course:
userTitle <- "user title" # Example 1
fullTitle <- paste(userTitle, ": Results", sep = "")
plot(1:10, main = fullTitle)
But what if the user's title contains an expression? Here's some things
I've tried:
# This works, but doesn't include the fixed string # Example 2
fullTitle <- bquote(.(userTitle))
plot(1:10, main = fullTitle)
Try to add the fixed string. Some things that don't quite work:
fullTitle <- bquote(.(userTitle)~':'~Results) # Example 3
plot(1:10, main = fullTitle) # title missing .(userTitle)
fullTitle <- bquote(paste("Results:", .(userTitle))) # Example 4
plot(1:10, main = fullTitle) # title missing .(userTitle)
But this example, from here works just fine.
x<- 232323
plot(1:10, main = bquote(paste(ARL[1], " curve for ", S^2, "; x=",.(x))))
My Example 4 looks pretty much exactly this last one, but doesn't behave
the same. There are so many combos of bquote, expression, substitute and
I've looked at a lot of answers, but I am likely missing something really
small. Any advice on how to get the user string and fixed string together
if the user string contains an expression in this case? Thanks.
I am trying to paste together user a user provided string and a fixed
string in a plot title.
A simple case that works, of course:
userTitle <- "user title" # Example 1
fullTitle <- paste(userTitle, ": Results", sep = "")
plot(1:10, main = fullTitle)
But what if the user's title contains an expression? Here's some things
I've tried:
# This works, but doesn't include the fixed string # Example 2
fullTitle <- bquote(.(userTitle))
plot(1:10, main = fullTitle)
Try to add the fixed string. Some things that don't quite work:
fullTitle <- bquote(.(userTitle)~':'~Results) # Example 3
plot(1:10, main = fullTitle) # title missing .(userTitle)
fullTitle <- bquote(paste("Results:", .(userTitle))) # Example 4
plot(1:10, main = fullTitle) # title missing .(userTitle)
But this example, from here works just fine.
x<- 232323
plot(1:10, main = bquote(paste(ARL[1], " curve for ", S^2, "; x=",.(x))))
My Example 4 looks pretty much exactly this last one, but doesn't behave
the same. There are so many combos of bquote, expression, substitute and
I've looked at a lot of answers, but I am likely missing something really
small. Any advice on how to get the user string and fixed string together
if the user string contains an expression in this case? Thanks.
Why three.js morph animation works only shadow?
Why three.js morph animation works only shadow?
I have created morph animation from Blender and use bone with IK. But it
doesn't works well. I can see an animation only shadow, not animate a
model.
I have created other model with morph animation, that was working well. I
didn't change the settings of three.js exporter.
Here is sample:
http://works.edo-m18.me/three.js/demos/03/json-ver/
This is working animation only shadow, why?
I have created morph animation from Blender and use bone with IK. But it
doesn't works well. I can see an animation only shadow, not animate a
model.
I have created other model with morph animation, that was working well. I
didn't change the settings of three.js exporter.
Here is sample:
http://works.edo-m18.me/three.js/demos/03/json-ver/
This is working animation only shadow, why?
What's a quick and dirty way to get "lapsed" members in WordPress configured with s2Member?
What's a quick and dirty way to get "lapsed" members in WordPress
configured with s2Member?
I have a default installation of WordPress configured with the membership
management plugin known as s2Member. What is a quick and dirty way to
return an array of "lapsed" members?
I assume this information is hidden somewhere in the user's metadata.
configured with s2Member?
I have a default installation of WordPress configured with the membership
management plugin known as s2Member. What is a quick and dirty way to
return an array of "lapsed" members?
I assume this information is hidden somewhere in the user's metadata.
The Lie exponential map and commuting elements
The Lie exponential map and commuting elements
By Baker–Campbell–Hausdorff formula, if $[v,w]=0$ for $v,w$ in the Lie
algebra $\mathfrak g$ of a Lie group $G$ then $exp(v)$ and $exp(w)$
commute in $G$.
Does anyone know a reference or a method of proof of the following partial
inverse: For $v,w$ sufficiently close to $0$ in $\mathfrak g$,
$exp(v)exp(w)=exp(w)exp(v)$ implies $[v,w]=0$?
Being sufficiently close to zero is of course necessary here.
By Baker–Campbell–Hausdorff formula, if $[v,w]=0$ for $v,w$ in the Lie
algebra $\mathfrak g$ of a Lie group $G$ then $exp(v)$ and $exp(w)$
commute in $G$.
Does anyone know a reference or a method of proof of the following partial
inverse: For $v,w$ sufficiently close to $0$ in $\mathfrak g$,
$exp(v)exp(w)=exp(w)exp(v)$ implies $[v,w]=0$?
Being sufficiently close to zero is of course necessary here.
Image Slider plugin repositioning images
Image Slider plugin repositioning images
Im having trouble with some images I have put in a wordpress slider plugin.
I am convinced it was fine last night though I didnt try it in other
browsers, and it is still fine in FF and Opera but in Chrome and IE, my
slider is in the right position as the pagination is correctly positioned
but the actual sliding images are 140px lower than they should be.
Not too sure whats causing this, it is not a plugin problem as I have
tried 2 different plugins and it is not a parent element problem as I have
changed the divs around.
Anyone shed some light on this?
my site
Im having trouble with some images I have put in a wordpress slider plugin.
I am convinced it was fine last night though I didnt try it in other
browsers, and it is still fine in FF and Opera but in Chrome and IE, my
slider is in the right position as the pagination is correctly positioned
but the actual sliding images are 140px lower than they should be.
Not too sure whats causing this, it is not a plugin problem as I have
tried 2 different plugins and it is not a parent element problem as I have
changed the divs around.
Anyone shed some light on this?
my site
Parsing XML and showing Parent-Child Data in Storyboard
Parsing XML and showing Parent-Child Data in Storyboard
Im currently making a project which parsed the XML below and show the
data, Im showing the data in a story board where the first TableView will
only show the main categories, in the case here its Main Name1 and Main
Name2, but what Im really trying to do is when i click on any main
category name it will navigate me to its own sub-category and not to any
other sub-category or to all, coz i tried doing it and its only showing me
all the rest of the sub-category.
<categories>
<category>
<name>Main Name1</name>
<description>given description</description>
<image> Link Here </image>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
</category>
<category>
<name>Main Name2</name>
<description>given description</description>
<image> Link Here </image>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
</category>
</categories>
My parsing code is like this
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString
*)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"category"] || [elementName
isEqualToString:@"sub_cat"]){
dataCurrent = [dataFileHolder alloc];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"name"]){
dataCurrent.nameLabel = currentList;
}
if ([elementName isEqualToString:@"description"]){
dataCurrent.descLabel = currentList;
}
if ([elementName isEqualToString:@"image"]) {
dataCurrent.imageLinkLabel = currentList;
}
if ([elementName isEqualToString:@"sub_name"]) {
dataCurrent.childNameLabel = currentList;
}
if ([elementName isEqualToString:@"sub_desc"]) {
dataCurrent.childDetailLabel = currentList;
}
if ([elementName isEqualToString:@"sub_image"]) {
dataCurrent.childImageLink = currentList;
}
if ([elementName isEqualToString:@"category"]) {
[_listPopulated addObject:dataCurrent];
dataCurrent = nil;
currentList = nil;
}
}
Im currently making a project which parsed the XML below and show the
data, Im showing the data in a story board where the first TableView will
only show the main categories, in the case here its Main Name1 and Main
Name2, but what Im really trying to do is when i click on any main
category name it will navigate me to its own sub-category and not to any
other sub-category or to all, coz i tried doing it and its only showing me
all the rest of the sub-category.
<categories>
<category>
<name>Main Name1</name>
<description>given description</description>
<image> Link Here </image>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
</category>
<category>
<name>Main Name2</name>
<description>given description</description>
<image> Link Here </image>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
<sub_cat>
<sub_name>Sub name</sub_name>
<sub_desc>sub cat description</sub_desc>
<sub_image> Link </sub_image>
</sub_cat>
</category>
</categories>
My parsing code is like this
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString
*)elementName namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"category"] || [elementName
isEqualToString:@"sub_cat"]){
dataCurrent = [dataFileHolder alloc];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:@"name"]){
dataCurrent.nameLabel = currentList;
}
if ([elementName isEqualToString:@"description"]){
dataCurrent.descLabel = currentList;
}
if ([elementName isEqualToString:@"image"]) {
dataCurrent.imageLinkLabel = currentList;
}
if ([elementName isEqualToString:@"sub_name"]) {
dataCurrent.childNameLabel = currentList;
}
if ([elementName isEqualToString:@"sub_desc"]) {
dataCurrent.childDetailLabel = currentList;
}
if ([elementName isEqualToString:@"sub_image"]) {
dataCurrent.childImageLink = currentList;
}
if ([elementName isEqualToString:@"category"]) {
[_listPopulated addObject:dataCurrent];
dataCurrent = nil;
currentList = nil;
}
}
how to parse json in blackberry 5?
how to parse json in blackberry 5?
I try to parse json data in blackberry 5 but i get error that
net.rim.json.org
not found.
This works fine in bb7. what can i do for bb 5. If i cant use that package
means which package should i use.
This is my code
JSONObject NewsList= new JSONObject(response).getJSONObject("NewsList");
JSONArray jArray = NewsList.getJSONArray("News");
for(int i=0;i<jArray.length();i++)
{
JSONObject jObject = jArray.getJSONObject(i);
String articleid = jObject.getString("articleid");
String headline = jObject.getString("headline");
String abstrac = jObject.getString("abstract");
String imgurl = jObject.getString("Articleid");
}
I try to parse json data in blackberry 5 but i get error that
net.rim.json.org
not found.
This works fine in bb7. what can i do for bb 5. If i cant use that package
means which package should i use.
This is my code
JSONObject NewsList= new JSONObject(response).getJSONObject("NewsList");
JSONArray jArray = NewsList.getJSONArray("News");
for(int i=0;i<jArray.length();i++)
{
JSONObject jObject = jArray.getJSONObject(i);
String articleid = jObject.getString("articleid");
String headline = jObject.getString("headline");
String abstrac = jObject.getString("abstract");
String imgurl = jObject.getString("Articleid");
}
Friday, 23 August 2013
Questions About DRBD
Questions About DRBD
Backround: We are in need of a HA server in a small office environment and
DRBD looks like it has some synchronization issues at times (like during
updates). We only have about 100GB that needs to be on the HA server and
server load will be extremely low. The data will probably increase about
10%-25% per year if we archive older office data, and 50%-75% each year if
we don't.
Point is we use a mix of consumer grade and used enterprise grade hardware
which WILL be a problem if we don't preemptively plan for it; and
pre-built quality servers DO fail, so redundant servers seems like the way
to go.
The Plan: We are thinking it would be good to find (2) of the best
bang-for-our-buck used servers and synchronize them. We simply need
SATA/SAS and space for as many drives as can be had for the price. These
servers seem like they can be had for $100-$200 (+some parts and
additional drives) if you catch a deal.
This would theoretically mean a server could fail and if we took days to
get to it, as long as we didn't have another coincidental failure (servers
don't break that often when you have two or three), things would still hum
along until our IT department (me) could get to it. We would use Debian as
an OS.
Some Questions
(A) How does DRBD handle controller failure? That is This shows DRBD
before the storage driver, so what happens when the controller fails and
writes dirty data? Is the data mirrored to the other server or not and is
there risk of data corruption across servers in cases like these?
(B) What are the fail points for DRBD; that is theoretically as long as
one server is up and running there are no issues EVER. But we know that
there are issues so what are the fail modes using DRBD since most of them
should theoretically be software? (For RAID you mainly have drive failure,
controller failure, software errors, and user errors; how about DRBD?)
If we are going to have two servers for this, would it be reasonable to
run VM's on each with MYSQL and Apache for database and web server
replication? (I am assuming so)
Is DRBD reliable enough? If not, is the unreliability isolated to certain
tasks, or is it more random. Searching turned up people with various issue
but this IS the internet with seemingly more bad info than good.
If data is being synchronized over LAN, does DRBD use double the
bandwidth? That is, should we double up on NICS and do some link
aggregation and trunking? Then maybe put them on separate routers on
separate circuits and UPS's in separate rooms and now you really have some
redundancy!
Is this too crazy for an office in terms of server management? Is there a
simpler REALTIME alternative (granted DRBD seems simple in theory).
We already have a server. So it seems to me a second server with a
dedicated drive for DRBD could easily be had for around $150-$250 with
some smart shopping. Add a second router, more drives, more NIC's (Used),
and (2) UPS's and were talking $1,000 +/-. That is relatively cheap! And I
am hoping this would mainly buy us time during a server fault. Drive
failures don't worry me at all with RAID these days. It's other hardware
failures like controllers, memory, or power supplies that might require
downtime to diagnose and fix that are the concern.
Redundant servers for us means used hardware becomes more viable with more
up time and more flexibility for me to fix things when my schedule allows
vs having to stop everything to repair the server or incurr the cost of
calling an IT tech (I'm fast enough for our system it is cheaper for me to
perform diagnosis and repairs)
Anyone out there who knows this stuff?
Hopefully I didn't miss that these questions have easy searchable answers.
I did a quick search and didn't find what I was looking for.
Backround: We are in need of a HA server in a small office environment and
DRBD looks like it has some synchronization issues at times (like during
updates). We only have about 100GB that needs to be on the HA server and
server load will be extremely low. The data will probably increase about
10%-25% per year if we archive older office data, and 50%-75% each year if
we don't.
Point is we use a mix of consumer grade and used enterprise grade hardware
which WILL be a problem if we don't preemptively plan for it; and
pre-built quality servers DO fail, so redundant servers seems like the way
to go.
The Plan: We are thinking it would be good to find (2) of the best
bang-for-our-buck used servers and synchronize them. We simply need
SATA/SAS and space for as many drives as can be had for the price. These
servers seem like they can be had for $100-$200 (+some parts and
additional drives) if you catch a deal.
This would theoretically mean a server could fail and if we took days to
get to it, as long as we didn't have another coincidental failure (servers
don't break that often when you have two or three), things would still hum
along until our IT department (me) could get to it. We would use Debian as
an OS.
Some Questions
(A) How does DRBD handle controller failure? That is This shows DRBD
before the storage driver, so what happens when the controller fails and
writes dirty data? Is the data mirrored to the other server or not and is
there risk of data corruption across servers in cases like these?
(B) What are the fail points for DRBD; that is theoretically as long as
one server is up and running there are no issues EVER. But we know that
there are issues so what are the fail modes using DRBD since most of them
should theoretically be software? (For RAID you mainly have drive failure,
controller failure, software errors, and user errors; how about DRBD?)
If we are going to have two servers for this, would it be reasonable to
run VM's on each with MYSQL and Apache for database and web server
replication? (I am assuming so)
Is DRBD reliable enough? If not, is the unreliability isolated to certain
tasks, or is it more random. Searching turned up people with various issue
but this IS the internet with seemingly more bad info than good.
If data is being synchronized over LAN, does DRBD use double the
bandwidth? That is, should we double up on NICS and do some link
aggregation and trunking? Then maybe put them on separate routers on
separate circuits and UPS's in separate rooms and now you really have some
redundancy!
Is this too crazy for an office in terms of server management? Is there a
simpler REALTIME alternative (granted DRBD seems simple in theory).
We already have a server. So it seems to me a second server with a
dedicated drive for DRBD could easily be had for around $150-$250 with
some smart shopping. Add a second router, more drives, more NIC's (Used),
and (2) UPS's and were talking $1,000 +/-. That is relatively cheap! And I
am hoping this would mainly buy us time during a server fault. Drive
failures don't worry me at all with RAID these days. It's other hardware
failures like controllers, memory, or power supplies that might require
downtime to diagnose and fix that are the concern.
Redundant servers for us means used hardware becomes more viable with more
up time and more flexibility for me to fix things when my schedule allows
vs having to stop everything to repair the server or incurr the cost of
calling an IT tech (I'm fast enough for our system it is cheaper for me to
perform diagnosis and repairs)
Anyone out there who knows this stuff?
Hopefully I didn't miss that these questions have easy searchable answers.
I did a quick search and didn't find what I was looking for.
How deselect row in grid of devexpress - winforms
How deselect row in grid of devexpress - winforms
I have one grid with property MiltiSelected in false, and I need clear the
selection in the current grid when the user clicked one button, I saw de
documentation about two method but is not working when the user only can
select one row. here my attempts for solve this.
gridView1.ClearSelection();
foreach (var i in gridView1.GetSelectedRows())
gridView1.UnselectRow(i);
I hope someone help me , thanks in advance
I have one grid with property MiltiSelected in false, and I need clear the
selection in the current grid when the user clicked one button, I saw de
documentation about two method but is not working when the user only can
select one row. here my attempts for solve this.
gridView1.ClearSelection();
foreach (var i in gridView1.GetSelectedRows())
gridView1.UnselectRow(i);
I hope someone help me , thanks in advance
asp.net - MVC model binding to nested collection
asp.net - MVC model binding to nested collection
I have a class:
public class ClientInformation{
public string UserName {get; set;}
public ICollection<RegionDistrictCity> RegionDistrictCity
{
get;
set;
}
public class RegionDistrictCity
{
public string Region { get; set; }
public string District { get; set; }
public string City { get; set; }
}
}
How should be formated the name attribute of input elements for properties
Region, Distirct, City in html in order to make model binder populate
collection "ICollection RegionDistrictCity"?
I tried to have an action method with parameter of type
"ClientInformation" and html name attributes formated like
"[index].PropertyName" but in that case only the property "UserName" is
binded.
I tried to have action method with parameter name "client" and have html
names attributes formated like "client[index].PropertyName" but it doesn't
work. (in tha case if I there is a "List client" then it would get
populated)
Thanks.
I have a class:
public class ClientInformation{
public string UserName {get; set;}
public ICollection<RegionDistrictCity> RegionDistrictCity
{
get;
set;
}
public class RegionDistrictCity
{
public string Region { get; set; }
public string District { get; set; }
public string City { get; set; }
}
}
How should be formated the name attribute of input elements for properties
Region, Distirct, City in html in order to make model binder populate
collection "ICollection RegionDistrictCity"?
I tried to have an action method with parameter of type
"ClientInformation" and html name attributes formated like
"[index].PropertyName" but in that case only the property "UserName" is
binded.
I tried to have action method with parameter name "client" and have html
names attributes formated like "client[index].PropertyName" but it doesn't
work. (in tha case if I there is a "List client" then it would get
populated)
Thanks.
How can I implement a Proportional Integral Derivative (PID) on an android app?
How can I implement a Proportional Integral Derivative (PID) on an android
app?
I would like to implement a Propotional-Integral- Derivative (PID)
controller on android app. Please how can I achieve this?
app?
I would like to implement a Propotional-Integral- Derivative (PID)
controller on android app. Please how can I achieve this?
Get error 404 from HttpHandler
Get error 404 from HttpHandler
I want to run my httphandler, when some user get access to image file with
extentions like png, jpeg, gif and other. But i get eror 404 when i try to
path. I think what server try find file on a disk, but i want use alias
for access to file in my handler and newer access for real phisical file
path.
Example config file:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="GET,HEAD" path="*.jpg" type="Startup.Shop.ImageHandler,
Startup.Shop" validate="false"/>
</httpHandlers>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<handlers>
<add name="ImageHandlerfor JPG" path="*.jpg" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
<add name="ImageHandler for GIF" path="*.gif" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
<add name="ImageHandler for BMP" path="*.bmp" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
<add name="ImageHandler for PNG" path="*.png" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
</handlers>
</system.webServer>
/configuration>
Example handler class:
public class ImageHandler : IHttpHandler, IRouteHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
}
And more - iis server configurated as classic mode
I want to run my httphandler, when some user get access to image file with
extentions like png, jpeg, gif and other. But i get eror 404 when i try to
path. I think what server try find file on a disk, but i want use alias
for access to file in my handler and newer access for real phisical file
path.
Example config file:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="GET,HEAD" path="*.jpg" type="Startup.Shop.ImageHandler,
Startup.Shop" validate="false"/>
</httpHandlers>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<handlers>
<add name="ImageHandlerfor JPG" path="*.jpg" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
<add name="ImageHandler for GIF" path="*.gif" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
<add name="ImageHandler for BMP" path="*.bmp" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
<add name="ImageHandler for PNG" path="*.png" verb="GET"
type="Startup.Shop.ImageHandler, Startup.Shop"
resourceType="Unspecified" />
</handlers>
</system.webServer>
/configuration>
Example handler class:
public class ImageHandler : IHttpHandler, IRouteHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
}
And more - iis server configurated as classic mode
phonegap push plugin class not found
phonegap push plugin class not found
I'm trying to add a push plugin on my android version of phonegap.
(https://github.com/phonegap-build/PushPlugin)
But I have a problem when I launch I have an error:
08-23 11:35:12.849: W/System.err(22031): Caused by:
java.lang.ClassNotFoundException: com.plugin.GCM.PushPlugin
I think the config.xml is trying to load the PushPlugin:
<plugin name="PushPlugin" value="com.plugin.gcm.PushPlugin" />
But I don't understand because my file exist.
com
plugin
gcm
PushPlugin.java
In the error gcm is on upper case this is maybe the error but I don't know
how to correct it
I'm trying to add a push plugin on my android version of phonegap.
(https://github.com/phonegap-build/PushPlugin)
But I have a problem when I launch I have an error:
08-23 11:35:12.849: W/System.err(22031): Caused by:
java.lang.ClassNotFoundException: com.plugin.GCM.PushPlugin
I think the config.xml is trying to load the PushPlugin:
<plugin name="PushPlugin" value="com.plugin.gcm.PushPlugin" />
But I don't understand because my file exist.
com
plugin
gcm
PushPlugin.java
In the error gcm is on upper case this is maybe the error but I don't know
how to correct it
Thursday, 22 August 2013
ANDROID: How To Calculate Frames Per Second (FPS) in SurfaceView Class?
ANDROID: How To Calculate Frames Per Second (FPS) in SurfaceView Class?
if someone could just give me a small code of how to calculate the frames
per second of my screen that would be just great.
This is my basic code, though you might not need this.
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
public class MainGame extends Activity implements OnTouchListener
{
MyBringBackSurface ourSurfaceView;
inr xpos = 0;
@ Override
protected void onCreate (Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate (savedInstanceState);
ourSurfaceView = new MyBringBackSurface (this);
ourSurfaceView.setOnTouchListener (this);
x [0] = 0;
y [0] = 0;
x [1] = 0;
y [1] = 0;
requestWindowFeature (Window.FEATURE_NO_TITLE);
getWindow ().addFlags
(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
/////////////////////check this NEWLY ADDED
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
/////////////////////////////////////////////////CHECK THIS MIGHT NOT
WORK
setContentView (ourSurfaceView); //ourSurfaceView
}
@ Override
protected void onPause ()
{
// TODO Auto-generated method stub
super.onPause ();
ourSurfaceView.pause ();
}
@ Override
protected void onResume ()
{
// TODO Auto-generated method stub
super.onResume ();
ourSurfaceView.resume ();
}
public class MyBringBackSurface extends SurfaceView implements Runnable
{
//vertical
SurfaceHolder ourHolder;
Canvas canvas = (Canvas) ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public MyBringBackSurface (Context context)
{
// TODO Auto-generated constructor stub
super (context);
ourHolder = getHolder ();
}
public void pause ()
{
isRunning = false;
while (true)
{
try
{
ourThread.join ();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace ();
}
break;
}
ourThread = null;
}
public void resume ()
{
isRunning = true;
ourThread = new Thread (this);
ourThread.start ();
}
public void run ()
{
// TODO Auto-generated method stub
while (isRunning)
{
if (!ourHolder.getSurface ().isValid ())
continue;
canvas = ourHolder.lockCanvas ();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawCircle(xpos,33,23,paint);
if(x<canvas.getWidth()){
xpos++;
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
PLEASE GIVE ME A SIMPLE WORKING CODE Thanks
if someone could just give me a small code of how to calculate the frames
per second of my screen that would be just great.
This is my basic code, though you might not need this.
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
public class MainGame extends Activity implements OnTouchListener
{
MyBringBackSurface ourSurfaceView;
inr xpos = 0;
@ Override
protected void onCreate (Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate (savedInstanceState);
ourSurfaceView = new MyBringBackSurface (this);
ourSurfaceView.setOnTouchListener (this);
x [0] = 0;
y [0] = 0;
x [1] = 0;
y [1] = 0;
requestWindowFeature (Window.FEATURE_NO_TITLE);
getWindow ().addFlags
(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
/////////////////////check this NEWLY ADDED
getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
/////////////////////////////////////////////////CHECK THIS MIGHT NOT
WORK
setContentView (ourSurfaceView); //ourSurfaceView
}
@ Override
protected void onPause ()
{
// TODO Auto-generated method stub
super.onPause ();
ourSurfaceView.pause ();
}
@ Override
protected void onResume ()
{
// TODO Auto-generated method stub
super.onResume ();
ourSurfaceView.resume ();
}
public class MyBringBackSurface extends SurfaceView implements Runnable
{
//vertical
SurfaceHolder ourHolder;
Canvas canvas = (Canvas) ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public MyBringBackSurface (Context context)
{
// TODO Auto-generated constructor stub
super (context);
ourHolder = getHolder ();
}
public void pause ()
{
isRunning = false;
while (true)
{
try
{
ourThread.join ();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace ();
}
break;
}
ourThread = null;
}
public void resume ()
{
isRunning = true;
ourThread = new Thread (this);
ourThread.start ();
}
public void run ()
{
// TODO Auto-generated method stub
while (isRunning)
{
if (!ourHolder.getSurface ().isValid ())
continue;
canvas = ourHolder.lockCanvas ();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawCircle(xpos,33,23,paint);
if(x<canvas.getWidth()){
xpos++;
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
PLEASE GIVE ME A SIMPLE WORKING CODE Thanks
right-click (xdg-open) opened up some opaque windows covering my screen; xkill won't kill them
right-click (xdg-open) opened up some opaque windows covering my screen;
xkill won't kill them
I right-clicked on something in chromium with relatively low memory.
Chromium opened up some opaque right-click boxes and never filled them in
and won't kill them. These are now covering part of all of my virtual
desktops. (not virtual console though)
I got information on them with xprop and xwininfo. Here's an example from
each:
$ xprop
WM_HINTS(WM_HINTS):
Client accepts input or input focus: True
Initial state is Normal State.
window id # of group leader: 0x7600001
_NET_WM_SYNC_REQUEST_COUNTER(CARDINAL) = 125152843
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_POPUP_MENU
_NET_WM_USER_TIME(CARDINAL) = 3142781307
_NET_WM_USER_TIME_WINDOW(WINDOW): window id # 0x775aca9
WM_CLIENT_LEADER(WINDOW): window id # 0x7600001
_NET_WM_PID(CARDINAL) = 23912
WM_LOCALE_NAME(STRING) = "en_US.UTF-8"
WM_CLIENT_MACHINE(STRING) = "scheherezade"
WM_NORMAL_HINTS(WM_SIZE_HINTS):
program specified location: 0, 0
program specified minimum size: 247 by 140
program specified maximum size: 247 by 140
window gravity: NorthWest
WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS,
_NET_WM_PING, _NET_WM_SYNC_REQUEST
WM_CLASS(STRING) = "chromium-browser", "Chromium-browser"
WM_ICON_NAME(STRING) = "Chromium"
_NET_WM_ICON_NAME(UTF8_STRING) = "Chromium"
WM_NAME(STRING) = "Chromium"
_NET_WM_NAME(UTF8_STRING) = "Chromium"
and
$ xwininfo
xwininfo: Please select the window about which you
would like information by clicking the
mouse in that window.
xwininfo: Window id: 0x775ac2d "Chromium"
Absolute upper-left X: 591
Absolute upper-left Y: 614
Relative upper-left X: 591
Relative upper-left Y: 614
Width: 247
Height: 140
Depth: 24
Visual: 0x21
Visual Class: TrueColor
Border width: 0
Class: InputOutput
Colormap: 0x20 (installed)
Bit Gravity State: NorthWestGravity
Window Gravity State: NorthWestGravity
Backing Store State: NotUseful
Save Under State: yes
Map State: IsViewable
Override Redirect State: yes
Corners: +591+614 -562+614 -562-296 +591-296
-geometry 247x140+591+614
xkill doesn't clear the zombie dialogs away. Neither does killall
xdg-open. There are some defunct Chromium processes in ps -u $USER -o
comm. Someone suggested killing X but I want to keep all my tabs open.
This is Ubuntu 12.04, Awesome Window Manager, no compositing.
xkill won't kill them
I right-clicked on something in chromium with relatively low memory.
Chromium opened up some opaque right-click boxes and never filled them in
and won't kill them. These are now covering part of all of my virtual
desktops. (not virtual console though)
I got information on them with xprop and xwininfo. Here's an example from
each:
$ xprop
WM_HINTS(WM_HINTS):
Client accepts input or input focus: True
Initial state is Normal State.
window id # of group leader: 0x7600001
_NET_WM_SYNC_REQUEST_COUNTER(CARDINAL) = 125152843
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_POPUP_MENU
_NET_WM_USER_TIME(CARDINAL) = 3142781307
_NET_WM_USER_TIME_WINDOW(WINDOW): window id # 0x775aca9
WM_CLIENT_LEADER(WINDOW): window id # 0x7600001
_NET_WM_PID(CARDINAL) = 23912
WM_LOCALE_NAME(STRING) = "en_US.UTF-8"
WM_CLIENT_MACHINE(STRING) = "scheherezade"
WM_NORMAL_HINTS(WM_SIZE_HINTS):
program specified location: 0, 0
program specified minimum size: 247 by 140
program specified maximum size: 247 by 140
window gravity: NorthWest
WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS,
_NET_WM_PING, _NET_WM_SYNC_REQUEST
WM_CLASS(STRING) = "chromium-browser", "Chromium-browser"
WM_ICON_NAME(STRING) = "Chromium"
_NET_WM_ICON_NAME(UTF8_STRING) = "Chromium"
WM_NAME(STRING) = "Chromium"
_NET_WM_NAME(UTF8_STRING) = "Chromium"
and
$ xwininfo
xwininfo: Please select the window about which you
would like information by clicking the
mouse in that window.
xwininfo: Window id: 0x775ac2d "Chromium"
Absolute upper-left X: 591
Absolute upper-left Y: 614
Relative upper-left X: 591
Relative upper-left Y: 614
Width: 247
Height: 140
Depth: 24
Visual: 0x21
Visual Class: TrueColor
Border width: 0
Class: InputOutput
Colormap: 0x20 (installed)
Bit Gravity State: NorthWestGravity
Window Gravity State: NorthWestGravity
Backing Store State: NotUseful
Save Under State: yes
Map State: IsViewable
Override Redirect State: yes
Corners: +591+614 -562+614 -562-296 +591-296
-geometry 247x140+591+614
xkill doesn't clear the zombie dialogs away. Neither does killall
xdg-open. There are some defunct Chromium processes in ps -u $USER -o
comm. Someone suggested killing X but I want to keep all my tabs open.
This is Ubuntu 12.04, Awesome Window Manager, no compositing.
Unpermitted parameters: assets_attributes
Unpermitted parameters: assets_attributes
Ruby Version: 2.0
Rails Version: 4.0
I have found a hundred questions with similar situations to mine, but none
of the answers seem to work for me.
I am using paperclip and attempting to upload multiple images to an
article. I have an assets model to accomplish this.
I have nested the model inside the article form here:
<%= form_for(@article, :html => { :multipart => true }) do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited this
article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<%= f.fields_for :assets do |asset| %>
<%= asset.file_field :image %><br />
<% end %>
<div class="actions">
<%= f.submit %>
<% end %>
And whitelisted the model and (what I assume to be) its only attribute -
image
def article_params
params.require(:article).permit(:title, :content)
end
def asset_params
params.require(:asset).permit(:image)
end
Yet I am still getting this in my development log when I try to create a
new article with an image:
Unpermitted parameters: assets_attributes
What am I missing? (additional resources below):
article.rb
class Article < ActiveRecord::Base
has_many :assets
accepts_nested_attributes_for :assets
end
asset.rb
class Asset < ActiveRecord::Base
belongs_to :article
has_attached_file :image,
:styles => {
:thumb => '150x150#',
:medium => '300x300>',
:large => '600x600>'
}
end
full dump from development log
Started POST "/articles" for 127.0.0.1 at 2013-08-22 18:36:46 -0500
Processing by ArticlesController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"8x5YJgZV7PsQkqxMM3nOvEZ5Zr4m7tKy8FAiQayvTrI=",
"article"=>{"title"=>"Test", "content"=>"Test",
"assets_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fd3fbcf2bb0
@tempfile=#<Tempfile:/var/folders/ws/xtl93rn97nv1n1l61kzr9m0m0000gn/T/RackMultipart20130822-11705-evlabr>,
@original_filename="PLunKmQ.jpg", @content_type="image/jpeg",
@headers="Content-Disposition: form-data;
name=\"article[assets_attributes][0][image]\";
filename=\"PLunKmQ.jpg\"\r\nContent-Type: image/jpeg\r\n">}}},
"commit"=>"Create Article"}
Unpermitted parameters: assets_attributes
[1m[35m (0.1ms)[0m begin transaction
[1m[36mSQL (0.4ms)[0m [1mINSERT INTO articles (content, created_at,
title, updated_at) VALUES (?, ?, ?, ?)[0m [[content, Test],
[created_at, Thu, 22 Aug 2013 23:36:46 UTC +00:00], [title, Test],
[updated_at, Thu, 22 Aug 2013 23:36:46 UTC +00:00]]
[1m[35m (0.8ms)[0m commit transaction
Redirected to http://localhost:3000/articles/15
Completed 302 Found in 5ms (ActiveRecord: 1.3ms)
/code/pre
Ruby Version: 2.0
Rails Version: 4.0
I have found a hundred questions with similar situations to mine, but none
of the answers seem to work for me.
I am using paperclip and attempting to upload multiple images to an
article. I have an assets model to accomplish this.
I have nested the model inside the article form here:
<%= form_for(@article, :html => { :multipart => true }) do |f| %>
<% if @article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@article.errors.count, "error") %> prohibited this
article from being saved:</h2>
<ul>
<% @article.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<%= f.fields_for :assets do |asset| %>
<%= asset.file_field :image %><br />
<% end %>
<div class="actions">
<%= f.submit %>
<% end %>
And whitelisted the model and (what I assume to be) its only attribute -
image
def article_params
params.require(:article).permit(:title, :content)
end
def asset_params
params.require(:asset).permit(:image)
end
Yet I am still getting this in my development log when I try to create a
new article with an image:
Unpermitted parameters: assets_attributes
What am I missing? (additional resources below):
article.rb
class Article < ActiveRecord::Base
has_many :assets
accepts_nested_attributes_for :assets
end
asset.rb
class Asset < ActiveRecord::Base
belongs_to :article
has_attached_file :image,
:styles => {
:thumb => '150x150#',
:medium => '300x300>',
:large => '600x600>'
}
end
full dump from development log
Started POST "/articles" for 127.0.0.1 at 2013-08-22 18:36:46 -0500
Processing by ArticlesController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"8x5YJgZV7PsQkqxMM3nOvEZ5Zr4m7tKy8FAiQayvTrI=",
"article"=>{"title"=>"Test", "content"=>"Test",
"assets_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fd3fbcf2bb0
@tempfile=#<Tempfile:/var/folders/ws/xtl93rn97nv1n1l61kzr9m0m0000gn/T/RackMultipart20130822-11705-evlabr>,
@original_filename="PLunKmQ.jpg", @content_type="image/jpeg",
@headers="Content-Disposition: form-data;
name=\"article[assets_attributes][0][image]\";
filename=\"PLunKmQ.jpg\"\r\nContent-Type: image/jpeg\r\n">}}},
"commit"=>"Create Article"}
Unpermitted parameters: assets_attributes
[1m[35m (0.1ms)[0m begin transaction
[1m[36mSQL (0.4ms)[0m [1mINSERT INTO articles (content, created_at,
title, updated_at) VALUES (?, ?, ?, ?)[0m [[content, Test],
[created_at, Thu, 22 Aug 2013 23:36:46 UTC +00:00], [title, Test],
[updated_at, Thu, 22 Aug 2013 23:36:46 UTC +00:00]]
[1m[35m (0.8ms)[0m commit transaction
Redirected to http://localhost:3000/articles/15
Completed 302 Found in 5ms (ActiveRecord: 1.3ms)
/code/pre
how to implement OSPF using Ns-2
how to implement OSPF using Ns-2
I am new in this field.Please help me to implement open shortest path
first(OSPF) in ns2.
I am new in this field.Please help me to implement open shortest path
first(OSPF) in ns2.
internationalization with jQuery
internationalization with jQuery
I'm trying to make a simple internationalization by replacing strings of
text and I have developed the next code for it:
//INTERNACIONALIZACIÓN
$(function(){
arrayCadenas = $(".texts").text(); // creamos un array con las cadenas
de texto a traducir.
//lang = $(".lang").attr("id");
//Generamos un array JS con las cadenas para insertar -las traducciones-.
var es_ES = ["Federación de reinserción1", "NOSOTROS", "QUIENES
SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED
INCORPORA", "APRENDIZAJE", "CONTACTO"];
var eu_EU = ["Federación de reinserción2", "GUK", "NORK GARA", "ZER
EGIN", "PROIEKTUAK", "SGU-UPD SARTU II", "RED INCORPORA",
"APRENDIZAJE", "KONTAKTUA"];
var en_EN = ["Federación de reinserción3", "NOSOTROS", "QUIENES
SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED
INCORPORA", "APRENDIZAJE", "CONTACTO"];
languages = [es_ES, eu_EU, en_EN];
$(".lang").each(function(i, lis){
//lis simplemente hace referencia a los elementos seleccionados, en
este caso no nos es util dentro del buble, en otros quizás lo sea.
// El indice te pueede valer como una variable de control para saber
en que posicion estas del bucle.
$(this).on("click", function(e){
e.stopPropagation; // evitamos que nos dispare eventos en niveles
superiores.
select = languages[i]; // hacemos coincidir la posicion de los
lenguages con la iteración, es decir las banderas en el mismo orden
que las traducciones.
console.log(arrayCadenas);
console.log(languages[i]);
arrayCadenas.each(function(j, cadena){ // Hacemos una iteracion por
todas las cadenas que habia en el documento.
cadena.text(languages[i][j]); // en cada elemento actual, insertamos
el texto correspondiente a la bandera -i- y la cadena
correspondiente a la iteracion -j-.
}); // fin each
});// fin evento click sobre la bandera seleccionada.
}); // fin each de las banderas.
}); // fin ready INTERNACIONALIZACION
When I click on a flag, in console I got this:
[17:53:04.223] TypeError: arrayCadenas.each is not a function @
file:///var/www/TRABAJOS/SARTUWEB/%2806-08-2013%29%20sartutheme7/index.html:253
[17:53:04.222] Federación de reinserciónNOSOTROSQUIENES SOMOSQUE
HACEMOSPROYECTOSSGU-UPD SARTU IIRED INCORPORAAPRENDIZAJECONTACTO
[17:53:04.222] ["Federaci\xF3n de reinserci\xF3n3", "NOSOTROS", "QUIENES
SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED INCORPORA",
"APRENDIZAJE", "CONTACTO"]
Thanks for your help
I'm trying to make a simple internationalization by replacing strings of
text and I have developed the next code for it:
//INTERNACIONALIZACIÓN
$(function(){
arrayCadenas = $(".texts").text(); // creamos un array con las cadenas
de texto a traducir.
//lang = $(".lang").attr("id");
//Generamos un array JS con las cadenas para insertar -las traducciones-.
var es_ES = ["Federación de reinserción1", "NOSOTROS", "QUIENES
SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED
INCORPORA", "APRENDIZAJE", "CONTACTO"];
var eu_EU = ["Federación de reinserción2", "GUK", "NORK GARA", "ZER
EGIN", "PROIEKTUAK", "SGU-UPD SARTU II", "RED INCORPORA",
"APRENDIZAJE", "KONTAKTUA"];
var en_EN = ["Federación de reinserción3", "NOSOTROS", "QUIENES
SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED
INCORPORA", "APRENDIZAJE", "CONTACTO"];
languages = [es_ES, eu_EU, en_EN];
$(".lang").each(function(i, lis){
//lis simplemente hace referencia a los elementos seleccionados, en
este caso no nos es util dentro del buble, en otros quizás lo sea.
// El indice te pueede valer como una variable de control para saber
en que posicion estas del bucle.
$(this).on("click", function(e){
e.stopPropagation; // evitamos que nos dispare eventos en niveles
superiores.
select = languages[i]; // hacemos coincidir la posicion de los
lenguages con la iteración, es decir las banderas en el mismo orden
que las traducciones.
console.log(arrayCadenas);
console.log(languages[i]);
arrayCadenas.each(function(j, cadena){ // Hacemos una iteracion por
todas las cadenas que habia en el documento.
cadena.text(languages[i][j]); // en cada elemento actual, insertamos
el texto correspondiente a la bandera -i- y la cadena
correspondiente a la iteracion -j-.
}); // fin each
});// fin evento click sobre la bandera seleccionada.
}); // fin each de las banderas.
}); // fin ready INTERNACIONALIZACION
When I click on a flag, in console I got this:
[17:53:04.223] TypeError: arrayCadenas.each is not a function @
file:///var/www/TRABAJOS/SARTUWEB/%2806-08-2013%29%20sartutheme7/index.html:253
[17:53:04.222] Federación de reinserciónNOSOTROSQUIENES SOMOSQUE
HACEMOSPROYECTOSSGU-UPD SARTU IIRED INCORPORAAPRENDIZAJECONTACTO
[17:53:04.222] ["Federaci\xF3n de reinserci\xF3n3", "NOSOTROS", "QUIENES
SOMOS", "QUE HACEMOS", "PROYECTOS", "SGU-UPD SARTU II", "RED INCORPORA",
"APRENDIZAJE", "CONTACTO"]
Thanks for your help
PHP mail() function for counting the emails that are send
PHP mail() function for counting the emails that are send
Hello
I have th following PHP script to send emails where the email address is
retrieved form a table in database.
I want to count the number of total emails that are to sent and the emails
that have been sent.
Can anyone help me? I have searched the web for this but it was useless
because I couldn't find anything.The code is as follows
<?php
ignore_user_abort(true);
set_time_limit(0);
if(isset ($_POST["send"]))
{
$upload_name=$_FILES["upload"]["name"];
$upload_type=$_FILES["upload"]["type"];
$upload_size=$_FILES["upload"]["size"];
$upload_temp=$_FILES["upload"]["tmp_name"];
$message=nl2br($_POST["msg"]);
$subject = $_POST["subject"];
$nome = $_POST["nome"];
$email = $_POST["email"];
$from = $nome."<".$email.">";
if($message==""||$subject==""||$nome==""||$email=="")
{
echo '<font style="font-family:Verdana, Arial; font-size:11px;
color:#F3363F; font-weight:bold">Please fill all fields</font>';
}
else
{
$fp = fopen($upload_temp, "rb");
$file = fread($fp, $upload_size);
$file = chunk_split(base64_encode($file));
$num = md5(time());
//Normal headers
$headers = "From:".$from."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$num."\r\n";
$headers .= "--$num\r\n";
// This two steps to help avoid spam
$headers .= "Message-ID: <".gettimeofday()."
TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";
// With message
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "".$message."\n";
$headers .= "--".$num."\n";
// Attachment headers
$headers .= "Content-Type:".$upload_type." ";
$headers .= "name=\"".$upload_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$upload_name."\"\r\n\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."--";
$sql = "SELECT * FROM table";
$result = mysql_query($sql,$link);
while($mail = mysql_fetch_assoc($result)){
if($mail['sponsor'] == $_POST['sendto']){
@mail($mail['email'], $subject, $message, $headers);
sleep(20);
}
if($_POST['sendto'] == 2){
@mail($mail['email'], $subject, $message, $headers);
sleep(20);
}
}
fclose($fp);
echo '<font style="font-family:Verdana, Arial; font-size:11px;
color:#333333; font-weight:bold">Mail sent please check inbox and spam
both <br /></font>';
}
}
?>
<html>
<head>
<title>Mail</title>
</head>
<body>
<form id="attach" name="attach" method="post" action="<?php echo
$_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<table>
<tr>
<td>Nome Mittente</td><td>:</td><td><input type="text"
name="nome" id="nome"></td>
</tr>
<tr>
<td>Email Mittente</td><td>:</td><td><input
type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Oggetto</td><td>:</td><td><input type="text"
name="subject" id="subject"></td>
</tr>
<tr>
<td>Message</td><td>:</td><td> <textarea name="msg"
id="msg" cols='40' rows='10'></textarea></td>
</tr>
<tr>
<td>Attachment(word,pdf,foto)<span
class="imp">*</span></td><td>:</td><td><input
type="file" name="upload" id="upload"></td>
</tr>
<tr>
<td>Send to</td><td>:</td><td> <select name='sendto'
id='sendto' >
<option value='----'>-------</option>
<option value='2'>All</option>
<option value='1'>Sponsor</option>
<option value='0'>Non Sponsor</option>
</select></td>
</tr>
<tr>
<td></td><td></td><td><input type="submit"
value="Submit" id="send" name="send"></td>
</tr>
</table>
</form>
</body>
</html>`
Hello
I have th following PHP script to send emails where the email address is
retrieved form a table in database.
I want to count the number of total emails that are to sent and the emails
that have been sent.
Can anyone help me? I have searched the web for this but it was useless
because I couldn't find anything.The code is as follows
<?php
ignore_user_abort(true);
set_time_limit(0);
if(isset ($_POST["send"]))
{
$upload_name=$_FILES["upload"]["name"];
$upload_type=$_FILES["upload"]["type"];
$upload_size=$_FILES["upload"]["size"];
$upload_temp=$_FILES["upload"]["tmp_name"];
$message=nl2br($_POST["msg"]);
$subject = $_POST["subject"];
$nome = $_POST["nome"];
$email = $_POST["email"];
$from = $nome."<".$email.">";
if($message==""||$subject==""||$nome==""||$email=="")
{
echo '<font style="font-family:Verdana, Arial; font-size:11px;
color:#F3363F; font-weight:bold">Please fill all fields</font>';
}
else
{
$fp = fopen($upload_temp, "rb");
$file = fread($fp, $upload_size);
$file = chunk_split(base64_encode($file));
$num = md5(time());
//Normal headers
$headers = "From:".$from."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$num."\r\n";
$headers .= "--$num\r\n";
// This two steps to help avoid spam
$headers .= "Message-ID: <".gettimeofday()."
TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";
// With message
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "".$message."\n";
$headers .= "--".$num."\n";
// Attachment headers
$headers .= "Content-Type:".$upload_type." ";
$headers .= "name=\"".$upload_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$upload_name."\"\r\n\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."--";
$sql = "SELECT * FROM table";
$result = mysql_query($sql,$link);
while($mail = mysql_fetch_assoc($result)){
if($mail['sponsor'] == $_POST['sendto']){
@mail($mail['email'], $subject, $message, $headers);
sleep(20);
}
if($_POST['sendto'] == 2){
@mail($mail['email'], $subject, $message, $headers);
sleep(20);
}
}
fclose($fp);
echo '<font style="font-family:Verdana, Arial; font-size:11px;
color:#333333; font-weight:bold">Mail sent please check inbox and spam
both <br /></font>';
}
}
?>
<html>
<head>
<title>Mail</title>
</head>
<body>
<form id="attach" name="attach" method="post" action="<?php echo
$_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<table>
<tr>
<td>Nome Mittente</td><td>:</td><td><input type="text"
name="nome" id="nome"></td>
</tr>
<tr>
<td>Email Mittente</td><td>:</td><td><input
type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Oggetto</td><td>:</td><td><input type="text"
name="subject" id="subject"></td>
</tr>
<tr>
<td>Message</td><td>:</td><td> <textarea name="msg"
id="msg" cols='40' rows='10'></textarea></td>
</tr>
<tr>
<td>Attachment(word,pdf,foto)<span
class="imp">*</span></td><td>:</td><td><input
type="file" name="upload" id="upload"></td>
</tr>
<tr>
<td>Send to</td><td>:</td><td> <select name='sendto'
id='sendto' >
<option value='----'>-------</option>
<option value='2'>All</option>
<option value='1'>Sponsor</option>
<option value='0'>Non Sponsor</option>
</select></td>
</tr>
<tr>
<td></td><td></td><td><input type="submit"
value="Submit" id="send" name="send"></td>
</tr>
</table>
</form>
</body>
</html>`
passing argument from vba to vbs
passing argument from vba to vbs
I have one vb script and excel page with command button.
vb script---test.vbs MsgBox("Hello world")
excel vba code
Private Sub CommandButton1_Click() Dim SFilename As String SFilename =
"C:\Users\mkamaraj\Desktop\test.vbs" 'Change the file path
' Run VBScript file
Set wshShell = CreateObject("Wscript.Shell")
wshShell.Run """" & SFilename & """"
End Sub
When i click the button in excel it executes the vbs and the message box
is displayed..it working fine..now i need to pass text box value from
excel dba to vbscript and that value should be displayed with that vbs
message box. How can i do that?
I have one vb script and excel page with command button.
vb script---test.vbs MsgBox("Hello world")
excel vba code
Private Sub CommandButton1_Click() Dim SFilename As String SFilename =
"C:\Users\mkamaraj\Desktop\test.vbs" 'Change the file path
' Run VBScript file
Set wshShell = CreateObject("Wscript.Shell")
wshShell.Run """" & SFilename & """"
End Sub
When i click the button in excel it executes the vbs and the message box
is displayed..it working fine..now i need to pass text box value from
excel dba to vbscript and that value should be displayed with that vbs
message box. How can i do that?
Wednesday, 21 August 2013
JQuery event handler for displaying hidden form in Rails
JQuery event handler for displaying hidden form in Rails
I have never used JQuery in Rails before but need it to make a button
clickable so that it opens up a form(which is currently hidden) on
clicking it -- The problem im having is in specifically using it in rails
as I have no idea how and where to include the jquery code (so far I have
installed the jQuery gems)
This the code in my view:
<td>
<div class="file_description"><%= object.metadata['description']%>
<button type="button" class="btn btn-default
edit_description">Edit</button></div>
<div class="file_description_update">
<%= form_tag({:action => 'update_file_info'}, multipart: true)
do %>
Update File Description: <%= text_area_tag :description %>
<%= hidden_field_tag :s3_path, file %>
<%= hidden_field_tag :prefix, @prefix %>
<%= submit_tag 'Submit' %> </td> <br />
<% end %>
</div>
</td>
Right now I have hidden the div.file_description_update class
This is the code I could possibly use for jquery:
var hiddenBox = $( "div.file_description_update" );
$( "button.edit_description" ).on( "click", function( event ) {
hiddenBox.show();
});
Can someone please let me know if the jquery I am using for this purpose
is correct and where and how I can include the jquery code within my rails
app (which file?)
I have never used JQuery in Rails before but need it to make a button
clickable so that it opens up a form(which is currently hidden) on
clicking it -- The problem im having is in specifically using it in rails
as I have no idea how and where to include the jquery code (so far I have
installed the jQuery gems)
This the code in my view:
<td>
<div class="file_description"><%= object.metadata['description']%>
<button type="button" class="btn btn-default
edit_description">Edit</button></div>
<div class="file_description_update">
<%= form_tag({:action => 'update_file_info'}, multipart: true)
do %>
Update File Description: <%= text_area_tag :description %>
<%= hidden_field_tag :s3_path, file %>
<%= hidden_field_tag :prefix, @prefix %>
<%= submit_tag 'Submit' %> </td> <br />
<% end %>
</div>
</td>
Right now I have hidden the div.file_description_update class
This is the code I could possibly use for jquery:
var hiddenBox = $( "div.file_description_update" );
$( "button.edit_description" ).on( "click", function( event ) {
hiddenBox.show();
});
Can someone please let me know if the jquery I am using for this purpose
is correct and where and how I can include the jquery code within my rails
app (which file?)
Cannot pass parameter from xml suite to test
Cannot pass parameter from xml suite to test
Im new to maven and testng I got an issue: I cannot get parameter from
suite xml file for my test when run Maven Test I dont know why Can anyone
help me on this I appreciate so much
Thank you
This is my main test: hTest.java
package demo;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class hTest {
@Parameters({"user"})
@Test
public void getUser(String user)
{
System.out.println("NAME= " + user);
}
}
This is my suite hTest.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="hTest" verbose="3" parallel="false">
<test name="hTest">
<parameter name="user" value="Giao"/>
<classes>
<class name="demo.hTest"/>
</classes>
</test>
</suite>
This is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BnS</name>
<properties>
<test.suite.dir>test.suites</test.suite.dir>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>2.33.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.14.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${test.suite.dir}/hTest.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
Im new to maven and testng I got an issue: I cannot get parameter from
suite xml file for my test when run Maven Test I dont know why Can anyone
help me on this I appreciate so much
Thank you
This is my main test: hTest.java
package demo;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class hTest {
@Parameters({"user"})
@Test
public void getUser(String user)
{
System.out.println("NAME= " + user);
}
}
This is my suite hTest.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="hTest" verbose="3" parallel="false">
<test name="hTest">
<parameter name="user" value="Giao"/>
<classes>
<class name="demo.hTest"/>
</classes>
</test>
</suite>
This is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BnS</name>
<properties>
<test.suite.dir>test.suites</test.suite.dir>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.5</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.33.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>2.33.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.14.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>${test.suite.dir}/hTest.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>
Subscribe to:
Comments (Atom)