text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('website', '0059_auto_20190815_1643'),
    ]

    operations = [
        migrations.RenameField(
            model_name='scheduledayone',
            old_name='lecture',
            new_name='lecture_hall_1',
        ),
        migrations.RenameField(
            model_name='scheduledaytwo',
            old_name='lecture',
            new_name='lecture_hall_1',
        ),
        migrations.AddField(
            model_name='scheduledayone',
            name='lecture_hall_2',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='website.Lecture'),
        ),
        migrations.AddField(
            model_name='scheduledaytwo',
            name='lecture_hall_2',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='website.Lecture'),
        ),
    ]


text:
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶2.5.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class LowercaseKeywordsFixer extends AbstractFixer
{
    private static $excludedTokens = array(T_HALT_COMPILER);

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isAnyTokenKindsFound(Token::getKeywords());
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $token) {
            if ($token->isKeyword() && !$token->isGivenKind(self::$excludedTokens)) {
                $token->setContent(strtolower($token->getContent()));
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHP keywords MUST be in lower case.';
    }
}

redpajama_set_name: RedPajamaGithub


text:
.. . Kicking page rebuild 2014-10-30 17:00:08
.. include:: defs.hrst

.. index:: Organization, Company

.. _Organization:

Organization
============

Schema
------

:name:
    string, multilingual

    |ocdsDescription|
    The common name of the organization.

:identifier:
    :ref:`Identifier`

    |ocdsDescription|
    The primary identifier for this organization.

:additionalIdentifiers:
    List of :ref:`identifier` objects
:address:
    :ref:`Address`, required
:contactPoint:
    :ref:`ContactPoint`, required

.. index:: Company, id

.. _Identifier:

Identifier
==========

Schema
------

:scheme:
   string

   |ocdsDescription|
   Organization identifiers be drawn from an existing identification scheme.
   This field is used to indicate the scheme or codelist in which the
   identifier will be found.  This value should be drawn from the
   Organization Identifier Scheme.

:id:
   string, required

   |ocdsDescription| The identifier of the organization in the selected
   scheme.

   The allowed codes are the ones found in `"Organisation Registration Agency"
   codelist of IATI
   Standard <http://iatistandard.org/codelists/OrganisationRegistrationAgency/>`_
   with addition of `UA-EDR` code for organizations registered in Ukraine
   (EDRPOU and IPN).

:legalName:
   string, multilingual

   |ocdsDescription|
   The legally registered name of the organization.

:uri:
   uri

   |ocdsDescription|
   A URI to identify the organization, such as those provided by Open
   Corporates or some other relevant URI provider.  This is not for listing
   the website of the organization: that can be done through the url field
   of the Organization contact point.

.. index:: Address, City, Street, Country

.. _Address:

Address
=======

Schema
------

:streetAddress:
    string

    |ocdsDescription|
    The street address. For example, 1600 Amphitheatre Pkwy.

:locality:
    string

    |ocdsDescription|
    The locality. For example, Mountain View.

:region:
    string

    |ocdsDescription|
    The region. For example, CA.

:postalCode:
    string

    |ocdsDescription|
    The postal code. For example, 94043.

:countryName:
    string, required

    |ocdsDescription|
    The country name. For example, United States.

.. index:: Person, Phone, Email, Website, ContactPoint

.. _ContactPoint:

ContactPoint
============

Schema
------

:name:
    string, multilingual, required

    |ocdsDescription|
    The name of the contact person, department, or contact point, for correspondence relating to this contracting process.

:email:
    email

    |ocdsDescription|
    The e-mail address of the contact point/person.

:telephone:
    string

    |ocdsDescription|
    The telephone number of the contact point/person. This should include the international dialling code.

:faxNumber:
    string

    |ocdsDescription|
    The fax number of the contact point/person. This should include the international dialling code.

:url:
    url

    |ocdsDescription|
    A web address for the contact point/person.

Either `email` or `telephone` field has to be provided.


text:
package com.asakusafw.lang.compiler.model.testing;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.text.MessageFormat;

import com.asakusafw.lang.compiler.model.description.AnnotationDescription;
import com.asakusafw.lang.compiler.model.description.ClassDescription;
import com.asakusafw.lang.compiler.model.description.MethodDescription;
import com.asakusafw.lang.compiler.model.graph.UserOperator;

/**
 * Extracts operator from declaring operator methods.
 */
public final class OperatorExtractor {

    private OperatorExtractor() {
        return;
    }

    /**
     * Returns user operator builder for the specified method.
     * @param annotationType the annotation type
     * @param operatorClass the operator class
     * @param methodName the target method name
     * @return the user operator builder
     */
    public static UserOperator.Builder extract(
            Class<? extends Annotation> annotationType,
            Class<?> operatorClass,
            String methodName) {
        Method method = findMethod(annotationType, operatorClass, methodName);
        Annotation annotation = method.getAnnotation(annotationType);
        assert annotation != null;
        return UserOperator.builder(
                AnnotationDescription.of(annotation),
                MethodDescription.of(method),
                ClassDescription.of(operatorClass));
    }

    private static Method findMethod(
            Class<? extends Annotation> annotationType,
            Class<?> operatorClass,
            String methodName) {
        for (Method method : operatorClass.getMethods()) {
            if (method.getName().equals(methodName) == false) {
                continue;
            }
            if (method.isAnnotationPresent(annotationType) == false) {
                continue;
            }
            return method;
        }
        throw new AssertionError(MessageFormat.format(
                "missing @{0} {1}#{2}()", //$NON-NLS-1$
                annotationType.getSimpleName(),
                operatorClass.getSimpleName(),
                methodName));
    }
}


text:
[:Outline:]

An if-expression is used to choose between two different values based on a predicate.

## Standard If-Then-Else Syntax

The following results in either the value [:e1](e1) or [:e2](e2) depending on whether the predicate [:p](e1 !== null) evaluates to
`true` or `false`.

		[:Success:]
			package io.sarl.docs.reference.gsr
			agent A {
				var [:e1!] : Object
				var [:e2!] : Object
				def example1 : Object {
					[:On]
					if ([:p!])
						[:e1!]
					else
						[:e2!]
					[:Off]
				}
			}
		[:End:]

## Optional Else Part

The else part is optional, which is a shorthand for an else branch that returns the
default value of the current type.

		[:Success:]
			package io.sarl.docs.reference.gsr
			agent A {
				var [:e1!] : Object
				var [:e2!] : Object
				def example1 : Object {
					[:On]
					if ([:p!]) [:e1!]
					[:Off]
				}
			}
		[:End:]

## Conditional Operator

