Read file

file io swift 2.2

        let fileLocation = NSBundle.mainBundle().pathForResource("2311393", ofType: "xml")!
        let text : String
        do
        {
            text = try String(contentsOfFile: fileLocation)
        }
        catch
        {
            text = ""
        }

Tags: 

App installed

func isAppInstalled(name:String)->Bool {
    return UIApplication.sharedApplication().canOpenURL(NSURL(string:"\(name):")!)
}

Tags: 

Meteor setup project with accounts

Router:

meteor add iron:router

Bootstrap:

meteor add twbs:bootstrap

Accounts:

meteor add accounts-ui accounts-password
meteor add joshowens:accounts-entry
meteor npm install --save bcrypt
meteor add check

adjust client with code from
https://github.com/Differential/accounts-entry/

meteor

Install
cd $HOME

git clone --depth 1 https://github.com/4commerce-technologies-AG/meteor.git

#now it installs if it is the first time!
$HOME/meteor/meteor --version

==========================
======= slow version =======
==========================

cd $HOME

git clone --depth 1 https://github.com/4commerce-technologies-AG/meteor.git

cd meteor

Build bundled node:

scripts/build-node-for-dev-bundle.sh

Get mongodb installation from OS (e.g. Debian based):

sudo apt-get install mongodb

Optional (long runner) build bundled mongo:

scripts/build-node-for-dev-bundle.sh
Beneath the compiler and development tools and standard libaries, you have to also install the zlib1g-dev (or whatever it's named on your OS) library sources. Otherwise the mongo build will fail with an error like "-lz is missing"

Build meteor dev_bundle:

scripts/generate-dev-bundle.sh

Check installed version:

$HOME/meteor/meteor --version
==========================
========= helpfull snips =====
==========================

cd $HOME

# get the command line to checkout the meteor example
$HOME/meteor/meteor create --example simple-todos-react

# this is what you will receive as command hint, so put it in
git clone https://github.com/meteor/simple-todos-react

# jump into the project folder
cd simple-todos-react

# get necessary npm stuff
$HOME/meteor/meteor npm install

# bring that project up to latest module updates
$HOME/meteor/meteor update --packages-only

# add one package to avoid counting of modules usage and DDP error message on start
$HOME/meteor/meteor add package-stats-opt-out

# run that app
$HOME/meteor/meteor

Raspberry gpio

Read value

import RPi.GPIO as GPIO

# read value
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.IN)
poweron = GPIO.input(21)
GPIO.cleanup(21)

print "turnonheater"
    GPIO.setup(21,GPIO.OUT, initial=GPIO.HIGH)
    GPIO.output(21, GPIO.HIGH)
    GPIO.cleanup(21)

print "turnoffheater"
    GPIO.setup(21,GPIO.OUT, initial=GPIO.LOW)
    GPIO.output(21, GPIO.LOW)
    GPIO.cleanup(21)

Crash Log Helper

.h

@interface CrashLogHelper : NSObject

+(void) writeNoCrashFile;
+(void) removeNoCrashFile;

.m
+(void) writeNoCrashFile
{
    NSError *error;
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"crashloggername.txt"];
    NSLog(@"file path for write nocrash file%@", filePath);
    NSFileManager *filemgr;
   
    filemgr = [NSFileManager defaultManager];
   
    if ([filemgr fileExistsAtPath: filePath ] == YES)
    {
        NSLog (@"File exists, so it did crash");
        [App.persistenceHelper setString:@"-1" forPersistentKey:PERSISTENCEHELPER_ratingsequence];
    }
    else
    {
        NSLog (@"File not found");
        // write new file
        NSString *stringToWrite = @"no crash";
        [stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }
}
+(void) removeNoCrashFile
{
    NSFileManager *filemgr;
    NSError *error;
    filemgr = [NSFileManager defaultManager];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"crashlogger.txt"];
  
    if ([filemgr fileExistsAtPath: filePath ] == YES){
        NSLog (@"File exists so remove");
        BOOL success = [filemgr removeItemAtPath:filePath error:&error];
        if (success) {
            NSLog(@"file removed");
        }
        else
        {
            NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
        }
    }
    else{
        NSLog (@"File not found"); // something fishy
    }
   
}

Tags: 

