text:
package opennlp.uima.chunker;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import opennlp.maxent.GIS;
import opennlp.tools.chunker.ChunkSample;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.util.ObjectStreamUtils;
import opennlp.uima.util.CasConsumerUtil;
import opennlp.uima.util.ContainingConstraint;
import opennlp.uima.util.OpennlpUtil;
import opennlp.uima.util.UimaUtil;

import org.apache.uima.UimaContext;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.cas.Feature;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.TypeSystem;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.collection.CasConsumer_ImplBase;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceProcessException;
import org.apache.uima.util.Level;
import org.apache.uima.util.Logger;
import org.apache.uima.util.ProcessTrace;

/**
 * OpenNLP Chunker trainer.
 *

 * Mandatory parameters
 *

 *
Type	 Name	 Description

 *
String	 opennlp.uima.ModelName	 The name of the model file

 *
String	 opennlp.uima.SentenceType	 The full name of the sentence type

 *
String	 opennlp.uima.TokenType	 The full name of the token type

 *
String	 opennlp.uima.POSFeature

 *
String	 opennlp.uima.ChunkType

 *
String	 opennlp.uima.ChunkTagFeature

 *

 */
public class ChunkerTrainer extends CasConsumer_ImplBase {

  private List<ChunkSample> mChunkSamples = new ArrayList<ChunkSample>();

  private UimaContext mContext;

  private String mModelName;

  private Type mSentenceType;

  private Type mTokenType;

  private Feature mPOSFeature;

  private Type mChunkType;

  private Feature mChunkTagFeature;

  private Logger mLogger;

  private String language;

  /**
   * Initializes the current instance.
   */
  public void initialize() throws ResourceInitializationException {

    super.initialize();

    mContext = getUimaContext();

    mLogger = mContext.getLogger();

    if (mLogger.isLoggable(Level.INFO)) {
      mLogger.log(Level.INFO, "Initializing the OpenNLP Chunker Trainer.");
    }

    mModelName = CasConsumerUtil.getRequiredStringParameter(mContext,
        UimaUtil.MODEL_PARAMETER);

    language = CasConsumerUtil.getRequiredStringParameter(mContext,
        UimaUtil.LANGUAGE_PARAMETER);
  }

  /**
   * Initialize the current instance with the given type system.
   */
  public void typeSystemInit(TypeSystem typeSystem)
        throws ResourceInitializationException {
    String sentenceTypeName =
        CasConsumerUtil.getRequiredStringParameter(mContext,
        UimaUtil.SENTENCE_TYPE_PARAMETER);

    mSentenceType = CasConsumerUtil.getType(typeSystem, sentenceTypeName);

    String chunkTypeName = CasConsumerUtil.getRequiredStringParameter(mContext,
        Chunker.CHUNK_TYPE_PARAMETER);

    mChunkType = CasConsumerUtil.getType(typeSystem, chunkTypeName);

    String chunkTagFeature = CasConsumerUtil.getRequiredStringParameter(
        mContext, Chunker.CHUNK_TAG_FEATURE_PARAMETER);

    mChunkTagFeature = mChunkType.getFeatureByBaseName(chunkTagFeature);

    CasConsumerUtil.checkFeatureType(mChunkTagFeature, CAS.TYPE_NAME_STRING);

    String tokenTypeName = CasConsumerUtil.getRequiredStringParameter(mContext,
        UimaUtil.TOKEN_TYPE_PARAMETER);

    mTokenType = CasConsumerUtil.getType(typeSystem, tokenTypeName);

    String posFeatureName = CasConsumerUtil.getRequiredStringParameter(mContext,
        UimaUtil.POS_FEATURE_PARAMETER);

    mPOSFeature = mTokenType.getFeatureByBaseName(posFeatureName);

    CasConsumerUtil.checkFeatureType(mPOSFeature, CAS.TYPE_NAME_STRING);
  }

  /**
   * Process the given CAS object.
   */
  public void processCas(CAS cas) {

    FSIndex<AnnotationFS> sentenceIndex = cas.getAnnotationIndex(mSentenceType);

    for (AnnotationFS sentenceAnnotation : sentenceIndex) {
      processSentence(cas, sentenceAnnotation);
    }
  }

  private void processSentence(CAS tcas, AnnotationFS sentence) {
    FSIndex<AnnotationFS> chunkIndex = tcas.getAnnotationIndex(mChunkType);

    ContainingConstraint containingConstraint =
      new ContainingConstraint(sentence);

    Iterator<AnnotationFS> chunkIterator = tcas.createFilteredIterator(
        chunkIndex.iterator(), containingConstraint);

    while (chunkIterator.hasNext()) {
      AnnotationFS chunkAnnotation = (AnnotationFS) chunkIterator.next();
      processChunk(tcas, (chunkAnnotation));
    }
  }

  private void processChunk(CAS tcas, AnnotationFS chunk) {

    String chunkTag = chunk.getFeatureValueAsString(mChunkTagFeature);

    FSIndex<AnnotationFS> tokenIndex = tcas.getAnnotationIndex(mTokenType);

    ContainingConstraint containingConstraint =
      new ContainingConstraint(chunk);

    Iterator<AnnotationFS> tokenIterator = tcas.createFilteredIterator(tokenIndex.iterator(),
        containingConstraint);

    List<String> tokens = new ArrayList<String>();
    List<String> tags = new ArrayList<String>();;
    List<String> chunkTags = new ArrayList<String>();;

    while (tokenIterator.hasNext()) {
      AnnotationFS tokenAnnotation = tokenIterator.next();

      tokens.add(tokenAnnotation.getCoveredText().trim());
      tags.add(tokenAnnotation.getFeatureValueAsString(mPOSFeature));
      chunkTags.add(chunkTag);
    }

    mChunkSamples.add(new ChunkSample(tokens, tags, chunkTags));
  }

  /**
   * Called if the processing is finished, this method
   * does the training.
   */
  public void collectionProcessComplete(ProcessTrace trace)
      throws ResourceProcessException, IOException {
    GIS.PRINT_MESSAGES = false;

    ChunkerModel chunkerModel = ChunkerME.train(language, ObjectStreamUtils.createObjectStream(mChunkSamples), 100, 5);

    // dereference to allow garbage collection
    mChunkSamples  = null;

    File modelFile = new File(getUimaContextAdmin().getResourceManager()
        .getDataPath() + File.separatorChar + mModelName);

    OpennlpUtil.serialize(chunkerModel, modelFile);
  }

  /**
   * The trainer is not stateless.
   */
  public boolean isStateless() {
    return false;
  }

  /**
   * Releases allocated resources.
   */
  public void destroy() {
    mChunkSamples = null;
  }
}


text:
import sys

from fabric.api import *
from fabric.contrib import *

import setup, {%= name %}, deploy

@task(default=True)
def list():
  fab.list_tasks()

@task
def dev():
  fab.read_yaml_config('dev')

@task
def prod(execute = ''):
  if execute != 'real':
    print 'You must write prod:real to actually execute this task'
    sys.exit(1)
  else:
    fab.read_yaml_config('prod')

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
 * CloudConvert API Example Class
 * 2013 by Lunaweb Ltd.
 * Feel free to use, modify or publish it.
 */
class CloudConvert {

    private $apikey;
    private $url;
    private $data;
    private $options = array();

    /*
     * creates new Process ID.
     * see: https://cloudconvert.org/page/api#start
     *
     */

    public static function createProcess($inputformat, $outputformat, $apikey = null) {

        $instance = new self();

        $instance -> apikey = $apikey;

        $data = $instance -> req('https://api.cloudconvert.org/process', array(
            'inputformat' => $inputformat,
            'outputformat' => $outputformat,
            'apikey' => $apikey
        ));

        if (strpos($data -> url, 'http') === false)
            $data -> url = "https:" . $data -> url;

        $instance -> url = $data -> url;

        return $instance;

    }

    /*
     * uses existing Process by given Process URL
     */
    public static function useProcess($url) {
        $instance = new self();
        if (strpos($url, 'http') === false)
            $url = "https:" . $url;
        $instance -> url = $url;
        return $instance;
    }

    /*
     * Set conversion option.
     * examples:
     * $converter -> setOption('eMail', '1');
     * $converter -> setOption('options[audio_bitrate]', '128');
     *
     */

    public function setOption($name, $val) {
        $this -> options[$name] = $val;
    }

    /*
     * Uploads the input file (server side)
     */
    public function upload($filepath, $outputformat) {
        $this -> req($this -> url, array_merge(array(
            'input' => 'upload',
            'format' => $outputformat,
            'file' => (class_exists('CURLFile') ? new CURLFile($filepath) : '@' . $filepath) // CURLFile is available PHP >= 5.5.0
        ), $this -> options));
    }

