text:
/**
 * This class is generated by jOOQ
 */
package org.ng200.openolympus.jooq.tables.records;

import java.time.LocalDate;

import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.jooq.Record1;
import org.jooq.impl.UpdatableRecordImpl;
import org.ng200.openolympus.jooq.tables.User;
import org.ng200.openolympus.jooq.tables.interfaces.IUser;

/**
 * This class is generated by jOOQ.
 */
@Generated(
	value = {
		"http://www.jooq.org",
		"jOOQ version:3.7.3"
	},
	comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
@Entity
@Table(name = "USER", schema = "public")
public class UserRecord extends UpdatableRecordImpl<UserRecord> implements IUser {

	private static final long serialVersionUID = 561572077;

	/**
	 * Setter for public.USER.id.
	 */
	@Override
	public UserRecord setId(Long value) {
		setValue(0, value);
		return this;
	}

	/**
	 * Getter for public.USER.id.
	 */
	@Id
	@Column(name = "id", unique = true, nullable = false, precision = 64)
	@Override
	public Long getId() {
		return (Long) getValue(0);
	}

	/**
	 * Setter for public.USER.username.
	 */
	@Override
	public UserRecord setUsername(String value) {
		setValue(1, value);
		return this;
	}

	/**
	 * Getter for public.USER.username.
	 */
	@Column(name = "username", unique = true, length = 255)
	@Override
	public String getUsername() {
		return (String) getValue(1);
	}

	/**
	 * Setter for public.USER.first_name_main.
	 */
	@Override
	public UserRecord setFirstNameMain(String value) {
		setValue(2, value);
		return this;
	}

	/**
	 * Getter for public.USER.first_name_main.
	 */
	@Column(name = "first_name_main", length = 255)
	@Override
	public String getFirstNameMain() {
		return (String) getValue(2);
	}

	/**
	 * Setter for public.USER.address_city.
	 */
	@Override
	public UserRecord setAddressCity(String value) {
		setValue(3, value);
		return this;
	}

	/**
	 * Getter for public.USER.address_city.
	 */
	@Column(name = "address_city", length = 255)
	@Override
	public String getAddressCity() {
		return (String) getValue(3);
	}

	/**
	 * Setter for public.USER.address_country.
	 */
	@Override
	public UserRecord setAddressCountry(String value) {
		setValue(4, value);
		return this;
	}

	/**
	 * Getter for public.USER.address_country.
	 */
	@Column(name = "address_country", length = 255)
	@Override
	public String getAddressCountry() {
		return (String) getValue(4);
	}

	/**
	 * Setter for public.USER.address_line1.
	 */
	@Override
	public UserRecord setAddressLine1(String value) {
		setValue(5, value);
		return this;
	}

	/**
	 * Getter for public.USER.address_line1.
	 */
	@Column(name = "address_line1")
	@Override
	public String getAddressLine1() {
		return (String) getValue(5);
	}

	/**
	 * Setter for public.USER.address_line2.
	 */
	@Override
	public UserRecord setAddressLine2(String value) {
		setValue(6, value);
		return this;
	}

	/**
	 * Getter for public.USER.address_line2.
	 */
	@Column(name = "address_line2")
	@Override
	public String getAddressLine2() {
		return (String) getValue(6);
	}

	/**
	 * Setter for public.USER.address_state.
	 */
	@Override
	public UserRecord setAddressState(String value) {
		setValue(7, value);
		return this;
	}

	/**
	 * Getter for public.USER.address_state.
	 */
	@Column(name = "address_state", length = 255)
	@Override
	public String getAddressState() {
		return (String) getValue(7);
	}

	/**
	 * Setter for public.USER.approval_email_sent.
	 */
	@Override
	public UserRecord setApprovalEmailSent(Boolean value) {
		setValue(8, value);
		return this;
	}

	/**
	 * Getter for public.USER.approval_email_sent.
	 */
	@Column(name = "approval_email_sent", nullable = false)
	@Override
	public Boolean getApprovalEmailSent() {
		return (Boolean) getValue(8);
	}

	/**
	 * Setter for public.USER.birth_date.
	 */
	@Override
	public UserRecord setBirthDate(LocalDate value) {
		setValue(9, value);
		return this;
	}

	/**
	 * Getter for public.USER.birth_date.
	 */
	@Column(name = "birth_date")
	@Override
	public LocalDate getBirthDate() {
		return (LocalDate) getValue(9);
	}

	/**
	 * Setter for public.USER.email_address.
	 */
	@Override
	public UserRecord setEmailAddress(String value) {
		setValue(10, value);
		return this;
	}

	/**
	 * Getter for public.USER.email_address.
	 */
	@Column(name = "email_address", length = 255)
	@Override
	public String getEmailAddress() {
		return (String) getValue(10);
	}

	/**
	 * Setter for public.USER.email_confirmation_token.
	 */
	@Override
	public UserRecord setEmailConfirmationToken(String value) {
		setValue(11, value);
		return this;
	}

	/**
	 * Getter for public.USER.email_confirmation_token.
	 */
	@Column(name = "email_confirmation_token", length = 255)
	@Override
	public String getEmailConfirmationToken() {
		return (String) getValue(11);
	}

	/**
	 * Setter for public.USER.enabled.
	 */
	@Override
	public UserRecord setEnabled(Boolean value) {
		setValue(12, value);
		return this;
	}

	/**
	 * Getter for public.USER.enabled.
	 */
	@Column(name = "enabled", nullable = false)
	@Override
	public Boolean getEnabled() {
		return (Boolean) getValue(12);
	}

	/**
	 * Setter for public.USER.first_name_localised.
	 */
	@Override
	public UserRecord setFirstNameLocalised(String value) {
		setValue(13, value);
		return this;
	}

	/**
	 * Getter for public.USER.first_name_localised.
	 */
	@Column(name = "first_name_localised", length = 255)
	@Override
	public String getFirstNameLocalised() {
		return (String) getValue(13);
	}

	/**
	 * Setter for public.USER.landline.
	 */
	@Override
	public UserRecord setLandline(String value) {
		setValue(14, value);
		return this;
	}

	/**
	 * Getter for public.USER.landline.
	 */
	@Column(name = "landline", length = 255)
	@Override
	public String getLandline() {
		return (String) getValue(14);
	}

	/**
	 * Setter for public.USER.last_name_localised.
	 */
	@Override
	public UserRecord setLastNameLocalised(String value) {
		setValue(15, value);
		return this;
	}

	/**
	 * Getter for public.USER.last_name_localised.
	 */
	@Column(name = "last_name_localised", length = 255)
	@Override
	public String getLastNameLocalised() {
		return (String) getValue(15);
	}

	/**
	 * Setter for public.USER.last_name_main.
	 */
	@Override
	public UserRecord setLastNameMain(String value) {
		setValue(16, value);
		return this;
	}

	/**
	 * Getter for public.USER.last_name_main.
	 */
	@Column(name = "last_name_main", length = 255)
	@Override
	public String getLastNameMain() {
		return (String) getValue(16);
	}

	/**
	 * Setter for public.USER.middle_name_localised.
	 */
	@Override
	public UserRecord setMiddleNameLocalised(String value) {
		setValue(17, value);
		return this;
	}

	/**
	 * Getter for public.USER.middle_name_localised.
	 */
	@Column(name = "middle_name_localised", length = 255)
	@Override
	public String getMiddleNameLocalised() {
		return (String) getValue(17);
	}

	/**
	 * Setter for public.USER.middle_name_main.
	 */
	@Override
	public UserRecord setMiddleNameMain(String value) {
		setValue(18, value);
		return this;
	}

	/**
	 * Getter for public.USER.middle_name_main.
	 */
	@Column(name = "middle_name_main", length = 255)
	@Override
	public String getMiddleNameMain() {
		return (String) getValue(18);
	}

	/**
	 * Setter for public.USER.mobile.
	 */
	@Override
	public UserRecord setMobile(String value) {
		setValue(19, value);
		return this;
	}

	/**
	 * Getter for public.USER.mobile.
	 */
	@Column(name = "mobile", length = 255)
	@Override
	public String getMobile() {
		return (String) getValue(19);
	}

	/**
	 * Setter for public.USER.password.
	 */
	@Override
	public UserRecord setPassword(String value) {
		setValue(20, value);
		return this;
	}

	/**
	 * Getter for public.USER.password.
	 */
	@Column(name = "password", length = 255)
	@Override
	public String getPassword() {
		return (String) getValue(20);
	}

	/**
	 * Setter for public.USER.school.
	 */
	@Override
	public UserRecord setSchool(String value) {
		setValue(21, value);
		return this;
	}

	/**
	 * Getter for public.USER.school.
	 */
	@Column(name = "school", length = 255)
	@Override
	public String getSchool() {
		return (String) getValue(21);
	}

	/**
	 * Setter for public.USER.teacher_first_name.
	 */
	@Override
	public UserRecord setTeacherFirstName(String value) {
		setValue(22, value);
		return this;
	}

	/**
	 * Getter for public.USER.teacher_first_name.
	 */
	@Column(name = "teacher_first_name", length = 255)
	@Override
	public String getTeacherFirstName() {
		return (String) getValue(22);
	}

	/**
	 * Setter for public.USER.teacher_last_name.
	 */
	@Override
	public UserRecord setTeacherLastName(String value) {
		setValue(23, value);
		return this;
	}

	/**
	 * Getter for public.USER.teacher_last_name.
	 */
	@Column(name = "teacher_last_name", length = 255)
	@Override
	public String getTeacherLastName() {
		return (String) getValue(23);
	}

	/**
	 * Setter for public.USER.teacher_middle_name.
	 */
	@Override
	public UserRecord setTeacherMiddleName(String value) {
		setValue(24, value);
		return this;
	}

	/**
	 * Getter for public.USER.teacher_middle_name.
	 */
	@Column(name = "teacher_middle_name", length = 255)
	@Override
	public String getTeacherMiddleName() {
		return (String) getValue(24);
	}

	/**
	 * Setter for public.USER.superuser.
	 */
	@Override
	public UserRecord setSuperuser(Boolean value) {
		setValue(25, value);
		return this;
	}

	/**
	 * Getter for public.USER.superuser.
	 */
	@Column(name = "superuser", nullable = false)
	@Override
	public Boolean getSuperuser() {
		return (Boolean) getValue(25);
	}

	/**
	 * Setter for public.USER.approved.
	 */
	@Override
	public UserRecord setApproved(Boolean value) {
		setValue(26, value);
		return this;
	}

	/**
	 * Getter for public.USER.approved.
	 */
	@Column(name = "approved", nullable = false)
	@Override
	public Boolean getApproved() {
		return (Boolean) getValue(26);
	}

	// -------------------------------------------------------------------------
	// Primary key information
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Record1<Long> key() {
		return (Record1) super.key();
	}

	// -------------------------------------------------------------------------
	// FROM and INTO
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void from(IUser from) {
		setId(from.getId());
		setUsername(from.getUsername());
		setFirstNameMain(from.getFirstNameMain());
		setAddressCity(from.getAddressCity());
		setAddressCountry(from.getAddressCountry());
		setAddressLine1(from.getAddressLine1());
		setAddressLine2(from.getAddressLine2());
		setAddressState(from.getAddressState());
		setApprovalEmailSent(from.getApprovalEmailSent());
		setBirthDate(from.getBirthDate());
		setEmailAddress(from.getEmailAddress());
		setEmailConfirmationToken(from.getEmailConfirmationToken());
		setEnabled(from.getEnabled());
		setFirstNameLocalised(from.getFirstNameLocalised());
		setLandline(from.getLandline());
		setLastNameLocalised(from.getLastNameLocalised());
		setLastNameMain(from.getLastNameMain());
		setMiddleNameLocalised(from.getMiddleNameLocalised());
		setMiddleNameMain(from.getMiddleNameMain());
		setMobile(from.getMobile());
		setPassword(from.getPassword());
		setSchool(from.getSchool());
		setTeacherFirstName(from.getTeacherFirstName());
		setTeacherLastName(from.getTeacherLastName());
		setTeacherMiddleName(from.getTeacherMiddleName());
		setSuperuser(from.getSuperuser());
		setApproved(from.getApproved());
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public <E extends IUser> E into(E into) {
		into.from(this);
		return into;
	}

	// -------------------------------------------------------------------------
	// Constructors
	// -------------------------------------------------------------------------

	/**
	 * Create a detached UserRecord
	 */
	public UserRecord() {
		super(User.USER);
	}

	/**
	 * Create a detached, initialised UserRecord
	 */
	public UserRecord(Long id, String username, String firstNameMain, String addressCity, String addressCountry, String addressLine1, String addressLine2, String addressState, Boolean approvalEmailSent, LocalDate birthDate, String emailAddress, String emailConfirmationToken, Boolean enabled, String firstNameLocalised, String landline, String lastNameLocalised, String lastNameMain, String middleNameLocalised, String middleNameMain, String mobile, String password, String school, String teacherFirstName, String teacherLastName, String teacherMiddleName, Boolean superuser, Boolean approved) {
		super(User.USER);

		setValue(0, id);
		setValue(1, username);
		setValue(2, firstNameMain);
		setValue(3, addressCity);
		setValue(4, addressCountry);
		setValue(5, addressLine1);
		setValue(6, addressLine2);
		setValue(7, addressState);
		setValue(8, approvalEmailSent);
		setValue(9, birthDate);
		setValue(10, emailAddress);
		setValue(11, emailConfirmationToken);
		setValue(12, enabled);
		setValue(13, firstNameLocalised);
		setValue(14, landline);
		setValue(15, lastNameLocalised);
		setValue(16, lastNameMain);
		setValue(17, middleNameLocalised);
		setValue(18, middleNameMain);
		setValue(19, mobile);
		setValue(20, password);
		setValue(21, school);
		setValue(22, teacherFirstName);
		setValue(23, teacherLastName);
		setValue(24, teacherMiddleName);
		setValue(25, superuser);
		setValue(26, approved);
	}
}


text:
@extends('layouts.app')

@section('content')

    <button class="btn btn-primary"
          role="button"
          data-toggle="collapse"
          href="#finpositionAddForm"
          aria-expanded="false"
          aria-controls="finpositionAddForm">
          Добавить финпозицию
    </button>

                     Укажите описание и код нового элемента

                    @include('common.errors')

                    <form action="{{ url('finposition') }}" method="post" class="form-horizontal">
                        {{ csrf_field() }}

                            описание:

                                <input type="text" name="finposition_desc" id="finposition_desc" class="form-control">

                            код:

                                <input type="text" name="finposition_cod" id="finposition_cod" class="form-control">

                                <button type="submit" class="btn btn-primary">Добавить</button>

                    </form>

  @if (count($finpositions) > 0)

                #
                Описание
                Код

              @foreach ($finpositions as $finposition)

                  {{ $finposition->id }}
                  {{ $finposition->finposition_desc }}
                  {{ $finposition->finposition_cod }}

                    <form action="{{url('finposition/' . $finposition->id)}}" method="post">
                      {{ csrf_field() }}
                      {{ method_field('delete') }}
                      <button type="submit" id="del-finposition-{{$finposition->id}}" class="btn btn-danger">
                        Удалить
                      </button>
                    </form>

                    <form action="{{url('finposition/' . $finposition->id . '/edit')}}" method="get">
                      {{ csrf_field() }}
                      <button type="submit" id="edit-finposition-{{$finposition->id}}" class="btn btn-primary">
                        Исправить
                      </button>
                    </form>

              @endforeach

  @endif

@endsection

redpajama_set_name: RedPajamaGithub


text:
package Model;

import java.util.Map;
import br.ufsc.inf.leobr.cliente.Jogada;

import java.util.HashMap;
import java.util.List;

public class Move implements Jogada {

	protected Card[] cardsOn1;
	protected Card[] cardsOn2;
	protected List<Battle> battles;
	protected int points1;
	protected int points2;

	// Convert hashmap to array
	private Card[] serializeMap(Map<Integer, Card> map) {
		Card[] array = new Card[5];
		for (int k = 0; k < 5; k++) {
			if (map.containsKey(k)) {
				array[k] = map.get(k);
			} else {
				array[k] = null;
			}
		}
		return array;
	}

	// Convert array to hashmap
	private Map<Integer, Card> deserializeMap(Card[] array) {
		Map<Integer, Card> map = new HashMap<Integer, Card>();
		for (int k = 0; k < 5; k++) {
			if (array[k] != null) {
				map.put(k, array[k]);
			}
		}
		return map;
	}

	public Map<Integer, Card> getCardsOn1() {
		return this.deserializeMap(this.cardsOn1);
	}

	public void setCardsOn1(Map<Integer, Card> cardsOn1) {
		this.cardsOn1 = this.serializeMap(cardsOn1);
	}

	public Map<Integer, Card> getCardsOn2() {
		return this.deserializeMap(this.cardsOn2);
	}

	public void setCardsOn2(Map<Integer, Card> cardsOn2) {
		this.cardsOn2 = this.serializeMap(cardsOn2);
	}

	public List<Battle> getBattles() {
		return this.battles;
	}

	public void setBattles(List<Battle> battles) {
		this.battles = battles;
	}

	public void setPoints(int[] points) {
		this.points1 = points[0];
		this.points2 = points[1];
	}

	public int[] getPoints() {
		int[] points = new int[2];
		points[0] = this.points1;
		points[1] = this.points2;
		return points;
	}

	public void invertData() {
		Card[] tempCards;
		int tempPoints;
		tempCards = this.cardsOn1;
		this.cardsOn1 = this.cardsOn2;
		this.cardsOn2 = tempCards;
		tempPoints = this.points1;
		this.points1 = this.points2;
		this.points2 = tempPoints;
	}

}


text:
package com.communote.server.core.note;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.communote.server.api.core.note.AutosavePropertyFilterProvider;
import com.communote.server.api.core.note.AutosavePropertyFilterProviderManager;
import com.communote.server.api.core.property.StringPropertyFilter;
import com.communote.server.api.core.property.StringPropertyTO;

/**
 * @author Communote GmbH - http://www.communote.com/
 */
@Service("autosavePropertyFilterProviderManager")
public class AutosavePropertyFilterProviderManagerImpl implements
AutosavePropertyFilterProviderManager {
    private List<AutosavePropertyFilterProvider> providers = new ArrayList<>();

    @Override
    public synchronized void addProvider(AutosavePropertyFilterProvider provider) {
        ArrayList<AutosavePropertyFilterProvider> newProviders = new ArrayList<>(providers);
        newProviders.add(provider);
        providers = newProviders;
    }

    @Override
    public Collection<StringPropertyFilter> getFiltersForComment(Long parentNoteId,
            Collection<StringPropertyTO> properties) {
        properties = normalizeProperties(properties);
        ArrayList<StringPropertyFilter> allFilters = new ArrayList<>();
        for (AutosavePropertyFilterProvider provider : providers) {
            Collection<StringPropertyFilter> filters = provider.getFiltersForComment(parentNoteId,
                    properties);
            if (filters != null) {
                allFilters.addAll(filters);
            }
        }
        return allFilters;
    }

    @Override
    public Collection<StringPropertyFilter> getFiltersForCreate(
            Collection<StringPropertyTO> properties) {
        properties = normalizeProperties(properties);
        ArrayList<StringPropertyFilter> allFilters = new ArrayList<>();
        for (AutosavePropertyFilterProvider provider : providers) {
            Collection<StringPropertyFilter> filters = provider.getFiltersForCreate(properties);
            if (filters != null) {
                allFilters.addAll(filters);
            }
        }
        return allFilters;
    }

    @Override
    public Collection<StringPropertyFilter> getFiltersForUpdate(Long noteId,
            Collection<StringPropertyTO> properties) {
        properties = normalizeProperties(properties);
        ArrayList<StringPropertyFilter> allFilters = new ArrayList<>();
        for (AutosavePropertyFilterProvider provider : providers) {
            Collection<StringPropertyFilter> filters = provider.getFiltersForUpdate(noteId,
                    properties);
            if (filters != null) {
                allFilters.addAll(filters);
            }
        }
        return allFilters;
    }

    @PostConstruct
    private void init() {
        providers.add(new RepostAutosavePropertyFilterProvider());
    }

    private Collection<StringPropertyTO> normalizeProperties(Collection<StringPropertyTO> properties) {
        if (properties == null) {
            return Collections.emptyList();
        }
        return properties;
    }

    @Override
    public synchronized void removeProvider(AutosavePropertyFilterProvider provider) {
        if (providers.contains(provider)) {
            ArrayList<AutosavePropertyFilterProvider> newProviders = new ArrayList<>(providers);
            newProviders.remove(provider);
            providers = newProviders;
        }
    }

}


text:
"""
Scrape weather from Weather Underground
"""

import sys
import os
import requests
import datetime
import time
import MySQLdb
import pprint

sys.path.append(os.path.abspath('{0}/../../'.format(os.path.abspath(__file__))))
from laptimes import config

def main():
    date_start = datetime.date(2012, 6, 30)
    date_end = datetime.date(2012, 12, 31)
    #date_end = datetime.date(2014, 9, 15)

    while date_start <= date_end:
        print 'Processing:', date_start
        sys.stdout.flush()
        year = date_start.year
        month = date_start.month
        day = date_start.day

        if month < 10:
            month = '0{0}'.format(month)
        if day < 10:
            day = '0{0}'.format(day)

        weather_date = (year, month, day)
        weather_json = get_weather('Caddo Mills, TX', weather_date)
        weather_dict = parse_weather(weather_json)
        save_weather(weather_dict)

        date_start += datetime.timedelta(days=1)
        print 'Sleeping for a minute.\n'
        sys.stdout.flush()
        time.sleep(7)

def get_weather(citystate, weather_date):
    city, state = parse_citystate(citystate)
    url = 'http://api.wunderground.com/api/{0}/history_{1}{2}{3}/q/{4}/{5}.json'.format(
            config.opts['wunderground']['apikey'],
            weather_date[0],
            weather_date[1],
            weather_date[2],
            state,
            city
    )

    r = requests.get(url)
    if r.status_code != 200:
        r.raise_for_status()

    return r.json()

def parse_citystate(citystate):
    citystate_split = citystate.split(',')
    city = citystate_split[0].replace(' ', '_')
    state = citystate_split[1].strip()

    return (city, state)

def parse_weather(weather_json):
    wdict = weather_json['history']['observations']

    weather_data = []
    dont_want = ['fog', 'hail', 'icon', 'metar', 'thunder', 'tornado', 'utcdate']
    for weather in wdict:
        wants_formatted = {}
        for key, value in weather.iteritems():
            if key in dont_want:
                continue
            if value in ['-9999.00', '-9999.0', '-9999', '-999']: value = None
            if key == 'date':
                value = '{0}-{1}-{2} {3}:{4}:00'.format(
                    value['year'],
                    value['mon'],
                    value['mday'],
                    value['hour'],
                    value['min']
                )
            wants_formatted[str(key)] = value
        weather_data.append(wants_formatted)

    return weather_data

def save_weather(weather_data):
    connection = MySQLdb.connect(config.opts['mysql']['host'], config.opts['mysql']['username'], config.opts['mysql']['password'], config.opts['mysql']['database'])
    cursor = connection.cursor()

    query = 'INSERT INTO weather(\
                dewpoint_c, dewpoint_f, heat_index_c, heat_index_f, observation_time,\
                precip_1hr_in, precip_1hr_metric, precip_today_in, pressure_in, pressure_mb,\
                relative_humidity, temp_c, temp_f, visibility_km, visibility_mi,\
                weather, wind_degrees, wind_dir, wind_kph, wind_mph,\
                windchill_c, windchill_f, wind_gust_kph, wind_gust_mph\
            )\
            VALUES(\
                %s, %s, %s, %s, %s,\
                %s, %s, %s, %s, %s,\
                %s, %s, %s, %s, %s,\
                %s, %s, %s, %s, %s,\
                %s, %s, %s, %s\
            )'

    for weather in weather_data:
        exists = cursor.execute('SELECT id FROM weather WHERE observation_time = %s', (weather['date'],))
        if exists:
            print 'Weather already recorded for this date and time:', weather['date']
            continue
        cursor.execute(query, (
            weather['dewptm'], weather['dewpti'], weather['heatindexm'], weather['heatindexi'], weather['date'],
            weather['precipi'], weather['precipm'], weather['rain'], weather['pressurei'], weather['pressurem'],
            weather['hum'], weather['tempm'], weather['tempi'], weather['vism'], weather['visi'],
            weather['conds'], weather['wdird'], weather['wdire'], weather['wspdm'], weather['wspdi'],
            weather['windchillm'], weather['windchilli'], weather['wgustm'], weather['wgusti']
        ))

    connection.commit()
    cursor.close()
    connection.close()

if __name__ == '__main__':
    sys.exit(main())


text:
var range = document.getElementById('range');

range.style.height = '400px';
range.style.margin = '0 auto 30px';

noUiSlider.create(range, {
	start: [ 1450, 2050, 2350, 3000 ], // 4 handles, starting at...
	margin: 300, // Handles must be at least 300 apart
	limit: 600, // ... but no more than 600
	connect: true, // Display a colored bar between the handles
	direction: 'rtl', // Put '0' at the bottom of the slider
	orientation: 'vertical', // Orient the slider vertically
	behaviour: 'tap-drag', // Move handle on tap, bar is draggable
	step: 150,
	tooltips: true,
	format: wNumb({
		decimals: 0
	}),
	range: {
		'min': 1300,
		'max': 3250
	},
	pips: { // Show a scale with the slider
		mode: 'steps',
		stepped: true,
		density: 4
	}
});


text:
VERSION  = ARGV.first
PACKAGES = %w(activesupport activerecord actionpack actionmailer activeresource)

# Checkout source
# `rm -rf release && svn export http://dev.rubyonrails.org/svn/rails/trunk release`

# Create Rails packages
`cd release/railties && rake template=jamis package`

# Upload documentation
`cd release/rails/doc/api && scp -r * davidhh@wrath.rubyonrails.com:public_html/api`

# Upload packages
(PACKAGES + %w(railties)).each do |p|
  `cd release/#{p} && echo "Releasing #{p}" && rake release`
end

# Upload rails tgz/zip
`rubyforge add_release rails rails 'REL #{VERSION}' release/rails-#{VERSION}.tgz`
`rubyforge add_release rails rails 'REL #{VERSION}' release/rails-#{VERSION}.zip`


text:
package org.axonframework.serialization.upcasting.event;

import org.axonframework.eventhandling.EventData;
import org.axonframework.eventhandling.GenericDomainEventMessage;
import org.axonframework.serialization.Converter;
import org.axonframework.serialization.Serializer;
import org.axonframework.serialization.TestSerializer;
import org.axonframework.utils.TestDomainEventEntry;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;

/**
 * Test for intermediate representation.
 *
 * @author Simon Zambrovski
 */
class IntermediateRepresentationTest {

    private final static Serializer serializer = TestSerializer.XSTREAM.getSerializer();

    @Test
    public void canConvertDataTo() {
        EventData<?> eventData = new TestDomainEventEntry(
            new GenericDomainEventMessage<>("test", "aggregateId", 0, "someString"), serializer
        );
        Serializer serializer = mock(Serializer.class);
        Converter converter = mock(Converter.class);
        when(serializer.getConverter()).thenReturn(converter);
        when(converter.canConvert(any(), eq(String.class))).thenReturn(true);

        IntermediateEventRepresentation input = new InitialEventRepresentation(eventData, serializer);
        EventUpcasterChain eventUpcasterChain = new EventUpcasterChain(
            new IntermediateRepresentationTest.MyEventUpcaster()
        );
        List<IntermediateEventRepresentation> result = eventUpcasterChain.upcast(Stream.of(input)).collect(toList());
        assertEquals(1, result.size());

        assertTrue(input.canConvertDataTo(String.class));
        assertTrue(result.get(0).canConvertDataTo(String.class));

        verify(converter).canConvert(String.class, String.class);
    }

    private static class MyEventUpcaster extends SingleEventUpcaster {

        @Override
        protected boolean canUpcast(IntermediateEventRepresentation intermediateRepresentation) {
            return true;
        }

        @Override
        protected IntermediateEventRepresentation doUpcast(IntermediateEventRepresentation intermediateRepresentation) {
            return new UpcastedEventRepresentation<>(
                intermediateRepresentation.getType(),
                intermediateRepresentation,
                Function.identity(),
                Function.identity(),
                Object.class,
                serializer.getConverter()
            );
        }
    }
}


text:
import messRoute from './mess.routes'

export { messRoute }


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

// This filter reads GRPC_ARG_SERVICE_CONFIG and populates ServiceConfigCallData
// in the call context per call for direct channels.

#include <grpc/support/port_platform.h>

#include <new>
#include <string>
#include <utility>

#include "absl/types/optional.h"

#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/log.h>

#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channel_stack_builder.h"
#include "src/core/lib/channel/context.h"
#include "src/core/lib/config/core_configuration.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/service_config/service_config.h"
#include "src/core/lib/service_config/service_config_call_data.h"
#include "src/core/lib/service_config/service_config_impl.h"
#include "src/core/lib/service_config/service_config_parser.h"
#include "src/core/lib/surface/channel_init.h"
#include "src/core/lib/surface/channel_stack_type.h"

namespace grpc_core {

namespace {

class ServiceConfigChannelArgChannelData {
 public:
  explicit ServiceConfigChannelArgChannelData(
      const grpc_channel_element_args* args) {
    const char* service_config_str = grpc_channel_args_find_string(
        args->channel_args, GRPC_ARG_SERVICE_CONFIG);
    if (service_config_str != nullptr) {
      grpc_error_handle service_config_error = GRPC_ERROR_NONE;
      auto service_config = ServiceConfigImpl::Create(
          args->channel_args, service_config_str, &service_config_error);
      if (service_config_error == GRPC_ERROR_NONE) {
        service_config_ = std::move(service_config);
      } else {
        gpr_log(GPR_ERROR, "%s",
                grpc_error_std_string(service_config_error).c_str());
      }
      GRPC_ERROR_UNREF(service_config_error);
    }
  }

  RefCountedPtr<ServiceConfig> service_config() const {
    return service_config_;
  }

 private:
  RefCountedPtr<ServiceConfig> service_config_;
};

class ServiceConfigChannelArgCallData {
 public:
  ServiceConfigChannelArgCallData(
      RefCountedPtr<ServiceConfig> service_config,
      const ServiceConfigParser::ParsedConfigVector* method_config,
      const grpc_call_element_args* args)
      : call_context_(args->context),
        service_config_call_data_(std::move(service_config), method_config,
                                  /*call_attributes=*/{}) {
    GPR_DEBUG_ASSERT(args->context != nullptr);
    // No need to set the destroy function, since it will be cleaned up
    // when this filter is destroyed in the filter stack.
    args->context[GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA].value =
        &service_config_call_data_;
  }

  ~ServiceConfigChannelArgCallData() {
    // Remove the entry from call context, just in case anyone above us
    // tries to look at it during call stack destruction.
    call_context_[GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA].value = nullptr;
  }

 private:
  grpc_call_context_element* call_context_;
  ServiceConfigCallData service_config_call_data_;
};

grpc_error_handle ServiceConfigChannelArgInitCallElem(
    grpc_call_element* elem, const grpc_call_element_args* args) {
  auto* chand =
      static_cast<ServiceConfigChannelArgChannelData*>(elem->channel_data);
  auto* calld = static_cast<ServiceConfigChannelArgCallData*>(elem->call_data);
  RefCountedPtr<ServiceConfig> service_config = chand->service_config();
  const ServiceConfigParser::ParsedConfigVector* method_config = nullptr;
  if (service_config != nullptr) {
    method_config = service_config->GetMethodParsedConfigVector(args->path);
  }
  new (calld) ServiceConfigChannelArgCallData(std::move(service_config),
                                              method_config, args);
  return GRPC_ERROR_NONE;
}

void ServiceConfigChannelArgDestroyCallElem(
    grpc_call_element* elem, const grpc_call_final_info* /* final_info */,
    grpc_closure* /* then_schedule_closure */) {
  ServiceConfigChannelArgCallData* calld =
      static_cast<ServiceConfigChannelArgCallData*>(elem->call_data);
  calld->~ServiceConfigChannelArgCallData();
}

grpc_error_handle ServiceConfigChannelArgInitChannelElem(
    grpc_channel_element* elem, grpc_channel_element_args* args) {
  ServiceConfigChannelArgChannelData* chand =
      static_cast<ServiceConfigChannelArgChannelData*>(elem->channel_data);
  new (chand) ServiceConfigChannelArgChannelData(args);
  return GRPC_ERROR_NONE;
}

void ServiceConfigChannelArgDestroyChannelElem(grpc_channel_element* elem) {
  ServiceConfigChannelArgChannelData* chand =
      static_cast<ServiceConfigChannelArgChannelData*>(elem->channel_data);
  chand->~ServiceConfigChannelArgChannelData();
}

const grpc_channel_filter ServiceConfigChannelArgFilter = {
    grpc_call_next_op,
    nullptr,
    grpc_channel_next_op,
    sizeof(ServiceConfigChannelArgCallData),
    ServiceConfigChannelArgInitCallElem,
    grpc_call_stack_ignore_set_pollset_or_pollset_set,
    ServiceConfigChannelArgDestroyCallElem,
    sizeof(ServiceConfigChannelArgChannelData),
    ServiceConfigChannelArgInitChannelElem,
    grpc_channel_stack_no_post_init,
    ServiceConfigChannelArgDestroyChannelElem,
    grpc_channel_next_get_info,
    "service_config_channel_arg"};

}  // namespace

void RegisterServiceConfigChannelArgFilter(
    CoreConfiguration::Builder* builder) {
  builder->channel_init()->RegisterStage(
      GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
      [](ChannelStackBuilder* builder) {
        auto channel_args = builder->channel_args();
        if (channel_args.WantMinimalStack() ||
            !channel_args.GetString(GRPC_ARG_SERVICE_CONFIG).has_value()) {
          return true;
        }
        builder->PrependFilter(&ServiceConfigChannelArgFilter);
        return true;
      });
}

}  // namespace grpc_core


text:
<?php

final class PhabricatorChatLogChannel
  extends PhabricatorChatLogDAO
  implements PhabricatorPolicyInterface {

  protected $serviceName;
  protected $serviceType;
  protected $channelName;
  protected $viewPolicy;
  protected $editPolicy;

  public function getCapabilities() {
    return array(
      PhabricatorPolicyCapability::CAN_VIEW,
      PhabricatorPolicyCapability::CAN_EDIT,
    );
  }

  public function getPolicy($capability) {
    switch ($capability) {
      case PhabricatorPolicyCapability::CAN_VIEW:
        return $this->viewPolicy;
        break;
      case PhabricatorPolicyCapability::CAN_EDIT:
        return $this->editPolicy;
        break;
    }
  }

  public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
    return false;
  }

}


text:
@implementation UIControl (DZControl)

static char OperationKey;

- (void)dzRemoveHandlerForEvent:(UIControlEvents)event
{

    NSString *methodName = [UIControl eventName:event];

    NSMutableDictionary *opreations = (NSMutableDictionary*)objc_getAssociatedObject(self, &OperationKey);

    if(opreations == nil)
    {
        opreations = [[NSMutableDictionary alloc] init];

        objc_setAssociatedObject(self, &OperationKey, opreations, OBJC_ASSOCIATION_RETAIN);
    }
    [opreations removeObjectForKey:methodName];

    [self removeTarget:self action:NSSelectorFromString(methodName) forControlEvents:event];
}

- (void)dzHandleControlEvent:(UIControlEvents)event withBlock:(void(^)(id sender))block {

    NSString *methodName = [UIControl eventName:event];

    //获取关联对象
    NSMutableDictionary *opreations = (NSMutableDictionary*)objc_getAssociatedObject(self, &OperationKey);

    if(opreations == nil)
    {
        opreations = [[NSMutableDictionary alloc] init];

        //创建关联对象
        objc_setAssociatedObject(self, &OperationKey, opreations, OBJC_ASSOCIATION_RETAIN);
    }
    [opreations setObject:block forKey:methodName];

    //动态加载实例方法
    [self addTarget:self action:NSSelectorFromString(methodName) forControlEvents:event];

}

- (void)callActionBlock:(UIControlEvents)event {

    NSMutableDictionary *opreations = (NSMutableDictionary*)objc_getAssociatedObject(self, &OperationKey);

    if(opreations == nil) return;

    void(^block)(id sender) = [opreations objectForKey:[UIControl eventName:event]];

    if (block) block(self);

}

-(void)UIControlEventTouchDown{[self callActionBlock:UIControlEventTouchDown];}
-(void)UIControlEventTouchDownRepeat{[self callActionBlock:UIControlEventTouchDownRepeat];}
-(void)UIControlEventTouchDragInside{[self callActionBlock:UIControlEventTouchDragInside];}
-(void)UIControlEventTouchDragOutside{[self callActionBlock:UIControlEventTouchDragOutside];}
-(void)UIControlEventTouchDragEnter{[self callActionBlock:UIControlEventTouchDragEnter];}
-(void)UIControlEventTouchDragExit{[self callActionBlock:UIControlEventTouchDragExit];}
-(void)UIControlEventTouchUpInside{[self callActionBlock:UIControlEventTouchUpInside];}
-(void)UIControlEventTouchUpOutside{[self callActionBlock:UIControlEventTouchUpOutside];}
-(void)UIControlEventTouchCancel{[self callActionBlock:UIControlEventTouchCancel];}
-(void)UIControlEventValueChanged{[self callActionBlock:UIControlEventValueChanged];}
-(void)UIControlEventEditingDidBegin{[self callActionBlock:UIControlEventEditingDidBegin];}
-(void)UIControlEventEditingChanged{[self callActionBlock:UIControlEventEditingChanged];}
-(void)UIControlEventEditingDidEnd{[self callActionBlock:UIControlEventEditingDidEnd];}
-(void)UIControlEventEditingDidEndOnExit{[self callActionBlock:UIControlEventEditingDidEndOnExit];}
-(void)UIControlEventAllTouchEvents{[self callActionBlock:UIControlEventAllTouchEvents];}
-(void)UIControlEventAllEditingEvents{[self callActionBlock:UIControlEventAllEditingEvents];}
-(void)UIControlEventApplicationReserved{[self callActionBlock:UIControlEventApplicationReserved];}
-(void)UIControlEventSystemReserved{[self callActionBlock:UIControlEventSystemReserved];}
-(void)UIControlEventAllEvents{[self callActionBlock:UIControlEventAllEvents];}

+(NSString *)eventName:(UIControlEvents)event
{
    switch (event) {
        case UIControlEventTouchDown:          return @"UIControlEventTouchDown";
        case UIControlEventTouchDownRepeat:    return @"UIControlEventTouchDownRepeat";
        case UIControlEventTouchDragInside:    return @"UIControlEventTouchDragInside";
        case UIControlEventTouchDragOutside:   return @"UIControlEventTouchDragOutside";
        case UIControlEventTouchDragEnter:     return @"UIControlEventTouchDragEnter";
        case UIControlEventTouchDragExit:      return @"UIControlEventTouchDragExit";
        case UIControlEventTouchUpInside:      return @"UIControlEventTouchUpInside";
        case UIControlEventTouchUpOutside:     return @"UIControlEventTouchUpOutside";
        case UIControlEventTouchCancel:        return @"UIControlEventTouchCancel";
        case UIControlEventValueChanged:       return @"UIControlEventValueChanged";
        case UIControlEventEditingDidBegin:    return @"UIControlEventEditingDidBegin";
        case UIControlEventEditingChanged:     return @"UIControlEventEditingChanged";
        case UIControlEventEditingDidEnd:      return @"UIControlEventEditingDidEnd";
        case UIControlEventEditingDidEndOnExit:return @"UIControlEventEditingDidEndOnExit";
        case UIControlEventAllTouchEvents:     return @"UIControlEventAllTouchEvents";
        case UIControlEventAllEditingEvents:   return @"UIControlEventAllEditingEvents";
        case UIControlEventApplicationReserved:return @"UIControlEventApplicationReserved";
        case UIControlEventSystemReserved:     return @"UIControlEventSystemReserved";
        case UIControlEventAllEvents:          return @"UIControlEventAllEvents";
        default:
            return @"description";
    }
    return @"description";
}

+(UIControlEvents)eventWithName:(NSString *)name
{
    if([name isEqualToString:@"UIControlEventTouchDown"])           return UIControlEventTouchDown;
    if([name isEqualToString:@"UIControlEventTouchDownRepeat"])     return UIControlEventTouchDownRepeat;
    if([name isEqualToString:@"UIControlEventTouchDragInside"])     return UIControlEventTouchDragInside;
    if([name isEqualToString:@"UIControlEventTouchDragOutside"])    return UIControlEventTouchDragOutside;
    if([name isEqualToString:@"UIControlEventTouchDragEnter"])      return UIControlEventTouchDragEnter;
    if([name isEqualToString:@"UIControlEventTouchDragExit"])       return UIControlEventTouchDragExit;
    if([name isEqualToString:@"UIControlEventTouchUpInside"])       return UIControlEventTouchUpInside;
    if([name isEqualToString:@"UIControlEventTouchUpOutside"])      return UIControlEventTouchUpOutside;
    if([name isEqualToString:@"UIControlEventTouchCancel"])         return UIControlEventTouchCancel;
    if([name isEqualToString:@"UIControlEventTouchDown"])           return UIControlEventTouchDown;
    if([name isEqualToString:@"UIControlEventValueChanged"])        return UIControlEventValueChanged;
    if([name isEqualToString:@"UIControlEventEditingDidBegin"])     return UIControlEventEditingDidBegin;
    if([name isEqualToString:@"UIControlEventEditingChanged"])      return UIControlEventEditingChanged;
    if([name isEqualToString:@"UIControlEventEditingDidEnd"])       return UIControlEventEditingDidEnd;
    if([name isEqualToString:@"UIControlEventEditingDidEndOnExit"]) return UIControlEventEditingDidEndOnExit;
    if([name isEqualToString:@"UIControlEventAllTouchEvents"])      return UIControlEventAllTouchEvents;
    if([name isEqualToString:@"UIControlEventAllEditingEvents"])    return UIControlEventAllEditingEvents;
    if([name isEqualToString:@"UIControlEventApplicationReserved"]) return UIControlEventApplicationReserved;
    if([name isEqualToString:@"UIControlEventSystemReserved"])      return UIControlEventSystemReserved;
    if([name isEqualToString:@"UIControlEventAllEvents"])           return UIControlEventAllEvents;
    return UIControlEventAllEvents;
}

@end


text:
package uuid

/****************
 * Date: 16/02/14
 * Time: 11:29 AM
 ***************/

import (
	"fmt"
	"net/url"
	"testing"
)

var (
	goLang Name = "https://google.com/golang.org?q=golang"
)

const (
	generate = 1000000
)

func TestUUID_NewV1(t *testing.T) {
	u := NewV1()
	if u.Version() != 1 {
		t.Errorf("Expected correct version %d, but got %d", 1, u.Version())
	}
	if u.Variant() != ReservedRFC4122 {
		t.Errorf("Expected RFC4122 variant %x, but got %x", ReservedRFC4122, u.Variant())
	}
	if !parseUUIDRegex.MatchString(u.String()) {
		t.Errorf("Expected string representation to be valid, given: %s", u.String())
	}
}

func TestUUID_NewV1Bulk(t *testing.T) {
	for i := 0; i < generate; i++ {
		NewV1()
	}
}

// Tests NewV3
func TestUUID_NewV3(t *testing.T) {
	u := NewV3(NamespaceURL, goLang)
	if u.Version() != 3 {
		t.Errorf("Expected correct version %d, but got %d", 3, u.Version())
	}
	if u.Variant() != ReservedRFC4122 {
		t.Errorf("Expected RFC4122 variant %x, but got %x", ReservedRFC4122, u.Variant())
	}
	if !parseUUIDRegex.MatchString(u.String()) {
		t.Errorf("Expected string representation to be valid, given: %s", u.String())
	}
	ur, _ := url.Parse(string(goLang))

	// Same NS same name MUST be equal
	u2 := NewV3(NamespaceURL, ur)
	if !Equal(u2, u) {
		t.Errorf("Expected UUIDs generated with same namespace and name to equal but got: %s and %s", u2, u)
	}

	// Different NS same name MUST NOT be equal
	u3 := NewV3(NamespaceDNS, ur)
	if Equal(u3, u) {
		t.Errorf("Expected UUIDs generated with different namespace and same name to be different but got: %s and %s", u3, u)
	}

	// Same NS different name MUST NOT be equal
	u4 := NewV3(NamespaceURL, u)
	if Equal(u4, u) {
		t.Errorf("Expected UUIDs generated with the same namespace and different names to be different but got: %s and %s", u4, u)
	}

	ids := []UUID{
		u, u2, u3, u4,
	}
	for j, id := range ids {
		i := NewV3(NamespaceURL, NewName(string(j), id))
		if Equal(id, i) {
			t.Errorf("Expected UUIDs generated with the same namespace and different names to be different but got: %s and %s", id, i)
		}
	}
}

func TestUUID_NewV3Bulk(t *testing.T) {
	for i := 0; i < generate; i++ {
		NewV3(NamespaceDNS, goLang)
	}
}

func TestUUID_NewV4(t *testing.T) {
	u := NewV4()
	if u.Version() != 4 {
		t.Errorf("Expected correct version %d, but got %d", 4, u.Version())
	}
	if u.Variant() != ReservedRFC4122 {
		t.Errorf("Expected RFC4122 variant %x, but got %x", ReservedRFC4122, u.Variant())
	}
	if !parseUUIDRegex.MatchString(u.String()) {
		t.Errorf("Expected string representation to be valid, given: %s", u.String())
	}
}

func TestUUID_NewV4Bulk(t *testing.T) {
	for i := 0; i < generate; i++ {
		NewV4()
	}
}

// Tests NewV5
func TestUUID_NewV5(t *testing.T) {
	u := NewV5(NamespaceURL, goLang)
	if u.Version() != 5 {
		t.Errorf("Expected correct version %d, but got %d", 5, u.Version())
	}
	if u.Variant() != ReservedRFC4122 {
		t.Errorf("Expected RFC4122 variant %x, but got %x", ReservedRFC4122, u.Variant())
	}
	if !parseUUIDRegex.MatchString(u.String()) {
		t.Errorf("Expected string representation to be valid, given: %s", u.String())
	}
	ur, _ := url.Parse(string(goLang))

	// Same NS same name MUST be equal
	u2 := NewV5(NamespaceURL, ur)
	if !Equal(u2, u) {
		t.Errorf("Expected UUIDs generated with same namespace and name to equal but got: %s and %s", u2, u)
	}

	// Different NS same name MUST NOT be equal
	u3 := NewV5(NamespaceDNS, ur)
	if Equal(u3, u) {
		t.Errorf("Expected UUIDs generated with different namespace and same name to be different but got: %s and %s", u3, u)
	}

	// Same NS different name MUST NOT be equal
	u4 := NewV5(NamespaceURL, u)
	if Equal(u4, u) {
		t.Errorf("Expected UUIDs generated with the same namespace and different names to be different but got: %s and %s", u4, u)
	}

	ids := []UUID{
		u, u2, u3, u4,
	}
	for j, id := range ids {
		i := NewV5(NamespaceURL, NewName(string(j), id))
		if Equal(id, i) {
			t.Errorf("Expected UUIDs generated with the same namespace and different names to be different but got: %s and %s", id, i)
		}
	}
}

func TestUUID_NewV5Bulk(t *testing.T) {
	for i := 0; i < generate; i++ {
		NewV5(NamespaceDNS, goLang)
	}
}

// A small test to test uniqueness across all UUIDs created
func TestUUID_EachIsUnique(t *testing.T) {
	s := 1000
	ids := make([]UUID, s)
	for i := 0; i < s; i++ {
		u := NewV1()
		ids[i] = u
		for j := 0; j < i; j++ {
			if Equal(ids[j], u) {
				t.Error("Should not create the same V1 UUID", u, ids[j])
			}
		}
	}
	ids = make([]UUID, s)
	for i := 0; i < s; i++ {
		u := NewV3(NamespaceDNS, NewName(string(i), Name(goLang)))
		ids[i] = u
		for j := 0; j < i; j++ {
			if Equal(ids[j], u) {
				t.Error("Should not create the same V3 UUID", u, ids[j])
			}
		}
	}
	ids = make([]UUID, s)
	for i := 0; i < s; i++ {
		u := NewV4()
		ids[i] = u
		for j := 0; j < i; j++ {
			if Equal(ids[j], u) {
				t.Error("Should not create the same V4 UUID", u, ids[j])
			}
		}
	}
	ids = make([]UUID, s)
	for i := 0; i < s; i++ {
		u := NewV5(NamespaceDNS, NewName(string(i), Name(goLang)))
		ids[i] = u
		for j := 0; j < i; j++ {
			if Equal(ids[j], u) {
				t.Error("Should not create the same V5 UUID", u, ids[j])
			}
		}
	}
}

// Not really a test but used for visual verification of the defaults
func UUID_NamespaceDefaults() {
	fmt.Println(NamespaceDNS)
	fmt.Println(NamespaceURL)
	fmt.Println(NamespaceOID)
	fmt.Println(NamespaceX500)
}


text:
var LineStyleCanvas = require('../LineStyleCanvas');
var SetTransform = require('../../../renderer/canvas/utils/SetTransform');

/**
 * Renders this Game Object with the Canvas Renderer to the given Camera.
 * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera.
 * This method should not be called directly. It is a utility function of the Render module.
 *
 * @method Phaser.GameObjects.Line#renderCanvas
 * @since 3.13.0
 * @private
 *
 * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer.
 * @param {Phaser.GameObjects.Line} src - The Game Object being rendered in this call.
 * @param {number} interpolationPercentage - Reserved for future use and custom pipelines.
 * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object.
 * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested
 */
var LineCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix)
{
    var ctx = renderer.currentContext;

    if (SetTransform(renderer, ctx, src, camera, parentMatrix))
    {
        var dx = src._displayOriginX;
        var dy = src._displayOriginY;

        if (src.isStroked)
        {
            LineStyleCanvas(ctx, src);

            ctx.beginPath();

            ctx.moveTo(src.geom.x1 - dx, src.geom.y1 - dy);
            ctx.lineTo(src.geom.x2 - dx, src.geom.y2 - dy);

            ctx.stroke();
        }

        //  Restore the context saved in SetTransform
        ctx.restore();
    }
};

