text:
Object.subclass('Serializer', {

    STORED_TYPE: "__stored_type__",
    initialize: function() {
	this.serialMap = new Hash();
	this.count = 0;
    },

    get: function(object) {
	var value = this.serialMap.get(object);
	if (value)
	    return value.valueOf();
	else
	    return null;
    },

    add: function(object) {
	var serial = this.get(object);
	if (serial)
    	    return serial;
	this.count ++;
	serial =  this.count;
	// console.log('registering ' + object + ' at ' + serial);
	this.serialMap.set(object, serial);
	return serial;
    },

    toJSONProp: function(value, name) {
	if (value instanceof Object)
	    value = value.valueOf(); // convert to primitive if possible
	if (name == 'constructor') // special case, it should't be there
	    return;

	var type = typeof value;
	switch (type) {
	case "function":
	    return;
	case "object": {
	    var ref = this.get(value);
	    if (ref) {
		return { ref: ref};
		// console.log('ref of ' + name + ' is '  + ref  + ', entry ' + entry.toJSONString());
	    } else if (value) {
	    	if (value.writeReplace) {
		    return this.toJSONObject(value.writeReplace());
	    	} else {
		    return this.toJSONObject(value);
	    	}
	    } else if (value && value.constructor) {
	    	console.log('cannot handle with object of type ' + value.constructor.name);
	    }
	}
	    break;
	case "undefined":
	    console.log("weird, name " + name + " has undefined value");
	    return;
	default:
    	    var entry = {};
	    entry[type] = value;
	    return entry;
	}
    },

    toJSONObject: function(obj, debug) {
	debug && console.log('calling toJSON on ' + obj);
	if (obj == null)
	    return null;

	switch (typeof obj) {
    	case 'string':
    	case 'number':
    	case 'boolean':
	    debug && console.log('shortcut on ' + obj);
	    return obj;
	}

	var myserial = this.get(obj);
	if (myserial)
	    return { ref: myserial };

	if (!obj.constructor) {
	    // pure java object ...
	    console.log("weird, no constructor");
	    return {ref: this.add(obj), "type": "Object"};
	}

	var ref = this.add(obj);
	var ser = {};

	if (obj instanceof Array) {
    	    var slots = [];
	    for (var i = 0; i < obj.length; i++) {
		if (!obj[i]) {
		    console.log('weird: empty entry ' + i + " for " + obj);
		    //				continue;
		}
	    	var entry = this.toJSONProp(obj[i]);
	    	// console.log(' array element ' + obj[i] + ' entry ' + entry);
	    	if (entry)
		    slots.push(entry);
	    }
	    if (slots.length > 0)
		ser.slots = slots;
	} else {
    	    var slots = {};
	    for (var name in obj) {
		if (name == this.STORED_TYPE)
		    continue;
		if (obj.isTransient && obj.isTransient(name))
		    continue;
	    	var entry = this.toJSONProp(obj[name]);
	    	if (entry)
		    slots[name] = entry;
	    }
	    if (obj.hiddenProperties) {
		var props = obj.hiddenProperties();
		for (var i = 0; i < props.length; i++) {
		    var name = props[i];
		    if (!obj[name]) // didn't care to declare the property
			continue;
		    var entry = this.toJSONProp(obj[name]);
	    	    if (entry)
			slots[name] = entry;
		    else
			console.log('no entry for prop ' + name);
		}
	    }
	    ser.slots = slots;
	}
	// assigned last, gets printed first ...
	ser.ref = ref;
	if (obj[this.STORED_TYPE]) {
    	    ser['type'] = obj[this.STORED_TYPE];
	} else {
    	    ser['type'] = obj.constructor.name;
	}
	return ser;
    }

});

Object.subclass('RemoteRef', {
    initialize: function(id) {
	this.id = id;
    },

    toString: function() {
	return "RemoteRef(" + this.id + ")";
    },

    writeExternal: function(ser) {
	return { id: this.id };
    },

    readExternal: function(deser, data) {
	//console.log('RemoteRef got data ' + data + "(" + (data || null).toJSONString() + ")");
	return new RemoteRef(data.slots.id.string);
    }
});

Object.subclass('Deserializer', {
    initialize: function() {
	this.serialMap = new Hash();
	//if (realClasses != false)
    	//this.setPrototype = true;
    }
    get: function(serial) {
	return this.serialMap.get(serial);
    },

    put: function(serial, object) {
	this.serialMap.set(serial, object);
	return serial;
    },

    extractValue: function(slot, debug) {
	var value = null;
	if (slot.hasOwnProperty('number')) {
    	    // console.log('value is ' + slot.number.toString());
	    return slot.number;
	} else if (slot.string) {
	    return slot.string;
	} else if (slot.hasOwnProperty('boolean')) {
	    return slot['boolean'];
	} else if (slot['type']) {
    	    // check class first
	    return this.fromJSON(slot, debug);
	    // console.log('got slot value ' + value);
	} else if (slot.ref) {
	    return this.get(slot.ref.valueOf());
	    // console.log(' looked up ref ' + slot.ref.valueOf()); // + " to " + value);
	}
	return null;
    },

    fromJSON: function(/* parsed json */ parsedJSON, debug) {
	if (!parsedJSON)
	    return null;

	if (debug && parsedJSON)
    	    console.log('processing : ' + Object.toJSON(parsedJSON));

	switch (typeof parsedJSON) {
    	case 'number':
    	case 'string':
    	case 'boolean':
	    return parsedJSON;
	}

	var type = parsedJSON["type"];

	var ref;

	if (parsedJSON.ref) {
	    ref = parsedJSON.ref.valueOf();
	    if (this.get(ref)) {
	    	var result = this.get(ref);
	    	debug && console.log('retrieved def  ' + result + " with ref " + ref);
	    	return result;
	    }
	} else {
    	    throw new Error(parsedJSON + '(' + Object.toJSON(parsedJSON) + ') doesnt have a ref');
	}

	var object;
	if (type == "Array") {
	    object = [];
	    this.put(ref, object);
	    if (parsedJSON.slots)
		for (var i = 0; i <  parsedJSON.slots.length; i++) {
		    object.push(this.extractValue(parsedJSON.slots[i], debug));
		}
	} else if (type) {
	    object = {};
	    // FIXME: ensure no funny business in the value of 'type'
	    if (this.setPrototype) {
		var constr = eval(type.toString());
		// note: a Rhino extension
		object.__proto__ = constr.prototype;
		if (object.readExternal) {
		    // read the ref first, in case readExternal overwrites it
	    	    debug && console.log('calling ' + type + ' readExternal on ' + parsedJSON.toJSONString());
	    	    object = object.readExternal(this, parsedJSON);
		    this.put(ref, object);
	   	    return object;
		}
	    } else {
		// special marker to recreate type
		object[Serializer.STORED_TYPE] = type.toString();
	    }
	    this.put(ref, object);
	    if (parsedJSON.slots) {
		for (var name in parsedJSON.slots) {
		    var slot = parsedJSON.slots[name];
		    if (typeof slot == 'function')
			continue;
		    object[name] = this.extractValue(slot, debug);
		    debug && console.log('set ' + name + ' to ' + object[name]
					 + "(" + Object.toJSON(object[name]) + ")");
		}
	    }
	} else {
	    console.log('not found type for ' + parsedJSON); // but that's OK, it may just be a forward ref
	}
	// warning: calling value.toString() may blow up!

	debug && console.log('put ref ' + ref.valueOf() + ' to ' + object.toJSONString() + ' class ' + type);
	return object;
    }

});


text:
package com.tang.intellij.lua.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.StubBasedPsiElement;
import com.tang.intellij.lua.stubs.LuaPlaceholderStub;
import com.tang.intellij.lua.comment.psi.api.LuaComment;

public interface LuaLocalDef extends LuaDeclaration, LuaStatement, LuaDeclarationScope, StubBasedPsiElement<LuaPlaceholderStub> {

  @Nullable
  LuaExprList getExprList();

  @Nullable
  LuaNameList getNameList();

  @Nullable
  LuaComment getComment();

  @Nullable
  PsiElement getAssign();

}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title:  "1 Second Everyday - My Life at 28"
date:   2020-04-08 19:16:00
disqus: true
categories: 1se
tags:
- video
---

Another birthday, another [1 Second Everyday](http://1se.co/) video. Plants, friends, weddings, food, sunsets, bunny, board games, programming and many more.

### Music

* [**Siesta** by Jahzzar](https://freemusicarchive.org/music/Jahzzar/Travellers_Guide/Siesta)
* [**Fuzz** by Jahzzar](https://freemusicarchive.org/music/Jahzzar/Dune/Fuzz)
* [**Dune** by Jahzzar](https://freemusicarchive.org/music/Jahzzar/Dune/Dune_1175)

### Thanks
Thanks to my SO and all of you who are in this video :)

<iframe src="https://player.vimeo.com/video/405110226" width="640" height="360" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>

_Note: if you're in the video, you'll have received the password._


text:
package org.apache.asterix.om.base;

import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.IAType;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class ADouble implements IAObject {

    protected double value;

    public ADouble(double value) {
        super();
        this.value = value;
    }

    public double getDoubleValue() {
        return value;
    }

    @Override
    public IAType getType() {
        return BuiltinType.ADOUBLE;
    }

    @Override
    public String toString() {
        return Double.toString(value);
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof ADouble))
            return false;
        return Double.doubleToLongBits(value) == Double.doubleToLongBits(((ADouble) obj).getDoubleValue());
    }

    @Override
    public int hashCode() {
        long bits = Double.doubleToLongBits(value);
        return (int) (bits ^ (bits >>> 32));
    }

    @Override
    public boolean deepEqual(IAObject obj) {
        return equals(obj);
    }

    @Override
    public int hash() {
        return hashCode();
    }

    @Override
    public ObjectNode toJSON()  {
        ObjectMapper om = new ObjectMapper();
        ObjectNode json = om.createObjectNode();

        json.put("ADouble", value);

        return json;
    }
}


text:
require("should");
const { makeNodeId } = require("node-opcua-nodeid");
const bs = require("..");
describe("Type coercion at construction time", function () {
    it("should coerce a nodeId at construction ", function () {
        const readValue = new bs.ReadValueId({ nodeId: "i=2255", attributeId: 13 });
        readValue.nodeId.should.eql(makeNodeId(2255));
    });
});


text:
    Save Draft
    Publish Changes

    (Optional)
    Please enter a brief description of what you have changed:
    <textarea rows="3" cols="50" ng-model="commitMessage" focus-on="saveChangesModalOpened" class="protractor-test-commit-message-input" autofocus></textarea>

  <button class="btn btn-default" ng-click="cancel()">Cancel</button>
  <button class="btn btn-success protractor-test-close-save-modal-button" ng-disabled="!isCollectionPrivate && !commitMessage" ng-click="save(commitMessage)">
    Save Draft
    Publish Changes
  </button>


text:
<?php
/**
 * Fix missing image width/height
 */

if(php_sapi_name() !== 'cli') {
	die('CLI only');
}

date_default_timezone_set('Europe/London');

require dirname(__FILE__) . '/../bootstrap.php';

$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Image', 'image');
$manager->filter("width = 0", array(), array(array("height = 0", array())));

$values = $manager->values();

if(!$values) {
	echo "Nothing to do.\n";
	exit(1);
	return;
}

foreach($values as $record) {
	echo "Doing ".$record->getUri()."... ";

	if(!file_exists('../'.$record->getUri())) {
		echo "NOT FOUND\n";

		continue;
	}

	$sizeInfo = getimagesize('../'.$record->getUri());

	$record->setWidth($sizeInfo['width']);
	$record->setHeight($sizeInfo['height']);
	$record->save();

	echo "DONE\n";
}

echo "All done.\n";
exit(0);


text:
package com.caffeinatedbliss.kayveep;

import java.io.File;

/**
 * DownloadCache
 *
 * @author Paul Hawke (phawke@rgare.com)
 */
public class DownloadCache {
	private String fileExtn;
	private FileSys fileSystem;
	private DataStore meta;
	private String dataDir;
	private KayVeepUtilities kayVeepUtilities;

	public DownloadCache() {
		this("bin");
	}

	public DownloadCache(String extn) {
		this.fileExtn = extn;
		this.fileSystem = new FileSys();
		this.meta = new DataStore();
		this.kayVeepUtilities = new KayVeepUtilities();
	}

	public void setDataDir(String dir) {
		this.dataDir = dir;
		this.fileSystem.mkdir(dir);
		this.meta.setDataDir(dir);
	}

	public void store(String urlString) {
		String key = kayVeepUtilities.getKey();
		String file = this.constructFilename(key);
		fileSystem.downloadTo(urlString, this.dataDir, file);
		updateMapping(key, urlString);
	}

	public File load(String urlString) {
		IdToNameMapper mapper = kayVeepUtilities.loadMapping("cache-index", meta);
		String key = mapper.getId(urlString);
		if (key == null) {
			return null;
		}
		String file = this.constructFilename(key);
		return fileSystem.getFile(this.dataDir, file);
	}

	private void updateMapping(String key, String urlString) {
		IdToNameMapper mapper = kayVeepUtilities.loadMapping("cache-index", meta);
		mapper.putRaw(key, urlString);
		kayVeepUtilities.storeMapping("cache-index", mapper, meta);
	}

	private String constructFilename(String name) {
		return name + '.' + this.fileExtn;
	}
}


text:
import csv
import os

from .parser import parse

def prepare_out_folder(path):
    os.makedirs(path, exist_ok=True)

def make_csv_file_path(meta, table, out_folder):
    return os.path.join(
        out_folder,
        f"{meta['BankName']} - {table['abbr']} - {table['name']}.csv",
    )

def parse_to_csv(db_folder, out_folder):
    metadata, tables = parse(db_folder)
    prepare_out_folder(out_folder)

    for table in tables:
        # TODO: do we want to export the "FL" table?
        if table['abbr'] == 'FL' and table['name'] == 'Files':
            continue

        csv_file_path = make_csv_file_path(metadata, table, out_folder)
        with open(csv_file_path, 'w') as fh:
            writer = csv.writer(fh)
            writer.writerow([
                col['name']
                for col in table['columns']
            ])

            writer.writerows(table['records'])


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.manufacturers.v1.model;

/**
 * The capacity of a product. For more information, see
 * https://support.google.com/manufacturers/answer/6124116#capacity.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Manufacturer Center API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Capacity extends com.google.api.client.json.GenericJson {

  /**
   * The unit of the capacity, i.e., MB, GB, or TB.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String unit;

  /**
   * The numeric value of the capacity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long value;

  /**
   * The unit of the capacity, i.e., MB, GB, or TB.
   * @return value or {@code null} for none
   */
  public java.lang.String getUnit() {
    return unit;
  }

  /**
   * The unit of the capacity, i.e., MB, GB, or TB.
   * @param unit unit or {@code null} for none
   */
  public Capacity setUnit(java.lang.String unit) {
    this.unit = unit;
    return this;
  }

  /**
   * The numeric value of the capacity.
   * @return value or {@code null} for none
   */
  public java.lang.Long getValue() {
    return value;
  }

  /**
   * The numeric value of the capacity.
   * @param value value or {@code null} for none
   */
  public Capacity setValue(java.lang.Long value) {
    this.value = value;
    return this;
  }

  @Override
  public Capacity set(String fieldName, Object value) {
    return (Capacity) super.set(fieldName, value);
  }

  @Override
  public Capacity clone() {
    return (Capacity) super.clone();
  }

}


