text:
package com.fourinone;

import java.util.List;
import java.util.ArrayList;
import java.lang.reflect.Array;

public abstract class Contractor extends ContractorParallel
{
	private Contractor ctor;
	WorkerLocal[] wks = null;

	public Contractor toNext(Contractor ctor)
	{
		this.ctor = ctor;
		return ctor;
	}

	public final WareHouse giveTask(WareHouse inhouse, boolean chainProcess)
	{
		WareHouse outhouse = giveTask(inhouse);
		if(chainProcess&&ctor!=null)
			return ctor.giveTask(outhouse, chainProcess);
		return outhouse;
	}

	final <T> T[] getLocals(String localType, Class<T> local){
		T[] locals = null;
		WorkerLocal[] wkls = getWaitingWorkers(localType);
		if(wkls!=null){
			locals = (T[])Array.newInstance(local, wkls.length);
			for(int i=0;i<wkls.length;i++){
				locals[i]=(T)wkls[i];
			}
		}
		return locals;
	}
	/*
	final WorkerLocal[] getWorkerLocals(Class[] locals){
		WorkerLocal[] wkls = null;
		if(locals!=null){
			wkls = new WorkerLocal[locals.length];
			for(int i=0;i<locals.length;i++){
				wkls[i]=(WorkerLocal)locals[i];
			}
		}
		return wkls;
	}*/

	public void doProject(WareHouse inhouse)
	{
		/*WareHouse outhouse = giveTask(inhouse);
		if(ctor!=null)
			ctor.doProject(outhouse);*/
		giveTask(inhouse, true);
	}

	WorkerLocal[] getWaitingWorkersFromService(String workerType)
	{
		return getWaitingWorkersFromService(workerType,null);
	}

	WorkerLocal[] getWaitingWorkersFromService(String workerType, MigrantWorker mw)
	{
		//get host:port from ParkLocal and get WorkerService from host:port
		LogUtil.fine("", "", "getWaitingWorkersFromService:"+workerType+",MigrantWorker:"+mw);
		/*List<ObjectBean> oblist = ParkPatternExector.getWorkerTypeList(workerType);
		List<WorkerLocal> wklist = new ArrayList<WorkerLocal>();
		for(ObjectBean ob:oblist)
		{
			String[] hostport = ((String)ob.toObject()).split(":");
			wklist.add(BeanContext.getWorkerLocal(hostport[0], Integer.parseInt(hostport[1]), workerType));
		}
		return wklist.toArray(new WorkerLocal[wklist.size()]);*/
		//if(wks==null){
			List<String[]> wslist = getWorkersService(workerType);
			List<WorkerLocal> wklist = new ArrayList<WorkerLocal>();
			for(String[] wsinfo:wslist)
				wklist.add(BeanContext.getWorkerLocal(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]));

			/*if(mw!=null){
				BeanContext.startInetServer();
				for(WorkerLocal wl:wklist)
					((WorkerProxy)wl).setWorker(mw);
			}*/
			wks=wklist.toArray(new WorkerLocal[wklist.size()]);
		//}
		return wks;
	}

	WorkerLocal[] getWaitingWorkersFromPark(String workerType)
	{
		LogUtil.fine("", "", "getWaitingWorkersFromPark:"+workerType);
		//if(wks==null){
			List<ObjectBean> oblist = ParkPatternExector.getWorkerTypeList(workerType);
			//System.out.println("getWaitingWorkersFromPark oblist:"+oblist);
			List<WorkerLocal> wklist = new ArrayList<WorkerLocal>();
			for(ObjectBean ob:oblist)
				wklist.add(BeanContext.getWorkerLocal(ob.getName()));
			wks=wklist.toArray(new WorkerLocal[wklist.size()]);
		//}
		return wks;
	}

	protected final WareHouse[] doTaskBatch(WareHouse wh){
		return doTaskBatch(wks, wh);
	}

	protected final WareHouse[] doTaskBatch(WorkerLocal[] wks, WareHouse wh){
		WareHouse[] hmarr = new WareHouse[wks.length];
		for(int i=0,j=0;j<hmarr.length;){
			if(hmarr[i]==null){
				hmarr[i] = wks[i].doTask(wh);
			}
			else if(hmarr[i].isReady()&&hmarr[i].getMark()){
				hmarr[i].setMark(false);
				j++;
			}
			i=i+1==hmarr.length?0:i+1;
		}
		return hmarr;
	}
}


text:
<?php
namespace Zhivankin\DanceDepartmentArchive;

/**
 * Dance Department Class
 * This class aims to provide an easy way of obtaining playlist files for the past 2 episodes of the Dance Department radio show for playing the episodes in Winamp or any other external player that supports the .
 * M3U playlist file format, instead of playing them through the Radio 538 flash player provided at the Dance Department website
 *
 * @author Georgi Zhivankin
 *         @website http://www.zhivankin.com/
 * @license GPL V 3
 *          @Version 1.0
 *          @Date 03 November 2014
 */
class DanceDepartmentArchive
{

    /**
     * function generateDates
     *
     * @return array
     */
    public function generateDates()
    {
        // First, set the time zone to GMT+01:00 (local time in Amsterdam, The Netherlands)
        date_default_timezone_set('UTC+1');
        // Get current date and time
        $currentDateTime = time();
        // Get last Saturday and the Saturday before
        $lastSaturday = strtotime('Last Saturday', $currentDateTime);
        $previousSaturday = strtotime('last Saturday -1 week', $currentDateTime);
        // echo "Last Saturday: ".date('l d/m/Y', $lastSaturday)."
";
        // echo "Previous Saturday: ".date('l d/m/Y', $previousSaturday)."
";

        // Add the two dates to an array that will be used to generate the URLs for the playlists to the archive
        $dates = array(
            $lastSaturday,
            $previousSaturday
        );
        // Return the dates
        return $dates;
    }

    /**
     * function generateHourURLSegments
     *
     * @param int $date
     * @return string
     */
    public function generateHourURLSegments($date)
    {
        // Generate proper URL segments for the 4 hours of the show
        $i = 20;
        $j = 23;
        while ($i <= $j) {
            $segmentDates[] = date('Ymd', $date) . "%20" . $i . "00";
            $i ++;
        }
        // Return the generated segments
        return $segmentDates;
    }

    /**
     * function generatePlaylistURLs
     *
     * @return string
     */
    public function generatePlaylistURLs()
    {
        // URL chunk
        $urlChunk = 'http://media2.538.nl/uitzendingen/%5BListenBack_RADIO538%20%28DAGELIJKS%29%5D%20538-ZATERDAG%20';
        // Get dates
        $dates = self::generateDates();
        // Generate hour segments for each date
        foreach ($dates as $date) {
            $hourSegments[$date] = self::generateHourURLSegments($date);
        }
        // Generate URLs for each date and segment
        foreach ($hourSegments as $date => $hourSegments) {
            foreach ($hourSegments as $hourSegment) {
                // Generate URLs
                $playlistURLs[$date][] = $urlChunk . $hourSegment . ".MP3";
            }
        }
        // Return the generated playlist URLs
        return $playlistURLs;
    }

    /**
     * function generatePlaylist
     *
     * @param array $urls
     * @return string
     */
    public function generatePlaylist(array $urls)
    {
        // Get all playlist URLs and generate an .m3u file
        $m3uFile = "#EXTM3U";
        foreach ($urls as $url) {
            $m3uFile .= sprintf("
                #EXTINF:-1, %1\$s
                %1\$s", $url);
        }
        // Return the M3U file
        return $m3uFile;
    }
}

redpajama_set_name: RedPajamaGithub


text:
ComplexPropertyAttribute Constructor
====================================
Initializes a new instance of the [ComplexPropertyAttribute][1] class

  **Namespace:**  [DbExtensions][2]
  **Assembly:** DbExtensions.dll

Syntax
------

```csharp
public ComplexPropertyAttribute()
```

See Also
--------

#### Reference
[ComplexPropertyAttribute Class][1]
[DbExtensions Namespace][2]

[1]: README.md
[2]: ../README.md


text:
Nuevo Usuario

		<form name="userForm" data-ng-submit="signup()" class="signin form-horizontal" novalidate autocomplete="off">
			<fieldset>

					Nombre
					<input type="text" required id="firstName" name="firstName" class="form-control" data-ng-model="credentials.firstName" placeholder="Nombre">

					Apellidos
					<input type="text" id="lastName" name="lastName" class="form-control" data-ng-model="credentials.lastName" placeholder="Apellidos">

					Correo Electronico
					<input type="email" id="email" name="email" class="form-control" data-ng-model="credentials.email" placeholder="Correo Electronico">

					Usuario
					<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Usuario">

					Contraseña
					<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Contraseña">

					<button type="submit" class="btn btn-lg btn-success btn-block">Registrar</button>

			</fieldset>

		</form>


text:
package wyrzyk.archetypes.config;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableJpaRepositories(basePackages = "io.leansoft.ac.auth.jwt.lifecycle")
@EnableTransactionManagement
class DataConfig {

    @Bean
    public EmbeddedDatabase h2() {
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    public AbstractEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setDataSource(h2());
        entityManagerFactory.setPackagesToScan("io.leansoft.ac.auth.jwt.lifecycle");
        entityManagerFactory.getJpaPropertyMap().put("hibernate.hbm2ddl.auto", "create");
        entityManagerFactory.setPersistenceProvider(new HibernatePersistenceProvider());
        return entityManagerFactory;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager();
    }
}


text:
module Vote
  module Condorcet
    module Schulze
      class Input
        def initialize(vote_list, candidate_count = nil)
          @vote_list = vote_list
          @candidate_count = candidate_count
          @candidates_abc = []
          if @candidate_count.nil?
            insert_vote_file(@vote_list) if vote_list.is_a?(File)
          else
            @vote_matrix = ::Matrix.scalar(@candidate_count, 0).extend(Vote::Matrix)
            insert_vote_array(@vote_list) if vote_list.is_a?(Array)
            insert_vote_strings(@vote_list) if vote_list.is_a?(String)
          end
        end

        def insert_vote_array(vote_array)
          vote_array.each do |vote|
            @vote_matrix.each_with_index do |_e, x, y|
              next if x == y
              @vote_matrix[x, y] += 1 if vote[x] && vote[y] && vote[x] > vote[y]
            end
          end
          @vote_count = vote_array.size
        end

        def insert_vote_strings(vote_strings)
          vote_array = []

          vote_strings.split(/\n|\n\r|\r/).each do |voter|
            voter = voter.split(/=/)
            vcount = (voter.size == 1) ? 1 : voter[0].to_i
            vcount.times do
              tmp = voter.last.split(/;/)
              vote_array << extract_vote_string(tmp)
            end
          end
          insert_vote_array vote_array
        end

        def extract_vote_string(tmp) # array of preferences  [['1, 2'], ['3']. ['4, 5']]
          tmp2 = flatten_votes(order_and_remap(tmp))
          tmp2.map! { |e| [e[0].to_i, e[1]] } if all_numbers?(tmp2)
          tmp2.sort.map { |e| e[1] } # order, strip & add
        end

        def flatten_votes(votes)
          tmp2 = []
          votes.map do |e| # find equal-weighted candidates
            (e[0].size > 1) ? e[0].split(/,/).each { |f| tmp2 << [f, e[1]] } : tmp2 << e
          end
          tmp2
        end

        def all_numbers?(array)
          array.map { |e| e[0] }.all? { |el| /\A\d+\z/.match(el) }
        end

        def order_and_remap(tmp)
          tmp.map { |e| [e, @candidate_count - tmp.index(e)] }
        end

