text:
Customer
========

The ``Customer`` class provides an interface to Authorize.net's Customer
Information Manager (CIM) API.

Create
------

When creating a customer profile, no information is actually needed. A random
merchant ID is associated to the customer if none is provided. Once a user
been created, address and payment information can then be associated to the
profile.

Minimal Example
~~~~~~~~~~~~~~~

.. code-block:: python

    result = authorize.Customer.create()

    result.customer_id
    # e.g. '19086351'

Creating Profile with Basic Information
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

    result = authorize.Customer.create({
        'email': 'rob@robotronstudios.com',
        'description': 'Rob the robot',
        'customer_type': 'individual',
    })

    result.customer_id
    # e.g. '19086352'

Full Example
~~~~~~~~~~~~

When creating a customer, additional shipping address and payment information
can be provided as well.

.. code-block:: python

    result = authorize.Customer.create({
        'merchant_id': '8989762983402603',
        'email': 'rob@robotronstudios.com',
        'description': 'Rob the robot',
        'customer_type': 'individual',
        'billing': {
            'first_name': 'Rob',
            'last_name': 'Oteron',
            'company': 'Robotron Studios',
            'address': '101 Computer Street',
            'city': 'Tucson',
            'state': 'AZ',
            'zip': '85704',
            'country': 'US',
            'phone_number': '520-123-4567',
            'fax_number': '520-456-7890',
        },
        'credit_card': {
            'card_number': '4111111111111111',
            'card_code': '456',
            'expiration_month': '04',
            'expiration_year': '2014',
        },
        'shipping': {
            'first_name': 'Rob',
            'last_name': 'Oteron',
            'company': 'Robotron Studios',
            'address': '101 Computer Street',
            'city': 'Tucson',
            'state': 'AZ',
            'zip': '85704',
            'country': 'US',
            'phone_number': '520-123-4567',
            'fax_number': '520-456-7890',
        }
    })

    result.customer_id
    # e.g. '19086352'

Details
-------

The ``details`` method returns the information for a given customer profile
based on the customer ID.

The following information is returned in the result attribute dictionary:

- ``profile.merchant_id``
- ``profile.email``
- ``profile.description``
- ``profile.customer_type``
- ``address_ids``
- ``payment_ids``

.. code-block:: python

    result = authorize.Customer.details('19086352')

Update
------

Customer profile information can be easily updated on the server.

.. code-block:: python

    result = authorize.Customer.update('19086352', {
        'email': 'rob@robotronstudios.com',
        'description': 'Rob the robot',
        'customer_type': 'individual',
    })

Delete
------

Deleting a customer will delete the customer profile along with all stored
addresses and billing information.

.. code-block:: python

    result = authorize.Customer.delete('19086352')

List
----

The ``list`` method returns a list of all customer profile IDs.

.. code-block:: python

    result = authorize.Customer.list()

    result.profile_ids
    # e.g. ['16467005', '16467010', '16467092', '17556329']


text:
namespace Azure.ResourceManager.RecoveryServicesSiteRecovery.Models
{
    /// <summary> Discover protectable item properties. </summary>
    public partial class DiscoverProtectableItemRequestProperties
    {
        /// <summary> Initializes a new instance of DiscoverProtectableItemRequestProperties. </summary>
        public DiscoverProtectableItemRequestProperties()
        {
        }