    /*
     * Let CloudConvert download the input file by a given URL and filename
     */
    public function uploadByURL($url, $filename, $outputformat) {
        $this -> req($this -> url, array_merge(array(
            'input' => 'download',
            'format' => $outputformat,
            'filename' => $filename,
            'link' => $url,
        ), $this -> options));

    }
    public function uploadByFTP($ftpRequest) {
    	$post_json = '{
    input: {
        ftp : {
            host: "ftp.engulfing.com",
            user: "dpr@engulfing.com",
            password: "orkpower78"
        }
    },
    file: "zkb_warrant_call.pdf",
    filename: "/zkb_warrant_call.pdf",
    outputformat: "html",
    output: {
        ftp : {
            host: "ftp.engulfing.com",
            user: "dpr@engulfing.com",
            password: "orkpower78"
        }
    }
}';
    	$this -> req($this -> url, $post_json);
    }

    /*
     * returns Process URL
     */
    public function getURL() {
        return $this -> url;
    }

    /*
     * Checks the current status of the process
     */
    public function status($action = null) {
        if (empty($this -> url))
            throw new Exception("No process URL found! (Conversion not started)");
        $this -> data = $this -> req($this -> url . ($action ? '/' . $action : ''));
        return $this -> data;
    }

    public function cancel() {
        return $this -> status('cancel');
    }

    public function delete() {
        return $this -> status('delete');
    }

    /*
     * Blocks until the conversion is finished
     */
    public function waitForConversion($timeout = 120) {
        $time = 0;
        /*
         * Check the status every second, up to timeout
         */
        while ($time <= $timeout) {
            sleep(1);
            $time++;
            $data = $this -> status();
            if ($data -> step == 'error') {
                throw new Exception($data -> message);
                return false;
            } elseif ($data -> step == 'finished' && isset($data -> output) && isset($data -> output -> url)) {
                return true;
            }
        }
        throw new Exception('Timeout');
        return false;
    }

    /*
     * Download output file to local target
     */
    public function download($target) {
        if (empty($this -> data -> output -> url))
            throw new Exception("No download URL found! (Conversion not finished or failed)");
        if (strpos($this -> data -> output -> url, 'http') === false)
            $this -> data -> output -> url = "https:" . $this -> data -> output -> url;
        $fp = fopen($target, 'w+');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this -> data -> output -> url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        if (!curl_exec($ch)) {
            throw new Exception(curl_error($ch));
        }
        curl_close($ch);
        fclose($fp);
    }

    /*
     * Return output stream to variable
     */
    public function downloadStream() {
        if (empty($this -> data -> output -> url))
            throw new Exception("No download URL found! (Conversion not finished or failed)");
        if (strpos($this -> data -> output -> url, 'http') === false)
            $this -> data -> output -> url = "https:" . $this -> data -> output -> url;

	$ch = curl_init();
		curl_setopt_array($ch, array(
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HEADER  => false,
		CURLOPT_HTTPGET => true,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_URL => $this -> data -> output -> url
	));

	$stream = curl_exec($ch);
	curl_close($ch);

	return $stream;
    }

    private function req($url, $post = null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        /*
         * If you have SSL cert errors, try to disable SSL verifyer.
         */
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        if (!empty($post)) {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }

        $return = curl_exec($ch);

        if ($return === FALSE) {
            throw new Exception(curl_error($ch));
        } else {
            $json = json_decode($return);
            if (isset($json -> error))
                throw new Exception($json -> error);
            return $json;
        }
        curl_close($ch);

    }

    function convertPDFtoHTML($url, $processing_file, $format, $location) {
    	$apikey = "3eBlFsNNQqunQAGT3lDRYOSkP2P4KUXTNrGQXn_C8hJEEe0L9Di-FVkNl8c5cpLrwUszNT6qZAkfQnzUITCQPA";

    	$process = $this->createProcess("pdf", "html", $apikey);
    	$process-> uploadByURL($url, $processing_file, "html" );

    	if ($process-> waitForConversion()) {
    		$process -> download(str_replace(".pdf", ".html", $location . $processing_file));
    		$process -> delete();
    	} else {
    		echo "Something went wrong :-(";
    	}

   		$files = file(str_replace(".pdf", ".html", $location . $processing_file));

   		$new_file = array();
   		foreach ($files as $line) {
   			if (substr($line, 0, 10) == "@font-face") {
   			} else {
   				$new_file[] = $line; // push line new array
   			}
   		}

   		file_put_contents(str_replace(".pdf", ".html", $location . $processing_file), $new_file);

    	$content = file_get_contents(str_replace(".pdf", ".html", $location . $processing_file));
    	$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");

    	return $content;
    }
}
?>


text:
package de.nedelosk.modularmachines.api.property;

import com.google.gson.JsonArray;

import de.nedelosk.modularmachines.api.recipes.IRecipe;
import de.nedelosk.modularmachines.api.recipes.RecipeItem;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;

public class PropertyRecipeItems extends PropertyBase<RecipeItem[], NBTTagCompound, IRecipe> implements IPropertyJson<RecipeItem[], NBTTagCompound, IRecipe, JsonArray> {

	public PropertyRecipeItems(String name) {
		super(name, RecipeItem[].class, new RecipeItem[1]);
	}

	@Override
	public JsonArray writeToJson(RecipeItem[] objects) {
		return JsonUtils.writeRecipeItem(objects);
	}

	@Override
	public RecipeItem[] readFromJson(JsonArray object) {
		return JsonUtils.parseRecipeItem(object);
	}

	@Override
	public NBTTagCompound writeToNBT(IRecipe state, RecipeItem[] value) {
		NBTTagCompound nbtTag = new NBTTagCompound();
		NBTTagList tagList = new NBTTagList();
		int maxIndex = 0;
		for(RecipeItem item : value){
			if(item != null){
				if(item.index > maxIndex){
					maxIndex=item.index;
				}
				NBTTagCompound nbtTagItem = new NBTTagCompound();
				item.writeToNBT(nbtTagItem);
				tagList.appendTag(nbtTagItem);
			}
		}
		nbtTag.setTag("Items", tagList);
		nbtTag.setInteger("MaxIndex", maxIndex);
		return nbtTag;
	}

	@Override
	public RecipeItem[] readFromNBT(NBTTagCompound nbt, IRecipe state) {
		NBTTagList tagList = nbt.getTagList("Items", 10);
		RecipeItem[] items = new RecipeItem[nbt.getInteger("MaxIndex") + 1];
		for(int i = 0;i < tagList.tagCount();i++){
			NBTTagCompound nbtTag = tagList.getCompoundTagAt(i);
			RecipeItem item = RecipeItem.loadFromNBT(nbtTag);
			items[item.index] = item;
		}
		return items;
	}
}


text:
from PyQt4 import QtCore, QtGui

from addresses import addBMIfNotPresent
from queues import (UISignalQueue, addressGeneratorQueue,
                    apiAddressGeneratorReturnQueue)
from tr import _translate

import widgets
from addressvalidator import AddressValidator, PassPhraseValidator
from retranslateui import RetranslateMixin
from utils import str_chan

class NewChanDialog(QtGui.QDialog, RetranslateMixin):
    def __init__(self, parent=None):
        super(NewChanDialog, self).__init__(parent)
        widgets.load('newchandialog.ui', self)
        self.parent = parent
        self.chanAddress.setValidator(AddressValidator(self.chanAddress, self.chanPassPhrase, self.validatorFeedback, self.buttonBox, False))
        self.chanPassPhrase.setValidator(PassPhraseValidator(self.chanPassPhrase, self.chanAddress, self.validatorFeedback, self.buttonBox, False))
        QtCore.QObject.connect(self.chanAddress, QtCore.SIGNAL('textEdited()'), self.chanAddress.validator(), QtCore.SLOT('checkData(self)'))
        QtCore.QObject.connect(self.chanPassPhrase, QtCore.SIGNAL('textEdited()'), self.chanPassPhrase.validator(), QtCore.SLOT('checkData(self)'))

        self.timer = QtCore.QTimer()
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.delayedUpdateStatus)
        self.timer.start(500) # milliseconds
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.show()

    def delayedUpdateStatus(self):
        self.chanPassPhrase.validator().checkQueue()

    def accept(self):
        self.timer.stop()
        self.hide()
        apiAddressGeneratorReturnQueue.queue.clear()
        if self.chanAddress.text().toUtf8() == "":
            addressGeneratorQueue.put(('createChan', 4, 1, str_chan + ' ' + str(self.chanPassPhrase.text().toUtf8()), self.chanPassPhrase.text().toUtf8(), True))
        else:
            addressGeneratorQueue.put(('joinChan', addBMIfNotPresent(self.chanAddress.text().toUtf8()), str_chan + ' ' + str(self.chanPassPhrase.text().toUtf8()), self.chanPassPhrase.text().toUtf8(), True))
        addressGeneratorReturnValue = apiAddressGeneratorReturnQueue.get(True)
        if len(addressGeneratorReturnValue) > 0 and addressGeneratorReturnValue[0] != 'chan name does not match address':
            UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Successfully created / joined chan %1").arg(str(self.chanPassPhrase.text().toUtf8()))))
            self.parent.ui.tabWidget.setCurrentIndex(3)
            self.done(QtGui.QDialog.Accepted)
        else:
            UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Chan creation / joining failed")))
            self.done(QtGui.QDialog.Rejected)

    def reject(self):
        self.timer.stop()
        self.hide()
        UISignalQueue.put(('updateStatusBar', _translate("newchandialog", "Chan creation / joining cancelled")))
        self.done(QtGui.QDialog.Rejected)


text:
@interface AKTremoloAudioUnit : AKAudioUnit
@property (nonatomic) float frequency;
@property (nonatomic) float depth;

- (void)setupWaveform:(int)size;
- (void)setWaveformValue:(float)value atIndex:(UInt32)index;
@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SitecoreCognitiveServices.Foundation.MSSDK.Models.Vision.ContentModerator
{
    public class GetImagesResponse
    {
        public int ContentSource { get; set; }
        public List<int> ContentIds { get; set; }
        public ResponseStatus Status { get; set; }
        public string TrackingId { get; set; }
    }
}


text:
<?php
namespace FormKit\Element;
use FormKit\Element;

class Span extends Element
{
    public $tagName = 'span';
    public $closeEmpty = true;

    public function __construct($attributes = array() ) {
        parent::__construct($this->tagName, $attributes);
    }
}


text:
package com.example.coolweather2.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.coolweather2.gson.Weather;
import com.example.coolweather2.util.HttpUtil;
import com.example.coolweather2.util.Utility;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/12/17.
 */
public class AutoUpdateService extends Service {

    private static final String TAG = "AutoUpdateService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: 我被执行了!!!");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: 我也执行了!!!");
        updateWeather();
        updateBingPic();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int time = 8 * 60 * 60 * 1000; // 8小时的毫秒数
        // SystemClock.elapsedRealtime为系统开机到现在所走的毫秒数
        // System.currentTimeMillis为1970/1/1零点到现在所走的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + time;
        Intent i = new Intent(this,AutoUpdateService.class);
        PendingIntent pi = PendingIntent.getService(this,0,i,0);
        manager.cancel(pi); // 这句话有什么用?
        // 之前是用的AlarmManager.ELAPSED_REALTIME导致不能后台更新数据
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新天气信息
     */
    private void updateWeather() {
        Log.d( TAG,"AutoUpdateService中的updateWeather执行了!!!");
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = sp.getString("weather_response",null);
        if(weatherString != null){
            Weather weather = Utility.handleWeatherResponse(weatherString);
            String weatherId = weather.basic.weatherId;

            String weatherUrl = "http://guolin.tech/api/weather?cityid="
                    + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
            HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseText = response.body().string();
                    Weather weather = Utility.handleWeatherResponse(responseText);
                    if( weather != null && "ok".equals(weather.status) ){
                        SharedPreferences.Editor editor = PreferenceManager
                                .getDefaultSharedPreferences(AutoUpdateService.this).edit();
                        editor.putString("weather_response",responseText);
                        editor.apply();
                    }
                }
                @Override
                public void onFailure(Call call, IOException e) {

                }
            });
        }
    }

    /**
     * 更新必应每日一图
     */
    private void updateBingPic() {
        Log.d( TAG,"AutoUpdateService中的updateBingPic执行了!!!");
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String imgUrl = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager
                        .getDefaultSharedPreferences(AutoUpdateService.this)
                        .edit();
                editor.putString("bing_img_url",imgUrl);
                editor.apply();
            }
            @Override
            public void onFailure(Call call, IOException e) {

            }
        });
    }

}


