text:
layout: global
title: Lineage Client API (alpha)
nickname: Lineage API
group: Features
priority: 2
---

* Table of Contents
{:toc}

O Alluxio pode alcançar alta vazão de escrita e leitura, sem comprometer a tolerância a falhar
através de *Lineage* (Linhagem), onde resultados perdidos são recuperados através da re-execução
de rotinas que criaram o resultado.

Com o `lineage`, os resultados das aplicações são escritos em memória, e o `checkpoints` dos
resultados ocorrem periodicamente no `under storage system`, de forma assíncrona. No caso de falhas,
o Alluxio executar uma *rotina de re-processamento* para restaurar os arquivos perdidos. O `lianeage`
assume que as rotinas são determinista então os resultados do reprocessamento são idênticos. Se
esta suposição não for comprida, fica a critério da aplicação de resolver os resultados divergentes.

## Hablitando Lineage

Por padrão, o `linaeage` não é habilitado. Este pode ser habilitado definindo o valor da propriedade
`alluxio.user.lineage.enabled` para `true` no arquivo de configuração.

## Lineage API

O Alluxio provê uma `API` estilo `Java` para gerenciamento e acesso das informações de linhagem.

### Obtendo um Lineage Client

Para obter um Alluxio `Lineage Client` em código `Java`, execute:

{% include Lineage-API/get-lineage-client.md %}

### Criando o Registro de Lineage

O `Lineage` pode ser criado através da execução de
`AlluxioLineage#createLineage(List<AlluxioURI>, List<AlluxioURI>, Job)`. O registro do `lineage`
obtém (1) uma lista de `URIs` de arquivos de entrada, (2) uma lista de de `URIs` arquivos de saída e
(3) uma tarefa. A tarefa é a descrição de um program que pode ser executado pelo Alluxio para
reprocessar os arquivos resultantes a partir de arquivos de entrada. *Nota: Na versão `alpha` atual,
somente o comando `CommandLineJob` é suportado, qual simplesmente obtém um comando `String` que
pode ser executado em um terminal. O usuário precisa prover as configurações necessárias e variáveis
ambientes de execução para garantir que o comando pode ser executado ed ambos o `client` e o `master`
(durante o reprocessamento).*

Por exemplo,
{% include Lineage-API/config-lineage.md %}

A função `createLineage` retorna um `id` de um recém registro de linhagem criado. Antes de
criar este registro, tenha certeza que todos os arquivos de entrada estão mantidos ou especifique
um arquivo de saída de outro registro de `lineage`.

### Especificando Opções de Operações

Para todas as operações do `AlluxioLineage`, campos de opções adicionais devem ser preenchidos
para que permitam os usuários de especificar definições que não são padrões para a operação.

### Apagando um Lineage

Um registro de `lineage` pode ser apagado através do comando `AlluxioLineage#deleteLineage`.
Deve ser informando um `id` para esta função.

{% include Lineage-API/delete-lineage.md %}

Por padrão, um registro de `lineage` a ser apagado não pode possuir arquivos resultantes
dependentes em outros `lineages`. Opcionalmente, todo o conjunto de `lineages` pode ser apagado
de uma única vez, utilizando a opção em cascata. Por exemplo:

{% include Lineage-API/delete-cascade.md %}

## Parâmetros de Configuração para o Lineage

Estes são os parâmetros de configuração relacionados as funcionalidades do `lineage`.

Parameter	Default Value	Description

{% for record in site.data.table.LineageParameter %}

  {{record.parameter}}
  {{record.defaultvalue}}
  {{site.data.table.en.LineageParameter[record.parameter]}}

{% endfor %}


text:
export default function sidebar({
  headersContainer,
  sidebarContainer,
  headerStartLevel,
}) {
  const headers = headersContainer.querySelectorAll('h2, h3');
  const select = document.createElement('select');
  const list = document.createElement('ul');
  const startLevel = headerStartLevel; // we start at h2
  list.classList.add('no-mobile');
  let currentList = list;
  let currentLevel = startLevel;

  Array.from(headers).forEach((header) => {
    const level = parseInt(header.tagName.split('')[1], 10);

    if (level > currentLevel) {
      // we enter a sublist
      currentLevel = level;
      if (currentList.lastChild) {
        currentList = currentList.lastChild.appendChild(
          document.createElement('ul')
        );
      }
    } else if (level < currentLevel) {
      // we exit a sublit
      currentLevel = level;
      if (currentList.parentNode && currentList.parentNode.parentNode) {
        currentList = currentList.parentNode.parentNode;
      }
    }

    const title = header.textContent;
    const listItem = document.createElement('li');
    const link = document.createElement('a');
    link.setAttribute('href', `#${header.getAttribute('id')}`);
    link.textContent = title;
    listItem.appendChild(link);
    currentList.appendChild(listItem);
    const option = document.createElement('option');
    option.setAttribute('value', link.getAttribute('href'));
    option.textContent = `${spacer(currentLevel - startLevel)}${title}`;
    select.classList.add('display-on-small');
    select.appendChild(option);
  });

  select.addEventListener('change', (e) => {
    window.location = e.target.value;
  });
  sidebarContainer.appendChild(list);
  sidebarContainer.appendChild(select);
  sidebarFollowScroll(sidebarContainer);
  activeLinks(sidebarContainer);
  scrollSpy(sidebarContainer, headersContainer);
}

function sidebarFollowScroll(sidebarContainer) {
  const positionSidebar = () => {
    // The following code is used to change the color of the navigation
    // depending the level of page scroll.
    const hero = document.querySelector('.hero-section');
    const footer = document.querySelector('.ac-footer');
    const navigation = document.querySelector('.ac-nav');
    const menu = document.querySelector('.sidebar > ul');
    const heroHeight = hero.offsetHeight;
    const navHeight = navigation.offsetHeight;
    const height = document.querySelector('html').getBoundingClientRect()
      .height;
    const footerHeight = footer.offsetHeight;
    const menuHeight = menu.offsetHeight;

    const currentScroll = window.pageYOffset;
    const doc = document.querySelector('.documentation-section');
    let paddingDoc = window
      .getComputedStyle(doc, null)
      .getPropertyValue('padding-top')
      .split('px')[0];
    paddingDoc = parseInt(paddingDoc, 10);
    // Fix the sidebar navigation
    if (currentScroll > heroHeight - navHeight + paddingDoc) {
      const fold = height - footerHeight - menuHeight - paddingDoc - 50;
      if (currentScroll > fold) {
        // eslint-disable-next-line no-param-reassign
        sidebarContainer.style.top = `${fold - currentScroll}px`;
      } else {
        // eslint-disable-next-line no-param-reassign
        sidebarContainer.style.top = null;
      }
      sidebarContainer.classList.add('fixed');
    } else {
      sidebarContainer.classList.remove('fixed');
    }
  };

  window.addEventListener('load', positionSidebar);
  document.addEventListener('DOMContentLoaded', positionSidebar);
  document.addEventListener('scroll', positionSidebar);
}

function scrollSpy(sidebarContainer, headersContainer) {
  const headers = Array.from(headersContainer.querySelectorAll('h2, h3'));

  const setActiveSidebarLink = (header) => {
    Array.from(sidebarContainer.querySelectorAll('a')).forEach((item) => {
      const matches = Array.from(item.parentNode.querySelectorAll('a'))
        .map((sub) => sub.getAttribute('href').slice(1))
        .filter((ref) => ref === header.getAttribute('id'));
      if (matches.length > 0) {
        item.classList.add('active');
      } else {
        item.classList.remove('active');
      }
    });
  };

  const findActiveSidebarLink = () => {
    const highestVisibleHeaders = headers
      .map((header) => ({
        element: header,
        rect: header.getBoundingClientRect(),
      }))
      .filter(
        ({ rect }) =>
          // top element relative viewport position should be at least 1/3 viewport
          // and element should be in viewport
          rect.top < window.innerHeight / 3 && rect.bottom < window.innerHeight
      )
      // then we take the closest to this position as reference
      .sort((header1, header2) => {
        const h1Top = Math.abs(header1.rect.top);
        const h2Top = Math.abs(header2.rect.top);
        return h1Top < h2Top ? -1 : 1;
      });

    if (highestVisibleHeaders.length === 0) {
      setActiveSidebarLink(headers[0]);
      return;
    }

    setActiveSidebarLink(highestVisibleHeaders[0].element);
  };

  findActiveSidebarLink();
  window.addEventListener('load', findActiveSidebarLink);
  document.addEventListener('DOMContentLoaded', findActiveSidebarLink);
  document.addEventListener('scroll', findActiveSidebarLink);
}

// The Following code is used to set active items
// On the documentation sidebar depending on the
// clicked item
function activeLinks(sidebarContainer) {
  const linksContainer = sidebarContainer.querySelector('ul');

  linksContainer.addEventListener('click', (e) => {
    if (e.target.tagName === 'A') {
      Array.from(linksContainer.querySelectorAll('a')).forEach((item) =>
        item.classList.remove('active')
      );
      e.target.classList.add('active');
    }
  });
}

function spacer(n) {
  if (n === 0) return '';
  const arr = new Array(n + 1);
  return `${arr.join('-')}> `;
}

redpajama_set_name: RedPajamaGithub


text:
package za.org.grassroot.integration.messaging;

/**
 * Created by luke on 2016/09/19.
 */
public enum MessagePushResponseType {

    ROUTED,
    DELIVERED,
    INVALID_CREDENTIALS,
    INSUFFICIENT_FUNDS,
    DUPLICATE_MESSAGE,
    MSISDN_INVALID,
    INVALID_QUERY,
    UNKNOWN_ERROR

}


text:
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

        </button>
        美好家园

                首页

                登陆

                注册

                 退出


text:
const Vue = require('vue')
const Vuex = require('vuex')

Vue.use(Vuex)

// A Vuex instance is created by combining the state, mutations, actions,
// and getters.
module.exports = new Vuex.Store({
  state: require('./state'),
  getters: require('./getters'),
  actions: require('./actions'),
  mutations: require('./mutations'),
})


text:
using System.Net.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ShopifySharp.Filters;

namespace ShopifySharp
{
    /// <summary>
    /// A service for manipulating Shopify's Location API.
    /// </summary>
    public class LocationService : ShopifyService
    {
        /// <summary>
        /// Creates a new instance of <see cref="LocationService" />.
        /// </summary>
        /// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
        /// <param name="shopAccessToken">An API access token for the shop.</param>
        public LocationService(string myShopifyUrl, string shopAccessToken) : base(myShopifyUrl, shopAccessToken)
        {
        }

        /// <summary>
        /// Retrieves the <see cref="Location"/> with the given id.
        /// </summary>
        /// <param name="id">The id of the charge to retrieve.</param>
        /// <param name="cancellationToken">Cancellation Token</param>
        /// <returns>The <see cref="Location"/>.</returns>
        public virtual async Task<Location> GetAsync(long id, CancellationToken cancellationToken = default)
        {
            return await ExecuteGetAsync<Location>($"locations/{id}.json", "location", cancellationToken: cancellationToken);
        }

        /// <summary>
        /// Retrieves a list of all <see cref="Location"/> objects.
        /// </summary>
        /// <returns>The list of <see cref="Location"/> objects.</returns>
        public virtual async Task<IEnumerable<Location>> ListAsync(CancellationToken cancellationToken = default)
        {
            return await ExecuteGetAsync<IEnumerable<Location>>($"locations.json", "locations", cancellationToken: cancellationToken);
        }
    }
}