module.exports = LineCanvasRenderer;


text:
<?xml version="1.0" encoding="UTF-8"?>
<results id="7144713" name="" total_number_of_results="1" number_of_results_returned="1" start="0" error_message="" version="1.6 rev 1152">
  <result>
    <id>7144713</id>
    <name>Boechera holboellii</name>
    <rank>Species</rank>
    <name_status>accepted name</name_status>
    <sn_id>0</sn_id>
    <genus>Boechera</genus>
    <species>holboellii</species>
    <infraspecies_marker></infraspecies_marker>
    <infraspecies></infraspecies>
    <author><![CDATA[(Hornem.) A. Löve & D. Löve]]></author>
    <record_scrutiny_date>
      <scrutiny>2009</scrutiny>
    </record_scrutiny_date>
    <online_resource></online_resource>
    <source_database>Brassicaceae species checklist and database</source_database>
    <source_database_url>http://www.cbif.gc.ca/pls/spec/brassicaceae</source_database_url>
    <name_html><![CDATA[Boechera holboellii (Hornem.) A. Löve & D. Löve]]></name_html>
    <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7144713</url>
    <distribution></distribution>
    <references/>
    <classification>
      <taxon>
        <id>2339694</id>
        <name>Plantae</name>
        <rank>Kingdom</rank>
        <name_html>Plantae</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/browse/tree/id/2339694</url>
      </taxon>
      <taxon>
        <id>2339695</id>
        <name>Magnoliophyta</name>
        <rank>Phylum</rank>
        <name_html>Magnoliophyta</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/browse/tree/id/2339695</url>
      </taxon>
      <taxon>
        <id>2339696</id>
        <name>Magnoliopsida</name>
        <rank>Class</rank>
        <name_html>Magnoliopsida</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/browse/tree/id/2339696</url>
      </taxon>
      <taxon>
        <id>2347614</id>
        <name>Capparales</name>
        <rank>Order</rank>
        <name_html>Capparales</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/browse/tree/id/2347614</url>
      </taxon>
      <taxon>
        <id>2347615</id>
        <name>Brassicaceae</name>
        <rank>Family</rank>
        <name_html>Brassicaceae</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/browse/tree/id/2347615</url>
      </taxon>
      <taxon>
        <id>2502077</id>
        <name>Boechera</name>
        <rank>Genus</rank>
        <name_html>Boechera</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/browse/tree/id/2502077</url>
      </taxon>
    </classification>
    <child_taxa/>
    <synonyms>
      <synonym>
        <id>7146704</id>
        <name>Arabis caduca</name>
        <rank>Species</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Arabis</genus>
        <species>caduca</species>
        <infraspecies_marker></infraspecies_marker>
        <infraspecies></infraspecies>
        <author>A. Nelson</author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html>Arabis caduca A. Nelson</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7146704/synonym/7146704</url>
        <references/>
      </synonym>
      <synonym>
        <id>7146854</id>
        <name>Arabis holboellii</name>
        <rank>Species</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Arabis</genus>
        <species>holboellii</species>
        <infraspecies_marker></infraspecies_marker>
        <infraspecies></infraspecies>
        <author>Hornem.</author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html>Arabis holboellii Hornem.</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7146854/synonym/7146854</url>
        <references/>
      </synonym>
      <synonym>
        <id>7146859</id>
        <name>Arabis holboellii holboellii</name>
        <rank>Infraspecies</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Arabis</genus>
        <species>holboellii</species>
        <infraspecies_marker>var.</infraspecies_marker>
        <infraspecies>holboellii</infraspecies>
        <author>Hornem.</author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html>Arabis holboellii holboellii Hornem.</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7146859/synonym/7146859</url>
        <references/>
      </synonym>
      <synonym>
        <id>7146864</id>
        <name>Arabis holboellii tenuis</name>
        <rank>Infraspecies</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Arabis</genus>
        <species>holboellii</species>
        <infraspecies_marker>var.</infraspecies_marker>
        <infraspecies>tenuis</infraspecies>
        <author>(Greene) Böcher</author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html>Arabis holboellii tenuis (Greene) Böcher</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7146864/synonym/7146864</url>
        <references/>
      </synonym>
      <synonym>
        <id>7147071</id>
        <name>Arabis rhodantha</name>
        <rank>Species</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Arabis</genus>
        <species>rhodantha</species>
        <infraspecies_marker></infraspecies_marker>
        <infraspecies></infraspecies>
        <author>Greene</author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html>Arabis rhodantha Greene</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7147071/synonym/7147071</url>
        <references/>
      </synonym>
      <synonym>
        <id>7147504</id>
        <name>Boechera tenuis</name>
        <rank>Species</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Boechera</genus>
        <species>tenuis</species>
        <infraspecies_marker></infraspecies_marker>
        <infraspecies></infraspecies>
        <author><![CDATA[(Böcher) A. Löve & D. Löve]]></author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html><![CDATA[Boechera tenuis (Böcher) A. Löve & D. Löve]]></name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7147504/synonym/7147504</url>
        <references/>
      </synonym>
      <synonym>
        <id>7150388</id>
        <name>Erysimum holboellii</name>
        <rank>Species</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Erysimum</genus>
        <species>holboellii</species>
        <infraspecies_marker></infraspecies_marker>
        <infraspecies></infraspecies>
        <author>(Hornem.) Kuntze</author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html>Erysimum holboellii (Hornem.) Kuntze</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7150388/synonym/7150388</url>
        <references/>
      </synonym>
      <synonym>
        <id>7154486</id>
        <name>Streptanthus virgatus</name>
        <rank>Species</rank>
        <name_status>synonym</name_status>
        <sn_id>7144713</sn_id>
        <genus>Streptanthus</genus>
        <species>virgatus</species>
        <infraspecies_marker></infraspecies_marker>
        <infraspecies></infraspecies>
        <author>Nutt.</author>
        <record_scrutiny_date></record_scrutiny_date>
        <online_resource></online_resource>
        <name_html>Streptanthus virgatus Nutt.</name_html>
        <url>http://www.catalogueoflife.org/annual-checklist/details/species/id/7154486/synonym/7154486</url>
        <references/>
      </synonym>
    </synonyms>
    <common_names/>
  </result>