text:
'use strict';
var path        = require('path');
var _           = require('lodash');
var gulp        = require('gulp-help')(require('gulp'));
var $           = require('gulp-load-plugins')({lazy: true});
var runSequence = require('run-sequence');
var args        = require('yargs').argv;
var notifier    = require('node-notifier');
var del         = require('del');

process.setMaxListeners(0);       // Disable max listeners for gulp

var isVerbose = args.verbose;     // Enable extra verbose logging with --verbose
var isProduction = args.prod;     // Run extra steps with production flag --prod
var isWatching = false;           // Enable/disable tasks when running watch

/************************************************************************
 * Functions/Utilities
 */

// Desktop notifications of errors
function onError(err) {
    // jshint validthis: true
    notifier.notify({
        title: err.plugin + ' Error',
        message: err.message
    });
    $.util.log(err.toString());
    $.util.beep();
    if (isWatching) {
        this.emit('end');
    } else {
        process.exit(1);
    }
}

function verbosePrintFiles(taskName) {
    return $.if(isVerbose, $.print(function(filepath) {
        return taskName + ': ' + filepath;
    }))
}

/************************************************************************
 * Clean temporary folders and files
 */

gulp.task('clean-coverage', false, function(cb) {
    del(['coverage'], cb);
});

gulp.task('clean', 'Remove all temporary files', ['clean-coverage']);

/************************************************************************
 * JavaScript tasks
 */

gulp.task('lint', 'Lints all JavaScript files', function() {
    return gulp.src('src/**/*.js')
        .pipe($.plumber({errorHandler: onError}))
        .pipe(verbosePrintFiles('lint-js'))
        .pipe($.jscs())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish', {verbose: true}))
        .pipe($.if(!isWatching, $.jshint.reporter('fail')));
});

/************************************************************************
 * Unit testing tasks
 */

function serverTestStream() {
    process.env.NODE_ENV = 'test';
    return gulp.src('src/**/*.spec.js', {read: false})
        .pipe($.plumber({errorHandler: onError}))
        .pipe($.if(args.verbose, $.print()))
        .pipe($.mocha({
            reporter: 'spec'
        }));
}

gulp.task('test-server', function() {
    return serverTestStream();
});

gulp.task('test-server-coverage', ['clean-coverage'], function(cb) {
    var coverageDir = './coverage';
    gulp.src(['src/**/*.js', '!**/*.spec.js'])
        .pipe($.if(args.verbose, $.print()))
        .pipe($.istanbul({ // Covering files
            //instrumenter: isparta.Instrumenter,
            includeUntested: true
        }))
        .pipe($.istanbul.hookRequire()) // Force `require` to return covered files
        .on('finish', function() {
            serverTestStream()
                .pipe($.istanbul.writeReports({
                    dir: coverageDir,
                    reportOpts: {dir: coverageDir},
                    reporters: ['text', 'text-summary', 'json', 'html']
                }))
                .pipe($.istanbulEnforcer({
                    thresholds: {
                        statements: 0,
                        branches: 0,
                        lines: 0,
                        functions: 0
                    },
                    coverageDirectory: coverageDir,
                    rootDirectory: ''
                }))
                .on('end', cb);
        });
});

gulp.task('test', 'Run unit tests', function(cb) {
    runSequence('clean-coverage', 'lint', 'test-server-coverage', cb);
});

/************************************************************************
 * Watch / Reload tasks
 */

gulp.task('watch-iterate', false, function(cb) {
    runSequence('lint', 'test-server', cb);
});

gulp.task('watch', false, function() {
    isWatching = true;
    gulp.watch('src/**/*.js', ['watch-iterate']);
});

gulp.task('nodemon', false, function(cb) {
    var firstStart = true;
    var serverPort = 8000;
    $.nodemon({
        script: 'example/server.js',
        ext: 'js',
        env: {
            'NODE_ENV': 'development',
            'PORT': serverPort
        },
        nodeArgs: ['--debug'],
        ignore: [
            'coverage/**', 'node_modules/**',
            'gulpfile.js', '.idea/**', '.git/**'
        ],
        stdout: false // important for 'readable' event
    })
    // The http server might not have started listening yet when
    // the `restart` event has been triggered. It's best to check
    // whether it is already listening for connections or not.
    .on('readable', function() {
        this.stdout.on('data', function(chunk) {
            process.stdout.write(chunk);
            if (/listening at http/.test(chunk)) {
                if (firstStart) {
                    firstStart = false;
                    cb();
                }
            }
        });
        this.stderr.pipe(process.stdout);
    });
    //.on('change', ['test-server'])
    //.on('start', function() {});
});

gulp.task('serve', 'Watch for file changes and re-run build and lint tasks', function(cb) {
    // When watch and nodemon tasks run at same time
    // the server seems to randomly blow up (??)
    runSequence(
        'watch',
        'nodemon',
        cb
    );
});


text:
require 'spec_helper'

describe 'resource_reference_without_title_capital' do

  context 'a proper reference' do
    let(:msg) { 'whitespce between reference type and title' }
    let(:code) { "file { 'foo': ensure => file, notify => Title['one'],}" }

    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

  context 'a proper reference in quotes' do
    let(:code) { "file { 'foo': ensure => file, notify => Title['One'],}" }

    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

  context 'a proper reference as array in quotes' do
    let(:code) { "file { 'foo': ensure => file, notify => Title['one', 'two'],}" }

    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

  context 'multiple proper references as array in quotes' do
    let(:code) { "file { 'foo': ensure => file, notify => [ Title['one'], Title['two'] ],}" }

    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

  context 'multiple proper references as array one in quotes, one as variable' do
    let(:code) { "file { 'foo': ensure => file, notify => [ Title['one'], Title[$foo_var] ],}" }

    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

  context 'a proper reference as variable' do
    let(:code) { "file { 'foo': ensure => file, notify => Title[$foo_var],}" }

    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

  context 'a proper reference with a variable enclosed' do
    let(:code) {
      %(file {'foo': ensure => file, notify => Title["with ${param}"],} )
    }
    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

  context 'resource reference with title as capital letter' do
    let(:msg) { 'resource reference with title with capital letter' }
    let(:code) { "file { 'foo': ensure => file, notify => Title[One],}" }

    it 'should only detect a single problem' do
      expect(problems).to have(1).problem
    end

    it 'should create an error' do
      expect(problems).to contain_error(msg).on_line(1)
    end
  end

  context 'resource reference with title as array of capital letters' do
    let(:msg) { 'resource reference with title with capital letter' }
    let(:code) { "file { 'foo': ensure => file, notify => Title[One, Two],}" }

    it 'should only detect a single problem' do
      expect(problems)
    end

    it 'should create an error' do
      expect(problems).to contain_error(msg).on_line(1)
    end
  end

  context 'resource reference with title as array of resource references with capital letters' do
    let(:msg) { 'resource reference with title with capital letter' }
    let(:code) { "file { 'foo': ensure => file, notify => [Title[One], Title[Two],]}" }

    it 'should only detect a single problem' do
      expect(problems)
    end

    it 'should create an error' do
      expect(problems).to contain_error(msg).on_line(1)
    end
  end

  context 'resource reference with title without quotes' do
    let(:msg) { 'resource reference with title with missing quotes' }
    let(:code) { "file { 'foo': ensure => file, notify => Title[one],}" }

    it 'should only detect a single problem' do
      expect(problems).to have(1).problem
    end

    it 'should create an error' do
      expect(problems).to contain_error(msg).on_line(1)
    end
  end

  context 'stay within the parameter context' do
    let(:code) { "file { 'foo': ensure => file, notify => Title['One'],} $var = [ Exec[runsomething] ]" }

    it 'should detect no problem' do
      expect(problems).to have(0).problem
    end
  end

end


text:
cask 'pg-commander' do
  version '1.5.9'
  sha256 '8c844dec96e459bd047bd60bc0daae2ee50f5af9594b506b627ff1ecc5395fff'

  # eggerapps-downloads.s3.amazonaws.com was verified as official when first introduced to the cask
  url "https://eggerapps-downloads.s3.amazonaws.com/pgcommander-#{version}.zip"
  name 'PG Commander'
  homepage 'https://eggerapps.at/pgcommander/'

  app 'PG Commander.app'
end


text:
<?php

namespace WikiRenderer\Markup\DokuWiki;

/**
 * Parse code inline tag.
 */
class NoWikiInline extends \WikiRenderer\InlineTag
{
    protected $name = 'nowiki';
    protected $generatorName = 'noformat';
    protected $beginTag = '%%';
    protected $endTag = '%%';

    public function isOtherTagAllowed()
    {
        return false;
    }
}


text:
package apple.gamecontroller;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;

@Library("GameController/GameController.h")
@Mapping("GCControllerPlayerIndex")
public final class GCControllerPlayerIndex extends ObjCEnum {

    @GlobalConstant("GCControllerPlayerIndexUnset")
    public static final long Unset = -1L;

}


text:
using Igneel.Graphics;
using OpenTK.Graphics.ES20;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Igneel.OpenGLES2
{
    public class ESGraphicBuffer : GraphicBufferBase
    {
        public int buffer;
        byte[] bufferData;
        GCHandle handle;
        All _type;
        public ESGraphicBuffer(int size, int stride, All type, ResourceUsage usage, CpuAccessFlags cpuAcces,
            ResBinding binding, IntPtr data)
        {
            _type = type;
            this._lenght = size;
            this._stride = stride;
            this._usage = usage;
            this._cpuAccesType = cpuAcces;
            this._binding = binding;

            GL.GenBuffers(1, out buffer);
            GL.BindBuffer(type, buffer);
            GL.BufferData(type, new IntPtr(size), data, Utils.GetUsage(usage));

            if (cpuAcces != CpuAccessFlags.None)
            {
                bufferData = new byte[size];
                if(data!= IntPtr.Zero)
                    ClrRuntime.Runtime.Copy(data, bufferData, 0, size);
            }
        }
        public override IntPtr Map(MapType map = MapType.Read, bool doNotWait = false)
        {
            if (bufferData != null)
            {
                handle = GCHandle.Alloc(bufferData, GCHandleType.Pinned);
                return ClrRuntime.Runtime.GetPtr(bufferData, 0);
            }
            else
                throw new InvalidOperationException();
        }

        public override void Unmap()
        {
            if (bufferData != null)
            {
                handle.Free();
                GL.BufferData(_type, new IntPtr(_lenght), bufferData, Utils.GetUsage(_usage));
            }
            else
                throw new InvalidOperationException();
        }
    }
}


