Search Results

Search found 197 results on 8 pages for 'readfile'.

Page 5/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • Haskell IO Passes to Another Function

    - by peterwkc
    This question here is related to http://stackoverflow.com/questions/3066956/haskell-input-return-tuple I wonder how we can passes the input from monad IO to another function in order to do some computation. Actually what i want is something like -- First Example test = savefile investinput -- Second Example maxinvest :: a maxinvest = liftM maximuminvest maxinvestinput maxinvestinput :: IO() maxinvestinput = do str <- readFile "C:\\Invest.txt" let cont = words str let mytuple = converttuple cont let myint = getint mytuple putStrLn "" -- Convert to Tuple converttuple :: [String] -> [(String, Integer)] converttuple [] = [] converttuple (x:y:z) = (x, read y):converttuple z -- Get Integer getint :: [(String, Integer)] -> [Integer] getint [] = [] getint (x:xs) = snd (x) : getint xs -- Search Maximum Invest maximuminvest :: (Ord a) => [a] -> a maximuminvest [] = error "Empty Invest Amount List" maximuminvest [x] = x maximuminvest (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maximuminvest xs In the second example, the maxinvestinput is read from file and convert the data to the type maximuminvest expected. Please help. Thanks.

    Read the article

  • File processing-Haskell

    - by Martinas Maria
    How can I implement in haskell the following: I receive an input file from the command line. This input file contains words separated with tabs,new lines and spaces.I have two replace this elements(tabs,new lines and spaces) with comma(,) .Observation:more newlines,tabs,spaces will be replaced with a single comma.The result has to be write in a new file(output.txt). Please help me with this.My haskell skills are very scarse. This is what I have so far: processFile::String->String processFile [] =[] processFile input =input process :: String -> IO String process fileName = do text <- readFile fileName return (processFile text) main :: IO () main = do n <- process "input.txt" print n In processFile function I should process the text from the input file. I'm stuck..Please help.

    Read the article

  • PHP: Grab an image from a stream (in an img tag) but if it's not there, i don't want the img tag wri

    - by Gary Willoughby
    I currently have code like this in a web based file called 'view_file.php' to grab an image from an internal network. <img src="put_file.php?type=<?=$TN_TYPE;?>&path=<?=$TN_PATH;?>&filename=<?=$TN_FILENAME;?>" /> The 'put_file.php' script allows access to an internal server that we don't want to expose to the internet. This script checks to see if an image is available and if it is, sends an image header and then uses readfile() to stream the image to the 'view_file.php' page. The problem is if there isn't an image available, instead of streaming a temporary 'spacer.gif' i want to not have the img tag written at all. Any Ideas how to do this? I'm thinking maybe move the img tag into the 'put_file.php' script, but how to mix strings and steams?

    Read the article

  • Newbie Question: Read and Process a List of Text Files

    - by johnv
    I'm completely new to .NET and am trying as a first step to write a text processing program. The task is simple: I have a list of 10,000 text files stored in one folder, and I'm trying to read each one, store it as a string variable, then run it through a series of functions, then save the final output to another folder. So far I can only manage to manually input the file path like this (in VB.NET): Dim tRead As System.IO.StreamReader Public Function ReadFile() As String Dim EntireFile As String tRead = File.OpenText("c:\textexample\00001.txt") EntireFile = tRead.ReadToEnd Return EntireFile End Function Public Function Step1() ..... End Function Public Function Step2() ..... End Function .............. I'm wondering, therefore, if there's a way to automate this process. Perhaps for example store all input file path into a text file then read each entry at a time, then save the final output into the save path, again listed in a text file. Any help is greatly appreciated. ReplyQuote

    Read the article

  • Rename PHP Downloaded File in File Downloader/Accelerator Applications

    - by Joe
    I have the following "download" script in PHP which basically makes an address on my website download the file for the user, eg. mysite.com/download.php?fileid=10 The question I have is, how can I send the file name to the used for the download when a user downloads the .php address with a File Downloaders/Accelerators? eg. "Content-Disposition" in this case makes the file called download.php where as I want it to be renamed to $downloadFileName as usual. // Set headers header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Description: File Transfer"); header("Content-Type: application/force-download"); header("Content-Disposition: attachment; filename=\"".$downloadFileName."\""); header("Content-Transfer-Encoding: binary"); // Read the file from disk readfile($downloadLocation);

    Read the article

  • Longish list of allowed referrers

    - by Tim
    I want to allow hotlinking only from a list of referrers (paying customers, probably a few hundred). I am on Apache 1.3 and I do not have access to the configuration (only .htaccess). What is the fastest way to implement this? My thoughts so far: PHP with database and readfile() (SSI with) Perl and database the list implemented as symlinks named after the allower referrer, then RewriteCond using HTTP_REFERER everything in .htaccess, lots of RewriteCond's everything in .htaccess, lots of SetEnvIf's Any better (faster) ways to do this? Thanks!

    Read the article

  • can't open file which download with php code

    - by user304828
    header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); i downloaded file but can't open file ? why ?

    Read the article

  • Application crashing when talking to oracle unless executable path contains spaces

    - by Lasse V. Karlsen
    We have an x-files problem with our .NET application. Or, rather, hybrid Win32 and .NET application. When it attempts to communicate with Oracle, it just dies. Vanishes. Goes to the big black void in the sky. No event log message, no exception, no nothing. If we simply ask the application to talk to a MS SQL Server instead, which has the effect of replacing the usage of OracleConnection and related classes with SqlConnection and related classes, it works as expected. Today we had a breakthrough. For some reason, a customer had figured out that by placing all the application files in a directory on his desktop, it worked as expected with Oracle as well. Moving the directory down to the root of the drive, or in C:\Temp or, well, around a bit, made the crash reappear. Basically it was 100% reproducable that the application worked if run from directory on desktop, and failed if run from directory in root. Today we figured out that the difference that counted was wether there was a space in the directory name or not. So, these directories would work: C:\Program Files\AppDir\Executable.exe C:\Temp Lemp\AppDir\Executable.exe C:\Documents and Settings\someuser\Desktop\AppDir\Executable.exe whereas these would not: C:\CompanyName\AppDir\Executable.exe C:\Programfiler\AppDir\Executable.exe <-- Program Files in norwegian C:\Temp\AppDir\Executable.exe I'm hoping someone reading this has seen similar behavior and have a "aha, you need to twiddle the frob on the oracle glitz driver configuration" or similar. Anyone? Followup #1: Ok, I've processed the procmon output now, both files from when I hit the button that attempts to open the window that triggers the cascade failure, and I've noticed that they keep track mostly, there's some smallish differences near the top of both files, and they they keep track a long way down. However, when one run fails, the other keeps going and the next few lines of the log output are these: ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 274 432, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 233 472, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O After this, the working run continues to execute, and the other touches the mscorwks.dll files a few times before threads close down and the app closes. Thus, the failed run does not touch the above files. Followup #2: Figured I'd try to upgrade the oracle client drivers, but 10.2.0.1 is apparently the highest version available for Windows 2003 server and XP clients. Followup #3: Well, we've ended up with a black-box solution. Basically we found that the problem is somewhere related to XPO and Oracle. XPO has a system-table it manages, called XPObjectType, with three columns: Oid, TypeName and AssemblyName. Due to how Oracle is configured in the databases we talk to, the column names were OID, TYPENAME and ASSEMBLYNAME. This would ordinarily not be a problem, except that XPO talks to the schema information directly and checks if the table is there with the right column names, and XPO doesn't handle case differences so it sees a XPObjectType table with three unknown columns and none of those it expects. Exactly what XPO does now I don't really know, but if I dropped this table, and recreated it with the right case, using double quotes around all the column names to get the case right, the problem doesn't crop up. Exactly where the space in the folder name comes into this, I still have no idea, but this problem had two tiers: Stop the application from crashing at our customers, short-term solution Fix the bug, long-term solution Right now tier 1 is solved, tier 2 will be put back into the queue for now and prioritized. We're facing some bigger changes to our data tier anyway so this might not be a problem we need to solve, at least if all our Oracle-customers verify that the table-fix actually gets rid of the problem. I'll accept the answer by Dave Markle since though Process Monitor (the big brother of File Monitor) didn't actually pinpoint the problem, I was able to use it to determine that after my breakpoint in user-code where XPO had built up the query for this table, no I/O happened until all the entries for the application closing down was logged, which led me to believe it was this table that was the culprit, or at least influenced the problem somehow. If I manage to get to the real cause of this, I'll update the post.

    Read the article

  • No progress bar in IE8 while executing the download using PHP

    - by user292918
    I am giving downloads to user using the PHP code below but when user downloading they are not able to see the progressbar in IE8 when clicked on save button. Please solve this. Thanks in advance. header('Content-Description: Songsbin.com - Downlaod'); header('Content-type: audio/mpeg'); header('Content-Disposition: attachment; filename='.$filename1); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: '.filesize($file)); ob_clean(); flush(); readfile($file);

    Read the article

  • Reusing a vector in C++

    - by Bobby
    I have a vector declared as a global variable that I need to be able to reuse. For example, I am reading multiple files of data, parsing the data to create objects that are then stored in a vector. vector<Object> objVector(100); void main() { while(THERE_ARE_MORE_FILES_TO_READ) { // Pseudocode ReadFile(); ParseFileIntoVector(); ProcessObjectsInVector(); /* Here I want to 'reset' the vector to 100 empty objects again */ } } Can I reset the vector to be "vector objVector(100)" since it was initially allocated on the stack? If I do "objVector.clear()", it removes all 100 objects and I would have a vector with a size of 0. I need it to be a size of 100 at the start of every loop.

    Read the article

  • Can't download file in IE7 but there isn't any problem in Firefox, Chrome, etc..?

    - by levhita
    I have an script that receives an encrypted url and from that generates a download, the most critic par of the script is this: $MimeType = new MimeType(); $mimetype = $MimeType->getType($filename); $basename = basename($filename); header("Content-type: $mimetype"); header("Content-Disposition: attachment; filename=\"$basename\""); header('Content-Length: '. filesize($filename)); if ( @readfile($filename)===false ) { header("HTTP/1.0 500 Internal Server Error"); loadErrorPage('500'); } Downloads works as charm in any Browser except IE, I have seen problems related to 'no-cache' headers but I don't send anything like that, they talk about utf-8 characters, but there is not any utf-8 characters(and the $filename has not any utf-8 characteres neither).

    Read the article

  • Image expire time

    - by Jens
    The google page speed tool recommends me to set 'Expires' headers for images etc. But what is the most efficient way to set an Expires header for an image? In now redirect all image requests to an imagehandler.php using htaccess: /* HTTP/1.1 404 Not Found, HTTP/1.1 400 Bad Request and content type detection stuff ... */ header( "Content-Type: " . $content_type ); header( "Cache-Control: public" ); header( "Last-Modified: ".gmdate("D, d M Y H:i:s", filemtime($path))." GMT"); header( "Expires: ". date("r",time() + (60*60*24*30))); readfile( $path ); But of course this adds extra loading time for my images on first request, and I was wondering if there was a better solution for this.

    Read the article

  • PHP Force Download Causing 0 Byte Files

    - by Alex
    Hey, I'm trying to force download files from my web server using PHP. I'm not a pro in PHP but I just can't seem to get around the problem of files downloading in 0 bytes in size. CODE: $filename = "FILENAME..."; header("Content-type: $type"); header("Content-Disposition: attachment;filename=$filename"); header("Content-Transfer-Encoding: binary"); header('Pragma: no-cache'); header('Expires: 0'); set_time_limit(0); readfile($file); Can anybody help? Thanks.

    Read the article

  • How to know the file type of the file which you are forcing the user to download?

    - by Starx
    I am trying to force the user to download a file. For that my script is: $file = "file\this.zip"; header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$file"); header("Content-Type: application/zip"); //This is what I need header("Content-Transfer-Encoding: binary"); readfile($file); The files I am going to upload my not be .zip all the time so I want to know the content type of the image I am going to receive in $file. How to accomplish this

    Read the article

  • File.Exists() returns false, but not in debug

    - by Tor Haugen
    I'm being completely confused here folks, My code throws an exception because File.Exists() returns false public override sealed TCargo ReadFile(string fileName) { if (!File.Exists(fileName)) { throw new ArgumentException("Provided file name does not exist", "fileName"); } Visual studio breaks at the throw statement, and I immediately check the value of File.Exists(fileName) in the immediate window. It returns true. When I drag the breakpoint back up to the if statement and execute it again, it throws again. fileName is an absolute path to a file. I'm not creating the file, nor writing to it (it's there all along). If I paste the path into the open dialog in Notepad, it reads the file without problems. The code is executing in a background worker. It's the only complicating factor I can think of. I am positive the file has not been opened already, either in the worker thread or elsewhere. What's going on here?

    Read the article

  • Improve disk read performance (multiple files) with threading

    - by pablo
    I need to find a method to read a big number of small files (about 300k files) as fast as possible. Reading them sequentially using FileStream and reading the entire file in a single call takes between 170 and 208 seconds (you know, you re-run, disk cache plays its role and time varies). Then I tried using PInvoke with CreateFile/ReadFile and using FILE_FLAG_SEQUENTIAL_SCAN, but I didn't appreciate any changes. I tried with several threads (divide the big set in chunks and have every thread reading its part) and this way I was able to improve speed just a little bit (not even a 5% with every new thread up to 4). Any ideas on how to find the most effective way to do this?

    Read the article

  • Printing Script Codes.

    - by Spelljack
    I wanna print out script's codes after the output. The script goes on different ways on the way it calls. So i wanna see it when script runs. is there any function that prints all script codes as the way it writed. Example: $foo = "bar"; $foo .= " is my bar"; function foobar() { // do some stuff here } i wanna see the codes just like this. is there a way to do this? without file_get_contents(), file(), readfile() functions?

    Read the article

  • Gluster bricks are offline and errors in logs

    - by Roman Newaza
    I have substituted all the IP addresses with hostnames and renamed configs (IP to hostname) in /var/lib/glusterd by my shell script. After that I restarted Gluster Daemon and the volume. Then I checked if all the peers are connected: root@GlusterNode1a:~# gluster peer status Number of Peers: 3 Hostname: gluster-1b Uuid: 47f469e2-907a-4518-b6a4-f44878761fd2 State: Peer in Cluster (Connected) Hostname: gluster-2b Uuid: dc3a3ff7-9e30-44ac-9d15-00f9dab4d8b9 State: Peer in Cluster (Connected) Hostname: gluster-2a Uuid: 72405811-15a0-456b-86bb-1589058ff89b State: Peer in Cluster (Connected) I could see mounted volumes size change on all the nodes when I execute df command, so new data is coming. But recently I noticed error messages in app log: copy(/storage/152627/dat): failed to open stream: Structure needs cleaning readfile(/storage/1438227/dat): failed to open stream: Input/output error unlink(/storage/189457/23/dat): No such file or directory Finally, I have found out some bricks are offline: root@GlusterNode1a:~# gluster volume status Status of volume: storage Gluster process Port Online Pid ------------------------------------------------------------------------------ Brick gluster-1a:/storage/1a 24009 Y 1326 Brick gluster-1b:/storage/1b 24009 N N/A Brick gluster-2a:/storage/2a 24009 N N/A Brick gluster-2b:/storage/2b 24009 N N/A Brick gluster-1a:/storage/3a 24011 Y 1332 Brick gluster-1b:/storage/3b 24011 N N/A Brick gluster-2a:/storage/4a 24011 N N/A Brick gluster-2b:/storage/4b 24011 N N/A NFS Server on localhost 38467 Y 24670 Self-heal Daemon on localhost N/A Y 24676 NFS Server on gluster-2b 38467 Y 4339 Self-heal Daemon on gluster-2b N/A Y 4345 NFS Server on gluster-2a 38467 Y 1392 Self-heal Daemon on gluster-2a N/A Y 1402 NFS Server on gluster-1b 38467 Y 2435 Self-heal Daemon on gluster-1b N/A Y 2441 What can I do about that? I need to fix it. Note: CPU and Network usage of all the four nodes are about the same.

    Read the article

  • Is there a limit setting a php_admin_value in php-fpm?

    - by PeeHaa
    I am trying to set a large value in the configuration of a pool in php-fpm, but at some point it just doesn't start anymore. php_admin_value[disable_functions] = dl,exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source,pcntl_exec,include,include_once,require,require_once,posix_mkfifo,posix_getlogin,posix_ttyname,getenv,get_current_use,proc_get_status,get_cfg_va,disk_free_space,disk_total_space,diskfreespace,getcwd,getlastmo,getmygid,getmyinode,getmypid,getmyuid,ini_set,mail,proc_nice,proc_terminate,proc_close,pfsockopen,fsockopen,apache_child_terminate,posix_kill,posix_mkfifo,posix_setpgid,posix_setsid,posix_setuid,fopen,tmpfile,bzopen,gzopen,chgrp,chmod,chown,copy,file_put_contents,lchgrp,lchown,link,mkdi,move_uploaded_file,rename,rmdi,symlink,tempnam,touch,unlink,iptcembed,ftp_get,ftp_nb_get,file_exists,file_get_contents,file,fileatime,filectime,filegroup,fileinode,filemtime,fileowne,fileperms,filesize,filetype,glob,is_di,is_executable,is_file,is_link,is_readable,is_uploaded_file,is_writable,is_writeable,linkinfo,lstat,parse_ini_file,pathinfo,readfile,readlink,realpath,stat,gzfile,create_function When trying to restart php-fpm it fails with the following message: Stopping php-fpm: [ OK ] Starting php-fpm: [20-Oct-2013 22:31:52] ERROR: [/etc/php-fpm.d/codepad.conf:235] value is NULL for a ZEND_INI_PARSER_ENTRY [20-Oct-2013 22:31:52] ERROR: Unable to include /etc/php-fpm.d/codepad.conf from /etc/php-fpm.conf at line 235 [20-Oct-2013 22:31:52] ERROR: failed to load configuration file '/etc/php-fpm.conf' [20-Oct-2013 22:31:52] ERROR: FPM initialization failed [FAILED] When I remove the last disabled function (create_function) it start again. I also tried with other functions, but this gives the same error so it's not related to the create_function function. The string currently is just over 1KB in size so it looks like I have hit a limit here? Is my assumption correct? Is there a way to overcome this limit? I also tried to add another php_admin_value[disable_functions] underneath it (hoping it would be appended), but that didn't work (it just used the first one).

    Read the article

  • creating objects from trivial graph format text file. java. dijkstra algorithm.

    - by user560084
    i want to create objects, vertex and edge, from trivial graph format txt file. one of programmers here suggested that i use trivial graph format to store data for dijkstra algorithm. the problem is that at the moment all the information, e.g., weight, links, is in the sourcecode. i want to have a separate text file for that and read it into the program. i thought about using a code for scanning through the text file by using scanner. but i am not quite sure how to create different objects from the same file. could i have some help please? the file is v0 Harrisburg v1 Baltimore v2 Washington v3 Philadelphia v4 Binghamton v5 Allentown v6 New York # v0 v1 79.83 v0 v5 81.15 v1 v0 79.75 v1 v2 39.42 v1 v3 103.00 v2 v1 38.65 v3 v1 102.53 v3 v5 61.44 v3 v6 96.79 v4 v5 133.04 v5 v0 81.77 v5 v3 62.05 v5 v4 134.47 v5 v6 91.63 v6 v3 97.24 v6 v5 87.94 and the dijkstra algorithm code is Downloaded from: http://en.literateprograms.org/Special:Downloadcode/Dijkstra%27s_algorithm_%28Java%29 */ import java.util.PriorityQueue; import java.util.List; import java.util.ArrayList; import java.util.Collections; class Vertex implements Comparable<Vertex> { public final String name; public Edge[] adjacencies; public double minDistance = Double.POSITIVE_INFINITY; public Vertex previous; public Vertex(String argName) { name = argName; } public String toString() { return name; } public int compareTo(Vertex other) { return Double.compare(minDistance, other.minDistance); } } class Edge { public final Vertex target; public final double weight; public Edge(Vertex argTarget, double argWeight) { target = argTarget; weight = argWeight; } } public class Dijkstra { public static void computePaths(Vertex source) { source.minDistance = 0.; PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>(); vertexQueue.add(source); while (!vertexQueue.isEmpty()) { Vertex u = vertexQueue.poll(); // Visit each edge exiting u for (Edge e : u.adjacencies) { Vertex v = e.target; double weight = e.weight; double distanceThroughU = u.minDistance + weight; if (distanceThroughU < v.minDistance) { vertexQueue.remove(v); v.minDistance = distanceThroughU ; v.previous = u; vertexQueue.add(v); } } } } public static List<Vertex> getShortestPathTo(Vertex target) { List<Vertex> path = new ArrayList<Vertex>(); for (Vertex vertex = target; vertex != null; vertex = vertex.previous) path.add(vertex); Collections.reverse(path); return path; } public static void main(String[] args) { Vertex v0 = new Vertex("Nottinghill_Gate"); Vertex v1 = new Vertex("High_Street_kensignton"); Vertex v2 = new Vertex("Glouchester_Road"); Vertex v3 = new Vertex("South_Kensignton"); Vertex v4 = new Vertex("Sloane_Square"); Vertex v5 = new Vertex("Victoria"); Vertex v6 = new Vertex("Westminster"); v0.adjacencies = new Edge[]{new Edge(v1, 79.83), new Edge(v6, 97.24)}; v1.adjacencies = new Edge[]{new Edge(v2, 39.42), new Edge(v0, 79.83)}; v2.adjacencies = new Edge[]{new Edge(v3, 38.65), new Edge(v1, 39.42)}; v3.adjacencies = new Edge[]{new Edge(v4, 102.53), new Edge(v2, 38.65)}; v4.adjacencies = new Edge[]{new Edge(v5, 133.04), new Edge(v3, 102.53)}; v5.adjacencies = new Edge[]{new Edge(v6, 81.77), new Edge(v4, 133.04)}; v6.adjacencies = new Edge[]{new Edge(v0, 97.24), new Edge(v5, 81.77)}; Vertex[] vertices = { v0, v1, v2, v3, v4, v5, v6 }; computePaths(v0); for (Vertex v : vertices) { System.out.println("Distance to " + v + ": " + v.minDistance); List<Vertex> path = getShortestPathTo(v); System.out.println("Path: " + path); } } } and the code for scanning file is import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class DataScanner1 { //private int total = 0; //private int distance = 0; private String vector; private String stations; private double [] Edge = new double []; /*public int getTotal(){ return total; } */ /* public void getMenuInput(){ KeyboardInput in = new KeyboardInput; System.out.println("Enter the destination? "); String val = in.readString(); return val; } */ public void readFile(String fileName) { try { Scanner scanner = new Scanner(new File(fileName)); scanner.useDelimiter (System.getProperty("line.separator")); while (scanner.hasNext()) { parseLine(scanner.next()); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void parseLine(String line) { Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("\\s*,\\s*"); vector = lineScanner.next(); stations = lineScanner.next(); System.out.println("The current station is " + vector + " and the destination to the next station is " + stations + "."); //total += distance; //System.out.println("The total distance is " + total); } public static void main(String[] args) { /* if (args.length != 1) { System.err.println("usage: java TextScanner2" + "file location"); System.exit(0); } */ DataScanner1 scanner = new DataScanner1(); scanner.readFile(args[0]); //int total =+ distance; //System.out.println(""); //System.out.println("The total distance is " + scanner.getTotal()); } }

    Read the article

  • How can I use Perl regular expressions to parse XML data?

    - by Luke
    I have a pretty long piece of XML that I want to parse. I want to remove everything except for the subclass-code and city. So that I am left with something like the example below. EXAMPLE TEST SUBCLASS|MIAMI CODE <?xml version="1.0" standalone="no"?> <web-export> <run-date>06/01/2010 <pub-code>TEST <ad-type>TEST <cat-code>Real Estate</cat-code> <class-code>TEST</class-code> <subclass-code>TEST SUBCLASS</subclass-code> <placement-description></placement-description> <position-description>Town House</position-description> <subclass3-code></subclass3-code> <subclass4-code></subclass4-code> <ad-number>0000284708-01</ad-number> <start-date>05/28/2010</start-date> <end-date>06/09/2010</end-date> <line-count>6</line-count> <run-count>13</run-count> <customer-type>Private Party</customer-type> <account-number>100099237</account-number> <account-name>DOE, JOHN</account-name> <addr-1>207 CLARENCE STREET</addr-1> <addr-2> </addr-2> <city>MIAMI</city> <state>FL</state> <postal-code>02910</postal-code> <country>USA</country> <phone-number>4014612880</phone-number> <fax-number></fax-number> <url-addr> </url-addr> <email-addr>[email protected]</email-addr> <pay-flag>N</pay-flag> <ad-description>DEANESTATES2BEDS2BATHSAPPLIANCED</ad-description> <order-source>Import</order-source> <order-status>Live</order-status> <payor-acct>100099237</payor-acct> <agency-flag>N</agency-flag> <rate-note></rate-note> <ad-content> MIAMI&#47;Dean Estates&#58; 2 beds&#44; 2 baths&#46; Applianced&#46; Central air&#46; Carpets&#46; Laundry&#46; 2 decks&#46; Pool&#46; Parking&#46; Close to everything&#46;No smoking&#46; No utilities&#46; &#36;1275 mo&#46; 401&#45;578&#45;1501&#46; </ad-content> </ad-type> </pub-code> </run-date> </web-export> PERL So what I want to do is open an existing file read the contents then use regular expressions to eliminate the unnecessary XML tags. open(READFILE, "FILENAME"); while(<READFILE>) { $_ =~ s/<\?xml version="(.*)" standalone="(.*)"\?>\n.*//g; $_ =~ s/<subclass-code>//g; $_ =~ s/<\/subclass-code>\n.*/|/g; $_ =~ s/(.*)PJ RER Houses /PJ RER Houses/g; $_ =~ s/\G //g; $_ =~ s/<city>//g; $_ =~ s/<\/city>\n.*//g; $_ =~ s/<(\/?)web-export>(.*)\n.*//g; $_ =~ s/<(\/?)run-date>(.*)\n.*//g; $_ =~ s/<(\/?)pub-code>(.*)\n.*//g; $_ =~ s/<(\/?)ad-type>(.*)\n.*//g; $_ =~ s/<(\/?)cat-code>(.*)<(\/?)cat-code>\n.*//g; $_ =~ s/<(\/?)class-code>(.*)<(\/?)class-code>\n.*//g; $_ =~ s/<(\/?)placement-description>(.*)<(\/?)placement-description>\n.*//g; $_ =~ s/<(\/?)position-description>(.*)<(\/?)position-description>\n.*//g; $_ =~ s/<(\/?)subclass3-code>(.*)<(\/?)subclass3-code>\n.*//g; $_ =~ s/<(\/?)subclass4-code>(.*)<(\/?)subclass4-code>\n.*//g; $_ =~ s/<(\/?)ad-number>(.*)<(\/?)ad-number>\n.*//g; $_ =~ s/<(\/?)start-date>(.*)<(\/?)start-date>\n.*//g; $_ =~ s/<(\/?)end-date>(.*)<(\/?)end-date>\n.*//g; $_ =~ s/<(\/?)line-count>(.*)<(\/?)line-count>\n.*//g; $_ =~ s/<(\/?)run-count>(.*)<(\/?)run-count>\n.*//g; $_ =~ s/<(\/?)customer-type>(.*)<(\/?)customer-type>\n.*//g; $_ =~ s/<(\/?)account-number>(.*)<(\/?)account-number>\n.*//g; $_ =~ s/<(\/?)account-name>(.*)<(\/?)account-name>\n.*//g; $_ =~ s/<(\/?)addr-1>(.*)<(\/?)addr-1>\n.*//g; $_ =~ s/<(\/?)addr-2>(.*)<(\/?)addr-2>\n.*//g; $_ =~ s/<(\/?)state>(.*)<(\/?)state>\n.*//g; $_ =~ s/<(\/?)postal-code>(.*)<(\/?)postal-code>\n.*//g; $_ =~ s/<(\/?)country>(.*)<(\/?)country>\n.*//g; $_ =~ s/<(\/?)phone-number>(.*)<(\/?)phone-number>\n.*//g; $_ =~ s/<(\/?)fax-number>(.*)<(\/?)fax-number>\n.*//g; $_ =~ s/<(\/?)url-addr>(.*)<(\/?)url-addr>\n.*//g; $_ =~ s/<(\/?)email-addr>(.*)<(\/?)email-addr>\n.*//g; $_ =~ s/<(\/?)pay-flag>(.*)<(\/?)pay-flag>\n.*//g; $_ =~ s/<(\/?)ad-description>(.*)<(\/?)ad-description>\n.*//g; $_ =~ s/<(\/?)order-source>(.*)<(\/?)order-source>\n.*//g; $_ =~ s/<(\/?)order-status>(.*)<(\/?)order-status>\n.*//g; $_ =~ s/<(\/?)payor-acct>(.*)<(\/?)payor-acct>\n.*//g; $_ =~ s/<(\/?)agency-flag>(.*)<(\/?)agency-flag>\n.*//g; $_ =~ s/<(\/?)rate-note>(.*)<(\/?)rate-note>\n.*//g; $_ =~ s/<ad-content>(.*)\n.*//g; $_ =~ s/\t(.*)\n.*//g; $_ =~ s/<\/ad-content>(.*)\n.*//g; } close( READFILE1 ); Is there an easier way of doing this? I don't want to use any modules. I know that it might make this easier but the file I am reading has a lot of data in it.

    Read the article

  • Probelm with String.split() in java

    - by Matt
    What I am trying to do is read a .java file, and pick out all of the identifiers and store them in a list. My problem is with the .split() method. If you run this code the way it is, you will get ArrayOutOfBounds, but if you change the delimiter from "." to anything else, the code works. But I need to lines parsed by "." so is there another way I could accomplish this? import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; public class MyHash { private static String[] reserved = new String[100]; private static List list = new LinkedList(); private static List list2 = new LinkedList(); public static void main (String args[]){ Hashtable hashtable = new Hashtable(997); makeReserved(); readFile(); String line; ListIterator itr = list.listIterator(); int listIndex = 0; while (listIndex < list.size()) { if (itr.hasNext()){ line = itr.next().toString(); //PROBLEM IS HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! String[] words = line.split("."); //CHANGE THIS AND IT WILL WORK System.out.println(words[0]); //TESTING TO SEE IF IT WORKED } listIndex++; } } public static void readFile() { String text; String[] words; BufferedReader in = null; try { in = new BufferedReader(new FileReader("MyHash.java")); //NAME OF INPUT FILE } catch (FileNotFoundException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } try { while ((text = in.readLine()) != null){ text = text.trim(); words = text.split("\\s+"); for (int i = 0; i < words.length; i++){ list.add(words[i]); } for (int j = 0; j < reserved.length; j++){ if (list.contains(reserved[j])){ list.remove(reserved[j]); } } } } catch (IOException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } try { in.close(); } catch (IOException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } } public static int keyIt (int x) { int key = x % 997; return key; } public static int horner (String word){ int length = word.length(); char[] letters = new char[length]; for (int i = 0; i < length; i++){ letters[i]=word.charAt(i); } char[] alphabet = new char[26]; String abc = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 26; i++){ alphabet[i]=abc.charAt(i); } int[] numbers = new int[length]; int place = 0; for (int i = 0; i < length; i++){ for (int j = 0; j < 26; j++){ if (alphabet[j]==letters[i]){ numbers[place]=j+1; place++; } } } int hornered = numbers[0] * 32; for (int i = 1; i < numbers.length; i++){ hornered += numbers[i]; if (i == numbers.length -1){ return hornered; } hornered = hornered % 997; hornered *= 32; } return hornered; } public static String[] makeReserved (){ reserved[0] = "abstract"; reserved[1] = "assert"; reserved[2] = "boolean"; reserved[3] = "break"; reserved[4] = "byte"; reserved[5] = "case"; reserved[6] = "catch"; reserved[7] = "char"; reserved[8] = "class"; reserved[9] = "const"; reserved[10] = "continue"; reserved[11] = "default"; reserved[12] = "do"; reserved[13] = "double"; reserved[14] = "else"; reserved[15] = "enum"; reserved[16] = "extends"; reserved[17] = "false"; reserved[18] = "final"; reserved[19] = "finally"; reserved[20] = "float"; reserved[21] = "for"; reserved[22] = "goto"; reserved[23] = "if"; reserved[24] = "implements"; reserved[25] = "import"; reserved[26] = "instanceof"; reserved[27] = "int"; reserved[28] = "interface"; reserved[29] = "long"; reserved[30] = "native"; reserved[31] = "new"; reserved[32] = "null"; reserved[33] = "package"; reserved[34] = "private"; reserved[35] = "protected"; reserved[36] = "public"; reserved[37] = "return"; reserved[38] = "short"; reserved[39] = "static"; reserved[40] = "strictfp"; reserved[41] = "super"; reserved[42] = "switch"; reserved[43] = "synchronize"; reserved[44] = "this"; reserved[45] = "throw"; reserved[46] = "throws"; reserved[47] = "trasient"; reserved[48] = "true"; reserved[49] = "try"; reserved[50] = "void"; reserved[51] = "volatile"; reserved[52] = "while"; reserved[53] = "="; reserved[54] = "=="; reserved[55] = "!="; reserved[56] = "+"; reserved[57] = "-"; reserved[58] = "*"; reserved[59] = "/"; reserved[60] = "{"; reserved[61] = "}"; return reserved; } }

    Read the article

  • Single use download script - Modification [on hold]

    - by Iulius
    I have this Single use download script! This contain 3 php files: page.php , generate.php and variables.php. Page.php Code: <?php include("variables.php"); $key = trim($_SERVER['QUERY_STRING']); $keys = file('keys/keys'); $match = false; foreach($keys as &$one) { if(rtrim($one)==$key) { $match = true; $one = ''; } } file_put_contents('keys/keys',$keys); if($match !== false) { $contenttype = CONTENT_TYPE; $filename = SUGGESTED_FILENAME; readfile(PROTECTED_DOWNLOAD); exit; } else { ?> <html> <head> <meta http-equiv="refresh" content="1; url=http://docs.google.com/"> <title>Loading, please wait ...</title> </head> <body> Loading, please wait ... </body> </html> <?php } ?> Generate.php Code: <?php include("variables.php"); $password = trim($_SERVER['QUERY_STRING']); if($password == ADMIN_PASSWORD) { $new = uniqid('key',TRUE); if(!is_dir('keys')) { mkdir('keys'); $file = fopen('keys/.htaccess','w'); fwrite($file,"Order allow,deny\nDeny from all"); fclose($file); } $file = fopen('keys/keys','a'); fwrite($file,"{$new}\n"); fclose($file); ?> <html> <head> <title>Page created</title> <style> nl { font-family: monospace } </style> </head> <body> <h1>Page key created</h1> Your new single-use page link:<br> <nl> <?php echo "http://" . $_SERVER['HTTP_HOST'] . DOWNLOAD_PATH . "?" . $new; ?></nl> </body> </html> <?php } else { header("HTTP/1.0 404 Not Found"); } ?> And the last one Variables.php Code: <? define('PROTECTED_DOWNLOAD','download.php'); define('DOWNLOAD_PATH','/.work/page.php'); define('SUGGESTED_FILENAME','download-doc.php'); define('ADMIN_PASSWORD','1234'); define('EXPIRATION_DATE', '+36 hours'); header("Cache-Control: no-cache, must-revalidate"); header("Expires: ".date('U', strtotime(EXPIRATION_DATE))); ?> The http://www.site.com/generate.php?1234 will generate a unique link like page.php?key1234567890. This link page.php?key1234567890 will be sent by email to my user. Now how can I generate a link like this page.php?key1234567890&[email protected] ? So I think I must access the generator page like this generate.php?1234&[email protected] . P.S. This variable will be posted on the download page by "Hello, " I tried everthing to complete this, and no luck. Thanks in advance for help.

    Read the article

  • Data breakpoints to find points where data gets broken

    - by raccoon_tim
    When working with a large code base, finding reasons for bizarre bugs can often be like finding a needle in a hay stack. Finding out why an object gets corrupted without no apparent reason can be quite daunting, especially when it seems to happen randomly and totally out of context. Scenario Take the following scenario as an example. You have defined the a class that contains an array of characters that is 256 characters long. You now implement a method for filling this buffer with a string passed as an argument. At this point you mistakenly expect the buffer to be 256 characters long. At some point you notice that you require another character buffer and you add that after the previous one in the class definition. You now figure that you don’t need the 256 characters that the first member can hold and you shorten that to 128 to conserve space. At this point you should start thinking that you also have to modify the method defined above to safeguard against buffer overflow. It so happens, however, that in this not so perfect world this does not cross your mind. Buffer overflow is one of the most frequent sources for errors in a piece of software and often one of the most difficult ones to detect, especially when data is read from an outside source. Many mass copy functions provided by the C run-time provide versions that have boundary checking (defined with the _s suffix) but they can not guard against hard coded buffer lengths that at some point get changed. Finding the bug Getting back to the scenario, you’re now wondering why does the second string get modified with data that makes no sense at all. Luckily, Visual Studio provides you with a tool to help you with finding just these kinds of errors. It’s called data breakpoints. To add a data breakpoint, you first run your application in debug mode or attach to it in the usual way, and then go to Debug, select New Breakpoint and New Data Breakpoint. In the popup that opens, you can type in the memory address and the amount of bytes you wish to monitor. You can also use an expression here, but it’s often difficult to come up with an expression for data in an object allocated on the heap when not in the context of a certain stack frame. There are a couple of things to note about data breakpoints, however. First of all, Visual Studio supports a maximum of four data breakpoints at any given time. Another important thing to notice is that some C run-time functions modify memory in kernel space which does not trigger the data breakpoint. For instance, calling ReadFile on a buffer that is monitored by a data breakpoint will not trigger the breakpoint. The application will now break at the address you specified it to. Often you might immediately spot the issue but the very least this feature can do is point you in the right direction in search for the real reason why the memory gets inadvertently modified. Conclusions Data breakpoints are a great feature, especially when doing a lot of low level operations where multiple locations modify the same data. With the exception of some special cases, like kernel memory modification, you can use it whenever you need to check when memory at a certain location gets changed on purpose or inadvertently.

    Read the article

  • EclEmma JAVA Code coverage - Unable to coverage service layer of RESTful Webservice

    - by Radhika
    I am using EMMA eclipse plugin to generate code coverage reports. My application is a RESTFul webservice. Junits are written such that a client is created for the webservice and invoked with various inputs. However EMMA shows 0% coverage for the source folder. The test folder alone is covered. The application server(jetty server) is started using a main method. Report: Element Coverage Covered Instructions Total Instructions MyRestFulService 13.6% 900 11846 src 0.5% 49 10412 test 98% 1021 1434 Junit Test method: @Test public final void testAddFlow() throws Exception { Client c = Client.create(); WebResource webResource = c.resource(BASE_URI); // Sample files for Add String xhtmlDocument = null; Iterator iter = mapOfAddFiles.entrySet().iterator(); while (iter.hasNext()) { Map.Entry pairs = (Map.Entry) iter.next(); try { document = helper.readFile(requestPath + pairs.getKey()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /* POST */ MultiPart multiPart = new MultiPart(); multiPart.bodyPart(.... ........... ClientResponse response = webResource.path("/add").type( MEDIATYPE_MULTIPART_MIXED).post(ClientResponse.class, multiPart); assertEquals("TESTING ADD FOR >>>>>>> " + pairs.getKey(), Status.OK, response.getClientResponseStatus()); } } } Invoked service method: @POST @Path("add") @Consumes("multipart/mixed") public Response add(MultiPart multiPart) throws Exception { Status status = null; List<BodyPart> bodyParts = null; bodyParts = multiPart.getBodyParts(); status = //call to business layer return Response.ok(status).build(); }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >