text:
package org.codehaus.groovy.grails.orm.hibernate.support;

import grails.validation.ValidationException;
import groovy.lang.Closure;
import groovy.lang.GroovySystem;
import groovy.lang.MetaClass;
import groovy.lang.MetaMethod;
import groovy.lang.MetaProperty;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainBinder;
import org.codehaus.groovy.grails.orm.hibernate.cfg.Mapping;
import org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractDynamicPersistentMethod;
import org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod;
import org.codehaus.groovy.grails.orm.hibernate.metaclass.BeforeValidateHelper;
import org.codehaus.groovy.grails.orm.hibernate.metaclass.ValidatePersistentMethod;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation;
import org.grails.datastore.mapping.engine.event.ValidationEvent;
import org.hibernate.EntityMode;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.event.*;
import org.hibernate.persister.entity.EntityPersister;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.Errors;

/**
 *
Invokes closure events on domain entities such as beforeInsert, beforeUpdate and beforeDelete.
 *
 *
Also deals with auto time stamping of domain classes that have properties named 'lastUpdated' and/or 'dateCreated'.
 *
 * @author Lari Hotari
 * @since 1.3.5
 */
@SuppressWarnings({"rawtypes", "unchecked", "serial"})
public class ClosureEventListener implements SaveOrUpdateEventListener,
                                             PreLoadEventListener,
                                             PostLoadEventListener,
                                             PostInsertEventListener,
                                             PostUpdateEventListener,
                                             PostDeleteEventListener,
                                             PreDeleteEventListener,
                                             PreUpdateEventListener {

    private static final long serialVersionUID = 1;
    private static final Log log = LogFactory.getLog(ClosureEventListener.class);
    private static final Object[] EMPTY_OBJECT_ARRAY = new Object[] {};

    EventTriggerCaller saveOrUpdateCaller;
    EventTriggerCaller beforeInsertCaller;
    EventTriggerCaller preLoadEventCaller;
    EventTriggerCaller postLoadEventListener;
    EventTriggerCaller postInsertEventListener;
    EventTriggerCaller postUpdateEventListener;
    EventTriggerCaller postDeleteEventListener;
    EventTriggerCaller preDeleteEventListener;
    EventTriggerCaller preUpdateEventListener;
    private BeforeValidateHelper beforeValidateHelper = new BeforeValidateHelper();
    boolean shouldTimestamp = false;
    MetaProperty dateCreatedProperty;
    MetaProperty lastUpdatedProperty;
    MetaClass domainMetaClass;
    boolean failOnErrorEnabled = false;
    MetaProperty errorsProperty;
    Map validateParams;
    MetaMethod validateMethod;

    public ClosureEventListener(Class<?> domainClazz, boolean failOnError, List failOnErrorPackages) {
        domainMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(domainClazz);
        dateCreatedProperty = domainMetaClass.getMetaProperty(GrailsDomainClassProperty.DATE_CREATED);
        lastUpdatedProperty = domainMetaClass.getMetaProperty(GrailsDomainClassProperty.LAST_UPDATED);
        if (dateCreatedProperty != null || lastUpdatedProperty != null) {
            Mapping m = GrailsDomainBinder.getMapping(domainClazz);
            shouldTimestamp = m == null || m.isAutoTimestamp();
        }

        saveOrUpdateCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.ONLOAD_SAVE);
        beforeInsertCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_INSERT_EVENT);
        preLoadEventCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.ONLOAD_EVENT);
        if (preLoadEventCaller == null) {
            preLoadEventCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_LOAD_EVENT);
        }
        postLoadEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_LOAD_EVENT);
        postInsertEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_INSERT_EVENT);
        postUpdateEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_UPDATE_EVENT);
        postDeleteEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_DELETE_EVENT);
        preDeleteEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_DELETE_EVENT);
        preUpdateEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_UPDATE_EVENT);

        if (failOnErrorPackages.size() > 0) {
            failOnErrorEnabled = GrailsClassUtils.isClassBelowPackage(domainClazz, failOnErrorPackages);
        } else {
            failOnErrorEnabled = failOnError;
        }

        validateParams = new HashMap();
        validateParams.put(ValidatePersistentMethod.ARGUMENT_DEEP_VALIDATE, Boolean.FALSE);

        errorsProperty = domainMetaClass.getMetaProperty(AbstractDynamicPersistentMethod.ERRORS_PROPERTY);

        validateMethod = domainMetaClass.getMetaMethod(ValidatePersistentMethod.METHOD_SIGNATURE,
                new Object[] { Map.class });
    }

    private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) {
        Method method = ReflectionUtils.findMethod(domainClazz, event);
        if (method != null) {
            ReflectionUtils.makeAccessible(method);
            return new MethodCaller(method);
        }

        Field field = ReflectionUtils.findField(domainClazz, event);
        if (field != null) {
            ReflectionUtils.makeAccessible(field);
            return new FieldClosureCaller(field);
        }

        MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY);
        if (metaMethod != null) {
            return new MetaMethodCaller(metaMethod);
        }

        MetaProperty metaProperty = domainMetaClass.getMetaProperty(event);
        if (metaProperty != null) {
            return new MetaPropertyClosureCaller(metaProperty);
        }

        return null;
    }

    public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
        // no-op, merely a hook for plugins to override
    }

    private void synchronizePersisterState(Object entity, EntityPersister persister, Object[] state) {
        String[] propertyNames = persister.getPropertyNames();
        for (int i = 0; i < propertyNames.length; i++) {
            String p = propertyNames[i];
            MetaProperty metaProperty = domainMetaClass.getMetaProperty(p);
            if (ClosureEventTriggeringInterceptor.IGNORED.contains(p) || metaProperty == null) {
                continue;
            }
            Object value = metaProperty.getProperty(entity);
            state[i] = value;
            persister.setPropertyValue(entity, i, value, EntityMode.POJO);
        }
    }

    public void onPreLoad(final PreLoadEvent event) {
        if (preLoadEventCaller == null) {
            return;
        }

        doWithManualSession(event, new Closure(this) {
            @Override
            public Object call() {
                preLoadEventCaller.call(event.getEntity());
                return null;
            }
        });
    }

    public void onPostLoad(final PostLoadEvent event) {
        if (postLoadEventListener == null) {
            return;
        }

       doWithManualSession(event, new Closure(this) {
            @Override
            public Object call() {
                postLoadEventListener.call(event.getEntity());
                return null;
            }
        });
    }

    public void onPostInsert(PostInsertEvent event) {
        final Object entity = event.getEntity();
        AbstractSavePersistentMethod.clearDisabledValidations(entity);
        if (postInsertEventListener == null) {
            return;
        }

        doWithManualSession(event, new Closure(this) {
            @Override
            public Object call() {
                postInsertEventListener.call(entity);
                return null;
            }
        });
    }

    public void onPostUpdate(PostUpdateEvent event) {
        final Object entity = event.getEntity();
        AbstractSavePersistentMethod.clearDisabledValidations(entity);
        if (postUpdateEventListener == null) {
            return;
        }

        doWithManualSession(event, new Closure(this) {
            @Override
            public Object call() {
                postUpdateEventListener.call(entity);
                return null;
            }
        });
    }

    public void onPostDelete(PostDeleteEvent event) {
        final Object entity = event.getEntity();
        AbstractSavePersistentMethod.clearDisabledValidations(entity);
        if (postDeleteEventListener == null) {
            return;
        }

        doWithManualSession(event, new Closure(this) {
            @Override
            public Object call() {
                postDeleteEventListener.call(entity);
                return null;
            }
        });
    }

    public boolean onPreDelete(final PreDeleteEvent event) {
        if (preDeleteEventListener == null) {
            return false;
        }

        return doWithManualSession(event, new Closure<Boolean>(this) {
            @Override
            public Boolean call() {
                return preDeleteEventListener.call(event.getEntity());
            }
        });
    }

    public boolean onPreUpdate(final PreUpdateEvent event) {
        return doWithManualSession(event, new Closure<Boolean>(this) {
            @Override
            public Boolean call() {
                Object entity = event.getEntity();
                boolean evict = false;
                if (preUpdateEventListener != null) {
                    evict = preUpdateEventListener.call(entity);
                    synchronizePersisterState(entity, event.getPersister(), event.getState());
                }
                if (lastUpdatedProperty != null && shouldTimestamp) {
                    Object now = DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] { System
                            .currentTimeMillis() });
                    event.getState()[ArrayUtils.indexOf(event.getPersister().getPropertyNames(), GrailsDomainClassProperty.LAST_UPDATED)] = now;
                    lastUpdatedProperty.setProperty(entity, now);
                }
                if (!AbstractSavePersistentMethod.isAutoValidationDisabled(entity)
                        && !DefaultTypeTransformation.castToBoolean(validateMethod.invoke(entity,
                                new Object[] { validateParams }))) {
                    evict = true;
                    if (failOnErrorEnabled) {
                        Errors errors = (Errors) errorsProperty.getProperty(entity);
                        throw new ValidationException("Validation error whilst flushing entity [" + entity.getClass().getName()
                                + "]", errors);
                    }
                }
                return evict;
            }
        });
    }

    private <T> T doWithManualSession(AbstractEvent event, Closure<T> callable) {
        Session session = event.getSession();
        FlushMode current = session.getFlushMode();
        try {
           session.setFlushMode(FlushMode.MANUAL);
           return callable.call();
        } finally {
            session.setFlushMode(current);
        }
    }

    public boolean onPreInsert(final PreInsertEvent event) {
        return doWithManualSession(event, new Closure<Boolean>(this) {
            @Override
            public Boolean call() {
                Object entity = event.getEntity();
                boolean synchronizeState = false;
                if (beforeInsertCaller != null) {
                    if (beforeInsertCaller.call(entity)) {
                        return true;
                    }
                    synchronizeState = true;
                }
                if (shouldTimestamp) {
                    long time = System.currentTimeMillis();
                    if (dateCreatedProperty != null) {
                        Object now = DefaultGroovyMethods.newInstance(dateCreatedProperty.getType(), new Object[] { time });
                        dateCreatedProperty.setProperty(entity, now);
                        synchronizeState = true;
                    }
                    if (lastUpdatedProperty != null) {
                        Object now = DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] { time });
                        lastUpdatedProperty.setProperty(entity, now);
                        synchronizeState = true;
                    }
                }

                if (synchronizeState) {
                    synchronizePersisterState(entity, event.getPersister(), event.getState());
                }

                boolean evict = false;
                if (!AbstractSavePersistentMethod.isAutoValidationDisabled(entity)
                        && !DefaultTypeTransformation.castToBoolean(validateMethod.invoke(entity,
                                new Object[] { validateParams }))) {
                    evict = true;
                    if (failOnErrorEnabled) {
                        Errors errors = (Errors) errorsProperty.getProperty(entity);
                        throw new ValidationException("Validation error whilst flushing entity [" + entity.getClass().getName()
                                + "]", errors);
                    }
                }
                return evict;
            }
        });
    }

    public void onValidate(ValidationEvent event) {
        beforeValidateHelper.invokeBeforeValidate(
                event.getEntityObject(), event.getValidatedFields());
    }

    private static abstract class EventTriggerCaller {

        public abstract boolean call(Object entity);

        boolean resolveReturnValue(Object retval) {
            if (retval instanceof Boolean) {
                return !((Boolean) retval).booleanValue();
            }
            return false;
        }
    }

    private static class MethodCaller extends EventTriggerCaller {
        Method method;

        MethodCaller(Method method) {
            this.method = method;
        }

        @Override
        public boolean call(Object entity) {
            Object retval = ReflectionUtils.invokeMethod(method, entity);
            return resolveReturnValue(retval);
        }
    }

    private static class MetaMethodCaller extends EventTriggerCaller {
        MetaMethod method;

        MetaMethodCaller(MetaMethod method) {
            this.method = method;
        }

        @Override
        public boolean call(Object entity) {
            Object retval = method.invoke(entity, EMPTY_OBJECT_ARRAY);
            return resolveReturnValue(retval);
        }
    }

    private static abstract class ClosureCaller extends EventTriggerCaller {
        boolean cloneFirst = false;

        Object callClosure(Object entity, Closure callable) {
            if (cloneFirst) {
                callable = (Closure)callable.clone();
            }
            callable.setResolveStrategy(Closure.DELEGATE_FIRST);
            callable.setDelegate(entity);
            return callable.call();
        }
    }

    private static class FieldClosureCaller extends ClosureCaller {
        Field field;

        FieldClosureCaller(Field field) {
            this.field = field;
            if (Modifier.isStatic(field.getModifiers())) {
                cloneFirst = true;
            }
        }

        @Override
        public boolean call(Object entity) {
            Object fieldval = ReflectionUtils.getField(field, entity);
            if (fieldval instanceof Closure) {
                return resolveReturnValue(callClosure(entity, (Closure) fieldval));
            }
            log.error("Field " + field + " is not Closure or method.");
            return false;
        }
    }

    private static class MetaPropertyClosureCaller extends ClosureCaller {
        MetaProperty metaProperty;

        MetaPropertyClosureCaller(MetaProperty metaProperty) {
            this.metaProperty = metaProperty;
            if (Modifier.isStatic(metaProperty.getModifiers())) {
                cloneFirst = true;
            }
        }

        @Override
        public boolean call(Object entity) {
            Object fieldval = metaProperty.getProperty(entity);
            if (fieldval instanceof Closure) {
                return resolveReturnValue(callClosure(entity, (Closure) fieldval));
            }
            log.error("Field " + metaProperty + " is not Closure.");
            return false;
        }
    }
}


text:
package com.tylerlubeck.maraudersmapmultiuser.Models;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Paint;
import android.graphics.Color;
import android.graphics.Canvas;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.tylerlubeck.maraudersmapmultiuser.R;

/**
 * Created by Hunter on 10/11/14.
 *
 */
public class FloorMapImage implements AdapterView.OnItemSelectedListener {
    private final int width;
    private final int height;
    private int original_width;
    private int original_height;
    private Bitmap unmarked_image;
    private final ImageView image_view;
    private final Context context;

    private final int DEFAULT_WIDTH = 1200;
    private final int DEFAULT_HEIGHT = 800;
    private final int DEFAULT_POINT_RADIUS = 20;

    /**
     * Create a class to represent a FloorMapImage.
     *      This will fetch the correct image from the drawables folder based on the building name and floor number.
     *      It will scale the image based on a screen size of 1200x800.
     *      It handles drawing points on the image
     * @param building_name     The name of the building this image_view represents
     * @param floor_number      The floor of the building this represents
     * @param image_view        The View to put the image on
     * @param context           The context the image_view belongs to
     */
    public FloorMapImage(String building_name, int floor_number, ImageView image_view, Context context){
        /* TODO: Eventually calculate these based on screen size */
        this.width = DEFAULT_WIDTH;
        this.height = DEFAULT_HEIGHT;
        this.image_view = image_view;
        this.context = context;
        this.setImage(building_name, floor_number);
    }

    /**
     * Instantiate a FloorMapImage based on a blank image view, with the image itself to be filled in later.
     * @param image_view
     * @param context
     */
    public FloorMapImage(ImageView image_view, Context context) {
        this.width = DEFAULT_WIDTH;
        this.height = DEFAULT_HEIGHT;
        this.image_view = image_view;
        this.context = context;
    }

    public void setImageFromUrl(String imageUrl, final int x_coordinate, final int y_coordinate) {
        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.displayImage(imageUrl, this.image_view, null, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                Log.d("MARAUDERSMAP", "STARTED LOADING IMAGE " + imageUri);
                View parentView = (View) view.getParent();
                TextView loadingText = (TextView) parentView.findViewById(R.id.map_loading_textview);
                loadingText.setText("Magic takes time. So do network requests.");
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                Log.e("MARAUDERSMAP", "FAILED TO LOAD IMAGE " + imageUri);
                Log.e("MARAUDERSMAP", "BECAUSE: " + failReason.toString());
                View parentView = (View) view.getParent();
                TextView loadingText = (TextView) parentView.findViewById(R.id.map_loading_textview);
                ProgressBar progressBar = (ProgressBar) parentView.findViewById(R.id.map_loading_spinner);
                Button updateBtn = (Button) parentView.findViewById(R.id.update_map_btn);
                progressBar.setVisibility(View.GONE);
                loadingText.setVisibility(View.GONE);
                view.setVisibility(View.VISIBLE);
                updateBtn.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                View parentView = (View) view.getParent();
                TextView loadingText = (TextView) parentView.findViewById(R.id.map_loading_textview);
                ProgressBar progressBar = (ProgressBar) parentView.findViewById(R.id.map_loading_spinner);
                Button updateBtn = (Button) parentView.findViewById(R.id.update_map_btn);
                progressBar.setVisibility(View.GONE);
                loadingText.setVisibility(View.GONE);
                view.setVisibility(View.VISIBLE);
                updateBtn.setVisibility(View.VISIBLE);
                Log.d("MARAUDERSMAP", "FINISHED LOADING IMAGE FROM " + imageUri);
                FloorMapImage.this.setImageFromBitmap(loadedImage);
                FloorMapImage.this.draw_point_clear(x_coordinate, y_coordinate);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                Log.e("MARAUDERSMAP", "CANCELLED LOADING IMAGE " + imageUri);

            }
        }, new ImageLoadingProgressListener() {
            @Override
            public void onProgressUpdate(String imageUri, View view, int current, int total) {
                View parentView = (View) view.getParent();
                TextView loadingText = (TextView) parentView.findViewById(R.id.map_loading_textview);
                loadingText.setText("Here we gooooo");
                Log.d("MARAUDERSMAP", String.format("Image %d/%d loaded", current, total));
            }
        });
    }

    /**
     * Sets the image in the image view, and repopulates the other images
     * @param building_name     The string name of the building
     * @param floor_number      The floor number of the building
     */
    void setImage(String building_name, int floor_number) {
        String file_path = building_name.toLowerCase().replaceAll(" ", "_").replaceAll("/", "") + String.valueOf(floor_number);

        this.image_view.setImageResource(this.context.getResources().getIdentifier(file_path,
                "drawable",
                this.context.getPackageName()));
        Bitmap Floorbitmap = ((BitmapDrawable) this.image_view.getDrawable()).getBitmap();
        this.setImageFromBitmap(Floorbitmap);

    }

    private void setImageFromBitmap(Bitmap bitmap) {
        this.original_height = bitmap.getHeight();
        this.original_width = bitmap.getWidth();
        this.unmarked_image = Bitmap.createScaledBitmap(bitmap,
                this.width,
                this.height,
                true);
        this.image_view.setImageBitmap(this.unmarked_image);
    }

    /**
     *  Draws a point on the image_view at (x, y)
     *  Clears all other points drawn on the image_view
     * @param x     The x coordinate to draw at
     * @param y     The y coordinate to draw at
     */
    void draw_point_clear(int x, int y){
        Bitmap bitmap = this.unmarked_image.copy(this.unmarked_image.getConfig(),
                                                true);
        this.draw_point(x, y, bitmap);
    }

    /**
     *  Draws a point on the image_view at (x, y)
     *  Does not clear the image_view before drawing
     * @param x     The x coordinate to draw at
     * @param y     The y coordinate to draw at
     */
    void draw_point_noclear(int x, int y){
        Bitmap bitmap = ((BitmapDrawable)this.image_view.getDrawable()).getBitmap();
        this.draw_point(x, y, bitmap);
    }

    /**
     * Draws a point on the given bitmap, and sets the image_view to display the updated bitmap
     * @param x         The x coordinate to draw at
     * @param y         The y coordinate to draw at
     * @param bitmap    The bitmap to draw on
     */
    private void draw_point(int x, int y, Bitmap bitmap) {
        if ( x >= 0 && y >= 0) {
            float scaled_x = x * (float) this.width / (float) this.original_width;
            float scaled_y = y * (float) this.height / (float) this.original_height;
            Paint paint = new Paint();
            paint.setColor(Color.BLUE);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawCircle(scaled_x, scaled_y, DEFAULT_POINT_RADIUS, paint);
            this.image_view.setImageBitmap(bitmap);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
        Location location = (Location) adapterView.getItemAtPosition(position);
        this.draw_point_clear(location.getX_coordinate(), location.getY_coordinate());
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        Bitmap bitmap = this.unmarked_image.copy(this.unmarked_image.getConfig(), true);
        this.image_view.setImageBitmap(bitmap);
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function(mi2){

var undef = void 0;

function Agregator(){
	this.computed = [];
}

mi2.Agregator = Agregator;
var proto = Agregator.prototype;

proto.withFields = function(fields){
	this.fields = fields;
	return this;
}

proto.withComputed = function(computed){
	this.computed = computed;
	return this;
}

proto.forEach = function(func){
	var items = this.fields;
	for(var p in items){
		func(items[p], p, items);
	}
}

proto.map = function(func){
	var ret = {};
	this.forEach((item,i,src)=>{ ret[i] = func(item,i,src); });
	return ret;
}

proto.filter = function(func){
	var ret = {};
	this.forEach((item,i,src)=>{ if(func(item,i,src)) ret[i] = item; });
	return new Agregator().withFields(ret);
}

proto.getValue = function(){
	return this.map(item=>item.value);
}

proto.getInitialValue = function(){
	return this.map(item=>item.initialValue());
}

/** agregate single row into new object or an existing continuation
*/
proto.add = function(row, obj){
	obj = obj || this.getInitialValue();
	this.forEach((item,i)=>{
		if(item.filter(row)) obj[i] = item.visit( obj[i], item.column(row) );
	});
	return obj;
}

proto.groupAdd = function(row, groupKey, groups){
	groups[groupKey] = this.add(row, groups[groupKey]);
}

/** agregate rows into new object or an existing continuation
*/
proto.agregate = function(arr, obj){
	obj = obj || {};
	var val;
	this.forEach((item,i)=>{
		val = item.initialValue();
		arr.forEach(row=>{
			if(item.filter(row)) val = item.visit( val, item.column(row) );
		});
		obj[i] = val;
	});
	return obj;
}

proto.combineAdd = function(old, dataToAdd){
	this.forEach((item,i)=>{
		old[i] = item.visit(old[i], dataToAdd[i]);
	});
}

/** combine calculated results into one
*/
proto.combine = function(arr, obj){
	obj = obj || {};
	var val;
	this.forEach((item,i)=>{
		val = item.initialValue();
		arr.forEach(row=>{
			val = item.visit( val, row[i] );
		});
		obj[i] = val;
	});
	return obj;
}

proto.addComputed = function(row, conf){
	conf = conf || this.computed;
	conf.forEach(singleConf=>{
		for(var p in singleConf){
			row[p] = singleConf[p](row);
		}
	});
}

mi2.columnForCount = row=>1;

mi2.agregatorFunc = {
	sum:   (column, filter)=> mi2.makeFieldAgregator({
		column, filter,
		visit: (old, val) => val === undef ? old : old+val,
		value: 0
	}),
	count: (filter)=> mi2.makeFieldAgregator({
		filter, column: mi2.columnForCount,
		visit: (old, val) => val === undef ? old : old+val,
		value: 0
	}),
	min:   (column, filter)=> mi2.makeFieldAgregator({
		column,filter,
		visit: (old, val) => val === undef || (old !== undef && old <= val) ? old : val,
	}),
	max:   (column, filter)=> mi2.makeFieldAgregator({
		column,filter,
		visit: (old, val) => val === undef || old >= val ? old : val,
		value: 0
	}),
	column:(column, filter)=> mi2.makeFieldAgregator({
		column,filter,
		visit: (old, val)=>val,
	}),
};

/** utility function to help build agregator definition with plenty of handy defaults.
*/
mi2.makeFieldAgregator = function(def){

	if(def.column){
		if(typeof def.column == 'string'){
			var column = def.column;
			def.column = row=>row[column];
		}

	}else{
		def.column = mi2.columnForCount;
	}

	if(!def.visit) def.visit = function(){};

	if(!def.filter) def.filter = row=>true;

	if(!def.initialValue){
		var _initialValue = def.value;
		def.initialValue = function(){ return _initialValue; }
	}

	if(!def.reset){
		def.reset = function(){ this.value = this.initialValue(); }
	}

	return def;
}

/** generate grouping key based on columns, by concatenating values into a string

columns example:
  ['groupId','userId']

hardcoded version that would give same key:
  row.groupId+'/'+row.userId+'/'
*/
mi2.makeGroupKeyFunction = function(columns){
	return function(row){
		ret = '';
		columns.forEach(column=>ret += row[column]+'/');
		return ret;
	}
}

mi2.groupRows = function(groupFunc, arr){
	return mi2.objToArray(mi2.mapRows(groupFunc, arr));
}

mi2.mapRow = function(groupKey, row, groups){
	groups[groupKey] = groups[groupKey] || [];
	groups[groupKey].push(row);
	return groupKey;
}

mi2.mapRows = function(groupFunc, arr, groups){
	groups = groups || {};
	var groupKey = groupFunc(row);
	arr.forEach( row=>mi2.mapRow(groupKey, row, groups) );
	return groups;
}

mi2.average = function(total, count){
	return count == 0 ? 0: total / count;
}

mi2.objToArray = function(obj){
	var ret = [];
	for(var p in obj) ret.push(obj[p]);
	return ret;
}

})(mi2JS)


text:
LEVEL = ../../../..

PROG     = is
LDFLAGS  =

ifdef SMALL_PROBLEM_SIZE
CPPFLAGS = -DSMALL_PROBLEM_SIZE
else
ifeq ($(ARCH),XCore)
XCORE_TARGET_NEEDS_MEMORY := 512
endif
endif

include $(LEVEL)/MultiSource/Makefile.multisrc


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.
 */
package io.prestosql.spi.type;

import com.fasterxml.jackson.annotation.JsonValue;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Objects;

import static io.prestosql.spi.type.Timestamps.MICROSECONDS_PER_SECOND;
import static io.prestosql.spi.type.Timestamps.NANOSECONDS_PER_MICROSECOND;
import static io.prestosql.spi.type.Timestamps.PICOSECONDS_PER_MICROSECOND;
import static io.prestosql.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND;
import static io.prestosql.spi.type.Timestamps.formatTimestamp;
import static io.prestosql.spi.type.Timestamps.round;
import static io.prestosql.spi.type.Timestamps.roundDiv;
import static java.lang.Math.floorDiv;
import static java.lang.Math.floorMod;
import static java.lang.String.format;

public final class SqlTimestamp
{
    private final int precision;
    private final long epochMicros;
    private final int picosOfMicros;

    public static SqlTimestamp fromMillis(int precision, long millis)
    {
        return newInstanceWithRounding(precision, millis * 1000, 0);
    }

    public static SqlTimestamp newInstance(int precision, long epochMicros, int picosOfMicro)
    {
        if (precision <= 6) {
            if (picosOfMicro != 0) {
                throw new IllegalArgumentException(format("Expected picosOfMicro to be 0 for precision %s: %s", precision, picosOfMicro));
            }
            if (round(epochMicros, 6 - precision) != epochMicros) {
                throw new IllegalArgumentException(format("Expected 0s for digits beyond precision %s: epochMicros = %s", precision, epochMicros));
            }
        }
        else {
            if (round(picosOfMicro, 12 - precision) != picosOfMicro) {
                throw new IllegalArgumentException(format("Expected 0s for digits beyond precision %s: picosOfMicro = %s", precision, picosOfMicro));
            }
        }

        if (picosOfMicro < 0 || picosOfMicro > PICOSECONDS_PER_MICROSECOND) {
            throw new IllegalArgumentException("picosOfMicro is out of range: " + picosOfMicro);
        }

        return new SqlTimestamp(precision, epochMicros, picosOfMicro);
    }

    private static SqlTimestamp newInstanceWithRounding(int precision, long epochMicros, int picosOfMicro)
    {
        if (precision < 6) {
            epochMicros = round(epochMicros, 6 - precision);
            picosOfMicro = 0;
        }
        else if (precision == 6) {
            if (round(picosOfMicro, 6) == PICOSECONDS_PER_MICROSECOND) {
                epochMicros++;
            }
            picosOfMicro = 0;
        }
        else {
            picosOfMicro = (int) round(picosOfMicro, 12 - precision);
        }

        return new SqlTimestamp(precision, epochMicros, picosOfMicro);
    }

    private SqlTimestamp(int precision, long epochMicros, int picosOfMicro)
    {
        this.precision = precision;
        this.epochMicros = epochMicros;
        this.picosOfMicros = picosOfMicro;
    }

    public int getPrecision()
    {
        return precision;
    }

    public long getMillis()
    {
        return roundDiv(epochMicros, 1000);
    }

    public long getEpochMicros()
    {
        return epochMicros;
    }

    public int getPicosOfMicros()
    {
        return picosOfMicros;
    }

    public SqlTimestamp roundTo(int precision)
    {
        return newInstanceWithRounding(precision, epochMicros, picosOfMicros);
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        SqlTimestamp that = (SqlTimestamp) o;
        return epochMicros == that.epochMicros &&
                picosOfMicros == that.picosOfMicros &&
                precision == that.precision;
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(epochMicros, picosOfMicros, precision);
    }

    @JsonValue
    @Override
    public String toString()
    {
        return formatTimestamp(precision, epochMicros, picosOfMicros);
    }

    /**
     * @return timestamp rounded to nanosecond precision
     */
    public LocalDateTime toLocalDateTime()
    {
        long epochSecond = floorDiv(epochMicros, MICROSECONDS_PER_SECOND);
        int microOfSecond = floorMod(epochMicros, MICROSECONDS_PER_SECOND);
        int nanoOfSecond = (microOfSecond * NANOSECONDS_PER_MICROSECOND) +
                roundDiv(picosOfMicros, PICOSECONDS_PER_NANOSECOND);
        return LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, ZoneOffset.UTC);
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

/**
 * @see BxDolCmtsNotes
 */
class BxTemplCmtsNotes extends BxBaseCmtsNotes
{
    function __construct($sSystem, $iId, $iInit = true, $oTemplate = false)
    {
        parent::__construct($sSystem, $iId, $iInit, $oTemplate);
    }
}

/** @} */


text:
package org.innovateuk.ifs.viewmodel;

import org.innovateuk.ifs.competition.resource.CompetitionResource;

import java.util.List;
import java.util.Map;

public class AssessorProfileSkillsViewModel {

    private CompetitionResource competition;
    private AssessorProfileDetailsViewModel assessorProfileDetailsViewModel;
    private Map<String, List<String>> innovationAreas;
    private String skillAreas;
    private boolean compAdminUser;

    public AssessorProfileSkillsViewModel(CompetitionResource competition,
                                          AssessorProfileDetailsViewModel assessorProfileDetailsViewModel,
                                          Map<String, List<String>> innovationAreas,
                                          String skillAreas,
                                          boolean compAdminUser) {
        this.competition = competition;
        this.assessorProfileDetailsViewModel = assessorProfileDetailsViewModel;
        this.innovationAreas = innovationAreas;
        this.skillAreas = skillAreas;
        this.compAdminUser = compAdminUser;
    }

    public CompetitionResource getCompetition() {
        return competition;
    }

    public AssessorProfileDetailsViewModel getAssessorProfileDetailsViewModel() {
        return assessorProfileDetailsViewModel;
    }

    public Map<String, List<String>> getInnovationAreas() {
        return innovationAreas;
    }

    public String getSkillAreas() {
        return skillAreas;
    }

    public boolean isCompAdminUser() {
        return compAdminUser;
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends MY_Controller
{
  function __construct()
  {
    parent::__construct();
    $this->load->library(array('ion_auth'));
  }

  public function index()
  {
  }

  public function login()
  {
    $this->data['page_title'] = 'Login';
    if($this->input->post())
    {
      $this->load->library('form_validation');
      $this->form_validation->set_rules('identity', 'Identity', 'required');
      $this->form_validation->set_rules('password', 'Password', 'required');
      $this->form_validation->set_rules('remember','Remember me','integer');
      if($this->form_validation->run()===TRUE)
      {
        $remember = (bool) $this->input->post('remember');
        if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
        {
          redirect('admin', 'refresh');
        }
        else
        {
          $this->session->set_flashdata('message',$this->ion_auth->errors());
          redirect('admin/user/login', 'refresh');
        }
      }
    }
    $this->load->helper('form');
    $this->render('admin/login_view','admin_master');
  }

  public function logout()
  {
    $this->ion_auth->logout();
    redirect('admin/user/login', 'refresh');
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>local.swt</groupId>
  <artifactId>swtlinux_x86_64</artifactId>
  <versioning>
    <release>4.25</release>
    <versions>
      <version>4.25</version>
    </versions>
    <lastUpdated>20221015155355</lastUpdated>
  </versioning>
</metadata>


text:
module.exports = set_and_verify_json_graph;

Array.prototype.flatMap = function(selector) {
    return this.reduce(function(xs, x, i, a){
        return xs.concat(selector(x, i, a));
    }, []);
};

var _ = require("lodash");
var falcor = require("./../../../lib/");
var Model = falcor.Model;
var partial_cache = require("./partial-cache");
var verify = require("./verify");
var set_envelopes = require("./set-envelopes");
var clone = require("./clone");

function set_and_verify_json_graph(test, suffix, envelopes, options) {
    var check_set = verify(suffix);
    var set_tuple = set_envelopes(envelopes, suffix, clone(options));
    var check_get = check_set.apply(test, set_tuple);
    var paths     = envelopes.flatMap(get_paths).map(slice_bound(set_tuple[0]))
    return check_get.apply(test, paths);
}

function get_paths(envelope) {
    return envelope.paths.map(function(path) {
        return JSON.parse(JSON.stringify(path));
    });
}

function slice_bound(model) {
    return function(path) {
        return path.slice(model._path.length);
    }
}


text:
import Vuex from 'vuex'
import { Netmask } from 'netmask'

const initAddr = '127.0.0.1'
const initPrefixLength = 8

export default Vuex.createStore({
  strict: process.env.NODE_ENV !== 'production',
  state: {
    ipAddrString: initAddr,
    ipBlock: new Netmask(`${initAddr}/${initPrefixLength}`)
  },
  getters: {
    ipAddrString (state) {
      return state.ipAddrString
    },
    ipBlock (state) {
      return state.ipBlock
    }
  },
  mutations: {
    setIPAddrString (state, payload) {
      state.ipAddrString = payload
    },
    setIPBlock (state, payload) {
      state.ipBlock = payload
    }
  }
})


text:
define([
  'intern!object',
  'intern/chai!expect',
  '../helper/fixtures/custom.fixture',
  'ally/query/tabsequence.sort-tabindex',
], function(registerSuite, expect, customFixture, sortTabindex) {

  registerSuite(function() {
    var fixture;

    return {
      name: 'query/tabsequence.sort-tabindex',

      beforeEach: function() {
        fixture = customFixture([
          '<input type="text" data-label="5">',
          '

',
          '

',
          '

',
          '

',
          '

',
          '

',
        ]);
      },
      afterEach: function() {
        fixture.remove();
        fixture = null;
      },

      sort: function() {
        var expected = '1 2 3 4 5 6 7'.split(' ');
        var nodes = [].slice.call(fixture.root.children, 0);
        var res = sortTabindex(nodes);
        var sequence = res.map(function(element) {
          return element.getAttribute('data-label');
        });
        expect(sequence).to.deep.equal(expected);
      },
    };
  });
});


text:
package com.stratio.sparta.driver.helper

import com.stratio.sparta.driver.cube.{Cube, CubeWriter}
import com.stratio.sparta.sdk.TypeOp.TypeOp
import com.stratio.sparta.sdk._
import com.stratio.sparta.serving.core.helpers.OperationsHelper
import com.stratio.sparta.serving.core.models._
import org.apache.spark.sql.types._

object SchemaHelper {

  final val Default_Precision = 10
  final val Default_Scale = 0
  final val Nullable = true
  final val NotNullable = false
  final val DefaultTimeStampTypeString = "timestamp"
  final val DefaultTimeStampType = TypeOp.Timestamp
  private val MetadataBuilder = new MetadataBuilder
  final val MeasureMetadata = MetadataBuilder.putBoolean(Output.MeasureMetadataKey, true).build()

  val mapTypes = Map(
    TypeOp.Long -> LongType,
    TypeOp.Double -> DoubleType,
    TypeOp.BigDecimal -> DecimalType(Default_Precision, Default_Scale),
    TypeOp.Int -> IntegerType,
    TypeOp.Boolean -> BooleanType,
    TypeOp.Date -> DateType,
    TypeOp.DateTime -> TimestampType,
    TypeOp.Timestamp -> TimestampType,
    TypeOp.ArrayDouble -> ArrayType(DoubleType),
    TypeOp.ArrayString -> ArrayType(StringType),
    TypeOp.String -> StringType,
    TypeOp.MapStringLong -> MapType(StringType, LongType),
    TypeOp.MapStringDouble -> MapType(StringType, DoubleType, false)
  )

  val mapSparkTypes: Map[DataType, TypeOp] = Map(
    LongType -> TypeOp.Long,
    DoubleType -> TypeOp.Double,
    DecimalType(Default_Precision, Default_Scale) -> TypeOp.BigDecimal,
    IntegerType -> TypeOp.Int,
    BooleanType -> TypeOp.Boolean,
    DateType -> TypeOp.Date,
    TimestampType -> TypeOp.Timestamp,
    ArrayType(DoubleType) -> TypeOp.ArrayDouble,
    ArrayType(StringType) -> TypeOp.ArrayString,
    StringType -> TypeOp.String,
    MapType(StringType, LongType) -> TypeOp.MapStringLong,
    MapType(StringType, DoubleType, false) -> TypeOp.MapStringDouble
  )

  val mapStringSparkTypes = Map(
    "long" -> LongType,
    "double" -> DoubleType,
    "int" -> IntegerType,
    "integer" -> IntegerType,
    "bool" -> BooleanType,
    "boolean" -> BooleanType,
    "date" -> DateType,
    "datetime" -> TimestampType,
    "timestamp" -> TimestampType,
    "string" -> StringType,
    "arraydouble" -> ArrayType(DoubleType),
    "arraystring" -> ArrayType(StringType),
    "text" -> StringType
  )

  def getSchemasFromParsers(transformationsModel: Seq[TransformationsModel],
                            initSchema: Map[String, StructType]): Map[String, StructType] = {
    initSchema ++ searchSchemasFromParsers(transformationsModel.sortBy(_.order), initSchema)
  }

  private def searchSchemasFromParsers(transformationsModel: Seq[TransformationsModel],
                                       schemas: Map[String, StructType]): Map[String, StructType] = {
    transformationsModel.headOption match {
      case Some(transformationModel) =>
        val schema = transformationModel.outputFieldsTransformed.map(outputField =>
          outputField.name -> StructField(outputField.name,
            mapStringSparkTypes.getOrElse(outputField.`type`.toLowerCase, StringType),
            Nullable
          )
        )
        val fields = schemas.values.flatMap(structType => structType.fields) ++ schema.map(_._2)
        val recursiveSchema = Map(transformationModel.order.toString -> StructType(fields.toSeq))

        if (transformationsModel.size == 1)
          schemas ++ recursiveSchema
        else schemas ++ searchSchemasFromParsers(transformationsModel.drop(1), recursiveSchema)
      case None =>
        schemas
    }
  }

  def getSchemaWithoutRaw(schemas: Map[String, StructType]): StructType =
    StructType(schemas.values.last.filter(_.name != Input.RawDataKey))

  def getSchemasFromCubes(cubes: Seq[Cube],
                          cubeModels: Seq[CubeModel]): Seq[TableSchema] = {
    for {
      (cube, cubeModel) <- cubes.zip(cubeModels)
      measuresMerged = (measuresFields(cube.operators) ++ getFixedMeasure(cubeModel.writer)).sortWith(_.name < _.name)
      timeDimension = getExpiringData(cubeModel).map(config => config.timeDimension)
      dimensions = filterDimensionsByTime(cube.dimensions.sorted, timeDimension)
      (dimensionsWithId, isAutoCalculatedId) = dimensionFieldsWithId(dimensions, cubeModel.writer)
      dateType = getTimeTypeFromString(cubeModel.writer.dateType.getOrElse(DefaultTimeStampTypeString))
      structFields = dimensionsWithId ++ timeDimensionFieldType(timeDimension, dateType) ++ measuresMerged
      schema = StructType(structFields)
      outputs = cubeModel.writer.outputs
    } yield TableSchema(outputs, cube.name, schema, timeDimension, dateType, isAutoCalculatedId)
  }

  def getExpiringData(cubeModel: CubeModel): Option[ExpiringDataConfig] = {
    val timeDimension = cubeModel.dimensions
      .find(dimensionModel => dimensionModel.computeLast.isDefined)

    timeDimension match {
      case Some(dimensionModelValue) =>
        Option(ExpiringDataConfig(
          dimensionModelValue.name,
          dimensionModelValue.precision,
          OperationsHelper.parseValueToMilliSeconds(dimensionModelValue.computeLast.get)))
      case _ => None
    }
  }

  // XXX Private methods.

  private def dimensionFieldsWithId(dimensions: Seq[Dimension],
                                    writerModel: WriterModel): (Seq[StructField], Boolean) = {
    val dimensionFields = dimensionsFields(dimensions)

    writerModel.isAutoCalculatedId.fold((dimensionFields, false)) { autoId =>
      if (autoId)
        (Seq(Output.defaultStringField(Output.Id, NotNullable)) ++ dimensionFields.filter(_.name != Output.Id), true)
      else (dimensionFields, false)
    }
  }

  private def filterDimensionsByTime(dimensions: Seq[Dimension], timeDimension: Option[String]): Seq[Dimension] =
    timeDimension match {
      case Some(timeName) => dimensions.filter(dimension => dimension.name != timeName)
      case None => dimensions
    }

  private def timeDimensionFieldType(timeDimension: Option[String], dateType: TypeOp.Value): Seq[StructField] = {
    timeDimension match {
      case None => Seq.empty[StructField]
      case Some(timeDimensionName) => Seq(Output.getTimeFieldType(dateType, timeDimensionName, NotNullable))
    }
  }

  def getTimeTypeFromString(timeType: String): TypeOp =
    timeType.toLowerCase match {
      case "timestamp" => TypeOp.Timestamp
      case "date" => TypeOp.Date
      case "datetime" => TypeOp.DateTime
      case "long" => TypeOp.Long
      case _ => TypeOp.String
    }

  private def measuresFields(operators: Seq[Operator]): Seq[StructField] =
    operators.map(operator =>
      StructField(operator.key, rowTypeFromOption(operator.returnType), NotNullable, MeasureMetadata))

  private def dimensionsFields(fields: Seq[Dimension]): Seq[StructField] =
    fields.map(field => StructField(field.name, rowTypeFromOption(field.precision.typeOp), NotNullable))

  private def rowTypeFromOption(optionType: TypeOp): DataType = mapTypes.getOrElse(optionType, StringType)

  private def getFixedMeasure(writerModel: WriterModel): Seq[StructField] =
    writerModel.fixedMeasure.fold(Seq.empty[StructField]) { fixedMeasure =>
      fixedMeasure.split(CubeWriter.FixedMeasureSeparator).headOption.fold(Seq.empty[StructField]) { measureName =>
        Seq(Output.defaultStringField(measureName, NotNullable, MeasureMetadata))
      }
    }

  def getSchemasFromTriggers(triggers: Seq[TriggerModel], outputModels: Seq[PolicyElementModel]): Seq[TableSchema] = {
    for {
      trigger <- triggers
      structFields = trigger.primaryKey.map(field => Output.defaultStringField(field, false))
      schema = StructType(structFields)
    } yield TableSchema(
      outputs = trigger.outputs,
      tableName = trigger.name,
      schema = schema,
      timeDimension = None,
      dateType = TypeOp.Timestamp,
      isAutoCalculatedId = false
    )
  }

  def getSchemasFromCubeTrigger(cubeModels: Seq[CubeModel], outputModels: Seq[PolicyElementModel]): Seq[TableSchema] = {
    val tableSchemas = for {
      cube <- cubeModels
      tableSchemas = getSchemasFromTriggers(cube.triggers, outputModels)
    } yield tableSchemas
    tableSchemas.flatten
  }
}


text:
published: true
layout: post
title: BCP for All Tables
---

I ran a lot of (am still running a lot of) `bcp` commands today. I just barely thought of the notion that I should/could have scripted a sproc to run all the `bcp` commands.

Here's a well-discussed example: [BCP all tables into files from a database](http://blogs.lessthandot.com/index.php/datamgmt/dbprogramming/bcp-all-tables-into-files/) from [Less Than Dot](http://blogs.lessthandot.com/).

```
SELECT 'EXEC xp_cmdshell ''bcp '           --bcp
+  QUOTENAME(DB_NAME())+ '.'               --database name
+  QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+ '.'  -- schema
+  QUOTENAME(name)                         -- table
+ ' out c:temp'                          -- output directory
+  REPLACE(SCHEMA_NAME(schema_id),' ','') + '_'
+  REPLACE(name,' ','')                    -- file name
+ '.txt -T -c'',no_output'   -- extension, security, no output
FROM sys.tables
```

With or without `xp_cmdshell`, I guess we can't actually run these commands as we create them. They still need to be run in Query Analyzer or SSMS.

---

For Microsoft's help page for `bcp`, see [bcp Utility](https://msdn.microsoft.com/en-us/library/ms162802.aspx).


text:
//Write a program that creates an array containing all letters from the alphabet (A-Z).
//Read a word from the console and print the index of each of its letters in the array.

using System;

class AllTheLetters
{
    static void Main()
    {
        char[] letters = new char[26];
        for (int i = 0; i < 26; i++)
        {
            letters[i] = (char)(65+i);
        }
        string input = Console.ReadLine();

        for (int i = 0; i < input.Length; i++)
        {
            Console.WriteLine("The code of letter--> "+input[i]+" <--is exactly  "+Array.IndexOf(letters,input[i]) );
            Console.WriteLine("                     ---               ---");
        }
    }
}


text:
<?php

/**
 * Represents a directory in the code coverage information tree.
 *
 * @category   PHP
 * @package    CodeCoverage
 * @author     Sebastian Bergmann <sebastian@phpunit.de>
 * @copyright  2009-2014 Sebastian Bergmann <sebastian@phpunit.de>
 * @license    http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @link       http://github.com/sebastianbergmann/php-code-coverage
 * @since      Class available since Release 1.1.0
 */
class PHP_CodeCoverage_Report_Node_Directory extends PHP_CodeCoverage_Report_Node implements IteratorAggregate
{

    /**
     * @var PHP_CodeCoverage_Report_Node[]
     */
    protected $children = array();

    /**
     * @var PHP_CodeCoverage_Report_Node_Directory[]
     */
    protected $directories = array();

    /**
     * @var PHP_CodeCoverage_Report_Node_File[]
     */
    protected $files = array();

    /**
     * @var array
     */
    protected $classes;

    /**
     * @var array
     */
    protected $traits;

    /**
     * @var array
     */
    protected $functions;

    /**
     * @var array
     */
    protected $linesOfCode = null;

    /**
     * @var integer
     */
    protected $numFiles = -1;

    /**
     * @var integer
     */
    protected $numExecutableLines = -1;

    /**
     * @var integer
     */
    protected $numExecutedLines = -1;

    /**
     * @var integer
     */
    protected $numClasses = -1;

    /**
     * @var integer
     */
    protected $numTestedClasses = -1;

    /**
     * @var integer
     */
    protected $numTraits = -1;

    /**
     * @var integer
     */
    protected $numTestedTraits = -1;

    /**
     * @var integer
     */
    protected $numMethods = -1;

    /**
     * @var integer
     */
    protected $numTestedMethods = -1;

    /**
     * @var integer
     */
    protected $numFunctions = -1;

    /**
     * @var integer
     */
    protected $numTestedFunctions = -1;

    /**
     * Returns the number of files in/under this node.
     *
     * @return integer
     */
    public function count()
    {

        if ($this->numFiles == -1) {
            $this->numFiles = 0;

            foreach ($this->children as $child) {
                $this->numFiles += count($child);
            }
        }

        return $this->numFiles;
    }

    /**
     * Returns an iterator for this node.
     *
     * @return RecursiveIteratorIterator
     */
    public function getIterator()
    {

        return new RecursiveIteratorIterator(
            new PHP_CodeCoverage_Report_Node_Iterator($this),
            RecursiveIteratorIterator::SELF_FIRST
        );
    }

    /**
     * Adds a new directory.
     *
     * @param  string $name
     *
     * @return PHP_CodeCoverage_Report_Node_Directory
     */
    public function addDirectory($name)
    {

        $directory = new PHP_CodeCoverage_Report_Node_Directory($name, $this);

        $this->children[] = $directory;
        $this->directories[] = &$this->children[count($this->children) - 1];

        return $directory;
    }

    /**
     * Adds a new file.
     *
     * @param  string  $name
     * @param  array   $coverageData
     * @param  array   $testData
     * @param  boolean $cacheTokens
     *
     * @return PHP_CodeCoverage_Report_Node_File
     * @throws PHP_CodeCoverage_Exception
     */
    public function addFile($name, array $coverageData, array $testData, $cacheTokens)
    {

        $file = new PHP_CodeCoverage_Report_Node_File(
            $name, $this, $coverageData, $testData, $cacheTokens
        );

        $this->children[] = $file;
        $this->files[] = &$this->children[count($this->children) - 1];

        $this->numExecutableLines = -1;
        $this->numExecutedLines = -1;

        return $file;
    }

    /**
     * Returns the directories in this directory.
     *
     * @return array
     */
    public function getDirectories()
    {

        return $this->directories;
    }

    /**
     * Returns the files in this directory.
     *
     * @return array
     */
    public function getFiles()
    {

        return $this->files;
    }

    /**
     * Returns the child nodes of this node.
     *
     * @return array
     */
    public function getChildNodes()
    {

        return $this->children;
    }

    /**
     * Returns the classes of this node.
     *
     * @return array
     */
    public function getClasses()
    {

        if ($this->classes === null) {
            $this->classes = array();

            foreach ($this->children as $child) {
                $this->classes = array_merge(
                    $this->classes, $child->getClasses()
                );
            }
        }

        return $this->classes;
    }

    /**
     * Returns the traits of this node.
     *
     * @return array
     */
    public function getTraits()
    {

        if ($this->traits === null) {
            $this->traits = array();

            foreach ($this->children as $child) {
                $this->traits = array_merge(
                    $this->traits, $child->getTraits()
                );
            }
        }

        return $this->traits;
    }

    /**
     * Returns the functions of this node.
     *
     * @return array
     */
    public function getFunctions()
    {

        if ($this->functions === null) {
            $this->functions = array();

            foreach ($this->children as $child) {
                $this->functions = array_merge(
                    $this->functions, $child->getFunctions()
                );
            }
        }

        return $this->functions;
    }

    /**
     * Returns the LOC/CLOC/NCLOC of this node.
     *
     * @return array
     */
    public function getLinesOfCode()
    {

        if ($this->linesOfCode === null) {
            $this->linesOfCode = array('loc' => 0, 'cloc' => 0, 'ncloc' => 0);

            foreach ($this->children as $child) {
                $linesOfCode = $child->getLinesOfCode();

                $this->linesOfCode['loc'] += $linesOfCode['loc'];
                $this->linesOfCode['cloc'] += $linesOfCode['cloc'];
                $this->linesOfCode['ncloc'] += $linesOfCode['ncloc'];
            }
        }

        return $this->linesOfCode;
    }

    /**
     * Returns the number of executable lines.
     *
     * @return integer
     */
    public function getNumExecutableLines()
    {

        if ($this->numExecutableLines == -1) {
            $this->numExecutableLines = 0;

            foreach ($this->children as $child) {
                $this->numExecutableLines += $child->getNumExecutableLines();
            }
        }

        return $this->numExecutableLines;
    }

    /**
     * Returns the number of executed lines.
     *
     * @return integer
     */
    public function getNumExecutedLines()
    {

        if ($this->numExecutedLines == -1) {
            $this->numExecutedLines = 0;

            foreach ($this->children as $child) {
                $this->numExecutedLines += $child->getNumExecutedLines();
            }
        }

        return $this->numExecutedLines;
    }

    /**
     * Returns the number of classes.
     *
     * @return integer
     */
    public function getNumClasses()
    {

        if ($this->numClasses == -1) {
            $this->numClasses = 0;

            foreach ($this->children as $child) {
                $this->numClasses += $child->getNumClasses();
            }
        }

        return $this->numClasses;
    }

    /**
     * Returns the number of tested classes.
     *
     * @return integer
     */
    public function getNumTestedClasses()
    {

        if ($this->numTestedClasses == -1) {
            $this->numTestedClasses = 0;

            foreach ($this->children as $child) {
                $this->numTestedClasses += $child->getNumTestedClasses();
            }
        }

        return $this->numTestedClasses;
    }

    /**
     * Returns the number of traits.
     *
     * @return integer
     */
    public function getNumTraits()
    {

        if ($this->numTraits == -1) {
            $this->numTraits = 0;

            foreach ($this->children as $child) {
                $this->numTraits += $child->getNumTraits();
            }
        }

        return $this->numTraits;
    }

    /**
     * Returns the number of tested traits.
     *
     * @return integer
     */
    public function getNumTestedTraits()
    {

        if ($this->numTestedTraits == -1) {
            $this->numTestedTraits = 0;

            foreach ($this->children as $child) {
                $this->numTestedTraits += $child->getNumTestedTraits();
            }
        }

        return $this->numTestedTraits;
    }

    /**
     * Returns the number of methods.
     *
     * @return integer
     */
    public function getNumMethods()
    {

        if ($this->numMethods == -1) {
            $this->numMethods = 0;

            foreach ($this->children as $child) {
                $this->numMethods += $child->getNumMethods();
            }
        }

        return $this->numMethods;
    }

    /**
     * Returns the number of tested methods.
     *
     * @return integer
     */
    public function getNumTestedMethods()
    {

        if ($this->numTestedMethods == -1) {
            $this->numTestedMethods = 0;

            foreach ($this->children as $child) {
                $this->numTestedMethods += $child->getNumTestedMethods();
            }
        }

        return $this->numTestedMethods;
    }

    /**
     * Returns the number of functions.
     *
     * @return integer
     */
    public function getNumFunctions()
    {

        if ($this->numFunctions == -1) {
            $this->numFunctions = 0;

            foreach ($this->children as $child) {
                $this->numFunctions += $child->getNumFunctions();
            }
        }

        return $this->numFunctions;
    }

    /**
     * Returns the number of tested functions.
     *
     * @return integer
     */
    public function getNumTestedFunctions()
    {

        if ($this->numTestedFunctions == -1) {
            $this->numTestedFunctions = 0;

            foreach ($this->children as $child) {
                $this->numTestedFunctions += $child->getNumTestedFunctions();
            }
        }

        return $this->numTestedFunctions;
    }
}


text:
Google::Ads::GoogleAds::Config.new do |c|
  # Treat deprecation warnings as errors will cause all deprecation warnings
  # to raise instead of calling `Warning#warn`. This lets you run your tests
  # against google-ads-googleads to make sure that you are not calling any
  # deprecated code
  c.treat_deprecation_warnings_as_errors = false

  # Warn on all deprecations. Setting this to `true` will cause the library to
  # warn every time a piece of deprecated code is called. The `false` (default)
  # behaviour is to only issue a warning once for each call site in your code.
  c.warn_on_all_deprecations = false

  # The developer token is required to authenticate that you are allowed to
  # make API calls.
  c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'

  # Authentication tells the API that you are allowed to make changes to the
  # specific account you're trying to access.
  # The default method of authentication is to use a refresh token, client id,
  # and client secret to generate an access token.
  c.client_id = 'INSERT_CLIENT_ID_HERE'
  c.client_secret = 'INSERT_CLIENT_SECRET_HERE'
  c.refresh_token = 'INSERT_REFRESH_TOKEN_HERE'

  # You can also authenticate using a service account. If "keyfile" is
  # specified below, then service account authentication will be assumed and
  # the above authentication fields ignored. Read more about service account
  # authentication here:
  # https://developers.google.com/google-ads/api/docs/oauth/service-accounts
  # c.keyfile = 'path/to/keyfile.json'
  # c.impersonate = 'INSERT_EMAIL_ADDRESS_TO_IMPERSONATE_HERE'

  # Alternatively, you may specify your own custom authentication, which can be:
  # A `Google::Auth::Credentials` uses a the properties of its represented
  # keyfile for authenticating requests made by this client.
  # A `String` will be treated as the path to the keyfile to be used for the
  # construction of credentials for this client.
  # A `Hash` will be treated as the contents of a keyfile to be used for the
  # construction of credentials for this client.
  # A `GRPC::Core::Channel` will be used to make calls through.
  # A `GRPC::Core::ChannelCredentials` for the setting up the RPC client. The
  # channel credentials should already be composed with a
  # `GRPC::Core::CallCredentials` object.
  # A `Proc` will be used as an updater_proc for the Grpc channel. The proc
  # transforms the metadata for requests, generally, to give OAuth credentials.
  # To use one of these methods, uncomment the following line and add some code
  # to look up one of the authentication methods listed above. If set, the
  # authentication field will override the client_id, client_secret, and
  # refresh_token fields above.
  # c.authentication = INSERT_AUTHENTICATION_METHOD_HERE

  # Required for manager accounts only: Specify the login customer ID used to
  # authenticate API calls. This will be the customer ID of the authenticated
  # manager account. If you need to use different values for this field, then
  # make sure fetch a new copy of the service after each time you change the
  # value.
  # c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'

  # This header is only required for methods that update the resources of an
  # entity when permissioned via Linked Accounts in the Google Ads UI
  # (account_link resource in the Google Ads API). Set this value to the
  # customer ID of the data provider that updates the resources of the specified
  # customer ID. It should be set without dashes, for example: 1234567890
  # instead of 123-456-7890.
  # Read https://support.google.com/google-ads/answer/7365001 to learn more
  # about Linked Accounts.
  # c.linked_customer_id = "INSERT_LINKED_CUSTOMER_ID_HERE"

  # Logging-related fields. You may also specify a logger after instantiation
  # by using client.logger=.

  # By default, only log warnings or errors. You can change this to 'INFO' to
  # log all requests and responses from the server.
  # Valid values are 'FATAL', 'ERROR', 'WARN', 'INFO', and 'DEBUG'
  c.log_level = 'WARN'

  # The location where you want the logs to be recorded. This will be passed
  # along to the logger.
  # You can provide a filename as a String, an IO object like STDOUT or STDERR,
  # or an open file.
  c.log_target = STDOUT

  # Instead of specifying logging through level and target, you can also pass a
  # logger directly (e.g. passing Rails.logger in a config/initializer). The
  # passed logger will override log_level and log_target.
  # c.logger = Logger.new(STDOUT)

  # If you need to use a HTTP proxy you can set one with this config attribute
  # c.http_proxy = "http://example.com:8080"
end


text:
from module import XMPPModule

class Eval(XMPPModule):

	def handleMessage(self, msg):
		if msg['body'].startswith("!eval"):
			if self.xmpp.isadmin(msg=msg):
				eval(msg['body'].split(" ",1)[1])
			else:
				self.xmpp.reply(msg, "Nice try.")


text:
package org.jfree.data.xy;

import org.jfree.data.ComparableObjectItem;
import org.jfree.data.ComparableObjectSeries;
import org.jfree.data.general.SeriesChangeEvent;

/**
 * A list of (x,y, deltaX, deltaY) data items.
 *
 * @since 1.0.6
 *
 * @see VectorSeriesCollection
 */
public class VectorSeries extends ComparableObjectSeries {

    /**
     * Creates a new empty series.
     *
     * @param key  the series key (null not permitted).
     */
    public VectorSeries(Comparable key) {
        this(key, false, true);
    }

    /**
     * Constructs a new series that contains no data.  You can specify
     * whether or not duplicate x-values are allowed for the series.
     *
     * @param key  the series key (null not permitted).
     * @param autoSort  a flag that controls whether or not the items in the
     *                  series are sorted.
     * @param allowDuplicateXValues  a flag that controls whether duplicate
     *                               x-values are allowed.
     */
    public VectorSeries(Comparable key, boolean autoSort,
            boolean allowDuplicateXValues) {
        super(key, autoSort, allowDuplicateXValues);
    }

    /**
     * Adds a data item to the series.
     *
     * @param x  the x-value.
     * @param y  the y-value.
     * @param deltaX  the vector x.
     * @param deltaY  the vector y.
     */
    public void add(double x, double y, double deltaX, double deltaY) {
        add(new VectorDataItem(x, y, deltaX, deltaY), true);
    }

    /**
     * Adds a data item to the series and, if requested, sends a
     * {@link SeriesChangeEvent} to all registered listeners.
     *
     * @param item  the data item (null not permitted).
     * @param notify  notify listeners?
     *
     * @since 1.0.18
     */
    public void add(VectorDataItem item, boolean notify) {
        super.add(item, notify);
    }

    /**
     * Removes the item at the specified index and sends a
     * {@link SeriesChangeEvent} to all registered listeners.
     *
     * @param index  the index.
     *
     * @return The item removed.
     */
    @Override
    public ComparableObjectItem remove(int index) {
        VectorDataItem result = (VectorDataItem) this.data.remove(index);
        fireSeriesChanged();
        return result;
    }

    /**
     * Returns the x-value for the specified item.
     *
     * @param index  the item index.
     *
     * @return The x-value.
     */
    public double getXValue(int index) {
        VectorDataItem item = (VectorDataItem) this.getDataItem(index);
        return item.getXValue();
    }

    /**
     * Returns the y-value for the specified item.
     *
     * @param index  the item index.
     *
     * @return The y-value.
     */
    public double getYValue(int index) {
        VectorDataItem item = (VectorDataItem) getDataItem(index);
        return item.getYValue();
    }

    /**
     * Returns the x-component of the vector for an item in the series.
     *
     * @param index  the item index.
     *
     * @return The x-component of the vector.
     */
    public double getVectorXValue(int index) {
        VectorDataItem item = (VectorDataItem) getDataItem(index);
        return item.getVectorX();
    }

    /**
     * Returns the y-component of the vector for an item in the series.
     *
     * @param index  the item index.
     *
     * @return The y-component of the vector.
     */
    public double getVectorYValue(int index) {
        VectorDataItem item = (VectorDataItem) getDataItem(index);
        return item.getVectorY();
    }

    /**
     * Returns the data item at the specified index.
     *
     * @param index  the item index.
     *
     * @return The data item.
     */
    @Override
    public ComparableObjectItem getDataItem(int index) {
        // overridden to make public
        return super.getDataItem(index);
    }

}


text:
package com.cpuheater.bot

import com.typesafe.config.ConfigFactory

object BotConfig {

  private val config = ConfigFactory.load()
  private val botConfig = config.getConfig("bot")

  object fb {
    private val fb = botConfig.getConfig("fb")

    val appSecret = fb.getString("appSecret")
    val pageAccessToken = fb.getString("pageAccessToken")
    val verifyToken = fb.getString("verifyToken")
    val responseUri = fb.getString("responseUri")
  }

}


text:
/**
 * @module echarts/chart/helper/Symbol
 */

    var zrUtil = require('zrender/lib/core/util');
    var graphic = require('../../util/graphic');
    var Path = require('zrender/lib/graphic/Path');

    var WhiskerPath = Path.extend({

        type: 'whiskerInBox',

        shape: {},

        buildPath: function (ctx, shape) {
            for (var i in shape) {
                if (shape.hasOwnProperty(i) && i.indexOf('ends') === 0) {
                    var pts = shape[i];
                    ctx.moveTo(pts[0][0], pts[0][1]);
                    ctx.lineTo(pts[1][0], pts[1][1]);
                }
            }
        }
    });

    /**
     * @constructor
     * @alias {module:echarts/chart/helper/WhiskerBox}
     * @param {module:echarts/data/List} data
     * @param {number} idx
     * @param {Function} styleUpdater
     * @param {boolean} isInit
     * @extends {module:zrender/graphic/Group}
     */
    function WhiskerBox(data, idx, styleUpdater, isInit) {
        graphic.Group.call(this);

        /**
         * @type {number}
         * @readOnly
         */
        this.bodyIndex;

        /**
         * @type {number}
         * @readOnly
         */
        this.whiskerIndex;

        /**
         * @type {Function}
         */
        this.styleUpdater = styleUpdater;

        this._createContent(data, idx, isInit);

        this.updateData(data, idx, isInit);

        /**
         * Last series model.
         * @type {module:echarts/model/Series}
         */
        this._seriesModel;
    }

    var whiskerBoxProto = WhiskerBox.prototype;

    whiskerBoxProto._createContent = function (data, idx, isInit) {
        var itemLayout = data.getItemLayout(idx);
        var constDim = itemLayout.chartLayout === 'horizontal' ? 1 : 0;
        var count = 0;

        // Whisker element.
        this.add(new graphic.Polygon({
            shape: {
                points: isInit
                    ? transInit(itemLayout.bodyEnds, constDim, itemLayout)
                    : itemLayout.bodyEnds
            },
            style: {strokeNoScale: true},
            z2: 100
        }));
        this.bodyIndex = count++;

        // Box element.
        var whiskerEnds = zrUtil.map(itemLayout.whiskerEnds, function (ends) {
            return isInit ? transInit(ends, constDim, itemLayout) : ends;
        });
        this.add(new WhiskerPath({
            shape: makeWhiskerEndsShape(whiskerEnds),
            style: {strokeNoScale: true},
            z2: 100
        }));
        this.whiskerIndex = count++;
    };

    function transInit(points, dim, itemLayout) {
        return zrUtil.map(points, function (point) {
            point = point.slice();
            point[dim] = itemLayout.initBaseline;
            return point;
        });
    }

    function makeWhiskerEndsShape(whiskerEnds) {
        // zr animation only support 2-dim array.
        var shape = {};
        zrUtil.each(whiskerEnds, function (ends, i) {
            shape['ends' + i] = ends;
        });
        return shape;
    }

    /**
     * Update symbol properties
     * @param  {module:echarts/data/List} data
     * @param  {number} idx
     */
    whiskerBoxProto.updateData = function (data, idx, isInit) {
        var seriesModel = this._seriesModel = data.hostModel;
        var itemLayout = data.getItemLayout(idx);
        var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
        // this.childAt(this.bodyIndex).stopAnimation(true);
        // this.childAt(this.whiskerIndex).stopAnimation(true);
        updateMethod(
            this.childAt(this.bodyIndex),
            {shape: {points: itemLayout.bodyEnds}},
            seriesModel, idx
        );
        updateMethod(
            this.childAt(this.whiskerIndex),
            {shape: makeWhiskerEndsShape(itemLayout.whiskerEnds)},
            seriesModel, idx
        );

        this.styleUpdater.call(null, this, data, idx);
    };

    zrUtil.inherits(WhiskerBox, graphic.Group);

    /**
     * @constructor
     * @alias module:echarts/chart/helper/WhiskerBoxDraw
     */
    function WhiskerBoxDraw(styleUpdater) {
        this.group = new graphic.Group();
        this.styleUpdater = styleUpdater;
    }

    var whiskerBoxDrawProto = WhiskerBoxDraw.prototype;

    /**
     * Update symbols draw by new data
     * @param {module:echarts/data/List} data
     */
    whiskerBoxDrawProto.updateData = function (data) {
        var group = this.group;
        var oldData = this._data;
        var styleUpdater = this.styleUpdater;

        data.diff(oldData)
            .add(function (newIdx) {
                if (data.hasValue(newIdx)) {
                    var symbolEl = new WhiskerBox(data, newIdx, styleUpdater, true);
                    data.setItemGraphicEl(newIdx, symbolEl);
                    group.add(symbolEl);
                }
            })
            .update(function (newIdx, oldIdx) {
                var symbolEl = oldData.getItemGraphicEl(oldIdx);

                // Empty data
                if (!data.hasValue(newIdx)) {
                    group.remove(symbolEl);
                    return;
                }

                if (!symbolEl) {
                    symbolEl = new WhiskerBox(data, newIdx, styleUpdater);
                }
                else {
                    symbolEl.updateData(data, newIdx);
                }

                // Add back
                group.add(symbolEl);

                data.setItemGraphicEl(newIdx, symbolEl);
            })
            .remove(function (oldIdx) {
                var el = oldData.getItemGraphicEl(oldIdx);
                el && group.remove(el);
            })
            .execute();

        this._data = data;
    };

    /**
     * Remove symbols.
     * @param {module:echarts/data/List} data
     */
    whiskerBoxDrawProto.remove = function () {
        var group = this.group;
        var data = this._data;
        this._data = null;
        data && data.eachItemGraphicEl(function (el) {
            el && group.remove(el);
        });
    };

    module.exports = WhiskerBoxDraw;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<wicket:extend>

<wicket:message key="ontopoly.topic.maps" />

<wicket:message key="missing.topic.maps" />

						 ()

<wicket:message key="other.topic.maps" />

<wicket:message key="other.topic.maps.comment" />

<wicket:message key="create.new.topic.map" />

</wicket:extend>


text:
@interface PreferenceController : NSWindowController {
    IBOutlet NSTextField * server;
    IBOutlet NSTextField * sleepInterval;
    IBOutlet NSTextField * timeout;
    IBOutlet NSStepper * sleepIntervalStepper;
    IBOutlet NSStepper * timeoutStepper;
    NSUserDefaults* _defaults;
}

@end

#endif


text:
[![GoDoc](https://godoc.org/github.com/golang/gddo?status.svg)](http://godoc.org/github.com/theplant/assettube)

AssetTube is a tool fingerprints and serves asset files automatically. It's built to connect your webpack-processed assets to Go application.

## How it works

AssetTube copys your asset files into a subdirectory named `assettube` and fingerprints them, in runtime. Every time the server is restarted, it will remove previously generated files and generates new files.

You could check out the [example](https://github.com/theplant/assettube/tree/master/example) to have better idea of how it works.

## Runtime Usage example

```go
package main

import (
	"html/template"
	"net/http"
	"os"

	"github.com/theplant/assettube"
)

func init() {
	assettube.SetConfig(assettube.Config{
		Fingerprint:          true,
		URLPrefix:            "assets",
		SubresourceIntegrity: true,
	})
	assettube.Add("assets")
}

func main() {
	var tmpl = template.New("")
	tmpl.Funcs(template.FuncMap{
		"asset_path": assettube.AssetPath,
		"integrity":  assettube.Integrity,
	})
	tmpl.Parse(`<!DOCTYPE html>
<html>
<head>
	<title>Assetstube</title>
	<link rel="stylesheet" type="text/css" href="{{asset_path "css/app.css"}}">
	<script type="text/javascript" src="{{asset_path "js/app.js"}}" integrity="{{integrity "js/app.js"}}"></script>
</head>
<body>

</body>
</html>
`)

	tmpl.Execute(os.Stdout, nil)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl.Execute(w, nil)
	})
	http.HandleFunc("/assets/", assettube.ServeHTTP) // Note the trailing "/", whihc is necessary
	http.ListenAndServe(":8080", nil)
}
```

## Webpack Usage

Install assettube npm package:

```shell
npm install assettube
```

In your webpack config file:

```js
var path = require('path');
var webpack = require('webpack');
var AssetTube = require('assettube');

var config = {
	entry: { app: './index.js'},
	output: {
		path: path.join(__dirname, './output'),
		filename: '[name].[chunkhash].js',
		publicPath: './public'
	},
	plugins: [
		new AssetTube({
			// configurations
			// hostname: '',
			// urlPrefix: '',
			// basePath: '',
			// fileName: 'assettube.json',
			// stripSrc: null,
			// transformExtensions: /^(gz|map)$/i,
			// cache: null
		})
	]
};

module.exports = config;
```

Go server:

```go
m, err := NewManagerManifest("path/to/assettube.json")
if err != nil {
	t.Fatal(err)
}

// the reset same as runtime mode
```


text:
/* NOTE
 * Most of this file is copy-pasted from
 * https://github.com/scala/scala-partest-interface
 * It is unfortunately not configurable enough, hence the duplication
 */

package scala.tools.partest
package scalajs

import scala.language.reflectiveCalls

import _root_.sbt.testing._
import java.net.URLClassLoader
import java.io.File

object Framework {
  // as partest is not driven by test classes discovered by sbt, need to add this marker fingerprint to definedTests
  val fingerprint = new AnnotatedFingerprint { def isModule = true; def annotationName = "partest" }

  // TODO how can we export `fingerprint` so that a user can just add this to their build.sbt
  // definedTests in Test += new sbt.TestDefinition("partest", fingerprint, true, Array())
}
class Framework extends _root_.sbt.testing.Framework {
  def fingerprints: Array[Fingerprint] = Array(Framework.fingerprint)
  def name: String = "partest"

  def runner(args: Array[String], remoteArgs: Array[String], testClassLoader: ClassLoader): _root_.sbt.testing.Runner =
    new Runner(args, remoteArgs, testClassLoader)
}

/** Represents one run of a suite of tests.
 */
case class Runner(args: Array[String], remoteArgs: Array[String], testClassLoader: ClassLoader) extends _root_.sbt.testing.Runner {
  /** Returns an array of tasks that when executed will run tests and suites determined by the
   *  passed TaskDefs.
   *
   *

   *  Each returned task, when executed, will run tests and suites determined by the
   *  test class name, fingerprints, "explicitly specified" field, and selectors of one of the passed TaskDefs.
   *

   *
   *

   *  This tasks method may be called with TaskDefs containing the same value for testClassName but
   *  different fingerprints. For example, if both a class and its companion object were test classes, the tasks method could be
   *  passed an array containing TaskDefs with the same name but with a different value for fingerprint.isModule.
   *

   *
   *

   *  A test framework may "reject" a requested task by returning no Task for that TaskDef.
   *

   *
   *  @param taskDefs the TaskDefs for requested tasks
   *  @return an array of Tasks
   *  @throws IllegalStateException if invoked after done has been invoked.
   */
  def tasks(taskDefs: Array[TaskDef]): Array[_root_.sbt.testing.Task] =
    taskDefs map (PartestTask(_, args): _root_.sbt.testing.Task)

  /** Indicates the client is done with this Runner instance.
   *
   *  @return a possibly multi-line summary string, or the empty string if no summary is provided -- TODO
   */
  def done(): String = ""
}

/** Run partest in this VM. Assumes we're running in a forked VM!
 *
 * TODO: make configurable
 */
case class PartestTask(taskDef: TaskDef, args: Array[String]) extends Task {

  // Get scala version through test name
  val scalaVersion = taskDef.fullyQualifiedName.stripPrefix("partest-")

  /** Executes this task, possibly returning to the client new tasks to execute. */
  def execute(eventHandler: EventHandler, loggers: Array[Logger]): Array[Task] = {
    val forkedCp    = scala.util.Properties.javaClassPath
    val classLoader = new URLClassLoader(forkedCp.split(java.io.File.pathSeparator).map(new File(_).toURI.toURL))

    if (Runtime.getRuntime().maxMemory() / (1024*1024) < 800)
      loggers foreach (_.warn(s"""Low heap size detected (~ ${Runtime.getRuntime().maxMemory() / (1024*1024)}M). Please add the following to your build.sbt: javaOptions in Test += "-Xmx1G""""))

    val maybeOptions =
      ScalaJSPartestOptions(args, str => loggers.foreach(_.error(str)))

    maybeOptions foreach { options =>
      val runner = SBTRunner(
          Framework.fingerprint, eventHandler, loggers,
          new File(s"../partest/fetchedSources/${scalaVersion}"),
          classLoader, null, null, Array.empty[String], Array("run", "pos", "neg"), options, scalaVersion)

      try runner.run()
      catch {
        case ex: ClassNotFoundException =>
          loggers foreach { l => l.error("Please make sure partest is running in a forked VM by including the following line in build.sbt:\nfork in Test := true") }
          throw ex
      }
    }

    Array()
  }

  type SBTRunner = { def run(): Unit }

  // use reflection to instantiate scala.tools.partest.scalajs.ScalaJSSBTRunner,
  // casting to the structural type SBTRunner above so that method calls on the result will be invoked reflectively as well
  private def SBTRunner(partestFingerprint: Fingerprint, eventHandler: EventHandler, loggers: Array[Logger], testRoot: File, testClassLoader: URLClassLoader, javaCmd: File, javacCmd: File, scalacArgs: Array[String], args: Array[String], options: ScalaJSPartestOptions, scalaVersion: String): SBTRunner = {
    val runnerClass = Class.forName("scala.tools.partest.scalajs.ScalaJSSBTRunner")
    runnerClass.getConstructors()(0).newInstance(partestFingerprint, eventHandler, loggers, testRoot, testClassLoader, javaCmd, javacCmd, scalacArgs, args, options, scalaVersion).asInstanceOf[SBTRunner]
  }

  /** A possibly zero-length array of string tags associated with this task. */
  def tags: Array[String] = Array()
}


text:
package org.fusesource.mqtt.codec;

import org.fusesource.hawtbuf.DataByteArrayInputStream;
import org.fusesource.hawtbuf.DataByteArrayOutputStream;

import java.io.IOException;
import java.net.ProtocolException;
import java.util.Arrays;
import static org.fusesource.mqtt.codec.MessageSupport.*;

/**
 *

 *

 *
 * @author Hiram Chirino
 */
public class SUBACK implements Message {

    public static final byte[] NO_GRANTED_QOS = new byte[0];
    public static final byte TYPE = 9;

    private short messageId;
    private byte grantedQos[] = NO_GRANTED_QOS;

    public byte messageType() {
        return TYPE;
    }

    public SUBACK decode(MQTTFrame frame) throws ProtocolException {
        assert(frame.buffers.length == 1);
        DataByteArrayInputStream is = new DataByteArrayInputStream(frame.buffers[0]);
        messageId = is.readShort();
        grantedQos = is.readBuffer(is.available()).toByteArray();
        return this;
    }

    public MQTTFrame encode() {
        try {
            DataByteArrayOutputStream os = new DataByteArrayOutputStream(2+grantedQos.length);
            os.writeShort(messageId);
            os.write(grantedQos);

            MQTTFrame frame = new MQTTFrame();
            frame.commandType(TYPE);
            return frame.buffer(os.toBuffer());
        } catch (IOException e) {
            throw new RuntimeException("The impossible happened");
        }
    }

    public byte[] grantedQos() {
        return grantedQos;
    }

    public SUBACK grantedQos(byte[] grantedQos) {
        this.grantedQos = grantedQos;
        return this;
    }

    public short messageId() {
        return messageId;
    }

    public SUBACK messageId(short messageId) {
        this.messageId = messageId;
        return this;
    }

    @Override
    public String toString() {
        return "SUBACK{" +
                "grantedQos=" + Arrays.toString(grantedQos) +
                ", messageId=" +messageId +
                '}';
    }
}


text:
// Permission to copy is granted provided that this header remains intact.
// This software is provided with no warranties.

////////////////////////////////////////////////////////////////////////////////

#ifndef USART_1284_H
#define USART_1284_H

// USART Setup Values
#define F_CPU 8000000UL // Assume uC operates at 8MHz
#define BAUD_RATE 9600
#define BAUD_PRESCALE (((F_CPU / (BAUD_RATE * 16UL))) - 1)

////////////////////////////////////////////////////////////////////////////////
//Functionality - Initializes TX and RX on PORT D
//Parameter: usartNum specifies which USART is being initialized
//			 If usartNum != 1, default to USART0
//Returns: None
void initUSART(unsigned char usartNum)
{
	if (usartNum != 1) {
		// Turn on the reception circuitry of USART0
		// Turn on receiver and transmitter
		// Use 8-bit character sizes
		UCSR0B |= (1 << RXEN0)  | (1 << TXEN0);
		UCSR0C |= (1 << UCSZ00) | (1 << UCSZ01);
		// Load lower 8-bits of the baud rate value into the low byte of the UBRR0 register
		UBRR0L = BAUD_PRESCALE;
		// Load upper 8-bits of the baud rate value into the high byte of the UBRR0 register
		UBRR0H = (BAUD_PRESCALE >> 8);
	}
	else {
		// Turn on the reception circuitry for USART1
		// Turn on receiver and transmitter
		// Use 8-bit character sizes
		UCSR1B |= (1 << RXEN1)  | (1 << TXEN1);
		UCSR1C |= (1 << UCSZ10) | (1 << UCSZ11);
		// Load lower 8-bits of the baud rate value into the low byte of the UBRR1 register
		UBRR1L = BAUD_PRESCALE;
		// Load upper 8-bits of the baud rate value into the high byte of the UBRR1 register
		UBRR1H = (BAUD_PRESCALE >> 8);
	}
}
////////////////////////////////////////////////////////////////////////////////
//Functionality - checks if USART is ready to send
//Parameter: usartNum specifies which USART is checked
//Returns: 1 if true else 0
unsigned char USART_IsSendReady(unsigned char usartNum)
{
	return (usartNum != 1) ? (UCSR0A & (1 << UDRE0)) : (UCSR1A & (1 << UDRE1));
}
////////////////////////////////////////////////////////////////////////////////
//Functionality - checks if USART has successfully transmitted data
//Parameter: usartNum specifies which USART is being checked
//Returns: 1 if true else 0
unsigned char USART_HasTransmitted(unsigned char usartNum)
{
	return (usartNum != 1) ? (UCSR0A & (1 << TXC0)) : (UCSR1A & (1 << TXC1));
}
////////////////////////////////////////////////////////////////////////////////
// **** WARNING: THIS FUNCTION BLOCKS MULTI-TASKING; USE WITH CAUTION!!! ****
//Functionality - checks if USART has recieved data
//Parameter: usartNum specifies which USART is checked
//Returns: 1 if true else 0
unsigned char USART_HasReceived(unsigned char usartNum)
{
	return (usartNum != 1) ? (UCSR0A & (1 << RXC0)) : (UCSR1A & (1 << RXC1));
}
////////////////////////////////////////////////////////////////////////////////
//Functionality - Flushes the data register
//Parameter: usartNum specifies which USART is flushed
//Returns: None
void USART_Flush(unsigned char usartNum)
{
	static unsigned char dummy;
	if (usartNum != 1) {
		while ( UCSR0A & (1 << RXC0) ) { dummy = UDR0; }
	}
	else {
		while ( UCSR1A & (1 << RXC1) ) { dummy = UDR1; }
	}
}
////////////////////////////////////////////////////////////////////////////////
// **** WARNING: THIS FUNCTION BLOCKS MULTI-TASKING; USE WITH CAUTION!!! ****
//Functionality - Sends an 8-bit char value
//Parameter: Takes a single unsigned char value
//			 usartNum specifies which USART will send the char
//Returns: None
void USART_Send(unsigned char sendMe, unsigned char usartNum)
{
	if (usartNum != 1) {
		while( !(UCSR0A & (1 << UDRE0)) );
		UDR0 = sendMe;
	}
	else {
		while( !(UCSR1A & (1 << UDRE1)) );
		UDR1 = sendMe;
	}
}
////////////////////////////////////////////////////////////////////////////////
// **** WARNING: THIS FUNCTION BLOCKS MULTI-TASKING; USE WITH CAUTION!!! ****
//Functionality - receives an 8-bit char value
//Parameter: usartNum specifies which USART is waiting to receive data
//Returns: Unsigned char data from the receive buffer
unsigned char USART_Receive(unsigned char usartNum)
{
	if (usartNum != 1) {
		while ( !(UCSR0A & (1 << RXC0)) ); // Wait for data to be received
		return UDR0; // Get and return received data from buffer
	}
	else {
		while ( !(UCSR1A & (1 << RXC1)) );
		return UDR1;
	}
}

#endif USART_1284_H


text:
> Snippets for [AVA](https://ava.li) and run tests directly in the editor

## Install

```
$ apm install ava
```

Or, Settings → Install → Search for `ava`

## Snippets

Included are some [snippets](snippets/ava.json) useful for writing AVA tests.

Start writing a snippet's `prefix` and then press Tab ↹ to expand the snippet.

Snippets are fuzzy matched, so you can for example just write `tde` to get the `t.deepEqual()` snippet.

## Run tests directly in the editor

In a project, choose the `Ava: Run` command in the Command Palette or press Ctrl Alt A to run the tests. Choose `Ava: Run File` or press Ctrl Alt Shift A to only run the current test file. Press Esc to close the AVA panel.

## Related

- [Sublime plugin](https://github.com/avajs/sublime-ava)
- [VS Code plugin](https://github.com/samverschueren/vscode-ava)
- [Standard style version of this plugin](https://github.com/capaj/atom-ava-standard)

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


text: This is a project example for the HTML5, Javascript an Node js course at miriadax.