text:
<?php

namespace ItvisionSy\Validator;

/**
 * Description of UrlValidatorRule
 *
 * @author Muhannad Shelleh <muhannad.shelleh@itvision-sy.com>
 */
class UrlValidatorRule extends ValidatorRule {

    protected function _validate($value) {
        return !!filter_var($value, \FILTER_VALIDATE_URL)?:"Value is not a valid URL";
    }

}

redpajama_set_name: RedPajamaGithub


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * A results that wants to defaultComplete to 0, but it has no matches,
 * though it notifies SUCCESS to the controller.
 */
function AutoCompleteNoMatchResult() {
  this.defaultIndex = 0;
}
AutoCompleteNoMatchResult.prototype = Object.create(AutoCompleteResultBase.prototype);

/**
 * A results that wants to defaultComplete to an index greater than the number
 * of matches.
 */
function AutoCompleteBadIndexResult(aValues, aDefaultIndex) {
  do_check_true(aValues.length <= aDefaultIndex);
  this._values = aValues;
  this.defaultIndex = aDefaultIndex;
}
AutoCompleteBadIndexResult.prototype = Object.create(AutoCompleteResultBase.prototype);

add_test(function autocomplete_noMatch_success() {
  const INPUT_STR = "moz";

  let searchNoMatch =
    new AutoCompleteSearchBase("searchNoMatch",
                               new AutoCompleteNoMatchResult());
  registerAutoCompleteSearch(searchNoMatch);

  // Make an AutoCompleteInput that uses our search and confirms results.
  let input = new AutoCompleteInputBase([searchNoMatch.name]);
  input.completeDefaultIndex = true;
  input.textValue = INPUT_STR;

  // Caret must be at the end for autoFill to happen.
  let strLen = INPUT_STR.length;
  input.selectTextRange(strLen, strLen);
  do_check_eq(input.selectionStart, strLen);
  do_check_eq(input.selectionEnd, strLen);

  let controller = Cc["@mozilla.org/autocomplete/controller;1"].
                   getService(Ci.nsIAutoCompleteController);
  controller.input = input;
  controller.startSearch(INPUT_STR);

  input.onSearchComplete = function () {
    // Should not try to autoFill to an empty value.
    do_check_eq(input.textValue, "moz");

    // Clean up.
    unregisterAutoCompleteSearch(searchNoMatch);
    run_next_test();
  };
});

add_test(function autocomplete_defaultIndex_exceeds_matchCount() {
  const INPUT_STR = "moz";

  // Result returning matches, but a bad defaultIndex.
  let searchBadIndex =
    new AutoCompleteSearchBase("searchBadIndex",
                               new AutoCompleteBadIndexResult(["mozillaTest"], 1));
  registerAutoCompleteSearch(searchBadIndex);

  // Make an AutoCompleteInput that uses our search and confirms results.
  let input = new AutoCompleteInputBase([searchBadIndex.name]);
  input.completeDefaultIndex = true;
  input.textValue = INPUT_STR;

  // Caret must be at the end for autoFill to happen.
  let strLen = INPUT_STR.length;
  input.selectTextRange(strLen, strLen);
  do_check_eq(input.selectionStart, strLen);
  do_check_eq(input.selectionEnd, strLen);

  let controller = Cc["@mozilla.org/autocomplete/controller;1"].
                   getService(Ci.nsIAutoCompleteController);
  controller.input = input;
  controller.startSearch(INPUT_STR);

  input.onSearchComplete = function () {
    // Should not try to autoFill to an empty value.
    do_check_eq(input.textValue, "moz");

    // Clean up.
    unregisterAutoCompleteSearch(searchBadIndex);
    run_next_test();
  };
});

function run_test() {
  run_next_test();
}


text:
package com.test.project.backupCourseManagementSystem.domain;

/**
 * Created by beigui on 2016/4/6.
 */
public class TechCourse {
    private Teacher teacher;
    private Course course;

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }
}


text:
> see https://aka.ms/autorest

This is the AutoRest configuration file for quantum.

## Getting Started

To build the SDKs for My API, simply install AutoRest via `npm` (`npm install -g autorest`) and then run:

> `autorest readme.md`

To see additional help and options, run:

> `autorest --help`

