text:
from math import sin, cos, radians, pi

class CoordCalc:
    def __init__(self, star_data_list, area, diagram_size):
        self.star_data_list = star_data_list
        self.area = area
        self.center_ra_angle = self._ra_to_angle((area.ra_min + area.ra_max) / 2)
        if area.ra_max - area.ra_min >= 12:
            self.center_dec_angle = self._dec_to_angle(
                90 if abs(area.dec_min) < abs(area.dec_max) else -90
            )
        else:
            self.center_dec_angle = self._dec_to_angle(
                (area.dec_min + area.dec_max) / 2
            )
        self.diagram_size = diagram_size

    def _ra_to_angle(self, ra):
        # convert right-ascension (0 -> 24) into angle (0 -> 2π)
        return pi * 2 * (1 - ra / 24)

    def _dec_to_angle(self, dec):
        # convert declination (-90 -> +90) into angle (-π/2 -> +π/2)
        return radians(dec)

    def _populate_angles(self):
        for star_data in self.star_data_list.data:
            star_data.ra_angle = self._ra_to_angle(star_data.ra)
            star_data.dec_angle = self._dec_to_angle(star_data.dec)

    def _angle_to_xy(self, ra_angle, dec_angle):
        # http://www.projectpluto.com/project.htm
        delta_ra = ra_angle - self.center_ra_angle
        x = cos(dec_angle) * sin(delta_ra)
        y = sin(dec_angle) * cos(self.center_dec_angle) - cos(dec_angle) * cos(
            delta_ra
        ) * sin(self.center_dec_angle)
        return x, y

    def _populate_xy(self):
        for star_data in self.star_data_list.data:
            star_data.x, star_data.y = self._angle_to_xy(
                star_data.ra_angle, star_data.dec_angle
            )

    def _offset_and_scale_xy(self):
        min_x = min(map(lambda sd: sd.x, self.star_data_list.data))
        min_y = min(map(lambda sd: sd.y, self.star_data_list.data))
        max_x = max(map(lambda sd: sd.x, self.star_data_list.data))
        max_y = max(map(lambda sd: sd.y, self.star_data_list.data))

        x_range = max_x - min_x
        y_range = max_y - min_y
        max_range = max(x_range, y_range)

        self.magnification = self.diagram_size / max_range

        def offset_and_scale_x(x):
            return (x - min_x) * self.magnification

        def offset_and_scale_y(y):
            return (y - min_y) * self.magnification

        def offset_and_scale(star_data):
            star_data.x = offset_and_scale_x(star_data.x)
            star_data.y = offset_and_scale_y(star_data.y)

        self.star_data_list.min_x = offset_and_scale_x(min_x)
        self.star_data_list.min_y = offset_and_scale_y(min_y)
        self.star_data_list.max_x = offset_and_scale_x(max_x)
        self.star_data_list.max_y = offset_and_scale_y(max_y)
        self.offset_and_scale_x = offset_and_scale_x
        self.offset_and_scale_y = offset_and_scale_y

        list(map(offset_and_scale, self.star_data_list.data))

    def process(self):
        self._populate_angles()
        self._populate_xy()
        self._offset_and_scale_xy()

    def _ra_dec_to_x_y(self, ra, dec):
        ra_angle = self._ra_to_angle(ra)
        dec_angle = self._dec_to_angle(dec)

        base_x, base_y = self._angle_to_xy(ra_angle, dec_angle)

        return self.offset_and_scale_x(base_x), self.offset_and_scale_y(base_y)

    def calc_ra_curve(self, ra, steps):
        points = []
        dec_min = self.area.dec_min
        dec_max = self.area.dec_max
        dec_step = (dec_max - dec_min) / steps

        for i in range(steps + 1):
            x, y = self._ra_dec_to_x_y(ra, dec_min + dec_step * i)
            points.append((x, y))

        return points

    def calc_dec_curve(self, dec, steps):
        points = []
        ra_min = self.area.ra_min
        ra_max = self.area.ra_max
        ra_step = (ra_max - ra_min) / steps

        for i in range(steps + 1):
            x, y = self._ra_dec_to_x_y(ra_min + ra_step * i, dec)
            points.append((x, y))

        return points

    def calc_curves(self, ra_steps=100, dec_steps=100):
        curves = []

        curves.append(self.calc_ra_curve(self.area.ra_min, ra_steps))
        ra = round(self.area.ra_min)
        while ra < self.area.ra_max:
            if ra > self.area.ra_min:
                curves.append(self.calc_ra_curve(ra, ra_steps))
            ra += 1
        curves.append(self.calc_ra_curve(self.area.ra_max, ra_steps))

        curves.append(self.calc_dec_curve(self.area.dec_min, dec_steps))
        dec = round(self.area.dec_min / 10) * 10
        while dec < self.area.dec_max:
            if dec > self.area.dec_min:
                curves.append(self.calc_dec_curve(dec, dec_steps))
            dec += 10
        curves.append(self.calc_dec_curve(self.area.dec_max, dec_steps))

        return curves


text:
<?php

namespace frontend\modules\search;

use Yii;

class Module extends \yii\base\Module
{
    public $controllerNamespace = 'frontend\modules\search\controllers';

    public function init()
    {
        parent::init();

        Yii::$app->getUrlManager()->addRules([
            'browse' => $this->id . '/default/browse',
            'search' => $this->id . '/default/index',
            'search.php' => $this->id . '/default/index',
            'recent' => $this->id . '/default/recent',
        ], false);

        // custom initialization code goes here
    }
}

redpajama_set_name: RedPajamaGithub


text:
```html
<amp-ad
  width="300"
  height="169"
  type="viralize"
  layout="responsive"
  data-zid="AACX6WjIMkl-yoGV"
>
</amp-ad>
```

## Configuration

