Archive for September 2014
Validating a XML against XSD schema in C#
Inputs:
xmlFileName: Input XML file name
schemaFileName: Input XSD file name
Output:
results: Results output
using System.Xml; using System.Xml.Schema; using System.IO; static List<string> results = new List<string>(); static void Validate(string xmlFileName, string schemaFileName) { XmlDocument x = new XmlDocument(); string source = xmlFileName; x.Load(source); XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = true; settings.ValidationEventHandler += Handler; settings.ValidationType = ValidationType.Schema; settings.Schemas.Add(null, schemaFileName); settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation; StringReader r; using (StreamReader sr = new StreamReader(source)) { r = new StringReader(sr.ReadToEnd()); } using (XmlReader validatingReader = XmlReader.Create(r, settings)) { while (validatingReader.Read()) { /* just loop through document */ } } } private static void Handler(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning) results.Add(String.Format("Line: {0}, Position: {1} "{2}"", e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message)); }
Batch converting videos to play on the Nexus 7 using FFMPEG
How to batch convert videos to play on the Nexus 7 using FFMPEG in Python.
mypath = r'path_to_video_files' from os import listdir from os.path import isfile, join onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ] for file in onlyfiles: infile = '"' + mypath + file + '"' outfile = '"' + mypath + file + '.mp4' + '"' ffmpegpath = r'ffmpeg.exe' cmd = r' -i ' + infile + ' -acodec libmp3lame -vcodec libx264 -aspect 16:9 -s 800x480 -ab 128k -b 512k -f mp4 -strict experimental ' + outfile import os os.system(ffmpegpath + cmd)
Starting source:
Passing a datastructure between Android activities as JSON
Passing a data structure between Android activities as JSON using Gson.
In the sending Activity:
//Data Droplet data = new Droplet(); //Create intent Intent intent = new Intent(SendingClass.this, ReceivingClass.class); //Create JSON object from data structure Gson gson = new Gson(); String json = gson.toJson(data); //Add JSON to intent intent.putExtra("json", json); //Start Activity with intent startActivity(intent);
In the receiving Activity:
//Get string String json = extras.getString("json","-1"); //Convert JSON to class Gson gson = new Gson(); Droplet droplet = gson.fromJson(json, Droplet.class);
Where Droplet is defined here.
Going through a xlsx spreadsheet by column in Python
Most examples iterate by row. This one iterates by col.
import xlrd workbook = xlrd.open_workbook('test_file.xlsx') worksheet = workbook.sheet_by_index(0) num_cols = worksheet.ncols - 1 curr_col = -1 while curr_col < num_cols: #Iterate through cols curr_col += 1 col = worksheet.col(curr_col) for cell in col: #Iterate through cells in col print cell.value
Generating a file filled with random characters in Python
Generating a file filled with random characters in Python and printing out the elapsed time.
Output goes in tempOut.txt
#!/usr/bin/python import random import string import time start = time.time() f = open('tempOut.txt', 'w') for i in range(0,100000): line = '' for j in range(0,5000): line += str(random.choice(string.letters)) f.write(line + "n") line = '' f.close() end = time.time() print "Elapsed: " + str(end - start)
Getting a JSON object from DigitalOcean in Java
How to get a JSON object from DigitalOcean. This uses Gson.
Getting the HTTP object.
Inputs:
url: URL to access i.e. https://api.digitalocean.com/v2/droplets/
auth_key: Authorization key from DO.
import com.google.gson.Gson; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; private static InputStream retrieveStream(String url, String auth_key) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("Authorization","Bearer " + auth_key); try { HttpResponse getResponse = client.execute(getRequest); statusCode = getResponse.getStatusLine().getStatusCode(); HttpEntity getResponseEntity = getResponse.getEntity(); return getResponseEntity.getContent(); } catch (IOException e) { getRequest.abort(); } return null; }
Converting the response into a Java object:
InputStream stream = retrieveStream(url, auth_key); Reader reader = new InputStreamReader(stream); Gson gson = new Gson(); Droplets response = gson.fromJson(reader, Droplets.class);
Where Droplets.class is implemented like this and Droplet.class is implemented like this.
C#: Recursively getting a list of files with a specific extension
How to recursively get a list of files with a specific extension in C#.
Inputs:
sDir – Starting directory
SExtension – file extension to filter by
List files – A empty list that is used to keep found files while recursing.
public List<string> getFiles(string sDir, string sExtension, List<string> files) { foreach (string d in Directory.GetDirectories(sDir)) { foreach (string f in Directory.GetFiles(d)) { if (f.EndsWith(sExtension)) { files.Add(f); } } getFiles(d, sExtension, files); } return files; }
Starting Source:
http://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c
Browsing through Amazon’s Top 10 Best Sellers
This project lets you browse through Amazon’s various product categories and view the top 10 sellers for that category. You can browse down into sub-categories as well as up into parent categories.
I wrote this to learn about Amazon’s Product Advertising API. Using the API is simple, especially with the sample code provided by Amazon. Amazon returns a lot of information, so the slightly tricky part was figuring out how to parse the XML to get only the information I need.
RSS Feed Creator with hosting
Need a way to get your audiobooks, open courseware, videos, or other content onto your podcast player? The RSS Feed Maker will take your URLs and convert them into a RSS document and give you a URL to give to your podcast player.
The RSS feed is created with Argotic and the files are hosted on Amazon’s S3 file hosting service.