<commit_before>//
//  AppDelegate.swift
//  RUG
//
//  Created by m-nakada on 11/12/2014.
//  Copyright (c) 2014 mna. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  @IBOutlet weak var window: NSWindow!
  @IBOutlet weak var pictureView: NSImageView!
  @IBOutlet weak var usernameTextField: NSTextField!
  @IBOutlet weak var nameTextField: NSTextField!
  @IBOutlet weak var emailTextField: NSTextField!
  @IBOutlet weak var legoSwitch: NSButtonCell!
  @IBOutlet weak var progressIndicator: NSProgressIndicator!
  @IBOutlet weak var refreshButton: NSButton!
  @IBOutlet weak var saveImageButton: NSButton!
  @IBOutlet weak var copyButton1: NSButton!
  @IBOutlet weak var copyButton2: NSButton!
  @IBOutlet weak var copyButton3: NSButton!
  
  var copyButtons: Array<NSButton> = [];
  var textFileds: Array<NSTextField> = [];
  var pictureData = NSData();

  func applicationDidFinishLaunching(aNotification: NSNotification) {
    // Insert code here to initialize your application
    self.copyButtons = [self.copyButton1, self.copyButton2, self.copyButton3]
    self.textFileds  = [self.usernameTextField, self.nameTextField, self.emailTextField]
  }

  func applicationWillTerminate(aNotification: NSNotification) {
    // Insert code here to tear down your application
  }

  @IBAction func refreshAction(sender: AnyObject) {
    self.getRondomUser()
  }
  
  @IBAction func saveAction(sender: AnyObject) {
    // Export image to Desktop
    let path = NSHomeDirectory().stringByAppendingString("/Desktop/\(self.nameTextField.stringValue).jpg")
    self.pictureData.writeToFile(path, atomically: true)
  }
  
  @IBAction func copyAction(sender: AnyObject) {
    // Copy to pasteboard
    let str = self.textFileds[sender.tag()].stringValue
    let pb = NSPasteboard.generalPasteboard()
    pb.declareTypes([NSStringPboardType], owner: self)
    pb.setString(str, forType: NSStringPboardType)
  }
  
  func startLoding() {
    self.progressIndicator.startAnimation(self)
    self.pictureView.image = nil
    self.usernameTextField.stringValue = ""
    self.nameTextField.stringValue = ""
    self.emailTextField.stringValue = ""
  }
  
  func stopLoding() {
    self.progressIndicator.stopAnimation(self)
  }
  
  func getRondomUser() {
    self.startLoding()
    
    let url = self.legoSwitch.state == NSOnState ? "http://api.randomuser.me/0.4/?lego" : "http://api.randomuser.me/"
    let request = NSURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    
    // Download JSON
    var resultsTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
      if (data != nil) {
        var error: NSError?
        let json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) as NSDictionary
        println("json \(json)")
        
        // Retrieve user
        let results = json["results"] as NSArray
        let user = results.firstObject?.objectForKey("user") as NSDictionary
        
        // Retrieve name
        let name  = user["name"] as NSDictionary
        let first = name["first"] as String
        let last  = name["last"] as String
        
        let username = user["username"] as String
        let email = user["email"] as String
        
        // Retrieve picture url
        let pictureObj = user["picture"] as NSObject
        var picture = "" as String

        // For LEGO
        if pictureObj is NSString {
          picture = user["picture"] as String
        }

        // For Normal
        if pictureObj is NSDictionary {
          let pictureDict = user["picture"] as NSDictionary
          picture = pictureDict["large"] as String
        }

        // Download Picture
        let pictureRequest = NSURLRequest(URL: NSURL(string: picture)!)
        var pictureTask = session.dataTaskWithRequest(pictureRequest, completionHandler: { (data, respoonse, error) -> Void in
          let image = NSImage(data: data)
          self.pictureData = data;
          self.stopLoding()
          
          // Update UI
          dispatch_async(dispatch_get_main_queue()) {
            self.pictureView.image = image
            self.nameTextField.stringValue = first.capitalizedString + " " + last.capitalizedString
            self.usernameTextField.stringValue = first + "-" + last
            self.emailTextField.stringValue = email
          }
        })
        
        pictureTask.resume()
      }
    })
    
    resultsTask.resume()
  }
}<commit_msg>Add Himotoki support and refactoring<commit_after>//
//  AppDelegate.swift
//  RUG
//
//  Created by m-nakada on 11/12/2014.
//  Copyright (c) 2014 mna. All rights reserved.
//