For further configuration details, please contact [Viralize](https://viralize.com/contact-us/).

## Required parameters

-   `data-zid`: Id of the unit.

## Optional parameters

-   `data-extra`: JSON object representing any other query parameter that could be passed to the unit.


text:
const char* yrmcds_strerror(yrmcds_error e) {
    switch( e ) {
    case YRMCDS_OK:
        return "OK";
    case YRMCDS_SYSTEM_ERROR:
        return "Check errno for details";
    case YRMCDS_BAD_ARGUMENT:
        return "Bad argument";
    case YRMCDS_NOT_RESOLVED:
        return "Host not found";
    case YRMCDS_TIMEOUT:
        return "Timeout";
    case YRMCDS_DISCONNECTED:
        return "Connection was reset by peer";
    case YRMCDS_OUT_OF_MEMORY:
        return "Failed to allocate memory";
    case YRMCDS_COMPRESS_FAILED:
        return "Failed to compress data";
    case YRMCDS_PROTOCOL_ERROR:
        return "Received malformed packet";
    case YRMCDS_NOT_IMPLEMENTED:
        return "Not implemented";
    default:
        return "Unknown error";
    };
}


text:
site-backend
============

backend side of http://emlakmagdurlari.org


text:
import { ChangeDetectorRef } from '@angular/core';
import { MdSort, MdSortable } from './sort';
import { MdSortHeaderIntl } from './sort-header-intl';
import { CdkColumnDef } from '@angular/cdk';
import { Subscription } from 'rxjs/Subscription';
/**
 * Applies sorting behavior (click to change sort) and styles to an element, including an
 * arrow to display the current sort direction.
 *
 * Must be provided with an id and contained within a parent MdSort directive.
 *
 * If used on header cells in a CdkTable, it will automatically default its id from its containing
 * column definition.
 */
export declare class MdSortHeader implements MdSortable {
    _intl: MdSortHeaderIntl;
    private _changeDetectorRef;
    _sort: MdSort;
    _cdkColumnDef: CdkColumnDef;
    /** @docs-private  */
    sortSubscription: Subscription;
    /**
     * ID of this sort header. If used within the context of a CdkColumnDef, this will default to
     * the column's name.
     */
    id: string;
    /** Sets the position of the arrow that displays when sorted. */
    arrowPosition: 'before' | 'after';
    /** Overrides the sort start value of the containing MdSort for this MdSortable. */
    start: 'asc' | 'desc';
    /** Overrides the disable clear value of the containing MdSort for this MdSortable. */
    disableClear: boolean;
    private _disableClear;
    _id: string;
    constructor(_intl: MdSortHeaderIntl, _changeDetectorRef: ChangeDetectorRef, _sort: MdSort, _cdkColumnDef: CdkColumnDef);
    ngOnInit(): void;
    ngOnDestroy(): void;
    /** Whether this MdSortHeader is currently sorted in either ascending or descending order. */
    _isSorted(): false | "" | "desc" | "asc";
}


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <link rel="stylesheet" type="text/css" media="all" href="/css/db_edit.css" />
    <?php //Ox_WidgetHandler::CSS() ?>
    <?php //Ox_WidgetHandler::JS() ?>
    <?php //Ox_WidgetHandler::HtmlTitle() ?>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    Editing Layout

		<input type="text" class="search" id="nameSearch" placeholder="Company Search"></input>
		<input type="text" class="search" id="stateSearch" placeholder="State Search"></input>
		<input type="text" class="search" id="citySearch" placeholder="City Search"></input>
		<input type="text" class="search" id="openjobSearch" placeholder="Open Position Search"></input>

		<button class="search" id="clearButton">Clear</button>

		<input type="text" id="addName" class="company-add-input required" placeholder="Company*"></input>
		<input type="text" id="addLink" class="company-add-input" placeholder="Careers Page"></input>
		<input type="text" id="addState" class="company-add-input required" placeholder="State*"></input>
		<input type="text" id="addCity" class="company-add-input required" placeholder="City*"></input>
		<input type="text" id="addOpenjobcount" class="company-add-input" placeholder="# of Openings"></input>

		<button id="addButton" onclick="addCompany()" class="company-add-input disable-target">Add Company</button>

    <?php echo date('Y-m-d H:i:s');?>


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.Serialization;
using DevExpress.CodeRush.Core;
using DevExpress.CodeRush.PlugInCore;
using DevExpress.CodeRush.StructuralParser;

namespace CR_AddDataContract
{
    public partial class PlugIn1 : StandardPlugIn
    {
        // DXCore-generated code...
        #region InitializePlugIn
        public override void InitializePlugIn()
        {
            base.InitializePlugIn();
            registerAddDataContract();
        }
        #endregion
        #region FinalizePlugIn
        public override void FinalizePlugIn()
        {
            //
            // TODO: Add your finalization code here.
            //

            base.FinalizePlugIn();
        }
        #endregion
        public void registerAddDataContract()
        {
            DevExpress.CodeRush.Core.CodeProvider AddDataContract = new DevExpress.CodeRush.Core.CodeProvider(components);
            ((System.ComponentModel.ISupportInitialize)(AddDataContract)).BeginInit();
            AddDataContract.ProviderName = "AddDataContract"; // Should be Unique
            AddDataContract.DisplayName = "Add DataContract";
            AddDataContract.CheckAvailability += AddDataContract_CheckAvailability;
            AddDataContract.Apply += AddDataContract_Apply;
            ((System.ComponentModel.ISupportInitialize)(AddDataContract)).EndInit();
        }
        private void AddDataContract_CheckAvailability(Object sender, CheckContentAvailabilityEventArgs ea)
        {
            // Limit availability to when the caret is within the name of the active class.
            if (CodeRush.Source.ActiveClass == null)
                return; // No active class
            if (!CodeRush.Source.ActiveClass.NameRange.Contains(CodeRush.Caret.SourcePoint))
                return;  // Caret not in class name
            ea.Available = true;
        }

        private void AddDataContract_Apply(Object sender, ApplyContentEventArgs ea)
        {
            TextDocument ActiveDoc = CodeRush.Documents.ActiveTextDocument;

            using (ActiveDoc.NewCompoundAction("Add DataContract"))
            {
                // Add Namespace Reference
                AddNamespaceReference("System.Runtime.Serialization");
                CodeRush.Project.AddReference(ActiveDoc.ProjectElement, "System.Runtime.Serialization");

                // Add DataContract Attribute
                AddAttribute(CodeRush.Source.ActiveClass, "DataContract");
                foreach (Property prop in CodeRush.Source.ActiveClass.AllProperties)
                {
                    // Add DataMember Attribute
                    AddAttribute(prop, "DataMember");
                }
                CodeRush.Documents.ActiveTextDocument.ApplyQueuedEdits();
                CodeRush.Documents.ActiveTextDocument.ParseIfNeeded();
                CodeRush.Actions.Get("FormatFile").DoExecute();
            }
        }
        private void AddNamespaceReference(string NamespaceName)
        {
            TextDocument ActiveDoc = CodeRush.Documents.ActiveTextDocument;
            var finder = new ElementEnumerable(ActiveDoc.FileNode, LanguageElementType.NamespaceReference, true);
            var NamespaceReferences = finder.OfType<NamespaceReference>();
            if (NamespaceReferences.Any(ns => ns.Name == NamespaceName))
                return;

            // Calculate Insert Location
            SourcePoint InsertionPoint;
            if (ActiveDoc.NamespaceReferences.Count <= 0)
            {
                InsertionPoint = ActiveDoc.Range.Start;
            }
            else
            {
                InsertionPoint = NamespaceReferences.Last().Range.Start;
            }

            // Generate new NamespaceReference
            var Code = CodeRush.CodeMod.GenerateCode(new NamespaceReference(NamespaceName));
            ActiveDoc.QueueInsert(InsertionPoint, Code);
        }
        private void AddAttribute(LanguageElement element, string AttributeName)
        {
            var Builder = new ElementBuilder();
            var Attribute = Builder.BuildAttribute(AttributeName);
            var Section = Builder.BuildAttributeSection();
            Section.AddAttribute(Attribute);
            var Code = CodeRush.CodeMod.GenerateCode(Section, false);
            SourcePoint InsertionPoint = new SourcePoint(element.Range.Start.Line, 1);
            CodeRush.Documents.ActiveTextDocument.QueueInsert(InsertionPoint, Code);
        }

    }
}


text:
Lexicon.add('layout/empty', {

  body:[
    { style:'border: 1px solid #444; padding: 6px;', _:[
      { tag:'h3', text:"Empty Layout Test" },
      { tag:'ul', style:'line-height:26px;', _:[
        { tag:'li', _:[{ tag:'a', href:'page:layout/Functional',    classname:'action', text:'Layout: Back' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/empty',         classname:'action', text:'Layout: Empty' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/event',         classname:'action', text:'Layout: Event' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/tall_event',    classname:'action', text:'Layout: Tall Event' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/midlin_event',  classname:'action', text:'Layout: Midlin Event' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/grande_event',  classname:'action', text:'Layout: Grande Event' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/venti_event',   classname:'action', text:'Layout: Venti Event' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/main',          classname:'action', text:'Layout: Main' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/location',      classname:'action', text:'Layout: Location' } ]},
        { tag:'li', _:[{ tag:'a', href:'page:layout/location_view', classname:'action', text:'Layout: Location View' } ]},
      ]},
    ]},
  ],

});


text:
/**
 *
 */
package com.danielesegato.adme.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Help with dates. Careful with {@link Date} methods, the date should be in UTC.
 */
public final class DateHelper {

    private static final ThreadLocal<DateFormat> ISO8601_UTC_FORMATTER = new ThreadLocal<DateFormat>();

    /**
     * The ISO8601 format specification (from w3c) without the timezone part.
     */
    private static final String ISO8601_CUSTOM_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";

    /**
     * Create a {@link SimpleDateFormat} per thread (not thread safe).
     *
     * @return create and store in the local thread an instance of {@link SimpleDateFormat}.
     */
    private static final DateFormat getIso8601UTCDateFormat() {
        DateFormat iso8601UTCDateFormat = ISO8601_UTC_FORMATTER.get();
        if (iso8601UTCDateFormat == null) {
            iso8601UTCDateFormat = new SimpleDateFormat(ISO8601_CUSTOM_FORMAT, Locale.UK);
            iso8601UTCDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            ISO8601_UTC_FORMATTER.set(iso8601UTCDateFormat);
        }
        return iso8601UTCDateFormat;
    }

    /**
     * Parse the date time string and return a {@link Date} object. If the parsing fail an exception is raised, if you
     * don't want to handle it see {@link #parseUTCDateTime(String, Date)} instead. The string is expected in the
     * ISO8601 CUSTOM format, see {@link #ISO8601_CUSTOM_FORMAT} for details.
     *
     * @param iso8601_datetime the string in the ISO8601 CUSTOM format
     * @return the {@link Date} object parsed
     * @throws ParseException if the iso8601_datetime is not in a valid format
     * @see #ISO8601_CUSTOM_FORMAT
     */
    public static final Date parseUTCDateTime(String iso8601_datetime) throws ParseException {
        return getIso8601UTCDateFormat().parse(iso8601_datetime);
    }

    /**
     * Parse the date time string and return a {@link Date} object. If the parsing fail or the iso8601_datetime is null
     * the _default value is returned. The string is expected in the ISO8601 CUSTOM format, see
     * {@link #ISO8601_CUSTOM_FORMAT} for details.
     *
     * @param iso8601_datetime the string in the ISO8601 CUSTOM format
     * @return the {@link Date} object parsed or _default in case of failure
     * @see #ISO8601_CUSTOM_FORMAT
     */
    public static final Date parseUTCDateTime(String iso8601_datetime, Date _default) {
        try {
            return iso8601_datetime != null ? parseUTCDateTime(iso8601_datetime) : _default;
        } catch (ParseException e) {
            return _default;
        }
    }

    /**
     * Format the datetime {@link Date} object into a Custom ISO8601 format string.
     *
     * @param datetime the {@link Date} object
     * @return the formatted string
     * @see #ISO8601_CUSTOM_FORMAT
     */
    public static final String formatUTCDateTime(Date datetime) {
        return getIso8601UTCDateFormat().format(datetime);
    }

}


text:
package luddite

import (
	"net/http"
	"strconv"

	"github.com/K-Phoen/negotiation"
)

var acceptedContentTypes = []string{
	ContentTypeJson,
	ContentTypeCss,
	ContentTypePlain,
	ContentTypeXml,
	ContentTypeHtml,
	ContentTypeGif,
	ContentTypePng,
	ContentTypeOctetStream,
}

// RegisterFormat registers a new format and associated MIME types.
func RegisterFormat(format string, mimeTypes []string) {
	negotiation.RegisterFormat(format, mimeTypes)
}

type negotiatorHandler struct{}

func (n *negotiatorHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	// If no Accept header was included, default to the first accepted format
	accept := req.Header.Get(HeaderAccept)
	if accept == "" {
		accept = acceptedContentTypes[0]
	}

	// Negotiate and set a Content-Type
	//
	// Note: Negotation failures do not return 406 errors here. This allows
	// resource handlers to potentially inspect/handle certain rarely-used
	// content types on their own. If a negotiation failure has occurred and
	// the resource handler doesn't deal with it, then we can expect a 406
	// from WriteResponse.
	if format, _ := negotiation.NegotiateAccept(accept, acceptedContentTypes); format != nil {
		rw.Header().Set(HeaderContentType, format.Value)
	}

	// If the X-Spirent-Inhibit-Response header is set and true-ish, then
	// set the same response header. This will cause subsequent calls to
	// WriteResponse to omit the response body for 2xx responses and also
	// makes the behavior obvious to clients (i.e. response header shows
	// intention beyond the 204 status).
	if inhibitResp, _ := strconv.ParseBool(req.Header.Get(HeaderSpirentInhibitResponse)); inhibitResp {
		rw.Header().Set(HeaderSpirentInhibitResponse, "1")
	}

	next(rw, req)
}


text:
from google.cloud import apigateway_v1

async def sample_get_gateway():
    # Create a client
    client = apigateway_v1.ApiGatewayServiceAsyncClient()

    # Initialize request argument(s)
    request = apigateway_v1.GetGatewayRequest(
        name="name_value",
    )

    # Make the request
    response = await client.get_gateway(request=request)

    # Handle the response
    print(response)

# [END apigateway_v1_generated_ApiGatewayService_GetGateway_async]


text:
<?php
namespace Elastica\Test\QueryBuilder\DSL;

use Elastica\Aggregation;
use Elastica\Query\Exists;
use Elastica\QueryBuilder\DSL;

class AggregationTest extends AbstractDSLTest
{
    /**
     * @group unit
     */
    public function testType()
    {
        $aggregationDSL = new DSL\Aggregation();

        $this->assertInstanceOf(DSL::class, $aggregationDSL);
        $this->assertEquals(DSL::TYPE_AGGREGATION, $aggregationDSL->getType());
    }

    /**
     * @group unit
     */
    public function testInterface()
    {
        $aggregationDSL = new DSL\Aggregation();

        $this->_assertImplemented($aggregationDSL, 'avg', Aggregation\Avg::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'cardinality', Aggregation\Cardinality::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'date_histogram', Aggregation\DateHistogram::class, ['name', 'field', 1]);
        $this->_assertImplemented($aggregationDSL, 'date_range', Aggregation\DateRange::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'extended_stats', Aggregation\ExtendedStats::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'filter', Aggregation\Filter::class, ['name', new Exists('field')]);
        $this->_assertImplemented($aggregationDSL, 'filters', Aggregation\Filters::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'geo_distance', Aggregation\GeoDistance::class, ['name', 'field', 'origin']);
        $this->_assertImplemented($aggregationDSL, 'geohash_grid', Aggregation\GeohashGrid::class, ['name', 'field']);
        $this->_assertImplemented($aggregationDSL, 'global_agg', Aggregation\GlobalAggregation::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'histogram', Aggregation\Histogram::class, ['name', 'field', 1]);
        $this->_assertImplemented($aggregationDSL, 'ipv4_range', Aggregation\IpRange::class, ['name', 'field']);
        $this->_assertImplemented($aggregationDSL, 'max', Aggregation\Max::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'min', Aggregation\Min::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'missing', Aggregation\Missing::class, ['name', 'field']);
        $this->_assertImplemented($aggregationDSL, 'nested', Aggregation\Nested::class, ['name', 'path']);
        $this->_assertImplemented($aggregationDSL, 'percentiles', Aggregation\Percentiles::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'range', Aggregation\Range::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'reverse_nested', Aggregation\ReverseNested::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'scripted_metric', Aggregation\ScriptedMetric::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'significant_terms', Aggregation\SignificantTerms::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'stats', Aggregation\Stats::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'sum', Aggregation\Sum::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'terms', Aggregation\Terms::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'top_hits', Aggregation\TopHits::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'value_count', Aggregation\ValueCount::class, ['name', 'field']);
        $this->_assertImplemented($aggregationDSL, 'bucket_script', Aggregation\BucketScript::class, ['name']);
        $this->_assertImplemented($aggregationDSL, 'serial_diff', Aggregation\SerialDiff::class, ['name']);

        $this->_assertNotImplemented($aggregationDSL, 'children', ['name']);
        $this->_assertNotImplemented($aggregationDSL, 'geo_bounds', ['name']);
        $this->_assertNotImplemented($aggregationDSL, 'percentile_ranks', ['name']);
    }
}


text:
Feel free to submit patches via pull requests. I will review them and merge.

For redmine 1.4 and older, see the right branch/tag, this one is suitable for 2.2

#MultiPass SSO Authentication plugin for Redmine (v 0.0.1)

This plugin is based on MultiPass gem (https://github.com/entp/multipass) and allows
users to register and login to the application with Single Sign On (SSO) link.
Configuration on both sides (Redmine and Custom app) is needed. Please read Configuration
instruction.

##Requirements
This plugin requires MultiPass gem installed.

gem install multipass

Edit your Gemfile and add there

gem 'multipass'

##Installation

1. cd plugins; git clone git://github.com/jozefvaclavik/redmine_multipass.git
2. cd ..; rake redmine:plugins:migrate RAILS_ENV=production
3. restart redmine

Because redmine from 1.4 version will not support wildchart routes, you need to add
your routes manually (I had same experience with Redmine 1.3.x).

Edit config/routes.rb and add these four lines AFTER first line.

match 'multipass', :controller => 'multipass', :action => 'index'
match 'multipass/index', :controller => 'multipass', :action => 'index'
match 'multipass/successful_authentication', :controller => 'multipass', :action => 'successful_authentication'
match 'multipass/register', :controller => 'multipass', :action => 'register'

##Configuration

###Redmine:

* Enable => Enable/Disable plugin.
* Debug Mode => Enable/Disable debug mode. While enabled, instead of proceeding
  User information to login/register, decrypted information are displayed.
* Self Registration => Enalbe/Disable registration mode.
* Support Email => Contact information in case that SSO Auth will fail to login/register
* Group => User group, where newly created users will be added
* SSO Api Key => SSO Key for encryption/decryption
* Site Key => Site key used for encryption/decryption

###Custom app: EXAMPLE USSAGE
- In User.rb model:
**site_key and sso_api_key are string values from redmine settings**

def self.multipass
  @multipass ||= MultiPass.new(site_key, sso_api_key)
end

def multipass
  users_remote_uid = "#{site_key}_#{id}"
  user_mail = "Obtain users email"
  user_first_name = "Obtain users first name"
  user_last_name = "Obtain users last name"
	user_login = "Obtain users login"
  self.class.multipass.encode(:email => user_mail, :first_name => user_first_name, :last_name => user_last_name, :login => user_login, :remote_uid => users_remote_uid, :expires => 30.minutes.from_now)
end

- In your view:
**Assume that @user is currently logged in user**

link_to( "Open Redmine", "http://link_to_your_redmine_app/multipass/?sso=#{CGI.escape(@user.multipass)}")

###PHP Support:
If your custom application is based on PHP, take a look at Tomdchi PHP version of multipass library. https://github.com/tomdchi/Redmine-PHP-MultiPass

Known issues
=======

So far, none :-)

Copyright (c) 2011 Jozef Vaclavik, released under the MIT license


text:
from google.cloud import metastore_v1beta

def sample_delete_service():
    # Create a client
    client = metastore_v1beta.DataprocMetastoreClient()

    # Initialize request argument(s)
    request = metastore_v1beta.DeleteServiceRequest(
        name="name_value",
    )

    # Make the request
    operation = client.delete_service(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

# [END metastore_v1beta_generated_DataprocMetastore_DeleteService_sync]


text:
//------------------------------------------------------------------------------
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
//------------------------------------------------------------------------------
#include "pch.h"

#if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
#endif

#include "MainPage.xaml.h"

void ::CSC_Regex_Tester::MainPage::InitializeComponent()
{
    if (_contentLoaded)
    {
        return;
    }
    _contentLoaded = true;
    ::Windows::Foundation::Uri^ resourceLocator = ref new ::Windows::Foundation::Uri(L"ms-appx:///MainPage.xaml");
    ::Windows::UI::Xaml::Application::LoadComponent(this, resourceLocator, ::Windows::UI::Xaml::Controls::Primitives::ComponentResourceLocation::Application);
}

void ::CSC_Regex_Tester::MainPage::Connect(int __connectionId, ::Platform::Object^ __target)
{
    switch (__connectionId)
    {
        case 1:
            {
                this->txtTestString = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
            }
            break;
        case 2:
            {
                this->txtResult = safe_cast<::Windows::UI::Xaml::Controls::TextBlock^>(__target);
            }
            break;
        case 3:
            {
                this->tbRegexValue = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
                (safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(this->tbRegexValue))->TextChanged += ref new ::Windows::UI::Xaml::Controls::TextChangedEventHandler(this, (void (::CSC_Regex_Tester::MainPage::*)
                    (::Platform::Object^, ::Windows::UI::Xaml::Controls::TextChangedEventArgs^))&MainPage::tbRegexValue_TextChanged);
            }
            break;
        case 4:
            {
                this->tbTestString = safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(__target);
                (safe_cast<::Windows::UI::Xaml::Controls::TextBox^>(this->tbTestString))->TextChanged += ref new ::Windows::UI::Xaml::Controls::TextChangedEventHandler(this, (void (::CSC_Regex_Tester::MainPage::*)
                    (::Platform::Object^, ::Windows::UI::Xaml::Controls::TextChangedEventArgs^))&MainPage::tbTestString_TextChanged);
            }
            break;
    }
    _contentLoaded = true;
}

::Windows::UI::Xaml::Markup::IComponentConnector^ ::CSC_Regex_Tester::MainPage::GetBindingConnector(int __connectionId, ::Platform::Object^ __target)
{
    __connectionId;         // unreferenced
    __target;               // unreferenced
    return nullptr;
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<module>
	<name>blockuserinfo</name>
	<displayName><![CDATA[User info block]]></displayName>
	<version><![CDATA[0.4.0]]></version>
	<description><![CDATA[Adds a block that displays information about the customer.]]></description>
	<author><![CDATA[PrestaShop]]></author>
	<tab><![CDATA[front_office_features]]></tab>
	<is_configurable>0</is_configurable>
	<need_instance>0</need_instance>
	<limited_countries></limited_countries>
</module>


text:
namespace gin_helper {

// Only lock when lockers are used in current thread.
class Locker {
 public:
  explicit Locker(v8::Isolate* isolate);
  ~Locker();

  // disable copy
  Locker(const Locker&) = delete;
  Locker& operator=(const Locker&) = delete;

  // Returns whether current process is browser process, currently we detect it
  // by checking whether current has used V8 Lock, but it might be a bad idea.
  static inline bool IsBrowserProcess() { return g_is_browser_process; }

  static void SetIsBrowserProcess(bool is_browser_process);

 private:
  void* operator new(size_t size);
  void operator delete(void*, size_t);

  std::unique_ptr<v8::Locker> locker_;

  static bool g_is_browser_process;
};

}  // namespace gin_helper

#endif  // ELECTRON_SHELL_COMMON_GIN_HELPER_LOCKER_H_


text:
@interface GameViewController : UIViewController <ZLSwipeableViewDataSource, ZLSwipeableViewDelegate>

@end


text:
import pandas as pd
import numpy as np

import sklearn
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from sklearn.naive_bayes import GaussianNB
from sklearn.cross_validation import cross_val_score
from sklearn.feature_selection import SelectKBest
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

import preparation

df, y_train = preparation.load_data()
df = preparation.fill_missing(df)
texts = preparation.get_texts(df)
df = df.drop('boilerplate', axis=1)
X_train = preparation.integerize(df, ['alchemy_category'])

print("Fit vectorizer")
vectorizer = TfidfVectorizer(ngram_range=(1, 3), analyzer='word', stop_words='english', min_df=3)
vectorizer = vectorizer.fit(texts)
print("transform")
texts = vectorizer.transform(texts)

print("Perform logreg prediction")
rd = LogisticRegression(penalty='l2', dual=True, tol=0.0001,
                             C=1, fit_intercept=True, intercept_scaling=1.0,
                             class_weight=None, random_state=None)
print(cross_val_score(rd, texts, y_train, cv=10))

#pca = PCA(n_components=X_train.shape[1]-1)
#pca.fit(X_train, y_train)
#X_train = np.array(pca.transform(X_train))

#mm_scaler = MinMaxScaler()
#X_train = mm_scaler.fit_transform(X_train)

#skb = SelectKBest(k=10)
#skb.fit(X_train, y_train)
#print(skb.scores_)
#print(df.columns)
#for col, score, p in zip(df.columns, skb.scores_, skb.pvalues_):
#    print("%s: %f, %f" % (col, score, p))
#X_train = skb.transform(X_train)

#gnb = GaussianNB()
#print(cross_val_score(gnb, X_train, y_train, cv=10))

clf = DecisionTreeClassifier()
print(cross_val_score(clf, X_train, y_train, cv=10))

#for i in range(25, 100):
#    nn = KNeighborsClassifier(n_neighbors=i)
#    print(cross_val_score(nn, X_train, y_train, cv=10).mean())


text:
#pragma once
#include <aws/pricing/Pricing_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Pricing
{
namespace Model
{
  enum class FilterType
  {
    NOT_SET,
    TERM_MATCH
  };

namespace FilterTypeMapper
{
AWS_PRICING_API FilterType GetFilterTypeForName(const Aws::String& name);

AWS_PRICING_API Aws::String GetNameForFilterType(FilterType value);
} // namespace FilterTypeMapper
} // namespace Model
} // namespace Pricing
} // namespace Aws


text:
extern crate syn;

#[macro_use]
extern crate quote;

extern crate proc_macro;
use proc_macro::TokenStream;

use std::iter;
use syn::*;
use quote::Tokens;

struct Context {
    location_ident: Ident,
    location_expr: Expr,
    location_type: Ty,
    deref_self_expr: Expr,
}

impl Context {
    pub fn new() -> Self {
        Context {
            location_ident: Ident::from("location"),

            location_expr: Expr::from(ExprKind::Path(None, Path::from("location"))),

            location_type: Ty::Path(None, Path {
                global: false,
                segments: vec![PathSegment {
                    ident: Ident::from("Option"),
                    parameters: PathParameters::AngleBracketed(AngleBracketedParameterData {
                        lifetimes: vec![],
                        types: vec![Ty::Path(None, Path::from("Span"))],
                        bindings: vec![]
                    })
                }]
            }),

            deref_self_expr: Expr::from(ExprKind::Unary(
                UnOp::Deref,
                Box::new(Expr::from(ExprKind::Path(None, Path::from("self"))))
            ))
        }
    }

    fn expand_tracking_data(&self, path: Path, data: &VariantData, mutability: Mutability) -> Arm {
        let location_pat = Pat::Ident(BindingMode::ByRef(mutability), self.location_ident.clone(), None);

        let expr = self.location_expr.clone();

        let (pat, expr) = match *data {
            VariantData::Struct(_) => (
                Pat::Struct(path, vec![FieldPat {
                    ident: self.location_ident.clone(),
                    pat: Box::new(location_pat),
                    is_shorthand: true
                }], true),
                if data.fields().iter().any(|field| field.ident.as_ref() == Some(&self.location_ident) && field.ty == self.location_type) {
                    expr
                } else {
                    panic!("Struct does not containt `location: Option<Span>`")
                }
            ),
            VariantData::Tuple(ref fields) => (
                Pat::TupleStruct(path, {
                    let mut v = Vec::with_capacity(fields.len());
                    v.push(location_pat);
                    v.extend(iter::repeat(Pat::Wild).take(fields.len() - 1));
                    v
                }, None),
                if data.fields()[0].ty == self.location_type {
                    expr
                } else {
                    Expr::from(ExprKind::MethodCall(
                        Ident::from(if mutability == Mutability::Immutable { "tracking_ref" } else { "tracking_mut" }),
                        vec![],
                        vec![expr]
                    ))
                }
            ),
            VariantData::Unit => panic!("Empty unit is not trackable")
        };

        Arm {
            attrs: vec![],
            pats: vec![pat],
            guard: None,
            body: Box::new(expr)
        }
    }

    fn expand_tracking(&self, ast: &MacroInput, mutability: Mutability) -> Tokens {
        // Helper is provided for handling complex generic types correctly and effortlessly
        let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

        let (impl_name, method) = if mutability == Mutability::Immutable {
            (Ident::from("TrackingRef"), quote! {
                tracking_ref(&self) -> &Option
            })
        } else {
            (Ident::from("TrackingMut"), quote! {
                tracking_mut(&mut self) -> &mut Option
            })
        };

        // Used in the quasi-quotation below as `#name`
        let name = &ast.ident;

        let body = Expr::from(ExprKind::Match(
            Box::new(self.deref_self_expr.clone()),
            match ast.body {
                Body::Struct(ref data) => {
                    vec![self.expand_tracking_data(Path::from(name.clone()), data, mutability)]
                },
                Body::Enum(ref variants) => {
                    variants.iter().map(|var| {
                        let path = Path {
                            global: false,
                            segments: vec![
                                PathSegment::from(name.clone()),
                                PathSegment::from(var.ident.clone())
                            ]
                        };
                        self.expand_tracking_data(path, &var.data, mutability)
                    }).collect()
                }
            }
        ));

        quote! {
            // The generated impl
            impl #impl_generics #impl_name for #name #ty_generics #where_clause {
                fn #method {
                    #body
                }
            }
        }
    }

    fn expand_untrack_data(&self, path: Path, data: &VariantData) -> Arm {
        let (pat, idents) = match *data {
            VariantData::Struct(ref fields) => {
                let mut field_pats = Vec::with_capacity(fields.len());
                let mut idents = Vec::with_capacity(fields.len());

                for field in fields {
                    let ident = field.ident.as_ref().unwrap();

                    field_pats.push(FieldPat {
                        ident: ident.clone(),
                        pat: Box::new(Pat::Ident(BindingMode::ByRef(Mutability::Mutable), ident.clone(), None)),
                        is_shorthand: true
                    });

                    idents.push(ident.clone());
                }

                (Pat::Struct(path, field_pats, false), idents)
            },
            VariantData::Tuple(ref fields) => {
                let mut pats = Vec::with_capacity(fields.len());
                let mut idents = Vec::with_capacity(fields.len());

                for i in 0..fields.len() {
                    let ident = Ident::from(format!("_f{}", i));

                    pats.push(Pat::Ident(BindingMode::ByRef(Mutability::Mutable), ident.clone(), None));

                    idents.push(ident);
                }

                (Pat::TupleStruct(path, pats, None), idents)
            },
            VariantData::Unit => {
                (Pat::Path(None, path), vec![])
            }
        };

        let expr = Expr::from(ExprKind::Block(BlockCheckMode::Default, Block {
            stmts: idents.into_iter().map(|ident| {
                Stmt::Semi(Box::new(Expr::from(ExprKind::MethodCall(
                    Ident::from("untrack"),
                    vec![],
                    vec![Expr::from(ExprKind::Path(None, Path::from(ident)))]
                ))))
            }).collect()
        }));

        Arm {
            attrs: vec![],
            pats: vec![pat],
            guard: None,
            body: Box::new(expr)
        }
    }

    pub fn expand_tracking_ref(&self, ast: &MacroInput) -> Tokens {
        self.expand_tracking(ast, Mutability::Immutable)
    }

    pub fn expand_tracking_mut(&self, ast: &MacroInput) -> Tokens {
        self.expand_tracking(ast, Mutability::Mutable)
    }

    pub fn expand_untrack(&self, ast: &MacroInput) -> Tokens {
        let mut generics = ast.generics.clone();

        let bound = TyParamBound::Trait(PolyTraitRef {
            bound_lifetimes: vec![],
            trait_ref: Path::from("Untrack")
        }, TraitBoundModifier::None);

        for ty in &mut generics.ty_params {
            ty.bounds.push(bound.clone());
        }

        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

        let name = &ast.ident;

        let body = Expr::from(ExprKind::Match(
            Box::new(self.deref_self_expr.clone()),
            match ast.body {
                Body::Struct(ref data) => {
                    vec![self.expand_untrack_data(Path::from(name.clone()), data)]
                },
                Body::Enum(ref variants) => {
                    variants.iter().map(|var| {
                        let path = Path {
                            global: false,
                            segments: vec![
                                PathSegment::from(name.clone()),
                                PathSegment::from(var.ident.clone())
                            ]
                        };
                        self.expand_untrack_data(path, &var.data)
                    }).collect()
                }
            }
        ));

        quote! {
            // The generated impl
            impl #impl_generics Untrack for #name #ty_generics #where_clause {
                fn untrack(&mut self) {
                    #body
                }
            }
        }
    }
}