text:
package Google::Ads::AdWords::v201809::Location;
use strict;
use warnings;

__PACKAGE__->_set_element_form_qualified(1);

sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' };

our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;

sub __get_attr_class {
    return $XML_ATTRIBUTE_CLASS;
}

use base qw(Google::Ads::AdWords::v201809::Criterion);
# Variety: sequence
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);

{ # BLOCK to scope variables

my %id_of :ATTR(:get<id>);
my %type_of :ATTR(:get<type>);
my %Criterion__Type_of :ATTR(:get<Criterion__Type>);
my %locationName_of :ATTR(:get<locationName>);
my %displayType_of :ATTR(:get<displayType>);
my %targetingStatus_of :ATTR(:get<targetingStatus>);
my %parentLocations_of :ATTR(:get<parentLocations>);

__PACKAGE__->_factory(
    [ qw(        id
        type
        Criterion__Type
        locationName
        displayType
        targetingStatus
        parentLocations

    ) ],
    {
        'id' => \%id_of,
        'type' => \%type_of,
        'Criterion__Type' => \%Criterion__Type_of,
        'locationName' => \%locationName_of,
        'displayType' => \%displayType_of,
        'targetingStatus' => \%targetingStatus_of,
        'parentLocations' => \%parentLocations_of,
    },
    {
        'id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
        'type' => 'Google::Ads::AdWords::v201809::Criterion::Type',
        'Criterion__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
        'locationName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
        'displayType' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
        'targetingStatus' => 'Google::Ads::AdWords::v201809::LocationTargetingStatus',
        'parentLocations' => 'Google::Ads::AdWords::v201809::Location',
    },
    {

        'id' => 'id',
        'type' => 'type',
        'Criterion__Type' => 'Criterion.Type',
        'locationName' => 'locationName',
        'displayType' => 'displayType',
        'targetingStatus' => 'targetingStatus',
        'parentLocations' => 'parentLocations',
    }
);

} # end BLOCK

1;

=pod

=head1 NAME

Google::Ads::AdWords::v201809::Location

=head1 DESCRIPTION

Perl data type class for the XML Schema defined complexType
Location from the namespace https://adwords.google.com/api/adwords/cm/v201809.

Represents Location criterion.
A criterion of this type can only be created using an ID. This is enabled for AdX.

=head2 PROPERTIES

The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:

=over

=item * locationName

=item * displayType

=item * targetingStatus

=item * parentLocations

=back

=head1 METHODS

=head2 new

Constructor. The following data structure may be passed to new():

=head1 AUTHOR

Generated by SOAP::WSDL

=cut


text:
#!/usr/bin/env node
/* jshint node: true */

"use strict";

var path = require("path"),
    webpack = require("webpack");

var outputDir = process.cwd(),
    sourcesDir = path.join(__dirname, ".."),
    bundle = process.argv.length > 2 ? process.argv[2] : "dx.custom";

bundle = bundle.replace(/.config.js$/, "");

var baseConfig = require("./webpack.config.js");
var createConfig = function(outputFile) {
    var config = Object.create(baseConfig);

    config.context = process.cwd();
    config.entry = "./" + bundle + ".config.js";
    config.output = {
        path: outputDir,
        filename: outputFile
    };

    config.resolve = {
        alias: {
            'devextreme': sourcesDir
        }
    };

    return config;
};

console.log("bundling using '" + bundle + ".config.js'...");
webpack([
    createConfig(bundle + ".debug.js"),
    (function() {
	    var config = createConfig(bundle + ".js");
	    config.plugins = (config.plugins || []).concat([
		    new webpack.optimize.UglifyJsPlugin({
		        compress: { warnings: false }
		    })
    ]);
	    return config;
    })()
], function(err, stats) {
    if(err) {
        throw err;
    }

    var jsonStats = stats.toJson();
    if(jsonStats.errors.length) {
        console.log("'" + bundle + "' bundles creation failed!\n\n" + jsonStats.errors.join("\n\n"));
    } else {
        console.log("'" + bundle + "' bundles created!");
    }
});


text:
<?php
if($_GET)
{
	$notes = trim($_GET['keynotes']);
	$file = "announcements/keynotes.txt";
	$handle = fopen($file, 'w+') or die("can't open file");
	if(fwrite($handle, $notes))
	{
		?>

		<?php
	}
	else
	{
		?>

		<?php
	}
	fclose($handle);
}
?>
<!DOCTYPE html>

		<title>Update Keynotes</title>
		<link type="text/css" rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
		<link type="text/css" rel="stylesheet" href="css/sidemenu.css">

		<?php include_once 'sidemenu.php'; ?>

Update Safety Talk

			<form action="keynotes.php" method="">

					<textarea class="form-control" name="keynotes" rows="10" id="keynotes"><?php
						$fh = fopen('announcements/keynotes.txt','r');
						while(! feof($fh))
						{
							echo fgets($fh);
						}
						fclose($fh);
					?></textarea>

					<button type="submit" class="btn btn-success btn-lg pull-right" value="Update"> Update </button>

			</form>

How to use:

					The text area is populated with what the current keynotes are.

					Remove or add to the text area, then hit 'Update'

					One keynote per line

								<button type="button" class="close" data-dismiss="modal">×</button>

Success

keynotes have been updated Successfully

								<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

								<button type="button" class="close" data-dismiss="modal">×</button>

Fail

Could not update, please try again!

								<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>


text:
<?php

namespace Letunovskiymn\KorablikBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * KeysBot
 *
 * @ORM\Table(name="keys_bot")
 * @ORM\Entity(repositoryClass="Letunovskiymn\KorablikBundle\Repository\KeysBotRepository")
 */
class KeysBot
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="key_client", type="string", length=255, unique=true)
     */
    private $keyClient;

    /**
     * @var string
     *
     * @ORM\Column(name="chat_id", type="string", length=255)
     */
    private $chatId;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set keyClient
     *
     * @param string $keyClient
     *
     * @return KeysBot
     */
    public function setKeyClient($keyClient)
    {
        $this->keyClient = $keyClient;

        return $this;
    }

    /**
     * Get keyClient
     *
     * @return string
     */
    public function getKeyClient()
    {
        return $this->keyClient;
    }

    /**
     * Set chatId
     *
     * @param string $chatId
     *
     * @return KeysBot
     */
    public function setChatId($chatId)
    {
        $this->chatId = $chatId;

        return $this;
    }

    /**
     * Get chatId
     *
     * @return string
     */
    public function getChatId()
    {
        return $this->chatId;
    }
}


text:
/*
 *  gravity_compensation.cpp
 *
 *  Created on: Nov 11, 2013
 *  Authors:   Francisco Viña
 *            fevb <at> kth.se
 */