        /// <summary> The friendly name of the physical machine. </summary>
        public string FriendlyName { get; set; }
        /// <summary> The IP address of the physical machine to be discovered. </summary>
        public string IPAddress { get; set; }
        /// <summary> The OS type on the physical machine. </summary>
        public string OSType { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Parallel;
using System.Diagnostics;
using System.Threading.Tasks;

namespace System.Linq.Parallel
{
    /// <summary>
    /// A special merge helper for indexible queries. Given an indexible query, we know how many elements
    /// we'll have in the result set, so we can allocate the array ahead of time. Then, as each result element
    /// is produced, we can directly insert it into the appropriate position in the output array, paying
    /// no extra cost for ordering.
    /// </summary>
    /// <typeparam name="TInputOutput"></typeparam>
    internal class ArrayMergeHelper<TInputOutput> : IMergeHelper<TInputOutput>
    {
        private QueryResults<TInputOutput> _queryResults; // Indexible query results
        private TInputOutput[] _outputArray; // The output array.
        private QuerySettings _settings; // Settings for the query.

        /// <summary>
        /// Instantiates the array merge helper.
        /// </summary>
        /// <param name="settings">The query settings</param>
        /// <param name="queryResults">The query results</param>
        public ArrayMergeHelper(QuerySettings settings, QueryResults<TInputOutput> queryResults)
        {
            _settings = settings;
            _queryResults = queryResults;

            int count = _queryResults.Count;
            _outputArray = new TInputOutput[count];
        }

        /// <summary>
        /// A method used as a delegate passed into the ForAll operator
        /// </summary>
        private void ToArrayElement(int index)
        {
            _outputArray[index] = _queryResults[index];
        }

        /// <summary>
        /// Schedules execution of the merge itself.
        /// </summary>
        public void Execute()
        {
            ParallelQuery<int> query = ParallelEnumerable.Range(0, _queryResults.Count);
            query = new QueryExecutionOption<int>(QueryOperator<int>.AsQueryOperator(query), _settings);
            query.ForAll(ToArrayElement);
        }

        /// <summary>
        /// Gets the enumerator over the results.
        ///
        /// We never expect this method to be called. ArrayMergeHelper is intended to be used when we want
        /// to consume the results using GetResultsAsArray().
        /// </summary>
        public IEnumerator<TInputOutput> GetEnumerator()
        {
            Debug.Fail("ArrayMergeHelper<>.GetEnumerator() is not intended to be used. Call GetResultsAsArray() instead.");
            return ((IEnumerable<TInputOutput>)GetResultsAsArray()).GetEnumerator();
        }

        /// <summary>
        /// Returns the merged results as an array.
        /// </summary>
        /// <returns></returns>
        public TInputOutput[] GetResultsAsArray()
        {
            Debug.Assert(_outputArray != null);
            return _outputArray;
        }
    }
}


text:
import os

# Function to rename multiple files
def main():
    def organizeLetters():
        ##Change path to the folder containing the final projects
        for filename in os.listdir("C:/Users/Tim/Desktop/Workspace/uwcl.preview/education/G370/2019FA/PDF"):
            i=1
            #Can change name to 8: if year is attached like 2010Fall
            name = filename[0:]
            last = name[0]
            #Skip First letter since name will have uppercase
            for letter in name[1:]:
                if letter.isupper() == False:
                    last += letter
                    i += 1
                    continue
                elif letter.isupper() == True:
                    break
            first = name[i]
            for letter in name[i+1:]:
                if letter != '.':
                    first += letter
                    continue
                elif letter == '.':
                    break
            #print(last + first)
            ##Use the os.rename if you still need to add the year/semester to the project names
            #os.rename('2019FA/PDF/' + filename, '2019FA/PDF/' + 'Fall2019' + last + first +'.PDF')

            #Change the relative path to the respective course time (If spring 2020: e.g. 2020SP)
            print("")
            print("
")
            #Change path to be the same as two lines above
            print("")
            print("

")
            print("
" + first + " " + last +"
")
            print("
")
            print

    organizeLetters()

# Driver Code
if __name__ == '__main__':

    # Calling main() function
    main()


text:
set -eo pipefail
# Display commands being run.
set -x

CLIENT_LIBRARY=$1

# Example JOB_TYPE: "test" or "graalvm"
export JOB_TYPE=$2
## Get the directory of the build script
scriptDir="$(realpath "$(dirname "${BASH_SOURCE[0]}")")"
## cd to the parent directory, i.e. the root of the git repo
cd "${scriptDir}"/..

# Round 1
# Publish gax to local maven to make it available for downstream libraries
./gradlew publishToMavenLocal

# Read current gax version
GAX_VERSION=$( ./gradlew -q :gax:properties | grep '^version: ' | cut -d' ' -f2 )

# Round 2
# Run this gax-java against HEAD of java-shared dependencies

git clone "https://github.com/googleapis/java-shared-dependencies.git" --depth=1
pushd java-shared-dependencies/first-party-dependencies

# replace version
xmllint --shell pom.xml << EOF
setns x=http://maven.apache.org/POM/4.0.0
cd .//x:artifactId[text()="gax-bom"]
cd ../x:version
set ${GAX_VERSION}
cd ../..
cd .//x:artifactId[text()="gax-grpc"]
cd ../x:version
set ${GAX_VERSION}
save pom.xml
EOF

cd ..
mvn verify install -B -V -ntp -fae \
-DskipTests=true \
-Dmaven.javadoc.skip=true \
-Dgcloud.download.skip=true \
-Denforcer.skip=true

# Namespace (xmlns) prevents xmllint from specifying tag names in XPath
SHARED_DEPS_VERSION=$( sed -e 's/xmlns=".*"//' pom.xml | xmllint --xpath '/project/version/text()' - )

if [ -z "${SHARED_DEPS_VERSION}" ]; then
  echo "Version is not found in pom.xml"
  exit 1
fi

# Round 3
# Run this shared-dependencies BOM against java client libraries
git clone "https://github.com/googleapis/java-${CLIENT_LIBRARY}.git" --depth=1
pushd java-"${CLIENT_LIBRARY}"

if [[ $CLIENT_LIBRARY == "bigtable" ]]; then
  pushd google-cloud-bigtable-deps-bom
fi

# replace version
xmllint --shell pom.xml << EOF
setns x=http://maven.apache.org/POM/4.0.0
cd .//x:artifactId[text()="google-cloud-shared-dependencies"]
cd ../x:version
set ${SHARED_DEPS_VERSION}
save pom.xml
EOF

if [[ $CLIENT_LIBRARY == "bigtable" ]]; then
  popd
fi

echo "Modification on the shared dependencies BOM:"
git diff
echo

export INTEGRATION_TEST_ARGS="-Denforcer.skip=true"

# This reads the JOB_TYPE environmental variable ("test" or "graalvm")
.kokoro/build.sh


text:
Input::Input(){
	for(int i = 0; i < 256; i++){
		keys[i] = KeyState::OFF;
	}
}

void Input::PushKey(unsigned char key){
	keys[key] = KeyState::PRESS;
}

void Input::ReleaseKey(unsigned char key){
	keys[key] = KeyState::RELEASE;
}

void Input::PushMouse(int button){
	if(button == GLUT_LEFT_BUTTON)  { mouseLeft   = KeyState::PRESS;}
	if(button == GLUT_RIGHT_BUTTON) { mouseRight  = KeyState::PRESS;}
	if(button == GLUT_MIDDLE_BUTTON){ mouseMiddle = KeyState::PRESS;}
}

void Input::ReleaseMouse(int button){
	if(button == GLUT_LEFT_BUTTON)  { mouseLeft   = KeyState::RELEASE;}
	if(button == GLUT_RIGHT_BUTTON) { mouseRight  = KeyState::RELEASE;}
	if(button == GLUT_MIDDLE_BUTTON){ mouseMiddle = KeyState::RELEASE;}
}

bool Input::GetKey(unsigned char key) const{
	return keys[key] == KeyState::PRESS || keys[key] == KeyState::HOLD;
}

bool Input::GetKeyUp(unsigned char key) const{
	return keys[key] == KeyState::RELEASE;
}

bool Input::GetKeyDown(unsigned char key) const{
	return keys[key] == KeyState::PRESS;
}

bool Input::GetMouse(int button) const{
	if(button == GLUT_LEFT_BUTTON)  { return mouseLeft   == KeyState::PRESS || mouseLeft   == KeyState::HOLD;}
	if(button == GLUT_RIGHT_BUTTON) { return mouseRight  == KeyState::PRESS || mouseRight  == KeyState::HOLD;}
	if(button == GLUT_MIDDLE_BUTTON){ return mouseMiddle == KeyState::PRESS || mouseMiddle == KeyState::HOLD;}
	return false;
}

bool Input::GetMouseUp(int button) const{
	if(button == GLUT_LEFT_BUTTON)  { return mouseLeft   == KeyState::RELEASE;}
	if(button == GLUT_RIGHT_BUTTON) { return mouseRight  == KeyState::RELEASE;}
	if(button == GLUT_MIDDLE_BUTTON){ return mouseMiddle == KeyState::RELEASE;}
	return false;
}

bool Input::GetMouseDown(int button) const{
	if(button == GLUT_LEFT_BUTTON)  { return mouseLeft   == KeyState::PRESS;}
	if(button == GLUT_RIGHT_BUTTON) { return mouseRight  == KeyState::PRESS;}
	if(button == GLUT_MIDDLE_BUTTON){ return mouseMiddle == KeyState::PRESS;}
	return false;
}

void Input::EndFrame(){
	for(int i = 0; i < 256; i++){
		if(keys[i] == KeyState::PRESS){
			keys[i] = KeyState::HOLD;
		}
		if(keys[i] == KeyState::RELEASE){
			keys[i] = KeyState::OFF;
		}
	}

	if(mouseLeft == KeyState::PRESS)  { mouseLeft = KeyState::HOLD;}
	if(mouseLeft == KeyState::RELEASE){ mouseLeft = KeyState::OFF; }

	if(mouseRight == KeyState::PRESS)  { mouseRight = KeyState::HOLD;}
	if(mouseRight == KeyState::RELEASE){ mouseRight = KeyState::OFF; }

	if(mouseMiddle == KeyState::PRESS)  { mouseMiddle = KeyState::HOLD;}
	if(mouseMiddle == KeyState::RELEASE){ mouseMiddle = KeyState::OFF; }
}


text:
<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "tour".
 *
 * @property integer $id
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $status
 * @property string $name
 * @property string $slug
 * @property string $note
 */

class Tour extends \yii\db\ActiveRecord
{

    const STATUS_NO_SCENES     = 1;
    const STATUS_SCENES_LOADED = 2;
    const STATUS_CONGIG_READY  = 3;

    public static function getStatuses()
    {
        return [
            self::STATUS_NO_SCENES     => 'нет панорам',
            self::STATUS_SCENES_LOADED => 'панорамы загружены',
            self::STATUS_CONGIG_READY  => 'готов',
        ];
    }

    public static function tableName()
    {
        return 'tour';
    }

    public function behaviors()
    {
         return [
            'timestampBehavior' => [
                'class' => TimestampBehavior::className(),
            ],
        ];
    }

    public function rules()
    {
        return [
            [['created_at', 'updated_at', 'status'], 'integer'],
            ['status', 'default', 'value' => self::STATUS_NO_SCENES],
            [['name', 'slug'], 'string', 'max' => 120],
            [['note'], 'string', 'max' => 500],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
            'status' => 'Статус',
            'name' => 'Название',
            'slug' => 'Алиас',
            'note' => 'Заметки',
        ];
    }

    public function getCompany()
    {
        return $this->hasOne(Company::className(), ['tour_id' => 'id']);
    }

    public function getScenes()
    {
        return $this->hasMany(Scene::className(), ['tour_id' => 'id']);
    }

    public function getPlugins()
    {
        return $this->hasMany(Plugin::className(), ['id' => 'plugin_id'])
            ->viaTable(TourPlugin::tableName(), ['tour_id' => 'id']);
    }

    // public static function checkAndMakeDirectory($directory, $user_name = 'www-data')
    // {
    //     if (! is_dir($directory)) {
    //         mkdir($directory);
    //         chown($directory, $user_name);
    //     }
    // }

    // public function rebuildKrpanoConfig()
    // {
    //     if ($fileConfig = fopen($this->config, "r+")) {

    //         $pluginSections = '';
    //         $content = file_get_contents($this->config);

    //         $content = preg_replace("/<plugin[^>]+>/i", "", $content);

    //         foreach ($this->plugins as $plugin) {
    //             $pluginSections .= "        " . $plugin->src . "\n";
    //         }

    //         if (strlen($pluginSections) > 0) {
    //             $pluginSections .= ' </krpano>';
    //             $content = str_replace('</krpano>', $pluginSections, $content);
    //         }
    //         fwrite($fileConfig, $content);
    //         fclose($fileConfig);
    //     }
    // }

}


text:
<?xml version="1.0"?>
<!--
  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.
-->

<project name="depend" basedir="." default="help">
  <property name="src1.dir" value="src1"/>
  <property name="src2.dir" value="src2"/>
  <property name="src3.dir" value="src3"/>
  <property name="src4.dir" value="src4"/>
  <property name="src5.dir" value="src5"/>

  <property name="tempsrc.dir" value="working"/>
  <property name="cache.dir" value="working"/>
  <property name="classes.dir" value="classes"/>
  <target name="help">
    <echo>This buildfile is used as part of Ant's test suite.</echo>
  </target>

  <target name="basesetup" depends="clean">
    <mkdir dir="${tempsrc.dir}"/>
  </target>

  <target name="src1setup" depends="basesetup">
    <copy todir="${tempsrc.dir}">
      <fileset dir="${src1.dir}"/>
    </copy>
  </target>

  <target name="src2setup" depends="basesetup">
    <copy todir="${tempsrc.dir}">
      <fileset dir="${src2.dir}"/>
    </copy>
  </target>

  <target name="src3setup" depends="basesetup">
    <copy todir="${tempsrc.dir}">
      <fileset dir="${src3.dir}"/>
    </copy>
  </target>

  <target name="src4setup" depends="basesetup">
    <copy todir="${tempsrc.dir}">
      <fileset dir="${src4.dir}"/>
    </copy>
  </target>

  <target name="src5setup" depends="basesetup">
    <copy todir="${tempsrc.dir}">
      <fileset dir="${src5.dir}"/>
    </copy>
  </target>

  <target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${tempsrc.dir}" destdir="${classes.dir}"/>
  </target>

  <target name="clean">
    <delete dir="${classes.dir}"/>
    <delete dir="${tempsrc.dir}"/>
  </target>

  <target name="testdirect" depends="src1setup, compile">
    <sleep seconds="3"/>
    <delete file="${tempsrc.dir}/C.java"/>
    <copy file="${src1.dir}/C.java" tofile="${tempsrc.dir}/C.java"/>
    <depend srcdir="${tempsrc.dir}" destdir="${classes.dir}"/>
    <fileset id="result" dir="${classes.dir}"/>
  </target>

  <target name="testclosure" depends="src1setup, compile">
    <sleep seconds="3"/>
    <delete file="${tempsrc.dir}/C.java"/>
    <copy file="${src1.dir}/C.java" tofile="${tempsrc.dir}/C.java"/>
    <depend srcdir="${tempsrc.dir}" destdir="${classes.dir}" closure="yes"/>
    <fileset id="result" dir="${classes.dir}"/>
  </target>

  <target name="testbasicset" depends="src1setup, compile">
    <classfileset id="result" dir="${classes.dir}" rootclass="A"/>
  </target>

  <target name="testsmallset" depends="src1setup, compile">
    <classfileset id="result" dir="${classes.dir}" rootclass="B"/>
  </target>

  <target name="testresourcecollection" depends="testsmallset">
    <fail>
      <condition>
        <not>
          <and>
            <resourcecount count="2" refid="result" />
            <resourcecount count="1">
              <intersect>
                <resources refid="result" />
                <file file="${classes.dir}/B.class" />
              </intersect>
            </resourcecount>
            <resourcecount count="1">
              <intersect>
                <resources refid="result" />
                <file file="${classes.dir}/C.class" />
              </intersect>
            </resourcecount>
          </and>
        </not>
      </condition>
    </fail>
  </target>

  <target name="testcomboset" depends="src1setup, compile">
    <classfileset id="result" dir="${classes.dir}" rootclass="B">
      <include name="**/C.class"/>
    </classfileset>
  </target>

  <target name="testbyreference" depends="src1setup, compile">
    <classfileset id="classSet" dir="${classes.dir}" rootclass="A">
      <include name="**/C.class"/>
    </classfileset>
    <jar destfile="${tempsrc.dir}/test.jar">
      <fileset refid="classSet"/>
    </jar>
  </target>

  <target name="testmethodparam" depends="src1setup, compile">
    <classfileset id="result" dir="${classes.dir}" rootclass="E"/>
  </target>

  <target name="testinner" depends="src2setup, compile">
    <sleep seconds="3"/>
    <delete file="${tempsrc.dir}/B.java"/>
    <copy file="${src2.dir}/B.java" tofile="${tempsrc.dir}/B.java"/>
    <depend srcdir="${tempsrc.dir}" destdir="${classes.dir}" closure="yes"/>
    <fileset id="result" dir="${classes.dir}"/>
  </target>

  <target name="testinnerinner" depends="src3setup, compile">
    <sleep seconds="3"/>
    <delete file="${tempsrc.dir}/B.java"/>
    <copy file="${src3.dir}/B.java" tofile="${tempsrc.dir}/B.java"/>
    <depend srcdir="${tempsrc.dir}" destdir="${classes.dir}" closure="yes"/>
    <fileset id="result" dir="${classes.dir}"/>
  </target>

  <target name="testmethodparaminner" depends="src4setup, compile">
    <classfileset id="result" dir="${classes.dir}" rootclass="test.MethodParam"/>
  </target>

  <target name="testnosource" depends="src1setup, compile">
    <depend destdir="${classes.dir}" closure="yes"/>
  </target>

  <target name="testemptysource" depends="src1setup, compile">
    <depend srcdir="" destdir="${classes.dir}" closure="yes"/>
  </target>

  <target name="testinnerclosure" depends="src4setup">
    <mkdir dir="${classes.dir}"/>
    <path id="path.compile">
        <pathelement location="${classes.dir}"/>
    </path>

    <javac srcdir="${tempsrc.dir}" destdir="${classes.dir}"
           classpathref="path.compile"/>

    <sleep seconds="3"/>
    <depend srcdir="${tempsrc.dir}" destdir="${classes.dir}"
            closure="yes" dump="yes"
            classpathref="path.compile"/>

    <fileset id="result" dir="${classes.dir}"/>
  </target>

  <target name="testcache" depends="src1setup, compile">
    <depend cache="${cache.dir}" srcdir="${tempsrc.dir}"
            destdir="${classes.dir}" closure="yes"/>
    <depend cache="${cache.dir}" srcdir="${tempsrc.dir}"
            destdir="${classes.dir}" closure="yes"/>
  </target>

  <target name="testnonpublic" depends="src5setup, compile">
    <sleep seconds="3"/>
    <delete file="${tempsrc.dir}/B.java"/>
    <copy file="${src2.dir}/B.java" tofile="${tempsrc.dir}/B.java"/>
    <depend srcdir="${tempsrc.dir}" destdir="${classes.dir}" closure="yes"/>
    <fileset id="result" dir="${classes.dir}"/>
  </target>
</project>


text:
#ifndef HEADER_CURL_TOOL_DOSWIN_H
#define HEADER_CURL_TOOL_DOSWIN_H

#include "tool_setup.h"

#if defined(MSDOS) || defined(WIN32)

char *sanitize_dos_name(char *file_name);

#if defined(MSDOS) && (defined(__DJGPP__) || defined(__GO32__))

char **__crt0_glob_function(char *arg);

#endif /* MSDOS && (__DJGPP__ || __GO32__) */

#ifdef WIN32

CURLcode FindWin32CACert(struct Configurable *config, const char *bundle_file);

#endif /* WIN32 */

#endif /* MSDOS || WIN32 */

#endif /* HEADER_CURL_TOOL_DOSWIN_H */


text:
package org.apache.isis.core.metamodel.facets.value;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import org.jmock.Expectations;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import org.apache.isis.applib.adapters.EncodingException;
import org.apache.isis.applib.value.Time;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facetapi.FacetHolderImpl;
import org.apache.isis.core.metamodel.facets.value.time.TimeValueSemanticsProvider;

public class TimeValueSemanticsProviderTest extends ValueSemanticsProviderAbstractTestCase {

    private TimeValueSemanticsProvider adapter;
    private Time time;
    private FacetHolder holder;

    @Before
    public void setUpObjects() throws Exception {
        context.checking(new Expectations() {
            {
                allowing(mockConfiguration).getString("isis.value.format.time");
                will(returnValue(null));
            }
        });

        TestClock.initialize();
        time = new Time(8, 13);
        holder = new FacetHolderImpl();
        setValue(adapter = new TimeValueSemanticsProvider(holder, mockServicesInjector));
    }

    @Test
    public void testTimeAsEncodedString() throws Exception {
        assertEquals("081300000", adapter.toEncodedString(time));
    }

    @Test
    public void testParseEntryOfHoursMinutesText() throws Exception {
        final Object parsed = adapter.parseTextEntry(null, "8:30");
        assertEquals(new Time(8, 30), parsed);
    }

    @Test
    @Ignore
    public void testParseEntryOfHoursMinutesSecondsText() throws Exception {
        final Object parsed = adapter.parseTextEntry(null, "8:30:45");
        // I can't get the text parser to parse HH:mm:ss before HH:mm!!
        final Time expected = new Time(8, 30, 45);
        assertEquals(expected, parsed);
    }

    @Test
    public void testParseEntryOfHoursAfterTime() throws Exception {
        final Object parsed = adapter.parseTextEntry(time, "+5H");
        assertEquals(new Time(13, 13), parsed);
    }

    @Test
    public void testParseEntryOfHoursAfterNow() throws Exception {
        final Object parsed = adapter.parseTextEntry(null, "+5H");
        assertEquals(new Time(2, 30, 25), parsed);
    }

    @Test
    public void testParseEntryOfHoursBeforeTime() throws Exception {
        final Object parsed = adapter.parseTextEntry(time, "-7H");
        assertEquals(new Time(1, 13), parsed);
    }

    @Test
    public void testParseEntryOfHoursBeforeToNow() throws Exception {
        final Object parsed = adapter.parseTextEntry(null, "-5H");
        assertEquals(new Time(16, 30, 25), parsed);
    }

    @Test
    public void testParseEntryOfKeywordNow() throws Exception {
        final Object parsed = adapter.parseTextEntry(time, "now");
        assertEquals(new Time(), parsed);
    }

    @Test
    public void testRestoreTime() throws Exception {
        final Time expected = new Time(21, 30);
        final Object parsed = adapter.fromEncodedString("213000000");
        assertEquals(expected, parsed);
    }

    @Test
    public void testRestoreOfInvalidDatal() throws Exception {
        try {
            adapter.fromEncodedString("two ten");
            fail();
        } catch (final EncodingException expected) {
        }
    }

}


text:
int main(int argc, char **argv) {
  morphie::AST ast = morphie::ast::value::MakeBool(false);
  std::string err;
  std::cout << ast.DebugString();
  if (morphie::ast::value::IsValue(ast, &err)) {
    std::cout << " is a value." << std::endl;
  } else {
    std::cout << " is not a value." << std::endl;
  }
}


text:
module HotDrinks
  class Drink < ActiveRecord::Base
    belongs_to :machine
    has_one :drink_type, through: :machine

    def name
      drink_type.name
    end
  end
end


text:
package org.apache.solr.search.function.distance;

import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.distance.GeodesicSphereDistCalc;
import com.spatial4j.core.io.GeohashUtils;
import com.spatial4j.core.shape.Point;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.apache.lucene.search.IndexSearcher;

import java.io.IOException;
import java.util.Map;

/**
 *  Calculate the Haversine distance between two geo hash codes.
 *
 *

 * Ex: ghhsin(ValueSource, ValueSource, radius)
 *

 *
 * @see org.apache.solr.search.function.distance.HaversineFunction for more details on the implementation
 *
 **/
public class GeohashHaversineFunction extends ValueSource {

  private final ValueSource geoHash1, geoHash2;
  private final SpatialContext ctx;
  private final double degreesToDist;

  public GeohashHaversineFunction(ValueSource geoHash1, ValueSource geoHash2, double radius) {
    this.geoHash1 = geoHash1;
    this.geoHash2 = geoHash2;
    this.degreesToDist = DistanceUtils.degrees2Dist(1, radius);
    this.ctx = SpatialContext.GEO;
    assert this.ctx.getDistCalc() instanceof GeodesicSphereDistCalc.Haversine;
  }

  protected String name() {
    return "ghhsin";
  }

  @Override
  public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException {
    final FunctionValues gh1DV = geoHash1.getValues(context, readerContext);
    final FunctionValues gh2DV = geoHash2.getValues(context, readerContext);

    return new DoubleDocValues(this) {
      @Override
      public double doubleVal(int doc) {
        return distance(doc, gh1DV, gh2DV);
      }
      @Override
      public String toString(int doc) {
        StringBuilder sb = new StringBuilder();
        sb.append(name()).append('(');
        sb.append(gh1DV.toString(doc)).append(',').append(gh2DV.toString(doc));
        sb.append(')');
        return sb.toString();
      }
    };
  }

  protected double distance(int doc, FunctionValues gh1DV, FunctionValues gh2DV) {
    double result = 0;
    String h1 = gh1DV.strVal(doc);
    String h2 = gh2DV.strVal(doc);
    if (h1 != null && h2 != null && h1.equals(h2) == false){
      //TODO: If one of the hashes is a literal value source, seems like we could cache it
      //and avoid decoding every time
      Point p1 = GeohashUtils.decode(h1,ctx);
      Point p2 = GeohashUtils.decode(h2,ctx);
      result = ctx.getDistCalc().distance(p1, p2) * degreesToDist;
    } else if (h1 == null || h2 == null){
      result = Double.MAX_VALUE;
    }
    return result;
  }

  @Override
  public void createWeight(Map context, IndexSearcher searcher) throws IOException {
    geoHash1.createWeight(context, searcher);
    geoHash2.createWeight(context, searcher);
  }

  @Override
  public boolean equals(Object o) {
    if (this.getClass() != o.getClass()) return false;
    GeohashHaversineFunction other = (GeohashHaversineFunction) o;
    return this.name().equals(other.name())
            && geoHash1.equals(other.geoHash1) &&
            geoHash2.equals(other.geoHash2) &&
            degreesToDist == other.degreesToDist;
  }

  @Override
  public int hashCode() {
    int result;
    result = geoHash1.hashCode();
    result = 31 * result + geoHash2.hashCode();
    result = 31 * result + name().hashCode();
    long temp =Double.doubleToRawLongBits(degreesToDist);
    result = 31 * result + (int) (temp ^ (temp >>> 32));
    return result;
  }

  @Override
  public String description() {
    StringBuilder sb = new StringBuilder();
    sb.append(name()).append('(');
    sb.append(geoHash1).append(',').append(geoHash2);
    sb.append(')');
    return sb.toString();
  }
}


text:
from loguru import logger

from flexget import options, plugin
from flexget.event import event
from flexget.terminal import console

try:
    from guppy import hpy
except ImportError:
    # this will leave the plugin unloaded
    raise plugin.DependencyError(issued_by='memusage', missing='ext lib `guppy`', silent=True)

logger = logger.bind(name='mem_usage')

"""
http://blog.mfabrik.com/2008/03/07/debugging-django-memory-leak-with-trackrefs-and-guppy/

# Print memory statistics
def update():
    print heapy.heap()

# Print relative memory consumption since last sycle
def update():
    print heapy.heap()
    heapy.setref()

# Print relative memory consumption w/heap traversing
def update()
    print heapy.heap().get_rp(40)
    heapy.setref()
"""

heapy = None

@event('manager.startup')
def on_manager_startup(manager):
    if not manager.options.mem_usage:
        return
    global heapy
    heapy = hpy()

@event('manager.shutdown')
def on_manager_shutdown(manager):
    if not manager.options.mem_usage:
        return

    import resource

    console(
        'Resource Module memory usage: %s (kb)'
        % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    )
    global heapy
    console('Heapy module calculating memory usage:')
    console(heapy.heap())
    console('-' * 79)
    console('Heapy module calculating report (this may take a while):')
    console(heapy.heap().get_rp(40))
    heapy = None

@event('options.register')
def register_parser_arguments():
    options.get_parser().add_argument(
        '--mem-usage',
        action='store_true',
        dest='mem_usage',
        default=False,
        help='display memory usage debug information',
    )


text:
This project allows you to create beautiful high quality images featuring a nice pattern created from Delaunay triangulation and applying a flat surface shader. These images could be used for:

- Wallpapers
- Blog post headers
- Magazines
- Posters
- And more

The tool provides export to PNG and SVG formats. With SVG format you could create an image of virtually any size, even as big as a billboard. Go crazy with it!

## Show me some results!

Here are a few of most obvious uses for the tool:

![three devices](https://raw.github.com/msurguy/triangles/master/examples/three-devices.png)
![two devices](https://raw.github.com/msurguy/triangles/master/examples/two-devices.png)
![billboard](https://raw.github.com/msurguy/triangles/master/examples/billboard.png)

And I made a video on Youtube of the tool in action, creating 11 wallpapers in under 7 minutes:
[![Video demo of the tool](http://img.youtube.com/vi/JbD-HsmBt_0/0.jpg)](http://www.youtube.com/watch?v=JbD-HsmBt_0)

You can also see some examples of the patterns made with this tool in this repository in the examples folder (the first one had text overlay added in Photoshop):

![0](https://raw.github.com/msurguy/triangles/master/examples/0.jpg)
![1](https://raw.github.com/msurguy/triangles/master/examples/1.jpg)
![2](https://raw.github.com/msurguy/triangles/master/examples/2.jpg)
![3](https://raw.github.com/msurguy/triangles/master/examples/3.jpg)
![4](https://raw.github.com/msurguy/triangles/master/examples/4.jpg)
![5](https://raw.github.com/msurguy/triangles/master/examples/5.jpg)
![6](https://raw.github.com/msurguy/triangles/master/examples/6.jpg)
![7](https://raw.github.com/msurguy/triangles/master/examples/7.jpg)

## Using

- To add a new light press Enter key on your keyboard or increase count manually via the slider.
- To "drop" or "pick up" the currently selected light, press Space bar.
- To change colors of the lights, change the ambient and diffuse color controls.
- To export as SVG select SVG in the "renderer" panel and then export the image via "Export big" button. Then navigate to "File -> Save as" in the browser's menu to save the resulting image to your computer.

## Running

Download this repository and run index.html in your browser or open [this link](http://msurguy.github.com/triangles/).

## Building

Install Dependencies:

    npm install uglify-js@2.2.5

Build (cd into 'build' folder first):

    node build.js

## Inspiration

The iOS game called "[Monument Valley][monument]" by [ustwo][ustwo] served as an inspiration for this project. Specifically the simulation of the ocean in the game.

## Acknowledgments

The shader work was done by Matthew Wagerfield on his MIT-licensed [repository][repository].

## Author

Maksim Surguy [@msurguy][msurguy]

## TODO

There are a few things that can be improved to make this tool even better.

- ~~Add varying depth of the vertices of the triangles~~ (Done as of 4/15/2014)
- ~~Add more color variation and presets~~ (Done as of 4/25/2014 with the randomizer functionality)
- Add text overlay and customizer for text

If you can do any of these things - feel free to make a pull request!

## License

Licensed under [MIT][mit]. Enjoy.

[repository]: https://github.com/wagerfield/flat-surface-shader
[msurguy]: http://twitter.com/msurguy
[mit]: http://www.opensource.org/licenses/mit-license.php
[monument]: http://www.monumentvalleygame.com/
[ustwo]: http://ustwo.com/


text:
package com.intellij.util.xml;

import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.PomRenameableTarget;
import com.intellij.pom.PsiDeclaredTarget;
import com.intellij.psi.DelegatePsiTarget;
import com.intellij.psi.PsiElement;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlTagValue;
import com.intellij.xml.util.XmlTagUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author peter
 */
public class DomTarget extends DelegatePsiTarget implements PsiDeclaredTarget, PomRenameableTarget {
  private final DomElement myDomElement;
  private final TextRange myRange;
  private GenericDomValue myNameDomElement;

  private DomTarget(DomElement domElement, PsiElement navigationElement, TextRange range, final GenericDomValue nameElement) {
    super(navigationElement);
    myDomElement = domElement;
    myRange = range;
    myNameDomElement = nameElement;
  }

  @Nullable
  public static DomTarget getTarget(@NotNull DomElement element) {
    final GenericDomValue nameElement = element.getGenericInfo().getNameDomElement(element);
    if (nameElement == null) {
      return null;
    }

    return getTarget(element, nameElement);
  }

  @Nullable
  public static DomTarget getTarget(DomElement element, GenericDomValue nameElement) {
    if (nameElement instanceof GenericAttributeValue) {
      final GenericAttributeValue genericAttributeValue = (GenericAttributeValue)nameElement;
      final XmlAttributeValue attributeValue = genericAttributeValue.getXmlAttributeValue();
      if (attributeValue == null) {
        return null;
      }

      final int length = attributeValue.getTextLength();
      if (length >= 2) {
        return new DomTarget(element, attributeValue, new TextRange(1, length - 1), nameElement);
      }
    }

    final XmlTag tag = nameElement.getXmlTag();
    if (tag == null) {
      return null;
    }

    XmlTagValue tagValue = tag.getValue();
    if (StringUtil.isEmpty(tagValue.getTrimmedText())) {
      return null;
    }

    return new DomTarget(element, tag, XmlTagUtil.getTrimmedValueRange(tag), nameElement);
  }

  public TextRange getNameIdentifierRange() {
    return myRange;
  }

  public boolean isWritable() {
    return getNavigationElement().isWritable();
  }

  public Object setName(@NotNull String newName) {
    myNameDomElement.setStringValue(newName);
    return myDomElement;
  }

  @Nullable
  public String getName() {
    return myNameDomElement.getStringValue();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    if (!super.equals(o)) return false;

    DomTarget domTarget = (DomTarget)o;

    if (myDomElement != null ? !myDomElement.equals(domTarget.myDomElement) : domTarget.myDomElement != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = super.hashCode();
    result = 31 * result + (myDomElement != null ? myDomElement.hashCode() : 0);
    result = 31 * result + (myRange != null ? myRange.hashCode() : 0);
    return result;
  }

  public DomElement getDomElement() {
    return myDomElement;
  }
}


text:
Namespace Commands

	'''
	''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
	''' <generator-date>10/02/2014 15:42:44</generator-date>
	''' <generator-functions>1</generator-functions>
	''' <generator-source>Leviathan\_Commands\Commands\Generated\FilesCommands.tt</generator-source>
	''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template>
	''' <generator-version>1</generator-version>
	<System.CodeDom.Compiler.GeneratedCode("Leviathan\_Commands\Commands\Generated\FilesCommands.tt", "1")> _
	<Leviathan.Commands.Command(ResourceContainingType:=GetType(FilesCommands), ResourceName:="CommandDetails", Name:="files", Description:="@commandFilesDescription@", Hidden:=False)> _
	Partial Public Class FilesCommands
		Inherits System.Object

		#Region " Public Constructors "

			''' Parametered Constructor (1 Parameters)
			Public Sub New( _
				ByVal _Host As Leviathan.Commands.ICommandsExecution _
			)

				MyBase.New()

				Host = _Host

			End Sub

		#End Region

		#Region " Public Constants "

			''' Public Shared Reference to the Name of the Property: Host
			''' <remarks></remarks>
			Public Const PROPERTY_HOST As String = "Host"

		#End Region

		#Region " Private Variables "

			''' Private Data Storage Variable for Property: Host
			''' <remarks></remarks>
			Private m_Host As Leviathan.Commands.ICommandsExecution

		#End Region

		#Region " Public Properties "

			''' Provides Access to the Property: Host
			''' <remarks></remarks>
			Public Property Host() As Leviathan.Commands.ICommandsExecution
				Get
					Return m_Host
				End Get
				Set(value As Leviathan.Commands.ICommandsExecution)
					m_Host = value
				End Set
			End Property

		#End Region

	End Class

End Namespace


text:
package examples.jodatime;

import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.Tag;

/**
 * It works only when JodaTime is not a JavaBean property
 */
public class JodaTimeImplicitContructor extends Constructor {
    public JodaTimeImplicitContructor() {
        this.yamlConstructors.put(Tag.TIMESTAMP, new ConstructJodaTimestamp());
    }

    private class ConstructJodaTimestamp extends ConstructYamlTimestamp {
        public Object construct(Node node) {
            Date date = (Date) super.construct(node);
            return new DateTime(date, DateTimeZone.UTC);
        }
    }
}


text:
#ifndef __WG_DRAW_HEADER_H__
#define __WG_DRAW_HEADER_H__

#define WG_SCREEN_WIDTH         (640)
#define WG_SCREEN_HEIGHT        (480)
#define WG_SCREEN_BPP           (8)     /**!< bits per pixel */
#define WG_MAX_COLORS           (256)   /**!< maximum colors */

#define WG_KEYDOWN(vk_code)     ((GetAsyncKeyState((vk_code)) & 0x8000) ? 1 : 0)
#define WG_KEYUP(vk_code)       ((GetAsyncKeyState((vk_code)) & 0x8000) ? 0 : 1)

/**! initializes a direct draw struct object */
#define WG_DDRAWSTRUCT_INIT(s)  { memset(&(s), 0, sizeof(s)); (s).dwSize = sizeof(s); }

/**! direct draw functions */
extern void* wgDrawCreate(HWND main_hwnd, HINSTANCE main_instance);
extern void wgDrawRelease(void** object);

extern int wgDrawInit(void* object, int width, int height, int bpp);
extern void wgDrawUninit(void* object);
extern LPDIRECTDRAWCLIPPER wgDrawAttachClipper(void* object, LPDIRECTDRAWSURFACE7 lpdds, int numRects, LPRECT clipList);
extern int wgDrawFlip(void* object);
extern int wgDrawFillSurface(void* object, LPDIRECTDRAWSURFACE7 lpdds, int color);
extern int wgDrawRectangle(void* object, int left, int top, int right, int bottom, int color);
extern int wgDrawTextGdi(void* object, int x, int y, LPCTSTR text, int color);

extern void* wgClockCreate(void);
extern void wgClockRelease(void** object);
extern DWORD wgClockStart(void* object);
extern DWORD wgClockGet(void* object);
extern DWORD wgClockWait(void* object, DWORD count);

#endif  /* __WG_DRAW_HEADER_H__ */


text:
using Microsoft.Xna.Framework;
using StardewValley;
using SObject = StardewValley.Object;

namespace Pathoschild.Stardew.Automate.Framework.Machines.Objects
{
    /// A geode crusher that accepts input and provides output.
    /// <remarks>Derived from <see cref="SObject.performObjectDropInAction"/> (search for 'Geode Crusher').</remarks>
    internal class GeodeCrusherMachine : GenericObjectMachine<SObject>
    {
        /*********
        ** Fields
        *********/
        /// The recipes to process.
        private readonly IRecipe[] Recipes =
        {
            new Recipe(
                input: item => Utility.IsGeode(item, disallow_special_geodes: true),
                inputCount: 1,
                output: Utility.getTreasureFromGeode,
                minutes: _ => 60
            )
        };

        /*********
        ** Public methods
        *********/
        /// Construct an instance.
        /// <param name="machine">The underlying machine.</param>
        /// <param name="location">The location containing the machine.</param>
        /// <param name="tile">The tile covered by the machine.</param>
        public GeodeCrusherMachine(SObject machine, GameLocation location, Vector2 tile)
            : base(machine, location, tile) { }

        /// Provide input to the machine.
        /// <param name="input">The available items.</param>
        /// <returns>Returns whether the machine started processing an item.</returns>
        public override bool SetInput(IStorage input)
        {
            if (input.TryGetIngredient(SObject.coal, 1, out IConsumable? coal) && this.GenericPullRecipe(input, this.Recipes))
            {
                coal.Reduce();
                this.Machine.showNextIndex.Value = true;
                Game1.stats.GeodesCracked++;
                return true;
            }
            return false;
        }
    }
}


text:
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / @brief initialize a new database
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2014 ArangoDB GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// /     http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is ArangoDB GmbH, Cologne, Germany
// /
// / @author Dr. Frank Celler
// / @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

// //////////////////////////////////////////////////////////////////////////////
// / @brief initialize a new database
// //////////////////////////////////////////////////////////////////////////////

(function () {
  var internal = require('internal');

  // do not overwrite arguments set from the calling C++ code
  if (!global.UPGRADE_ARGS) {
    global.UPGRADE_ARGS = {};
  }

  // merge in our arguments
  global.UPGRADE_ARGS.isCluster = true;
  global.UPGRADE_ARGS.isCoordinator = true;
  global.UPGRADE_ARGS.isRelaunch = false;

  // run the local upgrade-database script
  var res = internal.loadStartup('server/bootstrap/local-database.js');

  // Wait for synchronous replication to settle:
  // We do not do this for performance reasons and because it should not
  // be necessary. We leave the code here in case we need it again.
  //var db = require('internal').db;
  //var dbName = db._name();
  //if (dbName !== '_system') {
  //  // for _system we run this already at bootstrap
  //  var colls = db._collections();
  //  colls = colls.filter(c => c.name()[0] === '_');
  //  require('@arangodb/cluster').waitForSyncRepl(dbName, colls);
  //}

  return res;
}());


text:
package algorithm.leet_121_135;

import java.util.*;

/**
 * Created by songheng on 10/13/16.
 */
public class WordLadderII_126_3 {
    public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) {
        HashMap<String, List<String>> paths = new HashMap<>();
        Set<String> set1 = new HashSet<>();
        Set<String> set2 = new HashSet<>();
        set1.add(beginWord);
        set2.add(endWord);
        return null;
    }

    private void bfs(Set<String> set1, Set<String> set2, Set<String> wordList, Map<String, List<String>> paths, boolean front) {
        if (set1.size() > set1.size()) {
            bfs(set2, set1, wordList, paths, !front);
            return;
        }
        wordList.removeAll(set1);
        wordList.removeAll(set2);
        boolean connected = false;
        Set<String> set3 = new HashSet<>();
        for (String s : set1) {
            char[] chs = s.toCharArray();
            for (int i = 0; i < chs.length; i++) {
                char ch = chs[i];
                for (char x = 'a'; x <= 'z'; x++) {
                    if (x != ch) {
                        chs[i] = x;
                        String cand = new String(chs);
                        if (set2.contains(cand) || wordList.contains(cand)) {
                            if (set2.contains(cand)) {
                                connected = true;
                            }
                        }
                    }
                }
            }
        }
    }
}


text:
Date and Datetime Formatting
============================

Table of Contents
-----------------
  - [PHP DateTime Formatter](#php-datetime-formatter)
    - [format](#format)
    - [formatDate](#formatdate)
    - [formatTime](#formattime)
    - [getPattern](#getpattern)
  - [PHP DateTime Format Converters](#php-datetime-format-converters)
    - [getDateFormat](#getdateformat)
    - [getTimeFormat](#gettimeformat)
    - [getDateTimeFormat](#getdatetimeformat)
  - [Twig Extensions](#twig-extensions)
    - [Formatter filters](#formatter-filters)
    - [Format Converter functions](#format-converter-functions)
  - [JS DateTime Formatter](#js-datetime-formatter)

PHP DateTime Formatter
----------------------

DateTime formatter provides methods that allow formatting of entered data.
Formatter uses standard Intl library format types to render values:

* \IntlDateFormatter::NONE;
* \IntlDateFormatter::SHORT;
* \IntlDateFormatter::MEDIUM;
* \IntlDateFormatter::LONG;
* \IntlDateFormatter::FULL.

Each format uses it's own localized format for date, time and datetime.
Default date format is \IntlDateFormatter::MEDIUM, default time format is \IntlDateFormatter::SHORT.

### format

**Signature:** format(\DateTime|string|int date, dateType = null, timeType = null, locale = null, timeZone = null, pattern = null)

This functions provides most basic functionality to format date and time values.
It allows setting of date and time format types from Intl library, current locale as a string,
current timezone as a string and custom format pattern (in this case date and time format types will not be used).

```php
echo $formatter->format(new \DateTime('2012-12-12 23:23:23'));
// Dec 13, 2012 12:23 AM

echo $formatter->format(new \DateTime('2012-12-12 23:23:23'), \IntlDateFormatter::FULL, \IntlDateFormatter::MEDIUM);
// Thursday, December 13, 2012 12:23:23 AM

echo $formatter->format(new \DateTime('2012-12-12 23:23:23'), null, null, 'ru');
// 13.12.2012 0:23

echo $formatter->format(new \DateTime('2012-12-12 23:23:23'), null, null, null, 'America/Los_Angeles');
// Dec 12, 2012 1:23 PM

echo $formatter->format(new \DateTime('2012-12-12 23:23:23'), null, null, null, null, 'yyyy-MM-dd|HH:mm:ss');
// 2012-12-13|00:23:23
```

### formatDate

**Signature:** formatDate(\DateTime|string|int date, dateType = null, locale = null, timeZone = null)

This function formats date value using _format_ function described above.
Receives date value, date format type from Intl library, current locale and current timezone.

```php
echo $formatter->formatDate(new \DateTime('2012-12-12 23:23:23'));
// Dec 13, 2012

echo $formatter->formatDate(new \DateTime('2012-12-12 23:23:23'), \IntlDateFormatter::FULL);
// Thursday, December 13, 2012

echo $formatter->formatDate(new \DateTime('2012-12-12 23:23:23'), null, 'ru');
// 13.12.2012

echo $formatter->formatDate(new \DateTime('2012-12-12 23:23:23'), null, null, 'America/Toronto');
// Dec 12, 2012
```

### formatTime

**Signature:** formatTime(\DateTime|string|int date, dateType = null, locale = null, timeZone = null)

This function formats time value using _format_ function described above.
Receives time value, time format type from Intl library, current locale and current timezone.

```php
echo $formatter->formatTime(new \DateTime('2012-12-12 23:23:23'));
// 12:23 AM

echo $formatter->formatTime(new \DateTime('2012-12-12 23:23:23'), \IntlDateFormatter::FULL);
// 12:23:23 AM GMT+02:00

echo $formatter->formatTime(new \DateTime('2012-12-12 23:23:23'), null, 'ru');
// 0:23

echo $formatter->formatTime(new \DateTime('2012-12-12 23:23:23'), null, null, 'America/Toronto');
// 4:23 PM
```

### getPattern

**Signature:** getPattern($dateType, $timeType, $locale = null)

Returns Intl library pattern for specified date and time format types and locale.

```php
echo $formatter->getPattern(\IntlDateFormatter::FULL, \IntlDateFormatter::FULL);
// EEEE, MMMM d, y h:mm:ss a zzzz

echo $formatter->getPattern(\IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'ru');
// EEEE, d MMMM y 'г'. H:mm:ss zzzz
```

PHP DateTime Format Converters
------------------------------

OroPlatform application contains several libraries that works with datetime values.
Each library has its own datetime format placeholders, so, to unify approach to generate localized format strings
for all libraries LocaleBundle provides format converters.

For each used library there must be a format converter that contains rules of converting
of standard internal format to specific library format. Intl library format is used
for internal format representation. Each format converter has as alias specified as an alias in service configuration
and used to extract it from registry.

Main entry point for developer is a converter registry (DateTimeFormatConverterRegistry) -
it simply collects and stores existing format converters and allows to receive appropriate converter by it's alias.

LocaleBundle contains following format converters:
 - intl (IntlDateTimeFormatConverter) - default format converter that simply returns Intl formats;
 - moment (MomentDateTimeFormatConverter) - format converter for moment.js library.

Also bundle contains interface DateTimeFormatConverterInterface that must be implemented by all format converters.
Here is list of interface functions.

### getDateFormat

**Signature:** getDateFormat(dateFormat = null, locale = null)

Returns localized date format for specific library. Optionally receives date format type form Intl library
and custom locale.

```php
echo $converterRegistry->getFormatConverter('intl')->getDateFormat();
echo $converterRegistry->getFormatConverter('moment')->getDateFormat();
// MMM d, y
// MMM D, YYYY

echo $converterRegistry->getFormatConverter('intl')->getDateFormat(\IntlDateFormatter::FULL, 'ru');
echo $converterRegistry->getFormatConverter('moment')->getDateFormat(\IntlDateFormatter::FULL, 'ru');
// EEEE, d MMMM y 'г'.
// dddd, D MMMM YYYY [г].
```

### getTimeFormat

**Signature:** getTimeFormat(timeFormat = null, locale = null)

Returns localized time format for specific library. Optionally receives time format type form Intl library
and custom locale.

```php
echo $converterRegistry->getFormatConverter('intl')->getTimeFormat();
echo $converterRegistry->getFormatConverter('moment')->getTimeFormat();
// h:mm a
// h:mm A

echo $converterRegistry->getFormatConverter('intl')->getTimeFormat(\IntlDateFormatter::MEDIUM, 'ru');
echo $converterRegistry->getFormatConverter('moment')->getTimeFormat(\IntlDateFormatter::MEDIUM, 'ru');
// H:mm:ss
// H:mm:ss
```

### getDateTimeFormat

**Signature:** getDateTimeFormat(dateFormat = null, timeFormat = null, locale = null)

Returns localized datetime format for specific library. Optionally receives date and time format types
form Intl library and custom locale.

```php
echo $converterRegistry->getFormatConverter('intl')->getDateTimeFormat();
echo $converterRegistry->getFormatConverter('moment')->getDateTimeFormat();
// MMM d, y h:mm a
// MMM D, YYYY h:mm A

echo $converterRegistry->getFormatConverter('intl')->getDateTimeFormat(
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::MEDIUM,
    'ru'
);
echo $converterRegistry->getFormatConverter('moment')->getDateTimeFormat(
    \IntlDateFormatter::FULL,
    \IntlDateFormatter::MEDIUM,
    'ru'
);
// EEEE, d MMMM y 'г'. H:mm:ss
// dddd, D MMMM YYYY [г]. H:mm:ss
```

Twig Extensions
---------------

LocaleBundle has two twig extensions that provides formatter filters and format converter functions.

### Formatter filters

Twig extension DateTimeExtension has following functions.

#### oro_format_date

Proxy for [formatDate](#formatdate) function of DateTimeFormatter, receives date value as a first argument
and array of options as a second argument. Allowed options:
  * dateType,
  * locale,
  * timezone.

```
{{ entity.lastLogin|oro_format_date }}
{# Nov 6, 2013 #}

{{ entity.lastLogin|oro_format_date({'locale': 'ru'}) }}
{# 06.11.2013 #}
```

#### oro_format_time

Proxy for [formatTime](#formattime) function of DateTimeFormatter, receives time value as a first argument
and array of options as a second argument. Allowed options:
  * timeType,
  * locale,
  * timezone.

```
{{ entity.lastLogin|oro_format_time }}
{# 7:44 PM #}

{{ entity.lastLogin|oro_format_time({'locale': 'ru'}) }}
{# 19:44 #}
```

#### oro_format_datetime

Proxy for [format](#format) function of DateTimeFormatter, receives datetime value as a first argument
and array of options as a second argument. Allowed options:
  * dateType,
  * timeType,
  * locale,
  * timezone.

```
{{ entity.lastLogin|oro_format_datetime }}
{# Nov 6, 2013 7:44 PM #}

{{ entity.lastLogin|oro_format_datetime({'locale': 'ru'}) }}
{# 06.11.2013 19:44 #}
```

### Format Converter functions

Twig extension DateFormatExtension has following functions.

#### oro_date_format

Receives format converter alias, date format type and custom locale, returns date format from appropriate
format converter.

```
{{ oro_date_format('moment') }}
{# MMM D, YYYY #}

{{ oro_date_format('moment', null, 'ru') }}
{# DD.MM.YYYY #}
```

#### oro_time_format

Receives format converter alias, time format type and custom locale, returns time format from appropriate
format converter.

```
{{ oro_time_format('moment') }}
{# h:mm A #}

{{ oro_time_format('moment', null, 'ru') }}
{# H:mm #}
```

#### oro_datetime_format

Receives format converter alias, date and time format types and custom locale, returns time format from appropriate
format converter.

```
{{ oro_datetime_format('moment') }}
{# MMM D, YYYY h:mm A #}

{{ oro_datetime_format('moment', null, null, 'ru') }}
{# DD.MM.YYYY H:mm #}
```

#### oro_datetime_formatter_list

Returns array of all registered format converter aliases.

```
{{ oro_datetime_formatter_list()|join(', ') }}
{# intl, moment, jquery_ui, fullcalendar #}
```

JS DateTime Formatter
---------------------

From the frontend side there is JavaScript datetime converter that provides functions to format datetime values.
Formatter uses library moment.js to work with datetime values and localized formats injected from locale settings
configuration.

Formatter work with two string representations of datetime values: frontend - it's localized format
in current timezone, and backend - ISO format data in UTC (for date) or with direct timezone specification
(for datetime).

Formatter provides following functions.

### getDateFormat(), getTimeFormat(), getDateTimeFormat()

Returns appropriate localized frontend format for moment.js library received from locale settings configuration.

```js
console.log(datetimeFormatter.getDateTimeFormat());
// MMM D, YYYY h:mm A
```

### isDateValid(value), isTimeValid(value), isDateTimeValid(value)

Check whether input value has valid format and can be parsed to internal date representation.

```js
console.log(datetimeFormatter.isDateValid('qwerty'));
// false

console.log(datetimeFormatter.isDateTimeValid('oct 12 2013 12:12 pm'));
// true
```

### formatDate(value), formatTime(value), formatDateTime(value)

Receives either Date object or valid ISO string and returns value string in localized format.
Throws an exception in case of not valid string.

```js
console.log(datetimeFormatter.formatDate('2013-12-12'));
// Dec 12, 2013

console.log(datetimeFormatter.formatDateTime(new Date()));
// Nov 6, 2013 7:32 PM
```

### convertDateToBackendFormat(value), convertTimeToBackendFormat(value), convertDateTimeToBackendFormat(value, timezoneOffset)

Receives localized string data and convert in to ISO format string, *convertDateTimeToBackendFormat* optionally can receive
timezone offset - if no offset is set default offset will be used.
Throws an exception in case of not valid string.

```js
console.log(datetimeFormatter.convertDateToBackendFormat('Dec 12, 2013'));
// 2013-12-12

console.log(datetimeFormatter.convertDateTimeToBackendFormat('Nov 6, 2013 7:32 PM'));
// 2013-11-06T19:32:00+0200
```

### getMomentForBackendDate(value), getMomentForBackendTime(value), getMomentForBackendDateTime(value)

Receives either Date object or valid ISO string and returns moment object instance.
Throws an exception in case of not valid string.

### getMomentForFrontendDate(value), getMomentForFrontendTime(value), getMomentForFrontendDateTime(value[, timezoneOffset])

Receives valid formatted string and returns moment object instance.
Throws an exception in case of not valid string.

### unformatDate(value), unformatTime(value), unformatDateTime(value[, timezoneOffset])

Receives valid formatted string and returns Date object instance.
Throws an exception in case of not valid string.

### unformatBackendDate(value), unformatBackendTime(value), unformatBackendDateTime(value)

Receives either Date object or valid ISO string and returns Date object instance.
Throws an exception in case of not valid string.


text:
@interface DPWoDeShangHuController : UIViewController <
	UITableViewDataSource,
	UITableViewDelegate
>

@property (strong, nonatomic) NSMutableArray *myShangHus;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

- (IBAction)refreshMyShangHu:(id)sender;

@end


text:
using Faker.Tests.Common;
using NUnit.Framework;

namespace Faker.Tests.en_US
{
	[SetUICulture("en-US")]
	[SetCulture("en-US")]
	[Category("Culture 'en_US'")]
	public class InternetAmericanTests
	{
		[Test]
		[Repeat(1000)]
		public void Should_Create_Free_Email()
		{
			string freeEmailsFormat = Resources.Internet.FreeMail.ToFormat();

			string email = Internet.FreeEmail();

			Assert.That(email, Does.Match(string.Format("@({0})$", freeEmailsFormat))
								 .And.Match(InternetTests.EMAIL_REGEX)
								 .And.Not.Contains("www"));
		}
	}
}


text:
namespace MusicMinkAppLayer.Enums
{
    public enum SongOriginSource
    {
        Unknown = 0,
        Device = 1,
        OneDrive = 2,
    }

    public enum MixType
    {
        None = 0x0000,

        TYPE_MASK = 0xF000,
        SUBTYPE_MASK = 0xFFF0,
        VARIANT_MASK = 0xF00F,

        NUMBER_TYPE = 0x1000,
        STRING_TYPE = 0x2000,
        NESTED_TYPE = 0x3000,
        RANGE_TYPE = 0x4000,
        MEMBER_TYPE = 0x5000,

        BASIC_SUBTYPE = NESTED_TYPE | 0x000,

        And = BASIC_SUBTYPE | 0x1,
        Or = BASIC_SUBTYPE | 0x2,
        Not = BASIC_SUBTYPE | 0x3,

        NUMERIC_LESS_VARIANT = NUMBER_TYPE | 0x1,
        NUMERIC_MORE_VARIANT = NUMBER_TYPE | 0x2,
        NUMERIC_STRICTLYLESS_VARIANT = NUMBER_TYPE | 0x3,
        NUMERIC_STRICTLYMORE_VARIANT = NUMBER_TYPE | 0x4,
        NUMERIC_EQUAL_VARIANT = NUMBER_TYPE | 0x5,

        STRING_EQUAL_VARIANT = STRING_TYPE | 0x1,
        STRING_CONTAINS_VARIANT = STRING_TYPE | 0x2,
        STRING_STARTSWITH_VARIANT = STRING_TYPE | 0x3,
        STRING_ENDSWITH_VARIANT = STRING_TYPE | 0x4,

        RANGE_DAYS_VARIANT = RANGE_TYPE | 0x1,

        MEMBER_CONTAINS_VARIANT = MEMBER_TYPE | 0x1,

        RATING_SUBTYPE = NUMBER_TYPE | 0x010,
        RatingLess = RATING_SUBTYPE | NUMERIC_LESS_VARIANT,
        RatingMore = RATING_SUBTYPE | NUMERIC_MORE_VARIANT,
        RatingStrictlyLess = RATING_SUBTYPE | NUMERIC_STRICTLYLESS_VARIANT,
        RatingStrictlyMore = RATING_SUBTYPE | NUMERIC_STRICTLYMORE_VARIANT,
        RatingEqual = RATING_SUBTYPE | NUMERIC_EQUAL_VARIANT,

        PLAYCOUNT_SUBTYPE = NUMBER_TYPE | 0x020,
        PlayCountLess = PLAYCOUNT_SUBTYPE | NUMERIC_LESS_VARIANT,
        PlayCountMore = PLAYCOUNT_SUBTYPE | NUMERIC_MORE_VARIANT,
        PlayCountStrictlyLess = PLAYCOUNT_SUBTYPE | NUMERIC_STRICTLYLESS_VARIANT,
        PlayCountStrictlyMore = PLAYCOUNT_SUBTYPE | NUMERIC_STRICTLYMORE_VARIANT,
        PlayCountEqual = PLAYCOUNT_SUBTYPE | NUMERIC_EQUAL_VARIANT,

        TRACK_SUBTYPE = STRING_TYPE | 0x030,
        TrackEqual = TRACK_SUBTYPE | STRING_EQUAL_VARIANT,
        TrackContains = TRACK_SUBTYPE | STRING_CONTAINS_VARIANT,
        TrackStartsWith = TRACK_SUBTYPE | STRING_STARTSWITH_VARIANT,
        TrackEndsWith = TRACK_SUBTYPE | STRING_ENDSWITH_VARIANT,

        ALBUM_SUBTYPE = STRING_TYPE | 0x050,
        AlbumEqual = ALBUM_SUBTYPE | STRING_EQUAL_VARIANT,
        AlbumContains = ALBUM_SUBTYPE | STRING_CONTAINS_VARIANT,
        AlbumStartsWith = ALBUM_SUBTYPE | STRING_STARTSWITH_VARIANT,
        AlbumEndsWith = ALBUM_SUBTYPE | STRING_ENDSWITH_VARIANT,

        ARTIST_SUBTYPE = STRING_TYPE | 0x060,
        ArtistEqual = ARTIST_SUBTYPE | STRING_EQUAL_VARIANT,
        ArtistContains = ARTIST_SUBTYPE | STRING_CONTAINS_VARIANT,
        ArtistStartsWith = ARTIST_SUBTYPE | STRING_STARTSWITH_VARIANT,
        ArtistEndsWith = ARTIST_SUBTYPE | STRING_ENDSWITH_VARIANT,

        LENGTH_SUBTYPE = NUMBER_TYPE | 0x70,
        LengthCountLess = LENGTH_SUBTYPE | NUMERIC_LESS_VARIANT,
        LengthCountMore = LENGTH_SUBTYPE | NUMERIC_MORE_VARIANT,
        LengthCountStrictlyLess = LENGTH_SUBTYPE | NUMERIC_STRICTLYLESS_VARIANT,
        LengthCountStrictlyMore = LENGTH_SUBTYPE | NUMERIC_STRICTLYMORE_VARIANT,
        LengthCountEqual = LENGTH_SUBTYPE | NUMERIC_EQUAL_VARIANT,

        ALBUMARTIST_SUBTYPE = STRING_TYPE | 0x80,
        AlbumArtistEqual = ALBUMARTIST_SUBTYPE | STRING_EQUAL_VARIANT,
        AlbumArtistContains = ALBUMARTIST_SUBTYPE | STRING_CONTAINS_VARIANT,
        AlbumArtistStartsWith = ALBUMARTIST_SUBTYPE | STRING_STARTSWITH_VARIANT,
        AlbumArtistEndsWith = ALBUMARTIST_SUBTYPE | STRING_ENDSWITH_VARIANT,

        LASTPLAYED_SUBTYPE = RANGE_TYPE | 0x10,
        LastPlayedDays = LASTPLAYED_SUBTYPE | RANGE_DAYS_VARIANT,

        PLAYLISTMEMBER_SUBTYPE = MEMBER_TYPE | 0x10,
        PlaylistMemberContains = PLAYLISTMEMBER_SUBTYPE | MEMBER_CONTAINS_VARIANT,

        MIXMEMBER_SUBTYPE = MEMBER_TYPE | 0x20,
        MixMemberContains = MIXMEMBER_SUBTYPE | MEMBER_CONTAINS_VARIANT,
    }

    public enum MixSortOrder
    {
        None = 0x00,

        ORDER_MASK = 0x00F,
        PROPERTY_MASK = 0xFF0,

        SORTORDER_ASC = 0x00,
        SORTORDER_DESC = 0x01,

        ARTISTNAMESORT = 0x10,
        ArtistNameAsc = ARTISTNAMESORT | SORTORDER_ASC,
        ArtistNameDesc = ARTISTNAMESORT | SORTORDER_DESC,

        ALBUMNAMESORT = 0x20,
        AlbumNameAsc = ALBUMNAMESORT | SORTORDER_ASC,
        AlbumNameDesc = ALBUMNAMESORT | SORTORDER_DESC,

        ALBUMARTISTNAMESORT = 0x30,
        AlbumArtistNameAsc = ALBUMARTISTNAMESORT | SORTORDER_ASC,
        AlbumArtistNameDesc = ALBUMARTISTNAMESORT | SORTORDER_DESC,

        TRACKNAMESORT = 0x40,
        TrackNameAsc = TRACKNAMESORT | SORTORDER_ASC,
        TrackNameDesc = TRACKNAMESORT | SORTORDER_DESC,

        DURATIONSORT = 0x50,
        DurationAsc = DURATIONSORT | SORTORDER_ASC,
        DurationDesc = DURATIONSORT | SORTORDER_DESC,

        LASTPLAYEDSORT = 0x60,
        LastPlayedAsc = LASTPLAYEDSORT | SORTORDER_ASC,
        LastPlayedDesc = LASTPLAYEDSORT | SORTORDER_DESC,

        RATINGSORT = 0x70,
        RatingAsc = RATINGSORT | SORTORDER_ASC,
        RatingNameDesc = RATINGSORT | SORTORDER_DESC,

        PLAYCOUNTSORT = 0x80,
        PlayCountAsc = PLAYCOUNTSORT | SORTORDER_ASC,
        PlayCountDesc = PLAYCOUNTSORT | SORTORDER_DESC,
    }
}


text:
.PHONY: docs test

help:
	@echo "  env         create a development environment using virtualenv"
	@echo "  deps        install dependencies using pip"
	@echo "  clean       remove unwanted files like .pyc's"
	@echo "  lint        check style with flake8"
	@echo "  test        run all your tests using py.test"

up: down
	docker-compose up -d --build
	docker-compose logs -f

down:
	docker-compose down


text:
package de.lsoft.partition;

/**
 * Simple Closed-Range-Object with lower and upped endpoints.
 */
public class Range {

    private final int lowerEndpoint;
    private final int upperEndpoint;

    public Range(int lowerEndpoint, int upperEndpoint) {
        if (lowerEndpoint > upperEndpoint) {
            throw new IllegalArgumentException("lower endpoint must be lower than upper endpoint.");
        }

        this.lowerEndpoint = lowerEndpoint;
        this.upperEndpoint = upperEndpoint;
    }

    public int lowerEndpoint() {
        return lowerEndpoint;
    }

    public int upperEndpoint() {
        return upperEndpoint;
    }
}


text:
namespace {
const char kUnknownActionType[] = "unknownType";
}  // namespace

namespace extensions {

namespace keys = declarative_webrequest_constants;

TEST(WebRequestActionTest, CreateAction) {
  std::string error;
  bool bad_message = false;
  scoped_ptr<WebRequestAction> result;

  // Test wrong data type passed.
  error.clear();
  base::ListValue empty_list;
  result = WebRequestAction::Create(empty_list, &error, &bad_message);
  EXPECT_TRUE(bad_message);
  EXPECT_FALSE(result.get());

  // Test missing instanceType element.
  base::DictionaryValue input;
  error.clear();
  result = WebRequestAction::Create(input, &error, &bad_message);
  EXPECT_TRUE(bad_message);
  EXPECT_FALSE(result.get());

  // Test wrong instanceType element.
  input.SetString(keys::kInstanceTypeKey, kUnknownActionType);
  error.clear();
  result = WebRequestAction::Create(input, &error, &bad_message);
  EXPECT_NE("", error);
  EXPECT_FALSE(result.get());

  // Test success
  input.SetString(keys::kInstanceTypeKey, keys::kCancelRequestType);
  error.clear();
  result = WebRequestAction::Create(input, &error, &bad_message);
  EXPECT_EQ("", error);
  EXPECT_FALSE(bad_message);
  ASSERT_TRUE(result.get());
  EXPECT_EQ(WebRequestAction::ACTION_CANCEL_REQUEST, result->GetType());
}

TEST(WebRequestActionTest, CreateActionSet) {
  std::string error;
  bool bad_message = false;
  scoped_ptr<WebRequestActionSet> result;

  WebRequestActionSet::AnyVector input;

  // Test empty input.
  error.clear();
  result = WebRequestActionSet::Create(input, &error, &bad_message);
  EXPECT_TRUE(error.empty()) << error;
  EXPECT_FALSE(bad_message);
  ASSERT_TRUE(result.get());
  EXPECT_TRUE(result->actions().empty());
  EXPECT_EQ(std::numeric_limits<int>::min(), result->GetMinimumPriority());

  DictionaryValue correct_action;
  correct_action.SetString(keys::kInstanceTypeKey, keys::kIgnoreRulesType);
  correct_action.SetInteger(keys::kLowerPriorityThanKey, 10);
  DictionaryValue incorrect_action;
  incorrect_action.SetString(keys::kInstanceTypeKey, kUnknownActionType);

  // Test success.
  linked_ptr<json_schema_compiler::any::Any> action1 = make_linked_ptr(
      new json_schema_compiler::any::Any);
  action1->Init(correct_action);
  input.push_back(action1);
  error.clear();
  result = WebRequestActionSet::Create(input, &error, &bad_message);
  EXPECT_TRUE(error.empty()) << error;
  EXPECT_FALSE(bad_message);
  ASSERT_TRUE(result.get());
  ASSERT_EQ(1u, result->actions().size());
  EXPECT_EQ(WebRequestAction::ACTION_IGNORE_RULES,
            result->actions()[0]->GetType());
  EXPECT_EQ(10, result->GetMinimumPriority());

  // Test failure.
  linked_ptr<json_schema_compiler::any::Any> action2 = make_linked_ptr(
      new json_schema_compiler::any::Any);
  action2->Init(incorrect_action);
  input.push_back(action2);
  error.clear();
  result = WebRequestActionSet::Create(input, &error, &bad_message);
  EXPECT_NE("", error);
  EXPECT_FALSE(result.get());
}

// Test capture group syntax conversions of WebRequestRedirectByRegExAction
TEST(WebRequestActionTest, PerlToRe2Style) {
#define CallPerlToRe2Style WebRequestRedirectByRegExAction::PerlToRe2Style
  // foo$1bar -> foo\1bar
  EXPECT_EQ("foo\\1bar", CallPerlToRe2Style("foo$1bar"));
  // foo\$1bar -> foo$1bar
  EXPECT_EQ("foo$1bar", CallPerlToRe2Style("foo\\$1bar"));
  // foo\\$1bar -> foo\\\1bar
  EXPECT_EQ("foo\\\\\\1bar", CallPerlToRe2Style("foo\\\\$1bar"));
  // foo\bar -> foobar
  EXPECT_EQ("foobar", CallPerlToRe2Style("foo\\bar"));
  // foo$bar -> foo$bar
  EXPECT_EQ("foo$bar", CallPerlToRe2Style("foo$bar"));
#undef CallPerlToRe2Style
}

TEST(WebRequestActionTest, TestPermissions) {
  // Necessary for TestURLRequest.
  MessageLoop message_loop(MessageLoop::TYPE_IO);
  TestURLRequestContext context;

  std::string error;
  bool bad_message = false;
  scoped_ptr<WebRequestActionSet> action_set;

  // Setup redirect to http://www.foobar.com.
  base::DictionaryValue redirect;
  redirect.SetString(keys::kInstanceTypeKey, keys::kRedirectRequestType);
  redirect.SetString(keys::kRedirectUrlKey, "http://www.foobar.com");

  linked_ptr<json_schema_compiler::any::Any> action = make_linked_ptr(
      new json_schema_compiler::any::Any);
  action->Init(redirect);
  WebRequestActionSet::AnyVector actions;
  actions.push_back(action);

  action_set = WebRequestActionSet::Create(actions, &error, &bad_message);
  EXPECT_EQ("", error);
  EXPECT_FALSE(bad_message);
  ASSERT_TRUE(action.get());

  // Check that redirect works on regular URLs but not on protected URLs.
  TestURLRequest regular_request(GURL("http://test.com"), NULL, &context);
  std::list<LinkedPtrEventResponseDelta> deltas =
      action_set->CreateDeltas(
          NULL, "ext1",
          WebRequestRule::RequestData(&regular_request, ON_BEFORE_REQUEST),
          false, base::Time());
  EXPECT_EQ(1u, deltas.size());

  TestURLRequest protected_request(GURL(extension_urls::kGalleryBrowsePrefix),
                                   NULL, &context);
  deltas = action_set->CreateDeltas(
      NULL, "ext1",
      WebRequestRule::RequestData(&protected_request, ON_BEFORE_REQUEST),
      false, base::Time());
  EXPECT_EQ(0u, deltas.size());
}

}  // namespace extensions


text:
using UnityEngine;
using UnityEditor;
using System.IO;

class GvrAssetPostprocessor : AssetPostprocessor {
  void OnPreprocessTexture() {
    // Reconfigure all images in Plugins/iOS as so they don't get compressed,
    // resized, or mipmapped.  Saves a bunch of import time.
    if (assetPath.Contains("Plugins/iOS")) {
      TextureImporter ti = assetImporter as TextureImporter;
      // Don't compress at all.
      ti.textureFormat = TextureImporterFormat.AutomaticTruecolor;
      // Don't rescale at all.
      ti.npotScale = TextureImporterNPOTScale.None;
      // Don't generate mipmaps.
      ti.mipmapEnabled = false;
    }
  }
}


text:
coroutines2
===========

Lightweight coroutines for C++

My second jab at coroutines, after moderately successfull first attempt here: https://github.com/maciekgajewski/coroutines

This time the plan is slightly different: travel light, drop scheduler and channels, focus on flexibility and integration with existing technologies.


text:
<?php

namespace app\controllers;
use Yii;
use app\models\Links;
use rodzadra\geolocation\Geolocation;
use app\components\UserAgent;
use app\components\StatComponent;
use app\components\TtlComponent;

class LinkController extends \yii\web\Controller
{
    public function actionIndex()
    {
        $this->collStat();
        $model = new Links();
        return $this->render('index',['model' => $model,]);
    }

    /**
     * Генерирует короткий url
     *
     * @param string $host
     * @param int $length
     * @return string
     */
    private function generate($host,$length = 7){
        $chars = '1234567890abdefhiknrstyzABDEFGHKNQRSTYZ23456789';
        $numChars = strlen($chars);
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= substr($chars, rand(1, $numChars) - 1, 1);
        }
        $shortUrl = $host[0].'/'.$string;
        return $shortUrl;
    }

    /**
     * Возвращает массив с кусками URL
     *
     * @param $data
     * @return array
     */
    private function getHost($data){
        preg_match('/(https?:\/\/)?([\w\d\.]+)/',$data,$arr);
        if(!empty($arr)){
            return $arr;
        }
    }

    /**
     * Возвращает готовый короткий url
     *
     * @param object $url
     * @return string
     */
    private function getShortUrl($url){
        $arrHost  = $this->getHost($url);
        $shortUrl = $this->generate($arrHost);
        return $shortUrl;
    }

    /**
     * записывает занные в базу
     */
    public function actionSave()
    {   $model = new Links();
        $data  = Yii::$app->request->post();
        $model = $this->setData($model,$data);
        if($model->find()->where(['short_url'=>$data['short_url']])->one() !==null){
            $model->update();
            echo $model->short_url;
        }else {

            if ($model->save()) {
                echo $model->short_url;
            } else {
                echo 'Что-то пошло не так :(';
            }
        }
    }

    /**
     * Заполняет поля модели значениями
     *
     * @param object $model
     * @param array $data
     * @return object
     */
    private function setData($model,$data){
        $model->sourse_url    = $data['sourse_url'];
        if($data['short_url'] !== ''){
            $model->short_url = $data['short_url'];
        }else{
            $model->short_url = $this->getShortUrl($data['sourse_url']);
        }

        if($data['time_of_death'] != ''||$data['ttl_seconds'] != ''){
            $ttl = new TtlComponent();
            $model->time_of_death =  $ttl->setTtl($data);
        }else{
            $model->time_of_death = 0;
        }
        return $model;
    }

    /**
     * Запускает статистику
     */
    private function collStat(){
        $stat = new StatComponent();

        $stat->start(new userAgent(), new  Geolocation());
        $stat->parsData();
        $stat->rewriteStat();
    }
}


text:
class RestClientError(Exception):
    pass

class ServerResponseException(RestClientError):
    """Server response error class for client."""

class InvalidRestMethodException(RestClientError):
    """A valid HTTP method is required to make a request."""

class ConfigMissing(RestClientError):
    pass

class ConfigItemMissing(RestClientError):
    pass

# SALT
class SaltClientError(ServerResponseException):
    pass

class SaltAuthenticationError(SaltClientError):
    """Salt Authentication Error."""

class SaltModuleUnavailableException(SaltClientError):
    """Salt Module Unavailable."""

# SLB
class SLBClientError(ServerResponseException):
    pass

class SLBInternalError(SLBClientError):
    pass

class SLB4SOAServiceNotFound(SLBClientError):
    pass

class RLBClientError(SLBClientError):
    pass

# KAFKA
class KAFKAClientError(ServerResponseException):
    pass

# CMS
class CMSClientError(ServerResponseException):
    pass

# ROLES
class RolesClientError(ServerResponseException):
    pass

# ES
class ESClientError(ServerResponseException):
    pass

# JobAgent
class JobAgentClientError(ServerResponseException):
    pass


text:
package com.eaw1805.www.scenario.remote;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import com.eaw1805.data.dto.common.JumpOffDTO;
import com.eaw1805.data.dto.common.SectorDTO;
import com.eaw1805.data.dto.web.RegionDTO;
import com.eaw1805.data.dto.web.army.*;
import com.eaw1805.data.dto.web.economy.BaggageTrainDTO;
import com.eaw1805.data.dto.web.economy.WarehouseDTO;
import com.eaw1805.data.dto.web.fleet.FleetDTO;
import com.eaw1805.data.dto.web.fleet.ShipDTO;
import com.eaw1805.www.scenario.stores.ArmyData;
import com.eaw1805.www.scenario.stores.StaticEditorData;

import java.util.List;
import java.util.Map;

@RemoteServiceRelativePath("scenario.rpc")
public interface EmpireScenarioRpcService extends RemoteService {
    Map<RegionDTO, List<SectorDTO>> getRegionData(final int gameId);
    StaticEditorData getEditorStaticData();
    Map<Integer, Map<Integer, WarehouseDTO>> getWarehouses(final int gameId);
    ArmyData getArmies(final int gameId);

    Map<Integer, List<String>> getCommanderNamesByNation(final int gameId);
    int saveData(final int gameId, final List<RegionDTO> regions, final Map<Integer, List<SectorDTO>> regionSectors,
                 final Map<Integer, Map<Integer, WarehouseDTO>> regionNationWarehouses,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, BrigadeDTO>>>> brigades,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, CorpDTO>>>> corps,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, ArmyDTO>>>> armies,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, CommanderDTO>>>> commanders,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, SpyDTO>>>> spies,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, BaggageTrainDTO>>>> bTrains,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, ShipDTO>>>> ships,
                 final Map<Integer, Map<Integer, Map<Integer, Map<Integer, FleetDTO>>>> fleets,
                 final List<JumpOffDTO> jumpOffs);
}