macro_rules! register_tracking_derive {
    ($for_trait:ident, $method:ident) => {
        #[proc_macro_derive($for_trait)]
        pub fn $method(input: TokenStream) -> TokenStream {
            let source = input.to_string();
            let context = Context::new();

            // Parse the string representation into a syntax tree
            let ast = parse_macro_input(&source).unwrap();

            // Build the output, possibly using quasi-quotation
            let expanded = context.$method(&ast);

            // Parse back to a token stream and return it
            expanded.parse().unwrap()
        }
    }
}

register_tracking_derive!(TrackingRef, expand_tracking_ref);
register_tracking_derive!(TrackingMut, expand_tracking_mut);
register_tracking_derive!(Untrack, expand_untrack);


text:
#import "Keeva.h"
#import "KeevaDatabase.h"
#import "KeevaEncryptor.h"
#import "KeevaConfig.h"
#import "KeevaUtils.h"

@interface Keeva()

@property(nonatomic,retain) KeevaDatabase *kvDatabase;
@property(nonatomic,retain) NSString *storageName;
@property(nonatomic,retain) NSString *key;

@end

@implementation Keeva

- (id)initWithName:(NSString*)storageName andSecret:(NSString*)secret {
    @synchronized(self) {
        if (self = [super init]) {
            if (!secret || [secret length]==0) {
                [NSException raise:@"Invalid secret value" format:@"You must initialize Keeva with a secret. storageName: %@", storageName];
            }
            self.storageName = storageName;
            self.key = [KeevaUtils keyFromSecret:secret];
            self.kvDatabase = [[KeevaDatabase alloc] initWithName:storageName];
        }
        return self;
    }
}