/* Copyright (c) 2013, Francisco Viña, CVAP, KTH
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of KTH nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <ros/ros.h>
#include <gravity_compensation/gravity_compensation.h>
#include <geometry_msgs/PoseStamped.h>
#include <tf_conversions/tf_eigen.h>
#include <eigen3/Eigen/Core>
#include <eigen_conversions/eigen_msg.h>

GravityCompensation::GravityCompensation(GravityCompensationParams *g_comp_params)
{
    m_g_comp_params = g_comp_params;
    m_tf_listener = new tf::TransformListener();
}

GravityCompensation::~GravityCompensation()
{
    delete m_tf_listener;
}

void GravityCompensation::Zero(const geometry_msgs::WrenchStamped &ft_raw,
                          geometry_msgs::WrenchStamped &ft_zeroed)
{
    Eigen::Matrix<double, 6, 1> bias = m_g_comp_params->getBias();

    ft_zeroed = ft_raw;
    Eigen::Matrix<double, 6, 1> ft_raw_eigen;
    Eigen::Matrix<double, 6, 1> ft_zeroed_eigen;
    tf::wrenchMsgToEigen(ft_raw.wrench, ft_raw_eigen);

    ft_zeroed_eigen = ft_raw_eigen - bias;
    tf::wrenchEigenToMsg(ft_zeroed_eigen, ft_zeroed.wrench);
}

bool GravityCompensation::Compensate(const geometry_msgs::WrenchStamped &ft_zeroed,
                                     const sensor_msgs::Imu &gravity,
                                     geometry_msgs::WrenchStamped &ft_compensated)
{

  geometry_msgs::Vector3Stamped g;
  g.vector = gravity.linear_acceleration;
  g.header = gravity.header;
  g.header.stamp = ros::Time();

  // convert the accelerometer reading to the F/T sensor frame
  geometry_msgs::Vector3Stamped g_ft_frame;
  try
  {
    m_tf_listener->transformVector(ft_zeroed.header.frame_id, g, g_ft_frame);
  }

  catch(tf::TransformException &ex)
  {
    ROS_ERROR("Error transforming gravity vector to ft sensor frame...");
    ROS_ERROR("%s.", ex.what());
    return false;
  }

  double gripper_mass = m_g_comp_params->getGripperMass();
  ROS_DEBUG("gripper_mass = %f", gripper_mass);
  Eigen::Vector3d g_ft_frame_eigen;
  tf::vectorMsgToEigen(g_ft_frame.vector, g_ft_frame_eigen);

  Eigen::Matrix<double, 6, 1> gripper_wrench_eigen;
  gripper_wrench_eigen.topRows(3) = g_ft_frame_eigen*gripper_mass;

  // grab the gripper_com
  tf::StampedTransform gripper_com_tf = m_g_comp_params->getGripperCOM();

  // convert the gripper_com to geometry_msgs::PoseStamped
  geometry_msgs::PoseStamped gripper_com;
  tf::poseTFToMsg(gripper_com_tf, gripper_com.pose);
  gripper_com.header.stamp = ros::Time();
  gripper_com.header.frame_id = gripper_com_tf.frame_id_;

  // make sure the gripper COM is expressed with respect to the F/T sensor frame
  geometry_msgs::PoseStamped ft_gripper_com;

  try
  {
    m_tf_listener->transformPose(ft_zeroed.header.frame_id,
                                 gripper_com,
                                 ft_gripper_com);
  }

  catch(tf::TransformException &ex)
  {
    ROS_ERROR("Error looking up transform between the gripper COM and the ft sensor frame");
    ROS_ERROR("%s.", ex.what());
    return false;
  }

  // convert to Eigen to do cross product to compute the torque
  Eigen::Vector3d r;
  tf::pointMsgToEigen(ft_gripper_com.pose.position, r);

  // compute torque generated by weight of the gripper
  Eigen::Vector3d gripper_force_eigen = gripper_wrench_eigen.topRows(3);
  Eigen::Vector3d gripper_torque_eigen = r.cross(gripper_force_eigen);
  gripper_wrench_eigen.bottomRows(3) = gripper_torque_eigen;

  // compensate force & torque
  Eigen::Matrix<double, 6, 1> ft_zeroed_eigen;
  tf::wrenchMsgToEigen(ft_zeroed.wrench, ft_zeroed_eigen);
  Eigen::Matrix<double, 6, 1> ft_compensated_eigen;

  ft_compensated_eigen = ft_zeroed_eigen - gripper_wrench_eigen;

  tf::wrenchEigenToMsg(ft_compensated_eigen, ft_compensated.wrench);
  ft_compensated.header = ft_zeroed.header;

  return true;
}


text:
package com.developmentsprint.spring.breaker;

import org.springframework.core.NestedRuntimeException;

public class CircuitBreakerException extends NestedRuntimeException {

    private static final long serialVersionUID = 1L;

    public CircuitBreakerException(String msg) {
        super(msg);
    }

    public CircuitBreakerException(Throwable e) {
        super(messageFrom(e), e);
    }

    public CircuitBreakerException(String msg, Throwable cause) {
        super(msg, cause);
    }

    private static String messageFrom(Throwable e) {
        if (e != null) {
            return e.getMessage();
        } else {
            return null;
        }
    }

}


text:
using System;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Reflection;
using System.Collections.Generic;

namespace ZYSocket.RPCX.Service
{

    public delegate ProxyReturnValue CallHandler(string Tag, string MethodName, Type[] argTypelist, List<byte[]> arglist, Type returnType);

    public delegate void CallNullHandler(string Tag, string MethodName, Type[] argTypelist, List<byte[]> arglist);

    internal class ZYProxy : RealProxy
    {
        public string Tag { get; private set; }

        public event CallHandler CallHaveReturn;
        public event CallNullHandler CallNullReturn;

        private Type nullType = typeof(void);

        public ZYProxy(Type type,bool CallReturn)
           : base(type)
        {
            Tag = type.Name;

            if(!CallReturn)
            {
                foreach (var item in type.GetMethods())
                {
                    if (item.ReturnType != typeof(void))
                        throw new Exception("Not call sync method,If you want to use,Set RPCServer.IsCallReturn value is True!");

                    foreach (var parmeters in item.GetParameters())
                    {
                        if (parmeters.ParameterType.Name.LastIndexOf('&') >= 0)
                        {
                            throw new Exception("Not call sync method,If you want to use,Set RPCServer.IsCallReturn value is True!");

                        }
                    }

                }
            }

        }

        public override IMessage Invoke(IMessage reqMsg)
        {
            IMethodCallMessage ctorMsg = reqMsg as IMethodCallMessage;

            List<byte[]> arglist = new List<byte[]>(ctorMsg.ArgCount);

            Type[] types = ctorMsg.MethodSignature as Type[];

            Type[] argsType = new Type[ctorMsg.ArgCount];

            object[] args = ctorMsg.Args;

            for (int i = 0; i < ctorMsg.ArgCount; i++)
            {
                argsType[i] = args[i].GetType();
                arglist.Add(Serialization.PackSingleObject(argsType[i], args[i]));
            }

            var returnType = (ctorMsg.MethodBase as MethodInfo).ReturnType;

            if (returnType != nullType)
            {
                if(CallHaveReturn==null)
                    throw new Exception("event not register");
                ProxyReturnValue returnval = CallHaveReturn(Tag, Make.MakeMethodName(ctorMsg.MethodName, types), argsType, arglist, returnType);
                if (returnval.Args == null)
                {
                    returnval.Args = args;
                }

                return new ReturnMessage(returnval.returnVal, returnval.Args, returnval.Args == null ? 0 : returnval.Args.Length, null, ctorMsg);

            }
            else
            {
                if (CallNullReturn == null)
                    throw new Exception("event not register");

                CallNullReturn(Tag, Make.MakeMethodName(ctorMsg.MethodName, types), argsType, arglist); //如果你没有返回值那么out ref将失效

                return new ReturnMessage(null, args, args == null ? 0 : args.Length, null, ctorMsg);
            }

        }
    }

    public class ProxyReturnValue
    {
        public object returnVal { get; set; }

        public object[] Args { get; set; }

    }
}


text:
Compiles Snap! projects to JavaScript.

## Goals

snc aims to output runnable JavaScript code that exactly reproduces the runtime semantics of Snap! projects.

## Strategies

snc uses a simple evaluator with six state variables:

```js
var scope; // the current scope chain
var procs; // the procedure dictionary
var fn; // the current JavaScript function to evaluate
var conts; // the continuation chain
var value; // the value fn is called with
var tmps; // the temporary register stack
```

The evaluation loop stores `fn` and then sets it to `null`. It applies the stored function to `value` and replaces `value` with the result. If `fn` does not have a value after this occurs, it pops an `fn` off of `conts`.

Normal blocks are compiled to JavaScript function calls. The following:

    set a to 1 + 2

is compiled to:

```js
function $a() {
    set('a', add(1, 2));
}
```

Blocks that can yield pass a continuation to this function call. The following:

    run foo
    say "hi"

is compiled to:

```js
function $a() {
    call($b, get('foo'));
}
function $b() {
    say('hi');
}
```

User-defined procedures are also evaluated with continuation-passing style. The following:

    foo (str : any)
    say str

    foo "hello"

is compiled to:

```js
procs = {
    // ...
    'foo %s': {
        // ...
        types: ['s'],
        fps: ['str'],
        fn: function() {
            function $a() {
                say(get('str'));
            }
            return $a;
        }()
    }
};
function $a() {
    procedure($b, 'foo %s', 'hello');
}
function $b() {
}
```


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  nibName
  UITableViewRow

  notification
  GDAccessibilityNotification

  notificationCenter
  GDCarbonEvent

  notificationName
  GDCarbonEvent

Searching...

No Matches


text:
#ifndef STRINGDECODER_H
#define STRINGDECODER_H

#include "dtoolbase.h"

/**
 * The base class to a family of classes that decode various kinds of encoded
 * byte streams.  Give it a string, then ask it to pull the characters out one
 * at a time.  This also serves as the plain old byte-at-a-time decoder.
 */
class EXPCL_DTOOL StringDecoder {
public:
  INLINE StringDecoder(const string &input);
  virtual ~StringDecoder();

  virtual int get_next_character();
  INLINE bool is_eof();

  static void set_notify_ptr(ostream *ptr);
  static ostream *get_notify_ptr();

protected:
  INLINE bool test_eof();

  string _input;
  size_t _p;
  bool _eof;
  static ostream *_notify_ptr;
};

/**
 * This decoder extracts utf-8 sequences.
 */
class StringUtf8Decoder : public StringDecoder {
public:
  INLINE StringUtf8Decoder(const string &input);

  virtual int get_next_character();
};

/**
 * This decoder extracts characters two at a time to get a plain wide
 * character sequence.
 */
class StringUnicodeDecoder : public StringDecoder {
public:
  INLINE StringUnicodeDecoder(const string &input);

  virtual int get_next_character();
};

#include "stringDecoder.I"

#endif


text:
static SoundManager *gSoundManager = 0;
SoundManager *sound_manager() {return system()->sound_manager();}

// SoundSource
// ===========

void SoundSource::Play() {
  if (channel_ != 0)
    FMOD_Channel_SetPaused(channel_, false);
}

void SoundSource::Pause() {
  if (channel_ != 0)
    FMOD_Channel_SetPaused(channel_, true);
}

bool SoundSource::IsPaused() const {
  FMOD_BOOL is_paused = false;
  if (channel_ != 0)
    FMOD_Channel_GetPaused(channel_, &is_paused);
  return is_paused;
}

void SoundSource::Stop() {
  if (channel_ != 0)
    FMOD_Channel_Stop(channel_);
}

bool SoundSource::IsStopped() const {
  FMOD_BOOL is_playing = false;
  if (channel_ != 0)
    FMOD_Channel_IsPlaying(channel_, &is_playing);
  return !is_playing;
}

// SoundSample
// ===========

SoundSample *SoundSample::Load(InputStream in, bool store_compressed, float base_volume) {
  // Load the data into memory - we could eventually switch to using extra_info.fileoffset or
  // FMOD_OPENUSER mode instead but this is good for now.
  LOGF("SSLA %d, %d\n", in.IsValid(), sound_manager()->IsInitialized());
  if (!in.IsValid() || !sound_manager()->IsInitialized())
    return 0;
  char *data;
  int length = in.ReadAllData((void**)&data);

  // Attempt to create the sound
  FMOD_SOUND *sound;
  FMOD_RESULT result;
  FMOD_CREATESOUNDEXINFO extra_info;
  memset(&extra_info, 0, sizeof(extra_info));
  extra_info.cbsize = sizeof(extra_info);
  extra_info.length = length;
  if (store_compressed) {
    result = FMOD_System_CreateSound(sound_manager()->GetSystem(),
      data, FMOD_CREATECOMPRESSEDSAMPLE | FMOD_OPENMEMORY | FMOD_SOFTWARE | FMOD_LOOP_NORMAL, &extra_info, &sound);
  } else {
    result = FMOD_System_CreateSound(sound_manager()->GetSystem(),
      data, FMOD_DEFAULT | FMOD_OPENMEMORY | FMOD_SOFTWARE | FMOD_LOOP_NORMAL, &extra_info, &sound);
  }
  LOGF("SSLB %d, %d\n", result, FMOD_OK);

  // Store the result or return error
  delete[] data;
  if (result != FMOD_OK)
    return 0;
  return new SoundSample(sound, base_volume);
}

SoundSample::~SoundSample() {
  FMOD_Sound_Release(sound_);
}