text:
import {JitReflector} from '@angular/compiler';
import {DirectiveResolver} from '@angular/compiler/src/directive_resolver';
import {Component, ContentChild, ContentChildren, Directive, HostBinding, HostListener, Input, Output, ViewChild, ViewChildren} from '@angular/core/src/metadata';

@Directive({selector: 'someDirective'})
class SomeDirective {
}

@Directive({selector: 'someDirective', inputs: ['c']})
class SomeDirectiveWithInputs {
  @Input() a: any;
  @Input('renamed') b: any;
  c: any;
}

@Directive({selector: 'someDirective', outputs: ['c']})
class SomeDirectiveWithOutputs {
  @Output() a: any;
  @Output('renamed') b: any;
  c: any;
}

@Directive({selector: 'someDirective'})
class SomeDirectiveWithSetterProps {
  @Input('renamed')
  set a(value: any) {}
}

@Directive({selector: 'someDirective'})
class SomeDirectiveWithGetterOutputs {
  @Output('renamed')
  get a(): any { return null; }
}

@Directive({selector: 'someDirective', host: {'[c]': 'c'}})
class SomeDirectiveWithHostBindings {
  @HostBinding() a: any;
  @HostBinding('renamed') b: any;
  c: any;
}

@Directive({selector: 'someDirective', host: {'(c)': 'onC()'}})
class SomeDirectiveWithHostListeners {
  @HostListener('a')
  onA() {}
  @HostListener('b', ['$event.value'])
  onB(value: any) {}
}

@Directive({selector: 'someDirective', queries: {'cs': new ContentChildren('c')}})
class SomeDirectiveWithContentChildren {
  @ContentChildren('a') as: any;
  c: any;
}

@Directive({selector: 'someDirective', queries: {'cs': new ViewChildren('c')}})
class SomeDirectiveWithViewChildren {
  @ViewChildren('a') as: any;
  c: any;
}

@Directive({selector: 'someDirective', queries: {'c': new ContentChild('c')}})
class SomeDirectiveWithContentChild {
  @ContentChild('a') a: any;
  c: any;
}

@Directive({selector: 'someDirective', queries: {'c': new ViewChild('c')}})
class SomeDirectiveWithViewChild {
  @ViewChild('a') a: any;
  c: any;
}

@Component({selector: 'sample', template: 'some template', styles: ['some styles']})
class ComponentWithTemplate {
}

@Directive({
  selector: 'someDirective',
  host: {'[decorator]': 'decorator'},
  inputs: ['decorator'],
})
class SomeDirectiveWithSameHostBindingAndInput {
  @Input() @HostBinding() prop: any;
}

@Directive({selector: 'someDirective'})
class SomeDirectiveWithMalformedHostBinding1 {
  @HostBinding('(a)')
  onA() {}
}

@Directive({selector: 'someDirective'})
class SomeDirectiveWithMalformedHostBinding2 {
  @HostBinding('[a]')
  onA() {}
}

class SomeDirectiveWithoutMetadata {}