- (NSString*)getValueForKey:(NSString*)key {
    key = [KeevaEncryptor encryptString:key withKey:self.key];
    NSString* val = [self.kvDatabase getValForKey:key];
    if (val && [val length]>0){
        return [KeevaEncryptor decryptToString:val withKey:self.key];
    }

    return NULL;
}

- (void)setValue:(NSString*)val forKey:(NSString*)key {
    key = [KeevaEncryptor encryptString:key withKey:self.key];
    [self.kvDatabase setVal:[KeevaEncryptor encryptString:val withKey:self.key] forKey:key];
}

- (void)deleteValueForKey:(NSString*)key {
    key = [KeevaEncryptor encryptString:key withKey:self.key];
    [self.kvDatabase deleteKeyValWithKey:key];
}

- (NSDictionary*)getKeysValuesForNonEncryptedQuery:(NSString*)query {
    NSDictionary* dbResults = [self.kvDatabase getKeysValsForQuery:query];
    NSMutableDictionary* results = [NSMutableDictionary dictionary];
    NSArray* keys = [dbResults allKeys];
    for (NSString* key in keys) {
        NSString* val = dbResults[key];
        if (val && [val length]>0){
            NSString* valDec = [KeevaEncryptor decryptToString:val withKey:self.key];
            if (valDec && [valDec length]>0){
                [results setObject:valDec forKey:key];
            }
        }
    }

    return results;
}
- (NSArray*)getValuesForNonEncryptedQuery:(NSString*)query {
    return [self getValuesForNonEncryptedQuery:query withLimit:0];
}

- (NSArray*)getValuesForNonEncryptedQuery:(NSString*)query withLimit:(int)limit {
    NSArray* vals = [self.kvDatabase getValsForQuery:query withLimit:limit];
    NSMutableArray* results = [NSMutableArray array];
    for (NSString* val in vals) {
        if (val && [val length]>0){
            NSString* valDec = [KeevaEncryptor decryptToString:val withKey:self.key];
            if (valDec && [valDec length]>0){
                [results addObject:valDec];
            }
        }
    }

    return results;
}

- (NSString*)getOneForNonEncryptedQuery:(NSString*)query {
    NSString* val = [self.kvDatabase getOneForQuery:query];
    if (val && [val length]>0){
        NSString* valDec = [KeevaEncryptor decryptToString:val withKey:self.key];
        if (valDec && [valDec length]>0){
            return valDec;
        }
    }

    return NULL;
}

- (int)getCountForNonEncryptedQuery:(NSString*)query {
    return [self.kvDatabase getCountForQuery:query];
}

- (NSString*)getValueForNonEncryptedKey:(NSString*)key {
    NSString* val = [self.kvDatabase getValForKey:key];
    if (val && [val length]>0){
        return [KeevaEncryptor decryptToString:val withKey:self.key];
    }

    return NULL;
}