Sometimes, it is useful to put a if-then-else expression inside another expression.
This syntax is known as the [conditional operator, inline if, or ternary if](https://en.wikipedia.org/wiki/%3F:)
in many programming languages.
In programming languages such as Java or C/C++, this conditional operator has the syntax:

```java
a ? b : c
```

It evaluates to `b` if the value of `a` is true, otherwise to `c`.

In SARL, this specific syntax is not supported. The standard if-then-else expression (explained above) is
an expression. It means that it could be included into another expression like all the other expressions.
Consequently, there is no need of a specific syntax for the conditional operator in SARL.
The following example is the SARL equivelant of the Java conditional operator:

		[:Success:]
			package io.sarl.docs.reference.gsr
			agent A {
				var a : boolean
				var b : Object
				var c : Object
				def example1 : Object {
					[:On]
					if (a) b else c
					[:Off]
				}
			}
		[:End:]

You can use `if` expressions deeply nested within expressions:

		[:Success:]
			package io.sarl.docs.reference.gsr
			agent A {
				var e1 : Object
				var e2 : Object
				def example1 {
					[:On]
					val name = if ([:p!]) [:e1!] + ' ' + [:e2!] else [:e2!]
					[:Off]
				}
			}
		[:End:]

[:Include:](../generalsyntaxref.inc)

[:Include:](../../legal.inc)


text:
package tutorial.table_render_demo;

public class Test {

  final static String tag = Test.class.getPackage().getName();

  public static void main(String[] args) {
    System.out.println(tag);
    TableRenderDemo.main();
  }

}


text:
css

First Div

Second Div

		This is a glowing text


text:
import { connect } from 'react-redux';
import { selectUser } from 'redux/selectors/user';
import RewardsVerifyPage from './view';

const select = state => ({
  user: selectUser(state),
});

export default connect(select, null)(RewardsVerifyPage);


text:
function getDiverseNgramComps(cachedir, phrasenames, numComp)

try

disp(['getDiverseNgramComps(''' cachedir ''')']);

load([cachedir '/edgematrix.mat'], 'edgeval');
numcls = numel(phrasenames);

% update the matrix such that edgeval(i,j) has score at least as much as  edgeval(j,j)
dmat = edgeval;
for j=1:numcls
    inds = dmat(:,j) < dmat(j,j);
    dmat(inds, j) = dmat(j,j);

    inds = dmat(j,:) < dmat(j,j);
    dmat(j, inds) = dmat(j,j);
end

% for each node, pick all other nodes that it 'likes'
% i.e., gives high AP/low rank, and remove those nodes
% now amongst the remaining nodes, repeat the above process

rankThresh = 5;
offsetThresh = rankThresh/2;
remNodes = 1:numcls;
simNodes = cell(numcls, 1);
while ~isempty(remNodes)
    pickNode = remNodes(1);
    fprintf('%d ', pickNode);
    %likeNodes = find(dmat(pickNode, remNodes) < rankThresh);
    likeNodes = find(...
        [dmat(remNodes, pickNode) < max(rankThresh, dmat(pickNode, pickNode) + offsetThresh)] & ...
        [dmat(pickNode, remNodes)' < max(rankThresh, diag(dmat(remNodes, remNodes)) + offsetThresh)]);
    if isempty(find(likeNodes==1, 1))
        if ~isempty(likeNodes), disp('here'); keyboard; end
        likeNodes = [1 likeNodes];
    end
    %likeNodes = remNodes(likeNodes);
    simNodes{pickNode} = remNodes(likeNodes);
    remNodes(likeNodes) = [];
end

disp('here'); keyboard;

catch
    disp(lasterr); keyboard;
end

%{
colsum = sum(dmat, 1);
[~, cind] = sort(colsum, 'ascend');

rowsum = sum(dmat, 2);
[~, rind] = sort(rowsum, 'ascend');

ngids(rind(1:10))

disp('here'); keyboard;
%}


text:
 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InventoryVisualController : MonoBehaviour
{
    /// <summary>
    /// Bool that determines weather e was pressed already
    /// </summary>
    private bool pressed = false;

    /// <summary>
    /// Makes all the grid turn of its image
    /// </summary>
    private void Start()
    {
        for (int i = 0; i < 40; i++)
        {
            this.transform.GetChild(i).GetComponent<Image>().enabled = false;
        }
    }

    /// <summary>
    /// Makes the grid show or hide.
    /// </summary>
    public void Update()
    {
        if (Input.GetAxisRaw("Inventory") == 1 && pressed == false)
        {
            for (int i = 0; i < 40; i++)
            {
                if (this.transform.GetChild(i).GetComponent<Image>().enabled == false) this.transform.GetChild(i).GetComponent<Image>().enabled = true; else this.transform.GetChild(i).GetComponent<Image>().enabled = false;
            }
            pressed = true;
        }
            else if (Input.GetAxisRaw("Inventory") == 0) pressed = false;
    }

    /// <summary>
    /// Makes sure the images show
    /// </summary>
    public void Open()
    {
        for (int i = 0; i < 40; i++)
        {
            this.transform.GetChild(i).GetComponent<Image>().enabled = true;
        }
    }
}


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Instalar
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Instalar))
        Me.Label1 = New System.Windows.Forms.Label()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.Button3 = New System.Windows.Forms.Button()
        Me.FolderMod = New System.Windows.Forms.FolderBrowserDialog()
        Me.FileMod = New System.Windows.Forms.OpenFileDialog()
        Me.SuspendLayout()
        '
        'Label1
        '
        Me.Label1.Dock = System.Windows.Forms.DockStyle.Top
        Me.Label1.Font = New System.Drawing.Font("Segoe UI", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.Location = New System.Drawing.Point(0, 0)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(215, 44)
        Me.Label1.TabIndex = 0
        Me.Label1.Text = "Instalar desde..."
        Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'Button1
        '
        Me.Button1.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Button1.Location = New System.Drawing.Point(13, 48)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(190, 37)
        Me.Button1.TabIndex = 1
        Me.Button1.Text = "Carpeta"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'Button3
        '
        Me.Button3.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Button3.Location = New System.Drawing.Point(13, 91)
        Me.Button3.Name = "Button3"
        Me.Button3.Size = New System.Drawing.Size(190, 37)
        Me.Button3.TabIndex = 3
        Me.Button3.Text = "*.vpk"
        Me.Button3.UseVisualStyleBackColor = True
        '
        'FolderMod
        '
        '
        'Instalar
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 17.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.Color.White
        Me.ClientSize = New System.Drawing.Size(215, 140)
        Me.Controls.Add(Me.Button3)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.Label1)
        Me.Font = New System.Drawing.Font("Segoe UI", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.ForeColor = System.Drawing.Color.FromArgb(CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer))
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.Margin = New System.Windows.Forms.Padding(3, 4, 3, 4)
        Me.MaximizeBox = False
        Me.Name = "Instalar"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Instalar"
        Me.ResumeLayout(False)

    End Sub
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button3 As System.Windows.Forms.Button
    Friend WithEvents FolderMod As System.Windows.Forms.FolderBrowserDialog
    Friend WithEvents FileMod As System.Windows.Forms.OpenFileDialog
End Class


text:
package com.docd.purefm;

import com.docd.purefm.settings.Settings;
import com.docd.purefm.utils.PFMTextUtils;
import com.stericson.RootTools.RootTools;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;

public final class PureFM extends Application implements
        Application.ActivityLifecycleCallbacks {

    public static final int THEME_ID_LIGHT = 1;
    public static final int THEME_ID_DARK = 2;

    private int mActivityStartedCount;

    @Override
    public void onCreate() {
        if (BuildConfig.DEBUG) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                     .detectAll()
                     .penaltyLog()
                     .build());
            StrictMode.setVmPolicy(buildStrictModeVmPolicy().build());
        }
        super.onCreate();
        ActivityMonitor.init(this);
        RootTools.handlerEnabled = false;
        RootTools.debugMode = BuildConfig.DEBUG;
        Environment.init(this);
        PFMTextUtils.init(this);
        ensureNoShellUsedIfNoBusybox();
        registerActivityLifecycleCallbacks(this);
    }

    private void ensureNoShellUsedIfNoBusybox() {
        final Settings settings = Settings.getInstance(this);
        if (settings.useCommandLine()) {
            if (!Environment.hasBusybox()) {
                settings.setUseCommandLine(false, true);
                if (settings.isSuEnabled()) {
                    settings.setSuEnabled(false, true);
                }
            }
        }
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (++mActivityStartedCount == 1) {
            //rescan for environment changes
            ensureNoShellUsedIfNoBusybox();
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        mActivityStartedCount--;
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    private static StrictMode.VmPolicy.Builder buildStrictModeVmPolicy() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return StrictModeVmPolicyBuilder_JB_MR2.build();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return StrictModeVmPolicyBuilder_JB.build();
        }
        return StrictModeVmPolicyBuilder.build();
    }

    private static final class StrictModeVmPolicyBuilder {
        static StrictMode.VmPolicy.Builder build() {
            return new StrictMode.VmPolicy.Builder()
                    .penaltyLog()
                    .detectLeakedClosableObjects()
                    .detectLeakedSqlLiteObjects();
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private static final class StrictModeVmPolicyBuilder_JB {
        static StrictMode.VmPolicy.Builder build() {
            return StrictModeVmPolicyBuilder.build().detectLeakedRegistrationObjects();
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private static final class StrictModeVmPolicyBuilder_JB_MR2 {
        static StrictMode.VmPolicy.Builder build() {
            return StrictModeVmPolicyBuilder_JB.build().detectFileUriExposure();
        }
    }
}


text:
package org.apache.hadoop.yarn.server.nodemanager.containermanager.container;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ResourceSet;

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

public interface Container extends EventHandler<ContainerEvent> {

  ContainerId getContainerId();

  /**
   * The timestamp when the container start request is received.
   */
  long getContainerStartTime();

  /**
   * The timestamp when the container is allowed to be launched.
   */
  long getContainerLaunchTime();

  Resource getResource();

  ContainerTokenIdentifier getContainerTokenIdentifier();

  void setContainerTokenIdentifier(ContainerTokenIdentifier token);

  String getUser();

  ContainerState getContainerState();

  ContainerLaunchContext getLaunchContext();

  Credentials getCredentials();

  Map<Path,List<String>> getLocalizedResources();

  ContainerStatus cloneAndGetContainerStatus();

  NMContainerStatus getNMContainerStatus();

  boolean isRetryContextSet();

  boolean shouldRetry(int errorCode);

  String getWorkDir();

  void setWorkDir(String workDir);

  String getLogDir();

  void setLogDir(String logDir);

  void setIpAndHost(String[] ipAndHost);

  String toString();

  Priority getPriority();

  ResourceSet getResourceSet();

  boolean isRunning();

  void setIsReInitializing(boolean isReInitializing);

  boolean isReInitializing();

  boolean isMarkedForKilling();

  boolean canRollback();

  void commitUpgrade();

  void sendLaunchEvent();

  void sendKillEvent(int exitStatus, String description);

  boolean isRecovering();

  /**
   * Get assigned resource mappings to the container.
   *
   * @return Resource Mappings of the container
   */
  ResourceMappings getResourceMappings();

  void sendPauseEvent(String description);

  /**
   * Verify container is in final states.
   * @return true/false based on container's state
   */
  boolean isContainerInFinalStates();
}


text:
package com.ewolff.microservice.shipping;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@Entity
public class ShipmentLine {

	@Column(name = "F_COUNT")
	private int count;

	@Embedded
	private Item item;

	@Id
	@GeneratedValue
	private long id;

	public void setCount(int count) {
		this.count = count;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	public ShipmentLine() {
	}

	public ShipmentLine(int count, Item item) {
		this.count = count;
		this.item = item;
	}

	public int getCount() {
		return count;
	}

	public Item getItem() {
		return item;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);

	}

	@Override
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj);
	}

}


text:
import json
import logging

import elasticsearch
import six
from nefertari.json_httpexceptions import exception_response

log = logging.getLogger(__name__)

class ESHttpConnection(elasticsearch.Urllib3HttpConnection):
    def _catch_index_error(self, response):
        """ Catch and raise index errors which are not critical and thus
        not raised by elasticsearch-py.
        """
        code, headers, raw_data = response
        if not raw_data:
            return
        data = json.loads(raw_data)
        if not data or not data.get('errors'):
            return
        try:
            error_dict = data['items'][0]['index']
            message = error_dict['error']
        except (KeyError, IndexError):
            return
        raise exception_response(400, detail=message)

    def perform_request(self, *args, **kw):
        try:
            if log.level == logging.DEBUG:
                msg = str(args)
                if len(msg) > 512:
                    msg = msg[:300] + '...TRUNCATED...' + msg[-212:]
                log.debug(msg)
            resp = super(ESHttpConnection, self).perform_request(*args, **kw)
        except Exception as e:
            log.error(e.error)
            status_code = e.status_code
            if status_code == 'N/A':
                status_code = 400
            raise exception_response(
                status_code,
                explanation=six.b(e.error),
                extra=dict(data=e))
        else:
            self._catch_index_error(resp)
            return resp


text:
from .decoder_utilities import varint_parser, varint_parser_with_length, varint_prefixed_string_parser
from .encoder_utilities import varint_encoder, varint_prefixed_string_encoder, varint_prefixed_string_list_encoder, boolean_encoder
from .packet_utilties import make_packet_stream

def salt_password(password, salt):
    from hashlib import sha1

    content = sha1(salt.encode('utf-8')).hexdigest() + sha1(password.encode('utf-8')).hexdigest()
    return sha1(content.encode('utf-8')).hexdigest()


text:
<resources>
    <string name="app_name">Fibbonacci clock detector</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="picture">Picture</string>
    <string name="description_info">Info</string>
    <string name="request_permission">This sample needs camera permission.</string>
    <string name="camera_error">This device doesn\'t support Camera2 API.</string>
    <string name="intro_message">
    <![CDATA[

           This application let you decrypt the fibonnacci clock !!
           Made with the Camera2BasicFragment example from google

        ]]>
    </string>
</resources>


text:
package org.jeasy.batch.extensions.integration.jms;

import org.jeasy.batch.core.record.Batch;
import org.jeasy.batch.jms.JmsRecord;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import javax.jms.Message;
import javax.jms.QueueSender;

import static java.util.Arrays.asList;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class BroadcastJmsQueueRecordWriterTest {

    private BroadcastJmsQueueRecordWriter broadcastJmsQueueRecordWriter;

    @Mock
    private QueueSender queue1, queue2;
    @Mock
    private JmsRecord jmsRecord;
    @Mock
    private Message message;

    @Before
    public void setUp() {
        when(jmsRecord.getPayload()).thenReturn(message);

        broadcastJmsQueueRecordWriter = new BroadcastJmsQueueRecordWriter(asList(queue1, queue2));
    }

    @Test
    public void testBroadcastJmsRecord() throws Exception {
        broadcastJmsQueueRecordWriter.writeRecords(new Batch(jmsRecord));

        verify(queue1).send(message);
        verify(queue2).send(message);
    }

}


text:
suite('rb/reviewRequestPage/models/Entry', function() {
    it('parse', function() {
        const reviewRequestEditor = new RB.ReviewRequestEditor({
            reviewRequest: new RB.ReviewRequest(),
        });

        const entry = new RB.ReviewRequestPage.Entry({
            reviewRequestEditor: reviewRequestEditor,
            ignoredAttr: 'ignored',
        }, {
            parse: true,
        });

        expect(entry.attributes).toEqual({
            reviewRequestEditor: reviewRequestEditor,
        });
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<chapter xmlns="http://docbook.org/ns/docbook"
  xmlns:xi="http://www.w3.org/2001/XInclude"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  version="5.0"
  xml:id="ch_configuring-openstack-networking">
    <title>Networking</title>
    <para>This chapter explains the OpenStack Networking configuration options. For installation
        prerequisites, steps, and use cases, see the <citetitle>OpenStack Installation
            Guide</citetitle> for your distribution (<link xlink:href="http://docs.openstack.org"
            >docs.openstack.org</link>) and <citetitle><link
                xlink:href="http://docs.openstack.org/admin-guide-cloud/">Cloud
                Administrator Guide</link></citetitle>.</para>
    <xi:include href="networking/section_networking-options-reference.xml"/>
    <xi:include href="networking/section_networking-log-files.xml"/>
    <xi:include href="networking/section_networking-sample-configuration-files.xml"/>
    <xi:include href="conf-changes/neutron.xml"/>
</chapter>


text:
package com.jobxhub.server.alarm;
/**
 * @Package com.jobxhub.server.alarm
 * @Title: AbstractSendNotice
 * @author hitechr
 * @date 2018/6/12 9:39
 * @version V1.0
 */

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.jobxhub.common.util.collection.HashMap;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Descriptions:
 */
public abstract class AbstractSendNotice implements SendNotice {

    private boolean httpPostSend(int successCode,String urlPrefix, String content) {
        URL url = null;
        InputStream in = null;
        OutputStreamWriter writer = null;
        HttpURLConnection conn = null;

        try {
            url = new URL(urlPrefix);
            conn = (HttpURLConnection)url.openConnection();

            conn.setConnectTimeout(2000);
            conn.setReadTimeout(3000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("content-type", "application/json;charset=utf-8");
//            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            writer = new OutputStreamWriter(conn.getOutputStream());

            writer.write(content);
            writer.flush();

            in = conn.getInputStream();
            System.out.println(IOUtils.toString(in,"UTF-8"));
            int responseCode = conn.getResponseCode();
            return successCode==responseCode;
//            System.out.println(responseCode);
//
//            StringBuilder sb = new StringBuilder();
//            sb.append(IOUtils.toString(in,"UTF-8"));

        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
            }
        }
        return false;
    }

    private boolean httpGetSend(int successCode,String urlPrefix, String urlPars) {
        URL url = null;
        InputStream in = null;
        HttpURLConnection conn = null;

        try {
            url = new URL(urlPrefix + "?" + urlPars);
            conn = (HttpURLConnection)url.openConnection();

            conn.setConnectTimeout(2000);
            conn.setReadTimeout(3000);
            int responseCode = conn.getResponseCode();
            return successCode==responseCode;

//            in = conn.getInputStream();
//            StringBuilder sb = new StringBuilder();
//            sb.append(IOUtils.toString(in,"UTF-8"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    public boolean httpSend(int successCode, String type, String urlPrefix, String urlPars) {
        if ("get".equalsIgnoreCase(type)) {
            return httpGetSend(successCode, urlPrefix, urlPars);
        } else if ("post".equalsIgnoreCase(type)) {
            return httpPostSend(successCode, urlPrefix, urlPars);
        }
        return false;
    }
    public static void m23ain(String[] args) {
        List<String> list= new ArrayList<>();
        list.add("12121");
        list.add("27323");
        System.out.println(list);
    }

    public static void main(String[] args) {
        ;
        JSONObject jsonObject= new JSONObject();
        jsonObject.put("msgtype","text");
        JSONObject contest= new JSONObject();
        contest.put("content","test");
        jsonObject.put("text",contest.toJSONString());
        JSONObject mobile= new JSONObject();
        List<String> list= new ArrayList<>();
        list.add("1825718XXXX");
        mobile.put("atMobiles",list);
        mobile.put("isAtAll",false);
        jsonObject.put("at",mobile.toJSONString());
        System.out.println(jsonObject.toJSONString());

        Map<String,String> map= new HashMap<>();
        map.put("msgtype","text");

        String msg="{" +
                "     'msgtype': 'test'," +
                "     'text': {" +
                "         'content': '我就是我,  @1825718XXXX 是不一样的烟火'" +
                "     }," +
                "     'at': {" +
                "         'atMobiles': [" +
                "             '1825718XXXX'" +
                "         ], " +
                "         'isAtAll': false" +
                "     }" +
                " }";

//        AbstractSendNotice notice= new AbstractSendNotice();
//        String url="https://oapi.dingtalk.com/robot/send?access_token=cffcc6996a57a834a8bde29b79f4ae77103eb57fa1ce37f2743e1867be03dd87";
//        boolean b = notice.httpPostSend(200, url, jsonObject.toJSONString());
//        System.out.println(b);
    }

    public String getDDMsg(String content,String... mobiles){
        JSONObject jsonObject= new JSONObject();
        jsonObject.put("msgtype","text");
        JSONObject contest= new JSONObject();

        JSONObject mobile= new JSONObject();
        StringBuffer sb= new StringBuffer(content);

        if(mobiles!=null && mobiles.length>0){
            List<String> list= new ArrayList<>();
            for(String m:mobiles){
                list.add(m);
                sb.append("@"+m+";");
            }
            mobile.put("atMobiles",list);
        }else{
            mobile.put("isAtAll",false);
        }

        contest.put("content",sb.toString());

        jsonObject.put("text",contest.toJSONString());
        jsonObject.put("at",mobile.toJSONString());
        return jsonObject.toJSONString();
    }
}


text:
package com.ecorengia.org.cinemaapp.screens.main;

public enum MediaSection {
    UNDEFINED(-1),
    TOP_RATED(0),
    POPULAR(1),
    NOW_PLAYING(2);

    final int value;

    /* package */ MediaSection(final int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static MediaSection valueOf(final int value) {
        switch (value) {
            case 0:
                return TOP_RATED;
            case 1:
                return POPULAR;
            case 2:
                return NOW_PLAYING;
            default:
                return UNDEFINED;
        }
    }
}


text:
package kalang.compiler.compile.codegen.op;

import kalang.compiler.util.Exceptions;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.objectweb.asm.Opcodes.*;

/**
 * @author KasonYang
 */
public class OpOptimizer {

    public void optimize(OpCollector opCollector) {
        OpBase[] ops = opCollector.toArray(new OpBase[0]);
        int opsLen = ops.length;
        for (;;) {
            int newOpsLen = opsLen;
            newOpsLen = removeUnreachableOp(ops, newOpsLen, opCollector.getTryCatchBlocks());
            newOpsLen = removeUnnecessaryLoadPop(ops, newOpsLen);
            if (newOpsLen > opsLen) {
                throw Exceptions.unexpectedException("fail to optimize");
            } else if (newOpsLen == opsLen) {
                break;
            }
            opsLen = newOpsLen;
        }
        opCollector.clear();
        opCollector.addAll(Arrays.asList(ops).subList(0, opsLen));
        opCollector.getLineNumbers().removeIf(it -> !opCollector.contains(it.label) || opCollector.isEndLabel(it.label));
        opCollector.getLocalVariables().removeIf(it -> opCollector.isSamePosition(it.start, it.end));
    }

    private int removeUnreachableOp(OpBase[] ops, int len, List<TryCatchBlock> tryCatchBlocks) {
        Set<LabelOp> entryLabels = getEntryLabels(tryCatchBlocks, ops, len);
        int w;
        startLoop:
        for (int r = w = 1; r < len;) {
            OpBase prevOp = ops[w - 1];
            if (isTerminalOp(prevOp.opcode)) {
                while (r < len) {
                    OpBase op = ops[r];
                    if (op instanceof LabelOp) {
                        ops[w++] = ops[r++];
                        if (entryLabels.contains(op)) {
                            continue startLoop;
                        }
                    } else {
                        r++;
                    }
                }
                break;
            }
            ops[w++] = ops[r++];
        }
        return w;
    }

    private int removeUnnecessaryLoadPop(OpBase[] ops, int len) {
        int w;
        for (int r = w = 1; r < len;) {
            int opCode = ops[r].opcode;
            int prevOpCode = ops[w - 1].opcode;
            if (opCode == POP) {
                if (isLoad1(prevOpCode)) {
                    w--;
                    r++;
                    continue;
                } else if (prevOpCode == IINC && r >= 2 && isLoad1(ops[r - 2].opcode)) {
                    ops[w - 2] = ops[w - 1];
                    w--;
                    r++;
                }
            } else if (opCode == POP2) {
                if (isLoad2(prevOpCode)) {
                    w--;
                    r++;
                    continue;
                }
            }
            ops[w++] = ops[r++];
        }
        return w;
    }

    private boolean isLoad1(int opc) {
        return opc == ILOAD || opc == FLOAD || opc == ALOAD;
    }

    private boolean isLoad2(int opc) {
        return opc == LLOAD || opc == DLOAD;
    }

    private boolean isTerminalOp(int opc) {
        switch (opc) {
            case GOTO:
            case ATHROW:
            case RETURN:
            case IRETURN:
            case LRETURN:
            case FRETURN:
            case DRETURN:
            case ARETURN:
                return true;
            default:
                return false;
        }
    }

    private Set<LabelOp> getEntryLabels(List<TryCatchBlock> tryCatchBlocks, OpBase[] ops, int opsLen) {
        Set<LabelOp> result = new HashSet<>();
        for (int i = 0; i < opsLen; i++) {
            OpBase op = ops[i];
            if (op instanceof JumpInsnOp) {
                result.add(((JumpInsnOp) op).label);
            }
        }
        for (TryCatchBlock tcb : tryCatchBlocks) {
            result.add(tcb.handler);
        }
        return result;
    }

}


text:
class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or k == 0:
            return head

        slow = fast = head
        length = 1

        while k and fast.next:
            fast = fast.next
            length += 1
            k -= 1

        if k != 0:
            k = (k + length - 1) % length # original k % length
            return self.rotateRight(head, k)
        else:
            while fast.next:
                fast = fast.next
                slow = slow.next
            return self.rotate(head, fast, slow)

    def rotate(self, head, fast, slow):
        fast.next = head
        head = slow.next
        slow.next = None
        return head


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/ambient/model/ambient_topic_queue_animation_delegate.h"

#include <utility>

#include "ash/ambient/test/ambient_test_util.h"
#include "base/check.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_piece.h"
#include "cc/paint/skottie_resource_metadata.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/gfx/geometry/size.h"

namespace ash {
namespace {

using ::testing::UnorderedElementsAre;

}  // namespace

class AmbientTopicQueueAnimationDelegateTest : public ::testing::Test {
 protected:
  void RegisterAsset(base::StringPiece resource_id,
                     absl::optional<gfx::Size> size) {
    CHECK(resource_metadata_.RegisterAsset("test-path", "test-name",
                                           resource_id, std::move(size)))
        << "Asset " << resource_id << " already registered";
  }

  cc::SkottieResourceMetadataMap resource_metadata_;
};

TEST_F(AmbientTopicQueueAnimationDelegateTest,
       GetTopicSizesWithPortraitAndLandscape) {
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"A", /*idx=*/1),
      gfx::Size(100, 50));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"B", /*idx=*/1),
      gfx::Size(120, 40));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"C", /*idx=*/1),
      gfx::Size(50, 100));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"D", /*idx=*/1),
      gfx::Size(60, 80));
  AmbientTopicQueueAnimationDelegate delegate(resource_metadata_);
  EXPECT_THAT(
      delegate.GetTopicSizes(),
      UnorderedElementsAre(gfx::Size(125, 50),
                           gfx::Size(base::ClampRound<int>(62.5), 100)));
}

TEST_F(AmbientTopicQueueAnimationDelegateTest, GetTopicSizesWithOnlyPortrait) {
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"A", /*idx=*/1),
      gfx::Size(60, 100));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"B", /*idx=*/1),
      gfx::Size(100, 125));
  AmbientTopicQueueAnimationDelegate delegate(resource_metadata_);
  EXPECT_THAT(
      delegate.GetTopicSizes(),
      UnorderedElementsAre(gfx::Size(100, base::ClampRound<int>(100 / .7f))));
}

TEST_F(AmbientTopicQueueAnimationDelegateTest, GetTopicSizesWithOnlyLandscape) {
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"A", /*idx=*/1),
      gfx::Size(200, 100));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"B", /*idx=*/1),
      gfx::Size(120, 40));
  AmbientTopicQueueAnimationDelegate delegate(resource_metadata_);
  EXPECT_THAT(delegate.GetTopicSizes(),
              UnorderedElementsAre(gfx::Size(250, 100)));
}

TEST_F(AmbientTopicQueueAnimationDelegateTest, GetTopicSizesWithSquare) {
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"A", /*idx=*/1),
      gfx::Size(200, 100));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"B", /*idx=*/1),
      gfx::Size(120, 40));
  // Should be ignored when calculating the average aspect ratio.
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"C", /*idx=*/1),
      gfx::Size(300, 300));
  AmbientTopicQueueAnimationDelegate delegate(resource_metadata_);
  EXPECT_THAT(delegate.GetTopicSizes(),
              UnorderedElementsAre(gfx::Size(750, 300)));
}

TEST_F(AmbientTopicQueueAnimationDelegateTest, GetTopicSizesWithOnlySquare) {
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"A", /*idx=*/1),
      gfx::Size(200, 200));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"B", /*idx=*/1),
      gfx::Size(100, 100));
  AmbientTopicQueueAnimationDelegate delegate(resource_metadata_);
  EXPECT_THAT(delegate.GetTopicSizes(),
              UnorderedElementsAre(gfx::Size(200, 200)));
}

TEST_F(AmbientTopicQueueAnimationDelegateTest, HandlesMissingAssetSize) {
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"A", /*idx=*/1),
      gfx::Size(200, 100));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"B", /*idx=*/1),
      gfx::Size(120, 40));
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"C", /*idx=*/1),
      absl::nullopt);
  AmbientTopicQueueAnimationDelegate delegate(resource_metadata_);
  EXPECT_THAT(delegate.GetTopicSizes(),
              UnorderedElementsAre(gfx::Size(250, 100)));
}

TEST_F(AmbientTopicQueueAnimationDelegateTest, FiltersOutStaticImageAssets) {
  RegisterAsset(
      GenerateLottieDynamicAssetIdForTesting(/*position=*/"A", /*idx=*/1),
      gfx::Size(200, 100));
  RegisterAsset("static-image-asset-id", gfx::Size(120, 40));
  AmbientTopicQueueAnimationDelegate delegate(resource_metadata_);
  EXPECT_THAT(delegate.GetTopicSizes(),
              UnorderedElementsAre(gfx::Size(200, 100)));
}

}  // namespace ash


text:
package com.swfarm.biz.chain.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.bo.CustomerComplainInfo;
import com.swfarm.biz.chain.bo.CustomerOrder;
import com.swfarm.biz.chain.srv.ChainService;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.srv.WarehouseService;

public class SaveCustomerComplainInfoController extends AbstractController {

	private ChainService chainService;

	private WarehouseService warehouseService;

	public void setChainService(ChainService chainService) {
		this.chainService = chainService;
	}

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		String customerOrderId = req.getParameter("order");
		if (StringUtils.isNotEmpty(customerOrderId)) {
			CustomerComplainInfo customerComplainInfo = this.chainService
					.findCustomerComplainInfoByCustomerOrder(customerOrderId);
			if (customerComplainInfo == null) {
				customerComplainInfo = new CustomerComplainInfo();
				CustomerOrder customerOrder = this.chainService
						.findCustomerOrder(customerOrderId);
				customerComplainInfo.setCustomerOrderId(customerOrderId);
				customerComplainInfo.setCustomerOrderNo(customerOrder
						.getCustomerOrderNo());
				customerComplainInfo.setAccountNumber(customerOrder
						.getAccountNumber());
				customerComplainInfo
						.setCountry(customerOrder.getBuyerCountry());
				customerComplainInfo.setEbayUserId(customerOrder
						.getCustomerName());
				customerComplainInfo.setOrderDate(customerOrder.getOrderTime());
				customerComplainInfo.setShippingDate(customerOrder
						.getShippedTime());
				List allocationProductVouchers = this.warehouseService
						.findAllocationProductVouchersByCustomerOrder(customerOrderId);
				if (CollectionUtils.isNotEmpty(allocationProductVouchers)) {
					AllocationProductVoucher allocationProductVoucher = (AllocationProductVoucher) allocationProductVouchers
							.iterator().next();
					customerComplainInfo.setApvNo(allocationProductVoucher
							.getAllocationProductVoucherNo());
				}
				customerComplainInfo.setSfmCode(customerOrder
						.getShippingForwarderMethod());
				customerComplainInfo.setTrackingNumber(customerOrder
						.getShippingOrderNo());
				customerComplainInfo.setComplainDate(new Date());
			}
			String articleNumber = req.getParameter("articleNumber");
			String complainReason = req.getParameter("complainReason");
			String comments = req.getParameter("comments");
			customerComplainInfo.setArticleNumber(articleNumber);
			customerComplainInfo.setComplainReason(complainReason);
			customerComplainInfo.setComments(comments);
			this.chainService.saveCustomerComplainInfo(customerComplainInfo);
		}
		return new ModelAndView("redirect:/chain/customerorder.ahtml", "id",
				customerOrderId);
	}
}


text:
A library for building collaborative rich-text editors using [operational transformation](https://en.wikipedia.org/wiki/Operational_transformation).

It's based on [easysync](https://github.com/ether/etherpad-lite/tree/develop/doc/easysync) spec from the [Etherpad-Lite](https://github.com/ether/etherpad-lite) project. The format describes rich text document and any changes to it by expressing document and its rich formatting via text with attributes. The representation aims to be compact for quick transfers and effective storage.

This implementation is written from scratch and differs from Etherpad's [Changeset](https://github.com/ether/etherpad-lite/blob/develop/src/static/js/Changeset.js) library and EasySync format in the following ways:

* New attribute operation added: ^X, that removes attribute with index X from the text. Unlike original implementation, the format should be removed explicitly.
* "Remove text" operation should be accompanied by the text and its attributes that is being removed.
* As a result, invert() function is self-sufficient and does not require specific snapshot version to undo the operation.
* There should be no code path or situation without explicit check for operation validity to avoid breaked documents. Nothing slip through the cracks, period.
* It works with natural document representation – lines, not a big string. This reduces computation complexity on big documents.
* Complete tests coverage.

Resulting implementation is fast, solid and reliable. **Bonus**: it's compatible with [ShareJS ottypes API](https://github.com/ottypes/docs) that allows you to easily integrate it with existing OT-aware realtime backend.

It features all base OT operations:

* Composition
* Transformation
* Invertion
* **Bonus** Position transformation

## Install

In node:
```js
var OT = require('atext-changeset');
```

## Usage

Changeset is an ordered set of operations, there are 4 types of them:

1. Keep (skip text range),
2. Format (add attributes to the text range)
3. Insert
4. Remove

The changeset can be applied to the ADocument. **ADocument** is an internal rich-text document representation that stores it as an array of lines, where each line is an object containing text and its attributes. Additionaly each document have **Attribute Pool** – a dictionary of all formatting rules used in the document. It allows us to save a lot of bytes in the storage.

To start you need a document, so you either create empty one or start with a plain text:

```js
var doc = OT.ADocument.fromText('hello world');

// or
var doc = new OT.ADocument();

// or, if you've just received something from the database
var doc = OT.ADocument.unpack(data);
```

Now we start changing the document:
```js
var b = OT.Changeset.create(doc, 'stranger');
```
This code will return you a Changeset **Builder**. The document is required, because Builder will validate all changes you're going to make against it, plus fill the gaps for you so you don't have to figure out some details. Notice the last argument, it's optional. Changesets allows you to store author of the change, so you can later figure out who did what.

```js
// keep N chars with L lines
b.keep(N, L);

// format N chars and L lines with attributes
var format = new OT.AttributeList().addFormatOp('bold','true').addRemoveOp('italic','true');
b.format(N, L, format);

// remove all format on the text range
b.removeAllFormat(N, L);

// insert text at the current position
var insertFormat = new OT.AttributeList().addFormatOp('bold','true');
b.insert('hello\nworld', insertFormat);

// remove text range from the current position
b.remove(N, L);

// finish and return Changeset
var cs = b.finish();

// you can also chain calls
var cs2 = OT.Changeset.create(doc).keep(2, 0).insert('hello').remove(4, 1).finish();
```

### IMPORTANT
Notice the **N** and **L** parameters in the calls above. N stands for characters, and L stands for lines. There are few rules about them:

1. N includes L, for example ```'a\nb\n': N=4, L=2```
2. If you specify L>0, you should always complete operation **at the end of the line**. For example: ```'a\nb\n': N=4, L=2``` - VALID, but ```'a\nb': N=3, L=1``` - INVALID
3. That means if you need to remove 2 lines and then 2 more characters, you should split into 2 operations: ```b.remove(4, 2).remove(2, 0);```

## Operational Transformation
Assuming you know what Operational Transformation is, here's a short summary of what's available. All operations are immutable, i.e. they create a new Changeset object instead of touching existing ones.

### Compose
Return a composition of 2 changesets. That is, combines 2 consecutive changes into one.
```js
var res = cs1.compose(cs2);
```

### Transform
Transforms cs1 against cs2, specifying a side: 'left' or 'right'. For own changes usually use 'left', for remote - 'right'.
```js
var res = cs1.transform(cs2, side);
```

### Invert
Easy as it sounds. Inverts the changeset, no strings attached.
```js
var res = cs.invert();
```

### Apply
Modifies document in-place, because cloning it could be resource-unfriendly.
```js
cs.applyTo(doc);
```

## Attributes

Attributes are used to describe formatting. Each attribute is a key/value pair that can be anything. For example, rich text editors can use ```bold: true``` or ```img: http://....jpg``` and then render them accordingly.

There are 2 types of operations for the attributes:

* Format
* Remove format

If you have an ```img``` attribute and want to override its value with different URL, you can't just perform format with the new URL, you should first remove original attribute with ```Remove``` operation, and then ```Format``` it again. This is true for any attribute key, there can't be 2 keys with the same name. But usually you shouldn't bother, ```Builder``` will remove previous value for you.

Creating attributes list:
```js
// creates an empty list
var format = new OT.AttributeList();

// add format attribute
format.addFormatOp(key, value);

// remove format attribute
format.addRemoveOp(key, value);

// or chain calls
var format = new OT.AttributeList().addFormat(...).removeFormat(...);
```

There is one built-in attribute name that shouldn't be explicitly used. It's called ```author``` and stores author of the change, if was specified for the ```Builder```.

## Position

Position is used for presense awareness and drawing carets and selections of other users in the document (like Google Docs).
Most of the OT libraries use linear index for the position that only create problems in real life. Seriously, in the editor you have line and character position of the caret, and you should convert it to the linear offset by calculating how many characters you have before the caret, then transform, then split resulting offset again into lines and chars to get the new value in the document space. That's a lot of unnecessary work.

Here the Position is represented by natural 2-dimension coordinate that can be transformed directly. This makes a huge difference.

```js
var pos = new Position(char, line);

// transform it against changeset
var newPos = cs.transformPosition(pos);
```

## Storage and transport

Before storing or sending a changeset you need to pack it. Just do ```var res = cs.pack()```. Of course before working with received changeset, don't forget to unpack it first: ```var cs = OT.Changeset.unpack(data)```. Documents can do the same.

## TODO

- [ ] Figure out the best way to build for browser.
- [ ] Create a good client API to iterate over ADocument
- [ ] Describe how it integrates with ShareJS.
- [ ] Add some tests for ADocument class and find what could be missing.
- [ ] Implement diff algorithm from Etherpad

## License
MIT

## Changelog

0.1
* Initial release


text:
In order to include an image in your site, you can use the image helper tag
(without blankspaces):

[ [path/to/img] ]

Example of output:

[[http://nopat.ch/g/z.png]]


text:
"""calendar_clock.py: Public Calendar Clock class representing a time in the educational game Trusty Brusher."""

import threading
import time

class Calendar_Clock(threading.Thread):
    """
       A Calendar Clock that tracks current day of the week, current hour, and current minute.
       self.day_list: list value indicating names and order of days of the week
       self.current_day: string value indicating the current day of the week
       self.current_hour: int value indicating the current hour of the day (24-hour clock is used, 0-23)
       self.current_minute: int value indicating the current minute of the hour (60 minutes per hour, 0-59)
       self.stop_clock_flag: bool value indicating whether or not the Calendar Clock should stop

       To use Calendar_Clock, create an instance and call Python threading module methods on that instance:

           some_new_clock = Calendar_Clock()
           # ... or ...
           some_new_clock = Calendar_Clock("Friday", 17, 5)

           some_new_clock.start()

           # ... do some work ...
           # ... use instance methods defined below ...
           # ... and when finished ...

           some_new_clock.stop()
           some_new_clock.join()

       Some class design elements taken from Python Advanced Turtorial 5 - MultiThreading
       by DrapsTV, found here: https://youtu.be/EvbA3qVMGaw

    """
    def __init__(self, init_start_day="SUNDAY", init_start_hour=7, init_start_minute=0):
        threading.Thread.__init__(self)
        self.stop_clock_flag = False
        self.day_list = [ "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" ]
        self.current_day = init_start_day
        self.current_day = self.current_day.upper()
        self.current_hour = init_start_hour
        self.current_minute = init_start_minute

    def run(self):
        while self.stop_clock_flag == False:
            if self.current_minute == 59:
                self.current_minute = 0
                if self.current_hour == 23:
                    self.current_hour = 0
                    if self.day_list.index(self.current_day) == 6:
                        self.current_day = self.day_list[0]
                    else:
                        self.current_day = self.day_list[ self.day_list.index(self.current_day) + 1 ]
                else:
                    self.current_hour = self.current_hour + 1
            else:
                self.current_minute = self.current_minute + 1
            time.sleep(0.1)

    def stop(self):
        self.stop_clock_flag = True

    def get_day(self):
        return self.current_day

    def set_day(self, new_day):
        self.current_day = new_day
        self.current_day = self.current_day.upper()

    def get_hour(self):
        return self.current_hour

    def set_hour(self, new_hour):
        self.current_hour = new_hour

    def get_minute(self):
        return self.current_minute

    def set_minute(self, new_minute):
        self.current_minute = new_minute

    def get_time_stamp(self):
        if self.current_hour < 10:
    	    formated_hour = "0{}".format(str(self.current_hour))
        else:
            formated_hour = str(self.current_hour)
    	if self.current_minute < 10:
    	    formated_minute = "0{}".format(str(self.current_minute))
    	else:
    	    formated_minute = str(self.current_minute)
        return "{} {}:{}".format(self.current_day, formated_hour, formated_minute)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.UI.UserControls
{
    using System;
    using System.Linq;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;

    using DotNetNuke.Common.Lists;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Framework;
    using DotNetNuke.Security.Permissions;
    using DotNetNuke.Services.Exceptions;
    using DotNetNuke.Services.Localization;
    using DotNetNuke.UI.WebControls;

    /// <summary>
    /// The Address UserControl is used to manage User Addresses.
    /// </summary>
    /// <remarks>
    /// </remarks>
    public abstract class Address : UserControlBase
    {
        private const string MyFileName = "Address.ascx";
        protected CountryListBox cboCountry;
        protected DropDownList cboRegion;
        protected CheckBox chkCell;
        protected CheckBox chkCity;
        protected CheckBox chkCountry;
        protected CheckBox chkFax;
        protected CheckBox chkPostal;
        protected CheckBox chkRegion;
        protected CheckBox chkStreet;
        protected CheckBox chkTelephone;
        protected LabelControl plCell;
        protected LabelControl plCity;
        protected LabelControl plCountry;
        protected LabelControl plFax;
        protected LabelControl plPostal;
        protected LabelControl plRegion;
        protected LabelControl plStreet;
        protected LabelControl plTelephone;
        protected LabelControl plUnit;
        protected HtmlGenericControl divCell;
        protected HtmlGenericControl divCity;
        protected HtmlGenericControl divCountry;
        protected HtmlGenericControl divFax;
        protected HtmlGenericControl divPostal;
        protected HtmlGenericControl divRegion;
        protected HtmlGenericControl divStreet;
        protected HtmlGenericControl divTelephone;
        protected HtmlGenericControl divUnit;
        protected TextBox txtCell;
        protected TextBox txtCity;
        protected TextBox txtFax;
        protected TextBox txtPostal;
        protected TextBox txtRegion;
        protected TextBox txtStreet;
        protected TextBox txtTelephone;
        protected TextBox txtUnit;
        protected RequiredFieldValidator valCell;
        protected RequiredFieldValidator valCity;
        protected RequiredFieldValidator valCountry;
        protected RequiredFieldValidator valFax;
        protected RequiredFieldValidator valPostal;
        protected RequiredFieldValidator valRegion1;
        protected RequiredFieldValidator valRegion2;
        protected RequiredFieldValidator valStreet;
        protected RequiredFieldValidator valTelephone;
        private string _cell;
        private string _city;
        private string _controlColumnWidth = string.Empty;
        private string _country;
        private string _countryData = "Text";
        private string _fax;
        private string _labelColumnWidth = string.Empty;
        private int _moduleId;
        private string _postal;
        private string _region;
        private string _regionData = "Text";
        private bool _showCell = true;
        private bool _showCity = true;
        private bool _showCountry = true;
        private bool _showFax = true;
        private bool _showPostal = true;
        private bool _showRegion = true;
        private bool _showStreet = true;
        private bool _showTelephone = true;
        private bool _showUnit = true;
        private string _street;
        private string _telephone;
        private string _unit;

        /// <summary>
        /// Initializes a new instance of the <see cref="Address"/> class.
        /// </summary>
        protected Address()
        {
            this.StartTabIndex = 1;
        }

        public string LocalResourceFile
        {
            get
            {
                return Localization.GetResourceFile(this, MyFileName);
            }
        }

        public int ModuleId
        {
            get
            {
                return Convert.ToInt32(this.ViewState["ModuleId"]);
            }

            set
            {
                this._moduleId = value;
            }
        }

        public string LabelColumnWidth
        {
            get
            {
                return Convert.ToString(this.ViewState["LabelColumnWidth"]);
            }

            set
            {
                this._labelColumnWidth = value;
            }
        }

        public string ControlColumnWidth
        {
            get
            {
                return Convert.ToString(this.ViewState["ControlColumnWidth"]);
            }

            set
            {
                this._controlColumnWidth = value;
            }
        }

        public int StartTabIndex { private get; set; }

        public string Street
        {
            get
            {
                return this.txtStreet.Text;
            }

            set
            {
                this._street = value;
            }
        }

        public string Unit
        {
            get
            {
                return this.txtUnit.Text;
            }

            set
            {
                this._unit = value;
            }
        }

        public string City
        {
            get
            {
                return this.txtCity.Text;
            }

            set
            {
                this._city = value;
            }
        }

        public string Country
        {
            get
            {
                var retValue = string.Empty;
                if (this.cboCountry.SelectedItem != null)
                {
                    switch (this._countryData.ToLowerInvariant())
                    {
                        case "text":
                            retValue = this.cboCountry.SelectedIndex == 0 ? string.Empty : this.cboCountry.SelectedItem.Text;
                            break;
                        case "value":
                            retValue = this.cboCountry.SelectedItem.Value;
                            break;
                    }
                }

                return retValue;
            }

            set
            {
                this._country = value;
            }
        }

        public string Region
        {
            get
            {
                var retValue = string.Empty;
                if (this.cboRegion.Visible)
                {
                    if (this.cboRegion.SelectedItem != null)
                    {
                        switch (this._regionData.ToLowerInvariant())
                        {
                            case "text":
                                if (this.cboRegion.SelectedIndex > 0)
                                {
                                    retValue = this.cboRegion.SelectedItem.Text;
                                }

                                break;
                            case "value":
                                retValue = this.cboRegion.SelectedItem.Value;
                                break;
                        }
                    }
                }
                else
                {
                    retValue = this.txtRegion.Text;
                }

                return retValue;
            }

            set
            {
                this._region = value;
            }
        }

        public string Postal
        {
            get
            {
                return this.txtPostal.Text;
            }

            set
            {
                this._postal = value;
            }
        }

        public string Telephone
        {
            get
            {
                return this.txtTelephone.Text;
            }

            set
            {
                this._telephone = value;
            }
        }

        public string Cell
        {
            get
            {
                return this.txtCell.Text;
            }

            set
            {
                this._cell = value;
            }
        }

        public string Fax
        {
            get
            {
                return this.txtFax.Text;
            }

            set
            {
                this._fax = value;
            }
        }

        public bool ShowStreet
        {
            set
            {
                this._showStreet = value;
            }
        }

        public bool ShowUnit
        {
            set
            {
                this._showUnit = value;
            }
        }

        public bool ShowCity
        {
            set
            {
                this._showCity = value;
            }
        }

        public bool ShowCountry
        {
            set
            {
                this._showCountry = value;
            }
        }

        public bool ShowRegion
        {
            set
            {
                this._showRegion = value;
            }
        }

        public bool ShowPostal
        {
            set
            {
                this._showPostal = value;
            }
        }

        public bool ShowTelephone
        {
            set
            {
                this._showTelephone = value;
            }
        }

        public bool ShowCell
        {
            set
            {
                this._showCell = value;
            }
        }

        public bool ShowFax
        {
            set
            {
                this._showFax = value;
            }
        }

        public string CountryData
        {
            set
            {
                this._countryData = value;
            }
        }

        public string RegionData
        {
            set
            {
                this._regionData = value;
            }
        }

        /// <summary>
        /// Page_Load runs when the control is loaded.
        /// </summary>
        /// <remarks>
        /// </remarks>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.cboCountry.SelectedIndexChanged += this.OnCountryIndexChanged;
            this.chkCell.CheckedChanged += this.OnCellCheckChanged;
            this.chkCity.CheckedChanged += this.OnCityCheckChanged;
            this.chkCountry.CheckedChanged += this.OnCountryCheckChanged;
            this.chkFax.CheckedChanged += this.OnFaxCheckChanged;
            this.chkPostal.CheckedChanged += this.OnPostalCheckChanged;
            this.chkRegion.CheckedChanged += this.OnRegionCheckChanged;
            this.chkStreet.CheckedChanged += this.OnStreetCheckChanged;
            this.chkTelephone.CheckedChanged += this.OnTelephoneCheckChanged;

            try
            {
                this.valStreet.ErrorMessage = Localization.GetString("StreetRequired", Localization.GetResourceFile(this, MyFileName));
                this.valCity.ErrorMessage = Localization.GetString("CityRequired", Localization.GetResourceFile(this, MyFileName));
                this.valCountry.ErrorMessage = Localization.GetString("CountryRequired", Localization.GetResourceFile(this, MyFileName));
                this.valPostal.ErrorMessage = Localization.GetString("PostalRequired", Localization.GetResourceFile(this, MyFileName));
                this.valTelephone.ErrorMessage = Localization.GetString("TelephoneRequired", Localization.GetResourceFile(this, MyFileName));
                this.valCell.ErrorMessage = Localization.GetString("CellRequired", Localization.GetResourceFile(this, MyFileName));
                this.valFax.ErrorMessage = Localization.GetString("FaxRequired", Localization.GetResourceFile(this, MyFileName));

                if (!this.Page.IsPostBack)
                {
                    this.txtStreet.TabIndex = Convert.ToInt16(this.StartTabIndex);
                    this.txtUnit.TabIndex = Convert.ToInt16(this.StartTabIndex + 1);
                    this.txtCity.TabIndex = Convert.ToInt16(this.StartTabIndex + 2);
                    this.cboCountry.TabIndex = Convert.ToInt16(this.StartTabIndex + 3);
                    this.cboRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 4);
                    this.txtRegion.TabIndex = Convert.ToInt16(this.StartTabIndex + 5);
                    this.txtPostal.TabIndex = Convert.ToInt16(this.StartTabIndex + 6);
                    this.txtTelephone.TabIndex = Convert.ToInt16(this.StartTabIndex + 7);
                    this.txtCell.TabIndex = Convert.ToInt16(this.StartTabIndex + 8);
                    this.txtFax.TabIndex = Convert.ToInt16(this.StartTabIndex + 9);

                    // <tam:note modified to test Lists
                    // Dim objRegionalController As New RegionalController
                    // cboCountry.DataSource = objRegionalController.GetCountries
                    // <this test using method 2: get empty collection then get each entry list on demand & store into cache
                    var ctlEntry = new ListController();
                    var entryCollection = ctlEntry.GetListEntryInfoItems("Country");

                    this.cboCountry.DataSource = entryCollection;
                    this.cboCountry.DataBind();
                    this.cboCountry.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", string.Empty));

                    switch (this._countryData.ToLowerInvariant())
                    {
                        case "text":
                            if (string.IsNullOrEmpty(this._country))
                            {
                                this.cboCountry.SelectedIndex = 0;
                            }
                            else
                            {
                                if (this.cboCountry.Items.FindByText(this._country) != null)
                                {
                                    this.cboCountry.ClearSelection();
                                    this.cboCountry.Items.FindByText(this._country).Selected = true;
                                }
                            }

                            break;
                        case "value":
                            if (this.cboCountry.Items.FindByValue(this._country) != null)
                            {
                                this.cboCountry.ClearSelection();
                                this.cboCountry.Items.FindByValue(this._country).Selected = true;
                            }

                            break;
                    }

                    this.Localize();

                    if (this.cboRegion.Visible)
                    {
                        switch (this._regionData.ToLowerInvariant())
                        {
                            case "text":
                                if (string.IsNullOrEmpty(this._region))
                                {
                                    this.cboRegion.SelectedIndex = 0;
                                }
                                else
                                {
                                    if (this.cboRegion.Items.FindByText(this._region) != null)
                                    {
                                        this.cboRegion.Items.FindByText(this._region).Selected = true;
                                    }
                                }

                                break;
                            case "value":
                                if (this.cboRegion.Items.FindByValue(this._region) != null)
                                {
                                    this.cboRegion.Items.FindByValue(this._region).Selected = true;
                                }

                                break;
                        }
                    }
                    else
                    {
                        this.txtRegion.Text = this._region;
                    }

                    this.txtStreet.Text = this._street;
                    this.txtUnit.Text = this._unit;
                    this.txtCity.Text = this._city;
                    this.txtPostal.Text = this._postal;
                    this.txtTelephone.Text = this._telephone;
                    this.txtCell.Text = this._cell;
                    this.txtFax.Text = this._fax;

                    this.divStreet.Visible = this._showStreet;
                    this.divUnit.Visible = this._showUnit;
                    this.divCity.Visible = this._showCity;
                    this.divCountry.Visible = this._showCountry;
                    this.divRegion.Visible = this._showRegion;
                    this.divPostal.Visible = this._showPostal;
                    this.divTelephone.Visible = this._showTelephone;
                    this.divCell.Visible = this._showCell;
                    this.divFax.Visible = this._showFax;

                    if (TabPermissionController.CanAdminPage())
                    {
                        this.chkStreet.Visible = true;
                        this.chkCity.Visible = true;
                        this.chkCountry.Visible = true;
                        this.chkRegion.Visible = true;
                        this.chkPostal.Visible = true;
                        this.chkTelephone.Visible = true;
                        this.chkCell.Visible = true;
                        this.chkFax.Visible = true;
                    }

                    this.ViewState["ModuleId"] = Convert.ToString(this._moduleId);
                    this.ViewState["LabelColumnWidth"] = this._labelColumnWidth;
                    this.ViewState["ControlColumnWidth"] = this._controlColumnWidth;

                    this.ShowRequiredFields();
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnCountryIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.Localize();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnCityCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc) // Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnCountryCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnPostalCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnRegionCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnStreetCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnTelephoneCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnCellCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void OnFaxCheckChanged(object sender, EventArgs e)
        {
            try
            {
                this.UpdateRequiredFields();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// Localize correctly sets up the control for US/Canada/Other Countries.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void Localize()
        {
            var countryCode = this.cboCountry.SelectedItem.Value;
            var ctlEntry = new ListController();

            // listKey in format "Country.US:Region"
            var listKey = "Country." + countryCode;
            var entryCollection = ctlEntry.GetListEntryInfoItems("Region", listKey);

            if (entryCollection.Any())
            {
                this.cboRegion.Visible = true;
                this.txtRegion.Visible = false;
                {
                    this.cboRegion.Items.Clear();
                    this.cboRegion.DataSource = entryCollection;
                    this.cboRegion.DataBind();
                    this.cboRegion.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", string.Empty));
                }

                if (countryCode.Equals("us", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.valRegion1.Enabled = true;
                    this.valRegion2.Enabled = false;
                    this.valRegion1.ErrorMessage = Localization.GetString("StateRequired", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.Text = Localization.GetString("plState", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.HelpText = Localization.GetString("plState.Help", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.Text = Localization.GetString("plZip", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.HelpText = Localization.GetString("plZip.Help", Localization.GetResourceFile(this, MyFileName));
                }
                else
                {
                    this.valRegion1.ErrorMessage = Localization.GetString("ProvinceRequired", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.Text = Localization.GetString("plProvince", Localization.GetResourceFile(this, MyFileName));
                    this.plRegion.HelpText = Localization.GetString("plProvince.Help", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.Text = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName));
                    this.plPostal.HelpText = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName));
                }

                this.valRegion1.Enabled = true;
                this.valRegion2.Enabled = false;
            }
            else
            {
                this.cboRegion.ClearSelection();
                this.cboRegion.Visible = false;
                this.txtRegion.Visible = true;
                this.valRegion1.Enabled = false;
                this.valRegion2.Enabled = true;
                this.valRegion2.ErrorMessage = Localization.GetString("RegionRequired", Localization.GetResourceFile(this, MyFileName));
                this.plRegion.Text = Localization.GetString("plRegion", Localization.GetResourceFile(this, MyFileName));
                this.plRegion.HelpText = Localization.GetString("plRegion.Help", Localization.GetResourceFile(this, MyFileName));
                this.plPostal.Text = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName));
                this.plPostal.HelpText = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName));
            }

            var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", this.PortalSettings.PortalId, true);
            if (reqRegion)
            {
                this.valRegion1.Enabled = false;
                this.valRegion2.Enabled = false;
            }
        }

        /// <summary>
        /// ShowRequiredFields sets up displaying which fields are required.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void ShowRequiredFields()
        {
            var reqStreet = PortalController.GetPortalSettingAsBoolean("addressstreet", this.PortalSettings.PortalId, true);
            var reqCity = PortalController.GetPortalSettingAsBoolean("addresscity", this.PortalSettings.PortalId, true);
            var reqCountry = PortalController.GetPortalSettingAsBoolean("addresscountry", this.PortalSettings.PortalId, true);
            var reqRegion = PortalController.GetPortalSettingAsBoolean("addressregion", this.PortalSettings.PortalId, true);
            var reqPostal = PortalController.GetPortalSettingAsBoolean("addresspostal", this.PortalSettings.PortalId, true);
            var reqTelephone = PortalController.GetPortalSettingAsBoolean("addresstelephone", this.PortalSettings.PortalId, true);
            var reqCell = PortalController.GetPortalSettingAsBoolean("addresscell", this.PortalSettings.PortalId, true);
            var reqFax = PortalController.GetPortalSettingAsBoolean("addressfax", this.PortalSettings.PortalId, true);

            if (TabPermissionController.CanAdminPage())
            {
                if (reqCountry)
                {
                    this.chkCountry.Checked = true;
                    this.valCountry.Enabled = true;
                    this.cboCountry.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valCountry.Enabled = false;
                    this.cboCountry.CssClass = string.Empty;
                }

                if (reqRegion)
                {
                    this.chkRegion.Checked = true;
                    this.txtRegion.CssClass = "dnnFormRequired";
                    this.cboRegion.CssClass = "dnnFormRequired";

                    if (this.cboRegion.Visible)
                    {
                        this.valRegion1.Enabled = true;
                        this.valRegion2.Enabled = false;
                    }
                    else
                    {
                        this.valRegion1.Enabled = false;
                        this.valRegion2.Enabled = true;
                    }
                }
                else
                {
                    this.valRegion1.Enabled = false;
                    this.valRegion2.Enabled = false;
                    this.txtRegion.CssClass = string.Empty;
                    this.cboRegion.CssClass = string.Empty;
                }

                if (reqCity)
                {
                    this.chkCity.Checked = true;
                    this.valCity.Enabled = true;
                    this.txtCity.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valCity.Enabled = false;
                    this.txtCity.CssClass = string.Empty;
                }

                if (reqStreet)
                {
                    this.chkStreet.Checked = true;
                    this.valStreet.Enabled = true;
                    this.txtStreet.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valStreet.Enabled = false;
                    this.txtStreet.CssClass = string.Empty;
                }

                if (reqPostal)
                {
                    this.chkPostal.Checked = true;
                    this.valPostal.Enabled = true;
                    this.txtPostal.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valPostal.Enabled = false;
                    this.txtPostal.CssClass = string.Empty;
                }

                if (reqTelephone)
                {
                    this.chkTelephone.Checked = true;
                    this.valTelephone.Enabled = true;
                    this.txtTelephone.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valTelephone.Enabled = false;
                    this.txtTelephone.CssClass = string.Empty;
                }

                if (reqCell)
                {
                    this.chkCell.Checked = true;
                    this.valCell.Enabled = true;
                    this.txtCell.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valCell.Enabled = false;
                    this.txtCell.CssClass = string.Empty;
                }

                if (reqFax)
                {
                    this.chkFax.Checked = true;
                    this.valFax.Enabled = true;
                    this.txtFax.CssClass = "dnnFormRequired";
                }
                else
                {
                    this.valFax.Enabled = false;
                    this.txtFax.CssClass = string.Empty;
                }
            }
        }

        /// <summary>
        /// UpdateRequiredFields updates which fields are required.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private void UpdateRequiredFields()
        {
            if (this.chkCountry.Checked == false)
            {
                this.chkRegion.Checked = false;
            }

            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressstreet", this.chkStreet.Checked ? string.Empty : "N");
            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscity", this.chkCity.Checked ? string.Empty : "N");
            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscountry", this.chkCountry.Checked ? string.Empty : "N");
            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressregion", this.chkRegion.Checked ? string.Empty : "N");
            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresspostal", this.chkPostal.Checked ? string.Empty : "N");
            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresstelephone", this.chkTelephone.Checked ? string.Empty : "N");
            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscell", this.chkCell.Checked ? string.Empty : "N");
            PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressfax", this.chkFax.Checked ? string.Empty : "N");

            this.ShowRequiredFields();
        }
    }
}


text:
using System;
using System.Threading.Tasks;

namespace WindowsAzure.ServiceBus.Cqs
{
    internal class TaskWrapper<TResult> : ITaskHandler
    {
        private readonly TaskCompletionSource<TResult> _task;
        private DateTime _addedAt;

        public TaskWrapper(TaskCompletionSource<TResult> task)
        {
            _task = task;
            _addedAt = DateTime.UtcNow;
        }

        public bool IsExpired
        {
            get { return DateTime.UtcNow.Subtract(_addedAt) > TimeSpan.FromSeconds(60); }
        }

        public void SetResult(object result)
        {
            _task.SetResult((TResult) result);
        }

        public void SetException(Exception exception)
        {
            _task.SetException(exception);
        }
    }
}


text:
require 'simplecov'
require 'awesome_print'
require_relative '../test_classes'
SimpleCov.start
require 'pretentious'