For other options on installation see [Installing AutoRest](https://aka.ms/autorest/install) on the AutoRest github page.

---

## Configuration

### Basic Information

These are the global settings for the quantum.

``` yaml
openapi-type: arm
openapi-subtype: rpaas
tag: package-2022-01-10-preview
```

### Tag: package-2019-11-04-preview

These settings apply only when `--tag=package-2019-11-04-preview` is specified on the command line.

``` yaml $(tag) == 'package-2019-11-04-preview'
input-file:
  - Microsoft.Quantum/preview/2019-11-04-preview/quantum.json
```

### Tag: package-2022-01-10-preview

These settings apply only when `--tag=package-2022-01-10-preview` is specified on the command line.

``` yaml $(tag) == 'package-2022-01-10-preview'
input-file:
  - Microsoft.Quantum/preview/2022-01-10-preview/quantum.json
```

---

# Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-python-track2
  - repo: azure-sdk-for-go
  - repo: azure-sdk-for-js
  - repo: azure-powershell
```

## Go

See configuration in [readme.go.md](./readme.go.md)

## Python

See configuration in [readme.python.md](./readme.python.md)

## TypeScript

See configuration in [readme.typescript.md](./readme.typescript.md)

## CSharp

See configuration in [readme.csharp.md](./readme.csharp.md)

## Suppression

``` yaml
directive:
  - suppress: EnumInsteadOfBoolean
    where: $.definitions.operation.properties.isDataAction
    from: quantum.json
    reason: 'This property is really a boolean, there are no plans to have more than two values in the future.'
  - suppress: AvoidNestedProperties
    where: $.definitions.ProviderDescription.properties.properties
    from: quantum.json
    reason: We don't have end customers making direct API calls and this is a breaking change for our existing clients.
```


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="ca.dingkaiualberta.buzzergame.UI.SingleGameActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Restart"
        android:id="@+id/restart"
        android:visibility="gone"
        android:onClick="onStartGame"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="204dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/score"
        android:visibility="gone"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start!"
        android:id="@+id/start"
        android:visibility="gone"
        android:onClick="onStartGame"
        android:layout_below="@+id/welcome"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Tap Stop button\nwhen star appears"
        android:gravity="center"
        android:id="@+id/welcome"
        android:visibility="gone"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/starimage"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/red"
        android:visibility="gone"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Tap too early!"
        android:id="@+id/early"
        android:visibility="gone"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="130dp"
        android:text="Stop!"
        android:id="@+id/stop"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:visibility="gone"
        android:onClick="onStopGame"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>


text:
module Nack
  class Error < StandardError
  end
end


text:
class UpdateTravelAdviceSlugs < Mongoid::Migration
  def self.up
    Artefact.where(:slug => %r{\Atravel-advice/}).each do |artefact|
      if ! Rails.env.development? or ENV['UPDATE_SEARCH'].present?
        Rummageable.delete("/#{artefact.slug}")
      end
      artefact.set(:slug, "foreign-#{artefact.slug}")
    end
  end

  def self.down
    Artefact.where(:slug => %r{\Aforeign-travel-advice/(.*)\z}).each do |artefact|
      artefact.set(:slug, artefact.slug.sub(/\Aforeign-/, ''))
    end
  end
end


text:
require 'concur_connect/itinerary'

module ConcurConnect
  class ItineraryFinder
    attr_accessor :session

    def initialize(session)
      self.session = session
    end

    def find(user_id, start_date = nil)
      url = 'travel/trip/v1.0/'
      url += "?startDate=#{start_date.strftime('%Y-%m-%d')}" if start_date
      response = session.get url do |g|
        g.headers['X-UserID'] = user_id
      end
      build_itineraries response.body
    end

    def build_itineraries(data)
      list = []
      if data['ItineraryInfoList'] && data['ItineraryInfoList']['ItineraryInfo']
        data['ItineraryInfoList']['ItineraryInfo'].each do |datum|
          itinerary = Itinerary.new
          itinerary.concur_id = datum['id']
          itinerary.name = datum['TripName']
          itinerary.start_date = datum['StartDateLocal']
          itinerary.end_date = datum['EndDateLocal']
          list << itinerary
        end
      end
      list
    end
  end
end


text:
        <wicket:extend>

                <wicket:message key="space_list.spaceList"/>
                <wicket:enclosure>
                    [ <wicket:message key="space_list.createNewSpace"/> ]
                </wicket:enclosure>

                    <wicket:message key="space_list.name"/>
                    <wicket:message key="space_list.key"/>
                    <wicket:message key="space_list.description"/>
                    <wicket:message key="space_list.edit"/>
                    <wicket:message key="space_list.users"/>
                    <wicket:message key="space_list.emails"/>

                		Some icons obtained from Icon Drawer

        </wicket:extend>


text:
export interface TaskToken {
  readonly $$label?: "ivi-task-token";
}

export interface DirtyCheckToken {
  readonly $$label?: "ivi-dirty-check-token";
}

export interface UnmountToken {
  readonly $$label?: "ivi-unmount-token";
}

/**
 * Task token.
 */
export const TASK_TOKEN: TaskToken = (
  process.env.NODE_ENV !== "production" ? Object.freeze({}) : /* istanbul ignore next */{}
);

/**
 * Dirty check token.
 */
export const DIRTY_CHECK_TOKEN: DirtyCheckToken = (
  process.env.NODE_ENV !== "production" ? Object.freeze({}) : /* istanbul ignore next */{}
);

/**
 * Unmount token.
 */
export const UNMOUNT_TOKEN: UnmountToken = (
  process.env.NODE_ENV !== "production" ? Object.freeze({}) : /* istanbul ignore next */{}
);

/**
 * Empty object.
 */
export const EMPTY_OBJECT = process.env.NODE_ENV !== "production" ? Object.freeze({}) : /* istanbul ignore next */{};

/**
 * Empty array.
 */
export const EMPTY_ARRAY = process.env.NODE_ENV !== "production" ? Object.freeze([]) : /* istanbul ignore next */[];


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('api', '0091_alter_check_filter_body'),
    ]

    operations = [
        migrations.AlterField(
            model_name='check',
            name='success_kw',
            field=models.CharField(blank=True, default='', max_length=200),
            preserve_default=False,
        ),
    ]


text:
from rest_framework.permissions import AllowAny, IsAuthenticated
# from rest_framework.response import Response
# from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_201_CREATED, HTTP_200_OK
# from rest_framework.views import APIView
#
# from .serializers import *
# from django.contrib.auth import authenticate, login
#
#
# class CreateUserView(CreateAPIView):
#     model = User
#     permission_classes = [AllowAny]
#     serializer_class = UserSerializer
#
#     def create(self, request, *args, **kwargs):
#         user_serializer = self.get_serializer(data=request.data)
#         if user_serializer.is_valid(raise_exception=True):
#             user_serializer.save()
#             return Response(user_serializer.data, status=HTTP_201_CREATED)
#         else:
#             return Response(user_serializer.errors, status=HTTP_400_BAD_REQUEST)
#
#
# class CreateOwnerView(CreateAPIView):
#     model = Owner
#     serializer_class = OwnerSerializer
#     permission_classes = [IsAuthenticated]
#
#
# class LoginAPIView(APIView):
#     permission_classes = (AllowAny, )
#     serializer_class = LoginSerializer
#
#     def post(self, request):
#         serializer = LoginSerializer(data=request.data)
#         if serializer.is_valid(raise_exception=True):
#             user = User.objects.get(email=request.data['username'])
#             user = authenticate(request, username=user.id, password=request.data['password'])
#             login(request, user)
#             return Response(serializer.data, status=HTTP_200_OK)
#         return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

from django.conf import settings
from django.contrib.auth import authenticate, login, get_user_model
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response

from account.models.user import PhoneToken
from .serializers import (
    PhoneTokenCreateSerializer, PhoneTokenValidateSerializer, EmailValidateSerializer
)

User = get_user_model()

class GenerateToken(CreateAPIView):
    model = PhoneToken
    permission_classes = [AllowAny]
    serializer_class = PhoneTokenCreateSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(
            data=request.data,
            context={'request': request}
        )
        if serializer.is_valid():
            token = PhoneToken.create_token_for_number(
                request.data.get('phone_number')
            )

            if token:
                phone_token = self.serializer_class(
                    token, context={'request': request}
                )
                return Response(phone_token.data)
            return Response({
                'reason': "you can not have more than {n} attempts per day, please try again tomorrow".format(
                    n=getattr(settings, 'PHONE_LOGIN_ATTEMPTS', 10))}, status=status.HTTP_403_FORBIDDEN)
        return Response(
            {'reason': serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE)

class ValidateToken(CreateAPIView):
    model = PhoneToken
    permission_classes = [AllowAny]
    serializer_class = PhoneTokenValidateSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(
            data=request.data, context={'request': request}
        )
        if serializer.is_valid():
            phone_number = request.data.get('phone_number')
            token = request.data.get('token')
            try:
                user = authenticate(email_or_phone=phone_number, token=token)
                login(request, user)
                response = {
                    "phone_number": user.phone,
                    "status": status.HTTP_200_OK
                }
                return Response(response, status=status.HTTP_200_OK)
            except ObjectDoesNotExist:
                return Response(
                    {'reason': 'Token doesn\'t exist'},
                    status=status.HTTP_406_NOT_ACCEPTABLE
                )
        return Response(
            {'reason': serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE
        )

class EmailSignIn(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = EmailValidateSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(
            data=request.data, context={'request': request}
        )
        if serializer.is_valid():
            email = request.data.get('email')
            password = request.data.get('password')
            user = authenticate(email_or_phone=email, password=password)
            if user:
                login(request, user)
                response = {
                    'email': user.email,
                    'status': status.HTTP_200_OK
                }
                return Response(response, status=status.HTTP_200_OK)
            return Response(
                {'reason': 'User doesn\'t exist'},
                status=status.HTTP_406_NOT_ACCEPTABLE
            )
        return Response(
            {'reason': serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE
        )

class EmailSignUp(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = EmailValidateSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(
            data=request.data, context={'request': request}
        )
        if serializer.is_valid():
            email = request.data.get('email')
            password = request.data.get('password')
            user = User.objects.create(username=email)
            user.set_password(password)
            user.save()
            response = {
                'email': user.email,
            }
            return Response(response, status=status.HTTP_201_CREATED)
        else:
            return Response(
                {'reason': serializer.errors}, status=status.HTTP_406_NOT_ACCEPTABLE
            )


text:
using MusicMinkAppLayer.Tables;

namespace MusicMinkAppLayer.Models
{
    /// <summary>
    /// Model for PlayQueueEntry entries
    /// </summary>
    public class PlayQueueEntryModel : BaseModel<PlayQueueEntryTable>
    {
        public static class Properties
        {
            public const string RowId = "RowId";

            public const string SongId = "SongId";
            public const string NextId = "NextId";
            public const string PrevId = "PrevId";
        }

        public PlayQueueEntryModel(PlayQueueEntryTable table)
            : base(table)
        {

        }

        public int RowId
        {
            get
            {
                return GetTableField<int>(PlayQueueEntryTable.Properties.RowId);
            }
        }

        public int SongId
        {
            get
            {
                return GetTableField<int>(PlayQueueEntryTable.Properties.SongId);
            }
            set
            {
                SetTableField<int>(PlayQueueEntryTable.Properties.SongId, value, Properties.SongId);
            }
        }

        public int NextId
        {
            get
            {
                return GetTableField<int>(PlayQueueEntryTable.Properties.NextId);
            }
            set
            {
                SetTableField<int>(PlayQueueEntryTable.Properties.NextId, value, Properties.NextId);
            }
        }

        public int PrevId
        {
            get
            {
                return GetTableField<int>(PlayQueueEntryTable.Properties.PrevId);
            }
            set
            {
                SetTableField<int>(PlayQueueEntryTable.Properties.PrevId, value, Properties.PrevId);
            }
        }
    }
}


text:
typedef NS_ENUM(NSUInteger, IFTTTMaskSwipeDirection)
{
    IFTTTMaskSwipeFromTop,
    IFTTTMaskSwipeFromLeft,
    IFTTTMaskSwipeFromBottom,
    IFTTTMaskSwipeFromRight
};

@interface IFTTTMaskAnimation : IFTTTAnimation <IFTTTAnimatable>

- (instancetype)initWithView:(UIView *)view direction:(IFTTTMaskSwipeDirection)direction;
+ (instancetype)animationWithView:(UIView *)view direction:(IFTTTMaskSwipeDirection)direction;

- (void)addKeyframeForTime:(CGFloat)time visibility:(CGFloat)percent;
- (void)addKeyframeForTime:(CGFloat)time visibility:(CGFloat)percent withEasingFunction:(IFTTTEasingFunction)easingFunction;

@end


text:
import { CONST_EXPR, isPresent, isBlank, BaseException } from 'angular2/src/facade/lang';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import { DehydratedException, ExpressionChangedAfterItHasBeenCheckedException } from './exceptions';
import { WrappedValue } from './pipes/pipe';
import { CHECK_ALWAYS, CHECK_ONCE, ON_PUSH } from './constants';
export class SimpleChange {
    constructor(previousValue, currentValue) {
        this.previousValue = previousValue;
        this.currentValue = currentValue;
    }
    isFirstChange() { return this.previousValue === ChangeDetectionUtil.uninitialized; }
}
var _simpleChangesIndex = 0;
var _simpleChanges = [
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null),
    new SimpleChange(null, null)
];
function _simpleChange(previousValue, currentValue) {
    var index = _simpleChangesIndex++ % 20;
    var s = _simpleChanges[index];
    s.previousValue = previousValue;
    s.currentValue = currentValue;
    return s;
}
/* tslint:disable:requireParameterType */
export class ChangeDetectionUtil {
    static arrayFn0() { return []; }
    static arrayFn1(a1) { return [a1]; }
    static arrayFn2(a1, a2) { return [a1, a2]; }
    static arrayFn3(a1, a2, a3) { return [a1, a2, a3]; }
    static arrayFn4(a1, a2, a3, a4) { return [a1, a2, a3, a4]; }
    static arrayFn5(a1, a2, a3, a4, a5) { return [a1, a2, a3, a4, a5]; }
    static arrayFn6(a1, a2, a3, a4, a5, a6) { return [a1, a2, a3, a4, a5, a6]; }
    static arrayFn7(a1, a2, a3, a4, a5, a6, a7) { return [a1, a2, a3, a4, a5, a6, a7]; }
    static arrayFn8(a1, a2, a3, a4, a5, a6, a7, a8) {
        return [a1, a2, a3, a4, a5, a6, a7, a8];
    }
    static arrayFn9(a1, a2, a3, a4, a5, a6, a7, a8, a9) {
        return [a1, a2, a3, a4, a5, a6, a7, a8, a9];
    }
    static operation_negate(value) { return !value; }
    static operation_add(left, right) { return left + right; }
    static operation_subtract(left, right) { return left - right; }
    static operation_multiply(left, right) { return left * right; }
    static operation_divide(left, right) { return left / right; }
    static operation_remainder(left, right) { return left % right; }
    static operation_equals(left, right) { return left == right; }
    static operation_not_equals(left, right) { return left != right; }
    static operation_identical(left, right) { return left === right; }
    static operation_not_identical(left, right) { return left !== right; }
    static operation_less_then(left, right) { return left < right; }
    static operation_greater_then(left, right) { return left > right; }
    static operation_less_or_equals_then(left, right) { return left <= right; }
    static operation_greater_or_equals_then(left, right) { return left >= right; }
    static operation_logical_and(left, right) { return left && right; }
    static operation_logical_or(left, right) { return left || right; }
    static cond(cond, trueVal, falseVal) { return cond ? trueVal : falseVal; }
    static mapFn(keys) {
        function buildMap(values) {
            var res = StringMapWrapper.create();
            for (var i = 0; i < keys.length; ++i) {
                StringMapWrapper.set(res, keys[i], values[i]);
            }
            return res;
        }
        switch (keys.length) {
            case 0:
                return () => [];
            case 1:
                return (a1) => buildMap([a1]);
            case 2:
                return (a1, a2) => buildMap([a1, a2]);
            case 3:
                return (a1, a2, a3) => buildMap([a1, a2, a3]);
            case 4:
                return (a1, a2, a3, a4) => buildMap([a1, a2, a3, a4]);
            case 5:
                return (a1, a2, a3, a4, a5) => buildMap([a1, a2, a3, a4, a5]);
            case 6:
                return (a1, a2, a3, a4, a5, a6) => buildMap([a1, a2, a3, a4, a5, a6]);
            case 7:
                return (a1, a2, a3, a4, a5, a6, a7) => buildMap([a1, a2, a3, a4, a5, a6, a7]);
            case 8:
                return (a1, a2, a3, a4, a5, a6, a7, a8) => buildMap([a1, a2, a3, a4, a5, a6, a7, a8]);
            case 9:
                return (a1, a2, a3, a4, a5, a6, a7, a8, a9) => buildMap([a1, a2, a3, a4, a5, a6, a7, a8, a9]);
            default:
                throw new BaseException(`Does not support literal maps with more than 9 elements`);
        }
    }
    static keyedAccess(obj, args) { return obj[args[0]]; }
    static unwrapValue(value) {
        if (value instanceof WrappedValue) {
            return value.wrapped;
        }
        else {
            return value;
        }
    }
    static throwOnChange(proto, change) {
        throw new ExpressionChangedAfterItHasBeenCheckedException(proto, change, null);
    }
    static throwDehydrated() { throw new DehydratedException(); }
    static changeDetectionMode(strategy) {
        return strategy == ON_PUSH ? CHECK_ONCE : CHECK_ALWAYS;
    }
    static simpleChange(previousValue, currentValue) {
        return _simpleChange(previousValue, currentValue);
    }
    static addChange(changes, propertyName, change) {
        if (isBlank(changes)) {
            changes = {};
        }
        changes[propertyName] = change;
        return changes;
    }
    static isValueBlank(value) { return isBlank(value); }
    static s(value) { return isPresent(value) ? `${value}` : ''; }
}
ChangeDetectionUtil.uninitialized = CONST_EXPR(new Object());
//# sourceMappingURL=change_detection_util.js.map


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="pull_to_refresh_pull_label">Потяните для обновления…</string>
  <string name="pull_to_refresh_release_label">Отпустите для обновления…</string>
  <string name="pull_to_refresh_refreshing_label">Загрузка…</string>
</resources>


text:
package org.kuali.rice.kew.rule.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.engine.node.RouteNode;
import org.kuali.rice.kew.rule.web.DocumentConfigurationViewAction.PermissionForDisplay;
import org.kuali.rice.kew.rule.web.DocumentConfigurationViewAction.ResponsibilityForDisplay;
import org.kuali.rice.kim.api.role.Role;
import org.kuali.rice.kns.web.struts.form.KualiForm;

/**
 * This is a description of what this class does - kellerj don't forget to fill this in.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
public class DocumentConfigurationViewForm extends KualiForm {

	private static final long serialVersionUID = -6251534168125209176L;

	protected String documentTypeName;
	protected DocumentType documentType;
	protected DocumentType parentDocumentType;
	protected List<DocumentType> childDocumentTypes;
//    protected List<KimPermissionInfo> permissions = null;
    protected List<String> docTypeHierarchyList = new ArrayList<String>();
    protected LinkedHashMap<String,List<PermissionForDisplay>> permissionsByDocumentType = new LinkedHashMap<String, List<PermissionForDisplay>>();
    protected Map<String,List<Role>> permissionRoles = new HashMap<String, List<Role>>();
    protected Map<String,String> attributeLabels;
    protected List<RouteNode> routeNodes;
    protected Map<String,List<ResponsibilityForDisplay>> responsibilityMap;
    protected Map<String,List<Role>> responsibilityRoles;
    protected List<ResponsibilityForDisplay> exceptionResponsibilities;
    protected boolean canInitiateDocumentTypeDocument = false;
    protected boolean canInitiatePermissionDocument = false;
    protected boolean canInitiateResponsibilityDocument = false;

	public Map<String, List<Role>> getPermissionRoles() {
		return this.permissionRoles;
	}

	public void setPermissionRoles(Map<String, List<Role>> permissionRoles) {
		this.permissionRoles = permissionRoles;
	}

	public String getDocumentTypeName() {
		return this.documentTypeName;
	}

	public void setDocumentTypeName(String documentTypeName) {
		this.documentTypeName = documentTypeName;
	}

	public DocumentType getDocumentType() {
		return this.documentType;
	}

	public void setDocumentType(DocumentType documentType) {
		this.documentType = documentType;
	}

	public DocumentType getParentDocumentType() {
		return this.parentDocumentType;
	}

	public void setParentDocumentType(DocumentType parentDocumentType) {
		this.parentDocumentType = parentDocumentType;
	}

	public List<DocumentType> getChildDocumentTypes() {
		return this.childDocumentTypes;
	}

	public void setChildDocumentTypes(List<DocumentType> childDocumentTypes) {
		this.childDocumentTypes = childDocumentTypes;
	}

	public Map<String, String> getAttributeLabels() {
		return this.attributeLabels;
	}

	public void setAttributeLabels(Map<String, String> attributeLabels) {
		this.attributeLabels = attributeLabels;
	}

	public List<RouteNode> getRouteNodes() {
		return this.routeNodes;
	}

	public void setRouteNodes(List<RouteNode> routeNodes) {
		this.routeNodes = routeNodes;
	}

	public Map<String, List<ResponsibilityForDisplay>> getResponsibilityMap() {
		return this.responsibilityMap;
	}

	public void setResponsibilityMap(
			Map<String, List<ResponsibilityForDisplay>> responsibilityMap) {
		this.responsibilityMap = responsibilityMap;
	}

	public List<String> getDocTypeHierarchyList() {
		return this.docTypeHierarchyList;
	}

	public void setDocTypeHierarchyList(List<String> docTypeHierarchyList) {
		this.docTypeHierarchyList = docTypeHierarchyList;
	}

	public LinkedHashMap<String, List<PermissionForDisplay>> getPermissionsByDocumentType() {
		return this.permissionsByDocumentType;
	}

	public void setPermissionsByDocumentType(
			LinkedHashMap<String, List<PermissionForDisplay>> permissionsByDocumentType) {
		this.permissionsByDocumentType = permissionsByDocumentType;
	}

	public void addDocumentType( String documentTypeName ) {
		docTypeHierarchyList.add(documentTypeName);
	}

	public void setPermissionsForDocumentType( String documentTypeName, List<PermissionForDisplay> perms ) {
		permissionsByDocumentType.put(documentTypeName, perms);
	}

	public boolean isCanInitiateDocumentTypeDocument() {
		return this.canInitiateDocumentTypeDocument;
	}

	public void setCanInitiateDocumentTypeDocument(
			boolean canInitiateDocumentTypeDocument) {
		this.canInitiateDocumentTypeDocument = canInitiateDocumentTypeDocument;
	}

	public Map<String, List<Role>> getResponsibilityRoles() {
		return this.responsibilityRoles;
	}

	public void setResponsibilityRoles(
			Map<String, List<Role>> responsibilityRoles) {
		this.responsibilityRoles = responsibilityRoles;
	}

	public boolean isCanInitiatePermissionDocument() {
		return this.canInitiatePermissionDocument;
	}

	public void setCanInitiatePermissionDocument(
			boolean canInitiatePermissionDocument) {
		this.canInitiatePermissionDocument = canInitiatePermissionDocument;
	}

	public boolean isCanInitiateResponsibilityDocument() {
		return this.canInitiateResponsibilityDocument;
	}

	public void setCanInitiateResponsibilityDocument(
			boolean canInitiateResponsibilityDocument) {
		this.canInitiateResponsibilityDocument = canInitiateResponsibilityDocument;
	}

	/**
	 * @return the exceptionResponsibilities
	 */
	public List<ResponsibilityForDisplay> getExceptionResponsibilities() {
		return this.exceptionResponsibilities;
	}

	/**
	 * @param exceptionResponsibilities the exceptionResponsibilities to set
	 */
	public void setExceptionResponsibilities(
			List<ResponsibilityForDisplay> exceptionResponsibilities) {
		this.exceptionResponsibilities = exceptionResponsibilities;
	}

}


text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<title>{{page.title}}</title>

		<link rel="stylesheet" href="{{site.baseurl}}/reveal.js/css/reveal.css">
		<link rel="stylesheet" href="{{site.baseurl}}/reveal.js/css/theme/black.css">

		<link rel="stylesheet" href="{{site.baseurl}}/reveal.js/lib/css/zenburn.css">


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.study.upload_async.MainActivity">

    <EditText
        android:id="@+id/et_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="请输入要上传的文件的路径" />

    <Button
        android:id="@+id/btn_upload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上传"/>
</LinearLayout>


text:
<?php
namespace OpenDNS\MES\Trident;

/**
 * Pre-Authorize a transaction.
 *
 * Confirms that funds are available and reserves them for a short time. Must
 * be captured if you want to keep the money.
 */
class PreAuthorization extends CardTransaction
{
    /** @var string Transaction type to send in the request */
    protected $transactionType = 'P';

    /**
     * Sets the flag to store this card number for future use.
     *
     * If true, the card will be stored and a card_id will be returned. If false,
     * it won't.
     *
     * @param bool $enable
     * @return self The current class instance for chaining
     */
    public function setStoreCard($enable)
    {
        $this->setField('store_card', $enable ? 'y' : 'n');
    }
}


text:
package web.services;

import java.util.List;
import persistence.models.Country;

/**
 * @author sergio
 */
public interface CountryService {
    List<Country> getAll();
}


text:
'use strict';

CloudApp.controller('VolumeController', function ($rootScope, $scope, $filter, $interval, $modal, $i18next, $timeout, ngTableParams, status_desc, Volume, Instance, CommonHttpService, ToastrService) {
    $scope.$on('$viewContentLoaded', function () {
        Metronic.initAjax();
    });

    $rootScope.settings.layout.pageBodySolid = true;
    $rootScope.settings.layout.pageSidebarClosed = false;

    $scope.status_desc = status_desc;
    $scope.current_volume_data = [];

    $scope.volume_table = new ngTableParams({
        page: 1,
        count: 10
    }, {
        counts: [],
        getData: function ($defer, params) {
            Volume.query(function (data) {
                var data_list = params.sorting() ?
                    $filter('orderBy')(data, params.orderBy()) : data;
                params.total(data_list.length);
                $scope.current_volume_data = data_list.slice((params.page() - 1) * params.count(), params.page() * params.count());
                $defer.resolve($scope.current_volume_data);
            });
        }
    });
    //定时处理硬盘状态
    var timer = $interval(function () {
        var list = $scope.current_volume_data;
        var need_refresh = false;
        for (var i = 0; i < list.length; i++) {
            if (status_desc[list[i].status][1] == 0) {
                need_refresh = true;
                break;
            }
        }
        if (need_refresh) {
            $scope.volume_table.reload();
        }

    }, 5000);
    $rootScope.timer_list.push(timer);
    /////////////////////////
    $scope.checkboxes = {'checked': false, items: {}};

    // watch for check all checkbox
    $scope.$watch('checkboxes.checked', function (value) {
        angular.forEach($scope.current_volume_data, function (item) {
            if($scope.status_desc[item.status][1]==1){
                if (angular.isDefined(item.id)) {
                    $scope.checkboxes.items[item.id] = value;
                }
            }
        });
    });

    // watch for data checkboxes
    $scope.$watch('checkboxes.items', function (values) {
        $scope.checked_count = 0;
        if (!$scope.current_volume_data) {
            return;
        }
        var checked = 0, unchecked = 0,
            total = $scope.current_volume_data.length;

        angular.forEach($scope.current_volume_data, function (item) {
            if($scope.status_desc[item.status][1]==0){
                $scope.checkboxes.items[item.id] = false;
            }
            checked += ($scope.checkboxes.items[item.id]) || 0;
            unchecked += (!$scope.checkboxes.items[item.id]) || 0;
        });
        if ((unchecked == 0) || (checked == 0)) {
            $scope.checkboxes.checked = ((checked == total) && total != 0);
        }

        $scope.checked_count = checked;
        // grayed checkbox
        angular.element(document.getElementById("select_all")).prop("indeterminate", (checked != 0 && unchecked != 0));
    }, true);
    ////////////////////////

    /*创建云硬盘弹出窗口*/
    $scope.modal_create_volume = function () {
        //云硬盘元数据定义
        $scope.volume = {
            "count": 1,
            "size": 10
        };
        var modalVolume = $modal.open({
            templateUrl: 'create_volume.html',
            controller: 'VolumeCreateController',
            backdrop: "static",
            scope: $scope,
            resolve: {
                volume_table: function () {
                    return $scope.volume_table;
                },
                quota: function (CommonHttpService) {
                    return CommonHttpService.get("/api/account/quota/");
                }
            }
        });
        modalVolume.result.then(function (result) {
        }, function (result) {
        });
    }
    /*修改云硬盘弹出窗口*/
    $scope.modal_update_volume = function (volume) {
        $scope.volume = {
            "id": volume.id,
            "name": volume.name
        };
        console.log($scope.volume)
        var modalVolume = $modal.open({
            templateUrl: 'update_volume.html',
            controller: 'VolumeCreateController',
            backdrop: "static",
            scope: $scope,
            resolve: {
                volume_table: function () {
                    return $scope.volume_table;
                },
                quota: function (CommonHttpService) {
                    return CommonHttpService.get("/api/account/quota/");
                }
            }
        });
        modalVolume.result.then(function (result) {
        }, function (result) {
        });
    }
    /*挂载云硬盘弹出窗口*/
    $scope.modal_attach_to_instance = function (volume) {
        CommonHttpService.get("/api/instances/search/").then(function (data) {
            $scope.instances = data;
        });
        $scope.volume = volume;
        var modalVolume = $modal.open({
            templateUrl: 'instance.html',
            controller: 'VolumeAttachController',
            backdrop: "static",
            scope: $scope,
            resolve: {

                operation_tip: function () {
                    return "";
                },
                volume_table: function () {
                    return $scope.volume_table;
                }
            }
        });
        modalVolume.result.then(function (result) {
        }, function (result) {
        });
    }
    /*卸载云硬盘弹出窗口*/
    $scope.modal_detach_from_instance = function (volume) {
        $scope.volume = volume;
        var modalVolume = $modal.open({
            templateUrl: 'detach.html',
            controller: 'VolumeAttachController',
            backdrop: "static",
            scope: $scope,
            resolve: {
                operation_tip: function () {
                    return $i18next("volume.detach_tip_start") + "ssssssssssssss" + $i18next("volume.detach_tip_end");
                },
                instances: function () {
                    return "";
                },
                volume_table: function () {
                    return $scope.volume_table;
                }
            }
        });
        modalVolume.result.then(function (result) {
        }, function (result) {
        });
    }
    var post_action = function (vol, action) {
        var post_data = {
            "action": action,
            "volume_id": vol.id
        }
        CommonHttpService.post("/api/volumes/action/", post_data).then(function (data) {
            if (data.OPERATION_STATUS == 1) {
                $scope.volume_table.reload();
            }
            else {
                ToastrService.error(data.MSG, $i18next("op_failed"));
            }
        });
    };
    //批量操作 delete
    $scope.batch_action = function (action) {
        bootbox.confirm($i18next("volume.confirm_" + action), function (confirm) {
            if (confirm) {
                var items = $scope.checkboxes.items;
                var items_key = Object.keys(items);
                for (var i = 0; i < items_key.length; i++) {
                    if (items[items_key[i]]) {
                        post_action({"id": items_key[i]}, action);
                        $scope.checkboxes.items[items_key[i]] = false;
                    }
                }
            }
        });
    }
});
/*云硬盘创建类*/
CloudApp.controller('VolumeCreateController',
    function ($rootScope, $scope, $sce, $modalInstance, $i18next, CommonHttpService, ToastrService, volume_table, quota) {
        $scope.quota = quota;

        $scope.calcuate_resource_persent = function (resource) {
            if (quota[resource] <= 0) {
                return 0;
            }
            else {
                if(resource == "volume")
                    return (quota[resource + "_used"] + 1 ) / quota[resource] * 100;

                if(resource == "volume_size")
                    return (quota[resource + "_used"] + $scope.volume.size ) / quota[resource] * 100;

            }
        };
        $scope.resource_persent = function(resource){
            return $scope.calcuate_resource_persent(resource) + "%";
        }

        $scope.check_can_submit = function(){
            if(quota.volume <= 0 && quota.volume_size <= 0){
                return false;
            }
            else{
                var quota_volume_overlimt = false;
                var quota_volume_size_overlimt = false;

                if(quota.volume > 0)
                    quota_volume_overlimt = quota.volume_used + 1 > quota.volume;

                if(quota.volume_size > 0)
                    quota_volume_size_overlimt = quota.volume_size_used + $scope.volume.size > quota.volume_size;

                return quota_volume_overlimt || quota_volume_size_overlimt;
            }
        };
        //定义表单是否有错
        $scope.has_error = false;
        //监听model变化情况
        $scope.$watch('volume.name', function () {
            $scope.has_error = false;
        });
        //关闭窗口方法
        $scope.cancel = function () {
            $modalInstance.dismiss();
        };
        //控制表单重复提交
        $scope.flag = true;
        //提交方法
        $scope.volume_submit = function (volume, type) {
            if (typeof(volume.name) === 'undefined' || volume.name == "") {
                $scope.has_error = true;
                return false;
            }
            if(!$scope.flag){
                return
            }
            $scope.flag = false;
            if ("create" === type) {
                var post_data = {
                    "name": volume.name,
                    "size": volume.size
                }
                CommonHttpService.post("/api/volumes/create/", post_data).then(function (data) {
                    if (data.OPERATION_STATUS == 1) {
                        ToastrService.success(data.MSG, $i18next("success"));
                    }
                    else {
                        ToastrService.error(data.MSG, $i18next("op_failed"));
                    }
                    volume_table.reload();
                    $modalInstance.dismiss();
                });
            } else if ("update" === type) {

                var post_data = {
                    "id": volume.id,
                    "name": volume.name
                }
                CommonHttpService.post("/api/volumes/update/", post_data).then(function (data) {
                    if (data.OPERATION_STATUS == 1) {
                        ToastrService.success(data.MSG, $i18next("success"));
                    }
                    else {
                        ToastrService.error(data.MSG, $i18next("op_failed"));
                    }
                    volume_table.reload();
                    $modalInstance.dismiss();
                });
            }
        }
    });
/*云硬盘挂载controller*/
CloudApp.controller('VolumeAttachController', function ($rootScope, $scope, $sce, $modalInstance, $i18next, CommonHttpService, ToastrService, operation_tip, volume_table) {
    //定义表单是否有错
    $scope.has_error = false;
    $scope.selected_instance = false;
    //卸载云主机提示 卸载操作使用
    $scope.operation_tip = operation_tip;

    //关闭窗口方法
    $scope.cancel = function () {
        $modalInstance.dismiss();
    };
    $scope.flag = true;
    //挂载方法
    $scope.attach_or_detach = function (selected_instance, action) {
        if ((action == "attach" && selected_instance) || action=='detach') {
            if(!$scope.flag){
                return
            }
            $scope.flag = false;
            var post_data = {
                "volume_id": $scope.volume.id,
                "instance_id": selected_instance.id,
                "action": action
            }
            CommonHttpService.post("/api/volumes/action/", post_data).then(function (data) {
                if (data.OPERATION_STATUS == 1) {
                    ToastrService.success(data.MSG, $i18next("success"));
                    volume_table.reload();
                }
                else {
                    ToastrService.error(data.MSG, $i18next("op_failed"));
                }
                $modalInstance.dismiss();
            });
        } else {
            $scope.has_error = true;
        }

    };

});

CloudApp.directive("slider", [function () {
    return {
        restrict: 'E',
        templateUrl: 'slider.html',
        scope: {
            data: "=data"
        },
        link: function (scope, el, attrs, ctrl) {
            $(el).find("#slider-range-max").slider({
                isRTL: false,
                range: "max",
                min: 10,
                step: 10,
                max: 1000,
                value: 1,
                slide: function (event, ui) {
                    scope.data.size = ui.value;
                    scope.$apply();
                }
            });
        }
    };
}]);


text:
from collections import defaultdict
import subprocess
import sys, os, time
import tempfile
from ..util.prompt import prompt

class PrimerAlign(object):
    def __init__(self, template, seq, mismatch, offset):
        self.template = template
        self.origin = seq
        self.mismatch = mismatch
        self.offset = offset

class PCRFragment(object):
    def __init__(self, template, fw, rv):
        self.template = template
        self.fw = fw
        self.rv = rv

    def __len__(self):
        return self.rv.offset - self.fw.offset + len(self.rv.origin)

def virtualpcr(template, seqstrs, bowtie_path, threshold=None):
    '''
    bowtie manual: http://bowtie-bio.sourceforge.net/manual.shtml
    parser for default bowtie output
    '''

    stdout = tempfile.TemporaryFile()
    stderr = tempfile.TemporaryFile()
    command = '%s %s -c %s' %(os.path.abspath(bowtie_path), template, ','.join(seqstrs))
    try:
        print(command)
        # note. using subprocess.PIPE with p.wait() dead locks if output is large.
        p = subprocess.Popen(command, stdout=stdout, stderr=stderr, shell=True)
        with prompt('waiting for bowtie.') as pr:
            while p.poll() is None:
                pr.progress()
                time.sleep(1)
        retcode = p.wait()
        if retcode < 0:
            print('bowtie exist with return code ', retcode, '  command:', command, file=sys.stderr)
            return None
    except OSError as e:
        print("failed to invoke bowtie. command: ", command, ' error=', e, file=sys.stderr)
        return None

    stdout.seek(0)
    stderr.seek(0)

    # matched-align list for each template(chromosome). positive means forward strand match.
    matches_positive = defaultdict(list)
    matches_negative = defaultdict(list)

    primer_full_count = defaultdict(int)
    primer_miss_count = defaultdict(int)

    for l in stdout:
        '''see http://bowtie-bio.sourceforge.net/manual.shtml#default-bowtie-output for output format. '''
        r = [c.strip() for c in l.split()]
        assert( int(r[0]) in [0,1] )

        primer_i = int(r[0])
        primer = seqstrs[primer_i]
        direction = r[1]
        template = r[2]
        offset = int(r[3])
        try:
            difference = r[7]
        except:
            difference = None

        if difference:
            primer_miss_count[primer_i] += 1
        else:
            primer_full_count[primer_i] += 1

        align = PrimerAlign(template, primer, difference, offset)
        if direction == b'+':
            matches_positive[template].append(align)
        else:
            matches_negative[template].append(align)

    print('primer statistics')
    for i,p in enumerate(seqstrs):
        print('primer %s:' % p)
        print(' full match = %4d' % primer_full_count[i])
        print(' miss match = %4d' % primer_miss_count[i])

    for v in matches_positive.values():
        v.sort(key=lambda x:x.offset)
    for v in matches_negative.values():
        v.sort(key=lambda x:x.offset)

    templates = set(matches_positive.keys()) & set(matches_negative.keys())

    def pcr_pair(pl, nl):
        if len(pl) < 1 or len(nl) < 1:
            return
        p = 0
        n = 0
        while p < len(pl):
            while not pl[p].offset <= nl[n].offset:
                n += 1
                if not (n < len(nl)):
                    return
            while p+1 < len(pl) and pl[p+1].offset <= nl[n].offset:
                p += 1
            if not threshold or nl[n].offset-pl[p].offset < threshold:
                yield pl[p], nl[n]
            p += 1

    result = []

    for t in templates:
        pl = matches_positive[t]
        nl = matches_negative[t]
        for p,n in pcr_pair(pl, nl):
            result.append(PCRFragment(t, p, n))

    return result

def main():
    import os
    from optparse import OptionParser

    parser = OptionParser('usage: %prog [options] primer_sequence ...')
    parser.add_option("-t",'--template', dest='template', help="name of indexes of template", default=None)
    parser.add_option('-b', '--bisulfite', dest='bisulfite', action='store_true', default=False)
    parser.add_option('-l', '--length', dest='length', type=int, default=-1)

    (options, primers) = parser.parse_args()

    if len(primers) == 0:
        parser.error("no sequence input")

    if options.bisulfite and options.template:
        parser.error('bisulfite option and template option are exclusive.')

    length = options.length if options.length > 0 else None

    def s(template):
        '''
        -p 2 : number of thread
        --best : matches are ordered on number of mismatches.
        -k 1000 : maximum number of matches.
        -n 2 : allowed number of mismatches per primer.
        '''
        bowtie_path = os.path.expanduser('~/work/bowtie-1.0.0/bowtie -p 2 --best -k 1000 -n 3')
        #bowtie_path = os.path.expanduser('~/work/bowtie-0.12.7/bowtie -p 2 --best -k 1000 -n 2')

        result = virtualpcr(template, primers, bowtie_path, length)
        if result:
            for r in result:
                print('match at %s length=%10d %s(%s) -> %s(%s)' %(str(r.template).ljust(10), len(r), r.fw.origin,r.fw.mismatch, r.rv.origin,r.rv.mismatch))
        else:
            print('no result')

    if options.template:
        s(options.template)
    elif options.bisulfite:
        print('METHYL')
        s('bs_pos_met')
        s('bs_neg_met')
        print('UNMETHYL')
        s('bs_pos_unm')
        s('bs_neg_unm')
    else:
        parser.error('no template specified.')

if __name__=='__main__':
    main()


text:
module TrustyCms::AvailableLocales
  # Returns the list of available locale files in options_for_select format.
  #
  def self.locales
    available_locales = {}
    TrustyCms.configuration.i18n.load_path.each do |path|
      if File.exists?(path) && path !~ /_available_tags/
        locale_yaml = YAML.load_file(path)
        stem = File.basename(path, '.yml')
        if locale_yaml[stem] && lang = locale_yaml[stem]['this_file_language']
          available_locales[lang] = stem
        end
      end
    end
    available_locales.collect { |k, v| [k, v] }.sort_by { |s| s[0] }
  end
end


text:
using Umbraco.Cms.Infrastructure.Persistence;

namespace Umbraco.Cms.Persistence.Sqlite.Mappers;

public class SqliteGuidScalarMapper : ScalarMapper<Guid>
{
    protected override Guid Map(object value)
        => Guid.Parse($"{value}");
}

public class SqliteNullableGuidScalarMapper : ScalarMapper<Guid?>
{
    protected override Guid? Map(object? value)
    {
        if (value is null || value == DBNull.Value)
        {
            return default;
        }

        return Guid.TryParse($"{value}", out Guid result)
            ? result
            : default(Guid?);
    }
}


text:
package com.squareup.wire;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import com.squareup.wire.java.JavaGenerator;
import com.squareup.wire.schema.EnumType;
import com.squareup.wire.schema.Location;
import com.squareup.wire.schema.MessageType;
import com.squareup.wire.schema.ProtoFile;
import com.squareup.wire.schema.Schema;
import com.squareup.wire.schema.SchemaLoader;
import com.squareup.wire.schema.Type;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/** Compiler for Wire protocol buffers. */
public final class WireCompiler {
  private static final String CODE_GENERATED_BY_WIRE =
      "Code generated by Wire protocol buffer compiler, do not edit.";

  private final FileSystem fs;
  private final CommandLineOptions options;
  private final WireLogger log;

  /**
   * Runs the compiler.  See {@link CommandLineOptions} for command line options.
   */
  public static void main(String... args) throws IOException {
    try {
      WireCompiler.create(new CommandLineOptions(args)).compile();
    } catch (WireException e) {
      System.err.print("Fatal: ");
      e.printStackTrace(System.err);
      System.exit(1);
    }
  }

  static WireCompiler create(CommandLineOptions options) throws WireException {
    return new WireCompiler(options, FileSystems.getDefault(),
        new ConsoleWireLogger(options.quiet));
  }

  WireCompiler(CommandLineOptions options, FileSystem fs, WireLogger logger) throws WireException {
    this.options = options;
    this.fs = fs;
    this.log = logger;

    if (options.javaOut == null) {
      throw new WireException("Must specify " + CommandLineOptions.JAVA_OUT_FLAG + " flag");
    }
  }

  public void compile() throws IOException {
    SchemaLoader schemaLoader = new SchemaLoader();
    for (String protoPath : options.protoPaths) {
      schemaLoader.addSource(fs.getPath(protoPath));
    }
    for (String sourceFileName : options.sourceFileNames) {
      schemaLoader.addProto(sourceFileName);
    }
    Schema schema = schemaLoader.load();

    if (!options.roots.isEmpty()) {
      log.info("Analyzing dependencies of root types.");
      schema = schema.retainRoots(options.roots);
    }

    JavaGenerator javaGenerator = JavaGenerator.get(schema)
        .withOptions(options.emitOptions, options.enumOptions)
        .withAndroid(options.emitAndroid)
        .withCompact(options.emitCompact);

    for (ProtoFile protoFile : schema.protoFiles()) {
      if (!options.sourceFileNames.contains(protoFile.location().path())) {
        continue; // Don't emit anything for files not explicitly compiled.
      }

      for (Type type : protoFile.types()) {
        ClassName javaTypeName = (ClassName) javaGenerator.typeName(type.name());
        TypeSpec typeSpec = type instanceof MessageType
            ? javaGenerator.generateMessage((MessageType) type)
            : javaGenerator.generateEnum((EnumType) type);
        writeJavaFile(javaTypeName, typeSpec, type.location());
      }
    }
  }

  private void writeJavaFile(ClassName javaTypeName, TypeSpec typeSpec, Location location)
      throws IOException {
    JavaFile.Builder builder = JavaFile.builder(javaTypeName.packageName(), typeSpec)
        .addFileComment("$L", CODE_GENERATED_BY_WIRE);
    if (location != null) {
      builder.addFileComment("\nSource file: $L", location);
    }
    JavaFile javaFile = builder.build();

    Path path = fs.getPath(options.javaOut);
    log.artifact(path, javaFile);

    try {
      if (!options.dryRun) {
        javaFile.writeTo(path);
      }
    } catch (IOException e) {
      throw new IOException("Error emitting " + javaFile.packageName + "."
          + javaFile.typeSpec.name + " to " + options.javaOut, e);
    }
  }
}


text:
layout: post
title: Netty Channel Pool
date: '2015-06-03T16:32:00-08:00'
categories: Technology
tags: Netty ChannelPool
comments: true
---
Netty released ChannelPool in their most version 4.0.28 release: http://netty.io/news/2015/05/07/4-0-28-Final.html

While trying to use the pool, I came across an issue where the Channel pipeline was not getting initialized with the ChannelInitilizer setup in the Bootstrap.

Here is my initial implementation:
{% gist 8046e804d8b58a65cf8e %}
Output:
DefaultChannelPipeline{}

After many hours of debugging found out that it is meant to be like this bt design. Here is link to the issue on Github: https://github.com/netty/netty/issues/3770

Channel Pool provides an event listener called ChannelPoolHandler to capture pool events. ChannelPoolHandler handler can be implemented to handle events such as channel creation, channel acquisition, channel release etc. Modified the above code to initialize the Channel pipeline on channel creation, which works fine.

Here is the code snippet for initializing Channel within the ChannelPoolHandler:
{% gist 522e2556d2f119e26319 %}
Output:
DefaultChannelPipeline{(ProtobufVarint32FrameDecoder#0 =
    io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder),
   (ProtobufDecoder#0 = io.netty.handler.codec.protobuf.ProtobufDecoder),
   (ProtobufVarint32LengthFieldPrepender#0 =
     io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender),
   (ProtobufEncoder#0 = io.netty.handler.codec.protobuf.ProtobufEncoder),
   (LogClientHandler#0 = com.pubmatic.ripple.client.LogClientHandler)}


text:
package koper.aop;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SendMsgBeforeInvokeAdvice. 发消息切面
 *
 * @author kk
 * @since 1.0
 */
@Aspect
public class SendMsgAfterInvokeAdvice extends AbstractSendMessageAdvice {

	private static Logger log = LoggerFactory.getLogger(SendMsgAfterInvokeAdvice.class);
	/**
	 * 方法调用后发送消息
	 * @see com.kk.AbstractSendMessageAdvice#sendMessageAfter(Method, String, Object[], Object)
	 */
	@Override
	protected void sendMessageAfter(Method method, String topic, Object[] args, Object result) {

		List<Object> argList = Arrays.asList(args);

		Map<String,Object> invokeInfoMap = new HashMap<>();
		invokeInfoMap.put("args", argList);
		invokeInfoMap.put("result", result);

		String jsonMessage = JSON.toJSONString( invokeInfoMap );

		if(log.isDebugEnabled())
			log.debug("sendMessageAfter Topic={}, jsonMessage={}" ,topic, jsonMessage);

		getMessageSender().send(topic, jsonMessage);
	}
}


text:
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Raccoon.Util;

namespace Raccoon {
    public class Polygon : IEnumerable {
        #region Private Members

        private List<Vector2> _vertices;
        private List<Vector2[]> _convexComponents = new List<Vector2[]>();
        private bool _needRecalculateComponents;

        #endregion Private Members

        #region Constructors

        public Polygon(IEnumerable<Vector2> points) {
            _vertices = new List<Vector2>(points);
            IsConvex = false;
            Normals = new Vector2[0];
            Center = Vector2.Zero;

            Verify();
        }

        public Polygon(params Vector2[] points) : this((IEnumerable<Vector2>) points) { }

        public Polygon(Polygon polygon) {
            _vertices = new List<Vector2>(polygon._vertices);

            foreach (Vector2[] component in polygon.ConvexComponents()) {
                _convexComponents.Add(component);
            }

            IsConvex = polygon.IsConvex;

            Normals = new Vector2[polygon.Normals.Length];
            polygon.Normals.CopyTo(Normals, 0);

            Center = polygon.Center;

            _needRecalculateComponents = polygon._needRecalculateComponents;
        }

        public Polygon(Triangle triangle) : this(triangle.A, triangle.B, triangle.C) {
        }

        public Polygon(Rectangle rectangle) : this(rectangle.TopLeft, rectangle.TopRight, rectangle.BottomRight, rectangle.BottomLeft) {
        }

        #endregion Constructors

        #region Public Properties

        public int VertexCount { get { return _vertices.Count; } }
        public bool IsConvex { get; private set; }
        public Vector2[] Normals { get; private set; }
        public Vector2 Center { get; private set; }
        public ReadOnlyCollection<Vector2> Vertices { get { return _vertices.AsReadOnly(); } }

        public Vector2 this [int index] {
            get {
                return _vertices[index];
            }

            set {
                _vertices[index] = value;
                Verify();
            }
        }

        #endregion Public Properties

        #region Public Static Methods

        public static Polygon RotateAround(Polygon polygon, float degrees, Vector2 origin) {
            List<Vector2> _rotatedVertices = new List<Vector2>(polygon.VertexCount);
            foreach (Vector2 vertex in polygon._vertices) {
                _rotatedVertices.Add(Math.RotateAround(vertex, origin, degrees));
            }

            return new Polygon(_rotatedVertices);
        }

        public static Polygon Rotate(Polygon polygon, float degrees) {
            return RotateAround(polygon, degrees, polygon.Center);
        }

        public static int Orientation(IList<Vector2> vertices) {
            int rMin = 0;
            Vector2 vertexMin = vertices[0];

            for (int i = 1; i < vertices.Count; i++) {
                Vector2 vertex = vertices[i];
                if (vertex.Y > vertexMin.Y) {
                    continue;
                }

                if (vertex.Y == vertexMin.Y && vertex.X > vertexMin.X) {
                    continue;
                }

                rMin = i;
                vertexMin = vertex;
            }

            return Triangle.Orientation(Helper.At(vertices, rMin - 1), Helper.At(vertices, rMin), Helper.At(vertices, rMin + 1));
        }

        public static bool IsClockwise(IList<Vector2> vertices) {
            return Orientation(vertices) > 0;
        }

        public static bool IsCounterClockwise(IList<Vector2> vertices) {
            return Orientation(vertices) < 0;
        }

        public static bool IsDegenerate(IList<Vector2> vertices) {
            return Orientation(vertices) == 0;
        }

        public static List<Vector2> ConvexHull(ICollection<Vector2> points) {
            // using jarvis (gift wrapping) algorithm
            List<Vector2> convexHull = new List<Vector2>();

            if (points.Count < 3) {
                convexHull.AddRange(points);
                return convexHull;
            }

            Vector2? firstPoint = null,
                     leftmostPoint = null;

            // find leftmostPoint
            foreach (Vector2 point in points) {
                if (firstPoint == null) {
                    firstPoint = leftmostPoint = point;
                }

                if (point.X < leftmostPoint.Value.X) {
                    leftmostPoint = point;
                }
            }

            Vector2 endPoint, pointOnHull = leftmostPoint.Value;
            do {
                convexHull.Add(pointOnHull);
                endPoint = firstPoint.Value;
                foreach (Vector2 point in points) {
                    if (endPoint == pointOnHull || Math.IsLeft(pointOnHull, endPoint, point)) {
                        endPoint = point;
                    }
                }

                pointOnHull = endPoint;
            } while (endPoint != convexHull[0]);

            return convexHull;
        }

        public static Polygon Merge(Polygon polygonA, Polygon polygonB) {
            List<Vector2> vertices = new List<Vector2>(polygonA.Vertices);
            vertices.AddRange(polygonB.Vertices);
            List<Vector2> convexHullVertices = ConvexHull(vertices);
            return new Polygon(convexHullVertices);
        }

        public static Line? FindSharedEdge(Vector2[] polygonA, Vector2[] polygonB) {
            Line? line = null;
            Vector2 edgeAPointA = polygonA[0],
                    edgeBPointA = polygonB[0];

            for (int i = 1; i < polygonA.Length; i++) {
                Vector2 edgeAPointB = polygonA[i];
                for (int j = 1; j < polygonB.Length; j++) {
                    Vector2 edgeBPointB = polygonB[i];
                    if (Helper.EqualsPermutation(edgeAPointA, edgeAPointB, edgeBPointA, edgeBPointB)) {
                        line = new Line(edgeAPointA, edgeAPointB);
                        break;
                    }
                }

                if (line != null) {
                    break;
                }
            }

            return line;
        }

        public static Line? FindSharedEdge(Polygon polygonA, Polygon polygonB) {
            return FindSharedEdge(polygonA._vertices.ToArray(), polygonB._vertices.ToArray());
        }

        #endregion Public Static Methods

        #region Public Methods

        public void AddVertex(Vector2 vertex) {
            _vertices.Add(vertex);
            Verify();
        }

        public void AddVertices(IEnumerable<Vector2> vertex) {
            _vertices.AddRange(vertex);
            Verify();
        }

        public void RemoveVertex(Vector2 vertex) {
            _vertices.Remove(vertex);
            Verify();
        }

        public void RemoveVertex(int index) {
            _vertices.RemoveAt(index);
            Verify();
        }

        public void Translate(Vector2 dist) {
            for (int i = 0; i < VertexCount; i++) {
                _vertices[i] += dist;
            }

            CalculateCentroid();
        }

        public void Translate(float x, float y) {
            Translate(new Vector2(x, y));
        }

        public void Scale(Vector2 factor, Vector2 origin) {
            for (int i = 0; i < VertexCount; i++) {
                _vertices[i] = (_vertices[i] - origin) * factor + origin;
            }

            CalculateCentroid();
        }

        public void Scale(float factor, Vector2 origin) {
            Scale(new Vector2(factor), origin);
        }

        public void Scale(Vector2 factor) {
            Scale(factor, Center);
        }

        public void Scale(float factor) {
            Scale(new Vector2(factor), Center);
        }

        public void RotateAround(float degrees, Vector2 origin) {
            if (degrees == 0) {
                return;
            }

            for (int i = 0; i < VertexCount; i++) {
                _vertices[i] = Math.RotateAround(_vertices[i], origin, degrees);
            }

            CalculateCentroid();
            CalculateNormals();
            _needRecalculateComponents = true;
        }

        public void Rotate(float degrees) {
            RotateAround(degrees, Center);
        }

        public void Reflect(Vector2 axis) {
            for (int i = 0; i < VertexCount; i++) {
                Vector2 vertex = _vertices[i];
                _vertices[i] = new Vector2(2 * axis.X - vertex.X, 2 * axis.Y - vertex.Y);
            }

            CalculateCentroid();
            CalculateNormals();
            _needRecalculateComponents = true;
        }

        public void ReflectHorizontal(float axis) {
            for (int i = 0; i < VertexCount; i++) {
                Vector2 vertex = _vertices[i];
                _vertices[i] = new Vector2(2 * axis - vertex.X, vertex.Y);
            }

            CalculateCentroid();
            CalculateNormals();
            _needRecalculateComponents = true;
        }

        public void ReflectVertical(float axis) {
            for (int i = 0; i < VertexCount; i++) {
                Vector2 vertex = _vertices[i];
                _vertices[i] = new Vector2(vertex.X, 2 * axis - vertex.Y);
            }

            CalculateCentroid();
            CalculateNormals();
            _needRecalculateComponents = true;
        }

        public Range Projection(Vector2 axis) {
            return axis.Projection(_vertices);
        }

        public Rectangle BoundingBox() {
            if (VertexCount <= 1) {
                return Rectangle.Empty;
            }

            Vector2 firstVertex = _vertices[0];

            float top = firstVertex.Y,
                  left = firstVertex.X,
                  bottom = firstVertex.Y,
                  right = firstVertex.X;

            for (int i = 1; i < VertexCount; i++) {
                Vector2 vertex = _vertices[i];

                if (vertex.X < left) {
                    left = vertex.X;
                } else if (vertex.X > right) {
                    right = vertex.X;
                }

                if (vertex.Y < top) {
                    top = vertex.Y;
                } else if (vertex.Y > bottom) {
                    bottom = vertex.Y;
                }
            }

            return new Rectangle(new Vector2(left, top), new Vector2(right, bottom));
        }

        public Vector2 ClosestPoint(Vector2 point) {
            if (IsInside(point)) {
                return point;
            }

            Vector2 closestPoint = Center;
            float closestSquaredDist = float.PositiveInfinity;
            foreach (Line edge in Edges()) {
                Vector2 p = edge.ClosestPoint(point);
                float squaredDist = Math.DistanceSquared(p, point);
                if (squaredDist < closestSquaredDist) {
                    closestPoint = p;
                    closestSquaredDist = squaredDist;
                }
            }

            return closestPoint;
        }

        public float Area() {
            if (VertexCount < 3) {
                return 0;
            }

            float area = 0;
            for (int i = 1, j = 2, k = 0; i < VertexCount; i++, j++, k++) {
                area += Helper.At(_vertices, i).X * (Helper.At(_vertices, j).Y - Helper.At(_vertices, k).Y);
            }

            area += _vertices[0].X * (_vertices[1].Y - _vertices[VertexCount - 1].Y);
            return area / 2.0f;
        }

        public float DistanceSquared(Vector2 point) {
            Vector2 closestPoint = ClosestPoint(point);
            return Vector2.Dot(closestPoint - point, closestPoint - point);
        }

        public bool IsInside(Vector2 point) {
            // ref: http://geomalgorithms.com/a03-_inclusion.html
            int windNumber = 0;
            foreach (Line edge in Edges()) {
                if (edge.PointA.Y <= point.Y) {
                    if (edge.PointB.Y > point.Y && Math.IsLeft(edge.PointA, edge.PointB, point)) {
                        ++windNumber;
                    }
                } else {
                    if (edge.PointB.Y <= point.Y && Math.IsRight(edge.PointA, edge.PointB, point)) {
                        --windNumber;
                    }
                }
            }

            return windNumber != 0;
        }

        public Vector2[] Intersects(Line segment) {
            List<Vector2> intersections = new List<Vector2>();

            foreach (Line edge in Edges()) {
                if (edge.IntersectionPoint(segment, out Vector2 intersectionPoint)) {
                    intersections.Add(intersectionPoint);
                }
            }

            return intersections.ToArray();
        }

        public List<Vector2[]> ConvexComponents() {
            if (_needRecalculateComponents) {
                _needRecalculateComponents = false;
                CalculateComponents();
            }

            return _convexComponents;
        }

        public List<Triangle> Triangulate() {
            // force counterclockwise (as it's a precondition to ear clipping algorithm)
            LinkedList<Vector2> vertices = new LinkedList<Vector2>();
            if (IsCounterClockwise(_vertices)) {
                foreach (Vector2 vertex in _vertices) {
                    vertices.AddLast(vertex);
                }
            } else {
                foreach (Vector2 vertex in _vertices) {
                    vertices.AddFirst(vertex);
                }
            }

            // triangulate using ear clipping
            List<Triangle> triangles = new List<Triangle>();
            Stack<LinkedListNode<Vector2>> ears = new Stack<LinkedListNode<Vector2>>();

            LinkedListNode<Vector2> current = vertices.First;

            while (current != null) {
                if (IsInternalDiagonal(current.PreviousOrLast(), current.NextOrFirst())) {
                    ears.Push(current);
                }

                current = current.Next;
            }

            if (ears.Count == 0) {
                // no ears found, just stop
                return triangles;
            }

            LinkedListNode<Vector2> prev2, prev, next, next2;

            while (vertices.Count > 3 && ears.Count > 0) {
                current = ears.Pop();

                if (current == null || current.List == null) {
                    continue;
                }

                prev = current.PreviousOrLast();
                prev2 = prev.PreviousOrLast();
                next = current.NextOrFirst();
                next2 = next.NextOrFirst();

                triangles.Add(new Triangle(current.Value, prev.Value, next.Value));

                if (IsInternalDiagonal(prev2, next)) {
                    ears.Push(prev);
                }

                if (IsInternalDiagonal(prev, next2)) {
                    ears.Push(next);
                }

                vertices.Remove(current);
            }

            current = vertices.First;
            triangles.Add(new Triangle(current.PreviousOrLast().Value, current.Value, current.NextOrFirst().Value));

            return triangles;
        }

        public void Merge(Triangle triangle) {
            Vector2[] triangleVertices = triangle.Vertices;
            Vector2? vertexToMerge = null;
            int i;
            for (i = 0; i < VertexCount; i++) {
                Vector2 vertex = _vertices[i],
                        nextVertex = Helper.At(_vertices, i + 1);

                for (int j = 0; j < triangleVertices.Length; j++) {
                    if (vertex == triangleVertices[j]) {
                        if (nextVertex == Helper.At(triangleVertices, j + 1)) {
                            vertexToMerge = Helper.At(triangleVertices, j + 2);
                            break;
                        } else if (nextVertex == Helper.At(triangleVertices, j + 2)) {
                            vertexToMerge = Helper.At(triangleVertices, j + 1);
                            break;
                        }
                    }
                }

                if (vertexToMerge != null) {
                    break;
                }
            }

            if (vertexToMerge != null) {
                _vertices.Insert(Helper.Index(i + 1, VertexCount), triangle.C);
                Verify();
            }
        }

        public IEnumerable<Line> Edges() {
            for (int i = 0; i < VertexCount; i++) {
                yield return new Line(_vertices[i], _vertices[(i + 1) % VertexCount]);
            }
        }

        public IEnumerator GetEnumerator() {
            return _vertices.GetEnumerator();
        }

        public override string ToString() {
            return $"[{string.Join(", ", _vertices)}]";
        }

        #endregion Public Methods

        #region Private Methods

        private void Verify() {
            if (VertexCount < 3) {
                throw new System.InvalidOperationException("Polygon must have at least 3 vertices.");
            }

            CalculateCentroid();
            CalculateConvexity();
            CalculateNormals();
            _needRecalculateComponents = true;
        }

        private void CalculateCentroid() {
            Vector2 pointsSum = Vector2.Zero;
            foreach (Vector2 vertex in _vertices) {
                pointsSum += vertex;
            }

            Center = pointsSum / VertexCount;
        }

        private void CalculateConvexity() {
            // convexity test
            IsConvex = true;

            // algorithm to determine if it's convex: http://stackoverflow.com/a/1881201
            Vector2 previous = _vertices[_vertices.Count - 1], center = _vertices[0], next = _vertices[1];
            int sign = System.Math.Sign(Triangle.SignedArea2(previous, center, next));

            previous = center;
            for (int i = 1; i < VertexCount; i++) {
                center = _vertices[i];
                next = _vertices[(i + 1) % _vertices.Count];
                if (sign != System.Math.Sign(Triangle.SignedArea2(previous, center, next))) {
                    IsConvex = false;
                    break;
                }

                previous = center;
            }
        }

        private void CalculateNormals() {
            if (Vertices.Count < 3) {
                if (Normals.Length > 0) {
                    Normals = new Vector2[0];
                }

                return;
            }

            if (Normals.Length != VertexCount) {
                Normals = new Vector2[VertexCount];
            }

            int i = 0;
            if (Math.IsLeft(Vertices[0], Vertices[1], Vertices[2])) {
                foreach (Line line in Edges()) {
                    Normals[i] = line.ToVector2().PerpendicularCCW().Normalized();
                    i++;
                }
            } else {
                foreach (Line line in Edges()) {
                    Normals[i] = line.ToVector2().PerpendicularCW().Normalized();
                    i++;
                }
            }
        }

        private void CalculateComponents() {
            _convexComponents.Clear();
            CalculateConvexity();

            Vector2 anchorVertex;
            if (IsConvex) {
                Vector2[] singleComponent = new Vector2[_vertices.Count];
                anchorVertex = _vertices[0];

                for (int i = 0; i < _vertices.Count; i++) {
                    singleComponent[i] = _vertices[i] - anchorVertex;
                }

                _convexComponents.Add(singleComponent);
                return;
            }

            List<(int, int)> exclusionList = new List<(int, int)>();
            List<Vector2[]> components = new List<Vector2[]>();

            anchorVertex = _vertices[0];
            List<Triangle> triangles = Triangulate();

            if (triangles.Count == 0) {
                return;
            }

            triangles.ForEach(
                (Triangle t) => {
                    Vector2[] triangleVertices = t.Vertices;

                    for (int i = 0; i < triangleVertices.Length; i++) {
                        triangleVertices[i] -= anchorVertex;
                    }

                    components.Add(triangleVertices);
                }
            );

            Vector2 sharedVertexA = Vector2.Zero, sharedVertexB = Vector2.Zero;
            List<Vector2> verticesToConvexHull = new List<Vector2>();

            int mergeTries = 0;
            while (components.Count >= 2 && mergeTries < components.Count - 1) {
                (int poly1Index, int poly2Index) = FindGreatestSharedEdgePolygons(
                    ref components,
                    ref exclusionList,
                    ref sharedVertexA,
                    ref sharedVertexB,
                    out Vector2[] component1,
                    out Vector2[] component2
                );

                // just ignore if no valid index has been found
                if (poly1Index == -1 || poly2Index == -1) {
                    mergeTries++;
                    continue;
                }

                verticesToConvexHull.Clear();
                verticesToConvexHull.AddRange(component1);
                verticesToConvexHull.AddRange(component2);
                List<Vector2> componentConvexHull = ConvexHull(verticesToConvexHull);
                int indexSharedVertexA = componentConvexHull.IndexOf(sharedVertexA),
                    indexSharedVertexB = componentConvexHull.IndexOf(sharedVertexB);

                // test if it's a valid convex hull
                if (indexSharedVertexA != -1 && indexSharedVertexB != -1 && Math.IsLeft(Helper.At(componentConvexHull, indexSharedVertexA - 1), Helper.At(componentConvexHull, indexSharedVertexA + 1), Helper.At(componentConvexHull, indexSharedVertexA)) && Math.IsLeft(Helper.At(componentConvexHull, indexSharedVertexB - 1), Helper.At(componentConvexHull, indexSharedVertexB + 1), Helper.At(componentConvexHull, indexSharedVertexB))) {
                    if (poly1Index > poly2Index) {
                        components.RemoveAt(poly1Index);
                        components.RemoveAt(poly2Index);
                    } else {
                        components.RemoveAt(poly2Index);
                        components.RemoveAt(poly1Index);
                    }

                    components.Add(componentConvexHull.ToArray());
                    mergeTries = 0;
                    exclusionList.Clear();
                } else {
                    mergeTries++;
                    exclusionList.Add((poly1Index, poly2Index));
                }
            }

            _convexComponents.AddRange(components);
        }

        private (int p1Index, int p2Index) FindGreatestSharedEdgePolygons(ref List<Vector2[]> components, ref List<(int, int)> exclusionList, ref Vector2 sharedVertexA, ref Vector2 sharedVertexB,  out Vector2[] component1, out Vector2[] component2) {
            (int A, int B) indexes = (-1, -1);
            component1 = component2 = null;
            float greatestEdgeLength = 0;

            for (int a = 0; a < components.Count; a++) {
                Vector2[] componentA = components[a];
                for (int b = a + 1; b < components.Count; b++) {
                    Vector2[] componentB = components[b];

                    if (exclusionList.FindIndex(p => Helper.EqualsPermutation(p.Item1, p.Item2, a, b)) != -1) {
                        continue;
                    }

                    Line? sharedEdge = FindSharedEdge(componentA, componentB);
                    if (sharedEdge != null) {
                        float d = sharedEdge.Value.LengthSquared;
                        if (d <= greatestEdgeLength) {
                            continue;
                        }

                        indexes = (a, b);
                        greatestEdgeLength = d;
                        component1 = componentA;
                        component2 = componentB;
                        sharedVertexA = sharedEdge.Value.PointA;
                        sharedVertexB = sharedEdge.Value.PointB;
                    }
                }
            }

            return indexes;
        }

        #region Triangulate Helper

        private bool InCone(LinkedListNode<Vector2> A, LinkedListNode<Vector2> B) {

            Vector2 prevA = A.PreviousOrLast().Value,
                    a = A.Value,
                    nextA = A.NextOrFirst().Value,
                    b = B.Value;

            // if A is a convex vertex
            if (Math.IsLeftOn(a, nextA, prevA)) {
                return Math.IsLeft(a, b, prevA) && Math.IsLeft(b, a, nextA);
            }

            // else A is reflex
            return Math.IsLeftOn(a, b, nextA) || Math.IsLeftOn(b, a, prevA);
        }

        private bool IsDiagonalie(LinkedListNode<Vector2> A, LinkedListNode<Vector2> B) {
            Vector2 a = A.Value, b = B.Value;
            for (int i = 0; i < VertexCount; i++) {
                Vector2 c = Helper.At(_vertices, i),
                        c1 = Helper.At(_vertices, i + 1);

                if (c != a && c1 != a && c != b && c1 != b && Intersect(a, b, c, c1)) {
                    return false;
                }
            }

            return true;
        }

        private bool IsInternalDiagonal(LinkedListNode<Vector2> A, LinkedListNode<Vector2> B) {
            return InCone(A, B) && InCone(B, A) && IsDiagonalie(A, B);
        }

        private bool Intersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d) {
            if (IntersectProp(a, b, c, d)) {
                return true;
            }

            if (IsBetween(a, b, c) || IsBetween(a, b, d) || IsBetween(c, d, a) || IsBetween(c, d, b)) {
                return true;
            }

            return false;
        }

        private bool IsBetween(Vector2 a, Vector2 b, Vector2 c) {
            if (!Math.IsCollinear(a, b, c)) {
                return false;
            }

            if (a.X != b.X) {
                return (a.X <= c.X && c.X <= b.X) || (a.X >= c.X && c.X >= b.X);
            }

            return (a.Y <= c.Y && c.Y <= b.Y) || (a.Y >= c.Y && c.Y >= b.Y);
        }

        private bool IntersectProp(Vector2 a, Vector2 b, Vector2 c, Vector2 d) {
            if (Math.IsCollinear(a, b, c) || Math.IsCollinear(a, b, d) || Math.IsCollinear(c, d, a) || Math.IsCollinear(c, d, b)) {
                return false;
            }

            return (!Math.IsLeft(a, b, c) ^ !Math.IsLeft(a, b, d)) && (!Math.IsLeft(c, d, a) ^ !Math.IsLeft(c, d, b));
        }

        #endregion Triangulate Helper

        #endregion Private Methods
    }
}


text:
import sys
import gzip
import os
import logging
import argparse

DEBUG = 0

if DEBUG:
  input="Z:/Shared/Labs/Vickers Lab/Tiger/projects/20150930_TGIRT_tRNA_human/identical/result/KCVH01_clipped_identical.fastq.gz"
  output="H:/temp/KCVH01_clipped_identical_NTA.fastq.gz"
else:
  parser = argparse.ArgumentParser(description="Generate smallRNA NTA read for Fastq file.",
                                   formatter_class=argparse.ArgumentDefaultsHelpFormatter)

  parser.add_argument('-i', '--input', action='store', nargs='?', help='Input Fastq file')
  parser.add_argument('-o', '--output', action='store', nargs='?', help="Output Fastq file")

  args = parser.parse_args()

  print(args)

  input = args.input
  output = args.output

inputFiles = input.split(",")
outputFiles = output.split(",")

logger = logging.getLogger('removeFastqTerminalN')
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)-8s - %(message)s')

for idx in range(0, len(inputFiles)):
  inputFile = inputFiles[idx]
  outputFile = outputFiles[idx]

  logger.info("Processing queries in %s ..." % inputFile)
  if inputFile.endswith(".gz"):
    f = gzip.open(inputFile, 'rt')
  else:
    f = open(inputFile, 'r')

  try:
    tmpFile=outputFile + ".tmp"
    if outputFile.endswith(".gz"):
      fw = gzip.open(tmpFile, "wt")
    else:
      fw = open(tmpFile, "w")

    try:
      readCount = 0
      while True:
        header = f.readline()
        if '' == header:
          break

        if not header.startswith("@"):
          continue

        seq = f.readline().strip()
        ignore = f.readline().strip()
        score = f.readline().strip()
        seqLength = len(seq)

        readCount = readCount + 1
        if readCount % 10000 == 0:
          logger.info("%d reads processed" % readCount)

        while(seq.startswith('N')):
          seq = seq[1:]
          score = score[1:]

        while(seq.endswith('N')):
          seq = seq[:-1]
          score = score[:-1]

        fw.write(header.rstrip() + "\n")
        fw.write(seq + "\n")
        fw.write(ignore + "\n")
        fw.write(score + "\n")
      fw.close()
      if os.path.isfile(outputFile):
        os.remove(outputFile)
      os.rename(tmpFile, outputFile)
      logger.info("Remove terminal N successed!")
    except BaseException as e:
      logger.error('Failed to remove terminal N: %s' % str(e))
      fw.close()
  finally:
    f.close()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright (c) Contributors to the Eclipse Foundation

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    SPDX-License-Identifier: Apache-2.0
 -->

<components>

	<component
		xmlns="http://www.osgi.org/xmlns/scr/v1.0.0"
		name="org.osgi.test.cases.component.tb12.component"
		immediate="true">
		<implementation
			class="org.osgi.test.cases.component.tb12.Comp"/>
		<service>
			<provide interface="org.osgi.test.cases.component.service.BaseService"/>
		</service>
	</component>

</components>


text:
import React, { findDOMNode, PropTypes, Component, Children } from 'react';

import { ownerDocument } from '../HoverCard/positionUtils';

/*
 * A portal through to a div appended to the document body.
 */
export default class Portal extends Component {

  constructor(props) {
    super(props);

    this.portal = null;
    this.node = null;
  }

  componentDidMount() {
    this.node = document.createElement('div');
    this.getContainerDOMNode().appendChild(this.node);
    this.renderPortal(this.props);
  }

  componentWillReceiveProps(newProps) {
    this.renderPortal(newProps);
  }

  componentWillUnmount() {
    if (this.portal) {
      this.getContainerDOMNode().removeChild(this.node);
    }
  }

  getContainerDOMNode() {
    return findDOMNode(this.props.container) || ownerDocument(this).body;
  }

  renderPortal(props) {
    this.portal = React.render(
      Children.only(props.children),
      this.node
    );
  }

  render() {
    return null;
  }
}

Portal.propTypes = {
  container: PropTypes.any,
};


text:
const Controller = require('../libraries/controller');
const UserModel = require('../models/user-model');

// HTTP layer, in this instance you can manage express request, response and next.
// In libraries/controller you have the basic RESTful methods find, findOne, findById,
// create, update and remove. Because this class is extending from there, you got that solved.
// You can overwrite extended methods or create custom ones here.

class UserController extends Controller {

    // Example of overwriting update method using findOneAndUpdate from mongoose

    // update(req, res, next) {
    //  this.model.findOneAndUpdate({ _id: req.params.id }, req.body)
    //  .then(doc => {
    //      if (!doc) res.status(404).send();
    //      return res.status(200).json(doc);
    //  })
    //  .catch(err => next(err));
    // }
    create(req, res, next) {
        this.model.find({ account: req.body.account }).then(array => {
                //console.log(array);
                if (array.length != 0) {
                    return res.status(202).json({ error: '违反唯一性约束', message: '账户:' + req.body.account + '已经存在' });
                } else {
                    UserModel.create(req.body)
                        .then(doc => res.status(201).json(doc));
                }
            })
            .catch(err => next(err));
    }
    update(req, res, next) {
            if (req.body.newpwd != undefined) {
                //console.log(req.params.id);
               UserModel.changePassword(req.params.id,req.body.newpwd,function(error) {
                    if (error) {
                        return res.status(404).end();
                    }
                     return res.status(200).json({ result: '重置密码成功' });
                });
            } else {
                UserModel.update(req.params.id, req.body)
                    .then(doc => {
                        if (!doc) {
                            return res.status(404).end();
                        }
                        return res.status(200).json(doc);
                    })
                    .catch(err => next(err));
            }
        }
        // Example of a custom method. Remember that you can use this method
        // in a specific route in the router file

    // customMethod(req, res, next) {
    //  this.model.geoNear([1,3], { maxDistance : 5, spherical : true })
    //  .then(doc => {
    //      if (!doc) res.status(404).send();
    //      return res.status(200).json(doc);
    //  })
    //  .catch(err => next(err));
    // }
}

module.exports = new UserController(UserModel);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#c5cae9">

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimaryDark"
        android:id="@+id/viewListExerciseHeaderLine" />
    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:id="@+id/relativeLayoutListExerciseHeader"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:background="@android:color/transparent">

        <TextView
            android:id="@+id/txtListExerciseHeader"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="16sp"
            android:text="Group"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/imageListExerciseHeader"
            android:lines="1"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp"
            android:textStyle="bold" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageListExerciseHeader"
            android:src="@drawable/ic_expand_more_white_24dp"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp" />
    </RelativeLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimaryDark"
        android:id="@+id/viewListExerciseHeaderLineBottom" />
</LinearLayout>