export function main() {
  describe('DirectiveResolver', () => {
    let resolver: DirectiveResolver;

    beforeEach(() => { resolver = new DirectiveResolver(new JitReflector()); });

    it('should read out the Directive metadata', () => {
      const directiveMetadata = resolver.resolve(SomeDirective);
      expect(directiveMetadata).toEqual(new Directive({
        selector: 'someDirective',
        inputs: [],
        outputs: [],
        host: {},
        queries: {},
        exportAs: undefined,
        providers: undefined
      }));
    });

    it('should throw if not matching metadata is found', () => {
      expect(() => {
        resolver.resolve(SomeDirectiveWithoutMetadata);
      }).toThrowError('No Directive annotation found on SomeDirectiveWithoutMetadata');
    });

    it('should support inheriting the Directive metadata', function() {
      @Directive({selector: 'p'})
      class Parent {
      }

      class ChildNoDecorator extends Parent {}

      @Directive({selector: 'c'})
      class ChildWithDecorator extends Parent {
      }

      expect(resolver.resolve(ChildNoDecorator)).toEqual(new Directive({
        selector: 'p',
        inputs: [],
        outputs: [],
        host: {},
        queries: {},
        exportAs: undefined,
        providers: undefined
      }));

      expect(resolver.resolve(ChildWithDecorator)).toEqual(new Directive({
        selector: 'c',
        inputs: [],
        outputs: [],
        host: {},
        queries: {},
        exportAs: undefined,
        providers: undefined
      }));
    });

    describe('inputs', () => {
      it('should append directive inputs', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithInputs);
        expect(directiveMetadata.inputs).toEqual(['c', 'a', 'b: renamed']);
      });

      it('should work with getters and setters', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithSetterProps);
        expect(directiveMetadata.inputs).toEqual(['a: renamed']);
      });

      it('should remove duplicate inputs', () => {
        @Directive({selector: 'someDirective', inputs: ['a', 'a']})
        class SomeDirectiveWithDuplicateInputs {
        }

        const directiveMetadata = resolver.resolve(SomeDirectiveWithDuplicateInputs);
        expect(directiveMetadata.inputs).toEqual(['a']);
      });

      it('should use the last input if duplicate inputs (with rename)', () => {
        @Directive({selector: 'someDirective', inputs: ['a', 'localA: a']})
        class SomeDirectiveWithDuplicateInputs {
        }

        const directiveMetadata = resolver.resolve(SomeDirectiveWithDuplicateInputs);
        expect(directiveMetadata.inputs).toEqual(['localA: a']);
      });

      it('should prefer @Input over @Directive.inputs', () => {
        @Directive({selector: 'someDirective', inputs: ['a']})
        class SomeDirectiveWithDuplicateInputs {
          @Input('a')
          propA: any;
        }
        const directiveMetadata = resolver.resolve(SomeDirectiveWithDuplicateInputs);
        expect(directiveMetadata.inputs).toEqual(['propA: a']);
      });

      it('should support inheriting inputs', () => {
        @Directive({selector: 'p'})
        class Parent {
          @Input()
          p1: any;
          @Input('p21')
          p2: any;
        }

        class Child extends Parent {
          @Input('p22')
          p2: any;
          @Input()
          p3: any;
        }

        const directiveMetadata = resolver.resolve(Child);
        expect(directiveMetadata.inputs).toEqual(['p1', 'p2: p22', 'p3']);
      });
    });

    describe('outputs', () => {
      it('should append directive outputs', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithOutputs);
        expect(directiveMetadata.outputs).toEqual(['c', 'a', 'b: renamed']);
      });

      it('should work with getters and setters', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithGetterOutputs);
        expect(directiveMetadata.outputs).toEqual(['a: renamed']);
      });

      it('should remove duplicate outputs', () => {
        @Directive({selector: 'someDirective', outputs: ['a', 'a']})
        class SomeDirectiveWithDuplicateOutputs {
        }

        const directiveMetadata = resolver.resolve(SomeDirectiveWithDuplicateOutputs);
        expect(directiveMetadata.outputs).toEqual(['a']);
      });

      it('should use the last output if duplicate outputs (with rename)', () => {
        @Directive({selector: 'someDirective', outputs: ['a', 'localA: a']})
        class SomeDirectiveWithDuplicateOutputs {
        }

        const directiveMetadata = resolver.resolve(SomeDirectiveWithDuplicateOutputs);
        expect(directiveMetadata.outputs).toEqual(['localA: a']);
      });

      it('should prefer @Output over @Directive.outputs', () => {
        @Directive({selector: 'someDirective', outputs: ['a']})
        class SomeDirectiveWithDuplicateOutputs {
          @Output('a')
          propA: any;
        }
        const directiveMetadata = resolver.resolve(SomeDirectiveWithDuplicateOutputs);
        expect(directiveMetadata.outputs).toEqual(['propA: a']);
      });

      it('should support inheriting outputs', () => {
        @Directive({selector: 'p'})
        class Parent {
          @Output()
          p1: any;
          @Output('p21')
          p2: any;
        }

        class Child extends Parent {
          @Output('p22')
          p2: any;
          @Output()
          p3: any;
        }

        const directiveMetadata = resolver.resolve(Child);
        expect(directiveMetadata.outputs).toEqual(['p1', 'p2: p22', 'p3']);
      });
    });

    describe('host', () => {
      it('should append host bindings', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithHostBindings);
        expect(directiveMetadata.host).toEqual({'[c]': 'c', '[a]': 'a', '[renamed]': 'b'});
      });

      it('should append host binding and input on the same property', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithSameHostBindingAndInput);
        expect(directiveMetadata.host).toEqual({'[decorator]': 'decorator', '[prop]': 'prop'});
        expect(directiveMetadata.inputs).toEqual(['decorator', 'prop']);
      });

      it('should append host listeners', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithHostListeners);
        expect(directiveMetadata.host)
            .toEqual({'(c)': 'onC()', '(a)': 'onA()', '(b)': 'onB($event.value)'});
      });

      it('should throw when @HostBinding name starts with "("', () => {
        expect(() => resolver.resolve(SomeDirectiveWithMalformedHostBinding1))
            .toThrowError('@HostBinding can not bind to events. Use @HostListener instead.');
      });

      it('should throw when @HostBinding name starts with "["', () => {
        expect(() => resolver.resolve(SomeDirectiveWithMalformedHostBinding2))
            .toThrowError(
                `@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.`);
      });

      it('should support inheriting host bindings', () => {
        @Directive({selector: 'p'})
        class Parent {
          @HostBinding()
          p1: any;
          @HostBinding('p21')
          p2: any;
        }

        class Child extends Parent {
          @HostBinding('p22')
          p2: any;
          @HostBinding()
          p3: any;
        }

        const directiveMetadata = resolver.resolve(Child);
        expect(directiveMetadata.host)
            .toEqual({'[p1]': 'p1', '[p21]': 'p2', '[p22]': 'p2', '[p3]': 'p3'});
      });

      it('should support inheriting host listeners', () => {
        @Directive({selector: 'p'})
        class Parent {
          @HostListener('p1')
          p1() {}
          @HostListener('p21')
          p2() {}
        }

        class Child extends Parent {
          @HostListener('p22')
          p2() {}
          @HostListener('p3')
          p3() {}
        }

        const directiveMetadata = resolver.resolve(Child);
        expect(directiveMetadata.host)
            .toEqual({'(p1)': 'p1()', '(p21)': 'p2()', '(p22)': 'p2()', '(p3)': 'p3()'});
      });

      it('should combine host bindings and listeners during inheritance', () => {
        @Directive({selector: 'p'})
        class Parent {
          @HostListener('p11') @HostListener('p12')
          p1() {}

          @HostBinding('p21') @HostBinding('p22')
          p2: any;
        }

        class Child extends Parent {
          @HostListener('c1')
          p1() {}

          @HostBinding('c2')
          p2: any;
        }

        const directiveMetadata = resolver.resolve(Child);
        expect(directiveMetadata.host).toEqual({
          '(p11)': 'p1()',
          '(p12)': 'p1()',
          '(c1)': 'p1()',
          '[p21]': 'p2',
          '[p22]': 'p2',
          '[c2]': 'p2'
        });
      });
    });

    describe('queries', () => {
      it('should append ContentChildren', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithContentChildren);
        expect(directiveMetadata.queries)
            .toEqual({'cs': new ContentChildren('c'), 'as': new ContentChildren('a')});
      });

      it('should append ViewChildren', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithViewChildren);
        expect(directiveMetadata.queries)
            .toEqual({'cs': new ViewChildren('c'), 'as': new ViewChildren('a')});
      });

      it('should append ContentChild', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithContentChild);
        expect(directiveMetadata.queries)
            .toEqual({'c': new ContentChild('c'), 'a': new ContentChild('a')});
      });

      it('should append ViewChild', () => {
        const directiveMetadata = resolver.resolve(SomeDirectiveWithViewChild);
        expect(directiveMetadata.queries)
            .toEqual({'c': new ViewChild('c'), 'a': new ViewChild('a')});
      });

      it('should support inheriting queries', () => {
        @Directive({selector: 'p'})
        class Parent {
          @ContentChild('p1')
          p1: any;
          @ContentChild('p21')
          p2: any;
        }

        class Child extends Parent {
          @ContentChild('p22')
          p2: any;
          @ContentChild('p3')
          p3: any;
        }

        const directiveMetadata = resolver.resolve(Child);
        expect(directiveMetadata.queries).toEqual({
          'p1': new ContentChild('p1'),
          'p2': new ContentChild('p22'),
          'p3': new ContentChild('p3')
        });
      });
    });

    describe('Component', () => {
      it('should read out the template related metadata from the Component metadata', () => {
        const compMetadata: Component = resolver.resolve(ComponentWithTemplate);
        expect(compMetadata.template).toEqual('some template');
        expect(compMetadata.styles).toEqual(['some styles']);
      });
    });
  });
}