Screenwidth screen height

+ (CGFloat) getScreenWidth
{
    CGFloat swidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat sheight = [UIScreen mainScreen].bounds.size.height;
    return MIN(swidth, sheight);
}

+ (CGFloat) getScreenHeight
{
    CGFloat swidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat sheight = [UIScreen mainScreen].bounds.size.height;
    return MAX(swidth, sheight);
}

Tags: 

Read Write file IO

+(void) writeTextFile
{
    NSError *error;
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"text.txt"];
    NSFileManager *filemgr;
   
    filemgr = [NSFileManager defaultManager];
   
    if ([filemgr fileExistsAtPath: filePath ] == YES)
    {
        NSLog (@"File exists");
    }
    else
    {
        NSLog (@"File not found");
        // write new file
        NSString *stringToWrite = @"text text text";
        [stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }
}
+(void) removeTextFile
{
    NSFileManager *filemgr;
    NSError *error;
    filemgr = [NSFileManager defaultManager];
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"text.txt"];
  
    if ([filemgr fileExistsAtPath: filePath ] == YES){
        NSLog (@"File exists so remove");
        BOOL success = [filemgr removeItemAtPath:filePath error:&error];
        if (success) {
            NSLog(@"file removed");
        }
        else
        {
            NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
        }
    }
    else{
        NSLog (@"File not found"); // something fishy
    }
   
}

Tags: 

port mysql

SHOW GLOBAL VARIABLES LIKE 'PORT';

Tags: 

Drupal small core update drush

sudo apt-get update

put in maintenance mode:
drush vset --exact maintenance_mode 1 drush cache-clear all
update:
drush pm-update drupal
put out of maintenance mode:
drush vset --exact maintenance_mode 0 drush cache-clear all

Swift raspberry

sudo apt-get update
sudo apt-get install -y clang
wget https://s3-us-west-2.amazonaws.com/swiftpi.swiftlite.v1/swift-lite-3.0-r...
sudo tar -xzpf swift-lite-3.0-raspberrypi-universal.tar.gz -C/

examples
wget https://s3-us-west-2.amazonaws.com/swiftpi.swiftlite.v1/helloworld3.tar.gz
tar -xzpf helloworld3.tar.gz

cleanup
rm swift-lite-3.0-raspberrypi-universal.tar.gz helloworld3.tar.gz

to build
cd swiftProjects
swift-lite-build helloworld.swift

test/run
./helloworld.swapp

swift server Kitura

first

mkdir tuinhok
cd tuinhok
swift package init --type executable

adjust Package.swift
import PackageDescription


let package = Package(
  name: "proj1",
  dependencies: [
    .Package(url: "https://github.com/IBM-Swift/Kitura.git",
             majorVersion: 1),
    .Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1),
    .Package(url: "https://github.com/IBM-Swift/Kitura-StencilTemplateEngine.git", majorVersion: 1)
    ]
)

swift package generate-xcodeproj
mkdir public - for js css img etc
mkdir Views - for stencil files

in main swift
import Kitura
import LoggerAPI
import HeliumLogger
import KituraStencil

HeliumLogger.use(.info)
let router = Router()
router.setDefault(templateEngine: StencilTemplateEngine())
router.all("/static", middleware: StaticFileServer())

router.get("/") {
  request, response, next in
  defer { next() }
  try response.render("home", context: [:])
}

Kitura.addHTTPServer(onPort: 8090, with: router)

Kitura.run()

Tags: 

size database

SELECT table_schema NAMEOFDB,
sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB"
FROM information_schema.TABLES GROUP BY table_schema ;

Tags: 

xcode 3.7.1 cocoapods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'testNetworkingOperation' do
    pod 'Alamofire', '~> 3.0'
     pod 'SwiftyJSON', '2.4.0'
end

Tags: 

nodejs express

npm init

npm install express --save
npm install body-parser --save
npm install nodemon --save / --g
npm install bcryptjs --save

create app.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('listening on port 3000')
})

Tags: 

Symphony snips

timezone
in app kernel.php

public function __construct($environment, $debug)
{
    date_default_timezone_set('Europe/Amsterdam');
    parent::__construct($environment, $debug);
}

server:
php bin/console server:run

php bin/console generate:bundle