        def insert_vote_file(vote_file)
          vote_file.rewind
          @candidate_count = vote_file.first.strip.to_i # reads first line for count
          @vote_matrix = ::Matrix.scalar(@candidate_count, 0).extend(Vote::Matrix)
          insert_vote_strings vote_file.read # reads rest of file (w/o line 1)
          vote_file.close
        end

        def matrix
          @vote_matrix
        end

        def candidates
          @candidate_count
        end

        def voters
          @vote_count
        end
      end
    end
  end
end


text:
#ifndef regtable_h
#define regtable_h

#include "Arduino.h"
#include "register.h"
#include "commonregs.h"

/**
 * Register indexes
 */
DEFINE_REGINDEX_START()
  REGI_HEART_BEAT,
  REGI_ACK_HEART_BEAT,
  REGI_RAISE_FLAG,
  REGI_LOWER_FLAG
DEFINE_REGINDEX_END()

#endif


text:
/**
 * @fileOverview Main source file.
 * @author Your Name
 * @version 0.1
 */

/**
 * @namespace Holds the greeter functionality.
 */
Greeter = {

  /**
   * Greets something.
   * @param {String} [something="Anonymous"] Thing to greet.
   * @returns Nothing.
   */
  sayHelloTo: function(something) {
    return "Hello, " + (!something ? "Anonymous" : something) + '!';
  }
};


text:
page 'corner-badge.html', layout: false

set :css_dir, 'stylesheets'
set :js_dir, 'javascripts'
set :images_dir, 'images'

# Build-specific configuration
configure :build do
  # For example, change the Compass output style for deployment
  # activate :minify_css

  # Minify Javascript on build
  # activate :minify_javascript

  # Enable cache buster
  # activate :asset_hash

  # Use relative URLs
  # activate :relative_assets

  # Or use a different image path
  # set :http_prefix, "/Content/images/"
end
ready do
  sprockets.import_asset 'corner-badge'
end


text:
html,
body {
  height: 100%;
  width: 100%;
}
body {
  font-family: 'Merriweather', 'Helvetica Neue', Arial, sans-serif;
}
hr {
  border-color: #CA3317;
  border-width: 3px;
  max-width: 50px;
}
hr.light {
  border-color: white;
}
a {
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
  color: #CA3317;
}
a:hover,
a:focus {
  color: #CA3317;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
}
p {
  font-size: 16px;
  line-height: 1.5;
  margin-bottom: 20px;
}
.bg-primary {
  background-color: #CA3317;
}
.bg-dark {
  background-color: #111111;
  color: white;
}
.text-faded {
  color: rgba(255, 255, 255, 0.7);
}
section {
  padding: 100px 0;
}
aside {
  padding: 50px 0;
}
.no-padding {
  padding: 0;
}
.navbar-default {
  background-color: rgba(34, 34, 34, 0.05);
  border-color: rgba(34, 34, 34, 0.05);
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}
.navbar-default .navbar-header .navbar-brand {
  color: #CA3317;
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  font-weight: 700;

}
.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
  color: #CA3317;
}
.navbar-default .navbar-header .navbar-toggle {
  font-weight: 700;
  font-size: 12px;
  color: #111111;
}
.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
  font-weight: 700;
  font-size: 13px;
  color: #111111;
}
.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
  color: #CA3317;
}
.navbar-default .nav > li.active > a,
.navbar-default .nav > li.active > a:focus {
  color: #CA3317 !important;
  background-color: transparent;
}
.navbar-default .nav > li.active > a:hover,
.navbar-default .nav > li.active > a:focus:hover {
  background-color: transparent;
}
@media (min-width: 768px) {
  .navbar-default {
    background-color: transparent;
    border-color: #CA3317;
  }
  .navbar-default .navbar-header .navbar-brand {
    color: #CA3317;
  }
  .navbar-default .navbar-header .navbar-brand:hover,
  .navbar-default .navbar-header .navbar-brand:focus {
    color: white;
  }
  .navbar-default .nav > li > a,
  .navbar-default .nav > li > a:focus {
    color: rgba(255, 255, 255, .7);
  }
  .navbar-default .nav > li > a:hover,
  .navbar-default .nav > li > a:focus:hover {
    color: white;
  }
  .navbar-default.affix {
    background-color: white;
    border-color: white;
  }
  .navbar-default.affix .navbar-header .navbar-brand {
    color: #CA3317;
    font-size: 14px;
  }
  .navbar-default.affix .navbar-header .navbar-brand:hover,
  .navbar-default.affix .navbar-header .navbar-brand:focus {
    color: #CA3317;
  }
  .navbar-default.affix .nav > li > a,
  .navbar-default.affix .nav > li > a:focus {
    color: #111111;
  }
  .navbar-default.affix .nav > li > a:hover,
  .navbar-default.affix .nav > li > a:focus:hover {
    color: #CA3317;
  }
}
header {
  position: relative;
  width: 100%;
  min-height: auto;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  background-position: center;
  background-image: linear-gradient( rgba(0, 0, 0, 1), rgba(0, 0, 0, 0) ), url('../img/header6.jpg');
  text-align: center;
  color: white;

}

header .header-content {
  position: relative;
  text-align: center;
  padding: 100px 15px 100px;
  width: 100%;

}
header .header-content .header-content-inner h1 {
  font-weight: 700;
  text-transform: uppercase;
  margin-top: 0;
  margin-bottom: 0;
  font-size: 30px;
}
header .header-content .header-content-inner hr {
  margin: 30px auto;
}
header .header-content .header-content-inner p {
  font-weight: 300;
  color: rgba(255, 255, 255, .7);
  font-size: 16px;
  margin-bottom: 50px;
}
@media (min-width: 768px) {
  header {
    min-height: 100%;
  }
  header .header-content .header-content-inner {
    max-width: 1000px;
    margin-left: auto;
    margin-right: auto;
  }
  header .header-content .header-content-inner h1 {
    font-size: 50px;
  }
  header .header-content .header-content-inner p {
    font-size: 18px;
    max-width: 80%;
    margin-left: auto;
    margin-right: auto;
  }
}
.section-heading {
  margin-top: 0;
}
.service-box {
  max-width: 400px;
  margin: 50px auto 0;
}
@media (min-width: 992px) {
  .service-box {
    margin: 20px auto 0;
  }
}
.service-box p {
  margin-bottom: 0;
}
.portfolio-box {
  position: relative;
  display: block;
  max-width: 650px;
  margin: 0 auto;
}
.portfolio-box .portfolio-box-caption {
  color: white;
  opacity: 0;
  display: block;
  background: #CA3317;
  position: absolute;
  bottom: 0;
  text-align: center;
  width: 100%;
  height: 100%;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}
.portfolio-box .portfolio-box-caption .portfolio-box-caption-content {
  width: 100%;
  text-align: center;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category,
.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  padding: 0 15px;
}
.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category {
  text-transform: uppercase;
  font-weight: 600;
  font-size: 14px;
}
.portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
  font-size: 18px;
}
.portfolio-box:hover .portfolio-box-caption {
  opacity: 1;
}
.portfolio-box:focus {
  outline: none;
}
@media (min-width: 768px) {
  .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category {
    font-size: 16px;
  }
  .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name {
    font-size: 22px;
  }
}
.call-to-action h2 {
  margin: 0 auto 20px;
}
.text-primary {
  color: #CA3317;
}
.no-gutter > [class*='col-'] {
  padding-right: 0;
  padding-left: 0;
}
.btn-default {
  color: #111111;
  background-color: white;
  border-color: white;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}
.btn-default:hover,
.btn-default:focus,
.btn-default.focus,
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
  color: #111111;
  background-color: #f2f2f2;
  border-color: #ededed;
}
.btn-default:active,
.btn-default.active,
.open > .dropdown-toggle.btn-default {
  background-image: none;
}
.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled.focus,
.btn-default[disabled].focus,
fieldset[disabled] .btn-default.focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
  background-color: white;
  border-color: white;
}
.btn-default .badge {
  color: white;
  background-color: #111111;
}
.btn-primary {
  color: white;
  background-color: #CA3317;
  border-color: #CA3317;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary.focus,
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
  color: white;
  background-color: #ee4b28;
  border-color: #ed431f;
}
.btn-primary:active,
.btn-primary.active,
.open > .dropdown-toggle.btn-primary {
  background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled.focus,
.btn-primary[disabled].focus,
fieldset[disabled] .btn-primary.focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
  background-color: #CA3317;
  border-color: #CA3317;
}
.btn-primary .badge {
  color: #CA3317;
  background-color: white;
}
.btn {
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  border: none;
  border-radius: 300px;
  font-weight: 700;
  text-transform: uppercase;
}
.btn-xl {
  padding: 15px 30px;
}
::-moz-selection {
  color: white;
  text-shadow: none;
  background: #111111;
}
::selection {
  color: white;
  text-shadow: none;
  background: #111111;
}
img::selection {
  color: white;
  background: transparent;
}
img::-moz-selection {
  color: white;
  background: transparent;
}
body {
  webkit-tap-highlight-color: #111111;
}


text:
from .Person import *
from .Student import *
from .Faculty import *
from .SpecializationField import *


text:
import os
import os.path

from dtest import DISABLE_VNODES, Tester, create_ks
from tools.assertions import assert_almost_equal
from tools.data import create_c1c2_table, insert_c1c2, query_c1c2
from tools.decorators import since
from tools.jmxutils import (JolokiaAgent, make_mbean,
                            remove_perf_disable_shared_mem)
from tools.misc import new_node

@since('3.2')
class TestDiskBalance(Tester):
    """
    @jira_ticket CASSANDRA-6696
    """

    def disk_balance_stress_test(self):
        cluster = self.cluster
        if not DISABLE_VNODES:
            cluster.set_configuration_options(values={'num_tokens': 256})
        cluster.populate(4).start(wait_for_binary_proto=True)
        node1 = cluster.nodes['node1']

        node1.stress(['write', 'n=50k', 'no-warmup', '-rate', 'threads=100', '-schema', 'replication(factor=3)', 'compaction(strategy=SizeTieredCompactionStrategy,enabled=false)'])
        cluster.flush()
        # make sure the data directories are balanced:
        for node in cluster.nodelist():
            self.assert_balanced(node)

    def disk_balance_bootstrap_test(self):
        cluster = self.cluster
        if not DISABLE_VNODES:
            cluster.set_configuration_options(values={'num_tokens': 256})
        # apparently we have legitimate errors in the log when bootstrapping (see bootstrap_test.py)
        self.allow_log_errors = True
        cluster.populate(4).start(wait_for_binary_proto=True)
        node1 = cluster.nodes['node1']

        node1.stress(['write', 'n=50k', 'no-warmup', '-rate', 'threads=100', '-schema', 'replication(factor=3)', 'compaction(strategy=SizeTieredCompactionStrategy,enabled=false)'])
        cluster.flush()
        node5 = new_node(cluster)
        node5.start(wait_for_binary_proto=True)
        self.assert_balanced(node5)

    def disk_balance_decommission_test(self):
        cluster = self.cluster
        if not DISABLE_VNODES:
            cluster.set_configuration_options(values={'num_tokens': 256})
        cluster.populate(4).start(wait_for_binary_proto=True)
        node1 = cluster.nodes['node1']
        node4 = cluster.nodes['node4']
        node1.stress(['write', 'n=50k', 'no-warmup', '-rate', 'threads=100', '-schema', 'replication(factor=2)', 'compaction(strategy=SizeTieredCompactionStrategy,enabled=false)'])
        cluster.flush()

        node4.decommission()

        for node in cluster.nodelist():
            node.nodetool('relocatesstables')

        for node in cluster.nodelist():
            self.assert_balanced(node)

    def blacklisted_directory_test(self):
        cluster = self.cluster
        cluster.set_datadir_count(3)
        cluster.populate(1)
        [node] = cluster.nodelist()
        remove_perf_disable_shared_mem(node)
        cluster.start(wait_for_binary_proto=True)

        session = self.patient_cql_connection(node)
        create_ks(session, 'ks', 1)
        create_c1c2_table(self, session)
        insert_c1c2(session, n=10000)
        node.flush()
        for k in xrange(0, 10000):
            query_c1c2(session, k)

        node.compact()
        mbean = make_mbean('db', type='BlacklistedDirectories')
        with JolokiaAgent(node) as jmx:
            jmx.execute_method(mbean, 'markUnwritable', [os.path.join(node.get_path(), 'data0')])

        for k in xrange(0, 10000):
            query_c1c2(session, k)

        node.nodetool('relocatesstables')

        for k in xrange(0, 10000):
            query_c1c2(session, k)

    def alter_replication_factor_test(self):
        cluster = self.cluster
        if not DISABLE_VNODES:
            cluster.set_configuration_options(values={'num_tokens': 256})
        cluster.populate(3).start(wait_for_binary_proto=True)
        node1 = cluster.nodes['node1']
        node1.stress(['write', 'n=1', 'no-warmup', '-rate', 'threads=100', '-schema', 'replication(factor=1)'])
        cluster.flush()
        session = self.patient_cql_connection(node1)
        session.execute("ALTER KEYSPACE keyspace1 WITH replication = {'class':'SimpleStrategy', 'replication_factor':2}")
        node1.stress(['write', 'n=100k', 'no-warmup', '-rate', 'threads=100'])
        cluster.flush()
        for node in cluster.nodelist():
            self.assert_balanced(node)

    def assert_balanced(self, node):
        sums = []
        for sstabledir in node.get_sstables_per_data_directory('keyspace1', 'standard1'):
            sum = 0
            for sstable in sstabledir:
                sum = sum + os.path.getsize(sstable)
            sums.append(sum)
        assert_almost_equal(*sums, error=0.1, error_message=node.name)


