text:
package ecologylab.bigsemantics.generated.library.creativeWork;

import ecologylab.bigsemantics.generated.library.creativeWork.article.Article;
import ecologylab.bigsemantics.metadata.builtins.MetadataBuiltinsTypesScope;
import ecologylab.bigsemantics.metadata.scalar.MetadataString;
import ecologylab.bigsemantics.metametadata.MetaMetadataCompositeField;
import ecologylab.bigsemantics.namesandnums.SemanticsNames;
import ecologylab.serialization.annotations.simpl_inherit;
import ecologylab.serialization.annotations.simpl_scalar;
import java.lang.String;
import java.util.List;
import java.util.Map;

@simpl_inherit
public class NewsArticle extends Article
{
	@simpl_scalar
	private MetadataString publicationDate;

	@simpl_scalar
	private MetadataString subject;

	public NewsArticle()
	{ super(); }

	public NewsArticle(MetaMetadataCompositeField mmd) {
		super(mmd);
	}

	public MetadataString	publicationDate()
	{
		MetadataString	result = this.publicationDate;
		if (result == null)
		{
			result = new MetadataString();
			this.publicationDate = result;
		}
		return result;
	}

	public String getPublicationDate()
	{
		return this.publicationDate == null ? null : publicationDate().getValue();
	}

	public MetadataString getPublicationDateMetadata()
	{
		return publicationDate;
	}

	public void setPublicationDate(String publicationDate)
	{
		if (publicationDate != null)
			this.publicationDate().setValue(publicationDate);
	}

	public void setPublicationDateMetadata(MetadataString publicationDate)
	{
		this.publicationDate = publicationDate;
	}

	public MetadataString	subject()
	{
		MetadataString	result = this.subject;
		if (result == null)
		{
			result = new MetadataString();
			this.subject = result;
		}
		return result;
	}

	public String getSubject()
	{
		return this.subject == null ? null : subject().getValue();
	}

	public MetadataString getSubjectMetadata()
	{
		return subject;
	}

	public void setSubject(String subject)
	{
		if (subject != null)
			this.subject().setValue(subject);
	}

	public void setSubjectMetadata(MetadataString subject)
	{
		this.subject = subject;
	}
}


text:
  Saint-Brice est
       un village
       localisé dans le département de Mayenne en Pays de la Loire. On dénombrait 514 habitants en 2008.

Le nombre d'habitations, à Saint-Brice, se décomposait en 2011 en trois appartements et 249 maisons soit
 un marché relativement équilibré.

La commune propose quelques  équipements, elle propose entre autres un terrain de sport et une boucle de randonnée.

À proximité de Saint-Brice sont positionnées géographiquement les communes de
Beaumont-Pied-de-Boeuf à 5 km, 194 habitants,
Pincé localisée à 8 km, 196 habitants,
Grez-en-Bouère située à 6 km, 996 habitants,
Souvigné-sur-Sarthe à 5 km, 619 habitants,
Ballée à 8 km, 737 habitants,
Auvers-le-Hamon située à 8 km, 1 493 habitants,
 entre autres. De plus, Saint-Brice est située à seulement huit km de Sablé-sur-Sarthe.

Si vous envisagez de emmenager à Saint-Brice, vous pourrez facilement trouver une maison à vendre.

À Saint-Brice, le prix moyen à la vente d'un appartement s'évalue à 796 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 104 € du m². À la location la valorisation moyenne se situe à 5,97 € du m² mensuel.