</results>


text:
from oslo.config import cfg

cfg.CONF.use_stderr = False


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="CoreLABSBundle\Entity\CoreAccessRequest" table="core_access_request">
    <indexes>
      <index name="cu_pr_user_id_idx" columns="user_id"/>
      <index name="cu_pr_service_id_idx" columns="service_id"/>
    </indexes>
    <id name="id" type="integer" column="id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="dateRequested" type="datetime" column="date_requested" nullable="false"/>
    <field name="status" type="integer" column="status" nullable="false"/>
    <many-to-one field="user" target-entity="CoreUsers">
      <join-columns>
        <join-column name="user_id" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="service" target-entity="CoreServices">
      <join-columns>
        <join-column name="service_id" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
/****************************
*MFiles对象的操作:增、查、改、删(CRUD)
****************************/
var MF = MF || {};
(function (v) {
    var o = {
        ///<summery>获取临时搜索视图</summery>
        getTempSearchView: function (vault, searchText, typeId, objId, oSearchConditions) {
            var viewName = "临时视图" + " - " + typeId + "-" + objId + "-" + new Date().toString();
            var oViewNew = MFiles.CreateInstance('View');
            oViewNew.Name = viewName;

            var oSCriteria = MFiles.CreateInstance('SearchCriteria');
            if (searchText) {
                oSCriteria.FullTextSearchString = searchText;
                oSCriteria.FullTextSearchFlags = (MFFullTextSearchFlagsStemming
                    | MFFullTextSearchFlagsLookInMetaData
                    | MFFullTextSearchFlagsLookInFileData
                    | MFFullTextSearchFlagsTypeAnyWords);
            }
            oSCriteria.SearchFlags = MFSearchFlagNone;
            oSCriteria.ExpandUI = false;
            if (typeId && typeId >= 0) {
                var scObjType = MFiles.CreateInstance("SearchCondition");
                scObjType.ConditionType = MFConditionTypeEqual;
                scObjType.Expression.DataStatusValueType = MFStatusTypeObjectTypeID;
                scObjType.TypedValue.SetValue(MFDatatypeLookup, typeId);
                var oObjTypeEx = MFiles.CreateInstance('SearchConditionEx');
                oObjTypeEx.Enabled = true;
                oObjTypeEx.Ignored = false;
                oObjTypeEx.SpecialNULL = false;
                oObjTypeEx.SearchCondition = scObjType;
                oSCriteria.ObjectTypeCondition = oObjTypeEx;
            }

            var oExpression = MFiles.CreateInstance('Expression');
            oExpression.DataStatusValueType = MFStatusTypeDeleted;
            oExpression.DataStatusValueDataFunction = MFDataFunctionNoOp;
            var oTypedValue = MFiles.CreateInstance('TypedValue');
            oTypedValue.SetValue(MFDatatypeBoolean, false);
            var oDeletedEx = MFiles.CreateInstance('SearchConditionEx');
            oDeletedEx.SearchCondition.Set(oExpression, MFConditionTypeEqual, oTypedValue);
            oDeletedEx.Enabled = true;
            oDeletedEx.Ignored = false;
            oDeletedEx.SpecialNULL = false;
            oSCriteria.AdditionalConditions.Add(-1, oDeletedEx);

            if (oSearchConditions) {
                for (var i = 1; i <= oSearchConditions.Count; i++) {
                    var oScEx = MFiles.CreateInstance('SearchConditionEx');
                    oScEx.SearchCondition = oSearchConditions.Item(i);
                    oScEx.Enabled = true;
                    oScEx.Ignored = false;
                    oScEx.SpecialNULL = false;
                    oSCriteria.AdditionalConditions.Add(-1, oScEx);
                }
            }

            var oTempViewNew = vault.ViewOperations.AddTemporarySearchView(oViewNew, oSCriteria, MFiles.CreateInstance('SearchConditions'));
            return oTempViewNew;
        },
        ///<summery>获取临时搜索视图位置</summery>
        getSearchViewLoc: function (vault, oView) {
            return vault.ViewOperations.GetViewLocationInClient(oView.ID, true);
        }
    };
    v.ObjectOps = o;
})(MF);