text:
<?php
//============================================================+
// File name   : tcpdf_barcodes_1d_include.php
// Begin       : 2013-05-19
// Last Update : 2013-05-19
//
// Description : Search and include the TCPDF Barcode 1D class.
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

/**
 * Search and include the TCPDF Barcode 1D class.
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Include the main class.
 * @author Nicola Asuni
 * @since 2013-05-19
 */

// Include the TCPDF 1D barcode class (search the class on the following directories).
$tcpdf_barcodes_1d_include_dirs = array(realpath('tcpdf_barcodes_1d.php'));
foreach ($tcpdf_barcodes_1d_include_dirs as $tcpdf_barcodes_1d_include_path) {
	if (@file_exists($tcpdf_barcodes_1d_include_path)) {
		require_once($tcpdf_barcodes_1d_include_path);
		break;
	}
}

//============================================================+
// END OF FILE
//============================================================+


text:
import functools
import logging
import unittest

from . import template

logger = logging.getLogger('test')
_testcase = unittest.TestCase('skipTest')

def _format_args(args, kwargs):
    for a in args:
        yield repr(a)
    for kw, a in kwargs.items():
        yield '%s=%s' % (kw, repr(a))

def _log_assertion(func_name, *args, **kwargs):
    try:
        getattr(_testcase, func_name)(*args, **kwargs)
    except AssertionError as exc:
        logger.error('Ignoring %s', exc)
    else:
        logger.info('Succeeded %s(%s)',
                    func_name, ', '.join(_format_args(args, kwargs)))

class DummyTestCase(object):
    def __getattr__(self, name):
        if name.startswith('assert'):
            return functools.partial(_log_assertion, name)
        else:
            raise AttributeError(name)

def verify(test, reality, tmpl):
    for name in tmpl.resources:
        rsrc_count = len(reality.resources_by_logical_name(name))
        test.assertEqual(1, rsrc_count,
                         'Found %d copies of resource "%s"' % (rsrc_count,
                                                               name))

    all_rsrcs = reality.all_resources()

    for name, defn in tmpl.resources.items():
        phys_rsrc = list(reality.resources_by_logical_name(name).values())[0]

        for prop_name, prop_def in defn.properties.items():
            real_value = phys_rsrc.properties[prop_name]

            if isinstance(prop_def, template.GetAtt):
                targs = reality.resources_by_logical_name(prop_def.target_name)
                att_value = list(targs.values())[0].properties[prop_def.attr]
                test.assertEqual(att_value, real_value)

            elif isinstance(prop_def, template.GetRes):
                targs = reality.resources_by_logical_name(prop_def.target_name)
                test.assertEqual(list(targs)[0], real_value)

            else:
                test.assertEqual(prop_def, real_value)

        test.assertEqual(len(defn.properties), len(phys_rsrc.properties))

    test.assertEqual(len(tmpl.resources), len(all_rsrcs))


text:
( function () {

	/**
 * Work based on :
 * https://github.com/Slayvin: Flat mirror for three.js
 * https://home.adelphi.edu/~stemkoski/ : An implementation of water shader based on the flat mirror
 * http://29a.ch/ && http://29a.ch/slides/2012/webglwater/ : Water shader explanations in WebGL
 */

	class Water extends THREE.Mesh {

		constructor( geometry, options = {} ) {

			super( geometry );
			this.isWater = true;
			const scope = this;
			const textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512;
			const textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512;
			const clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
			const alpha = options.alpha !== undefined ? options.alpha : 1.0;
			const time = options.time !== undefined ? options.time : 0.0;
			const normalSampler = options.waterNormals !== undefined ? options.waterNormals : null;
			const sunDirection = options.sunDirection !== undefined ? options.sunDirection : new THREE.Vector3( 0.70707, 0.70707, 0.0 );
			const sunColor = new THREE.Color( options.sunColor !== undefined ? options.sunColor : 0xffffff );
			const waterColor = new THREE.Color( options.waterColor !== undefined ? options.waterColor : 0x7F7F7F );
			const eye = options.eye !== undefined ? options.eye : new THREE.Vector3( 0, 0, 0 );
			const distortionScale = options.distortionScale !== undefined ? options.distortionScale : 20.0;
			const side = options.side !== undefined ? options.side : THREE.FrontSide;
			const fog = options.fog !== undefined ? options.fog : false;

			//

			const mirrorPlane = new THREE.Plane();
			const normal = new THREE.Vector3();
			const mirrorWorldPosition = new THREE.Vector3();
			const cameraWorldPosition = new THREE.Vector3();
			const rotationMatrix = new THREE.Matrix4();
			const lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
			const clipPlane = new THREE.Vector4();
			const view = new THREE.Vector3();
			const target = new THREE.Vector3();
			const q = new THREE.Vector4();
			const textureMatrix = new THREE.Matrix4();
			const mirrorCamera = new THREE.PerspectiveCamera();
			const renderTarget = new THREE.WebGLRenderTarget( textureWidth, textureHeight );
			const mirrorShader = {
				uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib[ 'fog' ], THREE.UniformsLib[ 'lights' ], {
					'normalSampler': {
						value: null
					},
					'mirrorSampler': {
						value: null
					},
					'alpha': {
						value: 1.0
					},
					'time': {
						value: 0.0
					},
					'size': {
						value: 1.0
					},
					'distortionScale': {
						value: 20.0
					},
					'textureMatrix': {
						value: new THREE.Matrix4()
					},
					'sunColor': {
						value: new THREE.Color( 0x7F7F7F )
					},
					'sunDirection': {
						value: new THREE.Vector3( 0.70707, 0.70707, 0 )
					},
					'eye': {
						value: new THREE.Vector3()
					},
					'waterColor': {
						value: new THREE.Color( 0x555555 )
					}
				} ] ),
				vertexShader: /* glsl */`
				uniform mat4 textureMatrix;
				uniform float time;

				varying vec4 mirrorCoord;
				varying vec4 worldPosition;

				#include <common>
				#include <fog_pars_vertex>
				#include <shadowmap_pars_vertex>
				#include <logdepthbuf_pars_vertex>

				void main() {
					mirrorCoord = modelMatrix * vec4( position, 1.0 );
					worldPosition = mirrorCoord.xyzw;
					mirrorCoord = textureMatrix * mirrorCoord;
					vec4 mvPosition =  modelViewMatrix * vec4( position, 1.0 );
					gl_Position = projectionMatrix * mvPosition;

				#include <beginnormal_vertex>
				#include <defaultnormal_vertex>
				#include <logdepthbuf_vertex>
				#include <fog_vertex>
				#include <shadowmap_vertex>
			}`,
				fragmentShader: /* glsl */`
				uniform sampler2D mirrorSampler;
				uniform float alpha;
				uniform float time;
				uniform float size;
				uniform float distortionScale;
				uniform sampler2D normalSampler;
				uniform vec3 sunColor;
				uniform vec3 sunDirection;
				uniform vec3 eye;
				uniform vec3 waterColor;

				varying vec4 mirrorCoord;
				varying vec4 worldPosition;

				vec4 getNoise( vec2 uv ) {
					vec2 uv0 = ( uv / 103.0 ) + vec2(time / 17.0, time / 29.0);
					vec2 uv1 = uv / 107.0-vec2( time / -19.0, time / 31.0 );
					vec2 uv2 = uv / vec2( 8907.0, 9803.0 ) + vec2( time / 101.0, time / 97.0 );
					vec2 uv3 = uv / vec2( 1091.0, 1027.0 ) - vec2( time / 109.0, time / -113.0 );
					vec4 noise = texture2D( normalSampler, uv0 ) +
						texture2D( normalSampler, uv1 ) +
						texture2D( normalSampler, uv2 ) +
						texture2D( normalSampler, uv3 );
					return noise * 0.5 - 1.0;
				}

				void sunLight( const vec3 surfaceNormal, const vec3 eyeDirection, float shiny, float spec, float diffuse, inout vec3 diffuseColor, inout vec3 specularColor ) {
					vec3 reflection = normalize( reflect( -sunDirection, surfaceNormal ) );
					float direction = max( 0.0, dot( eyeDirection, reflection ) );
					specularColor += pow( direction, shiny ) * sunColor * spec;
					diffuseColor += max( dot( sunDirection, surfaceNormal ), 0.0 ) * sunColor * diffuse;
				}

				#include <common>
				#include <packing>
				#include <bsdfs>
				#include <fog_pars_fragment>
				#include <logdepthbuf_pars_fragment>
				#include <lights_pars_begin>
				#include <shadowmap_pars_fragment>
				#include <shadowmask_pars_fragment>

				void main() {

					#include <logdepthbuf_fragment>
					vec4 noise = getNoise( worldPosition.xz * size );
					vec3 surfaceNormal = normalize( noise.xzy * vec3( 1.5, 1.0, 1.5 ) );

					vec3 diffuseLight = vec3(0.0);
					vec3 specularLight = vec3(0.0);

					vec3 worldToEye = eye-worldPosition.xyz;
					vec3 eyeDirection = normalize( worldToEye );
					sunLight( surfaceNormal, eyeDirection, 100.0, 2.0, 0.5, diffuseLight, specularLight );

					float distance = length(worldToEye);

					vec2 distortion = surfaceNormal.xz * ( 0.001 + 1.0 / distance ) * distortionScale;
					vec3 reflectionSample = vec3( texture2D( mirrorSampler, mirrorCoord.xy / mirrorCoord.w + distortion ) );

					float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );
					float rf0 = 0.3;
					float reflectance = rf0 + ( 1.0 - rf0 ) * pow( ( 1.0 - theta ), 5.0 );
					vec3 scatter = max( 0.0, dot( surfaceNormal, eyeDirection ) ) * waterColor;
					vec3 albedo = mix( ( sunColor * diffuseLight * 0.3 + scatter ) * getShadowMask(), ( vec3( 0.1 ) + reflectionSample * 0.9 + reflectionSample * specularLight ), reflectance);
					vec3 outgoingLight = albedo;
					gl_FragColor = vec4( outgoingLight, alpha );

					#include <tonemapping_fragment>
					#include <fog_fragment>
				}`
			};
			const material = new THREE.ShaderMaterial( {
				fragmentShader: mirrorShader.fragmentShader,
				vertexShader: mirrorShader.vertexShader,
				uniforms: THREE.UniformsUtils.clone( mirrorShader.uniforms ),
				lights: true,
				side: side,
				fog: fog
			} );
			material.uniforms[ 'mirrorSampler' ].value = renderTarget.texture;
			material.uniforms[ 'textureMatrix' ].value = textureMatrix;
			material.uniforms[ 'alpha' ].value = alpha;
			material.uniforms[ 'time' ].value = time;
			material.uniforms[ 'normalSampler' ].value = normalSampler;
			material.uniforms[ 'sunColor' ].value = sunColor;
			material.uniforms[ 'waterColor' ].value = waterColor;
			material.uniforms[ 'sunDirection' ].value = sunDirection;
			material.uniforms[ 'distortionScale' ].value = distortionScale;
			material.uniforms[ 'eye' ].value = eye;
			scope.material = material;
			scope.onBeforeRender = function ( renderer, scene, camera ) {

				mirrorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
				cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
				rotationMatrix.extractRotation( scope.matrixWorld );
				normal.set( 0, 0, 1 );
				normal.applyMatrix4( rotationMatrix );
				view.subVectors( mirrorWorldPosition, cameraWorldPosition );

				// Avoid rendering when mirror is facing away

				if ( view.dot( normal ) > 0 ) return;
				view.reflect( normal ).negate();
				view.add( mirrorWorldPosition );
				rotationMatrix.extractRotation( camera.matrixWorld );
				lookAtPosition.set( 0, 0, - 1 );
				lookAtPosition.applyMatrix4( rotationMatrix );
				lookAtPosition.add( cameraWorldPosition );
				target.subVectors( mirrorWorldPosition, lookAtPosition );
				target.reflect( normal ).negate();
				target.add( mirrorWorldPosition );
				mirrorCamera.position.copy( view );
				mirrorCamera.up.set( 0, 1, 0 );
				mirrorCamera.up.applyMatrix4( rotationMatrix );
				mirrorCamera.up.reflect( normal );
				mirrorCamera.lookAt( target );
				mirrorCamera.far = camera.far; // Used in WebGLBackground

				mirrorCamera.updateMatrixWorld();
				mirrorCamera.projectionMatrix.copy( camera.projectionMatrix );

				// Update the texture matrix
				textureMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 );
				textureMatrix.multiply( mirrorCamera.projectionMatrix );
				textureMatrix.multiply( mirrorCamera.matrixWorldInverse );

				// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
				// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
				mirrorPlane.setFromNormalAndCoplanarPoint( normal, mirrorWorldPosition );
				mirrorPlane.applyMatrix4( mirrorCamera.matrixWorldInverse );
				clipPlane.set( mirrorPlane.normal.x, mirrorPlane.normal.y, mirrorPlane.normal.z, mirrorPlane.constant );
				const projectionMatrix = mirrorCamera.projectionMatrix;
				q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
				q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
				q.z = - 1.0;
				q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];

				// Calculate the scaled plane vector
				clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );

				// Replacing the third row of the projection matrix
				projectionMatrix.elements[ 2 ] = clipPlane.x;
				projectionMatrix.elements[ 6 ] = clipPlane.y;
				projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
				projectionMatrix.elements[ 14 ] = clipPlane.w;
				eye.setFromMatrixPosition( camera.matrixWorld );

				// Render

				const currentRenderTarget = renderer.getRenderTarget();
				const currentXrEnabled = renderer.xr.enabled;
				const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
				scope.visible = false;
				renderer.xr.enabled = false; // Avoid camera modification and recursion
				renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows

				renderer.setRenderTarget( renderTarget );
				renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897

				if ( renderer.autoClear === false ) renderer.clear();
				renderer.render( scene, mirrorCamera );
				scope.visible = true;
				renderer.xr.enabled = currentXrEnabled;
				renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
				renderer.setRenderTarget( currentRenderTarget );

				// Restore viewport

				const viewport = camera.viewport;
				if ( viewport !== undefined ) {

					renderer.state.viewport( viewport );

				}

			};

		}

	}

	THREE.Water = Water;

} )();