text:
Project Hoverboard is the next generation conference website template after [Project Zeppelin](https://github.com/gdg-x/zeppelin) and more optimized version - [Project Zeppelin-Grunt](https://github.com/gdg-x/zeppelin-grunt).

Template was build using [Polymer](http://polymer-project.org) according to [Material Design](http://www.google.com/design/spec/material-design/introduction.html) guidelines.
The site is **responsive**, **fast** and supports **offline access** (if you are using HTTPS protocol).

Template is brought by [Oleh Zasadnyy](https://plus.google.com/+OlehZasadnyy) from [GDG Lviv](http://lviv.gdg.org.ua/).

*Do you like it?* Show your support - please, **star the project**.

### Live demo [GDG DevFest Ukraine 2015](http://devfest.gdg.org.ua/)

#### The Hoverboard is still under development and can bring breaking changes shortly. If you are looking for stable website template try [Project Zeppelin-Grunt](https://github.com/gdg-x/zeppelin-grunt).

## Features
* Material design
* Polymer
* Responsive
* Integrated speakers and sessions management
* SVG icons
* SEO friendly
* Optimized and fast
* Offline access

## Quick-start guide
1.  [Fork](https://github.com/gdg-x/hoverboard/fork) this repo and clone locally or [download](https://github.com/gdg-x/hoverboard/archive/master.zip) and extract Project Hoverboard to where you want to work.
2.  Install [Node.js](www.nodejs.org).
3.  Run `npm install -g gulp bower && npm install && bower install` from the root of the folder.
4.  Modify template to suit your needs.

#### Requirements

Project dependencies:

- Node.js used to run JavaScript tools from the command line.
- npm, the node package manager, installed with Node.js and used to install Node.js packages.
- gulp, a Node.js-based build tool.
- bower, a Node.js-based package manager used to install front-end packages (like Polymer).

**To install dependencies:**

1)  Check your Node.js version.

```sh
node --version
```

The version should be 0.12.x or above.

2)  If you don't have Node.js installed, or you have a lower version, go to [nodejs.org](https://nodejs.org) and click on the big green Install button.

3)  Install `gulp` and `bower` globally.

```sh
npm install -g gulp bower
```

This lets you run `gulp` and `bower` from the command line.

4)  Install the projects's local `npm` and `bower` dependencies.

```sh
cd hoverboard && npm install && bower install
```

This installs the element sets and tools the hoverboard template requires to build and serve apps.

## Development workflow

#### Serve / watch

```sh
gulp serve
```

This outputs an IP address you can use to locally test and another that can be used on devices connected to your network.

#### Build & Vulcanize

```sh
gulp
```

Build and optimize the current project, ready for deployment. This includes linking as well as vulcanization, image, script, stylesheet and HTML optimization and minification.

#### Build, Vulcanize, and Deploy

```sh
gulp deploy
```

**Warning:** don't forget to [edit destination repository](https://github.com/gdg-x/hoverboard/blob/master/gulpfile.js#L205) to deploy the website.

## Next steps in the project
* Use generator to configure the template from files
* Refactor styles
* Schedule page
* Countdown
* Testimonials block
* Venue block

## Application Theming

Polymer 1.0 introduces a shim for CSS custom properties. We take advantage of this in `app/styles/app-theme.html` and `app/styles/tags-color.html` to provide theming for your application. You can also find our presets for Material Design breakpoints in this file.