SoundSource SoundSample::Play(bool looped, bool start_paused) const {
  FMOD_CHANNEL *channel;
  FMOD_Sound_SetLoopCount(sound_, looped? -1 : 0);
  FMOD_System_PlaySound(sound_manager()->GetSystem(), FMOD_CHANNEL_FREE, sound_, start_paused, &channel);
  FMOD_Channel_SetVolume(channel, base_volume_);
  return SoundSource(channel);
}

// SoundManager
// ============

void SoundManager::SetVolume(float volume) {
  volume_ = volume;
  if (IsInitialized()) {
    FMOD_CHANNELGROUP *master_channel_group;
    FMOD_System_GetMasterChannelGroup(system_, &master_channel_group);
    FMOD_ChannelGroup_SetVolume(master_channel_group, volume);
  }
}

SoundManager::SoundManager()
: system_(0), volume_(1) {
  // Create the system object and check versions
  const int kNumChannels = 128;
  FMOD_RESULT result = FMOD_System_Create(&system_);
  if (result != FMOD_OK) {
    LOGF("Sound driver initialization failed, result %d\n", result);
    return;
  }
  unsigned int version;
  if (FMOD_System_GetVersion(system_, &version) != FMOD_OK || version < FMOD_VERSION) {
    LOGF("Sound driver version checking failed\n");
    goto error;
  }

  // Fix bad initialization options. FMOD documentation strongly recommends doing this for Windows.
  FMOD_CAPS caps;
  FMOD_SPEAKERMODE speaker_mode;
  if (FMOD_System_GetDriverCaps(system_, 0, &caps, 0, 0, &speaker_mode) != FMOD_OK) {
    LOGF("Sound driver capability checking failed\n");
    goto error;
  }
  if (FMOD_System_SetSpeakerMode(system_, speaker_mode) != FMOD_OK) {
    LOGF("Sound driver speaker setting failed\n");
    goto error;
  }
  if (caps & FMOD_CAPS_HARDWARE_EMULATED) {
    if (FMOD_System_SetDSPBufferSize(system_, 1024, 10) != FMOD_OK) {
      LOGF("Sound driver DSP buffer set failed\n");
      goto error;
    }
  }

  // Initialize
  if (FMOD_System_Init(system_, kNumChannels, FMOD_INIT_NORMAL, 0) != FMOD_OK) {
    if (FMOD_System_SetSpeakerMode(system_, FMOD_SPEAKERMODE_STEREO) != FMOD_OK) {
      LOGF("Sound driver speaker mode set failed\n");
      goto error;
    }
    if (FMOD_System_Init(system_, kNumChannels, FMOD_INIT_NORMAL, 0) != FMOD_OK) {
      LOGF("Sound driver system init set failed\n");
      goto error;
    }
  }

  // Success
  SetVolume(volume_);
  return;

  // Failure
error:;
  system_ = 0;
}

SoundManager::~SoundManager() {
  if (IsInitialized())
    FMOD_System_Release(system_);
}

void SoundManager::Think() {
  if (IsInitialized())
    FMOD_System_Update(system_);
}

void SoundManager::PlayAllSources() {
  if (IsInitialized()) {
    FMOD_CHANNELGROUP *master_channel_group;
    FMOD_System_GetMasterChannelGroup(system_, &master_channel_group);
    FMOD_ChannelGroup_SetPaused(master_channel_group, false);
  }
}

void SoundManager::PauseAllSources() {
  if (IsInitialized()) {
    FMOD_CHANNELGROUP *master_channel_group;
    FMOD_System_GetMasterChannelGroup(system_, &master_channel_group);
    FMOD_ChannelGroup_SetPaused(master_channel_group, true);
  }
}

void SoundManager::StopAllSources() {
  if (IsInitialized()) {
    int num_channels;
    FMOD_CHANNELGROUP *master_channel_group;
    FMOD_System_GetMasterChannelGroup(system_, &master_channel_group);
    FMOD_ChannelGroup_GetNumChannels(master_channel_group, &num_channels);
    for (int i = 0; i < num_channels; i++) {
      FMOD_CHANNEL *channel;
      FMOD_ChannelGroup_GetChannel(master_channel_group, i, &channel);
      FMOD_Channel_Stop(channel);
    }
  }
}

#endif // GLOP_LEAN_AND_MEAN


text:
<?php

    namespace application\components\markdown;

    use \Ciconia\Common\Text;
    use \Ciconia\Markdown;

    /**
     * Markdown converts text with four spaces at the front of each line to code blocks.
     * GFM supports that, but we also support fenced blocks.
     * Just wrap your code blocks in ``` and you won't need to indent manually to trigger a code block.
     *
     * PHP Markdown style `~` is also available.
     *
     * @author Kazuyuki Hayashi <hayashi@valnur.net>
     */
    class FencedCodeBlockExtension extends \Ciconia\Extension\Gfm\FencedCodeBlockExtension
    {

        /**
         * @access private
         * @var Markdown $markdown
         */
        private $markdown;

        /**
         * Register
         *
         * @access public
         * @param Markdown $markdown "Markdown instance"
         * @return void
         */
        public function register(Markdown $markdown)
        {
            $this->markdown = $markdown;
            // Should be run before first hashHtmlBlocks().
            $markdown->on('initialize', array($this, 'processFencedCodeBlock'));
        }

        /**
         * Process: Fenced Code Block
         *
         * @access public
         * @param Text $text "The text to be processed."
         * @return string
         */
        public function processFencedCodeBlock(Text $text)
        {
            $regex = '{
                (?:\n+|\A)
                (?:
                    ([`~]{3})[ ]*         #1 fence ` or ~
                        ([a-zA-Z0-9]*?)?  #2 language [optional]
                    \n+
                    (.*?)\n                #3 code block
                    \1                    # matched #1
                )
            }smx';
            $text->replace($regex, function(Text $w, Text $fenced, Text $lang, Text $code) {
                $options = array();
                if(!$lang->isEmpty()) {
                    $options = array(
                        'attr' => array(
                            'class' => 'prettyprint lang-' . $lang->lower(),
                        ),
                    );
                }
                $code->escapeHtml(ENT_NOQUOTES);
                $this->markdown->emit('detab', array($code));
                $code->replace('/\A\n+/', '');
                $code->replace('/\s+\z/', '');
                return "\n\n" . $this->getRenderer()->renderCodeBlock($code, $options) . "\n\n";
            });
        }

    }


text:
package com.google.cloud.gkehub.v1beta;

import static com.google.cloud.gkehub.v1beta.GkeHubClient.ListFeaturesPagedResponse;

import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.StatusCode;
import com.google.common.collect.Lists;
import com.google.longrunning.Operation;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Any;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

@Generated("by gapic-generator-java")
public class GkeHubClientTest {
  private static MockGkeHub mockGkeHub;
  private static MockServiceHelper mockServiceHelper;
  private LocalChannelProvider channelProvider;
  private GkeHubClient client;

  @BeforeClass
  public static void startStaticServer() {
    mockGkeHub = new MockGkeHub();
    mockServiceHelper =
        new MockServiceHelper(
            UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockGkeHub));
    mockServiceHelper.start();
  }

  @AfterClass
  public static void stopServer() {
    mockServiceHelper.stop();
  }

  @Before
  public void setUp() throws IOException {
    mockServiceHelper.reset();
    channelProvider = mockServiceHelper.createChannelProvider();
    GkeHubSettings settings =
        GkeHubSettings.newBuilder()
            .setTransportChannelProvider(channelProvider)
            .setCredentialsProvider(NoCredentialsProvider.create())
            .build();
    client = GkeHubClient.create(settings);
  }

  @After
  public void tearDown() throws Exception {
    client.close();
  }

  @Test
  public void listFeaturesTest() throws Exception {
    Feature responsesElement = Feature.newBuilder().build();
    ListFeaturesResponse expectedResponse =
        ListFeaturesResponse.newBuilder()
            .setNextPageToken("")
            .addAllResources(Arrays.asList(responsesElement))
            .build();
    mockGkeHub.addResponse(expectedResponse);

    String parent = "parent-995424086";

    ListFeaturesPagedResponse pagedListResponse = client.listFeatures(parent);

    List<Feature> resources = Lists.newArrayList(pagedListResponse.iterateAll());

    Assert.assertEquals(1, resources.size());
    Assert.assertEquals(expectedResponse.getResourcesList().get(0), resources.get(0));

    List<AbstractMessage> actualRequests = mockGkeHub.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    ListFeaturesRequest actualRequest = ((ListFeaturesRequest) actualRequests.get(0));

    Assert.assertEquals(parent, actualRequest.getParent());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void listFeaturesExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockGkeHub.addException(exception);

    try {
      String parent = "parent-995424086";
      client.listFeatures(parent);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void getFeatureTest() throws Exception {
    Feature expectedResponse =
        Feature.newBuilder()
            .setName("name3373707")
            .putAllLabels(new HashMap<String, String>())
            .setResourceState(FeatureResourceState.newBuilder().build())
            .setSpec(CommonFeatureSpec.newBuilder().build())
            .putAllMembershipSpecs(new HashMap<String, MembershipFeatureSpec>())
            .setState(CommonFeatureState.newBuilder().build())
            .putAllMembershipStates(new HashMap<String, MembershipFeatureState>())
            .setCreateTime(Timestamp.newBuilder().build())
            .setUpdateTime(Timestamp.newBuilder().build())
            .setDeleteTime(Timestamp.newBuilder().build())
            .build();
    mockGkeHub.addResponse(expectedResponse);

    String name = "name3373707";

    Feature actualResponse = client.getFeature(name);
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockGkeHub.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    GetFeatureRequest actualRequest = ((GetFeatureRequest) actualRequests.get(0));

    Assert.assertEquals(name, actualRequest.getName());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void getFeatureExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockGkeHub.addException(exception);

    try {
      String name = "name3373707";
      client.getFeature(name);
      Assert.fail("No exception raised");
    } catch (InvalidArgumentException e) {
      // Expected exception.
    }
  }

  @Test
  public void createFeatureTest() throws Exception {
    Feature expectedResponse =
        Feature.newBuilder()
            .setName("name3373707")
            .putAllLabels(new HashMap<String, String>())
            .setResourceState(FeatureResourceState.newBuilder().build())
            .setSpec(CommonFeatureSpec.newBuilder().build())
            .putAllMembershipSpecs(new HashMap<String, MembershipFeatureSpec>())
            .setState(CommonFeatureState.newBuilder().build())
            .putAllMembershipStates(new HashMap<String, MembershipFeatureState>())
            .setCreateTime(Timestamp.newBuilder().build())
            .setUpdateTime(Timestamp.newBuilder().build())
            .setDeleteTime(Timestamp.newBuilder().build())
            .build();
    Operation resultOperation =
        Operation.newBuilder()
            .setName("createFeatureTest")
            .setDone(true)
            .setResponse(Any.pack(expectedResponse))
            .build();
    mockGkeHub.addResponse(resultOperation);

    String parent = "parent-995424086";
    Feature resource = Feature.newBuilder().build();
    String featureId = "featureId-420503887";

    Feature actualResponse = client.createFeatureAsync(parent, resource, featureId).get();
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockGkeHub.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    CreateFeatureRequest actualRequest = ((CreateFeatureRequest) actualRequests.get(0));

    Assert.assertEquals(parent, actualRequest.getParent());
    Assert.assertEquals(resource, actualRequest.getResource());
    Assert.assertEquals(featureId, actualRequest.getFeatureId());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void createFeatureExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockGkeHub.addException(exception);

    try {
      String parent = "parent-995424086";
      Feature resource = Feature.newBuilder().build();
      String featureId = "featureId-420503887";
      client.createFeatureAsync(parent, resource, featureId).get();
      Assert.fail("No exception raised");
    } catch (ExecutionException e) {
      Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass());
      InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
      Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
    }
  }

  @Test
  public void deleteFeatureTest() throws Exception {
    Empty expectedResponse = Empty.newBuilder().build();
    Operation resultOperation =
        Operation.newBuilder()
            .setName("deleteFeatureTest")
            .setDone(true)
            .setResponse(Any.pack(expectedResponse))
            .build();
    mockGkeHub.addResponse(resultOperation);

    String name = "name3373707";

    client.deleteFeatureAsync(name).get();

    List<AbstractMessage> actualRequests = mockGkeHub.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    DeleteFeatureRequest actualRequest = ((DeleteFeatureRequest) actualRequests.get(0));

    Assert.assertEquals(name, actualRequest.getName());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void deleteFeatureExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockGkeHub.addException(exception);

    try {
      String name = "name3373707";
      client.deleteFeatureAsync(name).get();
      Assert.fail("No exception raised");
    } catch (ExecutionException e) {
      Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass());
      InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
      Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
    }
  }

  @Test
  public void updateFeatureTest() throws Exception {
    Feature expectedResponse =
        Feature.newBuilder()
            .setName("name3373707")
            .putAllLabels(new HashMap<String, String>())
            .setResourceState(FeatureResourceState.newBuilder().build())
            .setSpec(CommonFeatureSpec.newBuilder().build())
            .putAllMembershipSpecs(new HashMap<String, MembershipFeatureSpec>())
            .setState(CommonFeatureState.newBuilder().build())
            .putAllMembershipStates(new HashMap<String, MembershipFeatureState>())
            .setCreateTime(Timestamp.newBuilder().build())
            .setUpdateTime(Timestamp.newBuilder().build())
            .setDeleteTime(Timestamp.newBuilder().build())
            .build();
    Operation resultOperation =
        Operation.newBuilder()
            .setName("updateFeatureTest")
            .setDone(true)
            .setResponse(Any.pack(expectedResponse))
            .build();
    mockGkeHub.addResponse(resultOperation);

    String name = "name3373707";
    Feature resource = Feature.newBuilder().build();
    FieldMask updateMask = FieldMask.newBuilder().build();

    Feature actualResponse = client.updateFeatureAsync(name, resource, updateMask).get();
    Assert.assertEquals(expectedResponse, actualResponse);

    List<AbstractMessage> actualRequests = mockGkeHub.getRequests();
    Assert.assertEquals(1, actualRequests.size());
    UpdateFeatureRequest actualRequest = ((UpdateFeatureRequest) actualRequests.get(0));

    Assert.assertEquals(name, actualRequest.getName());
    Assert.assertEquals(resource, actualRequest.getResource());
    Assert.assertEquals(updateMask, actualRequest.getUpdateMask());
    Assert.assertTrue(
        channelProvider.isHeaderSent(
            ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
            GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
  }

  @Test
  public void updateFeatureExceptionTest() throws Exception {
    StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
    mockGkeHub.addException(exception);

    try {
      String name = "name3373707";
      Feature resource = Feature.newBuilder().build();
      FieldMask updateMask = FieldMask.newBuilder().build();
      client.updateFeatureAsync(name, resource, updateMask).get();
      Assert.fail("No exception raised");
    } catch (ExecutionException e) {
      Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass());
      InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause());
      Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode());
    }
  }
}