text:
Ext.define('websure.backup.model.SetupWarningConfigModel', {
    extend: 'Ext.data.Model',
    fields: [
    		{name : 'configInfoId',   type: 'int'},
    		{name : 'configModelId', type: 'int'},
    		{name : 'configModeShow', type: 'string'},
    		{name : 'configTargetId', type: 'string'},
    		{name : 'timeAndFrequency', type: 'string'}
        ]
});


text:
package com.gmail.hasszhao.mininews.fragments.basic;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.gmail.hasszhao.mininews.R;

public class BasicDialogFragment extends SherlockDialogFragment {

	private final AnimationListener mInListener = new AnimationListener() {

		@Override
		public void onAnimationStart(Animation _animation) {
		}

		@Override
		public void onAnimationRepeat(Animation _animation) {
		}

		@Override
		public void onAnimationEnd(Animation _animation) {
			View v = getView();
			if (v != null) {
				v.findViewById(R.id.rl_dialog_container).setVisibility(View.VISIBLE);
			}
		}
	};
	private final AnimationListener mOutListener = new AnimationListener() {

		@Override
		public void onAnimationStart(Animation _animation) {
		}

		@Override
		public void onAnimationRepeat(Animation _animation) {
		}

		@Override
		public void onAnimationEnd(Animation _animation) {
			View v = getView();
			if (v != null) {
				v.findViewById(R.id.rl_dialog_container).setVisibility(View.GONE);
			}
			dismiss();
		}
	};

	@Override
	public void onCreate(Bundle _savedInstanceState) {
		super.onCreate(_savedInstanceState);
		setCancelable(true);
		setStyle(SherlockDialogFragment.STYLE_NO_TITLE, R.style.Dialog_Translucent);
	}

	@Override
	public void onViewCreated(View _view, Bundle _savedInstanceState) {
		super.onViewCreated(_view, _savedInstanceState);
		View v = getView();
		if (v != null) {
			Animation in = AnimationUtils.loadAnimation(getActivity(), R.anim.hyperspace_fast_in);
			in.setAnimationListener(mInListener);
			v.findViewById(R.id.sv_root).startAnimation(in);
		}
	}

	public void close() {
		View v = getView();
		if (v != null) {
			Animation out = AnimationUtils.loadAnimation(getActivity(), R.anim.hyperspace_fast_out);
			out.setAnimationListener(mOutListener);
			v.findViewById(R.id.sv_root).startAnimation(out);
		}
	}
}


text:
import lkml
import glob
import logging
import coloredlogs
import ast

import parse_lookml

logger = logging.getLogger(__name__)
coloredlogs.install(level='INFO')
logging.getLogger("looker_sdk").setLevel(logging.WARNING)

def format_str_list(list_str):
    new_list = ast.literal_eval(list_str)
    return new_list

def collate_view_files(parsed_lookml):
    response = []
    for instance_lookml in parsed_lookml:
        for path in instance_lookml.keys():
            if 'view.lkml' in path:
                response.append(instance_lookml)
    return response

def extract_field_names_from_lookml(parsed_lookml, data_storage):

    try:
        dimensions = parsed_lookml['dimensions']
    except KeyError:
        dimensions = []
        logger.warning('no dimensions present in view')
    try:
        measures = parsed_lookml['measures']
    except KeyError:
        measures = []
        logger.warning('no measures present in view')

    view_name = parsed_lookml.get('name')
    for dim in dimensions:
        field_name = dim.get('name')
        full_name = f'{view_name}.{field_name}'
        data_storage[full_name] = view_name

    for meas in measures:
        if len(meas) > 0:
            field_name = meas.get('name')
            full_name = f'{view_name}.{field_name}'
            data_storage[full_name] = view_name

    return data_storage

def match_fields_to_lookml(field_list, lookml):
    matched_fields = []
    for field in field_list:
        match = lookml.get(field, 'no match')
        if match != 'no match':
            matched_fields.append(field)

    print(matched_fields)
    return matched_fields

def extract_view_from_field(field_name):
    view_name = field_name.split('.')[0]
    return view_name

def match_element_to_lookml(instancedata, view_file):
    field_lookup = {}
    for lookml in view_file:
        parsed_lookml = parse_lookml.LookML(lookml)
        if parsed_lookml.has_views():
            for v in parsed_lookml.views():
                extract_field_names_from_lookml(
                    parsed_lookml=v, data_storage=field_lookup)

    matches = []
    for dashboard in instancedata:
        fields_used = format_str_list(dashboard.get('query.formatted_fields'))
        views_in_dash = []
        for field in fields_used:
            x = extract_view_from_field(field)
            if x not in views_in_dash:
                views_in_dash.append(x)
        matched_fields = match_fields_to_lookml(field_list=fields_used,
                                                lookml=field_lookup)

        temp = {}
        temp['used_views'] = views_in_dash
        temp['matched_fields'] = matched_fields
        temp['dashboard'] = dashboard.get('dashboard.id')
        matches.append(temp)
    return matches


text:
package com.gooddata.sdk.model.util;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.Set;

class TagsTestClass {

    private final Set<String> tags;

    @JsonCreator
    TagsTestClass(@JsonProperty("tags") @JsonDeserialize(using = TagsDeserializer.class) final Set<String> tags) {
        this.tags = tags;
    }

    @JsonSerialize(using = TagsSerializer.class)
    public Set<String> getTags() {
        return tags;
    }
}


text:
namespace AutoVersion{

	//Date Version Types
	static const char DATE[] = "20";
	static const char MONTH[] = "12";
	static const char YEAR[] = "2013";
	static const char UBUNTU_VERSION_STYLE[] = "13.12";

	//Software Status
	static const char STATUS[] = "Alpha";
	static const char STATUS_SHORT[] = "a";

	//Standard Version Type
	static const long MAJOR = 2;
	static const long MINOR = 4;
	static const long BUILD = 1686;
	static const long REVISION = 8239;

	//Miscellaneous Version Types
	static const long BUILDS_COUNT = 3467;
	#define RC_FILEVERSION 2,4,1686,8239
	#define RC_FILEVERSION_STRING "2, 4, 1686, 8239\0"
	static const char FULLVERSION_STRING[] = "2.4.1686.8239";

	//These values are to keep track of your versioning state, don't modify them.
	static const long BUILD_HISTORY = 46;

}
#endif //VERSION_H


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 288721 $ -->

<refentry xml:id="memcached.getstats" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>Memcached::getStats</refname>
  <refpurpose>Get server pool statistics</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>array</type><methodname>Memcached::getStats</methodname>
   <void />
  </methodsynopsis>
  <para>
   <function>Memcached::getStats</function> returns an array containing the
   state of all available memcache servers. See <link
    xlink:href="&url.memcache.protocol;">memcache protocol</link> specification
   for details on these statistics.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  &no.function.parameters;
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Array of server statistics, one entry per server.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>Memcached::getStats</function> example</title>
    <programlisting role="php">
<![CDATA[
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getStats());
?>
]]>
    </programlisting>
    &example.outputs.similar;
    <screen>