[Read more](https://www.polymer-project.org/1.0/docs/devguide/styling.html) about CSS custom properties.

_Ok, to be honest, it should be refactored ASAP._

## Dependency Management

Polymer uses [Bower](http://bower.io) for package management. This makes it easy to keep your elements up to date and versioned. For tooling, we use npm to manage Node.js-based dependencies.

## Service Worker

Template offers an offline-first experience thanks to Service Worker and the [Platinum Service Worker elements](https://github.com/PolymerElements/platinum-sw). New to Service Worker? Read the following [introduction](http://www.html5rocks.com/en/tutorials/service-worker/introduction/) to understand how it works.

#### I get an error message about "Only secure origins are allowed"

Service Workers are only available to "secure origins" (HTTPS sites, basically) in line with a policy to prefer secure origins for powerful new features. However http://localhost is also considered a secure origin, so if you can, developing on localhost is an easy way to avoid this error. For production, your site will need to support HTTPS.

#### How do I debug Service Worker?

If you need to debug the event listener wire-up use `chrome://serviceworker-internals`.

#### What are those buttons on chrome://serviceworker-internals?

This page shows your registered workers and provides some basic operations.

* Unregister: Unregisters the worker.
* Start: Starts the worker. This would happen automatically when you navigate to a page in the worker's scope.
* Stop: Stops the worker.
* Sync: Dispatches a 'sync' event to the worker. If you don't handle this event, nothing will happen.
* Push: Dispatches a 'push' event to the worker. If you don't handle this event, nothing will happen.
* Inspect: Opens the worker in the Inspector.

#### Not yet ready for Service Worker support?

If for any reason you decide that Service Worker support isn't for you, you can disable it from your project using these 3 steps:

* Remove 'precache' from the list in the 'default' gulp task ([gulpfile.js](https://github.com/PolymerElements/polymer-starter-kit/blob/master/gulpfile.js))
* Remove the two Platinum Service Worker elements (platinum-sw/..) in [app/elements/elements.html](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/elements/elements.html)
* Remove references to the platinum-sw elements from your application [index](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/index.html).

You will also want to navigate to `chrome://serviceworker-internals` and unregister any Service Workers registered by Hoverboard for your app just in case there's a copy of it cached.

## Frequently Asked Questions

> Where do I customize my application theme?

Theming can be achieved using [CSS Custom properties](https://www.polymer-project.org/1.0/docs/devguide/styling.html#xscope-styling-details) via [app/styles/app-theme.html](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/styles/app-theme.html).
You can also use `app/styles/main.css` for pure CSS stylesheets (e.g for global styles), however, note that Custom properties will not work there under the shim.

A [Polycast](https://www.youtube.com/watch?v=omASiF85JzI) is also available that walks through theming using Polymer 1.0.

> Where do I configure routes in my application?

This can be done via [`app/elements/routing.html`](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/elements/routing.html). We use Page.js for routing, and new routes
can be defined in this import. We then toggle which `<iron-pages>` page to display based on the [selected](https://github.com/PolymerElements/polymer-starter-kit/blob/master/app/index.html#L105) route.

> Something has failed during installation. How do I fix this?

Our most commonly reported issue is around system permissions for installing Node.js dependencies.
We recommend following the [fixing npm permissions](https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md)
guide to address any messages around administrator permissions being required. If you use `sudo`
to work around these issues, this guide may also be useful for avoiding that.

If you run into an exception that mentions five optional dependencies failing (or an `EEXIST` error), you
may have run into an npm [bug](https://github.com/npm/npm/issues/6309). We recommend updating to npm 2.11.0+
to work around this. You can do this by opening a Command Prompt/terminal and running `npm install npm@2.11.0 -g`. If you are on Windows,
Node.js (and npm) may have been installed into `C:\Program Files\`. Updating npm by running `npm install npm@2.11.0 -g` will install npm
into `%AppData%\npm`, but your system will still use the npm version. You can avoid this by deleting your older npm from `C:\Program Files\nodejs`
as described [here](https://github.com/npm/npm/issues/6309#issuecomment-67549380).

If the issue is to do with a failure somewhere else, you might find that due to a network issue
a dependency failed to install correctly. We recommend running `npm cache clean` and deleting the `node_modules` directory followed by
`npm install` to see if this corrects the problem. If not, please check the [issue tracker](https://github.com/PolymerElements/polymer-starter-kit/issues) in case
there is a workaround or fix already posted.

> I'm having trouble getting Vulcanize to build my project on Windows fully. Help?

Some Windows users have run into trouble with the `elements.vulcanized.html` file in their `dist` folder
not being correctly vulcanized. This can happen if your project is in a folder with a name containing a
space. You can work around this issue by ensuring your path doesn't contain one.

There is also an [in-flight](https://github.com/PolymerElements/polymer-starter-kit/issues/62#issuecomment-108974016) issue
where some are finding they need to disable the `inlineCss` option in our configuration for Vulcanize
to build correctly. We are still investigating this, however for the time-being use the workaround if
you find your builds getting stuck here.

> How do I add new JavaScript files to Hoverboard so they're picked up by the build process?

At the bottom of `app/index.html`, you will find a building block that can be used to include additional
scripts for your app. Build blocks are just normal script tags that are wrapped in an HTML
comment that indicates where to concatenate and minify their final contents to.

Below, we've added in `script2.js` and `script3.js` to this block. The line
`<!-- build:js scripts/app.js -->` specifies that these scripts will be squashed into `scripts/app.js`
during a build.

```html
<!-- build:js scripts/app.js -->
<script src="scripts/app.js"></script>
<script src="scripts/script2.js"></script>
<script src="scripts/script3.js"></script>
<!-- endbuild-->
```

## Who is using template?

Going to use template? Go on! The only thing we ask - let us know at [lviv@gdg.org.ua](mailto:lviv@gdg.org.ua) so we can include you to this list, or make a pull request.

| [GDG DevFest Ukraine](http://devfest.gdg.org.ua) |
| :------------ |
| [GDG DevFest Sao Paulo](http://sp.devfest.com.br)  |
| [GDG DevFest Hamburg 2015](http://devfest.de)  |

## Contributing

Project Hoverboard is still under development and it is open for contributions. Feel free to send PR. If you have any questions, feel free to contact [Oleh Zasadnyy](https://plus.google.com/+OlehZasadnyy).

## License

Project is published under the [MIT license](https://github.com/gdg-x/hoverboard/blob/master/LICENSE.md) Feel free to clone and modify repo as you want, but don't forget to add reference to authors :)


text:
// Copyright © 2016-2022 Andy Goryachev <andy@goryachev.com>
package goryachev.fx;
import goryachev.common.util.CList;
import goryachev.common.util.SB;
import goryachev.fx.internal.CssTools;
import goryachev.fx.internal.FxCssProp;
import goryachev.fx.internal.StandardFxProperties;

/**
 * FX CSS Style Sheet Generator.
 *

 * The following debugging options are defined by CssLoader:
 *

 *    -Dcss.refresh=true
 *    -Dcss.dump=true
 */
public class FxStyleSheet
	extends StandardFxProperties
{
	private final CList<Object> elements = new CList();

	public FxStyleSheet()
	{
	}

	public Selector selector(Object ... sel)
	{
		return new Selector(sel);
	}

	/** adds multiple selectors or style sheets */
	public void add(Object ... sel)
	{
		for(Object x: sel)
		{
			if(x instanceof Object[])
			{
				add((Object[])x);
			}
			else
			{
				elements.add(x);
			}
		}
	}

	/** adds a selector or a style sheet */
	public void add(Object ss)
	{
		elements.add(ss);
	}

	/** generates style sheet */
	public String generateStyleSheet()
	{
		SB sb = new SB();
		generate(sb);
		return sb.toString();
	}

	protected void generate(SB sb)
	{
		for(Object x: elements)
		{
			if(x instanceof Selector)
			{
				((Selector)x).write(sb, null);
			}
			else if(x instanceof FxStyleSheet)
			{
				((FxStyleSheet)x).generate(sb);
			}
			else if(x != null)
			{
				sb.append(x);
			}
		}
	}

	//

	public static class Selector
		extends StandardFxProperties
	{
		protected final String selector;
		protected final CList<Object> items = new CList();

		public Selector(Object ... sel)
		{
			selector = CssTools.selector(sel);
		}

		/** use this method to add properties or cascaded selectors */
		public Selector defines(Object ... sel)
		{
			items.addAll(sel);
			return this;
		}

		protected static Selector[] chain(Selector[] parents, Selector sel)
		{
			if(parents == null)
			{
				return new Selector[] { sel };
			}
			else
			{
				int sz = parents.length;
				Selector[] rv = new Selector[sz + 1];
				System.arraycopy(parents, 0, rv, 0, sz);
				rv[sz] = sel;
				return rv;
			}
		}

		protected void writeSelector(SB sb, boolean first, Object selector)
		{
			String s;
			if(selector instanceof Selector)
			{
				s = ((Selector)selector).selector;
			}
			else
			{
				s = (String)selector;
			}

			if(!first)
			{
				if(!s.startsWith(":"))
				{
					sb.sp();
				}
			}

			sb.a(s);
		}

		protected void write(SB sb, Selector[] parentSelectors)
		{
			if(items.size() == 0)
			{
				return;
			}

			boolean epilogue = false;

			CList<Selector> selectors = null;
			for(Object x: items)
			{
				if(x instanceof Selector)
				{
					if(selectors == null)
					{
						selectors = new CList<>();
					}
					selectors.add((Selector)x);
				}
				else if(x instanceof FxCssProp)
				{
					if(!epilogue)
					{
						// write selector prologue
						boolean first = true;
						if(parentSelectors != null)
						{
							for(Selector sel: parentSelectors)
							{
								writeSelector(sb, first, sel);
								first = false;
							}
						}

						writeSelector(sb, first, selector);
						sb.a("\n{\n");
						epilogue = true;
					}

					sb.a("\t");
					((FxCssProp)x).write(sb);
					sb.nl();
				}
				else if(x != null)
				{
					throw new Error("?" + x);
				}
			}

			if(epilogue)
			{
				sb.a("}\n\n");
			}

			if(selectors != null)
			{
				for(Selector sel: selectors)
				{
					sel.write(sb, chain(parentSelectors, this));
				}
			}
		}
	}
}


text:
<?php

/**
* General Footer
* @package Wordpress
* @subpackage Brikx
* @since 1.0
* @author Matthew Hansen & Bryan Haskin
*/
?>

<?php wp_footer(); ?>

</body>

</html>


text:
package git4idea.push;

import com.intellij.history.Label;
import com.intellij.openapi.vcs.update.UpdatedFiles;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Map;

/**
 * Combined push result for all affected repositories in the project.
 */
class GitPushResult {

  @NotNull private final Map<GitRepository, GitPushRepoResult> myResults;
  @NotNull private final UpdatedFiles myUpdatedFiles;
  @Nullable private final Label myBeforeUpdateLabel;
  @Nullable private final Label myAfterUpdateLabel;

  GitPushResult(@NotNull Map<GitRepository, GitPushRepoResult> results,
                @NotNull UpdatedFiles files,
                @Nullable Label beforeUpdateLabel,
                @Nullable Label afterUpdateLabel) {
    myResults = results;
    myUpdatedFiles = files;
    myBeforeUpdateLabel = beforeUpdateLabel;
    myAfterUpdateLabel = afterUpdateLabel;
  }

  @NotNull
  public Map<GitRepository, GitPushRepoResult> getResults() {
    return myResults;
  }

  @NotNull
  public UpdatedFiles getUpdatedFiles() {
    return myUpdatedFiles;
  }

  @Nullable
  public Label getBeforeUpdateLabel() {
    return myBeforeUpdateLabel;
  }

  @Nullable
  public Label getAfterUpdateLabel() {
    return myAfterUpdateLabel;
  }
}


text:
package org.springframework.social.facebook.web;

/**
 * Strategy interface for handling real time updates.
 * Implementations can be wired into {@link RealTimeUpdateController} to receive any updates from Facebook as they arrive.
 * @author Craig Walls
 */
public interface UpdateHandler {

	public void handleUpdate(String subscription, RealTimeUpdate update);

}


text:
<?php

namespace DoctrineModuleTest\Mvc\Router\Console;

use PHPUnit_Framework_TestCase;
use Symfony\Component\Console\Application;
use Zend\Console\Request;
use DoctrineModule\Mvc\Router\Console\SymfonyCli;

/**
 * Tests for {@see \DoctrineModule\Mvc\Router\Console\SymfonyCli}
 *
 * @license MIT
 * @author Aleksandr Sandrovskiy <a.sandrovsky@gmail.com>
 *
 * @covers \DoctrineModule\Mvc\Router\Console\SymfonyCli
 */
class SymfonyCliTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var \DoctrineModule\Mvc\Router\Console\SymfonyCli
     */
    protected $route;

    /**
     * {@inheritDoc}
     */
    public function setUp()
    {
        $this->route = new SymfonyCli(new Application());
    }

    public function testMatching()
    {
        $this->assertInstanceOf(
            'Zend\Mvc\Router\Console\RouteMatch',
            $this->route->match(new Request(array('scriptname.php', 'list')))
        );
    }

    public function testMatchingWithParams()
    {
        $this->assertInstanceOf(
            'Zend\Mvc\Router\Console\RouteMatch',
            $this->route->match(new Request(array('scriptname.php', 'list', '--help')))
        );
    }

    public function testNotMatching()
    {
        $this->assertNull($this->route->match(new Request(array('scriptname.php', 'unknowncommand'))));
    }
}


text:
package com.ait.toolkit.titanium.mobile.client.android;

import com.ait.toolkit.titanium.mobile.client.core.events.EventDispatcher;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsDate;

/**
 * The Titanium binding of Android RemoteViews. RemoteViews are an API for
 * referencing and updating views that live in another process (i.e. in a
 * com.ait.toolkit.titanium.mobile.client.Notification)
 */
public class RemoteViews extends EventDispatcher {

    protected RemoteViews(JavaScriptObject obj) {
        jsObj = obj;
    }

    /**
     * Call a method taking one boolean on a view in the layout for this
     * RemoteViews. See AndroidMedia's documentation for setBoolean
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param methodName
     *            , The name of the method to call
     * @param value
     *            , The boolean to pass to the method
     */
    public native void setBoolean(int viewId, String methodName, boolean value) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setBoolean(viewId, methodName, value);
    }-*/;

    /**
     * Sets a chronometer's base, format, and started flag. See AndroidMedia's
     * documentation for setChronometer
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param methodName
     *            , The name of the method to call
     *
     * @param base
     *            , The time at which the timer would have read 0:00
     * @param format
     *            , The Chronometer format string, or null to simply display the
     *            timer value
     * @param started
     *            , True if you want the clock to be started, false if not
     */
    public native void setChronometer(int viewId, JsDate base, String format, boolean started) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setChronometer(viewId, base, format, started);
    }-*/;

    /**
     * Call a method taking one double on a view in the layout for this
     * RemoteViews. See AndroidMedia's documentation for setDouble
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param methodName
     *            , The name of the method to call
     * @param value
     *            , The double to pass to the method
     */
    public native void setDouble(int viewId, String methodName, double value) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setDouble(viewId, methodName, value);
    }-*/;

    /**
     * Sets an ImageView's source given a Resource ID. See AndroidMedia's
     * documentation for setImageViewResource
     *
     * @param viewId
     *            , The resource id of the ImageView whose image should change
     *            (also see Titanium.App.Android.R)
     * @param srcId
     *            , The resource id of the image
     */
    public native void setViewResource(int viewId, int srcId) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setViewResource(viewId, srcId);
    }-*/;

    /**
     * Sets an ImageView's source given a URI (supports both AndroidMedia and
     * Titanium URLs). See AndroidMedia's documentation for setImageViewUri
     *
     * @param viewId
     *            , The resource id of the ImageView whose image should change
     *            (also see Titanium.App.Android.R)
     * @param uri
     *            , The URI of the image (both AndroidMedia and Titanium URLs
     *            are supported)
     */
    public native void setImageViewUri(int viewId, String uri) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setImageViewUri(viewId, uri);
    }-*/;

    /**
     * Call a method taking one int on a view in the layout for this
     * RemoteViews. See AndroidMedia's documentation for setInt
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param methodName
     *            , The name of the method to call
     * @param value
     *            , The int to pass to the method
     */
    public native void setInt(int viewId, String methodName, int value) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setInt(viewId, methodName, value);
    }-*/;

    /**
     * Launches a Titanium.Android.PendingIntent when the specified view is
     * clicked. See AndroidMedia's documentation for setOnClickPendingIntent
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param intent
     *            , The PendingIntent to execute when this view is clicked
     */
    public native void setOnclickPendingIntent(int viewId, PendingIntent intent) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setOnclickPendingIntent(viewId,
				intent.@com.ait.toolkit.core.client.JsObject::getJsObj()());
    }-*/;

    /**
     * Sets the progress, max value, and indeterminate flag of a ProgressBar.
     * See AndroidMedia's documentation for setProgressBar
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param max
     *            , The new max value of the ProgressBar
     * @param progress
     *            , The new progress value of the ProgressBar (from 0..max)
     * @param indeterminate
     *            , Whether or not the progress in indeterminate
     */
    public native void setProgressBar(int viewId, int max, int progress, boolean indeterminate) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setProgressBar(viewId, max, progress, indeterminate);
    }-*/;

    /**
     * Call a method taking one string on a view in the layout for this
     * RemoteViews. See AndroidMedia's documentation for setString
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param methodName
     *            , The name of the method to call
     * @param value
     *            , The string to pass to the method
     */
    public native void setString(int viewId, String methodName, String value) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setString(viewId, methodName, value);
    }-*/;

    /**
     * Sets the text color of a view. See AndroidMedia's documentation for
     * setTextColor
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param color
     *            , A color as an integer
     */
    public native void setTextColor(int viewId, int color) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setTextColor(viewId, color);
    }-*/;

    /**
     * Sets the text of a TextView. See AndroidMedia's documentation for
     * setTextViewText
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param text
     *            ,The new text of the TextView
     */
    public native void setTextViewText(int viewId, String text) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setTextViewText(viewId, text);
    }-*/;

    /**
     * Call a method taking one Uri on a view in the layout for this
     * RemoteViews. See AndroidMedia's documentation for setUri
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param methodName
     *            , The name of the method to call
     * @param value
     *            , The URI(as string) to pass to the method
     */
    public native void setUri(int viewId, String methodName, String value) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setUri(viewId, methodName, value);
    }-*/;

    /**
     * Sets the visibility of a View. See AndroidMedia's documentation for
     * setViewVisibility
     *
     * @param viewId
     *            , The resource id of the View (also see
     *            Titanium.App.Android.R)
     * @param visibility
     *            , The visibility, one of AndroidMedia.VISIBLE,
     *            AndroidMedia.INVISIBLE, or AndroidMedia.GONE
     */
    public native void setViewVisibility(int viewId, int visibility) /*-{
		var jso = this.@com.ait.toolkit.core.client.JsObject::getJsObj()();
		jso.setViewVisibility(viewId, visibility);
    }-*/;

}


text:
import assert from "assert";

const baseUrl = "http://localhost:8001";

export default (ajax, ajaxSettings, ajaxName) => {
  describe(`Polymorphism (${ajaxName})`, () => {
    it("should work without any callback.", done => {
      ajax({ url: baseUrl + "/data/1" });

      setTimeout(done, 200);
    });

    it("should work as ajax().then(success)", done => {
      ajax({
        url: baseUrl + "/data/1",
        error: () => {
          throw new Error("Unexpected error.");
        }
      }).then((data, textStatus, ...rest) => {
        assert.deepEqual(data.result, { data: "abcde", id: "1" });
        assert.equal(textStatus, "success");
        // rest contains xhr, unused here
        assert.equal(rest.length, 1);
        done();
      });
    });

    it("should work as ajax({ url, success, error })", done => {
      const res = ajax({
        url: baseUrl + "/data/1",
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data.result, { data: "abcde", id: "1" });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should work as ajax(url).then(success, error)", done => {
      const res = ajax(baseUrl + "/data/1");
      res.then(
        (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data.result, { data: "abcde", id: "1" });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        () => {
          throw new Error("Unexpected error.");
        }
      );
    });

    it("should work as ajax(url).done(success).fail(error)", done => {
      const res = ajax(baseUrl + "/data/1")
        .done((data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data.result, { data: "abcde", id: "1" });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        })
        .fail(() => {
          throw new Error("Unexpected error.");
        });
    });

    it("should work as ajax(url).fail(error).done(success)", done => {
      const res = ajax(baseUrl + "/data/1")
        .fail(() => {
          throw new Error("Unexpected error.");
        })
        .done((data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data.result, { data: "abcde", id: "1" });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        });
    });

    it("should work with res.done called after success", done => {
      const res = ajax(baseUrl + "/data/1")
        .fail(() => {
          throw new Error("Unexpected error.");
        })
        .done(() =>
          res.done((data, textStatus, xhr, ...rest) => {
            assert.deepEqual(data.result, { data: "abcde", id: "1" });
            assert.equal(textStatus, "success");
            assert.equal(xhr, res);
            assert.equal(rest.length, 0);
            done();
          })
        );
    });
  });

  describe(`HTTP verbs (${ajaxName})`, () => {
    it("should work with GET calls", done => {
      const res = ajax({
        url: baseUrl + "/data/1",
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data.result, { data: "abcde", id: "1" });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should work with POST calls", done => {
      const res = ajax({
        url: baseUrl + "/data/1",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({
          data: "DEFGH"
        }),
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data.result, { data: "DEFGH", id: "1" });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should work with PUT calls", done => {
      const res = ajax({
        url: baseUrl + "/data/",
        type: "PUT",
        contentType: "application/json",
        data: JSON.stringify({
          data: "First entry"
        }),
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data.result, { data: "First entry", id: "3" });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should work with DELETE calls", done => {
      const res = ajax({
        url: baseUrl + "/data/2",
        type: "DELETE",
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data, { ok: true });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should trigger the error callback when status is 400", done => {
      const res = ajax({
        url: baseUrl + "/data/inexisting_id",
        type: "POST",
        success: () => {
          throw new Error("Unexpected success.");
        },
        error: (xhr, textStatus, errorThrown, ...rest) => {
          assert.deepEqual(xhr, res);
          assert.equal(textStatus, "error");
          // TODO
          // Find why jQuery receives here "Bad Request" while djax
          // receives "Bad request"...
          // assert.equal(errorThrown, 'Bad request');
          assert.equal(errorThrown.toLowerCase(), "bad request");
          assert.equal(rest.length, 0);
          done();
        }
      });
    });

    it("should work with GET calls and empty data", done => {
      const res = ajax({
        url: baseUrl + "/adhoc/",
        success: (data, textStatus, xhr, ...rest) => {
          assert.equal(data, "");
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should work with GET calls and 204 HTTP status", done => {
      const res = ajax({
        url: baseUrl + "/adhoc/",
        data: { status: 204 },
        success: (data, textStatus, xhr, ...rest) => {
          assert.equal(data, undefined);
          assert.equal(textStatus, "nocontent");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });
  });

  describe(`Content types (${ajaxName})`, () => {
    it("should work with no content type", done => {
      const res = ajax({
        url: "/adhoc/",
        data: { data: "something" },
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(data, "something");
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should work with a FormData containing a file", done => {
      const form = new FormData();
      form.append("file", testfile, "testfile.json");

      const res = ajax({
        url: "/data/file",
        type: "PUT",
        data: form,
        processData: false,
        contentType: false,
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(JSON.parse(data.result.fileContent), { a: 2, b: 5 });
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });

    it("should work with params in a FormData", done => {
      const form = new FormData();
      form.append("file", testfile, "testfile.json");
      form.append("comment", "this is a test");

      const res = ajax({
        url: "/data/file",
        type: "PUT",
        data: form,
        processData: false,
        contentType: false,
        success: (data, textStatus, xhr, ...rest) => {
          assert.deepEqual(JSON.parse(data.result.fileContent), { a: 2, b: 5 });
          assert.equal(data.result.comment, "this is a test");
          assert.equal(textStatus, "success");
          assert.equal(xhr, res);
          assert.equal(rest.length, 0);
          done();
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });
  });

  describe(`Custom XHR (${ajaxName})`, () => {
    it("should make xhr available", done => {
      assert(ajaxSettings.xhr() instanceof XMLHttpRequest);
      done();
    });

    it("should accept a custom xhr", done => {
      let check = false;
      const res = ajax({
        url: "/adhoc/",
        data: { data: "something" },
        xhr() {
          const xhr = ajaxSettings.xhr();

          xhr.addEventListener(
            "load",
            () => {
              check = true;
            },
            false
          );

          return xhr;
        },
        success: (data, textStatus, xhr, ...rest) => {
          // Timeout to for load to be called before success in djax.
          // As it's a subset of jQuery.ajax, we don't aspire to respect
          // the spec at this level of details
          setTimeout(() => {
            assert(check);
            assert.deepEqual(data, "something");
            assert.equal(textStatus, "success");
            assert.equal(xhr, res);
            assert.equal(rest.length, 0);
            done();
          }, 0);
        },
        error: () => {
          throw new Error("Unexpected error.");
        }
      });
    });
  });
};


text:
View online at http://www.worlduality.com

Hackathon project for NBCUniversal's hackathon http://nbcuhackathon.com/medialabs/

March 2016

boilerplate from https://github.com/sahat/hackathon-starter

The MIT License (MIT)

Copyright (c) 2016 Ilan Granot & Ryan Tran

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.