text:
/* global describe, expect, test */

const FL = require('fantasy-land');
const Either = require('../../../src/either');

describe('Fantasy Check - Either', () => {
  describe('Either', () => {
    test('Static Monad', () => {
      expect(typeof Either[FL.map]).toBe('function');
      expect(typeof Either[FL.ap]).toBe('function');
      expect(typeof Either[FL.of]).toBe('function');
      expect(typeof Either[FL.chain]).toBe('function');
    });
  });

  describe('Either.Left', () => {
    test('Instance Monad', () => {
      expect(typeof Either.Left.prototype[FL.map]).toBe('function');
      expect(typeof Either.Left.prototype[FL.ap]).toBe('function');
      expect(typeof Either.Left.prototype[FL.of]).toBe('function');
      expect(typeof Either.Left.prototype[FL.chain]).toBe('function');
    });
  });

  describe('Either.Right', () => {
    test('Instance Monad', () => {
      expect(typeof Either.Right.prototype[FL.map]).toBe('function');
      expect(typeof Either.Right.prototype[FL.ap]).toBe('function');
      expect(typeof Either.Right.prototype[FL.of]).toBe('function');
      expect(typeof Either.Right.prototype[FL.chain]).toBe('function');
    });
  });
});


text:
package org.apache.commons.mail.util;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Static helper methods.
 *
 * @since 1.3
 * @version $Id$
 */
public final class MimeMessageUtils
{
    /**
     * Instances should NOT be constructed in standard programming.
     */
    private MimeMessageUtils()
    {
        super();
    }