<![CDATA[
Array
(
    [localhost:11211] => Array
        (
            [pid] => 4933
            [uptime] => 786123
            [threads] => 1
            [time] => 1233868010
            [pointer_size] => 32
            [rusage_user_seconds] => 0
            [rusage_user_microseconds] => 140000
            [rusage_system_seconds] => 23
            [rusage_system_microseconds] => 210000
            [curr_items] => 145
            [total_items] => 2374
            [limit_maxbytes] => 67108864
            [curr_connections] => 2
            [total_connections] => 151
            [connection_structures] => 3
            [bytes] => 20345
            [cmd_get] => 213343
            [cmd_set] => 2381
            [get_hits] => 204223
            [get_misses] => 9120
            [evictions] => 0
            [bytes_read] => 9092476
            [bytes_written] => 15420512
            [version] => 1.2.6
        )

)
]]>
    </screen>
   </example>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package se.vidstige.jadb.test.integration;

import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import se.vidstige.jadb.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.List;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class RealDeviceTestCases {

    private JadbConnection jadb;

    @Rule
    public TemporaryFolder temporaryFolder = new TemporaryFolder(); //Must be public

    @BeforeClass
    public static void tryToStartAdbServer() {
        try {
            new AdbServerLauncher(new Subprocess(), System.getenv()).launch();
        } catch (IOException | InterruptedException e) {
            System.out.println("Could not start adb-server");
        }
    }

    @Before
    public void connect() throws IOException {
        try {
            jadb = new JadbConnection();
            jadb.getHostVersion();
        } catch (Exception e) {
            org.junit.Assume.assumeNoException(e);
        }
    }

    @Test
    public void testGetHostVersion() throws Exception {
        jadb.getHostVersion();
    }

    @Test
    public void testGetDevices() throws Exception {
        List<JadbDevice> actual = jadb.getDevices();
        Assert.assertNotNull(actual);
        //Assert.assertEquals("emulator-5554", actual.get(0).getSerial());
    }

    @Test
    public void testListFilesTwice() throws Exception {
        JadbDevice any = jadb.getAnyDevice();
        for (RemoteFile f : any.list("/")) {
            System.out.println(f.getPath());
        }

        for (RemoteFile f : any.list("/")) {
            System.out.println(f.getPath());
        }
    }

    @Test
    public void testPushFile() throws Exception {
        JadbDevice any = jadb.getAnyDevice();
        any.push(new File("README.md"), new RemoteFile("/sdcard/README.md"));
        //second read on the same device
        any.push(new File("README.md"), new RemoteFile("/sdcard/README.md"));
    }

    @Test(expected = JadbException.class)
    public void testPushFileToInvalidPath() throws Exception {
        JadbDevice any = jadb.getAnyDevice();
        any.push(new File("README.md"), new RemoteFile("/no/such/directory/README.md"));
    }

    @Test
    public void testPullFile() throws Exception {
        JadbDevice any = jadb.getAnyDevice();
        any.pull(new RemoteFile("/sdcard/README.md"), temporaryFolder.newFile("foobar.md"));
        //second read on the same device
        any.pull(new RemoteFile("/sdcard/README.md"), temporaryFolder.newFile("foobar.md"));
    }

    @Test(expected = JadbException.class)
    public void testPullInvalidFile() throws Exception {
        JadbDevice any = jadb.getAnyDevice();
        any.pull(new RemoteFile("/file/does/not/exist"), temporaryFolder.newFile("xyz"));
    }

    @SuppressWarnings("deprecation")
	@Test
    public void testShellExecuteTwice() throws Exception {
        JadbDevice any = jadb.getAnyDevice();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        any.executeShell(bout, "ls /");
        any.executeShell(bout, "ls", "-la", "/");
        System.out.write(bout.toByteArray());
    }

    @Test
    public void testScreenshot() throws Exception {
        JadbDevice any = jadb.getAnyDevice();
        try (FileOutputStream outputStream = new FileOutputStream(temporaryFolder.newFile("screenshot.png"))) {
            InputStream stdout = any.executeShell("screencap", "-p");
            Stream.copy(stdout, outputStream);
        }
    }

    /**
     * This test requires emulator running on non-standard tcp port - this may be achieve by executing such command:
     * ${ANDROID_HOME}/emulator -verbose -avd ${NAME} -ports 10000,10001
     *
     * @throws IOException
     * @throws JadbException
     * @throws ConnectionToRemoteDeviceException
     */
    @Test
    public void testConnectionToTcpDevice() throws IOException, JadbException, ConnectionToRemoteDeviceException {
        jadb.connectToTcpDevice(new InetSocketAddress("127.0.0.1", 10001));
        List<JadbDevice> devices = jadb.getDevices();

        assertNotNull(devices);
        assertFalse(devices.isEmpty());
    }

    /**
     * @see #testConnectionToTcpDevice()
     *
     * @throws IOException
     * @throws JadbException
     * @throws ConnectionToRemoteDeviceException
     */
    @Test
    public void testDisconnectionToTcpDevice() throws IOException, JadbException, ConnectionToRemoteDeviceException {
        testConnectionToTcpDevice();

        jadb.disconnectFromTcpDevice(new InetSocketAddress("127.0.0.1", 10001));
        jadb.getDevices();

        List<JadbDevice> devices = jadb.getDevices();
        assertNotNull(devices);
        assertTrue(devices.isEmpty());
    }
}


text:
package com.jetbrains.python.codeInsight.intentions;

import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.template.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.NotNull;

/**
 * User: ktisha
 *
 * Helps to specify type  in annotations in python3
 */
public class SpecifyTypeInPy3AnnotationsIntention extends TypeIntention {
  private String myText = PyBundle.message("INTN.specify.type.in.annotation");
  public SpecifyTypeInPy3AnnotationsIntention() {
  }

  @NotNull
  public String getText() {
    return myText;
  }

  @NotNull
  public String getFamilyName() {
    return PyBundle.message("INTN.specify.type.in.annotation");
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!LanguageLevel.forElement(file).isPy3K()) return false;
    return super.isAvailable(project, editor, file);
  }

  public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    PsiElement elementAt = PyUtil.findNonWhitespaceAtOffset(file, editor.getCaretModel().getOffset());
    PyExpression problemElement = getProblemElement(elementAt);
    PsiReference reference = problemElement == null? null : problemElement.getReference();

    final PsiElement resolved = reference != null? reference.resolve() : null;
    PyParameter parameter = getParameter(problemElement, resolved);

    if (parameter != null) {
      annotateParameter(project, editor, parameter);
    }
    else {
      annotateReturnType(project, elementAt);
    }
  }

  private static void annotateParameter(Project project, Editor editor, PyParameter parameter) {
    PyExpression defaultParamValue = parameter instanceof PyNamedParameter? parameter.getDefaultValue() : null;

    final String name = StringUtil.notNullize(parameter.getName());
    PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);

    String defaultParamText = defaultParamValue == null? null: defaultParamValue.getText();
    final PyNamedParameter namedParameter = elementGenerator.createParameter(name, defaultParamText, PyNames.OBJECT, LanguageLevel.forElement(parameter));
    assert namedParameter != null;
    parameter = (PyParameter)parameter.replace(namedParameter);
    parameter = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(parameter);
    editor.getCaretModel().moveToOffset(parameter.getTextOffset());
    PyAnnotation annotation = parameter instanceof PyNamedParameter? ((PyNamedParameter)parameter).getAnnotation() : null;
    if (annotation != null) {
      PyExpression annotationValue = annotation.getValue();

      final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(parameter);
      int replacementStart = annotation.getStartOffsetInParent() + annotationValue.getStartOffsetInParent();
      builder.replaceRange(TextRange.create(replacementStart,
                                            replacementStart + annotationValue.getTextLength()), PyNames.OBJECT);
      Template template = ((TemplateBuilderImpl)builder).buildInlineTemplate();
      TemplateManager.getInstance(project).startTemplate(editor, template);
    }
  }

  private void annotateReturnType(Project project, PsiElement resolved) {
    PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);

    PyCallable callable = getCallable(resolved);

    if (callable instanceof PyFunction) {
      final String functionSignature = "def " + callable.getName() + callable.getParameterList().getText();
      String functionText = functionSignature +
                          " -> object:";
      final PyStatementList statementList = ((PyFunction)callable).getStatementList();
      assert statementList != null;
      for (PyStatement st : statementList.getStatements()) {
        functionText = functionText + "\n\t" + st.getText();
      }
      final PyFunction function = elementGenerator.createFromText(LanguageLevel.forElement(callable), PyFunction.class,
                                                                  functionText);
      callable = (PyFunction)callable.replace(function);
      callable = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(callable);

      final PyAnnotation annotation = ((PyFunction)callable).getAnnotation();
      assert annotation != null;
      final PyExpression annotationValue = annotation.getValue();
      final int offset = annotationValue.getTextOffset();

      final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(annotationValue);
      builder.replaceRange(TextRange.create(0, PyNames.OBJECT.length()), PyNames.OBJECT);
      Template template = ((TemplateBuilderImpl)builder).buildInlineTemplate();
      OpenFileDescriptor descriptor = new OpenFileDescriptor(
        project,
        callable.getContainingFile().getVirtualFile(),
        offset
      );
      Editor targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
      if (targetEditor != null) {
        targetEditor.getCaretModel().moveToOffset(offset);
        TemplateManager.getInstance(project).startTemplate(targetEditor, template);
      }
    }
  }

  @Override
  protected boolean isParamTypeDefined(PyParameter parameter) {
    return isDefinedInAnnotation(parameter);
  }

  private boolean isDefinedInAnnotation(PyParameter parameter) {
    if (LanguageLevel.forElement(parameter).isOlderThan(LanguageLevel.PYTHON30)) {
      return false;
    }
    if (parameter instanceof PyNamedParameter && (((PyNamedParameter)parameter).getAnnotation() != null)) return true;
    return false;
  }

  @Override
  protected boolean isReturnTypeDefined(@NotNull PyFunction function) {
    return function.getAnnotation() != null;
  }

  @Override
  protected void updateText(boolean isReturn) {
    myText = isReturn? PyBundle.message("INTN.specify.return.type.in.annotation") : PyBundle.message("INTN.specify.type.in.annotation");
  }
}


text:
There was a problem

Please amend the following details:

Provide an Address

Provide a Town or City

Provide a Postcode


text:
import numpy
import imaginet.tts as tts
import imaginet.vendrov_provider as vdp
import imaginet.data_provider as dp
import logging

def main():
    logging.getLogger().setLevel('INFO')
    for dataset in ['flickr8k', 'coco']:

        def mfcc(data):
            if dataset == 'coco':
                return [ tts.extract_mfcc(audio) for audio in data]
            else:
                return tts.add_accel([ tts.extract_mfcc(audio) for audio in data])

        logging.info('Generating features for {}'.format(dataset))
        savedir = "../data/%s/"%dataset
        if dataset == 'flickr8k':
            prov = dp.getDataProvider('flickr8k', root='..', audio_kind=None)
        else:
            prov = vdp.getDataProvider(dataset='coco', root='..', audio_kind=None)
        validate = list(prov.iterSentences(split='val'))

        #build lexicon
        words = set()
        for v in validate:
            for w in v['tokens']:
                words.add(w)

        numpy.save(savedir+"words-"+dataset+".npy", list(words))
        mp3dir = "{}/mp3/".format(savedir)
        spoken = [ tts.decodemp3(open("{}/{}.mp3".format(mp3dir, word), 'rb').read())
                   for word in words ]
        audiofeatures = mfcc(spoken)
        numpy.save(savedir+"mfcc-"+dataset+".npy", audiofeatures)