text:
package at.ac.tuwien.dsg.sanalytics.bridge.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.integration.annotation.MessageEndpoint;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.support.GenericMessage;

@MessageEndpoint
@Profile("outbound-logger")
public class OutboundLogger {

	private final static Logger LOG = LoggerFactory.getLogger(OutboundLogger.class);

	@ServiceActivator(inputChannel = "outboundChannel")
	public void log(GenericMessage<?> message) {
		try {
			LOG.info("Payload " + (message == null ? null : message.getPayload().getClass()));
			LOG.info("" + message);
		} catch(Exception e) {
			LOG.error("", e);
		}
	}
}


text:
[![Build status](https://ci.appveyor.com/api/projects/status/94d1q1it5e63t9t3?svg=true)](https://ci.appveyor.com/project/HTT323/iam)

# Work in progress ...

[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/IAM-for-Identity-Server-3)

# IAM
Identity and Access Management layer for Identity Server v3

Design decisions:
- Entity Framework with ASP.NET Identity
- Used CustomViewService to serve ID Server pages
- Replaced Bundles with Bower/Grunt

https://localhost:44300/identity
https://localhost:44300/{tenant}/{controller}/{action}

claims

tenant 			orion
tenant			nebula
orion.role		Administrator
orion.role		Owner
nebula.role		User

## Multi-Tenant Settings

### Hosts File

127.0.0.1 www.iam.dev
127.0.0.1 admin.iam.dev
127.0.0.1 auth.iam.dev
127.0.0.1 orion.iam.dev
127.0.0.1 nebula.iam.dev
127.0.0.1 www.orion-portal.dev
127.0.0.1 www.nebula-portal.dev

### Generate SSL Certificates

makecert -n "CN=IAM Development Root CA,O=IAM,OU=Development,L=Singapore,S=SG,C=SG" -pe -ss Root -sr LocalMachine -sky exchange -m 120 -a sha256 -len 2048 -r

makecert -n "CN=*.iam.dev" -pe -ss My -sr LocalMachine -sky exchange -m 120 -in "IAM Development Root CA" -is Root -ir LocalMachine -a sha256 -eku 1.3.6.1.5.5.7.3.1
makecert -n "CN=www.orion-portal.dev" -pe -ss My -sr LocalMachine -sky exchange -m 120 -in "IAM Development Root CA" -is Root -ir LocalMachine -a sha256 -eku 1.3.6.1.5.5.7.3.1
makecert -n "CN=www.nebula-portal.dev" -pe -ss My -sr LocalMachine -sky exchange -m 120 -in "IAM Development Root CA" -is Root -ir LocalMachine -a sha256 -eku 1.3.6.1.5.5.7.3.1

### NETSH SSL Settings

Remove current SSL binding > netsh http delete sslcert ipport=0.0.0.0:44300
Apply SSL binding > netsh http add sslcert ipport=0.0.0.0:44300 appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certhash=THUMBPRINT_OF_IAM_DEV

### IIS Express Settings

source/.vs/config/applicationhost.config

<binding protocol="https" bindingInformation="*:44300:*" />

### Web Settings

Set the Iam.Web Start URL > https://www.iam.dev:44300
Set the Iam.Orion.Web Start URL > https://www.orion-portal.dev:44310
Set the Iam.Nebula.Web Start URL > https://www.nebula-portal.dev:44320

### Design

Single IDS database instance
- client: iam

- IAM Client Mapping (using the registered sub-domain)
- tenant: orion
-- www.orionportal.com (client: orionportal)
-- www.orionhr.com (client: orionhr)
-- www.orion.com (client: orionhr)

### Orion Portal Setup

- be careful when copying the thumbprint from the cert - it contains hidden characters in front, sanitize first.

Remove current SSL binding > netsh http delete sslcert ipport=0.0.0.0:44310
Apply SSL binding > netsh http add sslcert ipport=0.0.0.0:44310 appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certhash=THUMBPRINT_OF_ORION_PORTAL_CERT

### Nebula Portal Setup

Remove current SSL binding > netsh http delete sslcert ipport=0.0.0.0:44320
Apply SSL binding > netsh http add sslcert ipport=0.0.0.0:44320 appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certhash=THUMBPRINT_OF_NEBULA_PORTAL_CERT

## ConfigWatch

- Make sure to set write permission to this folder (to enable 'reconfigure' OWIN)

## OKTA Login

1st:
Demo User
identitymgmt@yahoo.com / Demo123#

2nd:
iam.demouser@yahoo.com / Demo123#

## Important

The ReplyToUrl in OKTA must match the CallbackPath in WsFederationAuthenticationOptions

-> OKTA: https://auth.iam.dev:44300/callback/wsfed1
-> CallbackPath = new PathString($"/callback/wsfed{wsFed.Id}")

SP Identity Setup
-----------------

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\local.cer")
New-SPTrustedRootAuthority -Name "Token Signing Cert" -Certificate $cert
$nameClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.org/claims/username" -IncomingClaimTypeDisplayName "Name" -SameAsIncoming
$upnClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" -IncomingClaimTypeDisplayName "UPN" -SameAsIncoming
$roleClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" -IncomingClaimTypeDisplayName "Role" -SameAsIncoming
$emailClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming
$realm = "urn:nebula:8af89396db32459c8cf2a819f1142c36"
$signInURL = "https://auth.iam.dev:44300/wsfed"
$ap = New-SPTrustedIdentityTokenIssuer -Name "IAM" -Description "IAM Trusted Identity Provider" -realm $realm -ImportTrustCertificate $cert -ClaimsMappings $nameClaimMap, $emailClaimMap, $upnClaimMap, $roleClaimMap -SignInUrl $signInURL -IdentifierClaim $nameClaimMap.InputClaimType

V2 (using email as identifier claim)

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\signing.cer")
New-SPTrustedRootAuthority -Name "Token Signing Cert" -Certificate $cert
$nameClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.org/claims/username" -IncomingClaimTypeDisplayName "Name" -SameAsIncoming
$upnClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" -IncomingClaimTypeDisplayName "UPN" -SameAsIncoming
$roleClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" -IncomingClaimTypeDisplayName "Role" -SameAsIncoming
$emailClaimMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming
$realm = "urn:nebula:8af89396db32459c8cf2a819f1142c36"
$signInURL = "https://auth.iam.dev:44300/wsfed"
$ap = New-SPTrustedIdentityTokenIssuer -Name "IAM" -Description "IAM Trusted Identity Provider" -realm $realm -ImportTrustCertificate $cert -ClaimsMappings $nameClaimMap, $emailClaimMap, $upnClaimMap, $roleClaimMap -SignInUrl $signInURL -IdentifierClaim $emailClaimMap.InputClaimType

Remove-SPTrustedRootAuthority "Token Signing Cert"
Remove-SPTrustedIdentityTokenIssuer "IAM"


text:
ofImage *ofxWWTweetParticle::dotImages[NUM_DOT_IMAGES] = {NULL, NULL, NULL, NULL, NULL};

ofImage* ofxWWTweetParticle::highlightImage = NULL;

ofxWWTweetParticle::ofxWWTweetParticle(){
	boundingRect = ofRectangle(0,0,0,0);
	delete_id = 0;
	whichImage = ofRandom(0, 1);
	if(whichImage<0.5) whichImage = 0;
	else whichImage = ofMap(whichImage, 0.5, 1, 0, 1);
	imageScale = ofRandom(0.5, 2.3);
	manager = NULL;
	isTwoLines = false;
	isSearchTweet = false;
	speedAdjust = 0;

	state = STATE_DEFAULT;
	dot_opacity = 1.0;
	highlight_duration = 300;

	if(dotImages[0]==NULL) {
		for(int i = 0; i < NUM_DOT_IMAGES; i++) {
			dotImages[i] = new ofImage();
			dotImages[i]->loadImage("images/td"+ofToString(i)+".png");
		}
	}

	if(highlightImage == NULL) {
		highlightImage = new ofImage();
		highlightImage->loadImage("images/highlight.png");
		//highlightImage->setAnchorPercent(0.5, 0.5);
	}
}

void ofxWWTweetParticle::setTweet(rtt::Tweet tw){
	lastPos = pos;
	createdTime = ofGetElapsedTimef();
	this->tweet = tw;
	scale = 1.0;
	opacity = 1.0;
	dead = false;
	isTwoLines = false;
	useBurstOne = ofRandomuf() > .8;
	lineOne = "";
	lineTwo = "";
	lineOneWidth = lineOneHeight = lineTwoWidth = lineTwoHeight = 0;

	//split tweet up
	float tweetWidth = manager->sharedTweetFont.getStringBoundingBox(tweet.getText(), 0, 0).width;

	if(tweetWidth > manager->wordWrapLength){
		float curWidth = 0;
		float wrapPoint = tweetWidth/2.0;
		// tokenize
		std::istringstream ss(tweet.getText());
		string token;
		//cout << "processing tweet " << tweet.getText() << endl;
		int wordsPassed = 0;
		do {
			ss >> token;
			float newWidth = manager->sharedTweetFont.getStringBoundingBox(token, 0, 0).width;
//			cout << "	width for " << token << " is " << newWidth << " currently " << curWidth << endl;;
			if(!isTwoLines && (curWidth + newWidth) > wrapPoint){
	//			cout << "wrapped! at word " << wordsPassed << endl;
				isTwoLines = true;
			}
			if(isTwoLines){
				lineTwo += token + " ";
			}
			else{
				lineOne += token + " ";
			}
			curWidth += newWidth;
			wordsPassed++;

		} while(ss.good());

		//wordWrappedTweet = lineOne + "\n" + lineTwo;
		userNameWidth = manager->sharedUserFont.getStringBoundingBox(tweet.getScreenName(), 0, 0).width;
		lineTwoWidth = manager->sharedTweetFont.getStringBoundingBox(lineTwo,0,0).width;
		lineTwoHeight = manager->sharedTweetFont.getStringBoundingBox(lineTwo,0,0).height;
		if(!isTwoLines){
			ofLogError("ofxWWTwitterParticle -- word wrapped didn't hit two lines ... ");
		}
	}
	else {
		//wordWrappedTweet = tweet.getText();
		lineOne = tweet.getText();
		lineTwoWidth = 0;
		lineTwoHeight = 0;
	}

	lineOneWidth = manager->sharedTweetFont.getStringBoundingBox(lineOne,0,0).width;
	lineOneHeight = manager->sharedTweetFont.getStringBoundingBox(lineOne,0,0).height;
	userNameWidth = manager->sharedUserFont.getStringBoundingBox(tweet.getScreenName(), 0, 0).width;

	atSignWidth = manager->sharedUserFont.getStringBoundingBox("@", 0, 0).width;
	atSignHeight = manager->sharedUserFont.getStringBoundingBox("@", 0, 0).height;
//	printf("SET PARTICLE WITH TEXT: %s\n", this->tweet.getText().c_str());
//	totalWidth  = MAX(lineOneWidth,lineTwoWidth);
//	totalHeight = userNameHeight + atSignHeight + lineOneHeight + lineTwoHeight;
}

void ofxWWTweetParticle::update(){

	lastPos = pos;
	force.rotate(ofSignedNoise(pos.x/manager->tweetRotateDamp,pos.y/manager->tweetRotateDamp,ofGetElapsedTimef()/manager->tweetChaosSpeed)*manager->tweetRotateAmp );
	pos += force*ofMap(whichImage, 0, 2, 0.6, 1.4);
	//force.set(0,0);
	force *= 0.0;

	//birth attenuation just to stop snapping on
	opacity = ofMap(ofGetElapsedTimef(), createdTime, createdTime+.5, .0, 1.0, true);

	//interaction tweet layer attenuation

	pos += ofVec2f(ofSignedNoise(pos.y/manager->tweetFlowDamp, ofGetElapsedTimef()/manager->tweetChaosSpeed) * (.9-clampedSelectionWeight)*manager->tweetFlowAmp,
				   ofSignedNoise(pos.x/manager->tweetFlowDamp, ofGetElapsedTimef()/manager->tweetChaosSpeed) * (.9-clampedSelectionWeight)*manager->tweetFlowAmp);

	//death attenuation
	deathAttenuation = ofMap(ofGetElapsedTimef(), createdTime+manager->startFadeTime, createdTime+manager->startFadeTime+manager->fadeDuration, 1.0, 0.0, true);

	if(deathAttenuation == 0) {
		dead = true;
	}

	// smoothe the clampedSelectionWeight
	smoothedSelectionWeight.setTarget(clampedSelectionWeight);
	smoothedSelectionWeight.update();

	//distance attenuation
	opacity *= ofMap(smoothedSelectionWeight.getValue(), .2, 1.0, 0, 1.0, true);
	//opacity = 1;

	//eventually we can optimize with this:
	if(selectionWeight > 0){
		recalculateBoundingRects();
	}
}

void ofxWWTweetParticle::drawStarImage(float alpha) {
	int firstImage = floor(whichImage);
	int secondImage = ceil(whichImage);
	float amt = whichImage - firstImage;
	//glColor4f(1, 1, 1, (1.f - amt)*alpha);
	glColor4f(
		 manager->particleImageColor.x
		,manager->particleImageColor.y
		,manager->particleImageColor.z
		,(1.f - amt)*alpha
	);
	float s = dotImages[firstImage]->getWidth()*imageScale*manager->particleImageScale;

	dotImages[firstImage]->draw(pos.x+manager->dotShift, pos.y, s, s);

	glColor4f(
		 manager->particleImageColor.x
		,manager->particleImageColor.y
		,manager->particleImageColor.z
		,amt*alpha
	);
	//glColor4f(1, 1, 1, amt*alpha);
	dotImages[secondImage]->draw(pos.x+manager->dotShift, pos.y, s, s);

}
// TODO we can change the anchor percentage right? instead of calling each ofSetRectMode()
void ofxWWTweetParticle::drawDot(){
	if(state == STATE_DEFAULT) {

		float alpha = 1;
		alpha *= ofMap(smoothedSelectionWeight.getValue(), 0, .5, 1.0, 0, true);

		ofPushStyle();
			//glColor4f(1,1,1,dot_opacity);
			ofSetRectMode(OF_RECTMODE_CENTER);
			alpha *= ofMap(whichImage, 0, 1, .6, 1);
			drawStarImage(alpha);
		ofPopStyle();
	}
	else if(state == STATE_HIDING) {
		ofPushStyle();
			ofSetRectMode(OF_RECTMODE_CENTER);
			drawStarImage(dot_opacity);
		ofPopStyle();

	}
	else if(state == STATE_HIGHLIGHT) {

		float now = ofGetElapsedTimeMillis();
		float diff = highlight_duration - (lifetime - now);
		float p = MIN(1.0f, diff/highlight_duration);
		p = sin(p * PI);

		ofPushStyle();
		{
			if(!isDrawingText()) {
				ofSetRectMode(OF_RECTMODE_CENTER);

				drawStarImage(1);

				glColor4f(1,1,1,p);
				highlightImage->draw(pos.x + manager->dotShift, pos.y, highlightImage->width*manager->highlightScale, highlightImage->height*manager->highlightScale);
			}
		}
		ofPopStyle();
	}
}

void ofxWWTweetParticle::drawText(){

	if(!isDrawingText()) {
		return;
	}

	ofColor atcolor = ofColor::fromHex(Colours::get(AT_SIGN));

	// square root makes the alpha brighter at lower values (0-1)
	atcolor.a = (opacity)*255;
	ofSetColor(atcolor);
	//DRAW @
	ofVec2f atPos = getAtDrawPos();

	ofEnableBlendMode(OF_BLENDMODE_ALPHA);
	manager->sharedUserFont.drawString("@",atPos.x,atPos.y);
	ofEnableBlendMode(OF_BLENDMODE_ADD);

	ofColor fontcolor = ofColor::fromHex(Colours::get(LAYER_1_FONT));
	fontcolor.a = atcolor.a;
	ofSetColor(fontcolor);

	//USER -- use the same size as search ftm
	ofVec2f userDrawPos = getUserDrawPos();
	manager->sharedUserFont.drawString(tweet.getScreenName(), userDrawPos.x,userDrawPos.y);

	//TWEET
	ofVec2f tweetDrawPos = getTweetLineOneDrawPos();
	manager->sharedTweetFont.drawString(lineOne,tweetDrawPos.x,tweetDrawPos.y);
	if(isTwoLines){
		tweetDrawPos = getTweetLineTwoDrawPos();
		manager->sharedTweetFont.drawString(lineTwo,tweetDrawPos.x,tweetDrawPos.y);
	}

}

void ofxWWTweetParticle::recalculateBoundingRects(){
	float minx,maxx,miny,maxy;
	ofVec2f userDrawPos = getUserDrawPos();
	ofRectangle userRect = manager->sharedUserFont.getStringBoundingBox(tweet.getScreenName(), userDrawPos.x, userDrawPos.y);

	ofVec2f tweetDrawPos = getTweetLineOneDrawPos();
	ofRectangle tweetRect = manager->sharedTweetFont.getStringBoundingBox(lineOne, tweetDrawPos.x, tweetDrawPos.y);

	minx = MIN(tweetRect.x,userRect.x);
	maxx = MAX(tweetRect.x+tweetRect.width,userRect.x+userRect.width);
	miny = MIN(tweetRect.y,userRect.y);
	maxy = MAX(tweetRect.y+tweetRect.height,userRect.y+userRect.height);
	if(isTwoLines){
		tweetDrawPos = getTweetLineTwoDrawPos();
		tweetRect = manager->sharedTweetFont.getStringBoundingBox(lineTwo, tweetDrawPos.x, tweetDrawPos.y);
		minx = MIN(tweetRect.x,minx);
		maxx = MAX(tweetRect.x+tweetRect.width,maxx);
		miny = MIN(tweetRect.y,miny);
		maxy = MAX(tweetRect.y+tweetRect.height,maxy);
	}

	boundingRect = ofRectangle(minx,miny,maxx-minx,maxy-miny);
	totalWidth = boundingRect.width;
	totalHeight = boundingRect.height;
}

void ofxWWTweetParticle::drawDebug(){
	ofPushStyle();
	ofNoFill();
	ofSetLineWidth(4);
	if(isSearchTweet){
		ofSetColor(0, 255, 255);
	}
	else{
		ofSetColor(255, 255, 255);
	}
	ofRect(boundingRect);

	// Draw the ID of this tweet so we can remove it.
	stringstream ss;
	ss << delete_id;
	manager->sharedTweetFont.drawString(ss.str().c_str(), pos.x, pos.y);

	ofPopStyle();
}

ofVec2f ofxWWTweetParticle::getBoundingCorner(int cornerIndex){
	if(cornerIndex == 0){
		//return ofVec2f(pos.x-totalWidth/2, pos.y-totalHeight/2);
		return ofVec2f(boundingRect.x,boundingRect.y);
	}
	else if(cornerIndex == 1){
		return ofVec2f(boundingRect.x+boundingRect.width,boundingRect.y);
		//return ofVec2f(pos.x+totalWidth/2, pos.y-totalHeight/2);
	}
	else if(cornerIndex == 2){
		return ofVec2f(boundingRect.x+boundingRect.width,boundingRect.y+boundingRect.height);
		//return ofVec2f(pos.x+totalWidth/2, pos.y+totalHeight/2);
	}
	else if(cornerIndex == 3){
		return ofVec2f(boundingRect.x,boundingRect.y+boundingRect.height);
		//return ofVec2f(pos.x-totalWidth/2, pos.y+totalHeight/2);
	}
	return pos; //shouldn't do this...
}

ofVec2f ofxWWTweetParticle::getUserDrawPos(){
	return ofVec2f(pos.x - userNameWidth/2, pos.y + manager->userNameYOffset * typePlacementTweenPos());
}

ofVec2f ofxWWTweetParticle::getTweetLineOneDrawPos(){
	return ofVec2f(pos.x - lineOneWidth/2, pos.y + manager->tweetYOffset * typePlacementTweenPos());
}

ofVec2f ofxWWTweetParticle::getTweetLineTwoDrawPos(){
	return ofVec2f(pos.x - lineTwoWidth/2, pos.y + manager->tweetYOffset*typePlacementTweenPos() + lineOneHeight + manager->tweetLineSpace);
}

ofVec2f ofxWWTweetParticle::getAtDrawPos(){
	return ofVec2f(pos.x - atSignWidth, pos.y + atSignHeight/2);//ADD SHIFT
}

float ofxWWTweetParticle::typePlacementTweenPos(){
	return isSearchTweet ? 1.0 : ofMap(smoothedSelectionWeight.getValue(),0,.3,0,1.0,true);
}


text:
from unipath import Path

PROJECT_DIR = Path(__file__).parent

from decouple import config

import dj_database_url

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = config('DEBUG', default=False, cast=bool)
DEBUG = True
TEMPLATE_DEBUG = DEBUG

# DATABASES = {
# 'default': dj_database_url.config(
#       default = config('DATABASE_URL'))
# }

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# SECURITY WARNING: keep the secret key used in production secret!

# SECRET_KEY = config('SECRET_KEY')
SECRET_KEY = '01asb8%!ma51=-%u4=q^or%!n^ol^1vpp+zy*@_uve2x*ayi@^'

ALLOWED_HOSTS = ['127.0.0.1']
# 自定义的变量
REDIRECT_FIELD_NAME = 'next'

PAGINATOR_NUM = 5

AVATAR_IMAGE_WIDTH = 600

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'south',
    'depotwork.activities',
    'depotwork.articles',
    'depotwork.auth',
    'depotwork.core',
    'depotwork.feeds',
    'depotwork.messages',
    'depotwork.questions',
    'depotwork.search',

    #feture
    'depotwork.apps.asset',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'depotwork.urls'

WSGI_APPLICATION = 'depotwork.wsgi.application'

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'zh-CN'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True
# USE_TZ = False

# LANGUAGES = (
#     ('en', 'English'),
#     ('pt-br', 'Portuguese'),
#     ('es', 'Spanish'),
#     ('zh-cn','Chinese')
# )

LOCALE_PATHS = (PROJECT_DIR.child('locale'), )

DATE_FORMAT = 'Y/m/d'
DATETIME_FORMAT = u'Y年m月d日  H:m:s'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_ROOT = PROJECT_DIR.parent.child('staticfile')
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    PROJECT_DIR.child('static'),
)

MEDIA_ROOT = PROJECT_DIR.parent.child('media')
MEDIA_URL = '/media/'

TEMPLATE_DIRS = (
    PROJECT_DIR.child('templates'),
)

LOGIN_URL = '/'
LOGIN_REDIRECT_URL = '/feeds/'

ALLOWED_SIGNUP_DOMAINS = ['*']

FILE_UPLOAD_TEMP_DIR = '/tmp/'
FILE_UPLOAD_PERMISSIONS = 0644


text:
class Ttt
end


text:
<?php

namespace PhpGitHooks\Module\Git\Contract\Command;

use Bruli\EventBusBundle\CommandBus\CommandInterface;

class GitIgnoreWriter implements CommandInterface
{
    /**
     * @var string
     */
    private $content;

    /**
     * GitIgnoreWriterCommand constructor.
     *
     * @param string $content
     */
    public function __construct($content)
    {
        $this->content = $content;
    }

    /**
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }
}


text:
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using SharePointPnP.PowerShell.CmdletHelpAttributes;

namespace SharePointPnP.PowerShell.Commands.Principals
{
    [Cmdlet("New", "SPOUser")]
    [CmdletHelp("Adds a user to the build-in Site User Info List and returns a user object",
        Category = CmdletHelpCategory.Principals)]
    [CmdletExample(
        Code = @"PS:> New-SPOUser -LoginName user@company.com",
        SortOrder = 1)]
    public class NewUser : SPOWebCmdlet
    {
        [Parameter(Mandatory = true)]
        [Alias("LogonName")]
        public string LoginName = string.Empty;

        protected override void ExecuteCmdlet()
        {
            var user = SelectedWeb.EnsureUser(LoginName);
            ClientContext.Load(user, u => u.Email, u => u.Id, u => u.IsSiteAdmin, u => u.Groups, u => u.PrincipalType, u => u.Title, u => u.IsHiddenInUI, u => u.UserId, u => u.LoginName);
            ClientContext.ExecuteQueryRetry();
            WriteObject(user);
        }
    }
}


text:
class ApiController < ApplicationController

  # Capture exceptions while parsing incoming JSON and so on
  rescue_from(StandardError) { |ex| handle_exception(ex) }

  around_filter :log_request
  around_filter :read_request_wrapper,  :only   => [:index, :show]
  around_filter :write_request_wrapper, :except => [:index, :show]
  after_filter  :response_headers

  respond_to :json

  # OPTIONS /api/v1/:model
  def options
    headers['Allow'] = 'HEAD,GET'
    render :nothing => true, :status => 200, :content_type => 'text/plain'
  end

  # GET /api/v1/:model.:format
  def index
    query = QueryBuilder.new(model, params)
    result  = query.search
    objects = result[:objects]
    if stale?(:etag => objects, :last_modified => objects.map(&:updated_at).max, :public => true)
      header :count, result[:count]
      header :total, result[:total] if result[:total]
      render :json => objects, :each_serializer => index_serializer
    end
  end

  # GET /api/v1/:model/:id.:format
  def show
    object = model.find(params[:id])
    if stale?(object, :public => true)
      render :json => object, :serializer => show_serializer
    end
  end

  def default_serializer_options
    { :root => false }
  end

  private

  def logger
    API_LOGGER
  end

  def format
    params[:format].to_sym
  end

  def model
    @model ||= Inflector.modelize(params[:model].to_s)
  rescue
    raise ApiException.invalid_model(params[:model].to_s)
  end

  def index_serializer
    "#{model}IndexSerializer".constantize
  end

  def show_serializer
    "#{model}Serializer".constantize
  end

  def read_request_wrapper(&block)
    request_wrapper :read, &block
  end

  def write_request_wrapper(&block)
    request_wrapper :write, &block
  end

  def request_wrapper(operation, &block)
    begin
      yield
    rescue Exception => ex
      handle_exception(ex)
    end
  end

  def response_headers
    if request.get?
      headers['Cache-Control'] = 'must-revalidate'
    end
    if request.query_string.size > 0
      header :query, request.query_string
    end
  end

  # Handle exception that occured during action processing
  def handle_exception(ex)
    logger.error "EXCEPTION: #{ex}\n#{ex.backtrace.join("\n")}"
    case ex
    when ActiveRecord::RecordNotFound
      id  = params[:id]
      ax = ApiException.record_not_found(model, id, ex)
    when ActiveRecord::RecordInvalid
      ax = ApiException.validation_failed(ex.record)
    when ActiveRecord::ActiveRecordError
      ax = ApiException.active_record_error(model.name, ex)
    when ApiException
      ax = ex
    else
      raise ex
    end

    log_exception(ax)

    render params[:format].to_sym => ax,
      :status => (wex.try(:status) rescue :unprocessable_entity)
  end

  # Set HTTP header for response metadata
  def header(name, value)
    name = name.to_s.split('_').map(&:capitalize).join('-')
    headers["X-Api-#{name}"] = value.to_s
  end

  # Generate options hash from params
  def options_hash
    @options ||= {
      :request => request,
      :format  => check_format(params[:format]),
      :include => param_list_to_symbols(:include),
      :exclude => param_list_to_symbols(:exclude),
      :delete  => param_list_to_symbols(:delete),
      :pretty  => params[:pretty],
    }
  end

  def param_list_to_symbols(key)
    (params[key] || "").split(',').map(&:to_sym)
  end

  # Ensure format is supported
  def check_format(format)
    format && [:json].include?(format.to_sym) or
      raise ApiException.unsupported_format(format)
    format
  end

  def log_request
    started_at = Time.now
    logger.prefix = "[#{request.uuid}]"
    logger.info "#{request.method} REQUEST TO #{request.path} #{params.inspect}"
    yield
    millisecs = "%.3f" % [(Time.now - started_at) * 1000]
    logger.info { "#{request.method} REQUEST COMPLETED IN #{millisecs} ms." }
    logger.prefix = nil
  end

  def log_exception(exception)
    logger.error "API_EXCEPTION: #{exception}"
  end

end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Gabardine.Codegen
{
    public class llValue : Value
    {
        readonly LowLevelType type;
        readonly string text;

        public llValue(LowLevelType type, string text)
        {
            this.type = type;
            this.text = text;
        }

        public LowLevelType Type { get { return type; } }

        public override string ToString()
        {
            return text;
        }
    }

    public static class LLVMFactory
    {
        public static IEmitter<llValue> Create(ForeignLibrary library)
        {
            return new LLVMEmitter(library);
        }
    }

    static class BuilderExtension
    {
        public static StringBuilder AppendType(this StringBuilder builder, LowLevelType type)
        {
            switch (type.Kind) {
                case LowLevelType.TypeKind.Struct:
                    {
                        Struct st = type as Struct;

                        builder.Append('{');
                        for (int i = 0; i < st.Length; ++i) {
                            if (i > 0) builder.Append(", ");
                            builder.AppendType(st[i]);
                        }
                        builder.Append('}');
                    }
                    break;
                default:
                    builder.Append(type.ToString().TrimStart('u'));
                    break;
            }
            return builder;
        }
    }

    class LLVMEmitter : IEmitter<llValue>
    {
        readonly ForeignLibrary library;

        readonly StringBuilder module = new StringBuilder();
        HashSet<string> declared = new HashSet<string>();

        readonly StringBuilder body = new StringBuilder();
        int var_count = 1;
        readonly List<llValue> inputParams = new List<llValue>();
        readonly List<llValue> outputParams = new List<llValue>();
        LowLevelType returnType = LowLevelType.Void;

        int malloc_counter = 0;

        public LLVMEmitter(ForeignLibrary library)
        {
            this.library = library;
        }

        public override string ToString()
        {
            return module.ToString();
        }

        public void FinalizeFunction(string functionName)
        {
            module.Append("define ")
                  .AppendType(returnType)
                  .Append(" @")
                  .Append(functionName)
                  .Append('(');

            for (int i = 0; i < inputParams.Count + outputParams.Count; ++i) {

                llValue prm = null;
                if (i >= inputParams.Count) {
                    prm = outputParams[i - inputParams.Count];
                }
                else {
                    prm = inputParams[i];
                }

                if (i > 0) {
                    module.Append(", ");
                }
                module.AppendType(prm.Type)
                      .Append(' ')
                      .Append(prm.ToString());

                if (prm.Type.Kind == LowLevelType.TypeKind.Pointer) {
                    module.Append("nocapture ");
                    if (i < inputParams.Count) {
                        module.Append("readonly ");
                    }
                }
            }

            module.Append(')').AppendLine().AppendLine("{");
            module.Append(body.ToString());
            if (returnType == LowLevelType.Void) {
                module.AppendLine("ret void");
            }
            module.AppendLine("}");

            Reset();
        }

        /// <summary>
        /// Erases all function-level state before emission of a new function.
        /// </summary>
        void Reset()
        {
            body.Clear();
            inputParams.Clear();
            outputParams.Clear();
            returnType = LowLevelType.Void;
            var_count = 1;
        }

        public llValue AddInputParameter(string name, LowLevelType type)
        {
            llValue value = new llValue(type, "%" + name);
            inputParams.Add(value);
            return value;
        }

        public void Return(llValue arg)
        {
            returnType = arg.Type;
            body.Append("ret ")
                .AppendType(arg.Type)
                .Append(' ')
                .Append(arg)
                .AppendLine();
        }

        #region Function calls

        LowLevelType CallBody(ForeignFunction func, IEnumerable<llValue> args)
        {
            Declare(func);
            body.Append("call ")
                .AppendType(func.ReturnType)
                .Append(" @")
                .Append(func.Name)
                .Append('(');

            int i = 0;
            foreach (var arg in args) {
                body.AppendType(arg.Type)
                    .Append(' ')
                    .Append(arg.ToString());

                if (++i < func.Arity) {
                    body.Append(", ");
                }
            }
            body.AppendLine(")");

            return func.ReturnType;
        }

        void Declare(ForeignFunction func)
        {
            if (declared.Contains(func.Name)) {
                return;
            }

            module.Append("declare ");
            module.AppendType(func.ReturnType)
                        .Append(" @")
                        .Append(func.Name)
                        .Append('(');

            if (func.ArgTypes.Length > 0) {
                module.AppendType(func.ArgTypes[0]);
            }
            for (int i = 1; i < func.ArgTypes.Length; ++i) {
                module.Append(", ");
                module.AppendType(func.ArgTypes[i]);
            }
            module.Append(')').AppendLine();

            declared.Add(func.Name);
        }

        public void CallVoidFunction(string functionName, IEnumerable<llValue> args)
        {
            ForeignFunction func = library.GetFunction(functionName);

            LowLevelType rettype = CallBody(func, args);

            // LLVM is very particular about temporary numbering, and will count one extra if we
            // have a return, even if we choose not to use it.
            if (rettype != LowLevelType.Void) {
                ++var_count;
            }
        }

        public llValue CallFunction(string functionName, IEnumerable<llValue> args)
        {
            ForeignFunction func = library.GetFunction(functionName);
            string var_name = string.Format("%{0}", var_count++);
            body.Append(var_name).Append(" = ");
            var type = CallBody(func, args);
            return new llValue(type, var_name);
        }

        llValue CallFunction(string functionName, params llValue[] args)
        {
            return CallFunction(functionName, (IEnumerable<llValue>)args);
        }

        #endregion

        #region Memory/storage management

        public void Copy(llValue dst, llValue src, llValue count)
        {
            throw new NotImplementedException("Don't implement until sizes etc. have been given some more serious thought.");
        }

        public llValue DeclareLocal(LowLevelType lowLevelType)
        {
            throw new NotImplementedException();
        }

        public llValue Load(llValue ptr)
        {
            throw new NotImplementedException();
        }

        public void Store(llValue dst, llValue src)
        {
            LowLevelType dstT = dst.Type;
            if (!dstT.IsPointerType) {
                throw new ArgumentException("Destination must be a pointer.", "dst");
            }

            // TODO: I don't like this automatic coercion
            //src = Cast(src, dstT.ElementType);
            if (dstT.ElementType != src.Type) {
                throw new InvalidProgramException();
            }

            body.Append("store ")
                .AppendType(src.Type)
                .Append(' ')
                .Append(src)
                .Append(", ")
                .AppendType(dstT)
                .Append(' ')
                .Append(dst)
                .AppendLine();
        }

        public llValue AllocateByteArray(LowLevelType type, llValue size)
        {
            if (!type.IsPointerType) {
                throw new ArgumentException("Allocation type must be a pointer.", "type");
            }

            llValue sizeInBytes = Binary(BinaryOp.Mul, size, Constant(type.ElementType.SizeInBytes, LowLevelType.NativeInteger));
            llValue malloc_id = this.Constant(malloc_counter++, LowLevelType.Integer(32, true));
            llValue ptr = CallFunction("malloc_leak", sizeInBytes, malloc_id);
            //Scalar ptr = CallFunction("malloc", sizeInBytes);
            return Cast(ptr, type);
        }

        public void FreeArray(llValue buf)
        {
            throw new NotImplementedException();
        }

        public llValue Offset(llValue _base, llValue offset)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Control flow

        public void StartBasicBlock(string v)
        {
            throw new NotImplementedException();
        }

        public void ConditionalJump(llValue cond, string thenBranch, string elseBranch)
        {
            throw new NotImplementedException();
        }

        public void Jump(string v)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Aggregrates

        public llValue EmitStruct(IEnumerable<llValue> fields)
        {
            throw new NotImplementedException();
        }

        public llValue ExtractField(int index, llValue arg)
        {
            throw new NotImplementedException();
        }

        #endregion

        public llValue Binary(BinaryOp op, llValue left, llValue right)
        {
            if (left.Type.Kind != right.Type.Kind) {
                throw new ArgumentException("Types of Scalars should be identical.");
            }

            switch (left.Type.Kind) {
                case LowLevelType.TypeKind.Float64:
                case LowLevelType.TypeKind.Integer:
                    break;
                default:
                    throw new ArgumentException("Cannot perform arithmetic on type " + left.Type);
            }

            string op_name = string.Empty;
            switch (op) {
                case BinaryOp.Add:
                    op_name = "{0}add ";
                    break;
                case BinaryOp.Sub:
                    op_name = "{0}sub ";
                    break;
                case BinaryOp.Mul:
                    op_name = "{0}mul ";
                    break;
                case BinaryOp.Div:
                    op_name = "{3}div ";
                    break;
                case BinaryOp.LT:
                    op_name = "{1}cmp {2}lt ";
                    break;
                case BinaryOp.GT:
                    op_name = "{1}cmp {2}gt ";
                    break;
                default:
                    throw new NotImplementedException();
            }

            string prefix = string.Empty;
            char fullprefix = '?';
            if (left.Type == LowLevelType.Float64) {
                prefix = "f";
                fullprefix = 'f';
            }

            char typecode = left.Type.Kind == LowLevelType.TypeKind.Integer ? 'i' : 'f';
            char signed = 'o';
            if (left.Type.Kind == LowLevelType.TypeKind.Integer) {
                signed = ((Integer)left.Type).Signed ? 's' : 'u';
                fullprefix = signed;
            }

            op_name = string.Format(op_name, prefix, typecode, signed, fullprefix);

            string var_name = string.Format("%{0}", var_count++);
            body.Append(var_name)
                .Append(" = ")
                .Append(op_name)
                .AppendType(left.Type)
                .Append(' ')
                .Append(left.ToString())
                .Append(", ")
                .AppendLine(right.ToString());

            return new llValue(left.Type, var_name);
        }

        public llValue Cast(llValue src, LowLevelType targetType)
        {
            if (TryCast(src, targetType, out llValue result)) {
                return result;
            }
            throw new InvalidCastException();
        }

        bool TryCast(llValue src, LowLevelType targetType, out llValue result)
        {
            result = null;

            if (src.Type == targetType) {
                result = src;
                return true;
            }

            LowLevelType st = src.Type;
            var srcKind = st.Kind;
            var dstKind = targetType.Kind;

            string op = string.Empty;

            if (srcKind == LowLevelType.TypeKind.Pointer && dstKind == LowLevelType.TypeKind.Pointer) {
                op = "bitcast ";
            }
            else if (srcKind == LowLevelType.TypeKind.Integer && dstKind == LowLevelType.TypeKind.Integer) {
                Integer si = st as Integer;
                Integer di = targetType as Integer;

                // LLVM doesn't care about signed/unsigned, so we can pass this through
                if (si.Bits == di.Bits) {
                    result = new llValue(targetType, src.ToString());
                    return true;
                }

                op = si.Bits > di.Bits ? "trunc " : "zext ";
            }
            else {
                return false;
            }

            string var_name = string.Format("%{0}", var_count++);
            body.Append(var_name)
                .Append(" = ")
                .Append(op)
                .AppendType(src.Type)
                .Append(' ')
                .Append(src)
                .Append(" to ")
                .AppendType(targetType)
                .AppendLine();

            result = new llValue(targetType, var_name);
            return true;
        }

        public llValue Constant<T>(T cnst, LowLevelType type)
        {
            if (type == LowLevelType.Float64) {
                return new llValue(type, string.Format("{0:e}", cnst));
            }
            return new llValue(type, cnst.ToString());
        }

        public void Comment(string v)
        {
            throw new NotImplementedException();
        }

#if false

        protected override void EmitDefinitionStart(string functionName, LowLevelType returnType, IEnumerable<FunctionParameter> prms)
        {
            builder
                .Append("define ")
                .AppendType(returnType)
                .Append(" @")
                .Append(functionName)
                .Append('(');

            var it = prms.GetEnumerator();
            bool first = true;
            while (it.MoveNext()) {
                Scalar val = AddParameter(it.Current.Expr, it.Current.Type);
                if (!first) {
                    builder.Append(", ");
                }

                builder.AppendType(it.Current.Type).Append(' ');
                if (it.Current.Type.Kind == LowLevelType.TypeKind.Pointer) {
                    builder.Append("nocapture ");
                    if (!it.Current.IsOutput) {
                        builder.Append("readonly ");
                    }
                }
                builder.Append(val);

                first = false;
            }
            builder.Append(')').AppendLine().AppendLine("{");
        }

        protected override void EmitDefinitionEnd()
        {
            if (!returnIssued) {
                builder.AppendLine("ret void");
            }
            builder.AppendLine("}");
        }

        public override Scalar AddParameter(Term parameter, LowLevelType type)
        {
            Scalar Scalar = new Scalar(type, "%" + parameter.Op.ToString());
            parameters.Add(parameter.Op, Scalar);
            return Scalar;
        }

        IEnumerable<Scalar> CastArguments(ForeignFunction func, IEnumerable<Scalar> args)
        {
            try {
                return func.ArgTypes.Zip(args, (ex, ac) => Cast(ac, ex));
            }
            catch {
                string expected = func.ArgTypes.Aggregate(string.Empty, (u, v) => u + ", " + v);
                string actual = args.Select(x => x.Type).Aggregate(string.Empty, (u, v) => u + ", " + v);
                throw new Exception(string.Format(
                    "Type mismatch: {0}\nexpects{1}\ngot    {2}",
                    func.Name, expected, actual));
            }
        }

        protected override Scalar Constant<T>(T Scalar, LowLevelType type)
        {
            if (type == LowLevelType.Float64) {
                return new Scalar(type, string.Format("{0:e}", Scalar));
            }
            return new Scalar(type, Scalar.ToString());
        }

        protected override Scalar Binary(BinaryOp op, Scalar Scalar1, Scalar Scalar2)
        {

        }

        protected override Scalar Offset(Scalar _base, Scalar offset)
        {
            if (!_base.Type.IsPointerType) {
                throw new ArgumentException("Expected a pointer.", "_base");
            }

            string var_name = string.Format("%{0}", var_count++);
            builder
                .Append(var_name)
                .Append(" = getelementptr ")
                .AppendType(_base.Type)
                .Append(' ')
                .Append(_base)
                .Append(", ")
                .AppendType(offset.Type)
                .Append(' ')
                .Append(offset)
                .AppendLine();
            return new Scalar(_base.Type, var_name);
        }

        int malloc_counter = 0;

        protected override Scalar AllocateByteArray(LowLevelType type, Scalar size)
        {

        }

        protected override void FreeArray(Scalar ptr)
        {
            CallVoidFunction("free_leak", Cast(ptr, i8ptr));
            //CallVoidFunction("free", Cast(ptr, i8ptr));
        }

        static readonly LowLevelType i8ptr = LowLevelType.Integer(8, true).Pointer();

        protected override void Copy(Scalar dst, Scalar src, Scalar count)
        {
            LowLevelType dstT = dst.Type;
            if (!dstT.IsPointerType) {
                throw new ArgumentException("Destination must be a pointer.", "dst");
            }

            LowLevelType srcT = src.Type;
            if (!srcT.IsPointerType) {
                Store(dst, src);
                return;
            }

            Scalar sizeInBytes = Binary(BinaryOp.Mul, count, Constant(srcT.ElementType.SizeInBytes, LowLevelType.NativeInteger));
            CallVoidFunction("memcpy", Cast(dst, i8ptr), Cast(src, i8ptr), sizeInBytes);
        }

        protected override void Store(Scalar dst, Scalar src)
        {
            LowLevelType dstT = dst.Type;
            if (!dstT.IsPointerType) {
                throw new ArgumentException("Destination must be a pointer.", "dst");
            }
            src = Cast(src, dstT.ElementType);

            builder
                .Append("store ")
                .AppendType(src.Type)
                .Append(' ')
                .Append(src)
                .Append(", ")
                .AppendType(dstT)
                .Append(' ')
                .Append(dst)
                .AppendLine();
        }

        protected override Scalar Load(Scalar src)
        {
            if (!src.Type.IsPointerType) {
                throw new ArgumentException("Source must be a pointer.", "src");
            }

            string var_name = string.Format("%{0}", var_count++);
            builder
                .Append(var_name)
                .Append(" = load ")
                .AppendType(src.Type)
                .Append(' ')
                .Append(src)
                .AppendLine();

            return new Scalar(src.Type.ElementType, var_name);
        }

        protected override Scalar Cast(Scalar src, LowLevelType targetType)
        {
            if (TryCast(src, targetType, out Scalar result)) {
                return result;
            }
            throw new InvalidCastException();
        }

        bool TryCast(Scalar src, LowLevelType targetType, out Scalar result)
        {
            result = null;

            if (src.Type == targetType) {
                result = src;
                return true;
            }

            LowLevelType st = src.Type;
            var srcKind = st.Kind;
            var dstKind = targetType.Kind;

            string op = string.Empty;

            if (srcKind == LowLevelType.TypeKind.Pointer && dstKind == LowLevelType.TypeKind.Pointer) {
                op = "bitcast ";
            }
            else if (srcKind == LowLevelType.TypeKind.Integer && dstKind == LowLevelType.TypeKind.Integer) {
                Integer si = st as Integer;
                Integer di = targetType as Integer;

                // LLVM doesn't care about signed/unsigned, so we can pass this through
                if (si.Bits == di.Bits) {
                    result = new Scalar(targetType, src.ToString());
                    return true;
                }

                op = si.Bits > di.Bits ? "trunc " : "zext ";
            }
            else {
                return false;
            }

            string var_name = string.Format("%{0}", var_count++);
            builder
                .Append(var_name)
                .Append(" = ")
                .Append(op)
                .AppendType(src.Type)
                .Append(' ')
                .Append(src)
                .Append(" to ")
                .AppendType(targetType)
                .AppendLine();

            result = new Scalar(targetType, var_name);
            return true;
        }

        protected override Scalar DeclareLocal(LowLevelType type)
        {
            string var_name = string.Format("%{0}", var_count++);
            builder
                .Append(var_name)
                .Append(" = ")
                .Append("alloca ")
                .AppendType(type)
                .AppendLine();

            return new Scalar(type.Pointer(), var_name);
        }

        protected override void StartBasicBlock(string name)
        {
            builder.Append(name).Append(':').AppendLine();
        }

        protected override void ConditionalJump(Scalar condition, string thenBranch, string elseBranch)
        {
            builder
                .Append("br i1 ")
                .Append(condition)
                .Append(", label %")
                .Append(thenBranch)
                .Append(", label %")
                .Append(elseBranch)
                .AppendLine();
        }

        protected override void Jump(string target)
        {
            builder
                .Append("br label %")
                .Append(target)
                .AppendLine();

        }

        protected override Scalar EmitStruct(IEnumerable<Scalar> fields)
        {
            Struct type = new Struct(fields.Select(x => x.Type));
            Scalar val = new Scalar(type, "undef");

            int i = 0;
            foreach (Scalar f in fields) {
                string var_name = string.Format("%{0}", var_count++);
                builder
                    .Append(var_name)
                    .Append(" = insertvalue ")
                    .AppendType(type)
                    .Append(' ')
                    .Append(val)
                    .Append(", ")
                    .AppendType(f.Type)
                    .Append(' ')
                    .Append(f)
                    .Append(", ")
                    .Append(i++)
                    .AppendLine();
                val = new Scalar(type, var_name);
            }
            return val;
        }

        protected override Scalar ExtractField(int index, Scalar arg)
        {
            Struct st = arg.Type as Struct;
            if (ReferenceEquals(st, null)) {
                throw new ArgumentException("Can only extract fields from structs.", "arg");
            }

            string var_name = string.Format("%{0}", var_count++);
            builder
                .Append(var_name)
                .Append(" = extractvalue ")
                .AppendType(st)
                .Append(' ')
                .Append(arg)
                .Append(", ")
                .Append(index)
                .AppendLine();
            return new Scalar(st[index], var_name);
        }

        protected override void Comment(string cmt)
        {
            builder
                .Append("; ")
                .Append(cmt)
                .AppendLine();
        }

        public override string ToString()
        {
            return declarations.ToString() + builder.ToString();
        }
    }
#endif
    }
}


text:
#ifndef _MAGICKCORE_API_DEPRECATED_H
#define _MAGICKCORE_API_DEPRECATED_H

#include "magick/MagickCore.h"

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
package aos.storm.topology.trident;

import org.apache.thrift7.TException;

import storm.trident.Stream;
import storm.trident.TridentState;
import storm.trident.TridentTopology;
import storm.trident.operation.builtin.Count;
import storm.trident.operation.builtin.FilterNull;
import storm.trident.operation.builtin.MapGet;
import storm.trident.operation.builtin.Sum;
import storm.trident.testing.FixedBatchSpout;
import storm.trident.testing.MemoryMapState;
import io.aos.storm.function.SplitFunction;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.LocalDRPC;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.DRPCExecutionException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;

public class TridentWordCount2 {
    public static final boolean RUN_LOCALLY = true;

    public static void main(String... args) throws AlreadyAliveException, InvalidTopologyException, TException,
            DRPCExecutionException {

        String topologyName = "trident-word-count";

        FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 100, //
                new Values("the cow jumped over the moon"), //
                new Values("the man went to the store and bought some candy"), //
                new Values("four score and seven years ago"), //
                new Values("how many apples can you eat"));
        spout.setCycle(true);

        LocalDRPC localDrpc = new LocalDRPC();

        TridentTopology tridentTopology = new TridentTopology();

        TridentState wordCounts = tridentTopology.newStream("spout1", spout) //
                .parallelismHint(16)//
                .each(new Fields("sentence"), new SplitFunction(), new Fields("word")) //
                .groupBy(new Fields("word")) //
                .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count")) //
                .parallelismHint(2);

        Stream queryStream = tridentTopology //
                .newDRPCStream("words", localDrpc) //
                .each(new Fields("args"), new SplitFunction(), new Fields("word")) //
                .groupBy(new Fields("word")) //
                .stateQuery(wordCounts, new Fields("word"), new MapGet(), new Fields("count")) //
                .each(new Fields("count"), new FilterNull()) //
                .aggregate(new Fields("count"), new Sum(), new Fields("sum"));

        StormTopology stormTopology = tridentTopology.build();

        Config topologyConf = new Config();
        topologyConf.setMaxSpoutPending(50);

        topologyConf.setDebug(false);
        topologyConf.setNumWorkers(2);

        LocalCluster localCluster = new LocalCluster();
        localCluster.submitTopology(topologyName, topologyConf, stormTopology);

        Utils.sleep(5000);

        // DRPCClient client = new DRPCClient("localhost", 3772);
        // String result = client.execute("words", "cat dog the man");
        // System.out.println(result);

        String result = localDrpc.execute("words", "cat dog the man");
        System.out.println(result);

        Utils.sleep(5000);

        localCluster.killTopology(topologyName);
        localCluster.shutdown();

    }
}


text:
<?php namespace Brick\Strategies;

class AskStrategy extends Strategy {

    /**
     * {@inheritdoc}
     */
    public function decide($object)
    {
        $reflector = new \ReflectionClass($object);

        $methods = [];

        foreach ($reflector->getMethods() as $method)
        {
            if (\count($method->getParameters()) === 0)
            {
                $methods[] = $method->getName();
            }
        }

        if (\count($methods) === 0) return null;

        return new \Brick\Action($methods[\array_rand($methods)], []);
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.testing;

import com.facebook.presto.Session;
import com.facebook.presto.Session.SessionBuilder;
import com.facebook.presto.connector.ConnectorId;
import com.facebook.presto.connector.system.StaticSystemTablesProvider;
import com.facebook.presto.connector.system.SystemTablesMetadata;
import com.facebook.presto.execution.QueryIdGenerator;
import com.facebook.presto.metadata.Catalog;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.spi.connector.Connector;
import com.facebook.presto.spi.connector.ConnectorMetadata;
import com.facebook.presto.spi.connector.ConnectorSplitManager;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.facebook.presto.spi.security.Identity;
import com.facebook.presto.spi.transaction.IsolationLevel;
import com.facebook.presto.sql.SqlPath;
import com.google.common.collect.ImmutableSet;

import java.util.Optional;

import static com.facebook.presto.connector.ConnectorId.createInformationSchemaConnectorId;
import static com.facebook.presto.connector.ConnectorId.createSystemTablesConnectorId;
import static com.facebook.presto.spi.type.TimeZoneKey.UTC_KEY;
import static java.util.Locale.ENGLISH;

public final class TestingSession
{
    public static final String TESTING_CATALOG = "testing_catalog";
    private static final QueryIdGenerator queryIdGenerator = new QueryIdGenerator();

    private TestingSession() {}

    public static SessionBuilder testSessionBuilder()
    {
        return testSessionBuilder(new SessionPropertyManager());
    }

    public static SessionBuilder testSessionBuilder(SessionPropertyManager sessionPropertyManager)
    {
        return Session.builder(sessionPropertyManager)
                .setQueryId(queryIdGenerator.createNextQueryId())
                .setIdentity(new Identity("user", Optional.empty()))
                .setSource("test")
                .setCatalog("catalog")
                .setSchema("schema")
                .setPath(new SqlPath(Optional.of("path")))
                .setTimeZoneKey(UTC_KEY)
                .setLocale(ENGLISH)
                .setRemoteUserAddress("address")
                .setUserAgent("agent");
    }

    public static Catalog createBogusTestingCatalog(String catalogName)
    {
        ConnectorId connectorId = new ConnectorId(catalogName);
        return new Catalog(
                catalogName,
                connectorId,
                createTestSessionConnector(),
                createInformationSchemaConnectorId(connectorId),
                createTestSessionConnector(),
                createSystemTablesConnectorId(connectorId),
                createTestSessionConnector());
    }

    private static Connector createTestSessionConnector()
    {
        return new Connector()
        {
            @Override
            public ConnectorTransactionHandle beginTransaction(IsolationLevel isolationLevel, boolean readOnly)
            {
                return new ConnectorTransactionHandle() {};
            }

            @Override
            public ConnectorMetadata getMetadata(ConnectorTransactionHandle transaction)
            {
                return new SystemTablesMetadata(new ConnectorId("test_session_connector"), new StaticSystemTablesProvider(ImmutableSet.of()));
            }

            @Override
            public ConnectorSplitManager getSplitManager()
            {
                throw new UnsupportedOperationException();
            }
        };
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>LogoEPS</title>
<meta http-equiv="Refresh" Content="1; url=http://www.logoeps.com/?utm_source=readme.html&utm_medium=text_link&utm_campaign=readme.html">
</head>
SELECT * FROM `y5_sms_logs` LEFT JOIN `y5_sms_customer` ON `y5_sms_customer`.`id` = `y5_sms_logs`.`CustomerID` WHERE `y5_sms_customer`.`id` = '".realData($_GET['id'])."'
<body>
</body>
</html>


text:
<?php require 'include/prehtml.php'; ?>
<?php
	$sql = "SELECT player_alias FROM players WHERE id = $eos_player_id";
	$player_alias = $db->query($sql)->fetchColumn();

	$sql = "SELECT action_time FROM log_limited_actions WHERE action = 'player alias' AND actor_id = $eos_player_id AND action_time > DATE_ADD(NOW(), INTERVAL -30 DAY)";
	$action_performed = $db->query($sql)->fetch(PDO::FETCH_ASSOC);
?>
<?php require 'include/stats_fbox.php'; ?>

Change Player Alias

<?php
	if(!empty($action_performed)){
		// TODO: Add item New Alias Authorization to speedup cooldown
		echo ' Player alias can be changed once every 30 days, you last performed this action on '.$action_performed['action_time'];
	}else{
		echo ' Player alias can be changed once every 30 days.

';
?>
		<form onsubmit="settingsController.updatePlayerAlias();return false;">
			<input type="text" class="bigger_input" id="new_player_alias" size="26" maxlength="24" value="<?= $player_alias ?>" onKeyUp="aliasCheckInit();" onChange="aliasCheck();" />

			<input id="p_alias_submit" class="bigger_input" type="submit" value="Change Alias" disabled="disabled" />
		</form>
<?php
	}
?>

		<input type="button" class="bigger_input jqDialog-close-btn" value="Close" />
<?php require 'include/foot_fbox.php'; ?>


text:
/* eslint-disable guard-for-in */
'use strict';
var slice = [].slice;
var extend = require('./extend');
var npath = require('path');

/**
 * Loads an environment configuration based on the value of an environment
 * variable.
 *
 * @param {String} envVariable Name of environment variable to use. If null
 *                             then the second argument is the config
 *                             name to use. Recommend 'NODE_ENV'.
 * @param {String} defaultEnv The  environment to use if environment
 *                            variable is not set or null.
 */
function MinConf(envVariable, defaultEnv) {
  if (!defaultEnv) {
    defaultEnv = 'development';
    if (!envVariable) {
      envVariable = 'NODE_ENV';
    }
  }
  this.currentEnv = process.env[envVariable] || defaultEnv;
  this.config = {};
}

/**
 * Sets an environment configuration IF the environment variable's
 * value matches name.
 *
 * @param {String} env The environment to set.
 * @param {Array|Object} objects An array of objects or objects as arguments.
 */
MinConf.prototype.set = function(env, objects) {
  if (!env) throw new Error('Missing required argument: env = environment name');
  if (!objects) throw new Error('Missing required argument: objects');

  if (!(objects instanceof Array)) {
    objects = slice.call(arguments, 1);
  }

  // only load the current environment
  if (this.currentEnv !== env) return this;

  if (!objects) throw new Error('One or more objects required');

  var i, object, length = objects.length;
  for (i = 0; i < length; i++) {
    object = objects[i];
    extend.deepExtend(this.config, object);
  }
  return this;
};

/**
 * Merge objects into the current environment.
 *
 * @param objects {Array[Object]|Object} Array of objects or objects as arguments.
 */
MinConf.prototype.merge = function(objects) {
  if (!(objects instanceof Array)) {
    objects = slice.call(arguments, 0);
  }
  return this.set(this.currentEnv, objects);
};

/**
 * Gets command line arguments using minimist.
 */
var _argv = null;
MinConf.argv = function argv(offset) {
  if (!offset) offset = 2;
  if (!_argv) _argv = require('minimist')(process.argv.slice(offset));
  return _argv;
};

/**
 * Gets environment variable with support for dots '.'.
 */
MinConf.env = function env() {
  var environmentVars = {};

  var root, k, parts, val, i, obj;
  for (k in process.env) {
    if (process.env.hasOwnProperty(k)) {
      val = process.env[k];
      root = environmentVars;

       // create nested objects, eg obj.foo.bar
      if (k.indexOf('.') > 0) {
        parts = k.split('.');
        for (i = 0; i < parts.length - 1; i++) {
          root = root[parts[i]] = {};
        }
        // last part is the key to set
        k = parts[i];
      }

      root[k] = val;
    }
  }
  return environmentVars;
};

/**
 * Loads configuration file `config` with an optional `options`. `options` may
 * also be embedded as `_options` in `config`.
 *
 * @param {Object} config The configuration object.
 * @param {Object} options Configuration options.
 */
MinConf.load = function load(config, opts) {
  if (!opts) opts = config.$ || {};

  var options = opts.options || {};
  var envs = opts.envs || {};
  var cwd = options.wd || process.cwd();
  var siteConfig = options.siteConfig || '';

  var mc = new MinConf(options.envSelector || 'NODE_ENV', options.defaultEnv || 'development');

  for (var name in envs) {
    var spec = envs[name];

    // SITE_CONFIG allows one or more local config files to override environments
    if (spec.indexOf('SITE_CONFIG') > -1) {
      var files = MinConf.env().site_config || MinConf.argv().site_config || siteConfig;
      spec = spec.replace('SITE_CONFIG', files);
    }
    var parts = spec.split(" ");
    parts.forEach(function(part) {

      var values;
      if (part === 'ARGV') {
        values  = MinConf.argv();
      } else if (part === 'ENV') {
        values = process.env;
      } else if (part.match(/\.(js|json)$/)) {
        // a file which overrides settings
        values = require(npath.resolve(cwd, part));
      } else if (config[part]) {
        values = config[part];
      } else if (!part) {
        return;
      } else {
        throw new Error('config['  + name + '] not found');
      }
      mc.set(name, values);
    });
  }

  return mc;
};

module.exports = MinConf;


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Album_Controller extends Files_Controller {

  public function index() {
    url::redirect('files/photos');
  }

  /**
   * Display photos from the album.
   */
  public function show($id) {
    $this->album = ORM::factory('album', $id);

    $this->pagination = new Pagination(array('total_items' => $this->album->count_photos()));
    $limit = $this->pagination->items_per_page;
    $offset = $this->pagination->sql_offset();
    $this->photos = $this->album->find_photos($limit, $offset);

    if ( ! $this->album->loaded)
      Event::run('system.404');

    $this->title = $this->album->title;
  }

  public function edit($id) {
    $this->album = ORM::factory('album', $id);
    if ( ! $this->album->loaded)
      Event::run('system.404');
    if ( ! A2::instance()->allowed($this->album, 'edit'))
      Event::run('system.403');

    $this->title = sprintf('Editing Album: %s', $this->album->title);
    $this->view = 'files/photos/album/form';
    $this->form = $this->album->as_array();
    if ($post = $this->input->post()) {
      if ($this->album->validate($post, TRUE)) {
        message::add(TRUE, '%s album updated successfully.', $this->album->title);
        url::redirect('files/photos/album/'. $this->album->id);
      }
      else {
        $this->form = $post->as_array();
        $this->errors = $post->errors('form_album');
      }
    }
  }

  public function delete($id) {
    $this->album = ORM::factory('album', $id);
    if ( ! $this->album->loaded)
      Event::run('system.404');
    if ( ! A2::instance()->allowed($this->album, 'edit'))
      Event::run('system.403');

    message::add(TRUE, '%s album deleted succesfully.', $this->album->title);
    foreach ($this->album->photos as $photo) {
      $photo->delete();
    }
    $this->album->delete();
    url::redirect('files/photos');
  }

  /**
   * Add new album.
   */
  public function add() {
    $this->title = 'Create Album';
    $this->view = 'files/photos/album/form';

    if ($post = $this->input->post()) {
      $this->album = ORM::factory('album');
      if ($this->album->validate($post, TRUE)) {
        message::add(TRUE, 'Album created successfully. '. html::anchor('files/photos/album/upload/'. $this->album->id .'?KeepThis=true&TB_iframe=true&height=400&width=600&modal=true', 'Add photos', array('class' => 'thickbox')));
        url::redirect('files/photos/album/'. $this->album->id);
      }
      else {
        message::add(FALSE, 'Please fix the errors below.');
        $this->form = $post->as_array();
        $this->errors = $post->errors('form_album');
      }
    }
  }

  /**
   * Popup upload window to upload files to the album.
   */
  public function upload($id) {
    $this->template = 'basic';
    $this->album = ORM::factory('album', $id);
    $this->title = sprintf('Upload Photos to %s', $this->album->title);

    // Allow uploads on the album page.
    css::add('styles/fileuploader.css');
    javascript::add('scripts/fileuploader.js');
    javascript::add("
      new qq.FileUploader({
        element: document.getElementById('upload-photos'),
        action: '/files/photos/upload/{$this->album->id}',
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
        sizeLimit: 1024 * 1024 * 5, // max size 3MB
        minSizeLimit: 0, // min size
        template: '
' +
                '
Drop photos here to upload
' +
                '
Upload a photo

or drag and drop files here.
' +
                '

' +
             '
',
        // debug: true
    });", 'inline');
  }

  public function photo($id) {
    $this->photo = ORM::factory('file', $id);
    if ( ! ($this->photo->loaded && $this->photo->object_type == 'album'))
      Event::run('system.404');

    javascript::add('scripts/photos.js');
    $this->next_photo = ORM::factory('album')->next_photo($this->photo);
    $this->previous_photo = ORM::factory('album')->previous_photo($this->photo);
    $this->album_order = ORM::factory('album')->album_order($this->photo);
    $this->title = sprintf('Photo: %s', $this->photo->name);

    if ($post = $this->input->post()) {
      $comment = ORM::factory('comment');
      $comment->object_type = 'file';
      $comment->object_id = $this->photo->id;
      if ($comment->validate($post, TRUE)) {
        message::add(TRUE, 'Your comment has been added.');
      }
      else {
        message::add(FALSE, 'Unable to post your comment, please fix the errors below and try again.');
        $this->form = $post->as_array();
        $this->errors = $post->errors('form_comment');
      }
    }
  }

}


text:
'use strict';

const coffee = require('coffeescript');

function coffeeRenderer(data, options) {
  return coffee.compile(data.text, Object.assign({
    filename: data.path
  }, this.config.coffee, options));
}

module.exports = coffeeRenderer;


text:
package com.myopicmobile.textwarrior.common;

/**
 * Singleton class that represents a non-programming language without keywords,
 * operators etc.
 */
public class LanguageNonProg extends Language{
	private static Language _theOne = null;

	private final static String[] keywords = {};

	private final static char[] operators = {};

	public static Language getInstance(){
		if(_theOne == null){
			_theOne = new LanguageNonProg();
		}
		return _theOne;
	}

	private LanguageNonProg(){
		super.setKeywords(keywords);
		super.setOperators(operators);
	}

	@Override
	public boolean isProgLang(){
		return false;
	}

	@Override
	public boolean isEscapeChar(char c){
		return false;
	}

	@Override
	public boolean isDelimiterA(char c){
		return false;
	}

	@Override
	public boolean isDelimiterB(char c){
		return false;
	}

	@Override
	public boolean isLineAStart(char c){
		return false;
	}

	@Override
	public boolean isLineStart(char c0, char c1){
		return false;
	}

	@Override
	public boolean isMultilineStartDelimiter(char c0, char c1){
		return false;
	}

	@Override
	public boolean isMultilineEndDelimiter(char c0, char c1){
		return false;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright 2010 Red Hat, Inc.
  ~
  ~  Red Hat licenses this file to you under the Apache License, version
  ~  2.0 (the "License"); you may not use this file except in compliance
  ~  with the License.  You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~  Unless required by applicable law or agreed to in writing, software
  ~  distributed under the License is distributed on an "AS IS" BASIS,
  ~  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  ~  implied.  See the License for the specific language governing
  ~  permissions and limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.fusesource</groupId>
    <artifactId>tooling</artifactId>
    <version>1.0.0.redhat-379</version>
  </parent>

  <groupId>io.fabric8</groupId>
  <artifactId>tooling-camel-facade</artifactId>
  <packaging>bundle</packaging>

  <name>Fuse :: Tooling :: Camel Facade</name>

  <properties>
    <fuse.osgi.import.pkg>
      org.apache.camel*;version="[2.12,3)";resolution:=optional,
      org.springframework*;resolution:=optional,
      *
    </fuse.osgi.import.pkg>
    <fuse.osgi.export>
        io.fabric8.camel.facade*;version=${project.version};-noimport:=true,
    </fuse.osgi.export>
    <fuse.osgi.bundle.name>Fuse Camel Facade Plugin</fuse.osgi.bundle.name>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-core</artifactId>
      <version>${camel-version}</version>
    </dependency>
    <!-- camel JMS requires Spring JARs -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring</artifactId>
      <version>${camel-version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j-api-version}</version>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-api</artifactId>
    </dependency>
    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>fabric-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.fusesource.insight</groupId>
      <artifactId>insight-log</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-test</artifactId>
      <version>${camel-version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit-version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j-version}</version>
      <scope>test</scope>
    </dependency>

    <!-- use AMQ for testing -->
    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-jms</artifactId>
      <version>${camel-version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-broker</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-client</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-camel</artifactId>
      <scope>test</scope>
      <!-- break the cyclic dependency to camel-jms which otherwise would baffle the maven eclipse plugin -->
      <exclusions>
        <exclusion>
          <groupId>org.apache.camel</groupId>
          <artifactId>camel-jms</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-pool</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.activemq</groupId>
      <artifactId>activemq-kahadb-store</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
<?php

namespace WebinoAppLib\Factory;

use WebinoAppLib\Event\AppEvent;
use WebinoEventLib\EventManager;

/**
 * Class EventsFactory
 */
final class EventsFactory extends AbstractFactory
{
    /**
     * {@inheritdoc}
     */
    protected function create()
    {
        // TODO use setEventPrototype instead of setEventClass, cause deprecated by Zend
        return (new EventManager)->setEventClass(AppEvent::class);
    }
}


text:
#ifndef _HIERARCHICAL_MULTILABEL_MODEL__H__
#define _HIERARCHICAL_MULTILABEL_MODEL__H__

#include <shogun/lib/config.h>
#include <shogun/structure/StructuredModel.h>

namespace shogun
{

/** @brief Class CHierarchicalMultilabelModel represents application specific
 * model and contains application dependent logic for solving hierarchical
 * multilabel classification[1] within a generic SO framework.
 *
 * [1] Lijuan Cai. Multilabel Classification over Category Taxonomies
 *     http://cs.brown.edu/research/pubs/theses/phd/2008/cai.pdf
 *
 * [2] Wei Bi, et.al. Mandatory Leaf Node Prediction in Hierarchical
 *     Multilabel Classification
 *     http://papers.nips.cc/paper/4520-mandatory-leaf-node-prediction-in-hierarchical-multilabel-classification.pdf
 */
class HierarchicalMultilabelModel : public StructuredModel
{
public:
	/** default constructor */
	HierarchicalMultilabelModel();

	/** constructor
	 *
	 * @param features features
	 * @param labels structured labels
	 * @param taxonomy taxonomy is stored in an integer array with:
	 * - length of array = number of nodes
	 * - each element storing only its parent-id taxonomy[node-id] = parent-id
	 * - root node should store its parent-id as -1
	 * @param leaf_nodes_mandatory whether only full paths (from ROOT to
	 * TERMINAL NODES) are only allowed or not
	 * class or not
	 */
	HierarchicalMultilabelModel(std::shared_ptr<Features > features, std::shared_ptr<StructuredLabels > labels,
	                             SGVector<int32_t> taxonomy, bool leaf_nodes_mandatory = false);

	/** destructor */
	~HierarchicalMultilabelModel() override;

	/** create empty StructuredLabels object */
	std::shared_ptr<StructuredLabels > structured_labels_factory(int32_t num_labels = 0) override;

	/** @return the dimensionality of the joint feature space, i.e., the
	 * dimension of the weight vector \f$w\f$.
	 */
	int32_t get_dim() const override;

	/** get joint feature vector
	 *
	 * \f[
	 * \vec{\Psi}(\bf{x}_\text{feat\_idx}, \bf{y})
	 * \f]
	 *
	 * @param feat_idx index of the feature vector to use
	 * @param y structured labels to use
	 *
	 * @return joint feature vector
	 */
	SGVector<float64_t> get_joint_feature_vector(int32_t feat_idx,
	                std::shared_ptr<StructuredData > y) override;

	/** obtain the argmax of
	 *
	 * \f[
	 * \Delta(y_{pred}, y_{truth}) + \langle w, \Psi(x_{truth}, y_{pred} \rangle
	 * \f]
	 *
	 * @param w weight vector
	 * @param feat_idx index of the feature vector to use
	 * @param training whether training is being used
	 */
	std::shared_ptr<ResultSet > argmax(SGVector<float64_t> w, int32_t feat_idx,
	                            bool const training = true) override;

	/** computes \f$ \Delta(y_{1}, y_{2}) \f$
	 *
	 * @param y1 an instance of structured data
	 * @param y2 another instance of structured data
	 *
	 * @return loss value
	 */
	float64_t delta_loss(std::shared_ptr<StructuredData > y1, std::shared_ptr<StructuredData > y2) override;

	/** initialize the optimization problem
	 *
	 * @param regularization regularization strength
	 * @param A is [-dPsi(y) | -I_N ] with M+N columns => max, M+1 nnz per row
	 * @param a unused input
	 * @param B unused input
	 * @param b upper bound of the constraints, Ax <= b
	 * @param lb lower bounds for w
	 * @param ub upper bounds for w
	 * @param C regularization matrix, w'Cw
	 */
	void init_primal_opt(
	        float64_t regularization,
	        SGMatrix<float64_t> &A,
	        SGVector<float64_t> a,
	        SGMatrix<float64_t> B,
	        SGVector<float64_t> &b,
	        SGVector<float64_t> &lb,
	        SGVector<float64_t> &ub,
	        SGMatrix<float64_t> &C) override;

	/** @return name of the SGSerializable */
	const char * get_name() const override
	{
		return "HierarchicalMultilabelModel";
	}

private:
	int32_t m_num_classes;
	SGVector<int32_t> m_taxonomy;
	bool m_leaf_nodes_mandatory;
	int32_t m_root;
	// array for vectors storing the node-ids of the children
	// m_children[node_id] = vector of node_ids of the children
	//                     = empty vector, if node is a terminal node
	SGVector<int32_t> * m_children;

private:
	void init(SGVector<int32_t> taxonomy, bool leaf_nodes_mandatory);

	/** different versions of delta loss function */
	float64_t delta_loss(SGVector<int32_t> y1, SGVector<int32_t> y2);
	float64_t delta_loss(int32_t y1, int32_t y2);

	/** get the label vector for any label
	 * the label vector would be vector with value 1 for all the nodes
	 * that are ancestor of the given labels else 0
	 *
	 * @return label vector
	 */
	SGVector<int32_t> get_label_vector(SGVector<int32_t> sparse_label);

}; /* class CHierarchicalMultilabelModel */

} /* namespace shogun */

#endif /* _HIERARCHICAL_MULTILABEL_MODEL__H__ */


text:
#ifndef FETX_IO_H
#define FETX_IO_H

#include "fetx_netlist.h"

/* fetx_io is a wrapper around fetx that represents a modular circuit
 * with abstracted inputs and outputs. */

struct fetx_io {
  struct fetx fx;
  struct fetx_input_node *inputs;
  struct fetx_node **outputs;
  size_t inputs_size;
  size_t outputs_size;
};

void fetx_io_delete(struct fetx_io io);
int fetx_io_init(struct fetx_io *const io, const struct fetx_netlist nl);
void fetx_io_input(struct fetx_io *const io, const size_t input_index,
                   const enum fetx_node_states state);
enum fetx_node_states fetx_io_output(const struct fetx_io io,
                                     const size_t output_index);
void fetx_io_inputs(struct fetx_io *const io,
                    const enum fetx_node_states *const inputs);
void fetx_io_outputs(enum fetx_node_states *const outputs,
                     const struct fetx_io io);
unsigned char fetx_io_resolve(struct fetx_io *const io);

#endif


text:
/* public api for steve reid's public domain SHA-1 implementation */
/* this file is in the public domain */

#pragma once

#include "Platform.h"

struct SHA1_CTX
{
    uint32_t state[5];
    uint32_t count[2];
    uint8_t  buffer[64];
};

#define SHA1_DIGEST_SIZE 20

void SHA1_Init(SHA1_CTX* context);
void SHA1_Update(SHA1_CTX* context, const uint8_t* data, const size_t len);
void SHA1_Final(SHA1_CTX* context, uint8_t digest[SHA1_DIGEST_SIZE]);

void sha1_32a ( const void * key, int len, uint32_t seed, void * out );


text:
using System;
using Server;
using Server.Items;
using Server.Mobiles;

namespace Server.Engines.Quests.Zento
{
	public class AcceptConversation : QuestConversation
	{
		public override object Message
		{
			get
			{
				/* Important Quest Information

				 *
				 * During your quest, any important information that a
				 * NPC gives you, will appear in a window
				 * such as this one.  You can review the information at any time during your
				 * quest.

				 *
				 * Getting Help

				 *
				 * Some of the text you will come across during your quest,
				 * will be underlined links to the codex of wisdom,
				 * or online help system.  You can click on the text to get detailed information
				 * on the underlined subject.  You may also access the Codex Of Wisdom by
				 * pressing "F1" or by clicking on the "?" on the toolbar at the top of
				 * your screen.

Context Menus

				 *
				 * Context menus can be called up by single left-clicking (or Shift + single
				 * left-click, if you changed it) on most objects or NPCs in the world.
				 * Nearly everything, including your own avatar will have context menus available.
				 * Bringing up your avatar's context menu will give you options to cancel your quest
				 * and review various quest information.

				 */
				return 1049092;
			}
		}

		public AcceptConversation()
		{
		}

		public override void OnRead()
		{
			System.AddObjective( new FirstKillObjective() );
		}
	}

	public class DirectionConversation : QuestConversation
	{
		public override object Message
		{
			get
			{
				// The Deathwatch Beetle Hatchlings live in The Waste - the desert close to this city.
				return 1063323;
			}
		}

		public override bool Logged{ get{ return false; } }

		public DirectionConversation()
		{
		}
	}

	public class TakeCareConversation : QuestConversation
	{
		public override object Message
		{
			get
			{
				// I know you can take care of those nasty Deathwatch Beetle Hatchlings! No get to it!
				return 1063324;
			}
		}

		public override bool Logged{ get{ return false; } }

		public TakeCareConversation()
		{
		}
	}

	public class EndConversation : QuestConversation
	{
		public override object Message
		{
			get
			{
				/* Thank you for helping me get rid of these vile beasts!
				 * You have been rewarded for your good deeds. If you wish to
				 * help me in the future, visit me again.

				 *
				 * Farewell.
				 */
				return 1063321;
			}
		}

		public EndConversation()
		{
		}

		public override void OnRead()
		{
			System.Complete();
		}
	}
}


text:
/************************************************************************
 * File:	tree.c							*
 *									*
 * Description:	This file contains the public and private function	*
 *		definitions for expression trees.			*
 ************************************************************************/

# include <stdio.h>
# include <stdlib.h>
# include <pml/tree.h>

/************************************************************************
 * Function:	TreeCreate						*
 *									*
 * Description:	Creates, initializes, and returns an expression tree.	*
 ************************************************************************/

Tree TreeCreate (left, right, sval, ival)
    Tree   left;
    Tree   right;
    String sval;
    int    ival;
{
    Tree tree;

    tree = (Tree) malloc (sizeof (struct tree));

    tree -> left = left;
    tree -> right = right;
    tree -> sval = sval;
    tree -> ival = ival;

    return tree;
}

/************************************************************************
 * Function:	TreeDestroy						*
 *									*
 * Description:	Destroys the specified expression tree by recursively	*
 *		deallocating its associated memory.			*
 ************************************************************************/

void TreeDestroy (tree)
    Tree tree;
{
    if (tree -> left != NULL)
	TreeDestroy (tree -> left);

    if (tree -> right != NULL)
	TreeDestroy (tree -> right);

    free (tree);
}