composer require knplabs/knp-menu-bundle dev-master

bin/console doctrine:database:create
( drop:
bin/console doctrine:database:drop --force
)

bin/console doctrine:generate:entity
bin/console doctrine:schema:update --force

Fish, bash commands as functions

make Atom.app run from terminal:

ln -s /Applications/Atom.app/Contents/Resources/app/atom.sh /usr/local/bin/atom

make function in Fish:
nano ~/.config/fish/functions/atom.fish

some functions:
function atom
    bash -c 'atom .'
end

function xcodeclean
        command rm -rf ~/Library/Developer/Xcode/DerivedData/*
end

function ll
    ls -lahG $argv
end

Tags: 

log vector

// log vector
for (auto const& c : numbers)
{
    std::cout << c << ' ';
}

Tags: 

Before After in collection

public extension Collection where Iterator.Element: Equatable {

public func after(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(after: idx) < endIndex else { return nil }
let nextIdx = index(after: idx)
return self[nextIdx]
}

public func before(_ element: Iterator.Element) -> Iterator.Element? {
guard let idx = index(of: element), index(before: idx) >= startIndex else { return nil }
let previousIdx = index(idx, offsetBy: -1)
return self[previousIdx]
}

public func index(before idx: Index) -> Index {
return index(idx, offsetBy: -1)
}
}

Tags: 

ZoomableGridVC

enum GridFillDirection
{
    case Horizontal, Vertical
}

class ZoomableGridViewController: UIViewController,UIScrollViewDelegate {
   
    //MARK: - Properties
   
    var scrollView: UIScrollView!
    var scrollIsZoomedIn = false
    var gridView: UIView!//Grid!//or image etc
   
    var puzzleDirection:GridFillDirection = .Horizontal
   
    var logText:UILabel!
   
    //MARK: - VC
    override func viewDidLoad() {
        super.viewDidLoad()
       
        gridView = UIImageView(image: UIImage(named: "nasa_big"))//UIView(frame: CGRectMake(0,0,view.bounds.width,view.bounds.width))//
       
        scrollView = UIScrollView(frame: CGRectMake(0,80,view.bounds.width,view.bounds.width))
        scrollView.backgroundColor = UIColor.blackColor()
        scrollView.contentSize = gridView.bounds.size
        scrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
        scrollView.delegate = self
        scrollView.maximumZoomScale = 4.0
        setZoomScale()
        scrollView.contentOffset = CGPoint(x: 0, y: 0)
        scrollView.addSubview(gridView)
        view.addSubview(scrollView)
       
        setupGestureRecognizer()
       
        setupLogText()
    }
   
    //MARK: - Setup Layout
    func setupLogText()
    {
        let logtextHeight:CGFloat = 40
        logText = UILabel(frame: CGRectMake(0,view.bounds.height-logtextHeight,view.bounds.width,logtextHeight))
        logText.textAlignment = .Center
        view.addSubview(logText)
        createLogText()
    }
   
    func createLogText()
    {
        let text = (puzzleDirection == .Horizontal) ? "Hori" :  "Verti"
        logText.text = "\(text) zoom : \(scrollView.zoomScale) "
    }
   
    func setZoomScale() {
       
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        let heightScale = scrollView.bounds.size.height / gridView.bounds.size.height
       
        scrollView.minimumZoomScale = min(widthScale, heightScale)
        scrollView.zoomScale = widthScale
    }
   
    //MARK: - ScrollView delegates
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return gridView
    }
   
    func scrollViewDidZoom(scrollView: UIScrollView) {
       
        let verticalPadding = gridView.bounds.size.height < scrollView.bounds.size.height ? (scrollView.bounds.size.height - gridView.bounds.size.height) / 2 : 0
        let horizontalPadding = gridView.bounds.size.width < scrollView.bounds.size.width ? (scrollView.bounds.size.width - gridView.bounds.size.width) / 2 : 0
       
        scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
       
    }
   
    //MARK: - Gestures
    func setupGestureRecognizer() {
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleDoubleTap(_:)))
        doubleTap.numberOfTapsRequired = 2
        scrollView.addGestureRecognizer(doubleTap)
       
        let singleTap = UITapGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSingleTap(_:)))
        singleTap.numberOfTapsRequired = 1
        scrollView.addGestureRecognizer(singleTap)
       
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right
        self.view.addGestureRecognizer(swipeRight)
       
        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeDown.direction = UISwipeGestureRecognizerDirection.Down
        self.view.addGestureRecognizer(swipeDown)
       
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
        self.view.addGestureRecognizer(swipeLeft)
       
        let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(ZoomableGridViewController.handleSwipeGesture(_:)))
        swipeUp.direction = UISwipeGestureRecognizerDirection.Up
        self.view.addGestureRecognizer(swipeUp)
       
    }
   
    func handleSwipeGesture(gesture: UIGestureRecognizer) {
       
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
           
            createLogText()
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.Right:
               
                logText.text? += "Swiped right select next horizontal region"
                if swipeGesture.state == UIGestureRecognizerState.Began
                {
                   
                }
               
            case UISwipeGestureRecognizerDirection.Down:
               
                logText.text? += "Swiped down select next vertical region"
               
               
            case UISwipeGestureRecognizerDirection.Left:
               
                logText.text? += "Swiped left select previous horizontal region"
               
               
            case UISwipeGestureRecognizerDirection.Up:
               
               
                logText.text? += "Swiped up select previous vertical region"
               
               
            default:
                break
            }
        }
    }
   
    func checkZoomState()
    {
        let widthScale = scrollView.bounds.size.width / gridView.bounds.size.width
        if widthScale == scrollView.zoomScale
        {
            //print("zoom scale full")
            scrollIsZoomedIn = false
        }
        else
        {
            //print("zoom scale zoomed")
            scrollIsZoomedIn = true
        }
    }
   
    func handleSingleTap(recognizer: UITapGestureRecognizer)
    {
        checkZoomState()
        createLogText()
        if scrollIsZoomedIn
        {
            logText.text? += "singleTap - selected cell if selected change direction"
        }
        else
        {
            logText.text? += "singleTap - selected cell "
        }
    }
   
    func handleDoubleTap(recognizer: UITapGestureRecognizer) {
        //print("double tap")
        checkZoomState()
        createLogText()
        if puzzleDirection == .Horizontal
        {
            puzzleDirection = .Vertical
        }
        else
        {
            puzzleDirection = .Horizontal
        }
    
    }
 
}

Tags: 

UIGesture Tap

let tap = UITapGestureRecognizer(target: self, action: #selector({class}.{func}))
addGestureRecognizer(tap)

Tags: 

Pool

class Pool<T> {
    private var objectPool = [T]()
   
    init(items:[T]) {
        objectPool.reserveCapacity(objectPool.count)
        for item in items {
            objectPool.append(item)
        }
    }
   
    func getFromPool() -> T? {
        var result:T?
        if objectPool.count > 0 {
            result = self.objectPool.removeAtIndex(0)
        }
        return result
    }
   
    func returnToPool(item:T) {
        self.objectPool.append(item)
    }
}

Tags: 

Touch Tap

func handleSingleTap(sender:UITapGestureRecognizer){
        print("tapped")
    }
   
    func addTapGesture()
    {
        let singleTap = UITapGestureRecognizer(target:self, action:#selector(handleSingleTap))
        singleTap.numberOfTouchesRequired = 1
        singleTap.addTarget(self, action:#selector(handleSingleTap))
        view.userInteractionEnabled = true
        view.addGestureRecognizer(singleTap)
    }

or a touch view

enum Tap {
    case Single
    case Draw
    case Long
   
}

protocol HJHTouchViewDelegate: class{
    func removeSelectedFields()
    func checkThisLoc(pnt:CGPoint)
    func checkThisLocForMove(pnt:CGPoint)
    func touchEnded()
    func longpressAt(pnt:CGPoint)
    func longPressEnd()
}

class TouchView: UIView {
   
    weak var delegate: HJHTouchViewDelegate?
    var tC = 0
    var touchCells = [UIButton]()
    var startTime = NSDate()
    var longPresseTime:Double = 0.5
    var longPressTimer = NSTimer()
    var isInLongPress = false
    var isMoving = false
   
   
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        let touch = touches.first!
        tC = 0
        longPressTimer = NSTimer()
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.removeSelectedFields()
        delegate?.checkThisLoc(pnt)
        isInLongPress = false
        isMoving = false
       
        startTime = NSDate()
        longPressTimer =
            NSTimer.scheduledTimerWithTimeInterval(longPresseTime, target: self, selector: #selector(TouchView.updateTime(_:)), userInfo: [pnt.x, pnt.y], repeats: false
        )
       
    }
   
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        isMoving = true
        if isInLongPress
        {
            isInLongPress = false
            delegate?.longPressEnd()
        }
        let touch = touches.first! //as! UITouch
        tC += 1
        let pnt:CGPoint = touch.locationInView(self)
        delegate?.checkThisLocForMove(pnt)
       
    }
   
   
   
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
       
        longPressTimer.invalidate()
        isInLongPress = false
       
        delegate?.touchEnded()
    }
   
    func updateTime(timer:NSTimer)
    {
        if isInLongPress ==  true || isMoving == true
        {
            return
        }
       
        if timer.userInfo != nil
        {
            if let info: AnyObject = timer.userInfo
            {
                if isInLongPress == false
                {
                    isInLongPress = true
                    var arr:[CGFloat] = info as! [CGFloat]
                    delegate?.longpressAt( CGPoint(x: arr[0],y: arr[1]))
                }
            }
        }
    }
}

Tags: 

MongoDb on rasp (notes)

on rasp
sudo /usr/bin/mongod --quiet --rest --config /etc/mongodb.conf
===
sudo nano /etc/mongodb.conf
>
dbpath=/var/lib/mongodb

#where to log
logpath=/var/log/mongodb/mongodb.log

logappend=true

bind_ip = 127.0.0.1,192.168.0.14
port = 27017

# Enable journaling, http://www.mongodb.org/display/DOCS/Journaling
journal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

in rested

http://192.168.0.14:28017/test/
POST
Accept: */*
Accept-Encoding: gzip, deflate
Content-Type: application/json
Accept-Language: en-us