if __name__ == '__main__':
    main()


text:
//
//  NSObject+Common.m
//  Coding_iOS
//
//  Created by 王 原闯 on 14-7-31.
//  Copyright (c) 2014年 Coding. All rights reserved.
//
#define kPath_ImageCache @"ImageCache"
#define kPath_ResponseCache @"ResponseCache"
#define kTestKey @"BaseURLIsTest"
#define kHUDQueryViewTag 101

#import "NSObject+Common.h"
#import "JDStatusBarNotification.h"
#import "Login.h"
#import "AppDelegate.h"
#import "MBProgressHUD+Add.h"
//#import "NetAPIClient.h"
//#import <SDCAlertView/SDCAlertController.h>
//#import "Coding_NetAPIManager.h"
#import "UIImageView+WebCache.h"
@implementation NSObject (Common)

#pragma mark Tip M
+ (NSString *)tipFromError:(NSError *)error{
    if (error && error.userInfo) {
        NSMutableString *tipStr = [[NSMutableString alloc] init];
        if ([error.userInfo objectForKey:@"msg"]) {
            NSArray *msgArray = [[error.userInfo objectForKey:@"msg"] allValues];
            NSUInteger num = [msgArray count];
            for (int i = 0; i < num; i++) {
                NSString *msgStr = [msgArray objectAtIndex:i];
                //HtmlMedia *media = [HtmlMedia htmlMediaWithString:msgStr showType:MediaShowTypeAll];
                //msgStr = media.contentDisplay;
                if (i+1 < num) {
                    [tipStr appendString:[NSString stringWithFormat:@"%@\n", msgStr]];
                }else{
                    [tipStr appendString:msgStr];
                }
            }
        }else{
            if ([error.userInfo objectForKey:@"NSLocalizedDescription"]) {
                tipStr = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            }else{
                [tipStr appendFormat:@"ErrorCode%ld", (long)error.code];
            }
        }
        return tipStr;
    }
    return nil;
}
+ (BOOL)showError:(NSError *)error{
    if ([JDStatusBarNotification isVisible]) {//如果statusBar上面正在显示信息,则不再用hud显示error
        NSLog(@"如果statusBar上面正在显示信息,则不再用hud显示error");
        return NO;
    }
    NSString *tipStr = [NSObject tipFromError:error];
    [NSObject showHudTipStr:tipStr];
    return YES;
}
+ (void)showHudTipStr:(NSString *)tipStr{
    if (tipStr && tipStr.length > 0) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:kKeyWindow animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.detailsLabelFont = [UIFont boldSystemFontOfSize:15.0];
        hud.detailsLabelText = tipStr;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1.0];
    }
}
/**
 *  类似Android的Toast效果
 *
 *  @param str     显示的文字
 *  @param xOffset 指定距离中心点的x轴位置
 *  @param yOffset 指定距离中心点的y轴位置
 */
+ (void)showAllTextDialog:(NSString *)str xOffset:(CGFloat)xOffset yOffset:(CGFloat)yOffset {
   __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:kKeyWindow animated:YES];
    hud.labelText = str;
    hud.mode = MBProgressHUDModeText;
    hud.yOffset = yOffset;
    hud.xOffset = xOffset;
    [hud showAnimated:YES whileExecutingBlock:^{
        sleep(1);
    } completionBlock:^{
        [hud removeFromSuperview];
        hud = nil;
    }];
}

+ (instancetype)showHUDQueryStr:(NSString *)titleStr toView:(UIView *)view {
    titleStr = titleStr.length > 0? titleStr: @"正在获取数据...";
    view = view == nil? view:kKeyWindow;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.tag = kHUDQueryViewTag;
    hud.labelText = titleStr;
    hud.labelFont = [UIFont boldSystemFontOfSize:15.0];
    hud.margin = 10.f;
    return hud;
}

+ (instancetype)showHUDQueryStr:(NSString *)titleStr{
//    titleStr = titleStr.length > 0? titleStr: @"正在获取数据...";
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:kKeyWindow animated:YES];
//    hud.tag = kHUDQueryViewTag;
//    hud.labelText = titleStr;
//    hud.labelFont = [UIFont boldSystemFontOfSize:15.0];
//    hud.margin = 10.f;
    return [self showHUDQueryStr:titleStr toView:kKeyWindow];
}
+ (NSUInteger)hideHUDQuery{
    __block NSUInteger count = 0;
    NSArray *huds = [MBProgressHUD allHUDsForView:kKeyWindow];
    [huds enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
        if (obj.tag == kHUDQueryViewTag) {
            [obj removeFromSuperview];
            count++;
        }
    }];
    return count;
}
+ (void)showStatusBarQueryStr:(NSString *)tipStr{
    [JDStatusBarNotification showWithStatus:tipStr styleName:JDStatusBarStyleSuccess];
    [JDStatusBarNotification showActivityIndicator:YES indicatorStyle:UIActivityIndicatorViewStyleWhite];
}
+ (void)showStatusBarSuccessStr:(NSString *)tipStr{
    if ([JDStatusBarNotification isVisible]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
            [JDStatusBarNotification showWithStatus:tipStr dismissAfter:1.5 styleName:JDStatusBarStyleSuccess];
        });
    }else{
        [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
        [JDStatusBarNotification showWithStatus:tipStr dismissAfter:1.0 styleName:JDStatusBarStyleSuccess];
    }
}
+ (void)showStatusBarErrorStr:(NSString *)errorStr{
    if ([JDStatusBarNotification isVisible]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
            [JDStatusBarNotification showWithStatus:errorStr dismissAfter:1.5 styleName:JDStatusBarStyleError];
        });
    }else{
        [JDStatusBarNotification showActivityIndicator:NO indicatorStyle:UIActivityIndicatorViewStyleWhite];
        [JDStatusBarNotification showWithStatus:errorStr dismissAfter:1.5 styleName:JDStatusBarStyleError];
    }
}

+ (void)showStatusBarError:(NSError *)error{
    NSString *errorStr = [NSObject tipFromError:error];
    [NSObject showStatusBarErrorStr:errorStr];
}

#pragma mark BaseURL
+ (NSString *)baseURLStr{
    NSString *baseURLStr;
    if ([self baseURLStrIsTest]) {
        //staging
        //baseURLStr = kBaseUrlStr_Test;
    }else{
        //生产
        baseURLStr = @"http://42.99.0.100:9000/";
    }
//    //staging
//    baseURLStr = kBaseUrlStr_Test;
//    //村民
//    baseURLStr = @"http://192.168.0.188:8080/";
//    //彭博
//    baseURLStr = @"http://192.168.0.156:9990/";
//    //小胖
//    baseURLStr = @"http://192.168.0.222:8080/";

    return baseURLStr;
}

+ (BOOL)baseURLStrIsTest{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    return [[defaults valueForKey:kTestKey] boolValue];
}
+ (void)changeBaseURLStrToTest:(BOOL)isTest{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@(isTest) forKey:kTestKey];
    [defaults synchronize];

    //[NetAPIClient changeJsonClient];

    [[UINavigationBar appearance] setBackgroundImage: [UIImage imageWithColor:[UIColor colorWithHexString:isTest?@"0x3bbd79": @"0x28303b"]] forBarMetrics:UIBarMetricsDefault];
}

#pragma mark File M
//获取fileName的完整地址
+ (NSString* )pathInCacheDirectory:(NSString *)fileName
{
    NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [cachePaths objectAtIndex:0];
    return [cachePath stringByAppendingPathComponent:fileName];
}
//创建缓存文件夹
+ (BOOL) createDirInCache:(NSString *)dirName
{
    NSString *dirPath = [self pathInCacheDirectory:dirName];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    BOOL isCreated = NO;
    if ( !(isDir == YES && existed == YES) )
    {
        isCreated = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (existed) {
        isCreated = YES;
    }
    return isCreated;
}

// 图片缓存到本地
+ (BOOL) saveImage:(UIImage *)image imageName:(NSString *)imageName inFolder:(NSString *)folderName
{
    if (!image) {
        return NO;
    }
    if (!folderName) {
        folderName = kPath_ImageCache;
    }
    if ([self createDirInCache:folderName]) {
        NSString * directoryPath = [self pathInCacheDirectory:folderName];
        BOOL isDir = NO;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL existed = [fileManager fileExistsAtPath:directoryPath isDirectory:&isDir];
        bool isSaved = false;
        if ( isDir == YES && existed == YES )
        {
            isSaved = [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:imageName] options:NSAtomicWrite error:nil];
        }
        return isSaved;
    }else{
        return NO;
    }
}
// 获取缓存图片
+ (NSData*) loadImageDataWithName:( NSString *)imageName inFolder:(NSString *)folderName
{
    if (!folderName) {
        folderName = kPath_ImageCache;
    }
    NSString * directoryPath = [self pathInCacheDirectory:folderName];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL dirExisted = [fileManager fileExistsAtPath:directoryPath isDirectory:&isDir];
    if ( isDir == YES && dirExisted == YES )
    {
        NSString *abslutePath = [NSString stringWithFormat:@"%@/%@", directoryPath, imageName];
        BOOL fileExisted = [fileManager fileExistsAtPath:abslutePath];
        if (!fileExisted) {
            return NULL;
        }
        NSData *imageData = [NSData dataWithContentsOfFile : abslutePath];
        return imageData;
    }
    else
    {
        return NULL;
    }
}

// 删除图片缓存
+ (BOOL) deleteImageCacheInFolder:(NSString *)folderName{
    if (!folderName) {
        folderName = kPath_ImageCache;
    }
    return [self deleteCacheWithPath:folderName];
}

//网络请求
+ (BOOL)saveResponseData:(NSDictionary *)data toPath:(NSString *)requestPath{
//    User *loginUser = [Login curLoginUser];
//    if (!loginUser) {
//        return NO;
//    }else{
//        requestPath = [NSString stringWithFormat:@"%@_%@", loginUser.global_key, requestPath];
//    }
//    if ([self createDirInCache:kPath_ResponseCache]) {
//        NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
//        return [data writeToFile:abslutePath atomically:YES];
//    }else{
//        return NO;
//    }
    return NO;
}
+ (id) loadResponseWithPath:(NSString *)requestPath{//返回一个NSDictionary类型的json数据
//    User *loginUser = [Login curLoginUser];
//    if (!loginUser) {
//        return nil;
//    }else{
//        requestPath = [NSString stringWithFormat:@"%@_%@", loginUser.global_key, requestPath];
//    }
//    NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
//    return [NSMutableDictionary dictionaryWithContentsOfFile:abslutePath];
    return NO;
}

+ (BOOL)deleteResponseCacheForPath:(NSString *)requestPath{
//    User *loginUser = [Login curLoginUser];
//    if (!loginUser) {
//        return NO;
//    }else{
//        requestPath = [NSString stringWithFormat:@"%@_%@", loginUser.global_key, requestPath];
//    }
//    NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    if ([fileManager fileExistsAtPath:abslutePath]) {
//        return [fileManager removeItemAtPath:abslutePath error:nil];
//    }else{
//        return NO;
//    }
    return NO;
}

+ (BOOL) deleteResponseCache{
    return [self deleteCacheWithPath:kPath_ResponseCache];
}

+ (NSUInteger)getResponseCacheSize {
    NSString *dirPath = [self pathInCacheDirectory:kPath_ResponseCache];
    NSUInteger size = 0;
    NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:dirPath];
    for (NSString *fileName in fileEnumerator) {
        NSString *filePath = [dirPath stringByAppendingPathComponent:fileName];
        NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        size += [attrs fileSize];
    }
    return size;
}

