How can I do the equivalent of the Ruby snippet below using Java?
require 'net/http'
res = Net::HTTP.get_response(URI.parse("http://somewhere.com/isalive")).body
Hi,
I have two file.
I have to modify the file one in a particular node and add in a list of child.
The list is in the file2.
Can I do it, and how?
from xml.dom.minidom import Document
from xml.dom import minidom
file1=modificare.xml
file2=sorgente.xml
xmldoc=minidom.parse(file1)
for Node in xmldoc.getElementsByTagName("Sampler"):
# put in the file2 content
Thanks a lot.
How to handle the case where the token 'for' is used in two different situations in the language to parse? Such as statement and as a "parameter" as the following example:
echo for print example
for i in {0..10..2}
do
echo "Welcome $i times"
done
Output:
for print example
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times
Thanks.
I am writing a small C application that use some threads for processing data. I want to be able to know the number of processors on a certain machine, without using system() & in combination to a small script.
The only way i can think of is to parse /proc/cpuinfo. Any other useful suggestions ?
Hi,
I'm using g:datePicker name="date1" id="date1" value="${program?.startDate}"
In controller when used params.date1 it is showing value as "struct" and unable to save date in my database.
How can we parse date in to one param like eg: 2010-10-10 11:11:11 using datePicker ?
thanks in advance
srinath
Anyone know of a good library to invoke powershell scripts from within Java? I'm currently spawning a seperate process (powershell.exe) and then parse the output, but it would really be nice if I can leverage Powershell's 'power' by getting objects back from a powershell call.
Edit:
Otherwise, anyone else doing such interop? What method do you use?
I have a string of the form "ORDER20100322194007", it "20100322194007" Date and time 2010-03-22 19:40:07.000. How to parse a string and get the contained object DateTime?
I'm working on strengthening my F#-fu and decided to tackle the Facebook Hacker Cup Double Squares problem. I'm having some problems with the run-time and was wondering if anyone could help me figure out why it is so much slower than my C# equivalent.
There's a good description from another post;
Source: Facebook Hacker Cup
Qualification Round 2011
A double-square number is an integer X
which can be expressed as the sum of
two perfect squares. For example, 10
is a double-square because 10 = 3^2 +
1^2. Given X, how can we determine the number of ways in which it can be
written as the sum of two squares? For
example, 10 can only be written as 3^2
+ 1^2 (we don't count 1^2 + 3^2 as being different). On the other hand, 25 can
be written as 5^2 + 0^2 or as 4^2 + 3^2.
You need to solve this problem for 0 =
X = 2,147,483,647.
Examples:
10 = 1
25 = 2
3 = 0
0 = 1
1 = 1
My basic strategy (which I'm open to critique on) is to;
Create a dictionary (for memoize) of the input numbers initialzed to 0
Get the largest number (LN) and pass it to count/memo function
Get the LN square root as int
Calculate squares for all numbers 0 to LN and store in dict
Sum squares for non repeat combinations of numbers from 0 to LN
If sum is in memo dict, add 1 to memo
Finally, output the counts of the original numbers.
Here is the F# code (See code changes at bottom) I've written that I believe corresponds to this strategy (Runtime: ~8:10);
open System
open System.Collections.Generic
open System.IO
/// Get a sequence of values
let rec range min max =
seq { for num in [min .. max] do yield num }
/// Get a sequence starting from 0 and going to max
let rec zeroRange max = range 0 max
/// Find the maximum number in a list with a starting accumulator (acc)
let rec maxNum acc = function
| [] -> acc
| p::tail when p > acc -> maxNum p tail
| p::tail -> maxNum acc tail
/// A helper for finding max that sets the accumulator to 0
let rec findMax nums = maxNum 0 nums
/// Build a collection of combinations; ie [1,2,3] = (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)
let rec combos range =
seq {
let count = ref 0
for inner in range do
for outer in Seq.skip !count range do
yield (inner, outer)
count := !count + 1
}
let rec squares nums =
let dict = new Dictionary<int, int>()
for s in nums do
dict.[s] <- (s * s)
dict
/// Counts the number of possible double squares for a given number and keeps track of other counts that are provided in the memo dict.
let rec countDoubleSquares (num: int) (memo: Dictionary<int, int>) =
// The highest relevent square is the square root because it squared plus 0 squared is the top most possibility
let maxSquare = System.Math.Sqrt((float)num)
// Our relevant squares are 0 to the highest possible square; note the cast to int which shouldn't hurt.
let relSquares = range 0 ((int)maxSquare)
// calculate the squares up front;
let calcSquares = squares relSquares
// Build up our square combinations; ie [1,2,3] = (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)
for (sq1, sq2) in combos relSquares do
let v = calcSquares.[sq1] + calcSquares.[sq2]
// Memoize our relevant results
if memo.ContainsKey(v) then
memo.[v] <- memo.[v] + 1
// return our count for the num passed in
memo.[num]
// Read our numbers from file.
//let lines = File.ReadAllLines("test2.txt")
//let nums = [ for line in Seq.skip 1 lines -> Int32.Parse(line) ]
// Optionally, read them from straight array
let nums = [1740798996; 1257431873; 2147483643; 602519112; 858320077; 1048039120; 415485223; 874566596; 1022907856; 65; 421330820; 1041493518; 5; 1328649093; 1941554117; 4225; 2082925; 0; 1; 3]
// Initialize our memoize dictionary
let memo = new Dictionary<int, int>()
for num in nums do
memo.[num] <- 0
// Get the largest number in our set, all other numbers will be memoized along the way
let maxN = findMax nums
// Do the memoize
let maxCount = countDoubleSquares maxN memo
// Output our results.
for num in nums do
printfn "%i" memo.[num]
// Have a little pause for when we debug
let line = Console.Read()
And here is my version in C# (Runtime: ~1:40:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace FBHack_DoubleSquares
{
public class TestInput
{
public int NumCases { get; set; }
public List<int> Nums { get; set; }
public TestInput()
{
Nums = new List<int>();
}
public int MaxNum()
{
return Nums.Max();
}
}
class Program
{
static void Main(string[] args)
{
// Read input from file.
//TestInput input = ReadTestInput("live.txt");
// As example, load straight.
TestInput input = new TestInput
{
NumCases = 20,
Nums = new List<int>
{
1740798996,
1257431873,
2147483643,
602519112,
858320077,
1048039120,
415485223,
874566596,
1022907856,
65,
421330820,
1041493518,
5,
1328649093,
1941554117,
4225,
2082925,
0,
1,
3,
}
};
var maxNum = input.MaxNum();
Dictionary<int, int> memo = new Dictionary<int, int>();
foreach (var num in input.Nums)
{
if (!memo.ContainsKey(num))
memo.Add(num, 0);
}
DoMemoize(maxNum, memo);
StringBuilder sb = new StringBuilder();
foreach (var num in input.Nums)
{
//Console.WriteLine(memo[num]);
sb.AppendLine(memo[num].ToString());
}
Console.Write(sb.ToString());
var blah = Console.Read();
//File.WriteAllText("out.txt", sb.ToString());
}
private static int DoMemoize(int num, Dictionary<int, int> memo)
{
var highSquare = (int)Math.Floor(Math.Sqrt(num));
var squares = CreateSquareLookup(highSquare);
var relSquares = squares.Keys.ToList();
Debug.WriteLine("Starting - " + num.ToString());
Debug.WriteLine("RelSquares.Count = {0}", relSquares.Count);
int sum = 0;
var index = 0;
foreach (var square in relSquares)
{
foreach (var inner in relSquares.Skip(index))
{
sum = squares[square] + squares[inner];
if (memo.ContainsKey(sum))
memo[sum]++;
}
index++;
}
if (memo.ContainsKey(num))
return memo[num];
return 0;
}
private static TestInput ReadTestInput(string fileName)
{
var lines = File.ReadAllLines(fileName);
var input = new TestInput();
input.NumCases = int.Parse(lines[0]);
foreach (var lin in lines.Skip(1))
{
input.Nums.Add(int.Parse(lin));
}
return input;
}
public static Dictionary<int, int> CreateSquareLookup(int maxNum)
{
var dict = new Dictionary<int, int>();
int square;
foreach (var num in Enumerable.Range(0, maxNum))
{
square = num * num;
dict[num] = square;
}
return dict;
}
}
}
Thanks for taking a look.
UPDATE
Changing the combos function slightly will result in a pretty big performance boost (from 8 min to 3:45):
/// Old and Busted...
let rec combosOld range =
seq {
let rangeCache = Seq.cache range
let count = ref 0
for inner in rangeCache do
for outer in Seq.skip !count rangeCache do
yield (inner, outer)
count := !count + 1
}
/// The New Hotness...
let rec combos maxNum =
seq {
for i in 0..maxNum do
for j in i..maxNum do
yield i,j }
Is there an (unobtrusive, to the user) way to get all the text in a page with Javascript? I could get the HTML, parse it, remove all tags, etc, but I'm wondering if there's a way to get the text from the alread rendered page.
To clarify, I don't want to grab text from a selection, I want the entire page.
Thank you!
Imagine you have an object foo that you saved as saved.file.rda as follows:
foo <- 'a'
save(foo, file='saved.file.rda')
Suppose you load saved.file.rda into an environment with multiple objects but forgot the name of the object that is in saved.file.rda. Is there a way in R to determine that name?
You can do it the following way, which seems a little clunky:
bar <- load('saved.file.rda')
eval(parse(text=bar)) # this will pull up the object that was in saved.file.rda
However, is there a better way of doing this?
Hello,
Can anyone tell me how to parse a local xml file stored in the system using SAX ,with an example code.please also tell me where can i find information on that
Hello All - I have a task to import/transform and extract zipped binary files that contain both text data as well as embeded binary data. Within the data is data that is relational in nature and needs to be processed into a defined database structure. Currently I have a C# single threaded app that essentially grabs all the files from the directory (currently there is 13K files of varying sizes) and extracts the data on a single thread line by line inserts to the database. As you could imagine this is a very slow process and unacceptable. There are several different parsing routines used depending on the header record in the file. There are potentially upto a million rows per file when all the data is extracted to the row level of detail. Follow on task is to parse those rows into their appropriate tables based on is content. i.e. the textual content has to be parsed further into "buckets" of like data in the database. That about sums up the big picture. Now for the problem task list.
How do i iterate through a packet of data using SSIS? In the app the file is decompressed and then is parsed using streams data type and byte arrays and is routed to the required parsing routine based on the header data of each packet. There is bit swapping involved as well. Should i wrap up the app code into a script task(s) and let it do the custom processing? The data is seperated by year and the sql server tables is partitioned by year as well. I need to be able to "catch" bad file data as well and process by hand most likely.
Should i simply load the zipped file to sql as a blob and parse the file with T-SQL? Would that be multi threaded if done that way? Not sure how to do the parsing in tsql that is involved here. Which do you think would be faster?
Potentially the data that is currently processed via files could come to us via a socket. Can SSIS collect that data in real time? How would i go about setting that up?
Processing these new files from the directorys will become a daily task.
I can manage the data once i get it to sql server. Getting it there in a timely fashion seems to be the long pole in the tent for me. I would appreciate any comments or suggestions from the group.
Rick
I have set up a class to validate credit card numbers. The credit card type and number are selected on a form in a separate class. I'm trying to figure out how to get the credit card type and number that are selected in the other class (frmPayment) in to my credit card class algorithm:
public enum CardType
{
MasterCard, Visa, AmericanExpress
}
public sealed class CardValidator
{
public static string SelectedCardType { get; private set; }
public static string CardNumber { get; private set; }
private CardValidator(string selectedCardType, string cardNumber)
{
SelectedCardType = selectedCardType;
CardNumber = cardNumber;
}
public static bool Validate(CardType cardType, string cardNumber)
{
byte[] number = new byte[16];
int length = 0;
for (int i = 0; i < cardNumber.Length; i++)
{
if (char.IsDigit(cardNumber, i))
{
if (length == 16) return false;
number[length++] = byte.Parse(cardNumber[i]); //not working. find different way to parse
}
}
switch(cardType)
{
case CardType.MasterCard:
if(length != 16)
return false;
if(number[0] != 5 || number[1] == 0 || number[1] > 5)
return false;
break;
case CardType.Visa:
if(length != 16 & length != 13)
return false;
if(number[0] != 4)
return false;
break;
case CardType.AmericanExpress:
if(length != 15)
return false;
if(number[0] != 3 || (number[1] != 4 & number[1] != 7))
return false;
break;
}
// Use Luhn Algorithm to validate
int sum = 0;
for(int i = length - 1; i >= 0; i--)
{
if(i % 2 == length % 2)
{
int n = number[i] * 2;
sum += (n / 10) + (n % 10);
}
else
sum += number[i];
}
return (sum % 10 == 0);
}
}
I'd like to programatically determine the "publish location" (the location on the server which contains the installation) of the click-once application I'm running. I know that the appref-ms file contains this information and I could parse this file to find it but the application has no idea as to the location of the appref-ms file and I can't seem to find a way of determining this location.
Does anyone have any ideas how I can easily determine the publish location from within my application?
G'day guys, I'm currently using fasterCSV to parse a CSV file in ruby, and wondering how to get rid of the initial row of data on a CSV (The initial row contains the time/date information generated by another software package)
I tried using fasterCSV.table and then deleting row(0) then converting it to a CSV document then parsing it
but the row was still present in the document.
Any other ideas?
fTable = FasterCSV.table("sto.csv", :headers => true)
fTable.delete(0)
Hi guys,
I have this function put in a MasterPage, which shows up an mp3 player:
<script type="text/javascript">
$(document).ready(function() {
var stageW = 500;
var stageH = 216;
var cacheBuster = Date.parse(new Date());
var flashvars = {};
var params = {};
params.bgcolor = '#F6F6F6';
params.allowfullscreen = 'true';
flashvars.stageW = stageW;
flashvars.stageH = stageH;
flashvars.pathToFiles = '';
flashvars.settingsPath = '../mp3player/mp3player_settings.xml';
flashvars.xmlPath = '<%# getRestXmlPlayerUrl() %>';
flashvars.keepSelected = 't';
flashvars.selectedWindow = '4';
flashvars.slideshow = 't';
flashvars.imageWidth = '130';
flashvars.imageHeight = '130';
swfobject.embedSWF('swf/preview.swf?t=' + cacheBuster, 'myContent', stageW, stageH, '9.0.124', 'swf/expressInstall.swf', flashvars, params);
});
</script>
All works great.
But, because i have some ajax on the page with update panel, the flash in not rendered when ajax requests occurs so i need to register this function and i've tried something like this:
protected void Page_PreRender(object sender, EventArgs e)
{
Type cstype = this.GetType();
String csnameForPlayer = "applyStyleToMp3Player";
if (!Page.ClientScript.IsClientScriptBlockRegistered(cstype, csnameForPlayer))
{
StringBuilder cstextForPlayer = new StringBuilder();
cstextForPlayer.Append(" $(document).ready(function() { "
+ " var stageW = 500;"
+ " var stageH = 216;"
+ " var cacheBuster = Date.parse(new Date());"
+ " var flashvars = {};"
+ " var params = {};"
+ " params.bgcolor = '#F6F6F6';"
+ " params.allowfullscreen = 'true';"
+ " flashvars.stageW = stageW;"
+ " flashvars.stageH = stageH;"
+ " flashvars.pathToFiles = '';"
+ " flashvars.settingsPath = '../mp3player/mp3player_settings.xml';"
+ " flashvars.xmlPath = '<%# getRestXmlPlayerUrl() %>';"
+ " flashvars.keepSelected = 't';"
+ " flashvars.selectedWindow = '4';"
+ " flashvars.slideshow = 't';"
+ " flashvars.imageWidth = '130';"
+ " flashvars.imageHeight = '130';"
+ " swfobject.embedSWF('swf/preview.swf?t=' + cacheBuster, 'myContent', stageW, stageH, '9.0.124', 'swf/expressInstall.swf', flashvars, params);"
+ "}); ");
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), csnameForPlayer, cstextForPlayer.ToString(), true);
}
}
Well, this does not work. The flash player does not appear any more, so, i assume that is something wrong in the cstextForPlayer.
I've spent over one hour to figure it out but i've failed.
Does anyone see the problem?
Thanks in advance.
I am trying to display a WordPress post on the homepage of a site. It is reporting the following error:
Parse error: syntax error, unexpected '=' in /home/####/####/####/####/wp-content/themes/oceanswaves/home.php on line 105
<?php query_posts(‘p=143'); if(have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endif; ?>
Thank you
How can I cache an XSD schema (residing on disk) to be reused when parsing XMLs in Xerces (C++)?
I would like to load the XSD schema when starting the process, then, whenever I need to parse an XML, to validate it first using this loaded schema.
Hi All,
In my project i using LibXml to parse data, when i select a row in first controller i will take to next conttroller where i will get data using libxml if i click on the back button while loading the page i am getting exception. if i click afetr loading is completed it is working fine ca any one help me.
the exception is showing here
(void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data {
// Process the downloaded chunk of data.
xmlParseChunk(_xmlParserContext, (const char *)[data bytes], [data length], 0);
}
Thank You
I'm using Text.ParserCombinators.Parsec and Text.XHtml to parse an input like this:
hello 123 --this is an emphasized text-- bye\n
And my output should be:
<p>hello 123 <em>this is an emphasized text</em> bye\n</p>
Any ideas? Thanks!!
Hi I'm trying to run a WordPress plugin and I get the following error:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /nfs/c03/h05/mnt/52704/domains/creathive.net/html/wp-content/plugins/qr-code-tag/lib/qrct/QrctWp.php on line 13
What would be the problem here? Line 13 is the public bit
EDIT: Here is some code:
class QrctWp
{
public $pluginName = 'QR Code Tag';
Which one would you choose? My important attributes are (not in order)
Support & Future enhancements
Community & general knowledge
base (on the Internet)
Comprehensive (i.e proven to
parse a wide range of *.*ml pages)
Performance
Memory Footprint (runtime, not the code-base)
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
I have the following code:
foo :: Int -> [String] -> [(FilePath, Integer)] -> IO Int
foo _ [] _ = return 4
foo _ _ [] = return 5
foo n nameREs pretendentFilesWithSizes = do
result <- (bar n (head nameREs) pretendentFilesWithSizes)
if result == 0
then return 0 -- <========================================== here is the error
else foo n (tail nameREs) pretendentFilesWithSizes
I get an error on the line with the comment above, the error is:
aaa.hs:56:2:
parse error (possibly incorrect indentation)
I'm working with emacs, there's no spaces, and i do not understand what did i do wrong.