Some bits this week
cmd quser says when the user logged on, handy for when the boss asks why I am packing up so early, because I got here early :)
Found what looks like a good book, The Icarus Deception: How High Will You Fly?
rainforestQA awesome to have that many testers on standby.
Good pod cast, software engineering daily.
At the moment I like the idea of getting a laptop with a Linux on to play with even if it is dual boot.
So here is a mess but it works, trying to write a program that turns an image into lego blocks.
package com.company;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
public class LegoPictureMaker {
public String filePath;
public BufferedImage img;
public int legoSquareSideLength;
public LegoPictureMaker(String filePath) {
this.legoSquareSideLength = 16;
this.filePath = filePath;
}
public void makeImage() {
System.out.println("Grabbing file...");
img = grabFile();
System.out.println("Processing lego blocks");
processFile();
System.out.println("Done!");
}
//process file
private void processFile() {
//work out of squares needed in width and height
int xTiles = img.getRaster().getWidth() / legoSquareSideLength;
int yTiles = img.getRaster().getHeight() / legoSquareSideLength;
//build image I can write to
BufferedImage buildImage;
buildImage = new BufferedImage(
(xTiles * legoSquareSideLength),
(yTiles * legoSquareSideLength),
BufferedImage.TYPE_INT_RGB);
int totalTiles = xTiles * yTiles;
int red= 0, green = 0, blue = 0;
int[] testArray = new int[3];
img.getRaster().getPixel(0,0, testArray);
//make something usable
WritableRaster writableRaster = (WritableRaster)buildImage.getData();
int[][][] averageColour = new int[xTiles][yTiles][3];
for(int x = 0; x < xTiles; x++) {
for (int y = 0; y < yTiles; y++) {
averageColour[x][y] = getAverageColour(x * legoSquareSideLength, y * legoSquareSideLength);
writeTileColour(writableRaster, x * legoSquareSideLength, y * legoSquareSideLength, averageColour[x][y]);
}
}
saveImage(buildImage, writableRaster);
}
private void writeTileColour(WritableRaster writableRaster, int xPoint, int yPoint, int[] rgbValues) {
int endX = xPoint + legoSquareSideLength;
int endY = yPoint + legoSquareSideLength;
for (int x = xPoint; x < endX; x++) {
for (int y = yPoint; y < endY; y++) {
writableRaster.setPixel(x, y, rgbValues);
}
}
}
private int[] getAverageColour(int xPoint, int yPoint) {
int red= 0, green = 0, blue = 0;
int endX = xPoint + legoSquareSideLength;
int endY = yPoint + legoSquareSideLength;
int[] testArray = new int[3];;
for (int i = xPoint; i < endX; i++) {
for (int j = yPoint; j < endY; j++) {
img.getRaster().getPixel(i,j, testArray);
red += testArray[0];
green += testArray[1];
blue += testArray[2];
}
}
int amountOfPixels = legoSquareSideLength * legoSquareSideLength;
return new int[] { red / amountOfPixels,
green / amountOfPixels,
blue / amountOfPixels};
}
//save image
public void saveImage(BufferedImage buildImage, WritableRaster writableRaster) {
//save and close file
buildImage.setData(writableRaster);
File outputFile = new File("testest.png");
try {
ImageIO.write(buildImage, "png", outputFile);
} catch (IOException ex) {
ex.printStackTrace();
}
}
//get the file
public BufferedImage grabFile() {
BufferedImage img = null;
if (filePath != null && !filePath.isEmpty()) {
try {
img = ImageIO.read(new File(this.filePath));
} catch (IOException ex) {
System.out.println("broke here");
ex.printStackTrace();
}
}
return img;
}
}
Wednesday, 18 November 2015
Wednesday, 11 November 2015
Challenge where I got stuck
Annoyed something so simple took this long and still doesn't bloody work correctly, waaah!
package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class PasswordGame {
public String[] guessWords;
public String password;
enum difficultySettings {VERY_EASY, EASY, MEDIUM, HARD, VERY_HARD}
difficultySettings difficulty;
public int amountOfGuesses;
public PasswordGame(difficultySettings aDifficulty) {
this.difficulty = aDifficulty;
getGuessWordsAndPassword(difficulty);
}
public void gameRun() {
System.out.println("You have " + amountOfGuesses + " guess");
System.out.println("Your word list: ");
printWordList();
boolean gameWon = false;
String wordGuess;
System.out.println("Password is: " + this.password);
while (!gameWon && amountOfGuesses > 0) {
wordGuess = getGuess();
if (wordGuess.equals(password)) {
gameWon = true;
} else {
amountOfGuesses--;
System.out.println("Unlucky: " + passwordCompare(wordGuess) + " guesses left: " + amountOfGuesses);
}
}
if (gameWon) {
System.out.println("You WIN!!!");
} else {
System.out.println("You lose :(");
}
}
private String passwordCompare(String wordGuess) {
int correctChar = 0;
int correctCharAndPlace = 0;
ArrayList<Character> passWordCopy = new ArrayList<>();
for (char aChar : password.toCharArray()) { passWordCopy.add(aChar); }
ArrayList<Character> guess = new ArrayList<>();
for (char aChar : wordGuess.toUpperCase().toCharArray()) { guess.add(aChar); }
for(int i = 0; i < guess.size() && i < passWordCopy.size(); i++) {
if (guess.get(i) == passWordCopy.get(i)) {
correctChar++; correctCharAndPlace++;
} else if ( passWordCopy.contains(guess.get(i))) {
correctChar++;
passWordCopy.set(i, '+');
}
}
return "correct chracter: " + correctChar + " and in the correct place: " + correctCharAndPlace;
}
private String getGuess() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String wordGuessed = "";
try {
wordGuessed = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return wordGuessed;
}
private void printWordList() {
for (String word : guessWords) {
System.out.println(word);
}
}
public String[] getGuessWordsAndPassword(difficultySettings aDifficulty) {
switch (aDifficulty) {
case VERY_EASY:
amountOfGuesses = 20;
populateWordsAndPassWord(10,5);
break;
case EASY:
amountOfGuesses = 15;
populateWordsAndPassWord(10,6);
break;
case MEDIUM:
amountOfGuesses = 12;
populateWordsAndPassWord(10,7);
break;
case HARD:
amountOfGuesses = 10;
populateWordsAndPassWord(10,8);
break;
case VERY_HARD:
default:
amountOfGuesses = 8;
populateWordsAndPassWord(10,9);
break;
}
return new String[]{};
}
private void populateWordsAndPassWord(int wordLength, int amountOfWords) {
ArrayList<String> filteredList = this.filteredWordList(wordLength, amountOfWords);
Collections.shuffle(filteredList);
this.guessWords = filteredList.toArray(new String[filteredList.size()]);
this.password = guessWords[new Random().nextInt(this.guessWords.length)];
}
private ArrayList<String> filteredWordList(int wordLength, int amountOfwords) {
FileReader fileReader;
BufferedReader bufferedReader;
Set<String> wordSet = new HashSet<>(); //set to filter duplicates
try {
fileReader = new FileReader("someplace\\enable1.txt");
bufferedReader = new BufferedReader(fileReader);
String word;
while ((word = bufferedReader.readLine()) != null) {
if(word.length() == wordLength) {
wordSet.add(word);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
ArrayList<String> words = new ArrayList<>(wordSet);
ArrayList<String> sizedWords = new ArrayList<>();
for (int i = 0; i < amountOfwords; i++) {
sizedWords.add(words.get(i).toUpperCase());
}
return sizedWords;
}
}
package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class PasswordGame {
public String[] guessWords;
public String password;
enum difficultySettings {VERY_EASY, EASY, MEDIUM, HARD, VERY_HARD}
difficultySettings difficulty;
public int amountOfGuesses;
public PasswordGame(difficultySettings aDifficulty) {
this.difficulty = aDifficulty;
getGuessWordsAndPassword(difficulty);
}
public void gameRun() {
System.out.println("You have " + amountOfGuesses + " guess");
System.out.println("Your word list: ");
printWordList();
boolean gameWon = false;
String wordGuess;
System.out.println("Password is: " + this.password);
while (!gameWon && amountOfGuesses > 0) {
wordGuess = getGuess();
if (wordGuess.equals(password)) {
gameWon = true;
} else {
amountOfGuesses--;
System.out.println("Unlucky: " + passwordCompare(wordGuess) + " guesses left: " + amountOfGuesses);
}
}
if (gameWon) {
System.out.println("You WIN!!!");
} else {
System.out.println("You lose :(");
}
}
private String passwordCompare(String wordGuess) {
int correctChar = 0;
int correctCharAndPlace = 0;
ArrayList<Character> passWordCopy = new ArrayList<>();
for (char aChar : password.toCharArray()) { passWordCopy.add(aChar); }
ArrayList<Character> guess = new ArrayList<>();
for (char aChar : wordGuess.toUpperCase().toCharArray()) { guess.add(aChar); }
for(int i = 0; i < guess.size() && i < passWordCopy.size(); i++) {
if (guess.get(i) == passWordCopy.get(i)) {
correctChar++; correctCharAndPlace++;
} else if ( passWordCopy.contains(guess.get(i))) {
correctChar++;
passWordCopy.set(i, '+');
}
}
return "correct chracter: " + correctChar + " and in the correct place: " + correctCharAndPlace;
}
private String getGuess() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String wordGuessed = "";
try {
wordGuessed = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return wordGuessed;
}
private void printWordList() {
for (String word : guessWords) {
System.out.println(word);
}
}
public String[] getGuessWordsAndPassword(difficultySettings aDifficulty) {
switch (aDifficulty) {
case VERY_EASY:
amountOfGuesses = 20;
populateWordsAndPassWord(10,5);
break;
case EASY:
amountOfGuesses = 15;
populateWordsAndPassWord(10,6);
break;
case MEDIUM:
amountOfGuesses = 12;
populateWordsAndPassWord(10,7);
break;
case HARD:
amountOfGuesses = 10;
populateWordsAndPassWord(10,8);
break;
case VERY_HARD:
default:
amountOfGuesses = 8;
populateWordsAndPassWord(10,9);
break;
}
return new String[]{};
}
private void populateWordsAndPassWord(int wordLength, int amountOfWords) {
ArrayList<String> filteredList = this.filteredWordList(wordLength, amountOfWords);
Collections.shuffle(filteredList);
this.guessWords = filteredList.toArray(new String[filteredList.size()]);
this.password = guessWords[new Random().nextInt(this.guessWords.length)];
}
private ArrayList<String> filteredWordList(int wordLength, int amountOfwords) {
FileReader fileReader;
BufferedReader bufferedReader;
Set<String> wordSet = new HashSet<>(); //set to filter duplicates
try {
fileReader = new FileReader("someplace\\enable1.txt");
bufferedReader = new BufferedReader(fileReader);
String word;
while ((word = bufferedReader.readLine()) != null) {
if(word.length() == wordLength) {
wordSet.add(word);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
ArrayList<String> words = new ArrayList<>(wordSet);
ArrayList<String> sizedWords = new ArrayList<>();
for (int i = 0; i < amountOfwords; i++) {
sizedWords.add(words.get(i).toUpperCase());
}
return sizedWords;
}
}
Tuesday, 10 November 2015
Short one
I went over board on an intermediate challenge so put off doing a post.
Links for much happiness,
http://12factor.net/
http://www.sunjw.us/jstoolnpp/ js tool, good plugin for notepad++
https://skillsmatter.com/ guys at work talking about clojure came across skills matter, over £2k to listen to uncle bob!
Got quite into evernote, beats the bits of paper I always lose by a large margin.
Since I am studying for the Java 8 OCA, http://enthuware.com/index.php apparently is the thing to do, the exam does seem quite pedantic to me but that also shows how dependent I am on autocomplete.
Links for much happiness,
http://12factor.net/
http://www.sunjw.us/jstoolnpp/ js tool, good plugin for notepad++
https://skillsmatter.com/ guys at work talking about clojure came across skills matter, over £2k to listen to uncle bob!
Got quite into evernote, beats the bits of paper I always lose by a large margin.
Since I am studying for the Java 8 OCA, http://enthuware.com/index.php apparently is the thing to do, the exam does seem quite pedantic to me but that also shows how dependent I am on autocomplete.
Sunday, 1 November 2015
Windows 10 start button not working and I also did a programming challenge
On windows 10 and needed some anti virus, installed Kaspersky, windows key no longer works and cannot click on any of the buttons except shortcuts. I may need another way of getting to applications other than win key and type.
Solution: https://www.techmesto.com/fix-start-menu-broken-windows-10-technical-preview/
Or run this in power shell
Solution: https://www.techmesto.com/fix-start-menu-broken-windows-10-technical-preview/
Or run this in power shell
Get-AppXPackage -AllUsers | Foreach {Add-AppxPackage
-DisableDevelopmentMode
-Register "$($_.InstallLocation)\AppXManifest.xml"}
Challenge 238 Easy consonants and vowels
package com.company;
import java.util.Random;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String inputString = "CVcvcvcc";
char[] consonants = "bcdfghjklmnpqrstvwxyz".toCharArray();
char[] vowels = "aeiou".toCharArray();
Random random = new Random();
Pattern pattern = Pattern.compile("[^vcVC]");
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
System.out.println("Invalid character in input");
} else {
StringBuilder output =
new StringBuilder(inputString.length());
for (char letter : inputString.toCharArray()) {
switch (letter) {
case 'c':
output.append(consonants[random.nextInt
(consonants.length)]);
break;
case 'C':
output.append(Character.toUpperCase
(consonants[random.nextInt(consonants.length)]));
break;
case 'V':
output.append(Character.toUpperCase
(vowels[random.nextInt(vowels.length)]));
break;
case 'v':
output.append(vowels[random.nextInt
(vowels.length)]);
break;
}
}
System.out.println(output);
}
}
}
Originally did this with multiple ifs' and it looked bloody awful.
Sunday, 25 October 2015
I'm not dead
I got a bit busy and a bit depressed
BCS foundation level test: DONE!
Changed the way I test, I need to get a better balance as it seems geared towards lots of documentation to the extent that I spend a lot of time documenting what I am doing rather than actually doing it. There has been the benefit that less is getting missed and managers can decide on risk relative to test cases run. A big benefit has been the confidence to say no and be able to back it up.
ITIL foundation: DONE!
Again a lot of documentation and process, a good trainer from Quanta. It was good as he was willing to engage and discuss that ITIL does not really deal with modern ways of doing project work (agile). From my point of view it is a way for the IT department to have the confidence to talk about business demands and maintaining a good relationship. It was an eye opener in what managers have to deal with in terms of scope creep.
BONUS, work paid for it all.
Getting back to programming now the above are out the way, started on the Java OCA 8, forgotten how much I enjoyed programming, big highs when it works, lows when it doesn't and a good challenge in between. So the habit I need to build is program everyday and build things, I want to mix in code challenges as a way of testing myself and doing something different.
And here is one I made earlier, I wanted an easy to paste example, it should have been a proper class.
BCS foundation level test: DONE!
Changed the way I test, I need to get a better balance as it seems geared towards lots of documentation to the extent that I spend a lot of time documenting what I am doing rather than actually doing it. There has been the benefit that less is getting missed and managers can decide on risk relative to test cases run. A big benefit has been the confidence to say no and be able to back it up.
ITIL foundation: DONE!
Again a lot of documentation and process, a good trainer from Quanta. It was good as he was willing to engage and discuss that ITIL does not really deal with modern ways of doing project work (agile). From my point of view it is a way for the IT department to have the confidence to talk about business demands and maintaining a good relationship. It was an eye opener in what managers have to deal with in terms of scope creep.
BONUS, work paid for it all.
Getting back to programming now the above are out the way, started on the Java OCA 8, forgotten how much I enjoyed programming, big highs when it works, lows when it doesn't and a good challenge in between. So the habit I need to build is program everyday and build things, I want to mix in code challenges as a way of testing myself and doing something different.
And here is one I made earlier, I wanted an easy to paste example, it should have been a proper class.
package com.company;
import java.io.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
private static HashSet<String> words = new HashSet<>();
public static void main(String[] args) {
//read file into a set
FileReader fileReader;
BufferedReader bufferedReader;
try {
fileReader = new FileReader("C:\\enable1.txt");
bufferedReader = new BufferedReader(fileReader);
String currentWord = "";
while ((currentWord = bufferedReader.readLine()) != null) {
words.add(currentWord);
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("File not found bro!");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("HDD broke bro!");
ex.printStackTrace();
}
// int how many lines to read
System.out.print("Lines to read: ");
Scanner scanner = new Scanner(System.in);
int linesToRead = scanner.nextInt();
// amount of lines specified above with string of what keys can be entered
String[] inputWords = new String[linesToRead];
for (int i = 0; i < linesToRead; i++) {
inputWords[i] = scanner.next();
}
System.out.println();
//output each user input line = longestWordFound
for (String word : inputWords) {
System.out.println(word + " = " + longestWordFromChars(word) );
}
}
// find the longest word that can be found using those keys
private static String longestWordFromChars(String chars) {
Pattern regex = Pattern.compile("\\b[" + chars + "]+\\b");
Matcher regexMatcher;
String longestWord = "";
for (String word : words) {
regexMatcher = regex.matcher(word);
if(regexMatcher.find()) {
if(word.length() > longestWord.length()) {
longestWord = word;
}
}
}
return longestWord;
}
}
Saturday, 18 July 2015
Another interview
It went OK i just panicked and forgot all the words, also if anyone interviews please do not ask them to work from a TV on the wall, what is so hard about getting them to use a proper workstation.
Any way from what I remember of the interview questions there were three, solve quadratic equations, formula given, connect to a db in c# and out order the values not to worry about displaying them, and a t-sql question from the pubs database.
Pubs was actually a not that easy to get hold of, a bit of searching and the database can be build by using a script from SQL from the trenches, use the script as the old db files are not compatible with modern iterations of mssql server.
Note code is not perfect as tried to keep to similar timescales
Question 1 & 2
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var dt = new DataTable();
var connectionString = @"Server=D\SQLEXPRESS;
Database=pubs;Integrated Security=true;";
var query = "SELECT * FROM authors";
var conn = new SqlConnection(connectionString);
var cmd = new SqlCommand(query, conn);
conn.Open();
var sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
conn.Close();
sda.Dispose();
DataView dv = dt.DefaultView;
dv.Sort = "au_lname ASC";
foreach (DataRow row in dv.ToTable().Rows)
{
Console.WriteLine("{0,-15}{1,-15}{2,-15}",
row["au_lname"], row["au_fname"], row["city"]);
}
var anAnswer = quadSolver(1, 9, 18);
Console.WriteLine("The answer is: {0} and {1}",
anAnswer.Item1, anAnswer.Item2);
Console.Read();
}
public static Tuple<double, double> quadSolver(double a, double b, double c)
{
double answer1 = 0.0;
double answer2 = 0.0;
answer1 = ((b * -1) + Math.Sqrt(Math.Pow(b, 2) -
(4 * a * c))) / (2 * a);
answer2 = ((b * -1) - Math.Sqrt(Math.Pow(b, 2) -
(4 * a * c))) / (2 * a);
return new Tuple<double, double>(answer1, answer2);
}
}
}
Question 3
SELECT (au_fname + ' ' + au_lname) AS NAME,
[PUBLISHED TITLES],
[AVERAGE COST],
[LAST PUBLISHED]
FROM authors AS A
JOIN
(
SELECT AU_ID,
COUNT(*) AS [PUBLISHED TITLES],
AVG(price) AS [AVERAGE COST],
FORMAT(MAX(pubdate), 'dd/MM/yyyy') AS [LAST PUBLISHED]
FROM [dbo].[titles] AS T JOIN [dbo].[titleauthor] AS TA
ON T.title_id = TA.title_id
GROUP BY au_id
) AS FT ON A.au_id = FT.au_id
ORDER BY NAME;
Any way from what I remember of the interview questions there were three, solve quadratic equations, formula given, connect to a db in c# and out order the values not to worry about displaying them, and a t-sql question from the pubs database.
Pubs was actually a not that easy to get hold of, a bit of searching and the database can be build by using a script from SQL from the trenches, use the script as the old db files are not compatible with modern iterations of mssql server.
Note code is not perfect as tried to keep to similar timescales
Question 1 & 2
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var dt = new DataTable();
var connectionString = @"Server=D\SQLEXPRESS;
Database=pubs;Integrated Security=true;";
var query = "SELECT * FROM authors";
var conn = new SqlConnection(connectionString);
var cmd = new SqlCommand(query, conn);
conn.Open();
var sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
conn.Close();
sda.Dispose();
DataView dv = dt.DefaultView;
dv.Sort = "au_lname ASC";
foreach (DataRow row in dv.ToTable().Rows)
{
Console.WriteLine("{0,-15}{1,-15}{2,-15}",
row["au_lname"], row["au_fname"], row["city"]);
}
var anAnswer = quadSolver(1, 9, 18);
Console.WriteLine("The answer is: {0} and {1}",
anAnswer.Item1, anAnswer.Item2);
Console.Read();
}
public static Tuple<double, double> quadSolver(double a, double b, double c)
{
double answer1 = 0.0;
double answer2 = 0.0;
answer1 = ((b * -1) + Math.Sqrt(Math.Pow(b, 2) -
(4 * a * c))) / (2 * a);
answer2 = ((b * -1) - Math.Sqrt(Math.Pow(b, 2) -
(4 * a * c))) / (2 * a);
return new Tuple<double, double>(answer1, answer2);
}
}
}
Question 3
SELECT (au_fname + ' ' + au_lname) AS NAME,
[PUBLISHED TITLES],
[AVERAGE COST],
[LAST PUBLISHED]
FROM authors AS A
JOIN
(
SELECT AU_ID,
COUNT(*) AS [PUBLISHED TITLES],
AVG(price) AS [AVERAGE COST],
FORMAT(MAX(pubdate), 'dd/MM/yyyy') AS [LAST PUBLISHED]
FROM [dbo].[titles] AS T JOIN [dbo].[titleauthor] AS TA
ON T.title_id = TA.title_id
GROUP BY au_id
) AS FT ON A.au_id = FT.au_id
ORDER BY NAME;
Wednesday, 8 July 2015
Github
Finally got github account set up and time to get updating my blog again!
https://github.com/Decimater/xfireDownloader
https://github.com/Decimater/xfireDownloader
Subscribe to:
Posts (Atom)