redpajama_set_name: RedPajamaGithub


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150518_082133_add_multiworker_in_task extends Migration
{
    public function up()
    {

        $tableOptionsMyISAM = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=MyISAM';

        $this->createTable('{{%worker}}', [
            'worker_id' => Schema::TYPE_PK,
            'worker_task_id' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
            'worker_us_id' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT 0',
        ], $tableOptionsMyISAM);

        $this->createIndex('idx_worker_task_id', '{{%worker}}', 'worker_task_id');
        $this->createIndex('idx_worker_us_id', '{{%worker}}', 'worker_us_id');

        $sSql = 'Insert Into {{%worker}} (worker_task_id, worker_us_id) Select task_id As worker_task_id, task_worker_id As worker_us_id FROM {{%tasklist}} Where task_worker_id > 0';

        $nRec = Yii::$app->db->createCommand($sSql)->execute();

        echo "Inserted {$nRec} records\n\n";

        $this->refreshCache();
    }

    public function down()
    {
        $this->dropTable('{{%worker}}');
        $this->refreshCache();
        return true;
    }

    public function refreshCache()
    {
        Yii::$app->db->schema->refresh();
        Yii::$app->db->schema->getTableSchemas();
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
package dbconfig_test

import (
	"os"

	"github.com/improwised/cantaloupe/dbconfig"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Reading the Rails database yml file with default settings", func() {

	var dbConf dbconfig.DbConfig

	BeforeEach(func() {
		os.Setenv("POSTGRESQL_PASSWORD", "password")
		dbConf = dbconfig.LoadYamlConfig("test-files/database.yml")
	})

	It("should return the database name of the development environment", func() {
		Expect(dbConf["development"]["database"]).Should(Equal("blog_development"))
	})

	It("should return the database name of the production environment", func() {
		Expect(dbConf["production"]["statement_limit"]).Should(Equal("200"))
	})

	It("should return the get corresponding environment variable if defined in erb tags", func() {
		Expect(dbConf["test"]["password"]).Should(Equal("password"))
	})

})


text:
author: "Robert Pearce"
authorTwitter: "@RobertWPearce"
desc: "Two weeks ago today, I quit a rewarding and lucrative job without having another gig lined up. Oh, sh*t."
image: "/images/path.jpg"
keywords: "quitting your job, freelancing, healthcare, retirement accounts, technology, digital nomad"
title: "Turning A New Leaf"
---

Two weeks ago today, I quit a rewarding and lucrative job without having another gig lined up. Oh, sh\*t.

## The Immediate Aftermath
The following day consisted of my mind completely shutting down after being unable to answer the following questions:
* What do I do about health & dental insurance?
* How am I going to pay for life?
  * rent (in London)
  * food/house supplies
  * transportation
  * what if I break my leg?
  * what if I get [bit by a snake like Jules Weiss](http://www.medicaldaily.com/55000-snake-bite-has-uninsured-maryland-woman-jules-weiss-searching-options-anti-venom-costs-more) and get footed a $55,000 bill?
* Should I start looking for a new job?
* Should I get an actual undergrad degree in the industry I'm in? (how to afford this without debt?)
* Should I go to business school? (how to afford this without debt?)
* Am I in the right industry?
* Should I start over?

Apple's Healthkit app on my phone told me I walked _10 steps_ that day and not many more the next. Clearly, something had to be done.

## Organizing My Concerns
After a few days of lethargy and absorption of what I'd done and what had happened, my mind became restless and went back in to "solve all the things!" mode. When something feels like too big of a task, I remember what my father has asked me since childhood, _How do you eat an elephant? One bite at a time._ Now, I am not advocating for the consumption of elephants, but you get the point. It was time to break the problem of "What do I do next?" in to many smaller, solvable problems.

_Disclaimer: I am not an healthcare nor life expert; this is a story._

### Healthcare & Retirement Account(s)
When it comes to the unknown, humility is an asset, for you cannot possibly know everything about everything, so it's okay to ask people for help. If you're in this position, make sure you listen to your human resources contact at the company you're leaving, specifically
* how long your healthcare is covered for under their plan
* the details about making the COBRA election to extend your healthcare at your own cost
* if you have a high-deductible healthcare plan and have a health savings account (HSA) of your own, what can you do with this? How does that work, and where do I go from here with it? It is yours, but their advice is valuable.
* how you can rollover your retirement accounts in to other ones? (I have my own, managed via Schwab)

Additionally, consult your bank/brokerage firm/family/life liason about what your options are and what they think you need to do to ensure you are handling these things correctly. This is what I have been doing, and it is such a relief when someone can help you down your path.

### Paying for Life
Naturally, since I have no income until I either sell a product or do freelance work, expenses have had to be slashed. Eating out, pubs, entertainment, etc., are not great expenses until I add up their cost over a year. Rent, healthcare and car insurance are the major killers. There's no way I'd be able to even be thinking this way with a family to support, so I've got it relatively easy. Luckily, I saved up a bit of money before quitting, so I am cushioned for a little bit.

However, frugal is the word.

### What Do I Want and Need?
Once I got past the immediate financial and health issues I was able to start tackling the next question: _what do I want and need?_

I came up with potential paths to go down, sought advice from family and friends, and came up with the things I need in my life:
* be where I need to be (with my significant other after a year apart)
* recover from the mindset I've been in for the last 6 months and allow myself to change and not be defined by it
* level-up my programming skills and algorithmic knowledge
* make something that matters and which matters _to me_
* work for myself for a bit

There were so many other contenders that, after examing what mattered to me and defining what was just outside my sphere of knowledge and influence, didn't make sense for right now.

## Turning a New Leaf
Currently, I am spending my days focused on learning and working. Here's my routine:
* wake up, brew some tea or coffee
* light exercise
* solve coding problems on [CodeWars](http://www.codewars.com/)
* work on basic algebra/trig/geometry/calculus skills that I either don't remember or never learned via worksheets
* spend 4-5 hours on a MOOC (massive open online course)
* exercise
* spend the rest of the working day working on my own projects (or, eventually, freelance work)
* play my guitar and record music or a potential podcast
* enjoy life and friends

This daily routine allows me to get things done that matter to me, cut out the things that don't and make sure I stop and smell the flowers along the way.

## Thank Yous
Thank you Emily, my family, [Jason Vanderslice](https://twitter.com/javanderslice), [Marty Bauer](https://twitter.com/bauermarty), [James Dabbs](https://twitter.com/jamesdabbs) and the rest of you (you know who you are) for your guidance, encouragement and friendship.


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

<title>R: Utilities for flow cytometry</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="R.css" />

 Utilities for flow cytometry

Documentation for package ‘flowUtils’ version 1.42.0

DESCRIPTION file.

User guides, package vignettes and other documentation.

Help Pages

flowUtils-package
Utilities for flow cytometry data

flowUtils
Utilities for flow cytometry data

internal.read.gatingML
Function to parse a Gating-ML XML file into objects in the R environment

read.gatingML
Function to parse a Gating-ML XML file into objects in the R environment

testGatingMLCompliance
Function to perform all the Gating-ML compliance tests

write.gatingML
Function to write a Gating-ML XML file based on gating and transformation objects stored in an R environment.


text:
<?php
ob_start();
session_start();

require_once 'persona.php';

$login_button = '<button onclick="persona_login()" class="persona-button" >Sign in/ Sign up with Email</button>';
$logout_button = '<button onclick="persona_logout()" class="persona-button" >Sign out</button>';

$email = $body_button = $message = NULL;

if( isset($_SESSION['user_email']) && !empty($_SESSION['user_email']) )
{
    $body_button = $logout_button;
    $message = "
Logged In as ".$_SESSION['user_email']."
";
    $email = $_SESSION['user_email'];
}
else
{
    $body_button = $login_button;
}

?>

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Title of the document</title>
<link rel="stylesheet" type="text/css" href="persona-buttons.css">

<?php
echo $message;
echo $body_button;
?>


text:
import { combineReducers } from 'redux';
import extractControls from '@ringcentral-integration/phone-number/lib/extractControls';
import RcModule from '../../lib/RcModule';
import { Module } from '../../lib/di';
import callingModes from '../CallingSettings/callingModes';
import proxify from '../../lib/proxy/proxify';
import ensureExist from '../../lib/ensureExist';

import callActionTypes from './actionTypes';
import getCallReducer, {
  getLastPhoneNumberReducer,
  getLastRecipientReducer,
} from './getCallReducer';

import callStatus from './callStatus';
import callErrors from './callErrors';
import ringoutErrors from '../Ringout/ringoutErrors';
import validateNumbers from '../../lib/validateNumbers';

const TO_NUMBER = 'toNumber';
const FROM_NUMBER = 'fromNumber';
const ANONYMOUS = 'anonymous';

/**
 * @class
 * @description Call managing module
 */
@Module({
  deps: [
    'Alert',
    'Storage',
    'Brand',
    'Softphone',
    'Ringout',
    'NumberValidate',
    'RegionSettings',
    'CallingSettings',
    'RolesAndPermissions',
    { dep: 'Webphone', optional: true },
    { dep: 'AvailabilityMonitor', optional: true },
    { dep: 'CallOptions', optional: true },
  ],
})
export default class Call extends RcModule {
  /**
   * @constructor
   * @param {Object} params - params object
   * @param {Brand} params.brand - brand module instance
   * @param {Alert} params.alert - alert module instance
   * @param {Client} params.client - client module instance
   * @param {Storage} params.storage - storage module instance
   * @param {CallingSettings} params.callingSettings - callingSettings module instance
   * @param {Softphone} params.softphone - softphone module instance
   * @param {Ringout} params.ringout - ringout module instance
   * @param {Webphone} params.webphone - webphone module instance
   * @param {NumberValidate} params.numberValidate - numberValidate module instance
   * @param {RegionSettings} params.regionSettings - regionSettings module instance
   */
  constructor({
    alert,
    brand,
    storage,
    callingSettings,
    softphone,
    ringout,
    webphone,
    numberValidate,
    regionSettings,
    rolesAndPermissions,
    internationalCheck = true,
    permissionCheck = true,
    availabilityMonitor,
    ...options
  }) {
    super({
      ...options,
      actionTypes: callActionTypes,
    });

    this._brand = brand;

    this._alert = this::ensureExist(alert, 'alert');
    this._storage = this::ensureExist(storage, 'storage');
    this._storageKey = 'callData';
    this._reducer = getCallReducer(this.actionTypes);
    this._callingSettings = this::ensureExist(
      callingSettings,
      'callingSettings',
    );
    this._ringout = this::ensureExist(ringout, 'ringout');
    this._softphone = this::ensureExist(softphone, 'softphone');
    this._webphone = webphone;
    this._numberValidate = this::ensureExist(numberValidate, 'numberValidate');
    this._regionSettings = this::ensureExist(regionSettings, 'regionSettings');
    this._rolesAndPermissions = this::ensureExist(
      rolesAndPermissions,
      'rolesAndPermissions',
    );
    this._internationalCheck = internationalCheck;
    this._availabilityMonitor = availabilityMonitor;
    this._callSettingMode = null;
    this._permissionCheck = permissionCheck;

    this._storage.registerReducer({
      key: this._storageKey,
      reducer: combineReducers({
        lastPhoneNumber: getLastPhoneNumberReducer(this.actionTypes),
        lastRecipient: getLastRecipientReducer(this.actionTypes),
      }),
    });
  }

  initialize() {
    this.store.subscribe(() => this._onStateChange());
  }

  async _onStateChange() {
    if (this._shouldInit()) {
      this.store.dispatch({
        type: this.actionTypes.init,
      });
      this._initCallModule();
      this.store.dispatch({
        type: this.actionTypes.initSuccess,
      });
    } else if (this._shouldReset()) {
      this._resetCallModule();
    } else if (this.ready) {
      await this._processCall();
    }
  }

  _shouldInit() {
    return (
      this._numberValidate.ready &&
      this._callingSettings.ready &&
      this._storage.ready &&
      this._regionSettings.ready &&
      (!this._webphone || this._webphone.ready) &&
      (!this._availabilityMonitor || this._availabilityMonitor.ready) &&
      this._ringout.ready &&
      this._softphone.ready &&
      this._rolesAndPermissions.ready &&
      this.pending
    );
  }

  _shouldReset() {
    return (
      (!this._numberValidate.ready ||
        !this._callingSettings.ready ||
        !this._regionSettings.ready ||
        (!!this._webphone && !this._webphone.ready) ||
        (!!this._availabilityMonitor && !this._availabilityMonitor.ready) ||
        !this._ringout.ready ||
        !this._softphone.ready ||
        !this._rolesAndPermissions.ready ||
        !this._storage.ready) &&
      this.ready
    );
  }

  async _initCallModule() {
    this._callSettingMode = this._callingSettings.callingMode;
    if (this._callSettingMode === callingModes.webphone && this._webphone) {
      await this._webphone.connect();
    }
  }

  _resetCallModule() {
    this.store.dispatch({
      type: this.actionTypes.resetSuccess,
    });
    this._callSettingMode = this._callingSettings.callingMode;
    if (this._callSettingMode === callingModes.webphone && this._webphone) {
      this._webphone.disconnect();
    }
  }

  async _processCall() {
    const oldCallSettingMode = this._callSettingMode;
    if (
      this._callingSettings.callingMode !== oldCallSettingMode &&
      this._webphone
    ) {
      this._callSettingMode = this._callingSettings.callingMode;
      if (oldCallSettingMode === callingModes.webphone) {
        this._webphone.disconnect();
      } else if (this._callSettingMode === callingModes.webphone) {
        await this._webphone.connect();
      }
    }
  }

  @proxify
  async onToNumberChange(value) {
    this.store.dispatch({
      type: this.actionTypes.toNumberChanged,
      data: value,
    });
  }

  // save the click to dial entity, only when call took place
  onToNumberMatch({ entityId, startTime }) {
    if (this.isIdle) {
      this.store.dispatch({
        type: this.actionTypes.toNumberMatched,
        data: { entityId, startTime },
      });
    }
  }

  cleanToNumberEntities() {
    this.store.dispatch({
      type: this.actionTypes.cleanToNumberEntities,
    });
  }

  @proxify
  async call({
    phoneNumber: input,
    recipient,
    fromNumber,
    isConference = false,
  }) {
    let session = null;
    if (this.isIdle) {
      const { phoneNumber, extendedControls } = extractControls(input);
      const toNumber =
        (recipient && (recipient.phoneNumber || recipient.extension)) ||
        phoneNumber;
      if (!toNumber || `${toNumber}`.trim().length === 0) {
        this._alert.warning({
          message: callErrors.noToNumber,
        });
      } else {
        this.store.dispatch({
          type: this.actionTypes.connect,
          isConference,
          phoneNumber,
          recipient,
          callSettingMode: this._callSettingMode, // for Track
        });
        try {
          let validatedNumbers;
          if (this._permissionCheck) {
            validatedNumbers = await this._getValidatedNumbers({
              toNumber,
              fromNumber,
              isConference,
            });
          } else {
            validatedNumbers = this._getNumbers({
              toNumber,
              fromNumber,
              isConference,
            });
          }
          if (validatedNumbers) {
            session = await this._makeCall({
              ...validatedNumbers,
              extendedControls,
            });
            this.store.dispatch({
              type: this.actionTypes.connectSuccess,
              callSettingMode: this._callSettingMode, // for Track
            });
          } else {
            this.store.dispatch({
              type: this.actionTypes.connectError,
            });
          }
        } catch (error) {
          if (!error.message && error.type && callErrors[error.type]) {
            // validate format error
            this._alert.warning({
              message: callErrors[error.type],
              payload: {
                phoneNumber: error.phoneNumber,
              },
            });
          } else if (error.message === ringoutErrors.firstLegConnectFailed) {
            this._alert.warning({
              message: callErrors.connectFailed,
              payload: error,
            });
          } else if (error.message === 'Failed to fetch') {
            this._alert.danger({
              message: callErrors.networkError,
              payload: error,
            });
          } else if (error.message !== 'Refresh token has expired') {
            if (
              !this._availabilityMonitor ||
              !this._availabilityMonitor.checkIfHAError(error)
            ) {
              this._alert.danger({
                message: callErrors.internalError,
                payload: error,
              });
            }
          }
          this.store.dispatch({
            type: this.actionTypes.connectError,
          });
          throw error;
        }
      }
    }
    return session;
  }

  @proxify
  _getNumbers({ toNumber, fromNumber, isConference }) {
    const isWebphone =
      this._callingSettings.callingMode === callingModes.webphone;
    const theFromNumber =
      fromNumber ||
      (isWebphone
        ? this._callingSettings.fromNumber
        : this._callingSettings.myLocation);

    if (isWebphone && (theFromNumber === null || theFromNumber === '')) {
      return null;
    }

    const waitingValidateNumbers = [];

    if (!isConference) {
      waitingValidateNumbers.push({
        type: TO_NUMBER,
        number: toNumber,
      });
    }

    if (
      theFromNumber &&
      theFromNumber.length > 0 &&
      !(isWebphone && theFromNumber === ANONYMOUS)
    ) {
      waitingValidateNumbers.push({
        type: FROM_NUMBER,
        number: theFromNumber,
      });
    }

    let parsedToNumber;
    let parsedFromNumber;

    if (waitingValidateNumbers.length) {
      const numbers = waitingValidateNumbers.map((x) => x.number);
      const validatedResult = validateNumbers(
        numbers,
        this._regionSettings,
        this._brand.id,
      );
      const toNumberIndex = waitingValidateNumbers.findIndex(
        (x) => x.type === TO_NUMBER,
      );
      const fromNumberIndex = waitingValidateNumbers.findIndex(
        (x) => x.type === FROM_NUMBER,
      );
      parsedToNumber = validatedResult[toNumberIndex];
      parsedFromNumber = validatedResult[fromNumberIndex];
    }
    if (isWebphone && theFromNumber === ANONYMOUS) {
      parsedFromNumber = ANONYMOUS;
    }
    return {
      toNumber: parsedToNumber || toNumber,
      fromNumber: parsedFromNumber,
    };
  }

  @proxify
  async _getValidatedNumbers({ toNumber, fromNumber, isConference }) {
    const isWebphone =
      this._callingSettings.callingMode === callingModes.webphone;
    const theFromNumber =
      fromNumber ||
      (isWebphone
        ? this._callingSettings.fromNumber
        : this._callingSettings.myLocation);

    if (isWebphone && (theFromNumber === null || theFromNumber === '')) {
      return null;
    }

    const waitingValidateNumbers = [];

    if (!isConference) {
      waitingValidateNumbers.push({
        type: TO_NUMBER,
        number: toNumber,
      });
    }

    if (
      theFromNumber &&
      theFromNumber.length > 0 &&
      !(isWebphone && theFromNumber === ANONYMOUS)
    ) {
      waitingValidateNumbers.push({
        type: FROM_NUMBER,
        number: theFromNumber,
      });
    }

    let parsedToNumber;
    let parsedFromNumber;
    if (waitingValidateNumbers.length) {
      const numbers = waitingValidateNumbers.map((x) => x.number);
      const validatedResult = await this._numberValidate.validateNumbers(
        numbers,
      );
      if (!validatedResult.result) {
        validatedResult.errors.forEach((error) => {
          // this._alert.warning({
          //   message: callErrors[error.type],
          //   payload: {
          //     phoneNumber: error.phoneNumber
          //   }
          // });
          throw error;
        });
        return null;
      }
      const toNumberIndex = waitingValidateNumbers.findIndex(
        (x) => x.type === TO_NUMBER,
      );
      const fromNumberIndex = waitingValidateNumbers.findIndex(
        (x) => x.type === FROM_NUMBER,
      );
      parsedToNumber = validatedResult.numbers[toNumberIndex];
      parsedFromNumber = validatedResult.numbers[fromNumberIndex];
    }
    if (this._internationalCheck) {
      if (
        parsedToNumber &&
        parsedToNumber.international &&
        !this._rolesAndPermissions.permissions.InternationalCalls
      ) {
        const error = {
          phoneNumber: parsedToNumber.originalString,
          type: 'noInternational',
        };
        throw error;
      }
    }

    let parsedToNumberE164 = toNumber;
    if (parsedToNumber) {
      parsedToNumberE164 = parsedToNumber.e164;
      // add ext back if any
      if (parsedToNumber.e164 && parsedToNumber.subAddress) {
        parsedToNumberE164 = [
          parsedToNumber.e164,
          parsedToNumber.subAddress,
        ].join('*');
      }
    }

    // using e164 in response to call
    let parsedFromNumberE164;
    if (parsedFromNumber) {
      parsedFromNumberE164 = parsedFromNumber.e164;
      // add ext back if any
      if (parsedFromNumber.e164 && parsedFromNumber.subAddress) {
        parsedFromNumberE164 = [
          parsedFromNumber.e164,
          parsedFromNumber.subAddress,
        ].join('*');
      }
    }
    if (isWebphone && theFromNumber === ANONYMOUS) {
      parsedFromNumberE164 = ANONYMOUS;
    }
    return {
      toNumber: parsedToNumberE164,
      fromNumber: parsedFromNumberE164,
    };
  }

  @proxify
  async _makeCall({
    toNumber,
    fromNumber,
    callingMode = this._callingSettings.callingMode,
    extendedControls = [],
  }) {
    const homeCountryId = this._regionSettings.homeCountryId;
    let session;
    switch (callingMode) {
      case callingModes.softphone:
        session = this._softphone.makeCall(toNumber);
        break;
      case callingModes.ringout:
        session = await this._ringout.makeCall({
          fromNumber,
          toNumber: toNumber && toNumber.split('*')[0], // remove extension number in ringout mode
          prompt: this._callingSettings.ringoutPrompt,
        });
        break;
      case callingModes.webphone:
        if (this._webphone) {
          session = await this._webphone.makeCall({
            fromNumber,
            toNumber,
            homeCountryId,
            extendedControls,
          });
        }
        break;
      default:
        break;
    }
    return session;
  }

  get status() {
    return this.state.status;
  }

  get callStatus() {
    return this.state.callStatus;
  }

  get isIdle() {
    return this.state.callStatus === callStatus.idle;
  }

  get lastPhoneNumber() {
    return this._storage.getItem(this._storageKey).lastPhoneNumber;
  }

  get lastRecipient() {
    return this._storage.getItem(this._storageKey).lastRecipient;
  }

  get toNumber() {
    return this.state.toNumber;
  }

  get toNumberEntities() {
    return this.state.toNumberEntities;
  }
}


text:
package commands

import (
	"context"
	"encoding/json"
	"os"
	"time"

	"github.com/hyperledger/burrow/core"
	"github.com/hyperledger/burrow/dump"
	"github.com/hyperledger/burrow/logging/logconfig"
	"github.com/hyperledger/burrow/rpc/rpcdump"
	"github.com/hyperledger/burrow/rpc/rpcquery"
	cli "github.com/jawher/mow.cli"
	"google.golang.org/grpc"
)

type dumpOptions struct {
	height            *int
	filename          *string
	useBinaryEncoding *bool
}

func addDumpOptions(cmd *cli.Cmd, specOptions ...string) *dumpOptions {
	cmd.Spec += "[--height=<state height to dump at>] [--binary]"
	for _, spec := range specOptions {
		cmd.Spec += " " + spec
	}
	cmd.Spec += " FILE"
	return &dumpOptions{
		height:            cmd.IntOpt("h height", 0, "Block height to dump to, defaults to latest block height"),
		useBinaryEncoding: cmd.BoolOpt("b binary", false, "Output in binary encoding (default is JSON)"),
		filename:          cmd.StringArg("FILE", "", "Save dump here"),
	}
}

// Dump saves the state from a remote chain
func Dump(output Output) func(cmd *cli.Cmd) {
	return func(cmd *cli.Cmd) {
		cmd.Command("local", "create a dump from local Burrow directory", func(cmd *cli.Cmd) {
			output.Logf("dumping from local Burrow dir")
			configFileOpt := cmd.String(configFileOption)
			genesisFileOpt := cmd.String(genesisFileOption)

			dumpOpts := addDumpOptions(cmd, configFileSpec, genesisFileSpec)

			cmd.Action = func() {
				conf, err := obtainDefaultConfig(*configFileOpt, *genesisFileOpt)
				if err != nil {
					output.Fatalf("could not obtain config: %v", err)
				}

				kern, err := core.NewKernel(conf.BurrowDir)
				if err != nil {
					output.Fatalf("could not create burrow kernel: %v", err)
				}

				err = kern.LoadState(conf.GenesisDoc)
				if err != nil {
					output.Fatalf("could not load burrow state: %v", err)
				}

				// Include all logging by default
				logger, err := logconfig.New().NewLogger()
				if err != nil {
					output.Fatalf("could not make logger: %v", err)
				}

				source := dump.NewDumper(kern.State, kern.Blockchain).WithLogger(logger).
					Source(0, uint64(*dumpOpts.height), dump.All)

				err = dumpToFile(*dumpOpts.filename, source, *dumpOpts.useBinaryEncoding)
				if err != nil {
					output.Fatalf("could not dump to file %s': %v", *dumpOpts.filename, err)
				}
				output.Logf("dump successfully written to '%s'", *dumpOpts.filename)
			}
		})

		cmd.Command("remote", "pull a dump from a remote Burrow node", func(cmd *cli.Cmd) {
			chainURLOpt := cmd.StringOpt("c chain", "127.0.0.1:10997", "chain to be used in IP:PORT format")
			timeoutOpt := cmd.IntOpt("t timeout", 0, "Timeout in seconds")
			dumpOpts := addDumpOptions(cmd, "[--chain=<chain GRPC address>]",
				"[--timeout=<GRPC timeout seconds>]")

			cmd.Action = func() {
				output.Logf("dumping from remote chain at %s", *chainURLOpt)

				ctx, cancel := context.WithCancel(context.Background())
				if *timeoutOpt != 0 {
					timeout := time.Duration(*timeoutOpt) * time.Second
					ctx, cancel = context.WithTimeout(context.Background(), timeout)
				}
				defer cancel()

				var opts []grpc.DialOption
				opts = append(opts, grpc.WithInsecure())
				conn, err := grpc.DialContext(ctx, *chainURLOpt, opts...)
				if err != nil {
					output.Fatalf("failed to connect: %v", err)
				}

				qCli := rpcquery.NewQueryClient(conn)
				chainStatus, err := qCli.Status(context.Background(), &rpcquery.StatusParam{})
				if err != nil {
					output.Logf("could not get chain status: %v", err)
				}
				stat, err := json.Marshal(chainStatus)
				if err != nil {
					output.Logf("failed to marshal: %v", err)
				}
				output.Logf("dumping from chain: %s", string(stat))

				dc := rpcdump.NewDumpClient(conn)
				receiver, err := dc.GetDump(ctx, &rpcdump.GetDumpParam{Height: uint64(*dumpOpts.height)})
				if err != nil {
					output.Fatalf("failed to retrieve dump: %v", err)
				}

				err = dumpToFile(*dumpOpts.filename, receiver, *dumpOpts.useBinaryEncoding)
				if err != nil {
					output.Fatalf("could not dump to file %s': %v", *dumpOpts.filename, err)
				}
				output.Logf("dump successfully written to '%s'", *dumpOpts.filename)

			}
		})
	}
}

func dumpToFile(filename string, source dump.Source, useBinaryEncoding bool) error {
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return err
	}

	// Receive
	err = dump.Write(f, source, useBinaryEncoding, dump.All)
	if err != nil {
		return err
	}

	err = f.Close()
	if err != nil {
		return err
	}
	return nil
}


text:
class AdminAssistant
  class PaperclipColumn < Column
    attr_reader :name

    def initialize(name)
      @name = name.to_s
    end

    def contains?(column_name)
      column_name.to_s == @name ||
      column_name.to_s =~
          /^#{@name}_(file_name|content_type|file_size|updated_at)$/
    end

    class View < AdminAssistant::Column::View
      def image_html(record)
        @action_view.image_tag record.send(@column.name).url
      end
    end

    class FormView < View
      include AdminAssistant::Column::FormViewMethods

      def default_html(form)
        form.file_field name
      end
    end

    class IndexView < View
      include AdminAssistant::Column::IndexViewMethods

      def html(record)
        image_html record
      end
    end

    class ShowView < View
      include AdminAssistant::Column::ShowViewMethods

      def html(record)
        image_html record
      end
    end
  end
end


text:
/**
 * Created by hans on 18.09.15.
 */
var requests = (function () {
    var runtime;

    var ACTIONS = {
        RENDER_MAP: "RENDER_MAP",
        UPDATE_COURSE_HISTORY: "UPDATE_COURSE_HISTORY",
        RENDER_COURSE_HISTORY: "RENDER_COURSE_HISTORY",
        RENDER_REMINDER: "RENDER_REMINDER",
        CREATE_REMINDER: "CREATE_REMINDER"
    };

    var init = function (chromeRuntime) {
        runtime = chromeRuntime;
    };

    var renderMap = function (data, callback) {
        runtime.sendMessage(
            {action: ACTIONS.RENDER_MAP, data: data}, function (result) {
                callback(result)
            });
    };

    var renderHistory = function (data, callback) {
        runtime.sendMessage(
            {action: ACTIONS.RENDER_COURSE_HISTORY, data: data}, function (result) {
                callback(result);
            });
    };

    var updateHistory = function(data, callback){
        runtime.sendMessage( {
            action: ACTIONS.UPDATE_COURSE_HISTORY,
            data: data}, function(result) {
                callback(result)
        })
    };

    var renderReminder = function (callback) {
        runtime.sendMessage(
            {action: ACTIONS.RENDER_REMINDER}, function (result) {
                callback(result);
            }
        )
    };

    var createReminder = function (data, callback) {
        runtime.sendMessage({
            action: ACTIONS.CREATE_REMINDER, data: data
        }, function (result) {
            callback(result)

        })
    };

    return {
        ACTIONS: ACTIONS,
        init: init,
        renderMap: renderMap,
        updateHistory: updateHistory,
        renderHistory: renderHistory,
        renderReminder: renderReminder,
        createReminder: createReminder
    };
}());


text:
namespace StorageAdapters.InMemory
{
    public class InMemoryStorageAdapter : StorageAdapterBase<InMemoryStorageService, InMemoryConfiguration>
    {
        public InMemoryStorageAdapter(InMemoryConfiguration configuration) : base(configuration)
        { }
    }
}


text:
extern crate libc;
extern crate efreet_sys;
extern crate eina_sys;

use libc::*;
use efreet_sys::Efreet_Uri;
use eina_sys::Eina_List;

/* automatically generated by rust-bindgen */

#[link(name = "efreet_trash")]
extern "C" {
    pub fn efreet_trash_init() -> c_int;
    pub fn efreet_trash_shutdown() -> c_int;
    pub fn efreet_trash_dir_get(for_file: *const c_char)
     -> *const c_char;
    pub fn efreet_trash_delete_uri(uri: *mut Efreet_Uri,
                                   force_delete: c_int)
     -> c_int;
    pub fn efreet_trash_ls() -> *mut Eina_List;
    pub fn efreet_trash_is_empty() -> c_int;
    pub fn efreet_trash_empty_trash() -> c_int;
}


text:
@interface NSFileManager (GF)

- (unsigned long long)sizeOfFolder:(NSString *)folderPath;

- (NSString *)stringSizeOfFolder:(NSString *)folderPath;

@end


text:
<!DOCTYPE html>

	<title>Integration with dhtmlxTreeGrid</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>


text:
module Main where

import Graphics.Blank

main = blankCanvas 3000 $ \ context -> loop context (0 :: Float)

loop context n = do
        send context $ do
                -- clear the canvas
                ...
                -- draw the square
                ...

        loop context (n + 0.01)


text:
namespace _06.Animals
{
    using System;

    class Frog : Animal
    {
        public Frog(string name, int age, string gender)
            : base(name, age, gender)
        {
        }

        public override void ProduceSound()
        {
            Console.WriteLine("Frogggg");
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Kachuwa.Caching;
using Kachuwa.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Kachuwa.State;
using Newtonsoft.Json;

namespace Kachuwa.Storage
{
    public class LocalStorageProvider : IStorageProvider
    {
        private readonly string _filePath;
        private readonly IFileOptions _fileOptions;
        private readonly IKeyGenerator _keyGenerator;
        private readonly IWebHostEnvironment _environment;
        // private readonly ICacheService _cachingService;
       // private static Dictionary<string, FileSession> keys { get; set; } = new Dictionary<string, FileSession>();

        public LocalStorageProvider(IFileOptions fileOptions, IKeyGenerator keyGenerator, IWebHostEnvironment environment, ICacheService cachingService)
        {
            _fileOptions = fileOptions;
            _keyGenerator = keyGenerator;
            _environment = environment;
            // _cachingService = cachingService;
            string rootpath = environment.WebRootPath;
            _filePath = Path.Combine(rootpath, _fileOptions.Path);
            RootPath = _filePath;
        }

        public string GetTempPath()
        {
            return Path.Combine(_environment.WebRootPath, "temp", _keyGenerator.GetKey());
        }
        public string GetTempChunkedPath()
        {
            return Path.Combine(_environment.WebRootPath, "temp", "chuncked");
        }

        public string GetTempRelativePath()
        {
            return Path.Combine("temp", _keyGenerator.GetKey());
        }

        public string RootPath { get; set; }
        public async Task<IFile> GetFile(string filePath)
        {
            if (File.Exists(filePath))
            {

                using (var f = File.OpenRead(filePath))
                {
                    var ms = new MemoryStream();
                    await f.CopyToAsync(ms);
                    ms.Seek(0, SeekOrigin.Begin);

                    return new KachuwaFile()
                    {
                        ContentType = ExtensionToContentType(Path.GetExtension(filePath).TrimStart('.'), _fileOptions),
                        Stream = ms
                    };
                }
            }
            else
            {
                throw new Exception("file Not found");
            }
        }

        public Task<bool> Delete(string dirPath, string filePath)
        {
            string physicallPath = CheckOrCreateDirectory(dirPath).Result;
            var path = Path.Combine(physicallPath, filePath);
            if (File.Exists(path))
                File.Delete(path);
            return Task.FromResult(true);
        }

        public Task<bool> Delete(string filePath)
        {
            var physicalPath = "";
            if (filePath.StartsWith("/"))
            {
                filePath = filePath.TrimStart('/').Replace("/", "\\");
                physicalPath = Path.Combine(RootPath, filePath);
            }
            if (File.Exists(physicalPath))
                File.Delete(physicalPath);
            return Task.FromResult(true);
        }

        public void CopyStream(Stream stream, string destPath)
        {
            using (var fileStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
            {
                stream.CopyTo(fileStream);
            }
        }

        public Task<string> Save(IFormFile file)
        {
            IFormFile myFile = file;
            string rootpath = _environment.WebRootPath;
            string folderPath = _filePath;//Path.Combine(rootpath, "Uploads");
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);
            var tempFolderName = Path.GetTempFileName();
            string fileName = $"{_keyGenerator.GetKey()}.{ ContentTypeToExtension(myFile.ContentType, _fileOptions)}";// myFile.FileName;
            string physicalfilepath = folderPath + "\\" + fileName;
            var relativePath = Path.Combine(_fileOptions.Path, fileName);//uploads
            relativePath = relativePath.Replace("\\", "/").Replace(@"\", "/");
            if (!relativePath.StartsWith("/"))
            {
                relativePath = "/" + relativePath;
            }
            if (myFile != null && myFile.Length != 0)
            {

                try
                {
                    CopyStream(myFile.OpenReadStream(), physicalfilepath);
                    return Task.FromResult(relativePath);

                }
                catch (Exception ex)
                {
                    throw ex;
                }
                //}
            }
            return Task.FromResult("");
        }

        public async Task<string> SaveFile(string filePath, string contentType, Stream stream)
        {
            filePath = filePath.Replace(@"/", @"\\");
            string folder = await CheckOrCreateDirectory(filePath);
            string fileName = $"{_keyGenerator.GetKey()}.{ ContentTypeToExtension(contentType, _fileOptions)}";// myFile.FileName;

            string physicalfilepath = folder + "\\" + fileName;
            var relativePath = Path.Combine(_fileOptions.Path, filePath, fileName);//uploads
            relativePath = relativePath.Replace("\\", "/").Replace(@"\", "/");
            if (!relativePath.StartsWith("/"))
            {
                relativePath = "/" + relativePath;
            }
            using (var f = File.OpenWrite(physicalfilepath))
            {
                var buffer = new byte[8 * 1024];
                int len;
                while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    await f.WriteAsync(buffer, 0, len);
                }
            }

            return relativePath;
        }

        public Task<string> CheckOrCreateDirectory(string path)
        {
            string rootpath = _environment.WebRootPath;
            string folderPath = Path.Combine(rootpath, _fileOptions.Path, path);
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);
            return Task.FromResult(folderPath);
        }

        public async Task<string> Save(string dirPath, IFormFile file)
        {
            string physicallPath = await CheckOrCreateDirectory(dirPath);
            IFormFile myFile = file;
            string fileName = $"{_keyGenerator.GetKey()}.{ ContentTypeToExtension(myFile.ContentType, _fileOptions)}";// myFile.FileName;

            string physicalfilepath = physicallPath + "\\" + fileName;
            var relativePath = Path.Combine(_fileOptions.Path, dirPath, fileName);
            relativePath = relativePath.Replace("\\", "/").Replace(@"\", "/");
            if (!relativePath.StartsWith("/"))
            {
                relativePath = "/" + relativePath;
            }
            if (myFile != null && myFile.Length != 0)
            {

                try
                {
                    CopyStream(myFile.OpenReadStream(), physicalfilepath);
                    return relativePath;

                }
                catch (Exception ex)
                {
                    throw ex;
                }
                //}
            }
            return string.Empty;
        }

        private string ExtensionToContentType(string extension, IFileOptions options)
        {
            if (options.AllowedTypes != null)
            {
                foreach (var allowedImageType in options.AllowedTypes)
                {
                    if (extension.Equals(allowedImageType.FileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        return allowedImageType.ContentType;
                    }
                }
            }

            throw new Exception("Unsupported extension.");
        }

        private string ContentTypeToExtension(string contentType, IFileOptions options)
        {
            if (options.AllowedTypes != null)
            {
                foreach (var allowedImageType in options.AllowedTypes)
                {
                    if (contentType.Equals(allowedImageType.ContentType, StringComparison.OrdinalIgnoreCase))
                    {
                        return allowedImageType.FileExtension;
                    }
                }
            }

            throw new Exception("Unsupported content type.");
        }

        private const int CHUNK_LIMIT = 1024 * 1024;

        #region Chunked File upload
        public FileSession CreateSession(long user, string fileName, int chunkSize, long fileSize)
        {
            if (String.IsNullOrWhiteSpace(fileName))
                throw new BadRequestException("File name missing");

            if (chunkSize > CHUNK_LIMIT)
                throw new BadRequestException(String.Format("Maximum chunk size is {0} bytes", CHUNK_LIMIT));

            if (chunkSize < 1)
                throw new BadRequestException("Chunk size must be greater than zero");

            if (fileSize < 1)
                throw new BadRequestException("Total size must be greater than zero");

            FileSession session = new FileSession(user, new FileInformation(fileSize, fileName, chunkSize));

            //if (keys.TryGetValue()[session.Id] == null)
            //  keys.Add(session.Id, session);
            // return _cachingService.Get(session.Id,60*60, () => session);

            if (!Directory.Exists(Path.Combine(GetTempChunkedPath(), session.Id)))
            {
                Directory.CreateDirectory(Path.Combine(GetTempChunkedPath(), session.Id));
                File.WriteAllText(Path.Combine(GetTempChunkedPath(), session.Id, "session.json"),
                    JsonConvert.SerializeObject(session));
            }
            return session;

        }

        public FileSession GetSession(string id)
        {
            if (Directory.Exists(Path.Combine(GetTempChunkedPath(), id)))
            {

               var json= File.ReadAllText(Path.Combine(GetTempChunkedPath(), id, "session.json"));
               return JsonConvert.DeserializeObject<FileSession>(json);
            }

            return null;

        }

        public List<FileSession> GetAllSessions()
        {
            var list = new List<FileSession>();
            foreach (var key in Directory.GetFiles(Path.Combine(GetTempChunkedPath()), "*session.json", SearchOption.AllDirectories))
            {
                try
                {
                    var json = File.ReadAllText(key);
                    var file= JsonConvert.DeserializeObject<FileSession>(json);
                    list.Add(file);
                }
                catch (Exception e)
                {

                }

            }

            return list;
        }

        public void PersistBlock(string sessionId, long userId, int chunkNumber, byte[] buffer)
        {
            FileSession session = GetSession(sessionId);

            try
            {
                if (session == null)
                {
                    throw new NotFoundException("Session not found");
                }

                Persist(sessionId, chunkNumber, buffer);

                session.FileInfo.MarkChunkAsPersisted(chunkNumber);
                session.RenewTimeout();
                // _cachingService.Get(session.Id, 60 * 60, () => session);

                //keys[session.Id] = session;
                File.WriteAllText(Path.Combine(GetTempChunkedPath(), sessionId, "session.json"),
                    JsonConvert.SerializeObject(session));
            }
            catch (System.Exception e)
            {
                if (session != null)
                    session.MaskAsFailed();

                throw e;
            }
        }

        public void WriteToStream(Stream stream, FileSession session)
        {
            using (var sw = new BinaryWriter(stream))
            {
                for (int i = 1; i <= session.FileInfo.TotalNumberOfChunks; i++)
                {
                    sw.Write(Read(session.Id, i));
                }
            }

            stream.Flush();

        }

        public Stream GetFileStream(FileSession session)
        {
            return new ChunkedFileStream(this, session);

        }

        public async void Persist(string id, int chunkNumber, byte[] buffer)
        {
            string chunkDestinationPath = Path.Combine(GetTempChunkedPath(), id);

            if (!Directory.Exists(chunkDestinationPath))
            {
                Directory.CreateDirectory(chunkDestinationPath);
            }

            string path = Path.Combine(GetTempChunkedPath(), id, chunkNumber.ToString());
            await File.WriteAllBytesAsync(path, buffer);
        }

        public byte[] Read(string id, int chunkNumber)
        {
            string targetPath = Path.Combine(GetTempChunkedPath(), id, chunkNumber.ToString());
            return File.ReadAllBytes(targetPath);
        }

        #endregion
    }
}


text:
package merlin.ianusinc.ianusinchq;

/**
 * Created by Seine Eiligkeit on 29.06.2017.
 */
public class Reference {
    public static final String MODID = "ianusinchq";
    public static final String NAME = "Ianus Inc HQ";
    public static final String VERSION = "0.0.1";

    public static final String COMMONPROXY ="merlin.ianusinc.ianusinchq.proxy.CommonProxy";
    public static final String CLIENTPROXY ="merlin.ianusinc.ianusinchq.proxy.ClientProxy";
}


text:
<?php

namespace Autoload;

require_once(__DIR__."/AutoloadException.php");
require_once(__DIR__."/ClassFileOperations.php");
require_once(__DIR__."/../Singleton.php");
require_once(__DIR__."/../Globals.php");

use Autoload\Autoloader;
use Autoload\AutoloadException;
use Autoload\ClassFileOperations;
use Singleton;
use Globals;

class NSObject {
	public $type;
	public $nsname;
	public $name;
	public $code;
	public $ls;
	public $le;
	public $file;
	public $extern;
}

class ArgumentObject {
	public $type;
	public $name;
	public $default;
	public function __construct($t,$n,$d){
		$this->type = $t;
		$this->name = $n;
		$this->default = $d;
	}
	public function toString() {
		return "{$this->type} {$this->name}".($this->default!=""?" = {$this->default}":"");
	}
}

class ClassObject extends NSObject {
	public function toString() {
		$code = strlen($this->extern)?$this->extern."\n":"";
		$code .= "class {$this->name}";
		$code .= substr($this->code,strpos($this->code,"{"))."\n";
		return $code;
	}
}

class FunctionObject extends NSObject {
	public $arguments;
	public function toString() {
		$code = $this->extern."\n";
		$code .= "function {$this->name}";
		$code .= "(".implode(",",array_map(function($arg){return $arg->toString();},$this->arguments)).")\n";
		$code .= substr($this->code,strpos($this->code,"{"))."\n";
		return $code;
	}
}

use Autoload\ArgumentObject;
use Autoload\ClassObject;
use Autoload\FunctionObject;

class ClassFileOperations {

	use Singleton;

	const space = __DIR__."/Space/";

	private $file;
	private $code;
	private $mtime;
	private $structure;
	private $pragmas;
	private $nocollect = false;

	private function __construct(){}

	static public function __callStatic($name,array $arguments){
		if(0 != strcmp("Autoload\Autoloader",get_class($arguments[0]))){
			throw new AutoloadException("Unauthorised access to ".__CLASS__."::_$name");
		}
		array_shift($arguments);
		return call_user_func_array(array(static::getInstance(),"_{$name}"), $arguments);
	}

	private function _load($file){
		$this->file = $file;
		if(!file_exists($file)){
			throw new AutoloadException("File not found: {$file}");
		}
		$this->mtime = filemtime($file);
		$this->code = file_get_contents($file);
		$this->structure = false;
		$this->pragmas = [];
	}

	private function _show(){
		echo $this->code;
	}

	private function _setNoCollect($bool) {
		$this->nocollect = !!$bool;
	}

	private function _getStructure() {
		if(!$this->structure){
			$this->_readStructure();
		}
		return $this->structure;
	}

	private $idx;
	private $tokens;
	private $lines;
	private $stuff;
	private $namespace;
	private $class;
	private $identifier;

	private function look_behind_namespace_name() {
		$o = 1;
		$nsname = "";
		do{
			if(!preg_match("#^[_0-9a-zA-Z]*$#",($tmp = $this->last_token($o)).$nsname) && "\\"!=$tmp)
				return $nsname;
			$nsname = $tmp.$nsname;
		}while(++$o<$this->idx);
	}

	private function last_token($o = 1) {
		if($this->idx == 0)
			return "";
		$token = $this->tokens[$this->idx-$o];
		return is_array($token)?$token[1]:$token;
	}

	private function next_token($peek = false) {
		if($peek){
			$peek = $this->idx;
		}
		do{
			if($this->idx+1>=count($this->tokens)){
				$token = null;
				break;
			}
		}while(is_array($token = $this->tokens[++$this->idx])?0==strlen(trim($token[1])):0==strlen(trim($token)));
		if($peek){
			$this->idx = $peek;
			return is_array($token)?$token[1]:$token;
		}
		return $token;
	}
	private function advance($ignore = false) {
		while(!is_array($token = $this->next_token())){
			$ignore || ($this->stuff .= $token);
			if(!$token){
				break;
			}
		}
		return $token;
	}

	private function scan() {
		$token = $this->advance();
		do{
			if(in_array($token[0],[null,T_EXIT,T_OPEN_TAG,T_COMMENT,T_NAMESPACE,T_NS_SEPARATOR,T_CLASS,T_FUNCTION]))
				return $token;
		}while($token = $this->advance());
		return null;
	}

	private function _readStructure(){
		$this->lines = explode("\n",$this->code);
		$this->idx = -1;
		$this->tokens = token_get_all($this->code);
		//$this->tokens = array_combine(range(0,count($this->tokens)-1),array_values($this->tokens));
		$this->namespace = "";
		$this->identifier = "";
		$this->stuff = "";
		$arguments = [];
		while($token = $this->next_token()){
			$add = false;
			do{
				if(is_array($token)){
					if(in_array($token[0],[T_EXIT,T_NAMESPACE,T_NS_SEPARATOR,T_COMMENT,T_OPEN_TAG,T_FUNCTION,T_CLASS])){
						switch($token[0]){
							case T_NAMESPACE:
								if($this->next_token(true) == '{')
									throw new AutoloadException("Anonymous namespace not supported");
								$this->namespace = $this->advance()[1];
								break 2;
							case T_NS_SEPARATOR:
								$this->namespace .= "\\".$this->advance()[1];
								break 2;
							case T_COMMENT:
								if(preg_match_all("#/\*\s+@(\w+)\s*=\s*(\w+)@\s+\*/#",$token[1],$matches,PREG_SET_ORDER)){
									$matches = $matches[0];
									array_shift($matches);
									do{
										$this->pragmas[$matches[0]] = next($matches);
									}while(next($matches));
								}
								break 2;
							case T_OPEN_TAG:
								break 2;
							case T_EXIT:
								$add = !!strlen($this->namespace);
								break 2;
							case T_FUNCTION:
							case T_CLASS:
								$this->identifier = $this->advance()[1];
								break 2;
							default:
								$add = true;
								break 2;
						}
					}else{
						$add = true;
					}
				}else{
					switch($token){
						case "(":
							$identifier = $this->look_behind_namespace_name();
							if(!$this->nocollect && strlen($identifier)){
								$this->stuff = substr($this->stuff,0,strrpos($this->stuff,str_replace("\\","",$identifier)));
								$this->stuff .= $identifier;
							}
							break;
					}
					$add = true;
				}
			}while(false);
			$add && !$this->nocollect && ($this->stuff .= is_array($token)?$token[1]:$token);
			if(0<strlen($this->identifier)){
				switch($token[0]){
					case T_FUNCTION:
						$class = "Autoload\FunctionObject";
						break;
					case T_CLASS:
						$class = "Autoload\ClassObject";
						break;
				}
				$c = new $class();
				$c->ln = $token[2]-1;
				$c->name = $this->identifier;
				$this->identifier = "";
				switch($token[0]){
					case T_FUNCTION:
						$c->type = "Function";
						$c->nsname = $this->namespace."\\".$c->name;
						$this->structure[$this->namespace][$c->name] = $c;
						$this->function =& $c;
						$arguments = [];
						$arglist = "";
						while($this->next_token(true) != "("){$this->idx++;}
						$this->idx++;
						while(($tmp = $this->next_token(true)) !== ")"){
							$this->idx++;
							if(is_array($tmp)){
								$arglist .= $tmp[1];
							}else{
								$arglist .= $tmp;
							}
						}
						$arguments = explode(",",$arglist);
						$c->arguments = array_map(function($a){
							$parts = explode("=",$a);
							$type_name = $parts[0];
							$default = 1<count($parts)?$parts[1]:"";
							$parts = explode(" ",$type_name);
							$type = 1<count($parts)?$parts[0]:null;
							$name = 1<count($parts)?$parts[1]:$parts[0];
							return new ArgumentObject($type,$name,$default);
						},$arguments);
						break;
					case T_CLASS:
						$c->nsname = $this->namespace."\\".$c->name;
						$this->structure[$this->namespace][$c->name] = $c;
						$this->class =& $c;
						$c->type = "Class";
						break;
				}
				while(0==$this->count("{",$this->lines[$c->ln])){$c->ln++;}
				$this->mine($c);
			}
		}
	}

	private function mine(&$reference) {
		$depth = 0;
		$l = $reference->ln;
		$reference->code = "";
		do{
			$line = $this->lines[$l];
			$depth += $this->count("{",$line);
			if(0<$depth && !$this->nocollect)$reference->code .= "\n".$line;
			$depth -= $this->count("}",$line);
			if(0>=$depth && !is_null($reference)){
				!$this->nocollect && ($reference->extern = $this->stuff);
				break;
			}
		}while(++$l<count($this->lines));
		while($token = $this->advance(true)){
			if($token[2]>$l){
				break;
			}
		}
	}

	private function _output($namespace,$classname) {
		$code = "";
		//functions first
		$code .= implode("\n",array_map(function($c){
			return $c->type=="Class"?"":$c->toString();
		},$this->structure[$namespace]));
		//class
		$code .= $this->structure[$namespace][$classname]->toString();
		//
		return $code;
	}

	private function count($c,$l){
		$i = -1;
		$n = 0;
		while(++$i<strlen($l)){if($l[$i]==$c)$n++;};
		return $n;
	}

	private function _transpile($namespace,$classname,$prefix){
		$class = $this->structure[$namespace][$classname];
		$code = "<?php\n".(strlen($namespace)?"namespace $namespace;\n":"").$this->_output($namespace,$classname);
		$pragmas = Globals::getInstance()->__pragmas__;
		is_null($pragmas) && ($pragmas = []);
		$pragmas[$namespace][$class->name] = $this->pragmas;
		Globals::getInstance()->__pragmas__ = $pragmas;
		$hash = sha1(openssl_random_pseudo_bytes(129));
		file_put_contents($fname = self::space.$prefix.$hash,$code);
		return $fname;
	}

	private function _misenpile($prefix){
		$hash = sha1(openssl_random_pseudo_bytes(129));
		file_put_contents($fname = self::space.$prefix.$hash,$this->code);
		return $fname;
	}
}


text:
ginAuth Example
========

This folder includes a simple example RESTful server with ginAuth already plugged in.  It requires a
Postgres SQL database with a table simply called `users` with three fields:

1. `id` - primary key int
2. `email` - character varying(255)
3. `password` - character varying(60)

Of course you could easily plug in another SQL database really easily.  See
[the Beego ORM documentation](http://beego.me/docs/mvc/model/overview.md) for more information.


text:
from django.conf import settings
from django.contrib.auth.models import Group, User

from django_browserid.auth import BrowserIDBackend, default_username_algo

from remo.base.mozillians import BadStatusCodeError, is_vouched

USERNAME_ALGO = getattr(settings, 'BROWSERID_USERNAME_ALGO',
                        default_username_algo)

class RemoBrowserIDBackend(BrowserIDBackend):

    def create_user(self, email):
        try:
            data = is_vouched(email)
        except BadStatusCodeError:
            data = None

        # Add vouched mozillians to our db please.
        if data and data['is_vouched']:
            user = User.objects.create_user(username=USERNAME_ALGO(email),
                                            email=email)
            # Due to privacy settings, this might be missing
            if 'full_name' not in data:
                data['full_name'] = 'Anonymous Mozillian'
            else:
                user.userprofile.mozillian_username = data['username']
                user.userprofile.save()

            first_name, last_name = (data['full_name'].split(' ', 1)
                                     if ' ' in data['full_name']
                                     else ('', data['full_name']))
            user.first_name = first_name
            user.last_name = last_name
            user.save()
            user.groups.add(Group.objects.get(name='Mozillians'))
            return user


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>PIONEERS | Band</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" sizes="57x57" href="apple-icon-57x57.png">
        <link rel="apple-touch-icon" sizes="60x60" href="apple-icon-60x60.png">
        <link rel="apple-touch-icon" sizes="72x72" href="apple-icon-72x72.png">
        <link rel="apple-touch-icon" sizes="76x76" href="apple-icon-76x76.png">
        <link rel="apple-touch-icon" sizes="114x114" href="apple-icon-114x114.png">
        <link rel="apple-touch-icon" sizes="120x120" href="apple-icon-120x120.png">
        <link rel="apple-touch-icon" sizes="144x144" href="apple-icon-144x144.png">
        <link rel="apple-touch-icon" sizes="152x152" href="apple-icon-152x152.png">
        <link rel="apple-touch-icon" sizes="180x180" href="apple-icon-180x180.png">
        <link rel="icon" type="image/png" sizes="192x192"  href="android-icon-192x192.png">
        <link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="96x96" href="favicon-96x96.png">
        <link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
        <link rel="manifest" href="manifest.json">
        <meta name="msapplication-TileColor" content="#ffffff">
        <meta name="msapplication-TileImage" content="ms-icon-144x144.png">
        <meta name="theme-color" content="#ffffff">
        <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700" rel="stylesheet">
        <link rel="stylesheet" href="css/style.css">

Bio

Images

Music

Live

Press

Contact

Bio

"Keep your eyes fixed upon the sky"

5 non-millennials from the North, reminiscence of 80's guitar bands along with punk and post-rock influences.

Formed in a pre-Trump world from a mutual discontent in the mundane, they went to work twisting words and sounds to great effect.

They continue to aspire to create and to perform.

Images

Music

"It's what we know, so we keep it alive"

Checkout our tracks from our self-title demo.

More songs coming soon.

Live

03/12/2016 - The Telegraph, Newcastle

11/03/2017 - Head of Steam, Newcastle

01/07/2017 - THINK TANK, Newcastle

02/03/2018 - Head of Steam, Newcastle

Press

"They're brilliant and I'm probably going to cry. My new favourite band.

Nick Wesson, NARC Magazine

"Great sound, very professional attitude and an absolute pleasure to work with."

Jack Bowden, Heart Rock LIVE

Contact

Contact us:

                            Get in touch

Follows us:


text:
@interface TRNCategoryParser()

@end

@implementation TRNCategoryParser

- (instancetype) initWithContext:(NSManagedObjectContext *)context {
	self = [super initWithContext:context];
    if (self) {
    }
    return self;
}

- (NSArray *) fetchAllLocalObjectsSortedById {
	NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"TRNCategory"];

	fetchRequest.includesPropertyValues = NO;
	fetchRequest.sortDescriptors = @[
									[[NSSortDescriptor alloc] initWithKey: @"id" ascending:YES],
									 ];

	NSError *error = nil;
	NSArray *results = [self.context executeFetchRequest:fetchRequest error:&error];

	if (!results) {
		DDLogError(@"Error fetching local objects: %@",error);
	}

	return results;
}

- (NSComparisonResult) compareDictionary:(NSDictionary *) obj1 withDictionary:(NSDictionary *)obj2 {
	NSComparisonResult result;
	id id1 = obj1[@"id"];
	id id2 = obj2[@"id"];
	result = [id1 compare:id2];

	return result;
}

- (NSComparisonResult) compareObject:(TRNCategory *)obj1 withDictionary:(NSDictionary *)obj2 {
	return [self compareDictionary:@{
			@"id" : [obj1 valueForKey:@"id"]
		}
		withDictionary:obj2];
}

- (NSComparisonResult) compareObject:(TRNCategory *)obj1 withObject:(TRNCategory *)obj2 {
	NSComparisonResult result;

	id id1 = [obj1 valueForKey:@"id"];
	id id2 = [obj2 valueForKey:@"id"];
	result = [id1 compare:id2];

	return result;
}

- (BOOL) updateObject:(TRNCategory *)object withDictionary:(NSDictionary *) dic error:(NSError **) error {
	id value;
	value = dic[@"id"];
	if ([value isKindOfClass:[NSNumber class]]) {
		object.id = [value integerValue];
	}
	else {
		// If required stop parsing
		*error = [NSError errorWithDomain:@"Parse" code:BMFErrorInvalidType userInfo:@{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Invalid type or missing key: %@ for property id when parsing object: %@",value,self] }];
		return NO;
	}

	value = dic[@"title"];
	if ([value isKindOfClass:[NSString class]]) {
		object.title = value;
	}
	else {
		DDLogWarn(@"Invalid type or missing key for property title: %@",value);
	}

	if ([self.delegate respondsToSelector:@selector(didParseObject:withDictionary:)]) [self.delegate didParseObject:object withDictionary:dic];
	return YES;
}

- (id) newObject {
	return [TRNCategory MR_createInContext:self.context];
}

- (BOOL) deleteAllLocalObjects {
	return [TRNCategory MR_truncateAllInContext:self.context];
}

@end


text:
		juxtapo - front end tools, documentation

Return to the juxtapo website

juxtapo on github


text:
__author__ = 'aclapes'

from os.path import isfile, isdir, join, splitext
from os import listdir, system, remove
import shutil

# TODO: change MANUALLY these parameters
# ----------------------------------------------------
INTERNAL_PARAMETERS = dict(
    home_path = '/Volumes/MacintoshHD/Users/aclapes/',
    datasets_path = 'Datasets/',
    dataset_dirname = 'ucf_sports_actions',
)
# ----------------------------------------------------

def get_video_from_images(images_path, videofile_path, prefix='', n_leadzeros=4, image_format='jpg', fps=10):
    ''' Use external program (ffmpeg) to convert a set of images to video (loseless) '''
    parameters = ['-i ' + images_path + prefix + '%0' + str(n_leadzeros) + 'd.' + image_format,
                  '-vcodec libx264 -crf 20', # alt: '-codec copy',
                  # '-r ' + str(fps),  # not working!
                  videofile_path]
    cmd = 'ffmpeg ' + parameters[0] + ' ' + parameters[1] + ' ' + parameters[2]
    system(cmd)

if __name__ == '__main__':
    parent_path = INTERNAL_PARAMETERS['home_path'] + INTERNAL_PARAMETERS['datasets_path'] + INTERNAL_PARAMETERS['dataset_dirname'] + '/'
    videos_dir = parent_path

    for i, element in enumerate(listdir(videos_dir)):
        if isdir(join(videos_dir, element)):
            action_dir = element

            for instance_dir in listdir(join(videos_dir, action_dir)):
                if isdir(join(videos_dir, action_dir, element)):
                    instance_dir = element
                    print 'Processing', join(videos_dir, action_dir, instance_dir), '...'

                    # check if there are JPGs (uncropped) to generate a video
                    contains_jpegs = False
                    for element in listdir(join(videos_dir, action_dir, instance_dir)):
                        if isfile(join(videos_dir, action_dir, instance_dir, element)) and splitext(element)[1] == '.jpg':
                            contains_jpegs = True
                            break

                    if contains_jpegs:
                        dir = join(videos_dir, action_dir, instance_dir) + '/'  # this is from where we'll get JPGs
                    else:
                        # check, as a secondary option, if there's already a video
                        contains_video = False
                        videoname = ''
                        for element in listdir(join(videos_dir, action_dir, instance_dir)):
                            if isfile(join(videos_dir, action_dir, instance_dir, element)) and splitext(element)[1] == '.avi':
                                contains_video = True
                                videoname = element
                                break

                        if contains_video:
                            shutil.copyfile(join(videos_dir, action_dir, instance_dir, element), \
                                            join(videos_dir, action_dir + '_' + instance_dir + '.avi'))
                            continue
                        else:
                            # no JPGs (uncropped) and no video? use the cropped JPGs (in jpeg/ subfolder)
                            dir = join(videos_dir, action_dir, instance_dir, 'jpeg/')

                    videoname = ''
                    temporary_files = []
                    frame_ctr = 1

                    for element in listdir(dir):
                        if isfile(join(dir, element)) and splitext(element)[1] == '.jpg':
                            if videoname == '':
                                videoname = splitext(element)[0]
                            new_file = str(frame_ctr).zfill(4) + '.jpg'
                            try:
                                shutil.copyfile(join(dir, element), \
                                                join(dir, new_file))
                            except shutil.Error:
                                print "Already existing file:", new_file, "(no need to copy)"
                                pass

                            temporary_files.append(join(dir, new_file))
                            frame_ctr += 1

                    # create my own video
                    get_video_from_images(dir, join(videos_dir, action_dir + '_' + instance_dir + '.avi'), \
                                          image_format='jpg', prefix='', n_leadzeros=4, fps=10)

                    # remove image files that I copied with proper name to generate the video using ffmpeg
                    for filepath in temporary_files:
                        try:
                            remove(filepath)
                        except OSError:
                            pass

                    print 'DONE.'

    print 'ALL videos DONE.'


text:
package org.springframework.boot.actuate.metrics.export.prometheus;

import java.net.UnknownHostException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.PushGateway;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * Class that can be used to manage the pushing of metrics to a {@link PushGateway
 * Prometheus PushGateway}. Handles the scheduling of push operations, error handling and
 * shutdown operations.
 *
 * @author David J. M. Karlsen
 * @author Phillip Webb
 * @since 2.1.0
 */
public class PrometheusPushGatewayManager {

	private static final Log logger = LogFactory
			.getLog(PrometheusPushGatewayManager.class);

	private final PushGateway pushGateway;

	private final CollectorRegistry registry;

	private final String job;

	private final Map<String, String> groupingKey;

	private final ShutdownOperation shutdownOperation;

	private final TaskScheduler scheduler;

	private ScheduledFuture<?> scheduled;

	/**
	 * Create a new {@link PrometheusPushGatewayManager} instance using a single threaded
	 * {@link TaskScheduler}.
	 * @param pushGateway the source push gateway
	 * @param registry the collector registry to push
	 * @param pushRate the rate at which push operations occur
	 * @param job the job ID for the operation
	 * @param groupingKeys an optional set of grouping keys for the operation
	 * @param shutdownOperation the shutdown operation that should be performed when
	 * context is closed.
	 */
	public PrometheusPushGatewayManager(PushGateway pushGateway,
			CollectorRegistry registry, Duration pushRate, String job,
			Map<String, String> groupingKeys, ShutdownOperation shutdownOperation) {
		this(pushGateway, registry, new PushGatewayTaskScheduler(), pushRate, job,
				groupingKeys, shutdownOperation);
	}

	/**
	 * Create a new {@link PrometheusPushGatewayManager} instance.
	 * @param pushGateway the source push gateway
	 * @param registry the collector registry to push
	 * @param scheduler the scheduler used for operations
	 * @param pushRate the rate at which push operations occur
	 * @param job the job ID for the operation
	 * @param groupingKey an optional set of grouping keys for the operation
	 * @param shutdownOperation the shutdown operation that should be performed when
	 * context is closed.
	 */
	public PrometheusPushGatewayManager(PushGateway pushGateway,
			CollectorRegistry registry, TaskScheduler scheduler, Duration pushRate,
			String job, Map<String, String> groupingKey,
			ShutdownOperation shutdownOperation) {
		Assert.notNull(pushGateway, "PushGateway must not be null");
		Assert.notNull(registry, "Registry must not be null");
		Assert.notNull(scheduler, "Scheduler must not be null");
		Assert.notNull(pushRate, "PushRate must not be null");
		Assert.hasLength(job, "Job must not be empty");
		this.pushGateway = pushGateway;
		this.registry = registry;
		this.job = job;
		this.groupingKey = groupingKey;
		this.shutdownOperation = (shutdownOperation != null) ? shutdownOperation
				: ShutdownOperation.NONE;
		this.scheduler = scheduler;
		this.scheduled = this.scheduler.scheduleAtFixedRate(this::push, pushRate);
	}

	private void push() {
		try {
			this.pushGateway.pushAdd(this.registry, this.job, this.groupingKey);
		}
		catch (UnknownHostException ex) {
			String host = ex.getMessage();
			String message = "Unable to locate prometheus push gateway host"
					+ (StringUtils.hasLength(host) ? " '" + host + "'" : "")
					+ ". No longer attempting metrics publication to this host";
			logger.error(message, ex);
			shutdown(ShutdownOperation.NONE);
		}
		catch (Throwable ex) {
			logger.error("Unable to push metrics to Prometheus Pushgateway", ex);
		}
	}

	private void delete() {
		try {
			this.pushGateway.delete(this.job, this.groupingKey);
		}
		catch (Throwable ex) {
			logger.error("Unable to delete metrics from Prometheus Pushgateway", ex);
		}
	}

	/**
	 * Shutdown the manager, running any {@link ShutdownOperation}.
	 */
	public void shutdown() {
		shutdown(this.shutdownOperation);
	}

	private void shutdown(ShutdownOperation shutdownOperation) {
		if (this.scheduler instanceof PushGatewayTaskScheduler) {
			((PushGatewayTaskScheduler) this.scheduler).shutdown();
		}
		this.scheduled.cancel(false);
		switch (shutdownOperation) {
		case PUSH:
			push();
			break;
		case DELETE:
			delete();
			break;
		}
	}

	/**
	 * The operation that should be performed on shutdown.
	 */
	public enum ShutdownOperation {

		/**
		 * Don't perform any shutdown operation.
		 */
		NONE,

		/**
		 * Perform a 'push' before shutdown.
		 */
		PUSH,

		/**
		 * Perform a 'delete' before shutdown.
		 */
		DELETE

	}

	/**
	 * {@link TaskScheduler} used when the user doesn't specify one.
	 */
	static class PushGatewayTaskScheduler extends ThreadPoolTaskScheduler {

		PushGatewayTaskScheduler() {
			setPoolSize(1);
			setDaemon(true);
			setThreadGroupName("prometheus-push-gateway");
		}

		@Override
		public ScheduledExecutorService getScheduledExecutor()
				throws IllegalStateException {
			return Executors.newSingleThreadScheduledExecutor(this::newThread);
		}

	}

}


text:
<?php namespace Nocriz\Import;

use Nocriz\Import\Algorithm as Algorithm;
use Nocriz\Import\Container as Container;

/**
 * Base para implementação do algorítimo de importação.
 */
abstract class AbstractAlgorithm implements Algorithm
{
    /**
     * @var boolean
     */
    protected $acceptable = false;

    /**
     * @var Container
     */
    protected $container;

    /**
     * @var string
     */
    protected $type;

    /**
     * @param  Container $container
     * @return boolean
     */
    public function accept(Container $container)
    {
        if ( $container->read( 1 ) != $this->type ) {
            $container->seek( -1 );

            return $this->acceptable = false;
        }

        $this->container = $container;

        return $this->acceptable = true;
    }
}


text:
// ThrownSnowballEntity.h

// Declares the cThrownSnowballEntity representing a snowball that has been thrown

#pragma once

#include "ProjectileEntity.h"

// tolua_begin

class cThrownSnowballEntity :
	public cProjectileEntity
{
	typedef cProjectileEntity super;

public:

	// tolua_end

	CLASS_PROTODEF(cThrownSnowballEntity)

	cThrownSnowballEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const Vector3d & a_Speed);

protected:

	// cProjectileEntity overrides:
	virtual void OnHitSolidBlock(Vector3d a_HitPos, eBlockFace a_HitFace) override;
	virtual void OnHitEntity(cEntity & a_EntityHit, Vector3d a_HitPos) override;
	virtual void Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override;

private:

	/** Time in ticks to wait for the hit animation to begin before destroying */
	int m_DestroyTimer;

} ;  // tolua_export


text:
import {Map, List, Record} from 'immutable';
import * as Geometry from './geometry';

export const SNAP_POINT = 'SNAP_POINT';
export const SNAP_LINE = 'SNAP_LINE';
export const SNAP_SEGMENT = 'SNAP_SEGMENT';
export const SNAP_GRID = 'SNAP_GRID';
export const SNAP_GUIDE = 'SNAP_GUIDE';

export const SNAP_MASK = new Map({
  SNAP_POINT : true,
  SNAP_LINE : true,
  SNAP_SEGMENT : true,
  SNAP_GRID : false,
  SNAP_GUIDE : true
});

class PointSnap extends Record({
  type: 'point',
  x: -1, y: -1,
  radius: 1, priority: 1,
  related: new List()
}) {
  nearestPoint(x, y) {
    return {
      x: this.x,
      y: this.y,
      distance: Geometry.pointsDistance(this.x, this.y, x, y)
    };
  }
  isNear(x,y,distance){ return ~(this.x - x) + 1 < distance && ~(this.y - y) + 1 < distance; }
}

class LineSnap extends Record({
  type: 'line',
  a: -1, b: -1, c: -1,
  radius: 1, priority: 1,
  related: new List()
}) {
  nearestPoint(x, y) {
    return {
      ...Geometry.closestPointFromLine(this.a, this.b, this.c, x, y),
      distance: Geometry.distancePointFromLine(this.a, this.b, this.c, x, y)
    };
  }
  isNear(x,y,distance){ return true; }
}

class LineSegmentSnap extends Record({
  type: 'line-segment',
  x1: -1, y1: -1, x2: -1, y2: -1,
  radius: 1, priority: 1,
  related: new List()
}) {
  nearestPoint(x, y) {
    return {
      ...Geometry.closestPointFromLineSegment(this.x1, this.y1, this.x2, this.y2, x, y),
      distance: Geometry.distancePointFromLineSegment(this.x1, this.y1, this.x2, this.y2, x, y)
    };
  }
  isNear(x,y,distance){ return true; }
}

class GridSnap extends Record({
  type: 'grid',
  x: -1, y: -1,
  radius: 1, priority: 1,
  related: new List()
}) {
  nearestPoint(x, y) {
    return {
      x: this.x,
      y: this.y,
      distance: Geometry.pointsDistance(this.x, this.y, x, y)
    };
  }
  isNear(x,y,distance){ return ~(this.x - x) + 1 < distance && ~(this.y - y) + 1 < distance; }
}

export function nearestSnap(snapElements, x, y, snapMask) {

  let filter = {
    'point': snapMask.get(SNAP_POINT),
    'line': snapMask.get(SNAP_LINE),
    'line-segment': snapMask.get(SNAP_SEGMENT),
    'grid': snapMask.get(SNAP_GRID)
  };

  return snapElements
  .valueSeq()
  .filter( ( el ) => filter[el.type] && el.isNear(x,y, el.radius) )
  .map(snap => { return {snap, point: snap.nearestPoint(x, y)} })
  .filter(({snap: {radius}, point: {distance}}) => distance < radius)
  .min(
    (
      {snap: { priority : p1 }, point: { distance : d1 }},
      {snap: { priority : p2 }, point: { distance : d2 }}
    ) => p1 === p2 ? ( d1 < d2 ? -1 : 1 ) : ( p1 > p2 ? -1 : 1 )
  );
}

export function addPointSnap(snapElements, x, y, radius, priority, related) {
  related = new List([related]);
  return snapElements.push(new PointSnap({x, y, radius, priority, related}));
}

export function addLineSnap(snapElements, a, b, c, radius, priority, related) {
  related = new List([related]);

  return snapElements.withMutations(snapElements => {

    let alreadyPresent = snapElements.some(lineSnap =>
    lineSnap.type === 'line' &&
    a === lineSnap.a &&
    b === lineSnap.b &&
    c === lineSnap.c);
    if (alreadyPresent) return snapElements;

    let intersections = snapElements
      .valueSeq()
      .filter(snap => snap.type === 'line')
      .map(snap => Geometry.twoLinesIntersection(snap.a, snap.b, snap.c, a, b, c))
      .filter(intersection => intersection !== undefined)
      .forEach(({x, y}) => addPointSnap(snapElements, x, y, 20, 40));

    snapElements.push(new LineSnap({a, b, c, radius, priority, related}));
  })
}

export function addLineSegmentSnap(snapElements, x1, y1, x2, y2, radius, priority, related) {
  related = new List([related]);
  return snapElements.push(new LineSegmentSnap({x1, y1, x2, y2, radius, priority, related}));
}

export function addGridSnap(snapElements, x, y, radius, priority, related) {
  related = new List([related]);
  return snapElements.push(new GridSnap({x, y, radius, priority, related}));
}


text:
package org.tosca4iot.toscatypes;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.tosca4iot.webinterface.HttpRequest;

public class NodeTypeHTTPInterface extends NodeTypeInterface {
	public NodeTypeHTTPInterface(ServiceTemplate serviceTemplate) {
		super(serviceTemplate);
	}
	private String jsonBody;
	private String jsonBodyFilePath;
	private String jsonBodyRefFilePath;
	private String url;
	@Override
	public void executeInterfaceMethods() {
		HttpRequest request = new HttpRequest();
		String deviceURL=
				super.getServiceTemplate().getProperty("HTTP_Protocol")+"://"+
				super.getServiceTemplate().getProperty("IP")+":"+
				super.getServiceTemplate().getProperty("HTTP_Port");

		byte[] encoded;
		try {
			encoded = Files.readAllBytes(Paths.get(jsonBodyFilePath));
			String osFile = new String(encoded, StandardCharsets.UTF_8);
			request.send(deviceURL+"/os", "application/json", "POST", osFile );
			request.send(deviceURL+"/reboot", "application/json", "POST", "");
			Thread.sleep(120000);
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
	}
	public String getJsonBody() {
		return jsonBody;
	}
	public void setJsonBody(String jsonBody) {
		this.jsonBody = jsonBody;
	}
	public String getJsonBodyFilePath() {
		return jsonBodyFilePath;
	}
	public void setJsonBodyFilePath(String jsonBodyFilePath) {
		this.jsonBodyFilePath = jsonBodyFilePath;
	}
	public String getJsonBodyRefFilePath() {
		return jsonBodyRefFilePath;
	}
	public void setJsonBodyRefFilePath(String jsonBodyRefFilePath) {
		this.jsonBodyRefFilePath = jsonBodyRefFilePath;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace ArquiteturaBasica.Comuns.Seguranca
{
    /// <summary>
    /// Classe que criptografa e descriptografa pequenos textos.
    /// </summary>
    public class StringCryptography : Encryption
    {

        /// <summary>
        /// Metodo de criptografia de valor
        /// </summary>
        /// <param name="text">valor a ser criptografado</param>
        /// <returns>valor criptografado</returns>
        public static string Encrypt(string text)
        {
            try
            {
                // Se a string não está vazia, executa a criptografia
                if (!string.IsNullOrEmpty(text))
                {
                    // Cria instancias de vetores de bytes com as chaves
                    byte[] bKey = Convert.FromBase64String(cryptoKey);
                    byte[] bText = new UTF8Encoding().GetBytes(text);

                    // Instancia a classe de criptografia Rijndael
                    Rijndael rijndael = new RijndaelManaged();

                    // Define o tamanho da chave "256 = 8 * 32"
                    // Lembre-se: chaves possíves:
                    // 128 (16 caracteres), 192 (24 caracteres) e 256 (32 caracteres)
                    rijndael.KeySize = 256;

                    // Cria o espaço de memória para guardar o valor criptografado:
                    MemoryStream mStream = new MemoryStream();
                    // Instancia o encriptador
                    CryptoStream encryptor = new CryptoStream(
                        mStream,
                        rijndael.CreateEncryptor(bKey, bIV),
                        CryptoStreamMode.Write);

                    // Faz a escrita dos dados criptografados no espaço de memória
                    encryptor.Write(bText, 0, bText.Length);
                    // Despeja toda a memória.
                    encryptor.FlushFinalBlock();
                    // Pega o vetor de bytes da memória e gera a string criptografada
                    return Convert.ToBase64String(mStream.ToArray());
                }
                else
                {
                    // Se a string for vazia retorna nulo
                    return null;
                }
            }
            catch (Exception ex)
            {
                // Se algum erro ocorrer, dispara a exceção
                throw new CryptographicException("Erro ao criptografar", ex);
            }
        }

        /// <summary>
        /// Pega um valor previamente criptografado e retorna o valor inicial
        /// </summary>
        /// <param name="text">texto criptografado</param>
        /// <returns>valor descriptografado</returns>
        public static string Decrypt(string text)
        {
            try
            {
                // Se a string não está vazia, executa a criptografia
                if (!string.IsNullOrEmpty(text))
                {
                    // Cria instancias de vetores de bytes com as chaves
                    byte[] bKey = Convert.FromBase64String(cryptoKey);
                    byte[] bText = Convert.FromBase64String(text);

                    // Instancia a classe de criptografia Rijndael
                    Rijndael rijndael = new RijndaelManaged();

                    // Define o tamanho da chave "256 = 8 * 32"
                    // Lembre-se: chaves possíves:
                    // 128 (16 caracteres), 192 (24 caracteres) e 256 (32 caracteres)
                    rijndael.KeySize = 256;

                    // Cria o espaço de memória para guardar o valor DEScriptografado:
                    MemoryStream mStream = new MemoryStream();

                    // Instancia o Decriptador
                    CryptoStream decryptor = new CryptoStream(
                        mStream,
                        rijndael.CreateDecryptor(bKey, bIV),
                        CryptoStreamMode.Write);

                    // Faz a escrita dos dados criptografados no espaço de memória
                    decryptor.Write(bText, 0, bText.Length);
                    // Despeja toda a memória.
                    decryptor.FlushFinalBlock();
                    // Instancia a classe de codificação para que a string venha de forma correta
                    UTF8Encoding utf8 = new UTF8Encoding();
                    // Com o vetor de bytes da memória, gera a string descritografada em UTF8
                    return utf8.GetString(mStream.ToArray());
                }
                else
                {
                    // Se a string for vazia retorna nulo
                    return null;
                }
            }
            catch (Exception ex)
            {
                // Se algum erro ocorrer, dispara a exceção
                throw new CryptographicException("Erro ao descriptografar", ex);
            }
        }

    }
}


text:
package tester

import (
	"fmt"
	"os/exec"

	"go.etcd.io/etcd/tests/v3/functional/rpcpb"
)

type caseExternal struct {
	Case

	desc      string
	rpcpbCase rpcpb.Case

	scriptPath string
}

func (c *caseExternal) Inject(clus *Cluster) error {
	return exec.Command(c.scriptPath, "enable", fmt.Sprintf("%d", clus.rd)).Run()
}

func (c *caseExternal) Recover(clus *Cluster) error {
	return exec.Command(c.scriptPath, "disable", fmt.Sprintf("%d", clus.rd)).Run()
}

func (c *caseExternal) Desc() string {
	return c.desc
}

func (c *caseExternal) TestCase() rpcpb.Case {
	return c.rpcpbCase
}

func new_Case_EXTERNAL(scriptPath string) Case {
	return &caseExternal{
		desc:       fmt.Sprintf("external fault injector (script: %q)", scriptPath),
		rpcpbCase:  rpcpb.Case_EXTERNAL,
		scriptPath: scriptPath,
	}
}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Activities extends CI_Controller{
	public function _construct(){
		parent::_construct();
		$this->load->helper('url');
		$this->load->helper('html');
		}

	public function index(){
		$info = array('title' => 'Activities');
		$this->load->view('en/activities', $info);
		}
	}

?>


text:
function openInfo(orderID) {
    var feeInfo = document.getElementById('feeInfo');
    document.getElementById('feeInfo').style.display = "block";
    document.getElementById('feeInfoContent').innerHTML = "";

    form = document.createElement("form");
    form.id = "feeInfoForm";
    feeInfoContent.appendChild(form);

    var rowCandidates = document.getElementsByName(orderID);
    var row = rowCandidates[0].parentElement.parentElement;
    var cols = getColDefinition();

    newLine("Order ID", cols.id, "ID", row);
    newLine("Buyer", cols.buyer, "Buyer", row);
    newLine("Status", cols.status, "Order Status ", row);
    newLine("Shipping Cost", cols.shipping, "Ship.", row);
    newLine("Current Grand Total", cols.total, "Grand", row);

    //calculate fee
    var countryLow = ["Germany", "Belgium", "Bulgaria", "Croatia", "Denmark", "Estonia", "Finland", "France",
        "Greece", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg", "Malta", "Netherlands",
        "Austria", "Poland", "Portugal", "Romania", "Sweden", "Slovakia", "Slovenia", "Spain",
        "Czech Republic", "Hungary", "United Kingdom", "Cyprus", "Norway", "Iceland", "Liechtenstein"];

    var total = row.cells[cols.total].innerHTML.replace(/<[^>]*>/g, "").replace(/ /g, ' ').split(" ").pop();
    var country = row.cells[cols.buyer - 1].firstChild.alt;

    var rate;
    if (countryLow.indexOf(country) > -1) {
        rate = 0.019;
    } else {
        rate = 0.039;
    }
    var fee = total * rate + 0.35;
    fee = Math.round(fee * Math.pow(10, 2)) / Math.pow(10, 2).toFixed(2);

    //output
    var feeInfoForm = document.getElementById("feeInfoForm");
    feeInfoForm.appendChild(document.createElement("BR"));
    feeInfoForm.appendChild(document.createElement("BR"));
    var l = document.createElement("label");
    l.className = "feeLabel";
    l.htmlFor = "fee";
    l.innerHTML = "Suggested paypal fee";
    feeInfoForm.appendChild(l);

    var i = document.createElement("input");
    i.setAttribute('type', "text");
    i.setAttribute('name', "fee");
    i.setAttribute('value', fee);
    i.setAttribute('readOnly', true);

    feeInfoForm.appendChild(i);
    feeInfoForm.appendChild(document.createElement("BR"));
    feeInfoForm.appendChild(document.createElement("BR"));
    feeInfoForm.appendChild(document.createElement("BR"));

    var l = document.createElement("text");
    l.className = "feeLabel";
    l.innerHTML = "Applied rate: " + (rate * 100) + "%";
    feeInfoForm.appendChild(l);

}

function newLine(text, col, name, row) {
    var feeInfoForm = document.getElementById("feeInfoForm");
    var l = document.createElement("label");
    l.className = "feeLabel";
    l.htmlFor = name;
    l.innerHTML = text;
    feeInfoForm.appendChild(l);

    var i = document.createElement("input");
    i.setAttribute('type', "text");
    i.setAttribute('name', name);

    var value = row.cells[col].innerHTML.replace(/<[^>]*>/g, "").replace(/ /g, ' ');
    if ((value == "") || (name == "Order Status ")) {
        //could be input field
        value = row.cells[col].firstChild.value;
    }
    i.setAttribute('value', value);
    i.setAttribute('readOnly', true);

    feeInfoForm.appendChild(i);
    feeInfoForm.appendChild(document.createElement("BR"));
}

function getColDefinition() {
    //Assumption: only one table found
    var orders = document.getElementsByClassName('tableT1')[0];
    var cols = new Object();
    for (var j = 0, col; col = orders.rows[0].cells[j]; j++) {

        switch(get(col, 'firstChild.firstChild.data')) {
            case "ID":
                cols.id = getActualCellIndex(orders, col);
                break;
            case "Buyer":
                cols.buyer = getActualCellIndex(orders, col);
                break;
            case "Ship.":
                cols.shipping = getActualCellIndex(orders, col);
                break;
            case "Grand":
                cols.total = getActualCellIndex(orders, col);
                break;
            case "Order Status ": // _space_ seems to be an error on the new status page
            case "Order Status":
                cols.status = getActualCellIndex(orders, col);
                break;
            case "Date":
                cols.date = getActualCellIndex(orders, col);
                break;
            case "":
            case null:
                break;
            default:
                //console.log(get(col, 'firstChild.firstChild.data'));
        }
    }
    return cols;
}

//utility to get deep property pathes
function get(obj, key) {
    return key.split(".").reduce(function (o, x) {
        return (typeof o == "undefined" || o === null) ? o : o[x];
    }, obj);
}

//utility to get the right cellindex even with colspan
function computeTableHeaderCellIndexes(t) {
	var matrix = [];
	var lookup = {};
	var trs = t.getElementsByTagName('TR');
	for (var i=0; i<trs.length; i++) {
	    //check if maybe not a real line. Currently all other lines have className
	    if (trs[i].className == "") { continue; }
		var cells = trs[i].cells;
		for (var j=0; j<cells.length; j++) {
			var c = cells[j];
			var rowIndex = c.parentNode.rowIndex;
			var cellId = rowIndex+"-"+c.cellIndex;
			var rowSpan = c.rowSpan || 1;
			var colSpan = c.colSpan || 1
			var firstAvailCol;
			if(typeof(matrix[rowIndex])=="undefined") { matrix[rowIndex] = []; }
			// Find first available column in the first row
			for (var k=0; k<matrix[rowIndex].length+1; k++) {
				if (typeof(matrix[rowIndex][k])=="undefined") {
					firstAvailCol = k;
					break;
				}
			}
			lookup[cellId] = firstAvailCol;
			for (var k=rowIndex; k<rowIndex+rowSpan; k++) {
				if(typeof(matrix[k])=="undefined") { matrix[k] = []; }
				var matrixrow = matrix[k];
				for (var l=firstAvailCol; l<firstAvailCol+colSpan; l++) {
					matrixrow[l] = "x";
				}
			}
		}
	}
	return lookup;
}

function getActualCellIndex(table, cell) {
	return computeTableHeaderCellIndexes(table)[cell.parentNode.rowIndex+"-"+cell.cellIndex];
}


text:
Router.configure({
  layoutTemplate: 'ApplicationLayout'
});

Router.route('/', function () {
  this.render('home');
});

Router.route('/:slug', function () {
	var slug = this.params.slug;
	console.log(slug)
	var doc = Events.findOne({slug: this.params.slug});
	console.log(doc)
	Session.set("slug", slug);
	this.render('showEvent', {
		data: {
			"event": doc
		}
	});
});

Router.route('nope', function () {
  this.render('notComing');
});

// Router.route('/event/:_id', function () {
// 	this.render('showEvent', {
// 		data: function () {
// 			var params = this.params;
// 			return params
// 		}
// 	});
//   });