{
"user": {
"email": "blassa4@bbbla.com",
"pwd": "test4",
"username": "test4"
}
}

base64

var str = "Hello, playground"
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)//<48656c6c 6f2c2070 6c617967 726f756e 64>

if let base64Encoded = utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
{
   
    "Encoded:  \(base64Encoded)"//"Encoded:  SGVsbG8sIHBsYXlncm91bmQ="
   
    if let base64Decoded = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions(rawValue: 0))
        .map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
    {
        // Convert back to a string
        "Decoded:  \(base64Decoded)"//"Decoded:  Optional(Hello, playground)"
    }
}

Tags: 

Regex

func matchesForRegexInText(regex: String, text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
                                            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

var string = "aarde"
matchesForRegexInText("aa..e", text: string)

Tags: 

Remove Duplicates Use a Set

// Initialize the Array
var a = [1,2,3,4,5,2,4,1,4,3,6,5]

// Remove duplicates:
// first by converting to a Set
// and then back to Array
a = Array(Set(a))

print(a)

Tags: 

Text Spacing

extension UILabel{
    func addTextSpacing(spacing: CGFloat){
        let attributedString = NSMutableAttributedString(string: self.text!)
        attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSRange(location: 0, length: self.text!.characters.count))
        self.attributedText = attributedString
    }
}

cell.titleLabel.addTextSpacing(1.4)

Tags: 

moving/renaming xcode

from:
/Applications/Xcode.app
=>
/Applications/xcode/Xcode73.app

sudo xcode-select -switch /Applications/xcode/Xcode73.app/Contents/Developer

remove xcode plugins:
rm -rf ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-ins/*

Tags: 

nd char in String

var abc = "abcdefg"
//2nd char
String(abc[abc.characters.startIndex.advancedBy(1)]) //"b"

get range with
extension String {
   
    subscript (i: Int) -> Character
    {
        return self[self.startIndex.advancedBy(i)]
    }
   
    subscript (r: Range<Int>) -> String
    {
        let start = startIndex.advancedBy(r.startIndex)
        let end = start.advancedBy(r.endIndex - r.startIndex)
        return self[Range(start ..< end)]
    }
}

results: abc[0...1] // "ab"
abc[1] = "a"
Or
Array(abc.characters)[1] //"b"

Tags: 

Pages

Subscribe to hjsnips RSS