text:
Simple todo-app that use the server to save, update, remove and create new todos

#How run this app?
1. Download the zip
2. Extract zip in some folder, now access the extracted folder and run the command  **npm install serve bower -g**
3. Now run the command **bower install**
4. Into the extracted [todo-app-master] root folder run the command **serve .** (this will create a simple http server into your folder)
5. Now open the url into your navigator **http://localhost:3000/dist**

To you see the application run properly you will need configure the server, to do it follow this url todo-server


text:
package org.apache.ivy.core.event.download;

import org.apache.ivy.core.event.IvyEvent;
import org.apache.ivy.core.module.descriptor.Artifact;

public abstract class DownloadEvent extends IvyEvent {
    private Artifact artifact;

    public DownloadEvent(String name, Artifact artifact) {
        super(name);
        this.artifact = artifact;
        addArtifactAttributes(this.artifact);
    }

    protected void addArtifactAttributes(Artifact artifact) {
        addMridAttributes(artifact.getModuleRevisionId());
        addAttributes(artifact.getAttributes());
        addAttribute("metadata", String.valueOf(artifact.isMetadata()));
    }

    public Artifact getArtifact() {
        return artifact;
    }

}


text:
A collection of JavaScript utilities and sub-libraries I've built over the course of many projects. Nothing really big enough to live on it's own, at least yet.