+ (BOOL) deleteCacheWithPath:(NSString *)cachePath{
    NSString *dirPath = [self pathInCacheDirectory:cachePath];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    bool isDeleted = false;
    if ( isDir == YES && existed == YES )
    {
        isDeleted = [fileManager removeItemAtPath:dirPath error:nil];
    }
    return isDeleted;
}

#pragma mark NetError
-(id)handleResponse:(id)responseJSON{
    return [self handleResponse:responseJSON autoShowError:YES];
}
-(id)handleResponse:(id)responseJSON autoShowError:(BOOL)autoShowError{
    NSError *error = nil;
    //code为非0值时,表示有错
    NSInteger errorCode = [(NSNumber *)[responseJSON valueForKeyPath:@"code"] integerValue];

    if (errorCode != 0) {
        error = [NSError errorWithDomain:[NSObject baseURLStr] code:errorCode userInfo:responseJSON];
        if (errorCode == 1000 || errorCode == 3207) {//用户未登录
            if ([Login isLogin]) {
                [Login logOut];//已登录的状态要抹掉
                //更新 UI 要延迟 >1.0 秒,否则屏幕可能会不响应触摸事件。。暂不知为何
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [((AppDelegate *)[UIApplication sharedApplication].delegate) setupLoginViewController];
                    kTipAlert(@"%@", [NSObject tipFromError:error]);
                });
            }
        }else{
            //验证码弹窗
//            NSMutableDictionary *params = nil;
//            if (errorCode == 907) {//operation_need_captcha 比如:每日新增关注用户超过 20 个
//                params = @{@"type": @3}.mutableCopy;
//            }else if (errorCode == 1018){//user_not_get_request_too_many
//                params = @{@"type": @1}.mutableCopy;
//            }
//            if (params) {
//                [NSObject showCaptchaViewParams:params];
//            }
            //错误提示
            if (autoShowError) {
                [NSObject showError:error];
            }
        }
    }
    return error;
}

//+ (void)showCaptchaViewParams:(NSMutableDictionary *)params{
//    //Data
//    if (!params) {
//        params = @{}.mutableCopy;
//    }
//    if (!params[@"type"]) {
//        params[@"type"] = @1;
//    }
//    NSString *path = @"api/request_valid";
//    NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@api/getCaptcha?type=%@", [NSObject baseURLStr], params[@"type"]]];
//    //UI
//    SDCAlertController *alertV = [SDCAlertController alertControllerWithTitle:@"提示" message:@"亲,您操作这么快,不会是机器人吧?\n来,输个验证码先?" preferredStyle:SDCAlertControllerStyleAlert];
//    UITextField *textF = [UITextField new];
//    textF.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0);
//    textF.backgroundColor = [UIColor whiteColor];
//    [textF doBorderWidth:0.5 color:nil cornerRadius:2.0];
//    UIImageView *imageV = [UIImageView new];
//    imageV.backgroundColor = [UIColor lightGrayColor];
//    imageV.contentMode = UIViewContentModeScaleAspectFit;
//    imageV.clipsToBounds = YES;
//    imageV.userInteractionEnabled = YES;
//    [textF doBorderWidth:0.5 color:nil cornerRadius:2.0];
//    [imageV sd_setImageWithURL:imageURL placeholderImage:nil options:(SDWebImageRetryFailed | SDWebImageRefreshCached | SDWebImageHandleCookies)];
//
//    [alertV.contentView addSubview:textF];
//    [alertV.contentView addSubview:imageV];
//    [textF mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(alertV.contentView).offset(15);
//        make.height.mas_equalTo(25);
//        make.bottom.equalTo(alertV.contentView).offset(-10);
//    }];
//    [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(alertV.contentView).offset(-15);
//        make.left.equalTo(textF.mas_right).offset(10);
//        make.width.mas_equalTo(60);
//        make.height.mas_equalTo(25);
//        make.centerY.equalTo(textF);
//    }];
//    //Action
//    __weak typeof(imageV) weakImageV = imageV;
//    [imageV bk_whenTapped:^{
//        [weakImageV sd_setImageWithURL:imageURL placeholderImage:nil options:(SDWebImageRetryFailed | SDWebImageRefreshCached | SDWebImageHandleCookies)];
//    }];
//    __weak typeof(alertV) weakAlertV = alertV;
//    [alertV addAction:[SDCAlertAction actionWithTitle:@"取消" style:SDCAlertActionStyleCancel handler:nil]];
//    [alertV addAction:[SDCAlertAction actionWithTitle:@"还真不是" style:SDCAlertActionStyleDefault handler:nil]];
//    alertV.shouldDismissBlock =  ^BOOL (SDCAlertAction *action){
//        BOOL shouldDismiss = [action.title isEqualToString:@"取消"];
//        if (!shouldDismiss) {
//            params[@"j_captcha"] = textF.text;
////            [[CodingNetAPIClient sharedJsonClient] requestJsonDataWithPath:path withParams:params withMethodType:Post andBlock:^(id data, NSError *error) {
////                if (data) {
////                    [weakAlertV dismissWithCompletion:^{
////                        [NSObject showHudTipStr:@"验证码正确"];
////                    }];
////                }else{
////                    [weakImageV sd_setImageWithURL:imageURL placeholderImage:nil options:(SDWebImageRetryFailed | SDWebImageRefreshCached | SDWebImageHandleCookies)];
////                }
////            }];
//        }
//        return shouldDismiss;
//    };
//    [alertV presentWithCompletion:^{
//        [textF becomeFirstResponder];
//    }];
//}

@end


text:
#include <string.h>
#include "Control.h"
#include "Mask.h"
#include "Data/OtterData.h"
#include "Utilities/Utilities.h"
#include "Graphics/Graphics.h"
#include "Memory/Memory.h"
#include <assert.h>
#include <limits>

using namespace VectorMath;

namespace Otter
{
	/* Constructor
	 */
	Control::Control(Scene* pScene, Control* pParent, const ControlData* pControlData)
	{
		mParent = pParent;
		mControlData = pControlData;

		mScene = pScene;

		mEnabled = true;
		mUpdateTransform = true;

		mUserCreated = false;
		mTouchEnabled = true;

		mMaskControl = NULL;
	}

	/* Virtual Destructor
	 */
	Control::~Control(void)
	{
		SetParentControl(NULL);
	}

	/* Retrieves the control's name
	 */
	const char* Control::GetName()
	{
		if(!mControlData)
			return "";

		return mControlData->mName;
	}

	/* Retrieves the control's ID
	 */
	uint32 Control::GetID()
	{
		if(!mControlData)
			return 0xFFFFFFFF;

		return mControlData->mID;
	}

	/* Retrieves the control's position
	 */
	const Vector2& Control::GetPosition()
	{
		Vector2& v = *reinterpret_cast<Vector2*>((float*)mControlData->mPosition);
		return v;
	}

	/* Retrieves the control's absolute position
	 */
	const Vector2 Control::GetAbsolutePosition()
	{
		Vector2 v = *reinterpret_cast<Vector2*>((float*)mControlData->mPosition);

		Control* parent = GetParentControl();

		if( parent )
		{
			Vector2 parentv = parent->GetAbsolutePosition();
			v.x += parentv.x;
			v.y += parentv.y;
		}

		return v;
	}

	/* Sets the control's position
	 */
	void Control::SetPosition(const Vector2& position)
	{
		ControlData* pControlData = const_cast<ControlData*>(mControlData);
		pControlData->mPosition[0] = position.x;
		pControlData->mPosition[1] = position.y;

		mUpdateTransform = true;
	}

	/* Retrieves the control's center
	 */
	const Vector2& Control::GetCenter()
	{
		Vector2& v = *reinterpret_cast<Vector2*>((float*)mControlData->mCenter);
		return v;
	}

	/* Sets the control's center
	 */
	void Control::SetCenter(const Vector2& center)
	{
		ControlData* pControlData = const_cast<ControlData*>(mControlData);
		pControlData->mCenter[0] = center.x;
		pControlData->mCenter[1] = center.y;

		mUpdateTransform = true;
	}

	/* Retrieves the control's size
	 */
	const Vector2& Control::GetSize()
	{
		Vector2& v = *reinterpret_cast<Vector2*>((float*)mControlData->mSize);
		return v;
	}

	/* Sets the control's size
	 */
	void Control::SetSize(const Vector2& size)
	{
		ControlData* pControlData = const_cast<ControlData*>(mControlData);
		pControlData->mSize[0] = size.x;
		pControlData->mSize[1] = size.y;

		mUpdateTransform = true;
	}

	/* Gets the control's rotation
	 */
	float Control::GetRotation()
	{
		return mControlData->mRotation;
	}

	/* Sets the control's rotation
	 */
	void Control::SetRotation(float rotation)
	{
		ControlData* pControlData = const_cast<ControlData*>(mControlData);
		pControlData->mRotation = rotation;

		mUpdateTransform = true;
	}

	/* Gets the control's mask ID
	 */
	int Control::GetMask()
	{
		return mControlData->mMaskID;
	}

	/* Gets the control's mask
	 */
	Mask* Control::GetMaskControl()
	{
		return mMaskControl;
	}

	/* Sets the control's mask ID
	 */
	void Control::SetMask(int maskID)
	{
		ControlData* pControlData = const_cast<ControlData*>(mControlData);

		Control* parentView = GetParentView();
		if (parentView)
		{
			pControlData->mMaskID = maskID;

			if (maskID == -1)
				mMaskControl = NULL;
			else
				mMaskControl = (Mask*)parentView->GetControl(maskID);
		}
		else
		{
			//this is a view; you can't set a mask on a view
			pControlData->mMaskID = -1;
			mMaskControl = NULL;
		}
	}

	/* Calculates the local transform for this control.
	 */
	const Matrix4& Control::GetTransform()
	{
		if(mUpdateTransform)
		{
			const Vector2& center = GetCenter();
			const Vector2& pos = GetPosition();
			float rot = GetRotation();

			Matrix4 offsetTrans		= Matrix4::Translation(-center.x, -center.y, 0.0f);
			Matrix4 rotation		= Matrix4::RotationZ(rot * Constants::DEG_TO_RAD);
			Matrix4 locTrans		= Matrix4::Translation(pos.x, pos.y, 0.0f);

			mTransform = mBaseTransform * (locTrans * (rotation * offsetTrans));
			mUpdateTransform = false;
		}

		return mTransform;
	}

	/* Calculates the full transform for this control.
	 */
	const Matrix4 Control::GetFullTransform()
	{
		Matrix4 fullTransform = Matrix4::IDENTITY;
		Control* pControl = this;
		while(pControl)
		{
			fullTransform = pControl->GetTransform() * fullTransform;
			pControl = pControl->GetParentControl();
		}

		return fullTransform;
	}

	/**
		* Sets the base transform for this control
		*/
	void Control::SetBaseTransform(const VectorMath::Matrix4& baseTransform)
	{
		mBaseTransform = baseTransform;
		mUpdateTransform = true;
	}

	/* Retrieves a control in the hierachy by id
	 */
	Control* Control::GetControl(uint32 id)
	{
		if(id == 0xFFFFFFFF)
			return NULL;

		if(GetID() == id)
			return this;

		for(uint32 i = 0; i < mControls.size(); i++)
		{
			Control* pControl = mControls[i];
			pControl = pControl->GetControl(id);

			if(pControl)
				return pControl;
		}

		return NULL;
	}

