Public
snipts » file
showing 1-20 of 37 snipts for file
-
∞ Make file from clipboard data
package buildfromcbd; // import java.awt.Toolkit; import java.awt.datatransfer.*; import java.io.*; // public class Main { //this will be where we split up our values private static final String VALUE_SEPARATOR = ":::"; // public static void main(String[] args) throws IOException, UnsupportedFlavorException { build(); } public static String getClipboard() throws UnsupportedFlavorException, IOException { // here we grab the contents of the clipboard Transferable tran = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); try { if (tran != null && tran.isDataFlavorSupported(DataFlavor.stringFlavor)) { String text = (String)tran.getTransferData(DataFlavor.stringFlavor); return text; } } catch (UnsupportedFlavorException e) { return "CBD_BUILD_FAILED.txt::: Could not build file, JAVA error report as fallows:\n\n"+e; } catch (IOException e) { return "CBD_BUILD_FAILED.txt::: Could not build file, JAVA error report as fallows:\n\n"+e; } return null; } public static void build()throws IOException, UnsupportedFlavorException { Writer output = null; String text = getClipboard(); String[] cbd = parseCBD(text); //so our fist value will be our file name File file = new File(cbd[0]); //lets get our file open for writing now output = new BufferedWriter(new FileWriter(file)); //if cbd has a second value lets write it to our files contents if(cbd.length>1) { output.write(cbd[1]); }else{ // if we don't have a second value lets print "EMPTY :(" in our file output.write("EMPTY :("); } output.close(); } public static String[] parseCBD(String cb_txt) { //let's sperate our values out String[] cbd = cb_txt.split(VALUE_SEPARATOR); //in this function you could do more than just split the data, get creative :) return cbd; } }
-
∞ VB6: Write a message in a daily log
Public Sub WriteLog(Message As String) Dim fso, fileName As String, logString As String, f as Integer fileName = App.path & "\Log_" & Format(Now, "yyyymmdd") & ".txt" logString = Format(Now, "hh:mm:ss") & " - " & Message f = Freefile Open fileName For Append As #f Print #f, logString Close #f End Sub
-
∞ match my PM list to Hanno's TETRA results
import sys import re from sets import Set f = open ('/Users/user/Downloads/PM-1.txt') pm_match = re.compile (r'\d+_(\S+)') pms = set() unique = set() for line in f.readlines(): pm_result = pm_match.match (line.rstrip()) if pm_result: pms.add(pm_result.group(1)) f.close() #print pms matchobj = re.compile (r'(\S+):\s+\d+\.\d+') f_match = re.compile (r'f_(\d+)[a-z]+_\w+') a_match = re.compile (r'a4_([0-9a-z]+)_\w+') for line in sys.stdin: names = line.split("\t") output = "" for name in names: result = matchobj.match (name) if result: #print result.group(1) f_result = f_match.match (result.group(1)) if f_result: PM_name = "fc1f" + f_result.group(1) if PM_name in pms: unique.add(PM_name) a_result = a_match.match (result.group(1)) if a_result: PM_name = "anke4-" + a_result.group(1) if PM_name in pms: unique.add(PM_name) print len(unique) #print output.rstrip()
-
∞ Log errors in diffent folders/files reflecting the application folder structure.
<?php /** * Log PHP's error into separate files. Recommended for use in production site. * Should be used in set_error_handler() to handle certain PHP errors (i.e. E_STRICT). * @link http://www.php.net/manual/en/function.set-error-handler.php Reference */ function errorHandler($errno, $errstr, $errfile=NULL, $errline=NULL, $errcontext=NULL) { // Log uncategorized errors if (is_null($errfile)) { $errfile = 'errors.log'; } // Reconstruct the path // define('APP_DIR', '/my/application/') // define('LOG_DIR', '/log_dir/') // E.g. /my/application/controller/index.php -> /log_dir/controller/index.php $pos = strpos($errfile, APP_DIR); if ($pos !== FALSE) { // Strip off the application directory and attach log directory $errfile = LOG_DIR.substr($errfile, $pos + strlen(CMS_ROOT)); } else { $errfile = LOG_DIR.$errfile; // E.g. /log_dir/errors.log } $dir = dirname($errfile); // Create dir if necessary if (! file_exists($dir)) { mkdir($dir, 0775, TRUE); } $logFile = fopen($errfile, 'a'); fwrite($logFile, date('Y-m-d H:i:s ').$errstr); if ($errline) fwrite($logFile, " on line $errline"); fwrite($logFile, "\n"); fclose($logFile); if (PRODUCTION_SITE) // Prevent err msg from being printed out (log errors silently) return TRUE; return FALSE; } ?>
-
∞ Usage of Unix fuser
# Find process associated with a port $ fuser 80/tcp 80/tcp: 802 803 804 806 807 808 809 810 811 812 813 23556 23561 23562 23563 23564 23565 23566 23567 23568 28574 # Find process and users associated with a port $ fuser -nu tcp 80 80/tcp: 802(apache) 803(apache) 804(apache) 806(apache) 807(apache) 808(apache) 809(apache) 810(apache) 811(apache) 812(apache) 813(apache) 23556(root) 23561(apache) 23562(apache) 23563(apache) 23564(apache) 23565(apache) 23566(apache) 23567(apache) 23568(apache) 28574(apache) # Kills a process that is locking a file. Useful when you're trying to unmount a volume and other sticky situations where a rogue process is annoying the hell out of you. $ fuser -k /tmp/blocked_file
-
∞ Print a file line for line in Java (the 1.6 way)
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class SlugTester { static String FILENAME = "C:\\slug-test.txt"; public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader(FILENAME)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
-
∞ File object for logging loggers
To get access to underlying stream (filelike) object in Python's logging system: logger.handlers[0].stream You'll have to figure out which handler for a logger object you want. I've only got one in my sample code. This snipt allows one to pass this stream object into interfaces that are expecting a file object.
-
∞ Search file by content (improved)
grep -r 'public static void main(' . #will do the same thing. In fact, you can also use grep -rI 'public static void main(' . #for searching only text files. And if you only want to list the files without the matching content, use grep -rI –files-without-matches 'public static void main(' .
-
∞ Search file by content.
find . -type f | xargs grep 'public static void main(' -
∞ File I/O with semicolon Delimited
//Examples of file I/O //Another read example to read in a score.txt data file #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream DataIn("d:\\C++ Projects\\data.txt"); //edit file location for individual computers ofstream DataOut("d:\\C++ Projects\\output.txt"); //edit file location for individual computers if (DataIn.fail()) //check for file existence { cout << "File does not exist!" << endl; cout << "Program exits." << endl; cin.get(); return 0; } //data I/O char nameID[100]; do { DataIn.getline(nameID, 100, ';'); //reads in data until semicolon is detected cout << nameID << endl; //outputs data that was read from file DataOut << nameID << ";"; //Outputs data read in from data.txt into another text file output.txt }while(!DataIn.eof()); DataOut.close(); DataIn.close(); cin.get(); // pause to show screen output return 0; }
-
∞ Cleans up file names, strips invalid characters
$filename = preg_replace('/[^0-9a-z\.\_\-]/i','',$original_filename); -
∞ returns just the filename from a path string
$name = "somefilenamestring.php"; $ext = strrchr($name, '.'); if($ext !== false) $name = substr($name, 0, -strlen($ext));
-
∞ Delphi_GetParentDirectory
//returns the parent directory for the //provided "path" (file or directory) function GetParentDirectory(path : string) : string; begin result := ExpandFileName(path + '\..') end;
-
∞ create a file with unique filename
<?php //Create a file with unique filename $thetime = time(); $filename = "testfile".$thetime.".php"; if(!is_file($filename)) { fopen($filename,"x"); echo "File " . $filename . " created successfully."; } else { echo "File " . $filename . " already exists."; } ?>
-
∞ PHP return name of latest modified file
<? function searchDIRforLatestFile($dirOpen,$regex) { //searches through directory dirOpen, returns latest file matching regex $this->filetlist = array(); if ($dir = @opendir($dirOpen)) { while (($file = readdir($dir)) !== false) { if(is_file($dirOpen."/".$file)) { if (strcmp($file,".") and strcmp($file,"..")) { if(ereg($regex, $file)) $this->filetlist [$file] = filemtime ($dirOpen.'/'.$file); } } } closedir($dir); if(count($this->filetlist)>0) { arsort($this->filetlist); //sort into date order latest first $this->filetlist = array_reverse($this->filetlist); //latest now at the end $this->filetlist = array_flip($this->filetlist); //flip keys for values return array_pop ($this->filetlist); //pop latest file of the end } } } ?>
-
∞ Purge Directory
use strict; # This file is used to remove old log files from the given directories. # The syntax of the file is # perl purgeMigrationDirectory.pl DirectoryName NumberOfDaysToPurge # # This will remove all old log files that are older than ARGV[1] days old # Old log files include any text file with _error.txt _log.txt _export.xml _audit.txt # It will not remove any other folders or files if(($#ARGV + 1) == 2){ &startThePurge($ARGV[0], $ARGV[1]); } else{ &printHelp(); } #print help message to the console if the correct number of arguments are not supplied sub printHelp{ print "You must provide the full path of the directory you wish to " . "purge of old migration log files and the number of days back you wish to purge.\nExample:\n\n" . "perl purgeMigrationDirectory.pl 'C:\\ICC Migration Tool\\InformaticaOutputDir' 60 would purge the directory of any of the log files that are older than 60 days.\n\n" . "See the script for more details."; } #purge migration log files sub startThePurge{ #check to see if the directory exists if (-d @_[0]){ my $inputDir = shift; my $numFilesRemoved = 0; my $numDays = shift; print "Removing old migration files from " . $inputDir . " that are older than " . localtime(time() - 60*60*24*$numDays) ."\n"; #open input directory opendir(DIR, $inputDir); #only look at files with the following appends #_error.txt #_log.txt #_audit.txt #_export.xml #_query.txt #_cntl.txt foreach my $file (grep { /_(error.txt|log.txt|audit.txt|query.txt|cntl.txt|export.xml)$/} readdir DIR) { my $tempdm = (stat $inputDir . "\\" . $file)[9]; my $age = int(-M $inputDir . "\\" . $file); if($age >= $numDays){ #remove files older than two months print "Removing file " . $file . " because it was last modified on " . localtime($tempdm) . " days old.\n"; unlink($inputDir . "\\" . $file); #remove file $numFilesRemoved = $numFilesRemoved + 1; } } print "Removed " . $numFilesRemoved . " files from " . $inputDir . "\n"; } #directory does not exist else{ print STDERR @_[0] . " does not exist. Please try again"; } }
-
∞ List Todays Modified Files
find . -mtime -1 -type f -exec ls -lt {} \;
-
∞ Read CSV File
<? $fp = fopen($csv_file,'r'); while (($data = fgetcsv($fp, 1000, ",")) !== false) { // make sure we all 6 columns and it isn't the header if (count($data) == 6 && $data[0] != 'Name') { // extract the data $name = $data[0]; } } fclose($fp);
-
∞ alllow URL to find most up to date file in directory
//lowercase for file name $lc_lang = strtolower($_GET['lang']); $lc_filename = strtolower($_GET['file']); $lc_program = strtolower($_GET['program']); //clean the variables before processing validateVariable is a custom function we have built for executing a regular expression you can just pass through a regex however you would like to clean $clean_filename = validateVariable($lc_filename, 'regular', 255); $clean_lang = validateVariable($lc_lang, 'regular', 2); //initialize file time array $filetimes=array(); //tell where the files are stored - place the files in the same directory as this file but in a subfolder you want to call the language $files = scandir("./$clean_lang/"); // you can also specify further directories //loop through each file in the directory foreach ($files as $file){ //each file is named with 3 letters in the beginning of the file name that we use to determine the type of file not the extension - this example was designed for all the same file type $type=substr($file, 0, 3); if($type==$clean_filename){ //check when each file was created - you can specify a further directories $time=filemtime("./$clean_lang/"$file); $filetimes[$file]=$time; } } //sort the files arsort($filetimes); //cycle through the array but stop after first element is called- that is all we need foreach($filetimes as $filename => $filetime){ Header( "HTTP/1.1 302 Moved Temporarily" ); header( "Location: ./".$clean_lang."/".$filename ); break; } //Authored by Brian Thopsey http://topcweb.com
-
∞ list all file paths matching an extension in a given directory using the glob module
>>> import os >>> import glob >>> directory = os.getcwd() >>> for filePath in glob.glob(os.path.join(directory, '*.png')): ... print filePath ... /foobar.png /spam.png



Using Drupal