Docs are in READMEs or in comments at the top of each file.

I know a lot of folks don't like deep namespacing. I don't really either, but there comes a time when you have to be responsible at the expense of conciseness.

Feedback is welcome, you can reach me at jim at autonomousmachine dot com.


text:
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns             #-}
{-# LANGUAGE BangPatterns               #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE PackageImports             #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE TypeApplications           #-}

module Data.KeyStore.KS.Crypto
  ( sizeAesIV
  , sizeOAE
  , defaultEncryptedCopyKS
  , saveKS
  , restoreKS
  , mkAESKeyKS
  , encryptKS
  , decryptKS
  , decryptE
  , encodeRSASecretData
  , decodeRSASecretData
  , decodeRSASecretData_
  , encryptRSAKS
  , decryptRSAKS
  , decryptRSAE
  , oaep
  , signKS
  , verifyKS
  , pssp
  , encryptAESKS
  , encryptAES
  , decryptAES
  , randomAESKeyKS
  , randomIVKS
  , hashKS
  , defaultHashParams
  , defaultHashParamsKS
  , hashKS_
  , generateKeysKS
  , generateKeysKS_
  , decodePrivateKeyDERE
  , decodePublicKeyDERE
  , encodePrivateKeyDER
  , encodePublicKeyDER
  , decodeDERE
  , encodeDER
  -- testing
  , test_crypto
  ) where

import           Data.KeyStore.KS.KS
import           Data.KeyStore.KS.Opt
import           Data.KeyStore.Types
import           Data.API.Types
import qualified Data.ASN1.Encoding             as A
import qualified Data.ASN1.BinaryEncoding       as A
import qualified Data.ASN1.Types                as A
import qualified Data.ByteString.Lazy.Char8     as LBS
import qualified Data.ByteString.Char8          as B
import           Data.Coerce
import           Data.Maybe
import           Data.Typeable
import           Crypto.Error
import           Crypto.Hash.Algorithms
import           Crypto.PubKey.RSA
import qualified Crypto.PubKey.RSA.OAEP         as OAEP
import qualified Crypto.PubKey.RSA.PSS          as PSS
import           Crypto.PubKey.MaskGenFunction
import           Crypto.Cipher.AES
import qualified Crypto.Types.PubKey.RSA        as CPT

-- avoiding class with crypto-pubkey-types which we are using for DER generation
import qualified "cryptonite" Crypto.Cipher.Types as CCT

sizeAesIV, sizeOAE :: Octets
sizeAesIV = 16
sizeOAE   = 256

--
-- smoke tests
--

test_crypto :: Bool
test_crypto = test_oaep && test_pss

test_oaep :: Bool
test_oaep = trun $
 do (puk,prk) <- generateKeysKS
    tm'       <- encryptKS puk tm >>= decryptKS prk
    return $ tm' == tm
  where
    tm = ClearText $ Binary "test message"

test_pss :: Bool
test_pss = trun $
 do (puk,prk) <- generateKeysKS
    sig  <- signKS prk tm
    return $ verifyKS puk tm  sig && not (verifyKS puk tm' sig)
  where
    tm  = ClearText $ Binary "hello"
    tm' = ClearText $ Binary "gello"

--
-- defaultEncryptedCopy
--

defaultEncryptedCopyKS :: Safeguard -> KS EncrypedCopy
defaultEncryptedCopyKS sg =
 do ciphr <- lookupOpt opt__crypt_cipher
    prf   <- lookupOpt opt__crypt_prf
    itrns <- lookupOpt opt__crypt_iterations
    st_sz <- lookupOpt opt__crypt_salt_octets
    slt   <- randomBytes st_sz (Salt . Binary)
    return
        EncrypedCopy
            { _ec_safeguard   = sg
            , _ec_cipher      = ciphr
            , _ec_prf         = prf
            , _ec_iterations  = itrns
            , _ec_salt        = slt
            , _ec_secret_data = ECD_no_data void_
            }

--
-- saving and restoring secret copies
--

saveKS :: EncryptionKey -> ClearText -> KS EncrypedCopyData
saveKS ek ct =
    case ek of
      EK_public    puk -> ECD_rsa   <$> encryptKS puk ct
      EK_private   _   -> errorKS "Crypto.Save: saving with private key"
      EK_symmetric aek -> ECD_aes   <$> encryptAESKS aek ct
      EK_none      _   -> ECD_clear <$> return ct

restoreKS :: EncrypedCopyData -> EncryptionKey -> KS ClearText
restoreKS ecd ek =
    case (ecd,ek) of
      (ECD_rsa     rsd,EK_private   prk) -> decryptKS prk rsd
      (ECD_aes     asd,EK_symmetric aek) -> return $ decryptAES aek asd
      (ECD_clear   ct ,EK_none      _  ) -> return ct
      (ECD_no_data _  ,_               ) -> errorKS "restore: no data!"
      _                                  -> errorKS "unexpected EncrypedCopy/EncryptionKey combo"

--
-- making up an AESKey from a list of source texts
--

mkAESKeyKS :: EncrypedCopy -> [ClearText] -> KS AESKey
mkAESKeyKS _              []  = error "mkAESKey: no texts"
mkAESKeyKS EncrypedCopy{..} cts = p2 <$> lookupOpt opt__crypt_cipher
  where
    p2 ciphr = pbkdf _ec_prf ct _ec_salt _ec_iterations (keyWidth ciphr) $ AESKey . Binary

    ct       = ClearText $ Binary $ B.concat $ map (_Binary._ClearText) cts

--
-- encrypting & decrypting
--

encryptKS :: PublicKey -> ClearText -> KS RSASecretData
encryptKS pk ct =
 do cip <- lookupOpt opt__crypt_cipher
    aek <- randomAESKeyKS cip
    rek <- encryptRSAKS pk aek
    asd <- encryptAESKS aek ct
    return
        RSASecretData
            { _rsd_encrypted_key    = rek
            , _rsd_aes_secret_data = asd
            }

decryptKS :: PrivateKey -> RSASecretData -> KS ClearText
decryptKS pk dat = e2ks $ decryptE pk dat

decryptE :: PrivateKey -> RSASecretData -> E ClearText
decryptE pk RSASecretData{..} =
 do aek <- decryptRSAE pk _rsd_encrypted_key
    return $ decryptAES aek _rsd_aes_secret_data

--
-- Serializing RSASecretData
--

encodeRSASecretData :: RSASecretData -> RSASecretBytes
encodeRSASecretData RSASecretData{..} =
    RSASecretBytes $ Binary $
        B.concat
            [ _Binary $ _RSAEncryptedKey _rsd_encrypted_key
            , _Binary $ _IV              _asd_iv
            , _Binary $ _SecretData      _asd_secret_data
            ]
  where
    AESSecretData{..} = _rsd_aes_secret_data

decodeRSASecretData :: RSASecretBytes -> KS RSASecretData
decodeRSASecretData (RSASecretBytes dat) = e2ks $ decodeRSASecretData_ $ _Binary dat

decodeRSASecretData_ :: B.ByteString -> E RSASecretData
decodeRSASecretData_ dat0 =
 do (eky,dat1) <- slice sizeOAE   dat0
    (iv ,edat) <- slice sizeAesIV dat1
    return
        RSASecretData
            { _rsd_encrypted_key    = RSAEncryptedKey $ Binary eky
            , _rsd_aes_secret_data =
                AESSecretData
                    { _asd_iv           = IV         $ Binary iv
                    , _asd_secret_data  = SecretData $ Binary edat
                    }
            }
  where
    slice sz bs =
        case B.length bs >= _Octets sz of
          True  -> Right $ B.splitAt (_Octets sz) bs
          False -> Left  $ strMsg "decrypt: not enough bytes"

--
-- RSA encrypting & decrypting
--

encryptRSAKS :: PublicKey -> AESKey -> KS RSAEncryptedKey
encryptRSAKS pk (AESKey (Binary dat)) =
    fmap (RSAEncryptedKey . Binary) $ rsaErrorKS $ OAEP.encrypt oaep pk dat

decryptRSAKS :: PrivateKey -> RSAEncryptedKey -> KS AESKey
decryptRSAKS pk rek = either throwKS return $ decryptRSAE pk rek

decryptRSAE :: PrivateKey -> RSAEncryptedKey -> E AESKey
decryptRSAE pk rek = rsa2e $ fmap (AESKey . Binary) $
    OAEP.decrypt Nothing oaep pk $ _Binary $ _RSAEncryptedKey rek

type OAEPparams = OAEP.OAEPParams SHA512 B.ByteString B.ByteString

oaep :: OAEPparams
oaep = OAEP.OAEPParams
    { OAEP.oaepHash       = SHA512
    , OAEP.oaepMaskGenAlg = mgf1 SHA512
    , OAEP.oaepLabel      = Nothing
    }

--
-- signing & verifying
--

signKS :: PrivateKey -> ClearText -> KS RSASignature
signKS pk dat =
    fmap (RSASignature . Binary) $
          rsaErrorKS $ PSS.sign Nothing pssp pk $ _Binary $ _ClearText dat

verifyKS :: PublicKey -> ClearText -> RSASignature -> Bool
verifyKS pk (ClearText (Binary dat)) (RSASignature (Binary sig)) = PSS.verify pssp pk dat sig

type PSSparams = PSS.PSSParams SHA512 B.ByteString B.ByteString

pssp :: PSSparams
pssp = PSS.defaultPSSParams SHA512

--
-- AES encrypting/decrypting
--

encryptAESKS :: AESKey -> ClearText -> KS AESSecretData
encryptAESKS aek ct =
 do iv <- randomIVKS
    return $ encryptAES aek iv ct

encryptAES :: AESKey -> IV -> ClearText -> AESSecretData
encryptAES aek iv (ClearText (Binary dat)) =
    AESSecretData
        { _asd_iv          = iv
        , _asd_secret_data = SecretData $ Binary $ encryptCTR aek iv dat
        }

decryptAES :: AESKey -> AESSecretData -> ClearText
decryptAES aek AESSecretData{..} = ClearText $ Binary $
        encryptCTR aek _asd_iv $ _Binary $ _SecretData _asd_secret_data

randomAESKeyKS :: Cipher -> KS AESKey
randomAESKeyKS cip = randomBytes (keyWidth cip) $ AESKey . Binary

randomIVKS :: KS IV
randomIVKS = randomBytes sizeAesIV $ IV . Binary

encryptCTR :: AESKey -> IV -> B.ByteString -> B.ByteString
encryptCTR aek = case B.length $ coerce aek of
    16 -> aes_ctr (Proxy @AES128) aek
    24 -> aes_ctr (Proxy @AES192) aek
    32 -> aes_ctr (Proxy @AES256) aek
    ln -> error $ "aek_from_key: unexpected AES key size: " ++ show ln

aes_ctr :: forall k . (CCT.BlockCipher k,Typeable k)
        => Proxy k -> AESKey -> IV -> B.ByteString -> B.ByteString
aes_ctr pxy aek iv msg = CCT.ctrCombine ky_ iv_ msg
  where
    ky_ :: k
    ky_ = case CCT.cipherInit ky_b of
      CryptoFailed _ -> oops "key"
      CryptoPassed z -> z

    iv_ :: CCT.IV k
    iv_ = fromMaybe (oops "IV") $ CCT.makeIV iv_b

    oops :: String -> a
    oops thg = error $ tynm ++ " cryption error: mismatched size of "++thg

    tynm :: String
    tynm = show $ typeRep pxy

    AESKey (Binary ky_b) = aek
    IV     (Binary iv_b) = iv

--
-- hashing
--

hashKS :: ClearText -> KS Hash
hashKS ct = flip hashKS_ ct <$> defaultHashParamsKS

defaultHashParams :: HashDescription
defaultHashParams = trun defaultHashParamsKS

defaultHashParamsKS :: KS HashDescription
defaultHashParamsKS =
 do h_cmt <- lookupOpt opt__hash_comment
    h_prf <- lookupOpt opt__hash_prf
    itrns <- lookupOpt opt__hash_iterations
    hs_wd <- lookupOpt opt__hash_width_octets
    st_wd <- lookupOpt opt__hash_salt_octets
    st    <- randomBytes st_wd (Salt . Binary)
    return $ hashd h_cmt h_prf itrns hs_wd st_wd st
  where
    hashd  h_cmt h_prf itrns hs_wd st_wd st =
        HashDescription
            { _hashd_comment      = h_cmt
            , _hashd_prf          = h_prf
            , _hashd_iterations   = itrns
            , _hashd_width_octets = hs_wd
            , _hashd_salt_octets  = st_wd
            , _hashd_salt         = st
            }

hashKS_ :: HashDescription -> ClearText -> Hash
hashKS_ hd@HashDescription{..} ct =
    Hash
        { _hash_description = hd
        , _hash_hash        = pbkdf _hashd_prf ct _hashd_salt _hashd_iterations
                                        _hashd_width_octets (HashData . Binary)
        }

--
-- Generating a private/public key pair
--

default_e :: Integer
default_e = 0x10001

default_key_size :: Int
default_key_size = 2048 `div` 8

generateKeysKS :: KS (PublicKey,PrivateKey)
generateKeysKS = generateKeysKS_ default_key_size

generateKeysKS_ :: Int -> KS (PublicKey,PrivateKey)
generateKeysKS_ ksz = generate ksz default_e

--
-- Encoding & decoding private & public keys
--

decodePrivateKeyDERE :: ClearText -> E PrivateKey
decodePrivateKeyDERE = decodeDERE . _Binary . _ClearText

decodePublicKeyDERE :: ClearText -> E PublicKey
decodePublicKeyDERE = decodeDERE . _Binary . _ClearText

encodePrivateKeyDER :: PrivateKey -> ClearText
encodePrivateKeyDER = ClearText . Binary . encodeDER

encodePublicKeyDER :: PublicKey -> ClearText
encodePublicKeyDER = ClearText . Binary . encodeDER

class ASN1 a where
  decodeDERE :: B.ByteString -> E a
  encodeDER  :: a -> B.ByteString

instance ASN1 PrivateKey where
  decodeDERE = fmap privateFromCPT . decodeDERE_
  encodeDER  = encodeDER_ . privateIntoCPT

instance ASN1 PublicKey  where
  decodeDERE = fmap publicFromCPT . decodeDERE_
  encodeDER  = encodeDER_ . publicIntoCPT

privateFromCPT :: CPT.PrivateKey -> PrivateKey
privateFromCPT CPT.PrivateKey{..} =
  PrivateKey
    { private_pub  = publicFromCPT private_pub
    , ..
    }

privateIntoCPT :: PrivateKey -> CPT.PrivateKey
privateIntoCPT PrivateKey{..} =
  CPT.PrivateKey
    { private_pub  = publicIntoCPT private_pub
    , ..
    }

publicFromCPT :: CPT.PublicKey -> PublicKey
publicFromCPT CPT.PublicKey{..} = PublicKey{..}

publicIntoCPT :: PublicKey -> CPT.PublicKey
publicIntoCPT PublicKey{..} = CPT.PublicKey{..}

decodeDERE_ :: A.ASN1Object a => B.ByteString -> E a
decodeDERE_ bs =
    case A.decodeASN1 A.DER $ lzy bs of
      Left err -> Left $ strMsg $ show err
      Right as ->
        case A.fromASN1 as of
          Left err -> Left $ strMsg $ show err
          Right pr ->
            case pr of
              (pk,[]) -> return pk
              _       -> Left $ strMsg "residual data"
  where
    lzy = LBS.pack . B.unpack

encodeDER_ :: A.ASN1Object a => a -> B.ByteString
encodeDER_ = egr . A.encodeASN1 A.DER  . flip A.toASN1 []
  where
    egr = B.pack . LBS.unpack

--
-- Helpers
--

rsa2e :: Either Error a -> E a
rsa2e = either (Left . rsaError) Right


text:
<?php
/**
 * neckbeard engine room
 *
 * @package neckbeard
 */

/**
 * Initialize all the things.
 */
require get_template_directory() . '/inc/init.php';

// NECKBEARD theme specific functions below
// Let's try and keep this minimal...

/*
* Hide WP updates nag
*/
add_action('admin_menu','wphidenag');
function wphidenag() {
   remove_action( 'admin_notices', 'update_nag', 3 );
}

/**
 * Remove query strings from static resources for optimization
 *
 * @link https://wordpress.org/support/topic/how-to-remove-query-strings-from-static-resources
 */

function _remove_script_version( $src ){
  $parts = explode( '?', $src );
  return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );

/*
 * All times and local units in Finnish.
 */
 date_default_timezone_set('Europe/Helsinki');
 setlocale(LC_ALL, array('fi_FI.UTF-8','fi_FI@euro','fi_FI','finnish'));

/*
 * Custom icons for admin menus
 */
function FontAwesome_icons() {
    echo '<link href="//netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet">
          <style type="text/css">
          #adminmenu #menu-posts-custom-post-type .wp-menu-image:before {
            content: "\f135";
            font-family: "FontAwesome" !important;
            font-size: 18px !important;
          }
          </style>
    ';
}
add_action('admin_head', 'FontAwesome_icons');
add_action('wp_head', 'FontAwesome_icons');

/*
 * Custom wp-admin CSS
 * Hide useless notifications in admin
 */
function custom_admin_css() {
   echo '<style type="text/css" media="screen">
   #wpseo-dismiss-about, #wcml_translations_message, #ga_analyticator_global_notification { display: none !important; }
   </style>';
}
add_action('admin_head', 'custom_admin_css');

/*
 * More accurate time in WP Last Login.
 */
function my_last_login( ) {
return 'j.m.Y, H:i';
}
add_filter('wpll_date_format', 'my_last_login');

/*
 * Custom uploads folder instead of default content/uploads.
 * Comment these out if you want to set up media library folder in wp-admin.
 */
update_option( 'upload_path', untrailingslashit( str_replace( 'wp', 'media', ABSPATH ) ) );
update_option( 'upload_url_path', untrailingslashit( str_replace( 'wp', 'media', get_site_url() ) ) );
define( 'uploads', ''.'media' );
add_filter( 'option_uploads_use_yearmonth_folders', '__return_false', 100 );

/*
 * Hidden blog menu items by default.
 * Comment these out if you want to use blog or comments.
 */
function menuitems_remove() {
   remove_menu_page('edit.php');
   remove_menu_page('edit-comments.php');
}
add_action('admin_menu', 'menuitems_remove');

/*
 * Hiding things customers won't usually need.
 * Hides Tools, Themes, Customize, Widgets, Plugins, Custom Fields, Feedback.
 */
function remove_admin_menu_links() {
    $user = wp_get_current_user();
    if( $user && isset($user->user_email) && 'roni@dude.fi' == $user->user_email || 'juha@dude.fi' == $user->user_email ) {

      // For testing:
      // if( $user && isset($user->user_email) && 'roni@dude.fi' == $user->user_email) {

    } else {

        remove_menu_page('tools.php');
        remove_menu_page('themes.php?page=editcss');
        remove_menu_page('customize.php');
        remove_menu_page('widgets.php');
        remove_menu_page('plugins.php');
        remove_menu_page('edit.php?post_type=acf');
        remove_menu_page('edit.php?post_type=feedback');

  }

}
add_action('admin_menu', 'remove_admin_menu_links', 999);

/**
 * Remove WordPress Admin Bar
 *
 * @link http://davidwalsh.name/remove-wordpress-admin-bar-css
 */
add_action('get_header', 'remove_admin_login_header');
function remove_admin_login_header() {
        remove_action('wp_head', '_admin_bar_bump_cb');
}
show_admin_bar(false);