	/* Retrieves a control by point.
	 */
	Control* Control::GetControl(const Point& point, Point* localPoint, bool touchablesOnly)
	{
		if(!mEnabled || touchablesOnly && !TouchesEnabled())
			return NULL;
		for(sint32 i = (sint32)mControls.size() - 1; i >= 0; --i)
			if( Control * c=mControls[i]->GetControl(point, localPoint, touchablesOnly) )
				return c;
		Point lp;
		ScreenToLocal(point, lp);

		const Vector2& dims = GetSize();
		if (lp.x >= 0.0f && lp.x <= dims.x && lp.y >= 0.0 && lp.y <= dims.y)
		{
			if(localPoint)
			{
				localPoint->x = lp.x;
				localPoint->y = lp.y;
			}

			return this;
		}

		return NULL;
	}

	/* Adds a child control
		*/
	Result Control::AddControl(Control* pControl)
	{
		if(pControl == NULL)
			return kResult_InvalidParameter;

		if(pControl->GetParentControl() != NULL)
			pControl->GetParentControl()->RemoveControl(pControl);

		mControls.push_back(pControl);
		pControl->SetParentControl(this);

		return kResult_OK;
	}

	/* Removes a child control
	 */
	Result Control::RemoveControl(Control* pControl)
	{
		if(pControl == NULL)
			return kResult_InvalidParameter;

		for(uint32 i = 0; i < mControls.size(); i++)
		{
			if(mControls[i] == pControl)
			{
				mControls.erase(i);

				return kResult_OK;
			}
		}

		return kResult_InvalidParameter;
	}

	/* Retrieves a control by name
	 */
	Control* Control::GetControl(const char* szControlName)
	{
		if(strcmp(GetName(), szControlName) == 0)
			return this;

		for(uint32 i = 0; i < mControls.size(); i++)
		{
			Control* pControl = mControls[i];
			pControl = pControl->GetControl(szControlName);

			if(pControl)
				return pControl;
		}

		return NULL;
	}

	/* Retrieves a control by index
	 */
	Control* Control::GetControlAtIndex(uint32 index)
	{
		if(index >= mControls.size())
			return NULL;

		return mControls[index];
	}

	/* Retrieves the number of direct child controls
	 */
	uint32 Control::GetNumControls()
	{
		return mControls.size();
	}

	/* Converts the screen point to a local
	 * local point, relative to the control
	 */
	void Control::ScreenToLocal(const Point& point, Point& localPoint)
	{
		Matrix4 inverse = GetFullTransform().Inverse();
		Vector4 v(point.x, point.y, 0.0f, 1.0f);
		v = inverse * v;

		localPoint.x = v.x;
		localPoint.y = v.y;
	}

	/* Sets the control's parent
		*/
	Result Control::SetParentControl(Control* pParent)
	{
		mParent = pParent;
		mScene = (pParent == NULL) ? NULL : pParent->GetScene();

		mUpdateTransform = true;

		return kResult_OK;
	}

	/* Returns the parent of this control
	 */
	Control* Control::GetParentControl()
	{
		return mParent;
	}

	/* Returns the containing view of this control
	 * The top-most parent will always be a View, unless
	 * 'this' is a view, in which case mParent is NULL and
	 * GetView returns NULL.
	 */
	View* Control::GetParentView()
	{
		Control* pParent = mParent;
		while(pParent != NULL && pParent->GetParentControl() != NULL)
			pParent = pParent->GetParentControl();

		return (View*)pParent;
	}

	void Control::RemapMasks( View * parentView, Control * cloneRoot )
	{
		assert(parentView!=0);
		assert(cloneRoot!=0);
		if( mControlData->mMaskID!=-1 )
		{
			mMaskControl = static_cast<Mask *>(cloneRoot->GetControl(parentView->GetControl(mControlData->mMaskID)->GetName()));
			const_cast<ControlData *>(mControlData)->mMaskID = mMaskControl->GetID();
		}
		for (uint32 i = 0; i < mControls.size(); ++i)
			mControls[i]->RemapMasks(parentView,cloneRoot);
	}

	/* Brings the specified control the front, ie drawn on top of everything else
	 */
	void Control::BringToFront(Control* pControl)
	{
		if(!pControl)
			return;

		for(uint32 i = 0; i < mControls.size(); i++)
		{
			if(mControls[i]->GetID() == pControl->GetID())
			{
				mControls.erase(i);
				mControls.push_back(pControl);
				break;
			}
		}
	}

	/* Sends a control to the back, ie drawn behind everything else
	 */
	void Control::SendToBack(Control* pControl)
	{
		if(!pControl)
			return;

		for(uint32 i = 0; i < mControls.size(); i++)
		{
			if(mControls[i]->GetID() == pControl->GetID())
			{
				mControls.erase(i);
				mControls.push_front(pControl);
				break;
			}
		}
	}
	/* Points (touches/mouse/etc) were pressed down
	 */
	bool Control::OnPointsDown(const Point* points, sint32 numPoints)
	{
		assert(points!=0);
		assert(numPoints>=0);
		return false;
	}

	/* Points (touches/mouse/etc) were released
	 */
	bool Control::OnPointsUp(const Point* points, sint32 numPoints)
	{
		assert(points!=0);
		assert(numPoints>=0);
		return false;
	}

	/* Points (touches/mouse/etc) were moved.
	 */
	bool Control::OnPointsMove(const Point* points, sint32 numPoints)
	{
		assert(points!=0);
		assert(numPoints>=0);
		return false;
	}

	/**
	* Points (touches/mouse/etc) were released but the control was unreachable (other control in the way)
	* Returns a reference to the control that handled the points
	*/
	bool Control::OnPointsUpCancel(const Point* points, sint32 numPoints)
	{
		assert(points!=0);
		assert(numPoints>=0);
		return false;
	}

	/* Applies the interpolation of two keyframes to the control.
	 * pEndFrame can be NULL.
	 */
	void Control::ApplyKeyFrame(const KeyFrameData* pStartFrame, const KeyFrameData* pEndFrame, float factor)
	{
		if (pStartFrame == NULL && pEndFrame == NULL)
            return;

        Rectangle parentRect;
        if (mParent != NULL)
		{
			const Vector2& size = mParent->GetSize();
			parentRect.w = size.x;
			parentRect.h = size.y;
        }

		const ControlLayout* pStartLayout	= pStartFrame->GetLayout();
		const ControlLayout* pEndLayout		= pEndFrame ? pEndFrame->GetLayout() : NULL;

        float startLeft		= pStartLayout->mX - pStartLayout->mCenterX;
        float startRight	= startLeft + pStartLayout->mWidth;
        float startTop		= pStartLayout->mY - pStartLayout->mCenterY;
        float startBottom	= startTop + pStartLayout->mHeight;

        Rectangle startRect(startLeft, startTop, (startRight - startLeft), (startBottom - startTop));
		Point startCenter(pStartLayout->mCenterX, pStartLayout->mCenterY);

        float leftValue     = (mControlData->mAnchorFlags & LeftRelative) == 0 ? pStartFrame->mLeftAbs : pStartFrame->mLeftRel;
        float rightValue    = (mControlData->mAnchorFlags & RightRelative) == 0 ? pStartFrame->mRightAbs : pStartFrame->mRightRel;
        float topValue      = (mControlData->mAnchorFlags & TopRelative) == 0 ? pStartFrame->mTopAbs : pStartFrame->mTopRel;
        float bottomValue   = (mControlData->mAnchorFlags & BottomRelative) == 0 ? pStartFrame->mBottomAbs : pStartFrame->mBottomRel;

		Otter::ComputeAnchoredRectangle( startRect, startCenter, parentRect,
                                         (AnchorFlags)mControlData->mAnchorFlags,
                                         leftValue, rightValue, topValue, bottomValue);

        Rectangle endRect;
        Point endCenter;

        if(pEndFrame != NULL)
        {

            float endLeft = pEndLayout->mX - pEndLayout->mCenterX;
            float endRight = endLeft + pEndLayout->mWidth;
            float endTop = pEndLayout->mY - pEndLayout->mCenterY;
            float endBottom = endTop + pEndLayout->mHeight;

            endRect = Rectangle(endLeft, endTop, (endRight - endLeft), (endBottom - endTop));
			endCenter = Point(pEndLayout->mCenterX, pEndLayout->mCenterY);

            leftValue   = (mControlData->mAnchorFlags & LeftRelative) == 0 ? pEndFrame->mLeftAbs : pEndFrame->mLeftRel;
            rightValue  = (mControlData->mAnchorFlags & RightRelative) == 0 ? pEndFrame->mRightAbs : pEndFrame->mRightRel;
            topValue    = (mControlData->mAnchorFlags & TopRelative) == 0 ? pEndFrame->mTopAbs : pEndFrame->mTopRel;
            bottomValue = (mControlData->mAnchorFlags & BottomRelative) == 0 ? pEndFrame->mBottomAbs : pEndFrame->mBottomRel;

			Otter::ComputeAnchoredRectangle( endRect, endCenter, parentRect,
											 (AnchorFlags)mControlData->mAnchorFlags,
                                             leftValue, rightValue, topValue, bottomValue);
        }

        float newX = 0;
        float newY = 0;
        float newW = 0;
        float newH = 0;
        float newCX = 0;
        float newCY = 0;

        float newR = 0.0f;

        if (pEndFrame == NULL)
        {
            newCX = startCenter.x;
            newCY = startCenter.y;

            newX = startRect.x;
            newY = startRect.y;

            newW = startRect.w;
            newH = startRect.h;

            newR = pStartLayout->mRotation;
        }
        else
        {
            newCX = startCenter.x * (1.0f - factor) + endCenter.x * factor;
            newCY = startCenter.y * (1.0f - factor) + endCenter.y * factor;

            newX = startRect.x * (1.0f - factor) + endRect.x * factor;
            newY = startRect.y * (1.0f - factor) + endRect.y * factor;

            newW = (startRect.w) * (1.0f - factor) + (endRect.w) * factor;
            newH = (startRect.h) * (1.0f - factor) + (endRect.h) * factor;

            newR = pStartLayout->mRotation * (1.0f - factor) + pEndLayout->mRotation * factor;
        }

        SetCenter(Vector2(newCX, newCY));
		SetPosition(Vector2(newX + newCX, newY + newCY));
		SetSize(Vector2(newW, newH));
        SetRotation(newR);
	}

	/* Draws the control.
		*/
	void Control::Draw(Graphics* pGraphics)
	{
		if(!mEnabled)
			return;
		if( int const ncontrols=mControls.size() )
		{
			const VectorMath::Vector2& size = GetSize();
			if(size.x == 0.0f || size.y == 0.0f)
				return;
			pGraphics->PushMatrix(GetTransform());
			for(int i = 0; i !=ncontrols; i++)
			{
				Control* pControl = mControls[i];
				if( Mask* pMask = pControl->GetMaskControl() )
					pMask->DrawMask(pGraphics);
				pControl->Draw(pGraphics);
			}
			pGraphics->PopMatrix();
		}
	}

	/**
	 * Stores a pointer to this control's mask, and recurses on child controls
	 */
	void Control::SetMaskPointers()
	{
		SetMask(GetMask());

		for (uint32 i = 0; i < mControls.size(); ++i)
			mControls[i]->SetMaskPointers();
	}

}


text:
var fs = require('fs');
var zlib = require('zlib');

var archiver = require('archiver');

var out = fs.createWriteStream('out.tar.gz');
var gzipper = zlib.createGzip();
var archive = archiver.createTar();

archive.pipe(gzipper).pipe(out);

archive.addFile(fs.createReadStream('file1.js'), {name: 'file1.js'}, function() {
  archive.addFile(fs.createReadStream('file2.js'), {name: 'file2.js'}, function() {
    archive.finalize(function(written) {
      console.log(written + ' total bytes written'); // this wont be accurate since gzip happens after tar
    });
  });
});