text:
import { NextFunction, Request, Response, Router } from 'express'
import * as _ from 'lodash';
import { onError } from './onError';
import { onSuccess } from './onSuccess';
import {findAllVacantPositions, findAllVacantPositions2} from "../../../queries/applications/findAllVacant";

class CRUDapplicationRouter {
  public router: Router;

  constructor() {
    this.router = Router();
    this.init()
  }

  public getAll(req: Request, res: Response, next: NextFunction) {
    findAllVacantPositions(req.query.year)
      .then(_.partial(onSuccess, res))
      // .then(_.partial(onSuccess, res))
      .catch(_.partial(onError, res, 'Find vacant positions failed'));
  }

  public getAll2(req: Request, res: Response, next: NextFunction) {
    findAllVacantPositions2(req.query.year)
        .then(_.partial(onSuccess, res))
        // .then(_.partial(onSuccess, res))
        .catch(_.partial(onError, res, 'Find vacant positions failed'));
  }

  public init() {
    this.router.get('/', this.getAll);
    this.router.get('/test', this.getAll2);
  }
}

export default new CRUDapplicationRouter().router


text:
package com.appglu.android.sync;

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

import junit.framework.Assert;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;

import com.appglu.StorageFile;
import com.appglu.Row;
import com.appglu.RowChanges;
import com.appglu.SyncOperation;
import com.appglu.TableVersion;
import com.appglu.android.sync.Column;
import com.appglu.android.sync.SQLiteSyncRepository;
import com.appglu.android.sync.SyncDatabaseHelper;
import com.appglu.android.sync.TableColumns;

public class SQLiteSyncRepositoryTest extends AbstractSyncSQLiteTest {