    /**
     * Create a MimeMessage.
     *
     * @param session the mail session
     * @param source the input data
     * @return the MimeMessage
     * @throws MessagingException creating the MimeMessage failed
     * @throws IOException creating the MimeMessage failed
     */
    public static MimeMessage createMimeMessage(final Session session, final byte[] source)
        throws MessagingException, IOException
    {
        ByteArrayInputStream is = null;

        try
        {
            is = new ByteArrayInputStream(source);
            return new MimeMessage(session, is);
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }

    /**
     * Create a MimeMessage.
     *
     * @param session the mail session
     * @param source the input data
     * @return the MimeMessage
     * @throws MessagingException creating the MimeMessage failed
     * @throws IOException creating the MimeMessage failed
     */
    public static MimeMessage createMimeMessage(final Session session, final File source)
        throws MessagingException, IOException
    {
        FileInputStream is = null;

        try
        {
            is = new FileInputStream(source);
            return createMimeMessage(session, is);
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }

    /**
     * Create a MimeMessage.
     *
     * @param session the mail session
     * @param source the input data
     * @return the MimeMessage
     * @throws MessagingException creating the MimeMessage failed
     */
    public static MimeMessage createMimeMessage(final Session session, final InputStream source)
        throws MessagingException
    {
        return new MimeMessage(session, source);
    }

    /**
     * Create a MimeMessage using the platform's default character encoding.
     *
     * @param session the mail session
     * @param source the input data
     * @return the MimeMessage
     * @throws MessagingException creating the MimeMessage failed
     * @throws IOException creating the MimeMessage failed
     */
    public static MimeMessage createMimeMessage(final Session session, final String source)
        throws MessagingException, IOException
    {
        ByteArrayInputStream is = null;

        try
        {
            final byte[] byteSource = source.getBytes();
            is = new ByteArrayInputStream(byteSource);
            return createMimeMessage(session, is);
        }
        finally
        {
            if (is != null)
            {
                is.close();
            }
        }
    }

    /**
     * Convenience method to write a MimeMessage into a file.
     *
     * @param mimeMessage the MimeMessage to write
     * @param resultFile  the file containing the MimeMessgae
     * @throws MessagingException accessing MimeMessage failed
     * @throws IOException        writing the MimeMessage failed
     */
    public static void writeMimeMessage(final MimeMessage mimeMessage, final File resultFile)
        throws MessagingException, IOException
    {

        FileOutputStream fos = null;

        try
        {
            if (!resultFile.getParentFile().exists() && !resultFile.getParentFile().mkdirs())
            {
                throw new IOException(
                        "Failed to create the following parent directories: "
                                + resultFile.getParentFile());
            }

            fos = new FileOutputStream(resultFile);
            mimeMessage.writeTo(fos);
            fos.flush();
            fos.close();
            fos = null;
        }
        finally
        {
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (final Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.innobraves.kairosjava.models.results.subsets;

import javax.json.JsonObject;

/**
 * Representation of detected attributes
 * @author P. Willnow
 * @version 0.0.1
 */
public class Attributes {
    private String lips;
    private double asian;
    private Gender gender;
    private int age;
    private double hispanic;
    private double other;
    private double black;
    private double white;
    private String glasses;

    /**
     * Empty private constructor, so it can't be called from outside the class.
     */
    private Attributes(){}
//--------------------------------------------------------------------------------------------------------
//---------------------------Getters and Setters for all fields in this class-----------------------------
//--------------------------------------------------------------------------------------------------------
    public String getLips() {
        return lips;
    }

    public double getAsian() {
        return asian;
    }

    public Gender getGender() {
        return gender;
    }

    public int getAge() {
        return age;
    }

    public double getHispanic() {
        return hispanic;
    }

    public double getOther() {
        return other;
    }

    public double getBlack() {
        return black;
    }

    public double getWhite() {
        return white;
    }

    public String getGlasses() {
        return glasses;
    }
//--------------------------------------------------------------------------------------------------------
//--------------------------------------End of Getters and Setters----------------------------------------
//--------------------------------------------------------------------------------------------------------

    /**
     * Creator method, taking raw JSON data and filling fields with it
     * @param raw raw JSON data with result data
     * @return instance of this class filled with data
     */
    public static Attributes create(JsonObject raw){
        Attributes att = new Attributes();
        att.lips = raw.getJsonString("lips").getString();
        att.asian = raw.getJsonNumber("asian").doubleValue();
        att.hispanic = raw.getJsonNumber("hispanic").doubleValue();
        att.other = raw.getJsonNumber("other").doubleValue();
        att.black = raw.getJsonNumber("black").doubleValue();
        att.white = raw.getJsonNumber("white").doubleValue();
        att.gender = Gender.create(raw.getJsonObject("gender"));
        att.age = raw.getJsonNumber("age").intValue();
        att.glasses = raw.getJsonString("glasses").getString();
        return att;
    }

    @Override
    public String toString() {
        return "Attributes{\n" +
                "lips:\t'" + lips + '\'' + "\n" +
                "asian:\t" + asian + "\n" +
                "gender:\t" + gender + "\n" +
                "age:\t" + age + "\n" +
                "hispanic:\t" + hispanic + "\n" +
                "other:\t" + other + "\n" +
                "black:\t" + black + "\n" +
                "white:\t" + white + "\n" +
                "glasses:\t'" + glasses + '\'' + "\n" +
                '}';
    }
}


text:
/*
 * Portions Copyright (c) Microsoft Corporation
 */

package com.azure.cosmos.implementation.guava25.collect;

/**
 * Unused stub class, unreferenced under Java and manually emulated under GWT.
 *
 * @author Chris Povirk
 */
abstract class ForwardingImmutableSet<E> {
  private ForwardingImmutableSet() {}
}


text: {{ site.description }}


text:
require "helper"

module ActiveJobExpectationTests
  def test_must_enqueue_jobs
    must_enqueue_jobs 0
    UserInviteJob.logger.silence { UserInviteJob.perform_later }
    must_enqueue_jobs 1
  end

  def test_wont_enqueue_jobs
    wont_enqueue_jobs
    UserInviteJob.new
    wont_enqueue_jobs
  end

  def test_must_perform_jobs
    must_perform_jobs 0
    must_perform_jobs 2 do
      UserInviteJob.logger.silence do
        UserInviteJob.perform_later
        UserInviteJob.perform_later
      end
    end
  end

  def test_wont_perform_jobs
    wont_perform_jobs
    wont_perform_jobs do
      UserInviteJob.new
    end
  end

  def test_must_enqueue_with
    must_enqueue_with job: UserInviteJob, args: [209] do
      UserInviteJob.logger.silence { UserInviteJob.perform_later(209) }
    end
  end

  def test_must_perform_with
    must_perform_with job: UserInviteJob, args: [107] do
      UserInviteJob.logger.silence { UserInviteJob.perform_later(107) }
    end
  end
end

class TestActiveJobExpectations < ActiveJob::TestCase
  include ActiveJobExpectationTests
end

class TestActiveJobExpectationInCustomTestCase < ActiveSupport::TestCase
  include Minitest::Rails::Expectations::ActiveJob
  include ActiveJobExpectationTests
end


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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using XamarinRepairApp.Model;
using MSGraph = Microsoft.Graph;

namespace XamarinRepairApp
{
    public class App : Application
    {
        public static String Token;

        public static int IncidentId;

        public static String PropertyId;

        public static IncidentModel SelectedIncidet;

		public static MSGraph.GraphServiceClient GraphService;
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Restricted</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">

This is a restricted area.


text:
import numpy as np
import UsefulUtils as uu
from UsefulUtils import Bunch

import h5py

def load_andor_ccd_readout(filename, description=''):

    d = dict(np.load(filename))

    #uu.copy_string('\n'.join(d.keys()))

    o = Bunch(data_dict = d,
              keys = d.keys(),
              filename = filename,
              filetitle = uu.get_file_title(filename),
              description = description,
              wavelength = d['wls'],
              intg_time = d['andor_ccd_exposure_time'],
              intensity = d['spectrum'][0],
              center_wl = d['acton_spectrometer_center_wl']
              )

    o.everything=Bunch()
    for key in o.keys:
        setattr(o.everything, key, d[key])

    return o

def load_apd_map(filename, description=""):
    d = dict(np.load(filename))

    #uu.copy_string('\n'.join(d.keys()))

    o = Bunch(data_dict = d,
              keys = d.keys(),
              filename = filename,
              filetitle = uu.get_file_title(filename),
              description = description,
              intensity = d['count_rate_map'],
              extent = d['imshow_extent']
             )
    o.everything = Bunch()
    for key in o.keys:
        setattr(o.everything, key, d[key])

    return o

def load_picoharp_transient(filename, description="", truncate_bins = False):
    d = dict(np.load(filename))

    #uu.copy_string('\n'.join(d.keys()))

    o = Bunch(data_dict = d,
              keys = d.keys(),
              filename = filename,
              filetitle = uu.get_file_title(filename),
              description = description,
              intensity = d['time_histogram'],
              time = d['time_array'],
              resolution = d['picoharp_Resolution'],
              rep_rate = d['picoharp_count_rate0']
             )
    o.num_bins = int(np.ceil((1/o.rep_rate)/(o.resolution*1e-12)))
    if truncate_bins:
        o.time = o.time[0:o.num_bins]
        o.intensity = o.intensity[0:o.num_bins]

    o.everything = Bunch()
    for key in o.keys:
        setattr(o.everything, key, d[key])

    return o

def load_trpl_scan(filename, description):
    d = dict(np.load(filename))

    #uu.copy_string('\n'.join(d.keys()))

    o = Bunch(data_dict = d,
              keys = d.keys(),
              filename = filename,
              filetitle = uu.get_file_title(filename),
              description = description,
              extent = d['imshow_extent'],
              time = d['time_array'],
              resolution = d['picoharp_Resolution'],
              transients = d['time_trace_map'],
              rows = d['Nv'],
              cols = d['Nh']
             )

    o.everything = Bunch()
    for key in o.keys:
        setattr(o.everything, key, d[key])

    # average transient
    o.avg_transient = np.average(o.transients, axis=(0,1))

    # integrated intensity map
    o.intg_int_map = np.zeros((o.rows, o.cols), dtype=float)
    for row in range(o.rows):
        for col in range(o.cols):
            o.intg_int_map[row,col] = np.sum(o.transients[row,col])

    return o

def load_spec_and_glue(filename, description=""):
    h5_f = h5py.File(filename, 'r')

    o = Bunch(
      centers = h5_f['andor_ccd_step_and_glue']['center_wl_actual'][()].copy(),
      single_specs =  h5_f['andor_ccd_step_and_glue']['spectra_data'][()].copy(),
      single_wavelengths = h5_f['andor_ccd_step_and_glue']['wls'][()].copy(),
      filename = filename,
      filetitle = uu.get_file_title(filename),
      description=description
    )

    # Initialize with the first spectrum
    wls = o.single_wavelengths[0][:]
    raw_ints = o.single_specs[0][0,:]

    # Progressively merge spectra into the lists of wls.
    for i in range(1, o.centers.shape[0]):
        # Determine the array indices and size of the regions of overlap
        i_overlap_start = np.searchsorted(wls, o.single_wavelengths[i][0])
        overlap_size_1 = wls.shape[0] - i_overlap_start
        overlap_size_2 = np.searchsorted(o.single_wavelengths[i], wls[-1])
        #print(i_overlap_start, overlap_size_1, overlap_size_2)

        # Generate a uniformly spaced points in the overlap region
        wls_overlap = np.linspace(o.single_wavelengths[i][0], wls[-1],
                                  (overlap_size_1+overlap_size_2)/2)

        # Take the average of the interpolated values from the two data sets in the
        # interpolated region.
        raw_int_overlap = (np.interp(wls_overlap, wls[i_overlap_start:], raw_ints[i_overlap_start:] ) +
                           np.interp(wls_overlap, o.single_wavelengths[i][0:overlap_size_2],
                                     o.single_specs[i][0,0:overlap_size_2]))/2.0

        # Append the averaged overlapped data to the non-overlapped data at the beginning.
        wls = np.append(wls[0:i_overlap_start], wls_overlap)
        raw_ints = np.append(raw_ints[0:i_overlap_start], raw_int_overlap)

        # Append the remaining non-overlapped data
        wls = np.append(wls, o.single_wavelengths[i][overlap_size_2:])
        raw_ints = np.append(raw_ints, o.single_specs[i][0,overlap_size_2:])

    #print wls
    o.wavelength = wls
    o.intensity = raw_ints

    h5_f.close()

    return o

def load_kinetic_spectra(filename, description=''):

    d = dict(np.load(filename))

    #uu.copy_string('\n'.join(d.keys()))

    o = Bunch(data_dict = d,
              keys = d.keys(),
              filename = filename,
              filetitle = uu.get_file_title(filename),
              description = description,
              wavelength = d['wls'],
              intg_time = d['andor_ccd_exposure_time'],
              center_wl = d['acton_spectrometer_center_wl'],
              times = d['start_times'],
              frame_count = int(d['kinetic_spectra_frames']),
              specs = d['kinetic_spectra']
              )

    o.everything=Bunch()
    for key in o.keys:
        setattr(o.everything, key, d[key])

    return o

def load_spec_scan(filename, description=""):
    h5_f = h5py.File(filename, 'r')

    o = Bunch(
      specs = h5_f['spec_scan']['spec_map'][()].copy(),
      wavelength = h5_f['spec_scan']['wls'][()].copy(),
      extent = h5_f['spec_scan'].attrs['imshow_extent'][()].copy(),
      filename = filename,
        filetitle = uu.get_file_title(filename),
        description=description
    )

    return o

def merge_step_and_glue_specs(centers, wavelengths, specs):
    # Initialize with the first spectrum
    wls = wavelengths[0][:]
    raw_ints = specs[0][0,:]

    # Progressively merge spectra into the lists of wls.
    for i in range(1, centers.shape[0]):
        # Determine the array indices and size of the regions of overlap
        i_overlap_start = np.searchsorted(wls, wavelengths[i][0])
        overlap_size_1 = wls.shape[0] - i_overlap_start
        overlap_size_2 = np.searchsorted(wavelengths[i], wls[-1])
        #print(i_overlap_start, overlap_size_1, overlap_size_2)

        # Generate a uniformly spaced points in the overlap region
        wls_overlap = np.linspace(wavelengths[i][0], wls[-1],
                                  (overlap_size_1+overlap_size_2)/2)

        # Take the average of the interpolated values from the two data sets in the
        # interpolated region.
        raw_int_overlap = (np.interp(wls_overlap, wls[i_overlap_start:], raw_ints[i_overlap_start:] ) +
                           np.interp(wls_overlap, wavelengths[i][0:overlap_size_2],
                                     specs[i][0,0:overlap_size_2]))/2.0

        # Append the averaged overlapped data to the non-overlapped data at the beginning.
        wls = np.append(wls[0:i_overlap_start], wls_overlap)
        raw_ints = np.append(raw_ints[0:i_overlap_start], raw_int_overlap)

        # Append the remaining non-overlapped data
        wls = np.append(wls, wavelengths[i][overlap_size_2:])
        raw_ints = np.append(raw_ints, specs[i][0,overlap_size_2:])

    return wls, raw_ints

def load_power_sweep(filename, description=''):

    d = dict(np.load(filename))

    uu.copy_string('\n'.join(d.keys()))

    o = Bunch(data_dict = d,
              keys = d.keys(),
              filename = filename,
              filetitle = uu.get_file_title(filename),
              description = description,
              powers = d['power_meter_power'],
              N = d['Np']
              )

    if d['power_scan_motorized_collect_apd']:
        raise NotImplementedError('APD power scan not implemented')

    if d['power_scan_motorized_collect_lifetime']:
        o.rep_rate = d['picoharp_count_rate0']
        o.bin_size = d['picoharp_Resolution']
        o.num_bins = int(np.ceil((1/o.rep_rate)/(o.bin_size*1e-12)))
        o.time = d['time_array'][0:o.num_bins] # already in ns
        o.intensity = d['time_traces'][:,0:o.num_bins]

    if d['power_scan_motorized_collect_lockin']:
        raise NotImplementedError('Lockin power scan not implemented')

    if d['power_scan_motorized_collect_spectrum']:
        o.wavelength = d['wls']
        o.intg_time = d['andor_ccd_exposure_time']
        o.center_wl = d['acton_spectrometer_center_wl']
        o.specs = d['spectra']
        o.intg_spectrum_ints = np.sum(o.specs, axis=1)

    if d['power_scan_motorized_collect_step_and_glue']:
        N = d['Np']
        for i in range(N):
            wls, ints = merge_step_and_glue_specs(d['step_and_glue_centers'],
                                                  d['step_and_glue_wavelengths'][i],
                                                  d['step_and_glue_specs'][i])
            if i == 0:
                o.specs = np.empty([N, wls.shape[0]], dtype=float)
                o.wavelength = wls
            o.specs[i] = ints

        o.intg_time = d['andor_ccd_exposure_time']
        o.centers = d['step_and_glue_centers'][0]

    o.everything=Bunch()
    for key in o.keys:
        setattr(o.everything, key, d[key])

    return o

def load_spec_scan(filename, description=""):

    d = dict(np.load(filename))

    uu.copy_string('\n'.join(d.keys()))

    o = Bunch(data_dict = d,
              keys = d.keys(),
              filename = filename,
              filetitle = uu.get_file_title(filename),
              description = description,
              wavelength = d['wls'],
              intg_time = d['andor_ccd_exposure_time'],
              center_wl = d['acton_spectrometer_center_wl'],
              extent = d['imshow_extent'],
              rows = d['Nv'],
              cols = d['Nh'],
              specs = d['spec_map'],
             )

    o.everything=Bunch()
    for key in o.keys:
        setattr(o.everything, key, d[key])

    return o


text:
package com.atlassian.jira.plugins.dvcs.spi.github.service;

import com.atlassian.jira.plugins.dvcs.model.Repository;
import org.eclipse.egit.github.core.PullRequest;

import java.util.Set;

/**
 * Interface defining context for GitHub event synchronisation
 */
public interface GitHubEventContext
{
    /**
     * Saving pull request
     */

    void savePullRequest(PullRequest pullRequest);
}


text:
mod auth_context;
mod cancel;
mod credential;
mod kick;
mod metadata;
mod misc;
mod stream;


text:
package org.zalando.logbook.httpclient5;

import lombok.RequiredArgsConstructor;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.nio.DataStreamChannel;

import java.nio.ByteBuffer;
import java.util.List;

import static lombok.AccessLevel.PACKAGE;

@RequiredArgsConstructor(access = PACKAGE)
final class BufferingFixedSizeDataStreamChannel implements DataStreamChannel {
    private final byte[] buffer;

    public byte[] getBuffer() {
        return buffer;
    }

    @Override
    public void requestOutput() {
    }

    @Override
    public int write(ByteBuffer src) {
        ByteBufferUtils.fixedSizeCopy(src, buffer);
        return 0;
    }

    @Override
    public void endStream() {
    }

    @Override
    public void endStream(List<? extends Header> trailers) {
    }
}


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

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~   http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<ipojo>
	<component className="ipojo.example.hello.impl.HelloImpl"
		name="HelloProvider" architecture="true">
		<provides />
	</component>
	<instance component="HelloProvider" name="HelloService" />
</ipojo>


text:
#pragma once
#include "cocos2d.h"

/*	°ÔÀÓ Ç÷¹ÀÌ ¹æ¹ý°ú Á¡¼ö °è»ê ¹æ¹ýÀÌ ³ª¿À´Â ·¹À̾î	*/
class CHelpPopupLayer : public cocos2d::CCLayer
{
public:
	virtual bool init();
	virtual void onEnter();
	virtual void onExit();

	virtual bool ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent* event);
	virtual void ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent* event);
	virtual void ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent* event);

	// implement the "static node()" method manually
	CREATE_FUNC(CHelpPopupLayer);
};


text:
package couchdb

import (
	"fmt"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var expectedChannelNamePattern = `[a-z][a-z0-9.-]*`
var maxLength = 249

//CreateCouchInstance creates a CouchDB instance
func CreateCouchInstance(couchDBConnectURL, id, pw string, maxRetries,
	maxRetriesOnStartup int, connectionTimeout time.Duration) (*CouchInstance, error) {

	couchConf, err := CreateConnectionDefinition(couchDBConnectURL,
		id, pw, maxRetries, maxRetriesOnStartup, connectionTimeout)
	if err != nil {
		logger.Errorf("Error during CouchDB CreateConnectionDefinition(): %s\n", err.Error())
		return nil, err
	}

	// Create the http client once
	// Clients and Transports are safe for concurrent use by multiple goroutines
	// and for efficiency should only be created once and re-used.
	client := &http.Client{Timeout: couchConf.RequestTimeout}

	transport := &http.Transport{Proxy: http.ProxyFromEnvironment}
	transport.DisableCompression = false
	client.Transport = transport

	//Create the CouchDB instance
	couchInstance := &CouchInstance{conf: *couchConf, client: client}

	connectInfo, retVal, verifyErr := couchInstance.VerifyCouchConfig()
	if verifyErr != nil {
		return nil, verifyErr
	}

	//return an error if the http return value is not 200
	if retVal.StatusCode != 200 {
		return nil, fmt.Errorf("CouchDB connection error, expecting return code of 200, received %v", retVal.StatusCode)
	}

	//check the CouchDB version number, return an error if the version is not at least 2.0.0
	errVersion := checkCouchDBVersion(connectInfo.Version)
	if errVersion != nil {
		return nil, errVersion
	}

	return couchInstance, nil
}

//checkCouchDBVersion verifies CouchDB is at least 2.0.0
func checkCouchDBVersion(version string) error {

	//split the version into parts
	majorVersion := strings.Split(version, ".")

	//check to see that the major version number is at least 2
	majorVersionInt, _ := strconv.Atoi(majorVersion[0])
	if majorVersionInt < 2 {
		return fmt.Errorf("CouchDB must be at least version 2.0.0.  Detected version %s", version)
	}

	return nil
}

//CreateCouchDatabase creates a CouchDB database object, as well as the underlying database if it does not exist
func CreateCouchDatabase(couchInstance CouchInstance, dbName string) (*CouchDatabase, error) {

	databaseName, err := mapAndValidateDatabaseName(dbName)
	if err != nil {
		logger.Errorf("Error during CouchDB CreateDatabaseIfNotExist() for dbName: %s  error: %s\n", dbName, err.Error())
		return nil, err
	}

	couchDBDatabase := CouchDatabase{CouchInstance: couchInstance, DBName: databaseName}

	// Create CouchDB database upon ledger startup, if it doesn't already exist
	_, err = couchDBDatabase.CreateDatabaseIfNotExist()
	if err != nil {
		logger.Errorf("Error during CouchDB CreateDatabaseIfNotExist() for dbName: %s  error: %s\n", dbName, err.Error())
		return nil, err
	}

	return &couchDBDatabase, nil
}

//CreateSystemDatabasesIfNotExist - creates the system databases if they do not exist
func CreateSystemDatabasesIfNotExist(couchInstance CouchInstance) error {

	dbName := "_users"
	systemCouchDBDatabase := CouchDatabase{CouchInstance: couchInstance, DBName: dbName}
	_, err := systemCouchDBDatabase.CreateDatabaseIfNotExist()
	if err != nil {
		logger.Errorf("Error during CouchDB CreateDatabaseIfNotExist() for system dbName: %s  error: %s\n", dbName, err.Error())
		return err
	}

	dbName = "_replicator"
	systemCouchDBDatabase = CouchDatabase{CouchInstance: couchInstance, DBName: dbName}
	_, err = systemCouchDBDatabase.CreateDatabaseIfNotExist()
	if err != nil {
		logger.Errorf("Error during CouchDB CreateDatabaseIfNotExist() for system dbName: %s  error: %s\n", dbName, err.Error())
		return err
	}

	dbName = "_global_changes"
	systemCouchDBDatabase = CouchDatabase{CouchInstance: couchInstance, DBName: dbName}
	_, err = systemCouchDBDatabase.CreateDatabaseIfNotExist()
	if err != nil {
		logger.Errorf("Error during CouchDB CreateDatabaseIfNotExist() for system dbName: %s  error: %s\n", dbName, err.Error())
		return err
	}

	return nil

}

//mapAndValidateDatabaseName checks to see if the database name contains illegal characters
//CouchDB Rules: Only lowercase characters (a-z), digits (0-9), and any of the characters
//_, $, (, ), +, -, and / are allowed. Must begin with a letter.
//
//Restictions have already been applied to the database name from Orderer based on
//restrictions required by Kafka and couchDB (except a '.' char). The databaseName
// passed in here is expected to follow `[a-z][a-z0-9.-]*` pattern.
//
//This validation will simply check whether the database name matches the above pattern and will replace
// all occurence of '.' by '-'. This will not cause collisions in the trnasformed named
func mapAndValidateDatabaseName(databaseName string) (string, error) {
	// test Length
	if len(databaseName) <= 0 {
		return "", fmt.Errorf("Database name is illegal, cannot be empty")
	}
	if len(databaseName) > maxLength {
		return "", fmt.Errorf("Database name is illegal, cannot be longer than %d", maxLength)
	}
	re, err := regexp.Compile(expectedChannelNamePattern)
	if err != nil {
		return "", err
	}
	matched := re.FindString(databaseName)
	if len(matched) != len(databaseName) {
		return "", fmt.Errorf("databaseName '%s' does not matches pattern '%s'", databaseName, expectedChannelNamePattern)
	}
	// replace all '.' to '_'. The databaseName passed in will never contain an '_'. So, this translation will not cause collisions
	databaseName = strings.Replace(databaseName, ".", "_", -1)
	return databaseName, nil
}


text:
@implementation WebSocketClient {
}

- (id)initWithURL:(NSURL *)url command:(CDVInvokedUrlCommand *)command pkcs12Path:(NSString *)pkcs12Path password:(NSString *)password {

    self.command = command;
    self.uuid = [[NSUUID UUID] UUIDString];
    self.socket = [[JFRWebSocket alloc] initWithURL:url protocols:NULL];
    self.socket.selfSignedSSL = YES;

    if (pkcs12Path.length > 0) {
        [self.socket loadClientCertificate:pkcs12Path password:password];
    }

    self.socket.delegate = self;
    [self.socket connect];
    return self;
}

- (void)send:(NSString *)message {
    [self.socket writeString:message];
}

- (void)close {
    [self.socket disconnect];
}

- (void)websocketDidConnect:(JFRWebSocket *)socket {
    if([self.delegate respondsToSelector:@selector(clientDidConnect:client:)]) {
        [self.delegate clientDidConnect:self.uuid client:self];
    }
}

- (void)websocketDidDisconnect:(JFRWebSocket *)socket error:(NSError *)error {
    if([self.delegate respondsToSelector:@selector(clientDidDisconnect:client:error:)]) {
        [self.delegate clientDidDisconnect:self.uuid client:self error:error];
    }
}

- (void)websocket:(JFRWebSocket *)socket didReceiveMessage:(NSString *)string {
    if([self.delegate respondsToSelector:@selector(websocket:client:didReceiveMessage:)]) {
        [self.delegate websocket:self.uuid client:self didReceiveMessage:string];
    }
}

- (void)websocket:(JFRWebSocket *)socket didReceiveData:(NSData *)data {
    if([self.delegate respondsToSelector:@selector(websocket:client:didReceiveData:)]) {
        [self.delegate websocket:self.uuid client:self didReceiveData:data];
    }
}

@end


text:
require File.expand_path '../haml/filters/asciidoc.rb', __FILE__
require 'optaplanner'

Awestruct::Extensions::Pipeline.new do
	helper Awestruct::Extensions::Partial
	helper Awestruct::Extensions::Relative
	helper Awestruct::Extensions::Optaplanner

  extension Awestruct::Extensions::Posts.new('/blog')
  extension Awestruct::Extensions::Paginator.new(:posts, '/blog/index', :per_page => 10)
  extension Awestruct::Extensions::Tagger.new(:posts, '/blog/index', '/blog/tags', :per_page => 10)
  extension Awestruct::Extensions::Disqus.new
  extension Awestruct::Extensions::Atomizer.new(:posts, '/blog/news.atom', :template => File.join( File.dirname(__FILE__), 'relative_template.atom.haml'))
  extension Awestruct::Extensions::Sitemap.new()
end


text:
baseUrl=$1
urlList=$2
testIdentifier=$3
disableNewBase=$4

testIdentifier=$(date +"%Y-%m-%d_%H-%M-%S")"_"$testIdentifier
urlCounter=$(grep -v '^#' "$urlList" | wc -l)
finishedTestsCounter=0

echo "URLs to test: $urlCounter";
echo ""
grep -v '^#' "$urlList"| while IFS=$'\n' read urlToTest; do
	finishedTestsCounter=$(($finishedTestsCounter + 1));

	node_modules/casperjs/bin/casperjs test tests/demo2/testsuite.js --baseUrl="$baseUrl" --url="$urlToTest" --testIdentifier="$testIdentifier" --urlCounter="$urlCounter" --finishedTestsCounter="$finishedTestsCounter" --disableNewBase="$disableNewBase" < /dev/null

	#node_modules/casperjs/bin/casperjs --verbose="true" --log-level="debug" test tests/demo2/testsuite.js --baseUrl="$baseUrl" --url="$urlToTest" --testIdentifier="$testIdentifier" --urlCounter="$urlCounter" --finishedTestsCounter="$finishedTestsCounter" --disableNewBase="$disableNewBase" < /dev/null

	#PHANTOMJS_EXECUTABLE=node_modules/phantomjs-prebuilt/bin/phantomjs node_modules/casperjs/bin/casperjs test tests/demo2/testsuite.js --baseUrl="$baseUrl" --url="$urlToTest" --testIdentifier="$testIdentifier" --urlCounter="$urlCounter" --finishedTestsCounter="$finishedTestsCounter" --disableNewBase="$disableNewBase" < /dev/null
	#SLIMERJS_EXECUTABLE=node_modules/slimerjs/bin/slimerjs node_modules/casperjs/bin/casperjs test tests/demo2/testsuite.js --baseUrl="$baseUrl" --url="$urlToTest" --testIdentifier="$testIdentifier" --urlCounter="$urlCounter" --finishedTestsCounter="$finishedTestsCounter" --disableNewBase="$disableNewBase" --engine="slimerjs" < /dev/null

	echo "Tested $finishedTestsCounter of $urlCounter URLs"
	echo ""
done
echo "All tests finished";


text:
![screenshot1](https://github.com/imhui/LWSlideShow/blob/master/sample.png?raw=true)

## usage

```

	NSMutableArray *array = [@[] mutableCopy];
    LWSlideItem *item = [LWSlideItem itemWithCaption:@"1" imageUrl:@"http://img2.3lian.com/2014/f4/102/d/86.jpg"];
    [array addObject:item];
    item = [LWSlideItem itemWithCaption:@"2" imageUrl:@"http://image5.tuku.cn/wallpaper/Photography%20Wallpapers/11286_2560x1600.jpg"];
    [array addObject:item];
    item = [LWSlideItem itemWithCaption:@"3" imageUrl:@"http://img2.3lian.com/2014/f2/150/d/44.jpg"];
    [array addObject:item];
    item = [LWSlideItem itemWithCaption:@"4" imageUrl:@"http://img2.3lian.com/2014/f2/150/d/45.jpg"];
    [array addObject:item];
    item = [LWSlideItem itemWithCaption:@"5" imageUrl:@"http://img2.3lian.com/2014/f2/150/d/46.jpg"];
    [array addObject:item];

    LWSlideShow *slideShow = [[LWSlideShow alloc] initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.bounds), 160)];
    slideShow.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    slideShow.delegate = self;
    slideShow.slideItems = array;

```


text:
define("dojox/drawing/ui/Toolbar", ["dojo", "../library/icons", "../util/common", "../Drawing", "../manager/_registry"],
function(dojo, icons, utilCommon, Drawing, registry){

return dojo.declare("dojox.drawing.ui.Toolbar", [], {
	// summary:
	//		A Toolbar used for holding buttons; typically representing the Stencils
	//		used for a DojoX Drawing.
	// description:
	//		Creates a GFX-based toolbar that holds GFX-based buttons. Can be either created
	//		within the actual drawing or within a separate DOM element. When within the
	//		drawing, the toolbar will cover a portion of the drawing; hence the option.
	//
	//		A Toolbar can be created programmatically or in markup. Currently markup is as
	//		a separate DOM element and programmatic is within the drawing.
	// example:
	//		|	dojo.connect(myDrawing, "onSurfaceReady", function(){
	//		|		new dojox.drawing.ui.Toolbar({
	//		|			drawing:myDrawing,
	//		|			tools:"all",
	//		|			plugs:"all",
	//		|			selected:"ellipse"
	//		|		});
	//		|	});
	//
	//		|

	constructor: function(props, node){
		//console.warn("GFX Toolbar:", props, node)

		// no mixin. painful.
		if(props.drawing){
			// programmatic
			this.toolDrawing = props.drawing;
			this.drawing = this.toolDrawing;
			this.width = this.toolDrawing.width;
			this.height = this.toolDrawing.height;
			this.strSelected = props.selected;
			this.strTools = props.tools;
			this.strPlugs = props.plugs;
			this._mixprops(["padding", "margin", "size", "radius"], props);
			this.addBack();
			this.orient = props.orient ? props.orient : false;
		}else{
			// markup
			var box = dojo.marginBox(node);
			this.width = box.w;
			this.height = box.h;
			this.strSelected = dojo.attr(node, "selected");
			this.strTools = dojo.attr(node, "tools");
			this.strPlugs = dojo.attr(node, "plugs");
			this._mixprops(["padding", "margin", "size", "radius"], node);
			this.toolDrawing = new Drawing({mode:"ui"}, node);
			this.orient = dojo.attr(node, "orient");
		}

		this.horizontal = this.orient ? this.orient == "H" : this.width > this.height;
		 0 && console.log("this.hor: ",this.horizontal," orient: ",this.orient);
		if(this.toolDrawing.ready){
			this.makeButtons();
			if(!this.strSelected && this.drawing.defaults.clickMode){ this.drawing.mouse.setCursor('default'); };
		}else{
			var c = dojo.connect(this.toolDrawing, "onSurfaceReady", this, function(){
				// 0 && console.log("TB built")
				dojo.disconnect(c);
				this.drawing = registry.getRegistered("drawing", dojo.attr(node, "drawingId"));
				this.makeButtons();
				if(!this.strSelected && this.drawing.defaults.clickMode){
					var c = dojo.connect(this.drawing, "onSurfaceReady", this, function(){
					dojo.disconnect(c);
					this.drawing.mouse.setCursor('default');
					});
				}
			});
		}

	},

	// padding:Number
	//		The amount of spce between the top and left of the toolbar and the buttons.
	padding:10,
	// margin: Number
	//		The space between each button.
	margin:5,
	// size: Number
	//		The width and height of the button
	size:30,
	// radius: Number
	//		The size of the button's rounded corner
	radius:3,

	// toolPlugGap: number
	//		The distance between the tool buttons and plug buttons
	toolPlugGap:20,

	// strSelected: String
	//		The button that should be selected at startup.
	strSelected:"",

	// strTools: String
	//		A comma delineated list of the Stencil-tools to include in the Toolbar.
	//		If "all" is used, all registered tools are included.
	strTools:"",

	// strPlugs: String
	//		A comma delineated list of the plugins to include in the Toolbar.
	//		If "all" is used, all registered plugins are included.
	strPlugs:"",

	makeButtons: function(){
		// summary:
		//		Internal. create buttons.
		this.buttons = [];
		this.plugins = [];

		var x = this.padding, y = this.padding, w = this.size, h = this.size, r = this.radius, g = this.margin,
				 sym = icons,
				 s = {place:"BR", size:2, mult:4};

		if(this.strTools){
			var toolAr = [];
			var tools = registry.getRegistered("tool");
			var toolMap = {};
			for(var nm in tools){
				var tool = utilCommon.abbr(nm);
				toolMap[tool] = tools[nm];
				if(this.strTools=="all"){
					toolAr.push(tool);
					var details = registry.getRegistered("tool",nm);
					if(details.secondary){
						toolAr.push(details.secondary.name);
					}
				}
			}
			if(this.strTools!="all"){
				var toolTmp = this.strTools.split(",");
				dojo.forEach(toolTmp, function(tool){
					tool = dojo.trim(tool);
					toolAr.push(tool);
					var details = registry.getRegistered("tool",toolMap[tool].name);
					if(details.secondary){
						toolAr.push(details.secondary.name);
					}
				}, this);
				//dojo.map(toolAr, function(t){ return dojo.trim(t); });
			}

			dojo.forEach(toolAr, function(t){
				t = dojo.trim(t);
				var secondary = false;
				if(t.indexOf("Secondary")>-1){
					var prim = t.substring(0,t.indexOf("Secondary"));
					var sec = registry.getRegistered("tool",toolMap[prim].name).secondary;
					var label = sec.label;
					this[t] = sec.funct;
					if(sec.setup){ dojo.hitch(this, sec.setup)(); };
					var btn = this.toolDrawing.addUI("button", {data:{x:x, y:y, width:w, height:h/2, r:r}, toolType:t, secondary:true, text:label, shadow:s, scope:this, callback:this[t]});
					if(sec.postSetup){ dojo.hitch(this, sec.postSetup, btn)(); };
					secondary = true;
				} else {
					var btn = this.toolDrawing.addUI("button", {data:{x:x, y:y, width:w, height:h, r:r}, toolType:t, icon:sym[t], shadow:s, scope:this, callback:"onToolClick"});
				}
				registry.register(btn, "button");
				this.buttons.push(btn);
				if(this.strSelected==t){
					btn.select();
					this.selected = btn;
					this.drawing.setTool(btn.toolType);
				}
				if(this.horizontal){
					x += h + g;
				}else{
					var space = secondary ? h/2 + g : h + g;
					y += space;
				}
			}, this);
		}

		if(this.horizontal){
			x += this.toolPlugGap;
		}else{
			y += this.toolPlugGap;
		}

		if(this.strPlugs){
			var plugAr = [];
			var plugs = registry.getRegistered("plugin");
			var plugMap = {};
			for(var nm in plugs){
				var abbr = utilCommon.abbr(nm);
				plugMap[abbr] = plugs[nm];
				if(this.strPlugs=="all"){ plugAr.push(abbr); }
			}
			if(this.strPlugs!="all"){
				plugAr = this.strPlugs.split(",");
				dojo.map(plugAr, function(p){ return dojo.trim(p); });
			}

			dojo.forEach(plugAr, function(p){
				var t = dojo.trim(p);
				// 0 && console.log("   plugin:", p);
				if(plugMap[p].button != false){
					var btn = this.toolDrawing.addUI("button", {data:{x:x, y:y, width:w, height:h, r:r}, toolType:t, icon:sym[t], shadow:s, scope:this, callback:"onPlugClick"});
					registry.register(btn, "button");
					this.plugins.push(btn);

					if(this.horizontal){
						x += h + g;
					}else{
						y += h + g;
					}
				}

				var addPlug = {}
				plugMap[p].button == false ? addPlug = {name:this.drawing.stencilTypeMap[p]} : addPlug = {name:this.drawing.stencilTypeMap[p], options:{button:btn}};
				this.drawing.addPlugin(addPlug);
			}, this);
		}

		dojo.connect(this.drawing, "onRenderStencil", this, "onRenderStencil");
	},

	onRenderStencil: function(/* Object */stencil){
		// summary:
		//		Stencil render event.
		if(this.drawing.defaults.clickMode){
			this.drawing.mouse.setCursor("default");
			this.selected && this.selected.deselect();
			this.selected = null;
		}

	},

	addTool: function(){
		// TODO: add button here
	},

	addPlugin: function(){
		// TODO: add button here
	},

	addBack: function(){
		// summary:
		//		Internal. Adds the back, behind the toolbar.
		this.toolDrawing.addUI("rect", {data:{x:0, y:0, width:this.width, height:this.size + (this.padding*2), fill:"#ffffff", borderWidth:0}});
	},

	onToolClick: function(/*Object*/button){
		// summary:
		//		Tool click event. May be connected to.

		if(this.drawing.defaults.clickMode){ this.drawing.mouse.setCursor("crosshair"); }
		dojo.forEach(this.buttons, function(b){
			if(b.id==button.id){
				b.select();
				this.selected = b;
				this.drawing.setTool(button.toolType)
			}else{
				if(!b.secondary){ b.deselect(); }
			}
		},this)
	},

	onPlugClick: function(/*Object*/button){
		// summary:
		//		Plugin click event. May be connected to.
	},

	_mixprops: function(/*Array*/ props, /*Object|Node*/ objNode){
		// summary:
		//		Internally used for mixing in props from an object or
		//		from a dom node.
		dojo.forEach(props, function(p){
			this[p] = objNode.tagName
				? dojo.attr(objNode, p)===null ? this[p] : dojo.attr(objNode, p)
				: objNode[p]===undefined ? this[p] : objNode[p];
		}, this);
	}

});
});


text:
<TITLE>Review for GoldenEye (1995)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

GoldenEye (1995)

reviewed by
Sue Roberts

                                GOLDENEYE
                       A film review by Sue Roberts
                        Copyright 1996 Sue Roberts

Directed by Martin Campbell

Starring Pierce Brosnan, Izabella Scorupco, Joe Don Baker, Sean Bean,
Judi Dench, Famke Janssen.

Review by Sue Roberts.

The EVIL plot- to steal the "Goldeneye," which controls a space ray
capable of  knocking out electric's for a thirty mile radius on earth.
Can Bond find it before they cause terminal damage to all those
computers? And just how many satellites are there?

Best opening graphics ever- fab. montages! I could have sat through two
hours of just that. And don't you just love that theme music?

All the glamour and sweeping scale of the best 007 movies is on display.
However Brosnan is an entirely new kind of Bond, who views his opponents
with a hint of boyish amazement, (I mean, how could the cads behave like
that?) And , of course, he charms the sox off the ladies!

Scorupco is excellent and plays the heroine, Natalya, using wide eyed
innocence to disguise her intelligence. A beautifully judged parody of
this role.

They play the "Brit" card for all its worth. M's upstairs entourage
stiffly maintain a facade devoid of panic, no matter how serious the
situation, while downstairs in the gadget department the mask slips and
we see a more genuine U.K. response to a crisis from Q, in a great cameo
from David Llewelyn, and his backroom boys.

The photography is excellent and in the second half we really get the
benefit with all those great vehicles and effects. Cute helicopter,
smashing train, and best of all, a car chase which is an absolute
CLASSIC. "St. Petersburg" looks devastating..Anyway, the movie is worth
seeing for that alone.

Oh, and I loved the "Post- Stalinist" graveyard. Totally surreal. I felt
these touches worked best of all and were a nice contrast to the high
tech. interiors.

They stick to the formula, but manage to get plenty of variety into
their locations.

What the heck this is all good Saturday night stuff. And the complexity
of it! But come on guys- live dangerously! Just remember, we LIKE to be
blinded by loads of scientific jargon. When you do the video, how about
running some of that dialogue at 27 frames a second? It'll then match
the momentum your SFX team have worked so well to create. It looks
wonderful, but pace was always the hallmark of a Bond.

Sue Roberts
SRoberts@griffin.compulink.co.uk

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
/*
 * Camel ApiMethod Enumeration generated by camel-api-component-maven-plugin
 */
package org.apache.camel.component.box.internal;

import java.lang.reflect.Method;
import java.util.List;

import org.apache.camel.component.box.api.BoxEventLogsManager;

import org.apache.camel.support.component.ApiMethod;
import org.apache.camel.support.component.ApiMethodArg;
import org.apache.camel.support.component.ApiMethodImpl;

import static org.apache.camel.support.component.ApiMethodArg.arg;

/**
 * Camel {@link ApiMethod} Enumeration for org.apache.camel.component.box.api.BoxEventLogsManager
 */
public enum BoxEventLogsManagerApiMethod implements ApiMethod {

    GET_ENTERPRISE_EVENTS(
        java.util.List.class,
        "getEnterpriseEvents",
        arg("position", String.class),
        arg("after", java.util.Date.class),
        arg("before", java.util.Date.class),
        arg("types", new com.box.sdk.BoxEvent.Type[0].getClass()));

    private final ApiMethod apiMethod;

    private BoxEventLogsManagerApiMethod(Class<?> resultType, String name, ApiMethodArg... args) {
        this.apiMethod = new ApiMethodImpl(BoxEventLogsManager.class, resultType, name, args);
    }

    @Override
    public String getName() { return apiMethod.getName(); }

    @Override
    public Class<?> getResultType() { return apiMethod.getResultType(); }

    @Override
    public List<String> getArgNames() { return apiMethod.getArgNames(); }

    @Override
    public List<Class<?>> getArgTypes() { return apiMethod.getArgTypes(); }

    @Override
    public Method getMethod() { return apiMethod.getMethod(); }
}


text:
import os, sys, subprocess, difflib, time, signal

class Timeout(RuntimeError):
    def __str__(self):
        return "Timeout"

def runProc(process, timeout):
    start = time.time()
    while process.poll() is None:
        time.sleep(1.0)
        if float(time.time() - start) > float(timeout):
            os.kill(process.pid, signal.SIGKILL)
            os.waitpid(-1, os.WNOHANG)
            raise Timeout
    return process.communicate()

def compare(ref, test):
    ref_lines = [l.strip() for l in open(ref, 'U').readlines() if l.strip()]
    test_lines = [l.strip() for l in open(test, 'U').readlines() if l.strip()]
    diffOutput = difflib.unified_diff(ref_lines,
                                      test_lines,
                                      fromfile="Solutions",
                                      tofile="Test")
    tx = ''
    for line in diffOutput:
        tx = tx + line

    if tx: return 0
    else: return 1

def runTest(page, test, ref_output, test_output):
    try:
        p = subprocess.Popen('python %s %s %s %s' % (program, page, test, test_output), shell=True)
        runProc(p, timeout)
        return compare(ref_output, test_output)
    except Timeout:
        print ("Timeout")
        return 0
    except:
        print ("Interpreter Error")
        return 0

program = "browser_test.py"
testDir = "tests" + os.sep
timeout = 10

categories = ['rx-grader']
categories.sort()
tests = {}
scores = {}
max_scores = {}
for cat in categories:
    tests[cat] = filter(lambda f: f.endswith(".164"), os.listdir(testDir + cat))
    scores[cat] = 0
    max_scores[cat] = 0

for (cat, tl) in tests.items():
    for test in tl:
        testPath = testDir + cat + os.sep + test
        page = testDir + cat + os.sep + 'page.tml'
        ref_output = testPath + '.out'
        test_output = testPath + '.tmp'
        res = runTest(page, testPath, ref_output, test_output)
        if (res == 0):
            print (cat + os.sep + test + '  Failed')
        scores[cat] = scores[cat] + res
        max_scores[cat] = max_scores[cat] + 1

total = 0
max_total = 0
print ("\nScores:")
for cat in categories:
    print ("\t" + cat + ": " + str(scores[cat]) + " passed out of " + str(max_scores[cat]))
    total = total + scores[cat]
    max_total = max_total + max_scores[cat]

print ("Total: " + str(total) + " \ " + str(max_total))


text:
package entropy

import (
	"container/heap"
	"fmt"
	"kanzi"
)

const (
	FULL_ALPHABET          = 0
	PARTIAL_ALPHABET       = 1
	SEVEN_BIT_ALPHABET     = 0
	EIGHT_BIT_ALPHABET     = 1
	DELTA_ENCODED_ALPHABET = 0
	BIT_ENCODED_ALPHABET   = 1
	PRESENT_SYMBOLS_MASK   = 0
	ABSENT_SYMBOLS_MASK    = 1
)

type ErrorComparator struct {
	symbols []byte
	errors  []int
}

func ByIncreasingError(symbols []byte, errors []int) ErrorComparator {
	return ErrorComparator{symbols: symbols, errors: errors}
}

func (this ErrorComparator) Less(i, j int) bool {
	// Check errors (natural order) as first key
	ri := this.symbols[i]
	rj := this.symbols[j]

	if this.errors[ri] != this.errors[rj] {
		return this.errors[ri] < this.errors[rj]
	}

	// Check index (natural order) as second key
	return ri < rj
}

func (this ErrorComparator) Len() int {
	return len(this.symbols)
}

func (this ErrorComparator) Swap(i, j int) {
	this.symbols[i], this.symbols[j] = this.symbols[j], this.symbols[i]
}

type FreqSortData struct {
	frequencies []int
	errors      []int
	symbol      byte
}

type FreqSortPriorityQueue []*FreqSortData

func (this FreqSortPriorityQueue) Len() int {
	return len(this)
}

func (this FreqSortPriorityQueue) Less(i, j int) bool {
	di := this[i]
	dj := this[j]

	// Decreasing error
	if di.errors[di.symbol] != dj.errors[dj.symbol] {
		return di.errors[di.symbol] > dj.errors[dj.symbol]
	}

	// Decreasing frequency
	if di.frequencies[di.symbol] != dj.frequencies[dj.symbol] {
		return di.frequencies[di.symbol] > dj.frequencies[dj.symbol]
	}

	// Decreasing symbol
	return dj.symbol < di.symbol
}

func (this FreqSortPriorityQueue) Swap(i, j int) {
	this[i], this[j] = this[j], this[i]
}

func (this *FreqSortPriorityQueue) Push(data interface{}) {
	*this = append(*this, data.(*FreqSortData))
}

func (this *FreqSortPriorityQueue) Pop() interface{} {
	old := *this
	n := len(old)
	data := old[n-1]
	*this = old[0 : n-1]
	return data
}

type EntropyUtils struct {
	ranks  []byte
	errors []int
}

func NewEntropyUtils() (*EntropyUtils, error) {
	this := new(EntropyUtils)
	this.ranks = make([]byte, 0)
	this.errors = make([]int, 0)
	return this, nil
}

// alphabet must be sorted in increasing order
func EncodeAlphabet(obs kanzi.OutputBitStream, alphabet []byte) int {
	alphabetSize := len(alphabet)

	// First, push alphabet encoding mode
	if alphabetSize == 256 {
		// Full alphabet
		obs.WriteBit(FULL_ALPHABET)
		obs.WriteBit(EIGHT_BIT_ALPHABET)
		return 256
	}

	if alphabetSize == 128 {
		flag := true

		for i := byte(0); i < 128; i++ {
			if alphabet[i] != i {
				flag = false
				break
			}
		}

		if flag == true {
			obs.WriteBit(FULL_ALPHABET)
			obs.WriteBit(SEVEN_BIT_ALPHABET)
			return 128
		}
	}

	obs.WriteBit(PARTIAL_ALPHABET)

	diffs := make([]int, 32)
	maxSymbolDiff := 1

	if (alphabetSize != 0) && ((alphabetSize < 32) || (alphabetSize > 224)) {
		obs.WriteBit(DELTA_ENCODED_ALPHABET)

		if alphabetSize >= 224 {
			// Big alphabet, encode all missing symbols
			alphabetSize = 256 - alphabetSize
			obs.WriteBits(uint64(alphabetSize), 5)
			obs.WriteBit(ABSENT_SYMBOLS_MASK)
			symbol := uint8(0)
			previous := uint8(0)

			for i, n := 0, 0; n < alphabetSize; {
				if symbol == alphabet[i] {
					if i < len(alphabet)-1 {
						i++
					}

					symbol++
					continue
				}

				diffs[n] = int(symbol) - int(previous)
				symbol++
				previous = symbol

				if diffs[n] > maxSymbolDiff {
					maxSymbolDiff = diffs[n]
				}

				n++
			}
		} else {
			// Small alphabet, encode all present symbols
			obs.WriteBits(uint64(alphabetSize), 5)
			obs.WriteBit(PRESENT_SYMBOLS_MASK)
			previous := uint8(0)

			for i := 0; i < alphabetSize; i++ {
				diffs[i] = int(alphabet[i]) - int(previous)
				previous = alphabet[i] + 1

				if diffs[i] > maxSymbolDiff {
					maxSymbolDiff = diffs[i]
				}
			}
		}

		// Write log(max(diff)) to bitstream
		log := uint(1)

		for 1<<log <= maxSymbolDiff {
			log++
		}

		obs.WriteBits(uint64(log-1), 3) // delta size

		// Write all symbols with delta encoding
		for i := 0; i < alphabetSize; i++ {
			obs.WriteBits(uint64(diffs[i]), log)
		}
	} else {
		// Regular (or empty) alphabet
		obs.WriteBit(BIT_ENCODED_ALPHABET)
		masks := make([]uint64, 4)

		for i := 0; i < alphabetSize; i++ {
			masks[alphabet[i]>>6] |= (1 << uint(alphabet[i]&63))
		}

		for i := range masks {
			obs.WriteBits(masks[i], 64)
		}
	}

	return alphabetSize
}

func DecodeAlphabet(ibs kanzi.InputBitStream, alphabet []byte) (int, error) {
	// Read encoding mode from bitstream
	aphabetType := ibs.ReadBit()

	if aphabetType == FULL_ALPHABET {
		mode := ibs.ReadBit()
		var alphabetSize int

		if mode == EIGHT_BIT_ALPHABET {
			alphabetSize = 256
		} else {
			alphabetSize = 128
		}

		// Full alphabet
		for i := 0; i < alphabetSize; i++ {
			alphabet[i] = byte(i)
		}

		return alphabetSize, nil
	}

	alphabetSize := 0
	mode := ibs.ReadBit()

	if mode == BIT_ENCODED_ALPHABET {
		// Decode presence flags
		for i := 0; i < 256; i += 64 {
			val := ibs.ReadBits(64)

			for j := 0; j < 64; j++ {
				if val&(uint64(1)<<uint(j)) != 0 {
					alphabet[alphabetSize] = byte(i + j)
					alphabetSize++
				}
			}
		}
	} else { // DELTA_ENCODED_ALPHABET
		val := int(ibs.ReadBits(6))
		log := uint(1 + ibs.ReadBits(3)) // log(max(diff))
		alphabetSize = val >> 1
		n := 0
		symbol := uint8(0)

		if val&1 == ABSENT_SYMBOLS_MASK {
			for i := 0; i < alphabetSize; i++ {
				next := symbol + byte(ibs.ReadBits(log))

				for symbol < next {
					alphabet[n] = symbol
					symbol++
					n++
				}

				symbol++
			}

			alphabetSize = 256 - alphabetSize

			for n < alphabetSize {
				alphabet[n] = symbol
				n++
				symbol++
			}

		} else {
			for i := 0; i < alphabetSize; i++ {
				symbol += uint8(ibs.ReadBits(log))
				alphabet[i] = symbol
				symbol++
			}
		}
	}

	return alphabetSize, nil
}

// Returns the size of the alphabet
// The alphabet and freqs parameters are updated
func (this *EntropyUtils) NormalizeFrequencies(freqs []int, alphabet []byte, count int, scale int) (int, error) {
	if count == 0 {
		return 0, nil
	}

	if scale < 1<<8 || scale > 1<<16 {
		return 0, fmt.Errorf("Invalid range parameter: %v (must be in [256..65536])", scale)
	}

	alphabetSize := 0

	// range == count shortcut
	if count == scale {
		for i := 0; i < 256; i++ {
			if freqs[i] != 0 {
				alphabet[alphabetSize] = byte(i)
				alphabetSize++
			}
		}

		return alphabetSize, nil
	}

	if len(this.ranks) < 256 {
		this.ranks = make([]byte, 256)
	}

	if len(this.errors) < 256 {
		this.errors = make([]int, 256)
	}

	ranks := this.ranks
	errors := this.errors
	sum := -scale
	// Scale frequencies by stretching distribution over complete range
	for i := 0; i < 256; i++ {
		alphabet[i] = 0
		errors[i] = -1
		ranks[i] = byte(i)

		if freqs[i] == 0 {
			continue
		}

		sf := int64(freqs[i]) * int64(scale)
		scaledFreq := int(sf / int64(count))

		if scaledFreq == 0 {
			// Quantum of frequency
			scaledFreq = 1
		} else {
			// Find best frequency rounding value
			errCeiling := int64(scaledFreq+1)*int64(count) - sf
			errFloor := sf - int64(scaledFreq)*int64(count)

			if errCeiling < errFloor {
				scaledFreq++
				errors[i] = int(errCeiling)
			} else {
				errors[i] = int(errFloor)
			}
		}

		alphabet[alphabetSize] = byte(i)
		alphabetSize++
		sum += scaledFreq
		freqs[i] = scaledFreq
	}

	if alphabetSize == 0 {
		return 0, nil
	}

	if alphabetSize == 1 {
		freqs[alphabet[0]] = scale
		return 1, nil
	}

	if sum != 0 {
		// Need to normalize frequency sum to range
		var inc int

		if sum > 0 {
			inc = -1
		} else {
			inc = 1
		}

		queue := make(FreqSortPriorityQueue, 0)

		// Create sorted queue of present symbols (except those with 'quantum frequency')
		for i := 0; i < alphabetSize; i++ {
			if errors[alphabet[i]] >= 0 {
				heap.Push(&queue, &FreqSortData{errors: errors, frequencies: freqs, symbol: alphabet[i]})
			}
		}

		for sum != 0 && len(queue) > 0 {
			// Remove symbol with highest error
			fsd := heap.Pop(&queue).(*FreqSortData)

			// Do not zero out any frequency
			if freqs[fsd.symbol] == -inc {
				continue
			}

			// Distort frequency and error
			freqs[fsd.symbol] += inc
			errors[fsd.symbol] -= scale
			sum += inc
			heap.Push(&queue, fsd)
		}
	}

	return alphabetSize, nil
}


text:
Originally published: 2016-04-07 18:19:34
Last updated: 2016-04-07 18:19:35
Author: Vasudev Ram

This recipe shows how to create a simple binary file split utility in Python.

It takes two command line arguments: 1) the name of the input file to split , 2) the number of bytes per file into which to split the input.


text:
package garden

import proto "github.com/gogo/protobuf/proto"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf

type GetPropertyRequest struct {
	Handle           *string `protobuf:"bytes,1,opt,name=handle" json:"handle,omitempty"`
	Key              *string `protobuf:"bytes,2,opt,name=key" json:"key,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *GetPropertyRequest) Reset()         { *m = GetPropertyRequest{} }
func (m *GetPropertyRequest) String() string { return proto.CompactTextString(m) }
func (*GetPropertyRequest) ProtoMessage()    {}

func (m *GetPropertyRequest) GetHandle() string {
	if m != nil && m.Handle != nil {
		return *m.Handle
	}
	return ""
}

func (m *GetPropertyRequest) GetKey() string {
	if m != nil && m.Key != nil {
		return *m.Key
	}
	return ""
}

type GetPropertyResponse struct {
	Value            *string `protobuf:"bytes,1,req,name=value" json:"value,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *GetPropertyResponse) Reset()         { *m = GetPropertyResponse{} }
func (m *GetPropertyResponse) String() string { return proto.CompactTextString(m) }
func (*GetPropertyResponse) ProtoMessage()    {}

func (m *GetPropertyResponse) GetValue() string {
	if m != nil && m.Value != nil {
		return *m.Value
	}
	return ""
}

func init() {
}


text:
using System.Reflection;

namespace SimpleObjectFactory
{
    internal class SingletonObjectCreator<T> : IObjectCreator
    {
        private object instance;

        public object GetService(ObjectFactory factory)
        {
            if (instance != null)
                return instance;

            var implementationType = typeof(T);

            foreach (var constructor in implementationType.GetTypeInfo().DeclaredConstructors)
            {
                if (constructor.IsPublic)
                {
                    var parameterInfos = constructor.GetParameters();
                    var parameters = new object[parameterInfos.Length];
                    var parametersCompleted = true;

                    for (int i = 0; i < parameterInfos.Length; i++)
                    {
                        var parameterInfo = parameterInfos[i];
                        var parameter = factory.GetInstance(parameterInfo.ParameterType);
                        if (parameter == null)
                        {
                            parametersCompleted = false;
                            break;
                        }

                        parameters[i] = parameter;
                    }

                    if (parametersCompleted)
                    {
                        instance = constructor.Invoke(parameters);
                        return instance;
                    }
                }
            }

            return null;
        }
    }
}


text:
<Type Name="NSPathCellDisplayPanelEventArgs" FullName="MonoMac.AppKit.NSPathCellDisplayPanelEventArgs">
  <TypeSignature Language="C#" Value="public class NSPathCellDisplayPanelEventArgs : EventArgs" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit NSPathCellDisplayPanelEventArgs extends System.EventArgs" />
  <AssemblyInfo>
    <AssemblyName>MonoMac</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.EventArgs</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public NSPathCellDisplayPanelEventArgs (MonoMac.AppKit.NSOpenPanel openPanel);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class MonoMac.AppKit.NSOpenPanel openPanel) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="openPanel" Type="MonoMac.AppKit.NSOpenPanel" />
      </Parameters>
      <Docs>
        <param name="openPanel">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OpenPanel">
      <MemberSignature Language="C#" Value="public MonoMac.AppKit.NSOpenPanel OpenPanel { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class MonoMac.AppKit.NSOpenPanel OpenPanel" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.AppKit.NSOpenPanel</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
namespace ui {

void ResourceBundle::LoadCommonResources() {
  LoadChromeResources();
}

gfx::Image& ResourceBundle::GetNativeImageNamed(int resource_id, ImageRTL rtl) {
  // Flipped image is not used on ChromeOS.
  DCHECK_EQ(rtl, RTL_DISABLED);
  return GetImageNamed(resource_id);
}

}  // namespace ui


text:
<?php

namespace Transit;

use Transit\Exception\IoException;
use \InvalidArgumentException;
use \Closure;

/**
 * Handles the management of a single file on the file system.
 * Can return detailed information on the file as well as moving and renaming.
 *
 * @package Transit
 */
class File {

    /**
     * Cached values.
     *
     * @type array
     */
    protected $_cache = array();

    /**
     * Raw $_FILES data.
     *
     * @type array
     */
    protected $_data = array();

    /**
     * Absolute file path.
     *
     * @type string
     */
    protected $_path;

    /**
     * Store the file path.
     *
     * @param string|array $path
     * @throws \Transit\Exception\IoException
     */
    public function __construct($path) {
        if (is_array($path)) {
            if (empty($path['tmp_name'])) {
                throw new IoException('Passing via array must use $_FILES data');
            }

            $this->_data = $path;
            $path = $path['tmp_name'];
        }

        if (!file_exists($path)) {
            throw new IoException(sprintf('%s does not exist', $path));
        }

        $this->_path = $path;

        // @version 1.3.2 Rename file to add ext if ext is missing
        if (!$this->ext()) {
            $this->rename();
        }

        // @version 1.4.0 Reset the cache
        $this->_cache = array();
    }

    /**
     * Magic method for toString().
     *
     * @return string
     */
    public function __toString() {
        return $this->toString();
    }

    /**
     * Return the file name with extension.
     *
     * @return string
     */
    public function basename() {
        // @version 1.2.0 Use filename then fallback to path
        $path = $this->data('name') ?: $this->path();

        return pathinfo($path, PATHINFO_BASENAME);
    }

    /**
     * Return the $_FILES data.
     *
     * @param string $key
     * @return string
     */
    public function data($key) {
        return !empty($this->_data[$key]) ? $this->_data[$key] : null;
    }

    /**
     * Delete the file.
     *
     * @return bool
     */
    public function delete() {
        $this->reset();

        return @unlink($this->_path);
    }

    /**
     * Return the dimensions of the file if it is an image.
     *
     * @return array
     */
    public function dimensions() {
        return $this->_cache(__FUNCTION__, function($file) {
            /** @type \Transit\File $file */

            $dims = null;

            if (!$file->isImage()) {
                return $dims;
            }

            $data = @getimagesize($file->path());

            if ($data && is_array($data)) {
                $dims = array(
                    'width' => $data[0],
                    'height' => $data[1]
                );
            }

            if (!$data) {
                $image = @imagecreatefromstring(file_get_contents($file->path()));
                $dims = array(
                    'width' => @imagesx($image),
                    'height' => @imagesy($image)
                );
            }

            return $dims;
        });
    }

    /**
     * Return the directory the file is in.
     *
     * @return string
     */
    public function dir() {
        return dirname($this->_path) . '/';
    }

    /**
     * Attempt to read and determine correct exif data.
     *
     * @param array $fields
     * @returns array
     */
    public function exif(array $fields = array()) {
        if (!function_exists('exif_read_data')) {
            return array();
        }

        return $this->_cache(__FUNCTION__, function($file) use ($fields) {
            /** @type \Transit\File $file */

            $exif = array();
            $fields = $fields + array(
                'make' => 'Make',
                'model' => 'Model',
                'exposure' => 'ExposureTime',
                'orientation' => 'Orientation',
                'fnumber' => 'FNumber',
                'date' => 'DateTime',
                'iso' => 'ISOSpeedRatings',
                'focal' => 'FocalLength'
            );

            if ($file->supportsExif()) {
                if ($data = @exif_read_data($file->path())) {
                    foreach ($fields as $key => $find) {
                        $value = '';

                        if (!empty($data[$find])) {
                            $value = $data[$find];
                        }

                        $exif[$key] = $value;
                    }
                }
            }

            // Return empty values for files that don't support exif
            if (!$exif) {
                $exif = array_map(function() {
                    return '';
                }, $fields);
            }

            return $exif;
        });
    }

    /**
     * Return the extension.
     *
     * @return string
     */
    public function ext() {
        return $this->_cache(__FUNCTION__, function($file) {
            /** @type \Transit\File $file */

            // @version 1.1.1 Removed because of fileinfo bug
            // return MimeType::getExtFromType($file->type(), true);

            // @version 1.2.0 Allow support for $_FILES array
            $path = $file->data('name') ?: $file->path();

            return mb_strtolower(pathinfo($path, PATHINFO_EXTENSION));
        });
    }

    /**
     * Return the image height.
     *
     * @return int
     */
    public function height() {
        return $this->_cache(__FUNCTION__, function($file) {
            /** @type \Transit\File $file */

            if (!$file->isImage()) {
                return null;
            }

            $height = 0;

            if ($dims = $file->dimensions()) {
                $height = $dims['height'];
            }

            return $height;
        });
    }

    /**
     * Return true if the file is an application.
     *
     * @uses Transit\MimeType
     *
     * @return bool
     */
    public function isApplication() {
        return MimeType::isApplication($this);
    }

    /**
     * Return true if the file is an audio.
     *
     * @uses Transit\MimeType
     *
     * @return bool
     */
    public function isAudio() {
        return MimeType::isAudio($this);
    }

    /**
     * Return true if the file is an image.
     *
     * @uses Transit\MimeType
     *
     * @return bool
     */
    public function isImage() {
        return MimeType::isImage($this);
    }

    /**
     * Return true if the file is a text.
     *
     * @uses Transit\MimeType
     *
     * @return bool
     */
    public function isText() {
        return MimeType::isText($this);
    }

    /**
     * Return true if the file is a video.
     *
     * @uses Transit\MimeType
     *
     * @return bool
     */
    public function isVideo() {
        return MimeType::isVideo($this);
    }

    /**
     * Return true if the file is part of a sub-type.
     *
     * @uses Transit\MimeType
     *
     * @param string $subType
     * @return bool
     */
    public function isSubType($subType) {
        return MimeType::isSubType($subType, $this);
    }

    /**
     * Move the file to a new directory.
     * If a file with the same name already exists, either overwrite or increment file name.
     *
     * @param string $path
     * @param bool $overwrite
     * @return bool
     */
    public function move($path, $overwrite = false) {
        $path = str_replace('\\', '/', $path);

        if (substr($path, -1) !== '/') {
            $path .= '/';
        }

        // Don't move to the same folder
        if (realpath($path) === realpath($this->dir())) {
            return true;
        }

        if (!file_exists($path)) {
            mkdir($path, 0777, true);

        } else if (!is_writable($path)) {
            chmod($path, 0777);
        }

        // Determine name and overwrite
        $name = $this->name();
        $ext = $this->ext();

        if (!$overwrite) {
            $no = 1;

            while (file_exists($path . $name . '.' . $ext)) {
                $name = $this->name() . '-' . $no;
                $no++;
            }
        }

        // Move the file
        $targetPath = $path . $name . '.' . $ext;

        if (rename($this->path(), $targetPath)) {
            $this->reset($targetPath);

            return true;
        }

        return false;
    }

    /**
     * Return the file name without extension.
     *
     * @return string
     */
    public function name() {
        // @version 1.2.0 Use filename then fallback to path
        $path = $this->data('name') ?: $this->path();

        return pathinfo($path, PATHINFO_FILENAME);
    }

    /**
     * Return the absolute path.
     *
     * @return string
     */
    public function path() {
        return $this->_path;
    }

    /**
     * Rename the file within the current directory.
     *
     * @param string $name
     * @param string $append
     * @param string $prepend
     * @return bool
     */
    public function rename($name = '', $append = '', $prepend = '') {
        if (is_callable($name)) {
            $name = call_user_func_array($name, array($this->name(), $this));
        } else {
            $name = $name ?: $this->name();
        }

        // Add boundaries
        $name = (string) $prepend . $name . (string) $append;

        // Remove unwanted characters
        $name = preg_replace('/[^_\-\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/imu', '-', $name);

        // Rename file
        $ext = $this->ext() ?: MimeType::getExtFromType($this->type(), true);
        $targetPath = $this->dir() . $name . '.' . $ext;

        if (rename($this->path(), $targetPath)) {
            $this->reset($targetPath);

            return true;
        }

        return false;
    }

    /**
     * Reset all cache.
     *
     * @param string $path
     * @return \Transit\File
     */
    public function reset($path = '') {
        clearstatcache();

        $this->_cache = array();

        if ($path) {
            $this->_data['name'] = basename($path);
            $this->_path = $path;
        }

        return $this;
    }

    /**
     * Return the file size.
     *
     * @return int
     */
    public function size() {
        return filesize($this->_path);
    }

    /**
     * Checks if the file supports exif data.
     *
     * @return bool
     */
    public function supportsExif() {
        return $this->_cache(__FUNCTION__, function($file) {
            /** @type \Transit\File $file */

            if (!$file->isImage()) {
                return false;
            }

            return in_array($file->type(), array('image/jpeg', 'image/tiff'));
        });
    }

    /**
     * Return the mime type.
     *
     * @uses Transit\MimeType
     *
     * @return string
     */
    public function type() {
        return $this->_cache(__FUNCTION__, function($file) {
            /** @type \Transit\File $file */

            $type = null;

            // We can't use the file command on windows
            if (!defined('PHP_WINDOWS_VERSION_MAJOR')) {
                $type = shell_exec(sprintf("file -b --mime %s", escapeshellarg($file->path())));

                if ($type && strpos($type, ';') !== false) {
                    $type = strstr($type, ';', true);
                }
            }

            // Fallback because of fileinfo bug: https://bugs.php.net/bug.php?id=53035
            if (!$type) {
                $info = finfo_open(FILEINFO_MIME_TYPE);
                $type = finfo_file($info, $file->path());
                finfo_close($info);
            }

            // Check the mimetype against the extension
            // If they are different, use the extension since fileinfo returns invalid mimetypes
            // This could be problematic in the future, but unknown better alternative
            if ($ext = $file->ext()) {
                try {
                    $extType = MimeType::getTypeFromExt($ext);

                // Use $_FILES['type'] last since sometimes it returns application/octet-stream and other mimetypes
                // When we should always have a true mimetype
                } catch (InvalidArgumentException $e) {
                    $extType = $file->data('type');
                }

                if (!empty($extType) && $type !== $extType) {
                    $type = $extType;
                }
            }

            return $type;
        });
    }

    /**
     * Return the image width.
     *
     * @return int
     */
    public function width() {
        return $this->_cache(__FUNCTION__, function($file) {
            /** @type \Transit\File $file */

            if (!$file->isImage()) {
                return null;
            }

            $width = 0;

            if ($dims = $file->dimensions()) {
                $width = $dims['width'];
            }

            return $width;
        });
    }

    /**
     * Return all File information as an array.
     *
     * @return array
     */
    public function toArray() {
        $data = array(
            'basename' => $this->basename(),
            'dir' => $this->dir(),
            'ext' => $this->ext(),
            'name' => $this->name(),
            'path' => $this->path(),
            'size' => $this->size(),
            'type' => $this->type(),
            'height' => $this->height(),
            'width' => $this->width()
        );

        // Include exif data
        foreach ($this->exif() as $key => $value) {
            $data['exif.' . $key] = $value;
        }

        return $data;
    }

    /**
     * Return path when cast to string.
     *
     * @return string
     */
    public function toString() {
        return $this->path();
    }

    /**
     * Cache the results of a callback.
     *
     * @param string $key
     * @param \Closure $callback
     * @return mixed
     */
    protected function _cache($key, Closure $callback) {
        if (isset($this->_cache[$key])) {
            return $this->_cache[$key];
        }

        // Requires 5.4
        // Closure::bind($callback, $this, __CLASS__);

        $this->_cache[$key] = $callback($this);

        return $this->_cache[$key];
    }

}


text:
package types

import (
	"encoding/json"
	"fmt"
	"html/template"
	"reflect"
	"time"

	"github.com/spf13/cast"
)

// ToDuration converts v to time.Duration.
// See ToDurationE if you need to handle errors.
func ToDuration(v any) time.Duration {
	d, _ := ToDurationE(v)
	return d
}

// ToDurationE converts v to time.Duration.
func ToDurationE(v any) (time.Duration, error) {
	if n := cast.ToInt(v); n > 0 {
		return time.Duration(n) * time.Millisecond, nil
	}
	d, err := time.ParseDuration(cast.ToString(v))
	if err != nil {
		return 0, fmt.Errorf("cannot convert %v to time.Duration", v)
	}
	return d, nil
}

// ToStringSlicePreserveString is the same as ToStringSlicePreserveStringE,
// but it never fails.
func ToStringSlicePreserveString(v any) []string {
	vv, _ := ToStringSlicePreserveStringE(v)
	return vv
}

// ToStringSlicePreserveStringE converts v to a string slice.
// If v is a string, it will be wrapped in a string slice.
func ToStringSlicePreserveStringE(v any) ([]string, error) {
	if v == nil {
		return nil, nil
	}
	if sds, ok := v.(string); ok {
		return []string{sds}, nil
	}
	result, err := cast.ToStringSliceE(v)
	if err == nil {
		return result, nil
	}

	// Probably []int or similar. Fall back to reflect.
	vv := reflect.ValueOf(v)

	switch vv.Kind() {
	case reflect.Slice, reflect.Array:
		result = make([]string, vv.Len())
		for i := 0; i < vv.Len(); i++ {
			s, err := cast.ToStringE(vv.Index(i).Interface())
			if err != nil {
				return nil, err
			}
			result[i] = s
		}
		return result, nil
	default:
		return nil, fmt.Errorf("failed to convert %T to a string slice", v)
	}

}

// TypeToString converts v to a string if it's a valid string type.
// Note that this will not try to convert numeric values etc.,
// use ToString for that.
func TypeToString(v any) (string, bool) {
	switch s := v.(type) {
	case string:
		return s, true
	case template.HTML:
		return string(s), true
	case template.CSS:
		return string(s), true
	case template.HTMLAttr:
		return string(s), true
	case template.JS:
		return string(s), true
	case template.JSStr:
		return string(s), true
	case template.URL:
		return string(s), true
	case template.Srcset:
		return string(s), true
	}

	return "", false
}

// ToString converts v to a string.
func ToString(v any) string {
	s, _ := ToStringE(v)
	return s
}

// ToStringE converts v to a string.
func ToStringE(v any) (string, error) {
	if s, ok := TypeToString(v); ok {
		return s, nil
	}

	switch s := v.(type) {
	case json.RawMessage:
		return string(s), nil
	default:
		return cast.ToStringE(v)
	}
}


text:
package ru.napadovskiub;

/**
	*Class RemoveDuplicate для удаления дублей из массива.
	*@author napadovskiy
	*@since 15.08.2016
	*@version 1
*/

public class RemoveDuplicate {
    /**
     *Create new array with length of inputString.
     *and fill it with unique elements;
     *and decrement counter
     *then create new array with length of counter
     * @param inputString string for remove duplicate.
     * @return result Array string.
     */
	public String[] removeDuplicate(String[] inputString) {
        String[] tempString = new String[inputString.length];

        int counter = 0;

        for (int i = 0; i < inputString.length; i++) {
            if (i == 0) {
                tempString[counter] = inputString[i];
                counter++;
            } else {
                if (!findeElement(tempString, inputString[i])) {
                    tempString[counter] = inputString[i];
                    counter++;
                }
            }
        }
		String[] resultString = new String[counter];
		for (int i = 0; i < counter; i++) {
			resultString[i] = tempString[i];
		}
		return resultString;
    }

    /**
     *find value in tempString
     *If found then it is not necessary to add.
     * @param tempString string for search.
     * @param value serch value.
     * @return result.
     */
    boolean findeElement(String[] tempString, String value) {
        boolean findeElement = false;
        for (int i = 0; i < tempString.length; i++) {
            if (tempString[i] != null && tempString[i].equals(value)) {
                findeElement = true;
                break;
            }
        }
        return findeElement;
    }
}


text:
'use strict';

describe('GET', function() {

    var agent = chai.request.agent(server);

    beforeEach(function(done) {

        var users = [
            {
                'email': 'user1@mail.com',
                'firstName': 'first1',
                'lastName': 'last1',
                'accountType': 'coach',
                'password': 'password',
                'memberStart': '2017-05-10T09:25:10.000Z',
                'clients': [
                    'user2@mail.com',
                    'user3@mail.com'
                ]
            },
            {
                'email': 'user2@mail.com',
                'firstName': 'first2',
                'lastName': 'last2',
                'accountType': 'client',
                'password': 'password',
                'memberStart': '2017-05-10T09:25:10.000Z',
                'coach': 'user1@mail.com'
            },
            {
                'email': 'user3@mail.com',
                'firstName': 'first3',
                'lastName': 'last3',
                'accountType': 'client',
                'password': 'password',
                'memberStart': '2017-05-10T09:25:10.000Z',
                'coach': 'user1@mail.com'
            }
        ];
        var usersSaved = 0;

        users.forEach(function(current, index, array) {

            var user = new User(current);
            user.save().then(function() {

                usersSaved++;
                if (usersSaved == array.length) {
                    agent
                        .post('/api/authentication/sessions')
                        .send({
                            'email': 'user1@mail.com',
                            'password': 'password'
                        })
                        .end(function(err, res) {

                            done();

                        });
                }

            });

        });

    });

    afterEach(function(done) {

        // Drop all collections in test db
        mongoose.connection.db.listCollections().toArray(function(err, names) {

            if (err) {
                console.error(err);
            } else {
                names.forEach(function(value) {

                    mongoose.connection.db.dropCollection(value.name);

                });

                agent
                    .delete('/api/authentication/sessions')
                    .end(function(err, res) {

                        done();

                    });
            }

        });

    });

    it ('should read a list of existing users from the database on GET /api/users', function(done) {

        agent
            .get('/api/users')
            .send({
                'coach': 'user1@mail.com'
            })
            .end(function(err, res) {

                res.should.have.status(200);
                res.should.be.json;
                res.body.message.should.equal('Users retrieved successfully.');
                res.body.users.should.be.a('array');
                res.body.users[0].should.have.property('email');
                res.body.users[0].email.should.not.equal(null);
                res.body.users[0].should.have.property('accountType');
                res.body.users[0].accountType.should.equal('client');
                res.body.users[0].should.have.property('coach');
                res.body.users[0].coach.should.equal('user1@mail.com');
                res.body.users.should.have.lengthOf(2);
                done();

            });

    });

    it ('should read an existing user from the database on GET /api/users/:email', function(done) {

        User.findOne().then(function(doc) {

            var formattedEmail = doc.email.replace('@', '%40');

            agent
                .get('/api/users/' + formattedEmail)
                .end(function(err, res) {

                    res.should.have.status(200);
                    res.should.be.json;
                    res.body.message.should.equal('User retrieved successfully.');
                    res.body.user.should.be.a('array');
                    res.body.user[0].should.have.property('email');
                    res.body.user[0].email.should.not.equal(null);
                    res.body.user[0].should.have.property('firstName');
                    res.body.user[0].should.have.property('lastName');
                    res.body.user[0].should.have.property('accountType');
                    res.body.user[0].accountType.should.not.equal(null);
                    res.body.user.should.have.lengthOf(1);
                    done();

                });

        });

    });

});


text:
{% extends "layout.min.html" %}
{% block content %}
  {% if finished %}

      {% if imgsetid %}

          Filtering for imgsetid: {{ imgsettext }} ({{ imgsetid }})
          ×

      {% endif %}

    Congratulations, annotation turking is completed.  Thank you!

    View completed annotations

  {% else %}

      {% if imgsetid %}

          Filtering for imgsetid: {{ imgsettext }} ({{ imgsetid }})
          ×

      {% endif %}

      {% if not REFER_DST_ENCODED %}

            {{ progress }}%

      {% endif %}

      Aid: {{ aid }}

      Path: {{ image_path }}

      {% include 'turk/annotation_insert.html' %}

          <button type="button" class="close" data-dismiss="modal">×Close</button>

Annotation Turking Instructions

          To turk a viewpoint, simply adjust the slider for the image based on the following guidelines:

Top-down view (view from above)

              The easiest way to mentally-visualize and decide on the correct viewpoint is by asking "Which way is the head pointing?" in relation to the camera.  However, the pose of the animal will vary wildly based on physical characteristics of the species (long knecks, long legs, etc).  In all cases, use the body position of the animal to decide the orientation instead of the position of the animal's face.

              For example:

For this example, the camera is on the left side of the animal (looking from above), and the correct viewpoint that should be selected is .

For this example, again, the camera is on the left side of the animal (looking from above). However, even though the animal's face is pointed towards the camera, we use the body position to decide the correct orientation. The correct viewpoint that should be selected is .

This is a boarder-line example that is ultimately a left side view of the animal and not front-left.  Therefore, the correct viewpoint that should be selected is .

Another boarder-line example that is also ultimately a left side view of the animal and not back-left. The correct viewpoint that should be selected is .

This example, however, is a back-left side of the animal (looking from above).  The correct viewpoint that should be selected is .

For this example, the camera is on the front-right side of the animal (looking from above).  The correct viewpoint that should be selected is .

For faster viewpoint annotation, the number keys or a keypad can be used.  The numbers 1 thru 8 are mapped to increments of 45°.  We urge every turker to use the number pad to input the viewpoint, but you can further adjust the slider to get even closer accuracy, down to a precision of a single degree.

If the viewpoint cannot be determined due to not enough information (e.g., the animal is obscured by some obstacle, the image is too blurry or there isn't enough light, there is only a small chunk of an animal in the image - like a leg or a piece of the head), you have two choices:

edit the annotation by revisiting the image (link below the image)

simply press the Delete button

The Space key deletes the image and does not save any viewpoint information for that image.  The Enter key submits the current quality of the slider as the image's viewpoint.

Enter viewpoints as fast as you can while maintaining perfect accuracy.

To bring up these instructions again, click on the  button

          To turk a quality, simply adjust the slider for the image based on the following guidelines:

The "information" (keypoints) in the image that we want to classify

              When deciding the quality of an image, it is important to keep in mind what information the underlying image analysis algorithms care about.
              Looking at the image above, the white ellipsis on the body of the animal indicate what informaiton is the most important, whereas the red and orange
              ellipsis indicate information that is less important.

              The quality of the annotation is decided by 4 metrics (by order of importance):

                  Partially Visible - the entire animal is not visible due to visual obstruction by non-landscape objects (other animals, cars, buildings, the animal is off the side of the image, etc.)

                  Occlusion - the entire animal is not visible due to visual obstruction by natural landscape (brush, trees, grass, etc.)

                  Focus - the image of the animal is out of focus

                  Lighting and Shadow - the animal is under- or over-exposed, shadowed by another object, or its own pose is causing shadows on its body

              The way you measure the image's quality will change for each viewpoint.  If the viewpoint would not normally allow for one of the metrics above (e.g. a frontal image of a Plains Zebra would not normally
              give a view of the rump) then that metric can be ignored.  Judge the image on what an "ideal" image of that species given the viewpoint the animal is in.

              For example:

Junk

Severe occlusion

Little to no parts visible

Out of focus

Lots of shadow

Poor

Severe occlusion

Head, shoulder, OR rump visible

Mildly out of focus

Lots of shadow

OK

Little occlusion

Head, shoulder, AND rump visible

In focus

Moderate shadow

Good

Little occlusion

Entire animal visible

In focus

Little shadow

Excellent

No occlusion

Entire animal visible

In focus

No shadow

For faster quality annotation, the number keys or a keypad can be used.  The letters Q (1), W (2), E (3), R (4), T (5) are mapped to their corresponding star ratings.  We urge every turker to use the number pad to input the quality for speed purposes.

If the quality cannot be determined due to not enough information (e.g., the animal is no animal in the image, the image is too blurry or there isn't enough light, there is only a small chunk of an animal in the image - like a leg or a piece of the head), you have two choices:

edit the annotation by revisiting the image (link below the image)

simply press the Delete button

The Space key deletes the image and does not save any quality information for that image.  The Enter key submits the current value of the slider as the image's quality.

Enter qualities as fast as you can while maintaining perfect accuracy.

To bring up these instructions again, click on the  button

          <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="submit_cookie('ia-annotation_instructions_seen', '1');">Got it!</button>

  {% endif %}

          <button type="button" class="close" data-dismiss="modal">×Close</button>

Add a Species

            <input type="text" name="species-add" class="form-control" placeholder="New species tag">

          <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="add_species();">Add</button>

{% endblock %}
{% block content_custom_css %}
  {% if review %}

  {% endif %}
{% endblock %}
{% block content_custom_javascript %}
{% endblock %}