- (NSArray *)getEncryptedKeys {
    NSArray *encryptedKeys = [self.kvDatabase getAllKeys];
    NSMutableArray *resultKeys = [NSMutableArray array];

    for (NSString *encryptedKey in encryptedKeys) {
        @try {
            NSString *unencryptedKey = [KeevaEncryptor decryptToString:encryptedKey withKey:self.key];
            if (unencryptedKey) {
                [resultKeys addObject:unencryptedKey];
            }
        }
        @catch (NSException *exception) {
            LogDebug(TAG, ([NSString stringWithFormat:@"Exception while decrypting all keys: %@", exception.description]));
        }
    }

    return resultKeys;
}

- (void)setValue:(NSString*)val forNonEncryptedKey:(NSString*)key {
    [self.kvDatabase setVal:[KeevaEncryptor encryptString:val withKey:self.key] forKey:key];
}

- (void)deleteValueForNonEncryptedKey:(NSString*)key {
    [self.kvDatabase deleteKeyValWithKey:key];
}

- (void)purge {
    [self.kvDatabase purgeDatabase];
}

static NSString* TAG = @"KEEVA Keeva";

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Daenney</title>
    <meta name="description" content="Working on the future while maintaining the past." />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//daenney.github.io/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//daenney.github.io/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://daenney.github.io" />
    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Daenney" href="https://daenney.github.io/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Home

puppet-pypuppetdb-puppetboard-community

                    A 1-post collection

        Page 1 of 1

Open source identity and abandonment issues

Today I made one of the hardest decisions I’ve made in a while. I decided to give up maintainership of two projects that I »

             on puppet pypuppetdb puppetboard community
            <time class="post-date" datetime="2015-04-20">20 April 2015</time>

        Page 1 of 1

Daenney © 2015

Proudly published with HubPress


text:
import flickrapi
import psycopg2
import json
import time

# 图片经纬度信息类
class photo_coordinates():
    def __init__(self, photo_id, photo_owner, photo_post_date, photo_take_date, photo_lat, photo_lon, photo_accuracy,
                 neighbourhood, locality, county, region, country, geotag):
        self.photo_id = photo_id
        self.photo_owner = photo_owner
        self.photo_upload = photo_post_date
        self.photo_take_date = photo_take_date
        self.photo_lat = photo_lat
        self.photo_lon = photo_lon
        self.photo_accuracy = photo_accuracy
        self.neighbourhood = neighbourhood
        self.locality = locality
        self.county = county
        self.country = country
        self.region = region
        self.geotag = geotag

    # 输入经纬度等信息
    def input_coordinates(self, connection, cursor):
        try:
            sql_command_update = "UPDATE photo SET owner='{0}',photo_upload={1},photo_take_date='{2}'," \
                                 "lat={3},lon={4},accuracy={5},neighbourhood='{6}'," \
                                 "locality='{7}',county='{8}',country='{9}',region='{10}'," \
                                 "geotag='{11}' WHERE id={12}".format(
                self.photo_owner, self.photo_upload, self.photo_take_date, self.photo_lat, self.photo_lon,
                self.photo_accuracy, self.neighbourhood, self.locality, self.county,
                self.country, self.region, self.geotag, self.photo_id)
            cursor.execute(sql_command_update)
            connection.commit()
            print("Success Input Coordinates!")
            return True
        except Exception as e:
            with open('log.txt', 'a') as log_file:
                log_file.writelines(str(e))
            connection.rollback()
            return False

# 连接数据库
def db_connect():
    connection = psycopg2.connect(database="EmotionMap", user="postgres",
                                  password="postgres", host="127.0.0.1", port="5432")
    cursor = connection.cursor()
    print("Database Connection has been opened completely!")
    return connection, cursor

# 查询需要补充信息的照片
def query_photo(db_connection, db_cursor):
    sql_command_select = "SELECT id FROM photo WHERE start_info='FALSE' LIMIT 1"
    db_cursor.execute(sql_command_select)
    photo = db_cursor.fetchone()
    if photo is not None:
        photo_id = photo[0]
        try:
            sql_command_update = "UPDATE photo SET start_info='TRUE' WHERE id={0}".format(photo_id)
            db_cursor.execute(sql_command_update)
            db_connection.commit()
            return photo_id
        except Exception as e:
            with open('log.txt', 'a') as log_file:
                log_file.writelines(str(e))
            db_connection.rollback()
            return None
    else:
        return None

# flickr api信息
def flickrAPI():
    api_key = u'199ed59000c39dd0844b59d01fa7570c'
    api_secret = u'4a2ce28f1bb8a1fe'
    flickr = flickrapi.FlickrAPI(api_key, api_secret, cache=True)
    return flickr

# 获取图片的经纬度坐标等信息
def get_photo_coordinates(connection, cursor, photo_id):
    flickr = flickrAPI()
    photo_info = flickr.photos.getInfo(photo_id=photo_id, format='json')
    photo_info = photo_info.decode()
    photo_info = json.loads(photo_info)
    # 解析结果
    try:
        photo_owner = photo_info["photo"]["owner"]["nsid"]
    except:
        photo_owner = ""
    try:
        photo_post_date = photo_info["photo"]["dates"]["posted"]
    except:
        photo_post_date = ""
    try:
        photo_take_date = photo_info["photo"]["dates"]["taken"]
    except:
        photo_take_date = ""
    try:
        photo_lat = photo_info["photo"]["location"]["latitude"]
    except:
        photo_lat = ""
    try:
        photo_lon = photo_info["photo"]["location"]["longitude"]
    except:
        photo_lon = ""
    try:
        photo_accuracy = photo_info["photo"]["location"]["accuracy"]
    except:
        photo_accuracy = ""
    try:
        neighbourhood = photo_info["photo"]["location"]["neighbourhood"]["_content"]
    except:
        neighbourhood = ""
    try:
        locality = photo_info["photo"]["location"]["locality"]["_content"]
    except:
        locality = ""
    try:
        county = photo_info["photo"]["location"]["county"]["_content"]
    except:
        county = ""
    try:
        region = photo_info["photo"]["location"]["region"]["_content"]
    except:
        region = ""
    try:
        country = photo_info["photo"]["location"]["country"]["_content"]
    except:
        country = ""
    try:
        geotag = ""
        for tag in photo_info["photo"]["tags"]["tag"]:
            tag_raw = tag['raw']
            geotag = "{0}{1};".format(str(geotag), str(tag_raw))
    except:
        geotag = ""
    # 将信息录入数据库
    coordinates = photo_coordinates(photo_id, photo_owner, photo_post_date, photo_take_date, photo_lat, photo_lon,
                                    photo_accuracy, neighbourhood, locality, county, region, country, geotag)
    return coordinates.input_coordinates(connection, cursor)

# 关闭数据库
def close_connection(connection):
    try:
        connection.close()
        print("Database Connection has been closed completely!")
        return True
    except Exception as e:
        with open('log.txt', 'a') as log_file:
            log_file.writelines(str(e))

# 主要步骤
if __name__ == '__main__':
    connection, cursor = db_connect()
    photo = query_photo(connection, cursor)
    while photo is not None:
        try:
            get_photo_coordinates(connection, cursor, photo)
            time.sleep(1)
            photo = query_photo(connection, cursor)
        except Exception as  e:
            with open('log.txt', 'a') as log_file:
                log_file.writelines(str(e))
    close_connection(connection)
    print("All photos have information!")


text:
'use strict';

/**
 * Builds the component config object from its incremental dom call's
 * arguments.
 * @param {!Array} args
 * @return {!Object}
 */
export function buildConfigFromCall(args) {
	var config = {};
	if (args[1]) {
		config.key = args[1];
	}
	var attrsArr = (args[2] || []).concat(args.slice(3));
	for (var i = 0; i < attrsArr.length; i += 2) {
		config[attrsArr[i]] = attrsArr[i + 1];
	}
	return config;
}

/**
 * Builds an incremental dom call array from the given tag and config object.
 * @param {string} tag
 * @param {!Object} config
 * @return {!Array}
 */
export function buildCallFromConfig(tag, config) {
	var call = [tag, config.key, []];
	var keys = Object.keys(config);
	for (var i = 0; i < keys.length; i++) {
		if (keys[i] !== 'children') {
			call.push(keys[i], config[keys[i]]);
		}
	}
	return call;
}


text:
Add or remove Postfix configuration

## Requirements

- saslpasswd2
- sasldblistusers2

## Synopsis

- Modifies a sasldb file

## Parameters

| Parameter | Choices/Defaults | Comments |
| :-------- | :--------------- | :----- |
| dest      | | The file to modify |
| name      | | Name of the user to mange |
| password  | | Required when `state=present` |
| realm     | Default: `hostname` | Name of the realm to use |
| state     | **Choices**:

absent

**present**

 | Whether the use should be present or absent |

## Examples

```yaml
- sasldb:
    dest: /var/spool/postfix/etc/sasldb2
    name: test
    realm: relay.example.com
    password: testpass
```


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resources.generated;

import com.azure.core.util.Context;