	private SQLiteSyncRepository syncRepository;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		this.syncRepository = new SQLiteSyncRepository(this.syncDatabaseHelper);
	}

	public void testVersionsForAllTables() {
		List<TableVersion> tableVersions = this.syncRepository.versionsForAllTables();
		this.assertTableVersions(tableVersions, 0, 1, 2);
	}

	public void testVersionsForTables() {
		List<String> tables = new ArrayList<String>();

		tables.add("appglu_storage_files");
		tables.add("logged_table");
		tables.add("other_table");

		List<TableVersion> tableVersions = this.syncRepository.versionsForTables(tables);
		this.assertTableVersions(tableVersions, 0, 1, 2);
	}

	public void testExecuteSyncOperation() {
		RowChanges rowChanges = this.getRowChanges();

		this.syncRepository.buildContentValuesRowMapper("other_table");
		boolean succeed = this.syncRepository.executeSyncOperation("other_table", rowChanges);
		Assert.assertTrue(succeed);
	}

	public void testExecuteSyncOperation_nullContentValuesRowMapper() {
		RowChanges rowChanges = this.getRowChanges();

		boolean succeed = this.syncRepository.executeSyncOperation("other_table", rowChanges);
		Assert.assertFalse(succeed);
	}

	public void testExecuteSyncOperation_emptySyncKey() {
		RowChanges rowChanges = this.getRowChanges();
		rowChanges.setSyncKey(0);

		this.syncRepository.buildContentValuesRowMapper("other_table");
		boolean succeed = this.syncRepository.executeSyncOperation("other_table", rowChanges);
		Assert.assertFalse(succeed);
	}

	public void testExecuteSyncOperation_emptyPrimaryKey() {
		RowChanges rowChanges = this.getRowChanges();
		rowChanges.getRow().putNull("id");

		this.syncRepository.buildContentValuesRowMapper("other_table");
		boolean succeed = this.syncRepository.executeSyncOperation("other_table", rowChanges);
		Assert.assertFalse(succeed);
	}

	public void testExecuteSyncOperation_emptyRow() {
		RowChanges rowChanges = this.getRowChanges();
		rowChanges.setRow(new Row());

		this.syncRepository.buildContentValuesRowMapper("other_table");
		boolean succeed = this.syncRepository.executeSyncOperation("other_table", rowChanges);
		Assert.assertFalse(succeed);
	}

	public void testExecuteSyncOperation_noPrimaryKey() {
		RowChanges rowChanges = this.getRowChanges();

		this.syncRepository.buildContentValuesRowMapper("no_primary_key");
		boolean succeed = this.syncRepository.executeSyncOperation("no_primary_key", rowChanges);
		Assert.assertFalse(succeed);
	}

	public void testExecuteSyncOperation_composePrimaryKey() {
		RowChanges rowChanges = this.getRowChanges();

		this.syncRepository.buildContentValuesRowMapper("compose_primary_key");
		boolean succeed = this.syncRepository.executeSyncOperation("compose_primary_key", rowChanges);
		Assert.assertFalse(succeed);
	}

	public void testExecuteSyncOperation_noLocalColumns() {
		Row row = new Row();
		row.put("foo", 1);

		RowChanges rowChanges = this.getRowChanges();
		rowChanges.setRow(row);

		this.syncRepository.buildContentValuesRowMapper("other_table");
		boolean succeed = this.syncRepository.executeSyncOperation("other_table", rowChanges);
		Assert.assertFalse(succeed);
	}

	private RowChanges getRowChanges() {
		Row row = new Row();

		row.put("id", 10);
		row.put("name", "name");

		RowChanges rowChanges = new RowChanges();
		rowChanges.setRow(row);

		rowChanges.setSyncKey(1);
		rowChanges.setSyncOperation(SyncOperation.INSERT);

		return rowChanges;
	}

	public void testInsertOperation() {
		int rowsBefore = this.countTable("other_table");

		ContentValues values = new ContentValues();

		values.put("id", 2);
		values.put("name", "name");

		this.syncRepository.insertOperation("other_table", values);

		int rowsAfterInsert = this.countTable("other_table");
		Assert.assertEquals(rowsBefore + 1, rowsAfterInsert);

		Map<String, String> row = this.queryForMap("select * from other_table where id = 2", new String[0]);

		Assert.assertEquals("2", row.get("id"));
		Assert.assertEquals("name", row.get("name"));
	}

	public void testUpdateOperation() {
		int rowsBefore = this.countTable("other_table");

		ContentValues values = new ContentValues();

		values.put("id", 1);
		values.put("name", "newValue");

		this.syncRepository.updateOperation("other_table", values, "id", "1");

		int rowsAfterUpdate = this.countTable("other_table");
		Assert.assertEquals(rowsBefore, rowsAfterUpdate);

		Map<String, String> row = this.queryForMap("select * from other_table where id = 1", new String[0]);

		Assert.assertEquals("1", row.get("id"));
		Assert.assertEquals("newValue", row.get("name"));
	}

	public void testDeleteOperation() {
		int rowsBefore = this.countTable("other_table");

		this.syncRepository.deleteOperation("other_table", "id", "1");

		int rowsAfterDelte = this.countTable("other_table");
		Assert.assertEquals(rowsBefore - 1, rowsAfterDelte);

		Map<String, String> row = this.queryForMap("select * from other_table where id = 1", new String[0]);
		Assert.assertTrue(row.isEmpty());
	}

	public void testSaveTableVersions() {
		this.syncRepository.saveTableVersion(new TableVersion("appglu_storage_files", 5));
		this.syncRepository.saveTableVersion(new TableVersion("logged_table", 4));
		this.syncRepository.saveTableVersion(new TableVersion("other_table", 10));

		List<TableVersion> updatedTables = this.syncRepository.versionsForAllTables();
		this.assertTableVersions(updatedTables, 5, 4, 10);
	}

	public void testColumnsForTable() {
		TableColumns tableColumns = this.syncRepository.columnsForTable("logged_table");

		Assert.assertEquals(2, tableColumns.size());

		Assert.assertTrue(tableColumns.hasSinglePrimaryKey());
		Assert.assertFalse(tableColumns.hasComposePrimaryKey());
		Assert.assertEquals("id", tableColumns.getSinglePrimaryKeyName());

		Column idColumn = tableColumns.get("id");

		Assert.assertEquals("id", idColumn.getName());
		Assert.assertEquals("integer", idColumn.getType());
		Assert.assertEquals(true, idColumn.isPrimaryKey());

		Column nameColumn = tableColumns.get("name");

		Assert.assertEquals("name", nameColumn.getName());
		Assert.assertEquals("varchar", nameColumn.getType());
		Assert.assertEquals(false, nameColumn.isPrimaryKey());
	}

	public void testColumnsForTable_NoPrimaryKey() {
		TableColumns tableColumns = this.syncRepository.columnsForTable("no_primary_key");

		Assert.assertFalse(tableColumns.hasSinglePrimaryKey());
		Assert.assertFalse(tableColumns.hasComposePrimaryKey());
	}

	public void testColumnsForTable_ComposePrimaryKey() {
		TableColumns tableColumns = this.syncRepository.columnsForTable("compose_primary_key");
		Assert.assertFalse(tableColumns.hasSinglePrimaryKey());
		Assert.assertTrue(tableColumns.hasComposePrimaryKey());
	}

	public void testAreForeignKeysEnabled() {
		Assert.assertFalse(this.syncRepository.areForeignKeysEnabled());

		SyncDatabaseHelper fkDatabaseHelper = new SyncDatabaseHelper(this.getContext(), "fk.sqlite", 1, true) {
			public void onCreateAppDatabase(SQLiteDatabase db) {
			}
			public void onUpgradeAppDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
			}
		};

		SQLiteSyncRepository fkEnabledRepository = new SQLiteSyncRepository(fkDatabaseHelper);
		Assert.assertTrue(fkEnabledRepository.areForeignKeysEnabled());

		fkDatabaseHelper.close();
	}

	public void testSetForeignKeysEnabled() {
		Assert.assertFalse(this.syncRepository.areForeignKeysEnabled());

		this.syncRepository.setForeignKeysEnabled(true);
		Assert.assertTrue(this.syncRepository.areForeignKeysEnabled());

		this.syncRepository.setForeignKeysEnabled(false);
		Assert.assertFalse(this.syncRepository.areForeignKeysEnabled());
	}

	public void testPrimaryKeyForSyncKey() {
		String primaryKey = this.syncRepository.primaryKeyForSyncKey(1, "other_table");
		Assert.assertEquals("1", primaryKey);
	}

	public void testSaveSyncMetadata() {
		int rowsBefore = this.countTable("appglu_sync_metadata");

		this.syncRepository.saveSyncMetadata(123, "logged_table", "456");

		int rowsAfterInsert = this.countTable("appglu_sync_metadata");
		Assert.assertEquals(rowsBefore + 1, rowsAfterInsert);

		String primaryKeyAfterInsert = this.syncRepository.primaryKeyForSyncKey(123, "logged_table");
		Assert.assertEquals("456", primaryKeyAfterInsert);

		this.syncRepository.saveSyncMetadata(123, "logged_table", "123");

		int rowsAfterUpdate = this.countTable("appglu_sync_metadata");
		Assert.assertEquals(rowsAfterInsert, rowsAfterUpdate);

		String primaryKeyAfterUpdate = this.syncRepository.primaryKeyForSyncKey(123, "logged_table");
		Assert.assertEquals("123", primaryKeyAfterUpdate);
	}

	public void testDeleteSyncMetadata() {
		int rowsBefore = this.countTable("appglu_sync_metadata");

		this.syncRepository.deleteSyncMetadata(1, "other_table");

		int rowsAfterDelete = this.countTable("appglu_sync_metadata");
		Assert.assertEquals(rowsBefore - 1, rowsAfterDelete);

		String primaryKeyAfterDelete = this.syncRepository.primaryKeyForSyncKey(1, "other_table");
		Assert.assertNull(primaryKeyAfterDelete);
	}

	public void testGetAllFiles() {
		List<StorageFile> files = this.syncRepository.getAllFiles();

		Assert.assertNotNull(files);
		Assert.assertEquals(2, files.size());

		StorageFile fileOne = files.get(0);
		this.assertFileOne(fileOne);
	}

	public void testGetStorageFileByIdOrUrl() {
		StorageFile fileOneById = this.syncRepository.getStorageFileByIdOrUrl(1001, null);
		this.assertFileOne(fileOneById);

		StorageFile fileOneByUrl = this.syncRepository.getStorageFileByIdOrUrl(0, "https://d27pqr4ityvq45.cloudfront.net/trekguide_staging/5cff0bf8-74ff-4a7a-9092-60841018b5ea-DS9-S01-E01-Grid-1.jpg");
		this.assertFileOne(fileOneByUrl);

		StorageFile fileOneByIdOrUrl = this.syncRepository.getStorageFileByIdOrUrl(1001, "https://d27pqr4ityvq45.cloudfront.net/trekguide_staging/5cff0bf8-74ff-4a7a-9092-60841018b5ea-DS9-S01-E01-Grid-1.jpg");
		this.assertFileOne(fileOneByIdOrUrl);
	}

	private void assertFileOne(StorageFile fileOne) {
		Assert.assertEquals(1001, fileOne.getId());
		Assert.assertEquals("1ee26276-b773-4eaa-9762-49c380e604c7", fileOne.getKey());
		Assert.assertEquals("app-icon.png", fileOne.getName());
		Assert.assertEquals("image/png", fileOne.getContentType());
		Assert.assertEquals("app-icon", fileOne.getTitle());
		Assert.assertEquals(10125, fileOne.getSize());
		Assert.assertEquals(1357309209000L, fileOne.getLastModified().getTime());
		Assert.assertEquals("https://d27pqr4ityvq45.cloudfront.net/trekguide_staging/5cff0bf8-74ff-4a7a-9092-60841018b5ea-DS9-S01-E01-Grid-1.jpg", fileOne.getUrl());
		Assert.assertEquals("abdca54e4ca831ec8013ef9f597adf1c", fileOne.getETag());
		Assert.assertEquals("2", fileOne.getVersion());
		Assert.assertEquals(1, fileOne.getDirectoryId());
	}

}


text:
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>

Overview

Add quiz

Results

Change password

Create admin user

<button class="btn btn-link navbar-link" ng-click="logout()">Log out ({{user.username}})</button>

	<form name="createUserForm" ng-submit="submitCreateUser()">

Create admin user

      This is a required field

			Username
			<input class="form-control" type="text" name="username" ng-model="createUser.username" placeholder="Username" required="required">

        This is a required field

        Password must be minimum 8 characters

			Password
			<input class="form-control" type="password" name="newPassword1" ng-model="createUser.newPassword1" placeholder="Password" required="required" ng-minlength=8>

        This is a required field

        Passwords do not match

			Repeat password
			<input class="form-control" type="password" name="newPassword2" ng-model="createUser.newPassword2" placeholder="Repeat password" required="required" ng-minlength=8>

		<button type="submit" class="btn btn-lg btn-primary" ng-disabled="!createUserForm.$valid">Submit</button>
	</form>


text:
FROM debian:wheezy
MAINTAINER gi4nks "gnlc.lupo@gmail.com"

# --------------------------
# Debian:wheezy
# ---
# - Subversion: 1.7
# - Git: distribution default
# - unzip: distribution default
# - wget: distribution default
# - rake: distribution default
# - telnet: distribution default
# - vim: distribution default
# - curl: distribution default
# - supervisor: distribution default
# --------------------------

# this is a non-interactive automated build - avoid some warning messages
ENV DEBIAN_FRONTEND noninteractive

# install additional libraries
RUN apt-get update --fix-missing -q && \
apt-get install -y -q unzip libc6-i386 lib32stdc++6 lib32gcc1 lib32ncurses5 lib32z1 psmisc wget rake supervisor postfix telnet  libxml2-utils software-properties-common mlocate vim curl iotop sysstat htop nmon python-software-properties git libxrender-dev libxtst-dev && \
apt-get install --only-upgrade bash && \
rm -rf /var/lib/apt/lists/* && \
apt-get clean

# Fix the subversion client to 1.7, cause the jenkins subversion plugin cannot read 1.8 checkouts
# http://askubuntu.com/questions/453717/i-need-downgrade-from-subversion-1-8-to-subversion-1-7
RUN wget -q -O - http://opensource.wandisco.com/wandisco-debian.gpg | apt-key add -
echo "deb http://opensource.wandisco.com/debian/ wheezy svn17" > /etc/apt/sources.list.d/wandisco-subversion.list && \
apt-get update && \
apt-get install subversion subversion-tools && \
rm -rf /var/lib/apt/lists/* && \
apt-get clean

# Define working directory.
WORKDIR /data