import Cocoa
import Himotoki

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  // MARK: - Outlet
  
  @IBOutlet weak var copyButton1: NSButton!
  @IBOutlet weak var copyButton2: NSButton!
  @IBOutlet weak var copyButton3: NSButton!
  @IBOutlet weak var emailTextField: NSTextField!
  @IBOutlet weak var legoSwitch: NSButton!
  @IBOutlet weak var legoSwitchCell: NSButtonCell!
  @IBOutlet weak var nameTextField: NSTextField!
  @IBOutlet weak var pictureView: NSImageView!
  @IBOutlet weak var progressIndicator: NSProgressIndicator!
  @IBOutlet weak var refreshButton: NSButton!
  @IBOutlet weak var saveImageButton: NSButton!
  @IBOutlet weak var usernameTextField: NSTextField!
  @IBOutlet weak var window: NSWindow!

  // MARK: - Property
  
  var buttons:    [NSControl] = []
  var textFileds: [NSControl] = []
  var controls:   [NSControl] = []
  var pictureData: NSData?
  
  // MARK: - NSApplicationDelegate
  
  func applicationDidFinishLaunching(notification: NSNotification) {
    buttons    = [legoSwitch, refreshButton, saveImageButton, copyButton1, copyButton2, copyButton3]
    textFileds = [usernameTextField, nameTextField, emailTextField]
    controls   = buttons + textFileds
  }

  // MARK: - Action
  
  @IBAction func refreshAction(sender: AnyObject) {
    getRondomUser()
  }
  
  @IBAction func saveAction(sender: AnyObject) {
    // Export image to Desktop
    let path = NSHomeDirectory() + "/Desktop/\(nameTextField.stringValue).jpg"
    pictureData?.writeToFile(path, atomically: true)
  }
  
  @IBAction func copyAction(sender: AnyObject) {
    // Copy to pasteboard
    let str = textFileds[sender.tag()].stringValue
    let pb = NSPasteboard.generalPasteboard()
    pb.declareTypes([NSStringPboardType], owner: self)
    pb.setString(str, forType: NSStringPboardType)
  }
  
  // MARK: - Helper
  
  func startLoding() {
    progressIndicator.startAnimation(self)
    pictureView.image = nil
    usernameTextField.stringValue = ""
    nameTextField.stringValue = ""
    emailTextField.stringValue = ""
    controls.forEach { $0.enabled = false }
  }
  
  func stopLoding() {
    progressIndicator.stopAnimation(self)
    controls.forEach { $0.enabled = true }
  }
  
  func getRondomUser() {
    startLoding()
    let url = legoSwitch.state == NSOnState ? "http://api.randomuser.me/?lego" : "http://api.randomuser.me/"
    let request = NSURLRequest(URL: NSURL(string: url)!)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
      guard let data = data else { return }
      
      do {
        guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String: AnyObject] else { return }
        let rug: RUG = try decode(json)
        guard let result = rug.results.first else { return }
        
        self.downloadPicture(result.user.picture)
        
        dispatch_async(dispatch_get_main_queue()) {
          self.nameTextField.stringValue     = result.user.displayName
          self.usernameTextField.stringValue = result.user.username
          self.emailTextField.stringValue    = result.user.email
        }
        
      } catch let error as NSCocoaError {
        print(error)
      } catch let DecodeError.MissingKeyPath(keyPath) {
        print("Missing key path: \(keyPath)")
      } catch {
        print("Unknwon decode error")
      }
    }
    task.resume()
  }
  
  func downloadPicture(picture: Picture) {
    guard let url = NSURL(string: picture.large) else { return }
    
    let task = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url)) { (data, respoonse, error) in
      dispatch_async(dispatch_get_main_queue()) { self.stopLoding() }
      
      guard let data = data, image = NSImage(data: data) else { return }
      self.pictureData = data;
      
      dispatch_async(dispatch_get_main_queue()) {
        self.pictureView.image = image
      }
    }
    task.resume()
  }
  
}
{'fraction_non_alphanumeric': 0.10041077133728891, 'fraction_numerical': 0.004564125969876769, 'mean_word_length': 3.002283105022831, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7421418', 'n_tokens_mistral': 2649, 'n_tokens_neox': 2607, 'n_words': 628}