/** Samples for Subscriptions ListLocations. */
public final class SubscriptionsListLocationsSamples {
    /*
     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2021-01-01/examples/GetLocationsWithExtendedLocations.json
     */
    /**
     * Sample code: GetLocationsWithExtendedLocations.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void getLocationsWithExtendedLocations(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .genericResources()
            .manager()
            .subscriptionClient()
            .getSubscriptions()
            .listLocations("291bba3f-e0a5-47bc-a099-3bdcb2a50a05", true, Context.NONE);
    }

    /*
     * x-ms-original-file: specification/resources/resource-manager/Microsoft.Resources/stable/2021-01-01/examples/GetLocations.json
     */
    /**
     * Sample code: GetLocationsWithASubscriptionId.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void getLocationsWithASubscriptionId(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .genericResources()
            .manager()
            .subscriptionClient()
            .getSubscriptions()
            .listLocations("291bba3f-e0a5-47bc-a099-3bdcb2a50a05", null, Context.NONE);
    }
}


text:
package com.google.cloud.genomics.api.client.commands;

import com.google.api.client.util.store.MemoryDataStoreFactory;
import com.google.api.services.genomics.GenomicsScopes;
import com.google.api.services.genomics.model.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;

import static org.junit.Assert.assertTrue;

@RunWith(JUnit4.class)
public class ExportVariantsCommandTest extends CommandTest {

  @Test
  public void testScopes() throws Exception {
    assertTrue(new ExportVariantsCommand().getScopes()
        .contains(GenomicsScopes.BIGQUERY));
  }

  @Test
  public void testExportVariants() throws Exception {
    ExportVariantsCommand command = new ExportVariantsCommand();
    command.setDataStoreFactory(new MemoryDataStoreFactory());

    command.variantSetId = "abc";
    command.projectNumber = 3L;
    command.bigqueryDataset = "bigqueryDataset";
    command.bigqueryTable = "bigqueryTable";

    // Get the dataset
    Mockito.when(datasets.get("abc")).thenReturn(datasetGet);
    Mockito.when(datasetGet.execute()).thenReturn(
        new Dataset().setId("abc").setName("1kg"));

    // Export them
    Mockito.when(variantSets.export(
        Mockito.anyString(), Mockito.any(ExportVariantSetRequest.class)))
        .thenReturn(variantExport);
    Mockito.when(variantExport.execute()).thenReturn(
        new ExportVariantSetResponse().setJobId("8675309"));

    // Get the job
    Mockito.when(jobs.get("8675309")).thenReturn(jobGet);
    Mockito.when(jobGet.execute()).thenReturn(new Job().setDetailedStatus("description1"));

    command.handleRequest(genomics);

    String output = outContent.toString();
    assertTrue(output, output.contains("Exporting variants for variant set 1kg"));
    assertTrue(output, output.contains("Export job:"));
    assertTrue(output, output.contains("description1"));
  }

}


text: Web Project for 425 class. Website for hair salon.


text:
<resources>
  <plurals name="plural1">
    <<error>item</error>/>

    <item quantity="<error>aba</error>"/>
    <item quantity="zero"></item>
  </plurals>
</resources>


text:
import sinon from 'sinon';

import { ParserContext } from '../../src/parsers/parser-context';
import { PrinterContext } from '../../src/printers';
import { TransformerContext } from '../../src/transformers';

import { createTransformerOptions } from './factories';

export function parserContextStub(): sinon.SinonStubbedInstance<ParserContext> {
  return {
    parse: sinon.stub(),
  };
}

export function printerContextStub(): sinon.SinonStubbedInstance<PrinterContext> {
  return {
    print: sinon.stub(),
  };
}

export function transformerContextStub(): sinon.SinonStubbedInstance<TransformerContext> {
  return {
    transform: sinon.stub(),
    options: createTransformerOptions(),
  };
}


text:
namespace velox {

struct VeloxConfig {
  VeloxConfig()
      : confidence_level_(0.95), measurement_time_(10000), num_resamples_(100000),
        num_measurements_(100), warm_up_time_(5000), estimate_clock_cost_(false) {}

  // Used when calculating the https://en.wikipedia.org/wiki/Confidence_interval
  // of the various statistics
  VeloxConfig &confidence_level(const double cl) {
    assert(cl > 0.0 && cl < 1.0 && "Confidence level must be between 0 and 1");
    confidence_level_ = cl;
    return *this;
  }

  double confidence_level() const { return confidence_level_; }

  // The amount of time to use for taking num_measurements
  // This is not a strict upper bound, and the actual measurement time will probably be
  // a bit larger.
  VeloxConfig &measurement_time(const Ms ms) {
    assert(ms.count() > 0 && "Must measure for at least 1 ms");
    measurement_time_ = ms;
    return *this;
  }

  std::chrono::milliseconds measurement_time() const { return measurement_time_; }

  // Number of resamples to use for
  // http://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
  VeloxConfig &num_resamples(const std::uint32_t n) {
    assert(n && "Must resample at least once");
    num_resamples_ = n;
    return *this;
  }

  std::uint32_t num_resamples() const { return num_resamples_; }

  // The number of measurements to take
  VeloxConfig &num_measurements(const std::uint32_t n) {
    assert(n && "At least one sample must be taken");
    num_measurements_ = n;
    return *this;
  }

  std::uint32_t num_measurements() const { return num_measurements_; }

  // How long to warm up for
  VeloxConfig &warm_up_time(const Ms ms) {
    assert(ms.count() > 0 && "Must warm up for at least 1 ms");
    warm_up_time_ = ms;
    return *this;
  }

  std::chrono::milliseconds warm_up_time() const { return warm_up_time_; }

  // Whether to estimate the clock cost
  // Currently the clock cost is only reported, it is not used in any
  // calculations
  VeloxConfig &estimate_clock_cost(bool estimate) {
    estimate_clock_cost_ = estimate;
    return *this;
  }

  bool estimate_clock_cost() const { return estimate_clock_cost_; }

private:
  double confidence_level_;
  Ms measurement_time_;
  std::uint32_t num_resamples_;
  std::uint32_t num_measurements_;
  Ms warm_up_time_;
  bool estimate_clock_cost_;
};
}

#endif // VELOX_VELOX_CONFIG_H_INCLUDED


text:
'use strict';

module.exports = !process.mainModule;


text:
Block Chain Explorer Client for altcoins.

Extracted from BCE project.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'bce-client', github: 'madzebra/bce-client'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install bce-client

## Usage

```ruby
require 'bce-client'

bce_client = BceClient::Client.new \
  username: 'rpc_user',
  password: 'rpc_pass',
  host: '127.0.0.1',
  port: '19092'

bce_client.block(1).decode_with_tx # => Array with block info + all decoded txs

bce_client.network_info # => hash with getinfo content
bce_client.network_peer_info # => Array of connected peers
```

## Contributing

1. Fork it ( https://github.com/madzebra/bce-client/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
//The MIT License (MIT)
//
//Copyright (c) 2013 Alterplay
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import <UIKit/UIKit.h>
#import "APPinView.h"

@protocol APPinViewControllerDelegate;
@interface APPinViewController : UIViewController <APPinViewDelegate>
@property (weak, nonatomic) IBOutlet APPinView *pinCodeView;

//You can set it on order to compare entered pin code with this var.
@property (nonatomic, strong) NSString *pinCodeToCheck;

//Failed attempts incrementer
@property (nonatomic, readonly) NSUInteger failedAttempts;

//Set this property to YES if you want to reset your current pinCode.
//Note: self.pinCodeToCheck must be non nil; Will raise an exception othervise
@property (nonatomic) BOOL shouldResetPinCode;

//Delegate
@property (nonatomic, weak) id <APPinViewControllerDelegate> delegate;

//You can override it for initial properties
- (void)commonInit;

/*
 Strings.
 You can override all of them to show messages like alerts, set labels, etc...
 */

@property (nonatomic, strong) NSString *enterYourPinString;
@property (nonatomic, strong) NSString *createYourPinString;
@property (nonatomic, strong) NSString *pinVerifiedString;

@property (nonatomic, strong) NSString *pinsDontMatchTryOnceAgainString;
@property (nonatomic, strong) NSString *pinCreatedString;
@property (nonatomic, strong) NSString *enterOnceAgainString;

/*

 If not overrided, all of them will just NSLog about what message was shown.
 You should override them to show message in your custom UI (labels, alerts, etc...);

 */

- (void)showCreateThePinMessage;
- (void)showEnterYourPinMessage;
- (void)showPinsDontMatchMessage;
- (void)showPinCreatedMessage;
- (void)showEnterOnceAgainMessage;
- (void)showPinVerifiedMessage;
@end

@protocol APPinViewControllerDelegate <NSObject>
@optional

/*
 Will be called when pinCodeToCheck isEqualTo: entered PinCode
 */

- (void)pinCodeViewController:(APPinViewController *)controller didVerifiedPincodeSuccessfully:(NSString *)pinCode;

/*
 Will be called when entered pin code don't match pinCodeToCheck;
 */

- (void)pinCodeViewController:(APPinViewController *)controller didFailVerificationWithCount:(NSUInteger)failsCount;

/*
 Will be called when pin code created
 */

- (void)pinCodeViewController:(APPinViewController *)controller didCreatePinCode:(NSString *)pinCode;

/*
 Will be called when pin code changed
 */

- (void)pinCodeViewController:(APPinViewController *)controller didChangePinCode:(NSString *)pinCode;

@end


text:
package org.mybatis.scala.samples.delete

import org.mybatis.scala.mapping._
import org.mybatis.scala.config._
import org.mybatis.scala.session._
import org.mybatis.scala.samples.util._

object DeleteSample {

  // Simple Person POJO
  class Person {
    var id : Int = _
    var firstName : String = _
    var lastName : String = _
  }

  // Simple select method
  val findAll = new SelectList[Person] {
    def xsql =
      <xsql>
        SELECT id_ as id, first_name_ as firstName, last_name_ as lastName
        FROM person
        ORDER BY id_
      </xsql>
  }

  val findMaxId = new SelectOne[Int] {
    def xsql =
      <xsql>
        SELECT MAX(id_) FROM person
      </xsql>
  }

  val deletePersonById = new Delete[Int] {
    def xsql =
      <xsql>
        DELETE FROM person WHERE id_ = #{{id}}
      </xsql>
  }

  val deletePersonContacts = new Delete[Int] {
    def xsql =
      <xsql>
        DELETE FROM contact_info WHERE owner_id_ = #{{id}}
      </xsql>
  }

  // Load datasource configuration
  val config = Configuration("mybatis.xml")

  // Create a configuration space, add the data access method
  config.addSpace("ns1") { space =>
    space += findAll
    space += findMaxId
    space += deletePersonById
    space += deletePersonContacts
    space ++= DBSchema
    space ++= DBSampleData
  }

  // Build the session manager
  val db = config.createPersistenceContext

  // Do the Magic ...
  def main(args : Array[String]) : Unit = {

    db.transaction { implicit session =>

      DBSchema.create
      DBSampleData.populate

      println("Before =>")
      for (p <- findAll())
        println( "\tPerson(%d): %s %s".format(p.id, p.firstName, p.lastName) )

      for(id <- findMaxId()) {
        deletePersonContacts(id)
        deletePersonById(id)
      }

      println("After =>")
      for (p <- findAll())
        println( "\tPerson(%d): %s %s".format(p.id, p.firstName, p.lastName) )

    }

  }

}


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

<ruleset name="Second Test RuleSet"
         xmlns="http://pmd.sf.net/ruleset/1.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
         xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">

    <description>First description...</description>

    <rule ref="rulesets/set1.xml/RuleTwoInFirstRuleSet" />
    <rule ref="rulesets/set2.xml/RuleOneInSecondRuleSet" />
</ruleset>


text:
<!DOCTYPE html>

	<link rel="stylesheet" href="../_style.css">

PageFragment Test Page

This page contains elements for testing the functionality of the PageFragment base class.

				A simple page fragment

This is a page fragment (DIV)

				An invisible page fragment

						This is an invisible page fragment (DIV)

				A page fragment with attributes

						This is a page fragment with attributes: foo, bar

				A page fragment with style

						This is a page fragment with styles: "text-decoration: underline;"

				A enabled page fragment

					<input id="enabled">

				A disabled page fragment

					<input id="disabled" disabled>

				A input field for changing attributes

					<input id="textField" type="text">


text:
'use strict';

module.exports = (input, output) => {
	const file = input.read();
	Object.assign(file, {
		fullPath: file.fullPath.replace(/\.[^\.]+$/i, '.css'), // change extension
		preprocessed: true,
	});
	output.send(file);
};


text:
//
// BIM IFC export alternate UI library: this library works with Autodesk(R) Revit(R) to provide an alternate user interface for the export of IFC files from Revit.
// Copyright (C) 2015  Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Autodesk.Revit.DB;
using Autodesk.Revit.DB.IFC;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace Revit.IFC.Common.Extensions
{
    public class IFCAddress
    {
        private Schema m_schema = null;
        private static Guid s_schemaId = new Guid("79EE6AD8-8A45-49B1-AB13-DDDB128A9EFE");
        private const String s_addressMapField = "IFCAddressMapField";  // Don't change this name, it affects the schema.

        private const String s_addressPurpose = "Purpose";
        private const String s_addressDescription = "Description";
        private const String s_addressUserDefinedPurpose = "UserDefinedPurpose";
        private const String s_addressInternalLocation = "InternalLocation";
        private const String s_addressAddressLine1 = "AddressLine1";
        private const String s_addressAddressLine2 = "AddressLine2";
        private const String s_addressPOBox = "PostalBox";
        private const String s_addressTownOrCity = "Town";
        private const String s_addressRegionOrState = "Region";
        private const String s_addressPostalCode = "PostalCode";
        private const String s_addressCountry = "Country";

        /// <summary>
        /// IFC address initialization
        /// </summary>
        public IFCAddress()
        {
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema == null)
            {
                SchemaBuilder addressBuilder = new SchemaBuilder(s_schemaId);
                addressBuilder.SetSchemaName("IFCAddress");
                addressBuilder.AddMapField(s_addressMapField, typeof(String), typeof(String));
                m_schema = addressBuilder.Finish();
            }
        }

        /// <summary>
        /// Get saved addresses in Storage. Currently only one address is supported
        /// </summary>
        /// <param name="document">The document storing the saved address.</param>
        /// <param name="schema">The schema for address.</param>
        /// <returns>List of stored addresses</returns>
        private IList<DataStorage> GetAddressInStorage(Document document, Schema schema)
        {
            FilteredElementCollector collector = new FilteredElementCollector(document);
            collector.OfClass(typeof(DataStorage));
            Func<DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid());

            return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>();
        }

        /// <summary>
        /// Update the address saved into the extensible storage using values from the UI
        /// </summary>
        /// <param name="document">The document storing the saved address.</param>
        /// <param name="addressItem">address information from the UI to be saved into extensible storage</param>
        public void UpdateAddress(Document document, IFCAddressItem addressItem)
        {
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                IList<DataStorage> oldSavedAddress = GetAddressInStorage(document, m_schema);
                if (oldSavedAddress.Count > 0)
                {
                    Transaction deleteTransaction = new Transaction(document, "Delete old IFC address");
                    deleteTransaction.Start();
                    List<ElementId> dataStorageToDelete = new List<ElementId>();
                    foreach (DataStorage dataStorage in oldSavedAddress)
                    {
                        dataStorageToDelete.Add(dataStorage.Id);
                    }
                    document.Delete(dataStorageToDelete);
                    deleteTransaction.Commit();
                }
            }

            // Update the address using the new information
            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                Transaction transaction = new Transaction(document, "Update saved IFC Address");
                transaction.Start();

                DataStorage addressStorage = DataStorage.Create(document);

                Entity mapEntity = new Entity(m_schema);
                IDictionary<string, string> mapData = new Dictionary<string, string>();
                if (addressItem.Purpose != null) mapData.Add(s_addressPurpose, addressItem.Purpose.ToString());
                if (addressItem.Description != null) mapData.Add(s_addressDescription, addressItem.Description.ToString());
                if (addressItem.UserDefinedPurpose != null) mapData.Add(s_addressUserDefinedPurpose, addressItem.UserDefinedPurpose.ToString());
                if (addressItem.InternalLocation != null) mapData.Add(s_addressInternalLocation, addressItem.InternalLocation.ToString());
                if (addressItem.AddressLine1 != null) mapData.Add(s_addressAddressLine1, addressItem.AddressLine1.ToString());
                if (addressItem.AddressLine2 != null) mapData.Add(s_addressAddressLine2, addressItem.AddressLine2.ToString());
                if (addressItem.POBox != null) mapData.Add(s_addressPOBox, addressItem.POBox.ToString());
                if (addressItem.TownOrCity != null) mapData.Add(s_addressTownOrCity, addressItem.TownOrCity.ToString());
                if (addressItem.RegionOrState != null) mapData.Add(s_addressRegionOrState, addressItem.RegionOrState.ToString());
                if (addressItem.PostalCode != null) mapData.Add(s_addressPostalCode, addressItem.PostalCode.ToString());
                if (addressItem.Country != null) mapData.Add(s_addressCountry, addressItem.Country.ToString());

                mapEntity.Set<IDictionary<string, String>>(s_addressMapField, mapData);
                addressStorage.SetEntity(mapEntity);

                transaction.Commit();
            }
        }

        /// <summary>
        /// Get saved IFC address from the extensible storage.
        /// </summary>
        /// <param name="document">The document storing the saved address.</param>
        /// <param name="address">saved address information from the extensible storage.</param>
        /// <returns>returns status whether there is any saved address in the extensible storage.</returns>
        public bool GetSavedAddress(Document document, out IFCAddressItem address)
        {
            IFCAddressItem addressItemSaved = new IFCAddressItem();

            if (m_schema == null)
            {
                m_schema = Schema.Lookup(s_schemaId);
            }
            if (m_schema != null)
            {
                 IList<DataStorage> addressStorage = GetAddressInStorage(document, m_schema);

                if (addressStorage.Count > 0)
                {

                    // expected only one address in the storage
                    Entity savedAddress = addressStorage[0].GetEntity(m_schema);
                    IDictionary<string, string> savedAddressMap = savedAddress.Get<IDictionary<string, string>>(s_addressMapField);
                    if (savedAddressMap.ContainsKey(s_addressPurpose))
                        addressItemSaved.Purpose = savedAddressMap[s_addressPurpose];
                    if (savedAddressMap.ContainsKey(s_addressDescription))
                        addressItemSaved.Description = savedAddressMap[s_addressDescription];
                    if (savedAddressMap.ContainsKey(s_addressUserDefinedPurpose))
                        addressItemSaved.UserDefinedPurpose = savedAddressMap[s_addressUserDefinedPurpose];
                    if (savedAddressMap.ContainsKey(s_addressInternalLocation))
                        addressItemSaved.InternalLocation = savedAddressMap[s_addressInternalLocation];
                    if (savedAddressMap.ContainsKey(s_addressAddressLine1))
                        addressItemSaved.AddressLine1 = savedAddressMap[s_addressAddressLine1];
                    if (savedAddressMap.ContainsKey(s_addressAddressLine2))
                        addressItemSaved.AddressLine2 = savedAddressMap[s_addressAddressLine2];
                    if (savedAddressMap.ContainsKey(s_addressPOBox))
                        addressItemSaved.POBox = savedAddressMap[s_addressPOBox];
                    if (savedAddressMap.ContainsKey(s_addressTownOrCity))
                        addressItemSaved.TownOrCity = savedAddressMap[s_addressTownOrCity];
                    if (savedAddressMap.ContainsKey(s_addressRegionOrState))
                        addressItemSaved.RegionOrState = savedAddressMap[s_addressRegionOrState];
                    if (savedAddressMap.ContainsKey(s_addressPostalCode))
                        addressItemSaved.PostalCode = savedAddressMap[s_addressPostalCode];
                    if (savedAddressMap.ContainsKey(s_addressCountry))
                        addressItemSaved.Country = savedAddressMap[s_addressCountry];

                    address = addressItemSaved;
                    return true;
                }
            }

            address = addressItemSaved;
            return false;
        }
    }
}


text:
package config

type SearchConfig struct {
}

var DefaultSearchConfig = SearchConfig{}


text:
require 'spec_helper'

describe "the is_array function" do
  let(:scope) { PuppetlabsSpec::PuppetInternals.scope }

  it "should exist" do
    Puppet::Parser::Functions.function("is_array").should == "function_is_array"
  end

  it "should raise a ParseError if there is less than 1 arguments" do
    lambda { scope.function_is_array([]) }.should( raise_error(Puppet::ParseError))
  end

  it "should return true if passed an array" do
    result = scope.function_is_array([[1,2,3]])
    result.should(eq(true))
  end

  it "should return false if passed a hash" do
    result = scope.function_is_array([{'a'=>1}])
    result.should(eq(false))
  end

  it "should return false if passed a string" do
    result = scope.function_is_array(["asdf"])
    result.should(eq(false))
  end
end


text:
require 'bcrypt'

class UrlsController < ApplicationController
  include BCrypt
  before_filter :authenticate, :except => :redirect

  def index
    @urlEntry = UrlEntry.new
    @entries = UrlEntry.all

    respond_to do |format|
      format.html
      format.xml { render :xml => @entries }
    end
  end

  def create
    @urlEntry = UrlEntry.new(params[:url_entry])
    respond_to do |format|
      @urlEntry.url = "http://www.badattachment.com" unless @urlEntry.attachment.blank?
      if @urlEntry.save
        #Replace URL
        unless @urlEntry.attachment.blank?
          @urlEntry.url = "http://" + request.host + (request.port != 80 ? ":" + request.port.to_s : "") + @urlEntry.attachment.url
          @urlEntry.save
        end
        format.html { redirect_to(url_entries_path,
                      :notice => "URL entry successfully added!")}
        format.xml { render :xml => @urlEntry,
                     :status => :created }
      else
        format.html { redirect_to(url_entries_path,
                      :notice => "Error adding URL entry.")}
        format.xml { render :xml => @urlEntry.errors,
                            :status => unprocessable_entity }
      end
    end
  end

  def update
    @entry = UrlEntry.find(params[:id])

    respond_to do |format|
      if @entry.update_attributes(params[:id])
        format.html { redirect_to(url_entries_path,
                      :notice => "URL entry successfully updated!")}
        format.xml { head :ok }
      else
        format.html { redirect_to(url_entries_path,
                      :notice => "Error updating URL entry.")}
        format.xml { render :xml => @entry.errors,
                            :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @entry = UrlEntry.find(params[:id])
    @entry.destroy

    respond_to do |format|
      format.html { redirect_to(url_entries_url) }
      format.xml { head :ok }
    end
  end

  def redirect
    key = params[:key].blank? ? "default" : params[:key]
    @entry = UrlEntry.find_by_key(key) || not_found
    redirect_to @entry.url
  end

protected

  def authenticate
    authenticate_or_request_with_http_basic do |username, password|
      Password.new(Settings.site_password) == password
    end
  end
end


text:
using Database.Game;
using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Database.Tests.Helpers
{
  internal class DatabaseHelper
  {
    #region Public Methods

    /// <summary>
    /// Create a Database with the V0 schema
    /// </summary>
    /// <param name="path">Path the database should be created at</param>
    /// <returns>Whether the database was created</returns>
    public static bool CreateV0Database(string path)
    {
      SqliteConnection connection = new SqliteConnection(new SqliteConnectionStringBuilder()
      {
        DataSource = path
      }.ConnectionString);

      connection.Open();

      // Games table
      SqliteCommand command = connection.CreateCommand();
      command.CommandText = "CREATE TABLE Games (GameName text NOT NULL PRIMARY KEY," +
                            "AddedDate text NOT NULL, PC text NOT NULL, PS3 text NOT NULL," +
                            "PS4 text NOT NULL, PSVita text NOT NULL, OwnedStatus text, " +
                            "PlayedStatus text NOT NULL);";
      command.ExecuteNonQuery();

      // Settings table
      command.CommandText = "CREATE TABLE Settings (Key text NOT NULL PRIMARY KEY, " +
                            "Value text NOT NULL);";
      command.ExecuteNonQuery();

      // Add some data
      command.CommandText = "INSERT OR REPLACE INTO Games (GameName, AddedDate, PC, PS3, PS4, " +
                            "PSVita, OwnedStatus, PlayedStatus) VALUES ('The Last of Us', '" +
                             DateTime.Today.ToString() + "', 'False', 'True', 'False', " +
                             "'False', 'True', 'Complete')";
      command.ExecuteNonQuery();

      connection.Close();

      return CheckTableExists(path, "Games") && CheckTableExists(path, "Settings");
    }

    /// <summary>
    /// Drop a table from the database
    /// </summary>
    /// <param name="path">Path to the database file</param>
    /// <param name="tableName">Name of the table to drop</param>
    /// <returns>Whether the given table exists or not</returns>
    public static bool DropTable(string path, string tableName)
    {
      SqliteConnection connection = new SqliteConnection(new SqliteConnectionStringBuilder()
      {
        DataSource = path
      }.ConnectionString);

      connection.Open();

      // Games table
      SqliteCommand command = connection.CreateCommand();
      command.CommandText = "DROP TABLE " + tableName;
      command.ExecuteNonQuery();

      connection.Close();

      return !CheckTableExists(path, tableName);
    }

    /// <summary>
    /// Get the current schema version of the database
    /// </summary>
    /// <param name="path">Path to existing database</param>
    /// <returns>Schema version as int</returns>
    public static int GetCurrentSchema(string path)
    {
      SqliteConnection connection = new SqliteConnection(new SqliteConnectionStringBuilder()
      {
        DataSource = path
      }.ConnectionString);

      connection.Open();

      SqliteCommand command = connection.CreateCommand();
      command.CommandText = "SELECT Value FROM Settings WHERE Key = 'SchemaVersion'";

      int result = Convert.ToInt32(command.ExecuteScalar());
      connection.Close();

      return result;
    }

    #endregion Public Methods

    #region Private Methods

    /// <summary>
    /// Check if a table with the given name exists in the database
    /// </summary>
    /// <param name="path">Path to the database</param>
    /// <param name="tableName">Name of the table to check</param>
    /// <returns>If the table exists in the database</returns>
    private static bool CheckTableExists(string path, string tableName)
    {
      SqliteConnection connection = new SqliteConnection(new SqliteConnectionStringBuilder()
      {
        DataSource = path
      }.ConnectionString);

      connection.Open();

      SqliteCommand command = connection.CreateCommand();
      command.CommandText = "SELECT count(*) FROM sqlite_master WHERE type = 'table' " +
                            "AND name = '" + tableName + "'";

      return 0 < Convert.ToInt32(command.ExecuteScalar());
    }

    #endregion Private Methods
  }
}


text:
ALTER TABLE `users` ADD `country` varchar(8) NOT NULL default '';

--//@UNDO

ALTER TABLE `users` DROP `country`;

--


text:
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var React = require('react/addons');
var PureRenderMixin = React.addons.PureRenderMixin;
var ReactTransitionGroup = React.addons.TransitionGroup;
var StylePropable = require('../mixins/style-propable');
var ScaleInChild = require('./scale-in-child');

var ScaleIn = React.createClass({
  displayName: 'ScaleIn',

  mixins: [PureRenderMixin, StylePropable],

  propTypes: {
    childStyle: React.PropTypes.object,
    enterDelay: React.PropTypes.number,
    maxScale: React.PropTypes.number,
    minScale: React.PropTypes.number
  },

  getDefaultProps: function getDefaultProps() {
    return {
      enterDelay: 0
    };
  },

  render: function render() {
    var _props = this.props;
    var children = _props.children;
    var childStyle = _props.childStyle;
    var enterDelay = _props.enterDelay;
    var maxScale = _props.maxScale;
    var minScale = _props.minScale;
    var style = _props.style;

    var other = _objectWithoutProperties(_props, ['children', 'childStyle', 'enterDelay', 'maxScale', 'minScale', 'style']);

    var mergedRootStyles = this.mergeAndPrefix({
      position: 'relative',
      overflow: 'hidden',
      height: '100%'
    }, style);

    var newChildren = React.Children.map(children, function (child) {
      return React.createElement(
        ScaleInChild,
        {
          key: child.key,
          enterDelay: enterDelay,
          maxScale: maxScale,
          minScale: minScale,
          style: childStyle },
        child
      );
    });

    return React.createElement(
      ReactTransitionGroup,
      _extends({}, other, {
        style: mergedRootStyles,
        component: 'div' }),
      newChildren
    );
  }

});

module.exports = ScaleIn;


text:
namespace network {
class SharedURLLoaderFactory;
}

namespace policy {

class MockDeviceManagementServiceConfiguration
    : public DeviceManagementService::Configuration {
 public:
  MockDeviceManagementServiceConfiguration();
  explicit MockDeviceManagementServiceConfiguration(
      const std::string& server_url);
  MockDeviceManagementServiceConfiguration(
      const MockDeviceManagementServiceConfiguration&) = delete;
  MockDeviceManagementServiceConfiguration& operator=(
      const MockDeviceManagementServiceConfiguration&) = delete;
  ~MockDeviceManagementServiceConfiguration() override;

  std::string GetDMServerUrl() const override;
  std::string GetAgentParameter() const override;
  std::string GetPlatformParameter() const override;
  std::string GetRealtimeReportingServerUrl() const override;
  std::string GetEncryptedReportingServerUrl() const override;
  std::string GetReportingConnectorServerUrl(
      content::BrowserContext* context) const override;

 private:
  const std::string server_url_;
};

class MockJobCreationHandler {
 public:
  MockJobCreationHandler();
  MockJobCreationHandler(const MockJobCreationHandler&) = delete;
  MockJobCreationHandler& operator=(const MockJobCreationHandler&) = delete;
  ~MockJobCreationHandler();

  MOCK_METHOD(void,
              OnJobCreation,
              (const DeviceManagementService::JobForTesting&));
};

class FakeDeviceManagementService : public DeviceManagementService {
 public:
  using JobAction = testing::Action<void(const JobForTesting&)>;

  explicit FakeDeviceManagementService(
      MockJobCreationHandler* creation_handler);
  FakeDeviceManagementService(std::unique_ptr<Configuration> config,
                              MockJobCreationHandler* creation_handler);
  FakeDeviceManagementService(const FakeDeviceManagementService&) = delete;
  FakeDeviceManagementService& operator=(const FakeDeviceManagementService&) =
      delete;
  ~FakeDeviceManagementService() override;

  // Convenience actions to obtain the respective data from the job's
  // configuration.
  JobAction CaptureAuthData(DMAuth* auth_data);
  JobAction CaptureJobType(
      DeviceManagementService::JobConfiguration::JobType* job_type);
  JobAction CapturePayload(std::string* payload);
  JobAction CaptureQueryParams(
      std::map<std::string, std::string>* query_params);
  JobAction CaptureRequest(
      enterprise_management::DeviceManagementRequest* request);
  JobAction CaptureTimeout(base::TimeDelta* timeout);

  // Convenience actions to post a task which will call |SetResponseForTesting|
  // on the job.
  JobAction SendJobResponseAsync(
      int net_error,
      int response_code,
      const std::string& response = "",
      const std::string& mime_type = "application/x-protobuffer",
      bool was_fetched_via_proxy = false);

  JobAction SendJobResponseAsync(
      int net_error,
      int response_code,
      const enterprise_management::DeviceManagementResponse& response,
      const std::string& mime_type = "application/x-protobuffer",
      bool was_fetched_via_proxy = false);

  JobAction SendJobOKAsync(const std::string& response);

  JobAction SendJobOKAsync(
      const enterprise_management::DeviceManagementResponse& response);

  // Convenience wrappers around |job->SetResponseForTesting()|
  void SendJobResponseNow(
      DeviceManagementService::JobForTesting* job,
      int net_error,
      int response_code,
      const std::string& response = "",
      const std::string& mime_type = "application/x-protobuffer",
      bool was_fetched_via_proxy = false);

  void SendJobResponseNow(
      DeviceManagementService::JobForTesting* job,
      int net_error,
      int response_code,
      const enterprise_management::DeviceManagementResponse& response,
      const std::string& mime_type = "application/x-protobuffer",
      bool was_fetched_via_proxy = false);

  void SendJobOKNow(DeviceManagementService::JobForTesting* job,
                    const std::string& response);

  void SendJobOKNow(
      DeviceManagementService::JobForTesting* job,
      const enterprise_management::DeviceManagementResponse& response);

 private:
  std::unique_ptr<Job> CreateJob(
      std::unique_ptr<JobConfiguration> config) override;

  raw_ptr<MockJobCreationHandler> creation_handler_;
};

// A fake implementation of DMServerJobConfiguration that can be used in tests
// to set arbitrary request payloads for network requests.
class FakeJobConfiguration : public DMServerJobConfiguration {
 public:
  typedef base::OnceCallback<void(DeviceManagementService::Job* job,
                                  DeviceManagementStatus code,
                                  int net_error,
                                  const std::string&)>
      FakeCallback;

  typedef base::RepeatingCallback<void(int response_code,
                                       const std::string& response_body)>
      RetryCallback;

  explicit FakeJobConfiguration(DeviceManagementService* service);
  FakeJobConfiguration(
      DeviceManagementService* service,
      JobType type,
      const std::string& client_id,
      bool critical,
      DMAuth auth_data,
      absl::optional<std::string> oauth_token,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      FakeCallback callback,
      RetryCallback retry_callback,
      RetryCallback should_retry_callback);
  ~FakeJobConfiguration() override;

  void SetRequestPayload(const std::string& request_payload);
  void SetShouldRetryResponse(DeviceManagementService::Job::RetryMethod method);
  void SetTimeoutDuration(base::TimeDelta timeout);

 private:
  DeviceManagementService::Job::RetryMethod ShouldRetry(
      int response_code,
      const std::string& response_body) override;
  void OnBeforeRetry(int response_code,
                     const std::string& response_body) override;
  void OnURLLoadComplete(DeviceManagementService::Job* job,
                         int net_error,
                         int response_code,
                         const std::string& response_body) override;

  DeviceManagementService::Job::RetryMethod should_retry_response_;
  FakeCallback callback_;
  RetryCallback retry_callback_;
  RetryCallback should_retry_callback_;
};

}  // namespace policy

#endif  // COMPONENTS_POLICY_CORE_COMMON_CLOUD_MOCK_DEVICE_MANAGEMENT_SERVICE_H_


text:
package com.amazonaws.eclipse.lambda.serverless.model.transform;

public class PrimaryKey {
    private String name;
    private String type;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
}