text:
<?php

namespace vxPHP\Database;

use vxPHP\Application\Exception\ConfigException;
use vxPHP\Database\Adapter\Propel2ConnectionWrapper;

/**
 * Simple factory for DatabaseInterface classes
 *
 * @author Gregor Kofler, info@gregorkofler.com
 *
 * @version 0.6.0, 2021-07-21
 */
class DatabaseInterfaceFactory
{
	private function __construct() {}

	private function __clone() {}

    /**
     * get a PDO wrapper/extension class depending on $type
     * if no type is provided DSN string in the configuration
     * is searched for a type definition
     *
     * @param string|null $type
     * @param array $config
     * @return DatabaseInterface
     *
     * @throws ConfigException
     */
	public static function create(string $type = null, array $config = []): DatabaseInterface
    {
	    if(!$type) {

	        if(!isset($config['dsn'])) {
	            throw new \Exception('No database type defined.');
            }

            if(preg_match('/^([a-z0-9]+):/i', trim($config['dsn']), $matches)) {
                $type = $matches[1];
            }
            else {
                throw new \Exception('No driver found in DSN.');
            }

        }

		$type = strtolower($type);

		if($type === 'propel') {

			// check whether Propel is available (assume Propel2)

            if(!class_exists('\\Propel\\Runtime\\Propel')) {
                throw new \Exception('Propel is configured as driver for vxPDO but not available in this application.');
            }

            $serviceContainer = \Propel\Runtime\Propel::getServiceContainer();

            // retrieve adapter information

            $adapterName = $serviceContainer->getAdapterClass();
            $dsnName = $serviceContainer->getDefaultDatasource();

            /* @var $connection \Propel\Runtime\Connection\ConnectionInterface */

            $connection = \Propel\Runtime\Propel::getConnection();

            if(!in_array($adapterName, ['mysql', 'pgsql'])) {

                throw new \Exception(sprintf("vxPDO accepts only mysql and pgsql as established connection drivers. The configured Propel connection '%s' uses '%s'.", $dsnName, $adapterName));

			}

			// @todo fugly like hell - perhaps some more concise solution exists

            preg_match('/dbname=([^;]+)/i', \Propel\Runtime\Propel::getConnectionManager($dsnName)->getConfiguration()['dsn'], $matches);
            $dbName = $matches[1] ?? '';

            $pdoConnection = new Propel2ConnectionWrapper($connection);
            $pdoConnection->setName($dsnName);
            $pdoConnection->setDbName($dbName);

            $className =
                __NAMESPACE__ .
                '\\Adapter\\' .
                ucfirst($adapterName);

            /* @var $vxPDO DatabaseInterface */

            $vxPDO = new $className();
            $vxPDO->setConnection($pdoConnection);

            return $vxPDO;
		}

        $className =
            __NAMESPACE__ .
            '\\Adapter\\' .
            ucfirst($type);

        // check whether driver is available

        if(!class_exists($className)) {

            throw new ConfigException(sprintf("No class for driver '%s' supported.", $type));

        }

        return new $className($config);
	}
}


text:
import * as express from 'express';
import requestApi from '../../../../../core/request-api';

module.exports = (req: express.Request, res: express.Response): void => {

	requestApi('posts/user-timeline', {
		'user-id': res.locals.user.id,
		'limit': 10
	}, req.user).then((timeline: any[]) => {
		res.locals.display({
			user: res.locals.user,
			timeline: timeline
		}, 'user');
	});
};

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2011 Couchbase, Inc
 *
 *   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.
 */

#ifndef SRC_VBUCKETMAP_H_
#define SRC_VBUCKETMAP_H_ 1

#include "config.h"

#include <vector>

#include "kvshard.h"
#include "vbucket.h"
#include "utility.h"

/**
 * A map of known vbuckets.
 */
class VBucketMap {
friend class EventuallyPersistentStore;
friend class Warmup;

public:

    // This class uses the same id_type as VBucket
    typedef VBucket::id_type id_type;

    VBucketMap(Configuration &config, EventuallyPersistentStore &store);
    ~VBucketMap();

    ENGINE_ERROR_CODE addBucket(const RCPtr<VBucket> &b);
    void removeBucket(id_type id);
    void addBuckets(const std::vector<VBucket*> &newBuckets);
    RCPtr<VBucket> getBucket(id_type id) const;

    // Returns the size of the map, i.e. the total number of VBuckets it can
    // contain.
    id_type getSize() const;
    std::vector<id_type> getBuckets(void) const;
    std::vector<id_type> getBucketsSortedByState(void) const;
    std::vector<std::pair<id_type, size_t> > getActiveVBucketsSortedByChkMgrMem(void) const;
    bool isBucketDeletion(id_type id) const;
    bool setBucketDeletion(id_type id, bool delBucket);
    bool isBucketCreation(id_type id) const;
    bool setBucketCreation(id_type id, bool rv);
    uint64_t getPersistenceCheckpointId(id_type id) const;
    void setPersistenceCheckpointId(id_type id, uint64_t checkpointId);
    uint64_t getPersistenceSeqno(id_type id) const;
    void setPersistenceSeqno(id_type id, uint64_t seqno);
    KVShard* getShardByVbId(id_type id) const;
    KVShard* getShard(KVShard::id_type shardId) const;
    size_t getNumShards() const;

private:

    std::vector<KVShard*> shards;
    std::atomic<bool> *bucketDeletion;
    std::atomic<bool> *bucketCreation;
    std::atomic<uint64_t> *persistenceCheckpointIds;
    std::atomic<uint64_t> *persistenceSeqnos;
    const id_type size;

    DISALLOW_COPY_AND_ASSIGN(VBucketMap);
};

#endif  // SRC_VBUCKETMAP_H_


text:
package org.gradle.api;

import org.gradle.internal.exceptions.Contextual;
import org.gradle.internal.exceptions.DefaultMultiCauseException;

/**
 * Indicates a problem that occurs during project configuration.
 */
@Contextual
public class ProjectConfigurationException extends DefaultMultiCauseException {
    public ProjectConfigurationException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Creates an exception with the given message and causes.
     * @param message The message
     * @param causes The causes
     * @since 5.1
     */
    @Incubating
    public ProjectConfigurationException(String message, Iterable<? extends Throwable> causes) {
        super(message, causes);
    }
}


text:
struct PixelRef
{
  const ImageInfo info;
};

PixelRef* create_pixel_ref(ImageInfo&);
void delete_pixel_ref();

ImageInfo& get_info_pixel_ref(PixelRef* pixel_ref)
{
  return pixel_ref->info;
}


text:
intermol.forces.settles module
==============================

.. automodule:: intermol.forces.settles
    :members:
    :undoc-members:
    :show-inheritance:


text:
shared_examples 'a model' do |known_attributes|
  describe '#initialize' do
    subject { described_class.new(attributes) }

    context 'known attributes are set' do
      let(:attributes) { known_attributes }

      it 'sets the attributes' do
        known_attributes.each do |key, value|
          mapped_attribute = described_class.object_fields::FIELDS.key(key)
          expect(subject.send(mapped_attribute)).to eq(value)
        end
      end
    end

    context 'known and unknown attributes are present' do
      let(:attributes) do
        known_attributes.merge({ something_random: true })
      end

      it 'sets the attributes known' do
        known_attributes.each do |key, value|
          mapped_attribute = described_class.object_fields::FIELDS.key(key)
          expect(subject.send(mapped_attribute)).to eq(value)
        end
      end

      it 'does not include the uknown attributes' do
        expect(subject).to_not respond_to(:something_random)
      end
    end

    context 'only uknown attributes are present' do
      let(:attributes) { { something_random: true } }

      it 'does not set them' do
        expect(subject).to_not respond_to(:something_random)
      end

      it 'has empty attributes' do
        expect(subject.attributes.values.compact).to eq([])
      end
    end
  end
end


text:
section: appliance
description: The PSaaS Appliance is an option for your organization when compliance or other policy requirements prevent you from using a multi-tenant cloud service.
topics:
    - appliance
contentType: concept
useCase: appliance
applianceId: appliance52
sitemap: false
---

# PSaaS Appliance Overview

The PSaaS Appliance is an option for your organization when compliance or other policy requirements prevent you from using a multi-tenant cloud service. The PSaaS Appliance can be deployed in one of three places:

* a dedicated cloud environment hosted by Auth0 (you may opt for a shared cloud environment or an environment where resources are allocated only to your company).
* your cloud environment using **Amazon AWS**

## Infrastructure

If you opt to use a dedicated cloud environment hosted by Auth0, Auth0 is responsible for installation, maintenance, patching and updates.

If you choose to deploy to your own cloud environment or data center, you supply and monitor the infrastructure Auth0 runs on. This includes the VM host, storage, network resources (such as the load balancer, internet access, and so on), and other required dependencies (such as the SMTP, NTP, and so on).

## Deployment

You may deploy the PSaaS Appliance in several different configurations and use several different deployment models. The configurations support different levels of scale and high availability, and they are available in any of the PSaaS Appliance deployment models. The following table shows the configuration options:

        Single Node
        High Availability
        High Capacity

        Description
        Intended for development and testing environments.

Three-node redundant cluster

Tolerates a single-node outage

Recommended for most Production environments

Includes a single node for Dev/QA

Highly scalable capacity for the most demanding applications

Tolerates multi-node outages

Recommended for large-scale Production environments

Includes a single node for Dev/QA

        Geo HA
        Not Available

Multiple data center with active-passive clustering and automated failover

Auth0 continues to operate if a data center becomes unavailable

If the primary data center fails, traffic can quickly be routed to the secondary cluster

Cluster topology is replicated in each environment. Requires a global load balancing solution like AWS Route 53 or F5 Global Traffic Manager.

        Backup and Recovery

Virtual Machine Snapshot

Data backup with cluster restore

Virtual Machine Snapshot

Virtual Machine shipping with scripted restore (if using VMWare)

Data backup with cluster restore

[Auth0 Deployment Models](/overview/deployment-models) provides additional details and explains the differences between each of the PSaaS Appliance deployment models and the standard multi-tenant cloud deployment.

## Maintenance and Connectivity

As a managed service, Auth0 performs:

* initial setup and configuration;
*  ongoing maintenance operations (security patching, troubleshooting, and updating).

Auth0 will closely coordinate access to your PSaaS Appliance instances with your operations team, since these activities will often run on your infrastructure (such as your network, servers, and so on). Depending on the time it takes to prepare the required infrastructure and the deployment complexity, the PSaaS Appliance implementation project typically takes between 1-5 weeks.

If Auth0 is managing a dedicated environment for you, Auth0 will obtain your consent prior to applying any updates or configuration changes. Auth0 will not access any PSaaS Appliance, nor will any information be transferred off of the PSaaS Appliance without your consent.

### Connectivity

During maintenance operations, the PSaaS Appliance instances contact external Auth0 endpoints for updating under your consent and supervision. After maintenance completes, you can [continue to operate with limited internet access](/appliance/infrastructure/internet-restricted-deployment).

For normal maintenance, Auth0 will access the Management Dashboard (either over a temporary SSH connection or through remote control software) to apply the update. Auth0 will also need SSH access in the event that updates to the PSaaS Appliance are necessary. If you expose API endpoints to be used for monitoring, Auth0 will collect this information to proactively monitor PSaaS Appliance behavior for you.

Depending on which features are implemented, you may need to permit access to certain websites on the Internet from each PSaaS Appliance instance. For example, if Facebook logins are needed, you must open connectivity from the Auth0 servers to `facebook.com`. If users will be logging in from the Internet (and not through a VPN), you must publish the authentication endpoints.

### Update Cycle

The typical update cycle is once per month. You can control and which version is applied. Occasionally, lower-level actions may be performed on the nodes. You will be notified in advance on the nature of activities to be performed, and will be provided instructions on any actions you may need to execute on your side.

The diagram below details a few of these dependencies:

## Monitoring and Support

You are responsible for monitoring all the dependencies the Auth0 Service relies on within your environment, such as the network load balancer, VM hosts, SMTP gateways, and so on.

If you provide access to the appropriate monitoring endpoints, Auth0 will monitor the nodes' health and notify you of any conditions that require action.

If Auth0 hosts the PSaaS Appliance for you, then Auth0 will monitor the related services.

### Monitoring Endpoints
Auth0 provides specific monitoring endpoints that you can attach to your own monitoring tools (such as Microsoft System Center, IBM Tivoli, HP OpenView, and so on) for auditing, load balancing, and performance monitoring, such as in cases where the transaction under test includes application specific functionality (for example, a [rule](/rules) that integrates Auth0 with your own CRM).

You may find detailed guidance at [Monitoring Auth0](/monitoring).

In addition, the PSaaS Appliance has authenticated monitoring endpoints for metrics like CPU, memory, and disk space that you can query for more detailed information.

If the PSaaS Appliance does not perform as expected, you can contact your Auth0 Customer Success Engineer. Auth0 provides an incident escalation procedure during the onboarding process that explains the steps to be followed when an incident occurs. Auth0 has a 24 x 7, around-the-clock support staff.

## Server Requirements

You will be asked to set up a Dev/Test (non-Production) environment, as well as a Production environment.

For the Production environment, the number of virtual machines required to host the PSaaS Appliance depends on the expected traffic and the desired availability. For a highly-available configuration, the Production environment requires a minimum of three network load-balanced PSaaS Appliance instances and one for the Dev/Test (non-Production) environment (which also does *not* required any special load balancing logic/sticky sessions).


text:
/* globals L, describe, beforeEach, afterEach, it, expect, Terraformer*/

describe('L.esri.FeatureLayer', function () {
  var map,
      container,
      sandbox,
      url = 'http://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/stops/FeatureServer/0/';

  beforeEach(function () {
    // create container
    container = document.createElement('div');

    // give container a width/height
    container.setAttribute("style","width:500px; height: 500px;");

    // add contianer to body
    document.body.appendChild(container);

    // create map
    map = L.map(container).setView([37.75, -122.45], 12);

    // create sandbox
    sandbox = sinon.sandbox.create();
  });

  afterEach(function () {
    sandbox.restore();
  });

  describe('#constructor', function () {
    describe('when a FeatureLayer is first created', function () {
      it('will have an spatial index (rbush)', function () {
        var rbush = sandbox.spy(L.esri, '_rbush'),
            featLayer = L.esri.featureLayer(url);
        expect(rbush.calledOnce).to.be.ok();
        expect(featLayer.index).to.be.ok();
      });
    });
  });

  describe('#onAdd, #onRemove, #updateFeatures', function () {
    describe('when a FeatureLayer is added to the map', function () {
      it('should generate a feature grid with 4 cells', function(){
        var featLayer = L.esri.featureLayer(url);

        featLayer.addTo(map);

        expect(featLayer._previousCells.length).to.equal(4);
      })
    });
  });
});


text:
import {expect} from "chai"

import {LayoutDOM} from "@bokehjs/models/layouts/layout_dom"
import {ToolbarBox, ProxyToolbar} from "@bokehjs/models/tools/toolbar_box"
import {ToolProxy} from "@bokehjs/models/tools/tool_proxy"
import {CustomAction} from "@bokehjs/models/tools/actions/custom_action"
import {ResetTool} from "@bokehjs/models/tools/actions/reset_tool"
import {SaveTool} from "@bokehjs/models/tools/actions/save_tool"
import {BoxEditTool} from "@bokehjs/models/tools/edit/box_edit_tool"
import {PointDrawTool} from "@bokehjs/models/tools/edit/point_draw_tool"
import {SelectTool, SelectToolView} from "@bokehjs/models/tools/gestures/select_tool"
import {PanTool} from "@bokehjs/models/tools/gestures/pan_tool"
import {TapTool} from "@bokehjs/models/tools/gestures/tap_tool"
import {CrosshairTool} from "@bokehjs/models/tools/inspectors/crosshair_tool"
import {HoverTool} from "@bokehjs/models/tools/inspectors/hover_tool"

class MultiToolView extends SelectToolView {}

class MultiTool extends SelectTool {
  default_view = MultiToolView
  icon = "Multi Tool"
  tool_name = "Multi Tool"
  event_type = ["tap" as "tap", "pan" as "pan"]
}

describe("ToolbarBox", () => {

  it("should be an instance of LayoutDOM", () => {
    const box = new ToolbarBox()
    expect(box).to.be.an.instanceof(LayoutDOM)
  })
})

describe("ProxyToolbar", () => {

  describe("_init_tools method", () => {
    let multi: MultiTool
    let pan: PanTool
    let tap: TapTool

    before_each(() => {
      multi = new MultiTool()
      pan = new PanTool()
      tap = new TapTool()
    })

    it("should have proxied multi tool in gestures", () => {
      const toolbar = new ProxyToolbar({tools:[multi, tap, pan]})
      expect(toolbar.gestures.multi.tools.length).to.be.equal(1)
      expect(toolbar.gestures.multi.tools[0]).to.be.an.instanceof(ToolProxy)
      expect(toolbar.gestures.multi.tools[0].computed_icon).to.be.equal('Multi Tool')
      expect(((toolbar.gestures.multi.tools[0]) as any).tools.length).to.be.equal(1) // XXX
      expect(((toolbar.gestures.multi.tools[0]) as any).tools[0]).to.be.equal(multi) // XXX
    })
  })

  describe("_merge_tools method", () => {

    it("should correctly merge multiple actions", () => {
      const reset1 = new ResetTool()
      const reset2 = new ResetTool()
      const save1 = new SaveTool()
      const save2 = new SaveTool()
      const proxy_toolbar = new ProxyToolbar({tools: [reset1, reset2, save1, save2]})
      expect(proxy_toolbar.actions.length).equal(2)
    })

    it("should correctly merge multiple inspectors", () => {
      const hover1 = new HoverTool()
      const hover2 = new HoverTool()
      const crosshair1 = new CrosshairTool()
      const crosshair2 = new CrosshairTool()
      const proxy_toolbar = new ProxyToolbar({tools: [hover1, hover2, crosshair1, crosshair2]})
      expect(proxy_toolbar.inspectors.length).equal(2)
    })

    it("should avoid merge of multiple multi-gesture tools", () => {
      const pointdraw = new PointDrawTool()
      const boxedit1 = new BoxEditTool()
      const boxedit2 = new BoxEditTool()
      const proxy_toolbar = new ProxyToolbar({tools: [pointdraw, boxedit1, boxedit2]})
      expect(proxy_toolbar.gestures.multi.tools.length).equal(3)
    })

    it("should avoid merge of multiple CustomAction tools", () => {
      const reset1 = new ResetTool()
      const reset2 = new ResetTool()
      const custom_action1 = new CustomAction()
      const custom_action2 = new CustomAction()
      const proxy_toolbar = new ProxyToolbar({tools: [reset1, reset2, custom_action1, custom_action2]})
      expect(proxy_toolbar.actions.length).equal(3)
    })
  })
})


text:
<?
/**
 * These are EAV rows.  Entities are dual-named in Stuki as both Doctrine Entities (this class)
 * and EAV entities.
 */
namespace Entities;

use Stuki\Entity\Entity,
    ZfcUserDoctrineORM\Entity\User,
    Doctrine\ORM\Mapping AS ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="entities")
 */
class EntityRelations extends Entity
{

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue
     */
    protected $entity_relation_key;

    public function getKey() {
        return $this->entity_relation_key;
    }

    protected $parent;

    public function getParent() {
        return $this->parent;
    }

    public function setParent(\Entities\Entities $value) {
        $this->parent = $value;
    }

    protected $child;

    public function getChild() {
        return $this->child;
    }

    public function setChild(\Entities\Entities $value) {
        $this->child = $value;
        return $this;
    }

    protected $sort;

    public function getSort() {
        return $this->sort;
    }

    public function setSort($value) {
        $this->sort = $value;
    }

}


text:
{-# LANGUAGE GADTs, ExplicitForAll #-}
module T16254 where

newtype Size a b where
  Size :: forall b a. Int -> Size a b

{-# INLINABLE val2 #-}
val2 = Size 17

-- In the core, we should see a comparison against 34#, i.e. constant
-- folding should have happened. We actually see it twice: Once in f's
-- definition, and once in its unfolding.
f n = case val2 of Size s -> s + s > n


text: A exercise of iOS development


text:
/* jshint -W106 */
// jscs:disable
(function () {
    'use strict';

    angular
        .module('app.custom')
        .run(appRun);

    /* @ngInject */
    function appRun(routerHelper) {
        routerHelper.configureStates(getStates());
    }

    function getStates() {
        return [
            {
                state: 'custom',
                config: {
                    url: '/custom',
                    templateUrl: 'app/custom/template/custom.html',
                    controller: 'CustomController',
                    controllerAs: 'vm',
                    title: 'custom',
                    resolve: {
                        translations: function (translateHelper) {
                            return translateHelper.addParts('dashboard');
                        }
                    }
                }
            }
        ];
    }
})();


text:
CGFloat colorComponentFrom(NSString *string, NSUInteger start, NSUInteger length) {
    NSString *substring = [string substringWithRange:NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];

    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}

@implementation UIColor (HEX)
+ (UIColor *)colorWithHex:(UInt32)hex {
    return [UIColor colorWithHex:hex andAlpha:1];
}
+ (UIColor *)colorWithHex:(UInt32)hex andAlpha:(CGFloat)alpha {
    return [UIColor colorWithRed:((hex >> 16) & 0xFF)/255.0
                           green:((hex >> 8) & 0xFF)/255.0
                            blue:(hex & 0xFF)/255.0
                           alpha:alpha];
}

+ (UIColor *)colorWithHexString:(NSString *)hexString {
    CGFloat alpha, red, blue, green;

    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""] uppercaseString];
    switch ([colorString length]) {
        case 3: // #RGB
            alpha = 1.0f;
            red   = colorComponentFrom(colorString, 0, 1);
            green = colorComponentFrom(colorString, 1, 1);
            blue  = colorComponentFrom(colorString, 2, 1);
            break;

        case 4: // #ARGB
            alpha = colorComponentFrom(colorString, 0, 1);
            red   = colorComponentFrom(colorString, 1, 1);
            green = colorComponentFrom(colorString, 2, 1);
            blue  = colorComponentFrom(colorString, 3, 1);
            break;

        case 6: // #RRGGBB
            alpha = 1.0f;
            red   = colorComponentFrom(colorString, 0, 2);
            green = colorComponentFrom(colorString, 2, 2);
            blue  = colorComponentFrom(colorString, 4, 2);
            break;

        case 8: // #AARRGGBB
            alpha = colorComponentFrom(colorString, 0, 2);
            red   = colorComponentFrom(colorString, 2, 2);
            green = colorComponentFrom(colorString, 4, 2);
            blue  = colorComponentFrom(colorString, 6, 2);
            break;

        default:
            return nil;
    }
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

- (NSString *)HEXString {
    UIColor* color = self;
    if (CGColorGetNumberOfComponents(color.CGColor) < 4) {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0]
                                green:components[0]
                                 blue:components[0]
                                alpha:components[1]];
    }
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    return [NSString stringWithFormat:@"#%02X%02X%02X", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[1]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}

+ (UIColor *)colorWithWholeRed:(CGFloat)red
                         green:(CGFloat)green
                          blue:(CGFloat)blue
                         alpha:(CGFloat)alpha
{
    return [UIColor colorWithRed:red/255.f
                           green:green/255.f
                            blue:blue/255.f
                           alpha:alpha];
}

+ (UIColor *)colorWithWholeRed:(CGFloat)red
                         green:(CGFloat)green
                          blue:(CGFloat)blue
{
    return [self colorWithWholeRed:red
                             green:green
                              blue:blue
                             alpha:1.0];
}

+ (UIColor *)randomColor {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.deeplearning4j</groupId>
        <artifactId>deeplearning4j-ui-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>deeplearning4j-vertx</artifactId>

    <properties>

        <module.name>deeplearning4j.vertx</module.name>
    </properties>

    <build>
        <plugins>
        <!--    <plugin>
                <groupId>org.moditect</groupId>
                <artifactId>moditect-maven-plugin</artifactId>
            </plugin>-->
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>${vertx.version}</version>
        </dependency>
        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>${vertx.version}</version>
        </dependency>
        <dependency>
            <groupId>org.deeplearning4j</groupId>
            <artifactId>deeplearning4j-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.deeplearning4j</groupId>
            <artifactId>deeplearning4j-ui-model</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
        </dependency>
        <dependency>
            <groupId>com.beust</groupId>
            <artifactId>jcommander</artifactId>
            <version>${jcommander.version}</version>
        </dependency>
        <dependency>
            <groupId>jakarta.xml.bind</groupId>
            <artifactId>jakarta.xml.bind-api</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.deeplearning4j</groupId>
            <artifactId>deeplearning4j-common-tests</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- WebJars Dependencies -->
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>babel__polyfill</artifactId>
            <version>7.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>coreui__coreui</artifactId>
            <version>2.1.9</version>
            <exclusions>
                <exclusion>
                    <groupId>org.webjars.npm</groupId>
                    <artifactId>coreui__coreui-plugin-npm-postinstall</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>coreui__icons</artifactId>
            <version>0.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>popper.js</artifactId>
            <version>1.12.9</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>bootstrap</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-migrate</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-ui</artifactId>
            <version>1.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>modernizr</artifactId>
            <!--<version>2.6.2</version>-->
            <version>2.8.3-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-cookie</artifactId>
            <version>1.4.1-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>fullcalendar</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>excanvas</artifactId>
            <version>3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>cytoscape</artifactId>
            <version>3.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>cytoscape-dagre</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>dagre</artifactId>
            <version>0.8.4</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>cytoscape-cola</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>cytoscape-cose-bilkent</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>cytoscape-euler</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>cytoscape-klay</artifactId>
            <version>3.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>klayjs</artifactId>
            <version>0.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>cytoscape-spread</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>weaverjs</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>retinajs</artifactId>
            <version>0.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>flot</artifactId>
            <version>0.8.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>chosen</artifactId>
            <version>0.9.8</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>uniform</artifactId>
            <version>2.1.2-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>noty</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-raty</artifactId>
            <version>2.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>imagesloaded</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>masonry</artifactId>
            <version>3.1.5</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery.sparkline</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-knob</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>datatables</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery-ui-touch-punch</artifactId>
            <version>0.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>d3js</artifactId>
            <version>3.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-notify</artifactId>
            <version>3.1.3-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>github-com-jboesch-Gritter</artifactId>
            <version>1.7.4</version>
        </dependency>
        <!-- Fonts -->
        <dependency>
            <groupId>org.webjars.bowergithub.stenin-nikita</groupId>
            <artifactId>open-sans</artifactId>
            <version>0.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>font-awesome</artifactId>
            <version>3.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-glyphicons</artifactId>
            <version>bdd2cbfba0</version>
        </dependency>
        <!-- For SameDiff UI -->
        <dependency>
            <groupId>org.webjars.npm</groupId>
            <artifactId>flatbuffers</artifactId>
            <version>1.9.0</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <!-- Override webjars dependencies with fixed versions.
            See issue #7730 for details
            WebJars defines its dependencies using ranges - [3.10.0,4)
            However, we want to lock down the versions, for a few reasons:
            (a) When defined in a range like this, user builds will check on every build of their project
            (b) It makes it harder to debug issues, if user and developers are using different versions
            (c) Though in-principle this should be safe, we can't be sure that a 3rd party change won't break our UI with a new version
            (d) The ranges don't always work as expected in practice: in one instance 3.0.0-beta9 was considered within the range [2.0.0,3)
             -->

            <!-- babel__polyfill dependencies -->
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>core-js</artifactId>
                <version>2.6.5</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>regenerator-runtime</artifactId>
                <version>0.13.2</version>
            </dependency>
            <!-- coreui__coreui dependencies -->
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>bootstrap</artifactId>
                <version>4.3.1</version>
            </dependency>
            <!-- org.webjars.npm:cytoscape -->
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>heap</artifactId>
                <version>0.2.6</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>lodash.debounce</artifactId>
                <version>4.0.8</version>
            </dependency>
            <!-- org.webjars.npm:dagre -->
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>graphlib</artifactId>
                <version>2.1.7</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.bower</groupId>
                <artifactId>cytoscape</artifactId>
                <version>3.2.5</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.bower</groupId>
                <artifactId>dagre</artifactId>
                <version>0.7.4</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.bower</groupId>
                <artifactId>graphlib</artifactId>
                <version>1.0.7</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.bower</groupId>
                <artifactId>lodash</artifactId>
                <version>3.10.1</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>lodash</artifactId>
                <version>4.17.11</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>webcola</artifactId>
                <version>3.3.8</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>d3-dispatch</artifactId>
                <version>1.0.5</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>d3-drag</artifactId>
                <version>1.2.3</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>d3-selection</artifactId>
                <version>1.4.0</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>d3-timer</artifactId>
                <version>1.0.9</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>klayjs</artifactId>
                <version>0.4.1</version>
            </dependency>
            <dependency>
                <groupId>org.webjars.npm</groupId>
                <artifactId>weaverjs</artifactId>
                <version>1.2.0</version>
            </dependency>
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>explorercanvas</artifactId>
                <version>r3-1</version>
            </dependency>
            <dependency>
                <groupId>org.webjars</groupId>
                <artifactId>bootstrap</artifactId>
                <version>2.2.2-1</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>


text:
001
018
019    package org.apache.hadoop.yarn.api.protocolrecords;
020
021    import java.util.List;
022
023    import org.apache.hadoop.classification.InterfaceAudience.Private;
024    import org.apache.hadoop.classification.InterfaceAudience.Public;
025    import org.apache.hadoop.classification.InterfaceStability.Stable;
026    import org.apache.hadoop.classification.InterfaceStability.Unstable;
027    import org.apache.hadoop.yarn.api.ApplicationClientProtocol;
028    import org.apache.hadoop.yarn.api.records.ApplicationReport;
029    import org.apache.hadoop.yarn.util.Records;
030
031    /**
032     * <p>The response sent by the <code>ResourceManager</code> to a client
033     * requesting an {@link ApplicationReport} for applications.</p>
034     *
035     * <p>The <code>ApplicationReport</code> for each application includes details
036     * such as user, queue, name, host on which the <code>ApplicationMaster</code>
037     * is running, RPC port, tracking URL, diagnostics, start time etc.</p>
038     *
039     * @see ApplicationReport
040     * @see ApplicationClientProtocol#getApplications(GetApplicationsRequest)
041     */
042    @Public
043    @Stable
044    public abstract class GetApplicationsResponse {
045      @Private
046      @Unstable
047      public static GetApplicationsResponse newInstance(
048          List<ApplicationReport> applications) {
049        GetApplicationsResponse response =
050            Records.newRecord(GetApplicationsResponse.class);
051        response.setApplicationList(applications);
052        return response;
053      }
054
055      /**
056       * Get <code>ApplicationReport</code> for applications.
057       * @return <code>ApplicationReport</code> for applications
058       */
059      @Public
060      @Stable
061      public abstract List<ApplicationReport> getApplicationList();
062
063      @Private
064      @Unstable
065      public abstract void setApplicationList(List<ApplicationReport> applications);
066    }


text:
/**
 * @generated SignedSource<<6f39d9df64ceb1fb8762c075a2339e7d>>
 * @lightSyntaxTransform
 * @nogrep
 */

/* tslint:disable */
/* eslint-disable */
// @ts-nocheck

import { ConcreteRequest, Query } from 'relay-runtime';
import { FragmentRefs } from "relay-runtime";
export type AppSecondFactorRefetchQuery$variables = {};
export type AppSecondFactorRefetchQuery$data = {
  readonly me: {
    readonly " $fragmentSpreads": FragmentRefs<"AppSecondFactor_me">;
  } | null;
};
export type AppSecondFactorRefetchQuery = {
  response: AppSecondFactorRefetchQuery$data;
  variables: AppSecondFactorRefetchQuery$variables;
};

const node: ConcreteRequest = {
  "fragment": {
    "argumentDefinitions": [],
    "kind": "Fragment",
    "metadata": null,
    "name": "AppSecondFactorRefetchQuery",
    "selections": [
      {
        "alias": null,
        "args": null,
        "concreteType": "Me",
        "kind": "LinkedField",
        "name": "me",
        "plural": false,
        "selections": [
          {
            "args": null,
            "kind": "FragmentSpread",
            "name": "AppSecondFactor_me"
          }
        ],
        "storageKey": null
      }
    ],
    "type": "Query",
    "abstractKey": null
  },
  "kind": "Request",
  "operation": {
    "argumentDefinitions": [],
    "kind": "Operation",
    "name": "AppSecondFactorRefetchQuery",
    "selections": [
      {
        "alias": null,
        "args": null,
        "concreteType": "Me",
        "kind": "LinkedField",
        "name": "me",
        "plural": false,
        "selections": [
          {
            "alias": null,
            "args": null,
            "kind": "ScalarField",
            "name": "hasSecondFactorEnabled",
            "storageKey": null
          },
          {
            "alias": "appSecondFactors",
            "args": [
              {
                "kind": "Literal",
                "name": "kinds",
                "value": [
                  "app"
                ]
              }
            ],
            "concreteType": null,
            "kind": "LinkedField",
            "name": "secondFactors",
            "plural": true,
            "selections": [
              {
                "alias": null,
                "args": null,
                "kind": "ScalarField",
                "name": "__typename",
                "storageKey": null
              },
              {
                "kind": "InlineFragment",
                "selections": [
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "internalID",
                    "storageKey": null
                  },
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "name",
                    "storageKey": null
                  }
                ],
                "type": "AppSecondFactor",
                "abstractKey": null
              }
            ],
            "storageKey": "secondFactors(kinds:[\"app\"])"
          },
          {
            "alias": null,
            "args": null,
            "kind": "ScalarField",
            "name": "id",
            "storageKey": null
          }
        ],
        "storageKey": null
      }
    ]
  },
  "params": {
    "cacheID": "0fd614359fcbd334b9bcc786fb220eed",
    "id": null,
    "metadata": {},
    "name": "AppSecondFactorRefetchQuery",
    "operationKind": "query",
    "text": "query AppSecondFactorRefetchQuery {\n  me {\n    ...AppSecondFactor_me\n    id\n  }\n}\n\nfragment AppSecondFactor_me on Me {\n  hasSecondFactorEnabled\n  appSecondFactors: secondFactors(kinds: [app]) {\n    __typename\n    ... on AppSecondFactor {\n      __typename\n      internalID\n      name\n    }\n  }\n}\n"
  }
};

(node as any).hash = "6fe77b566e0c28ba19ba5573a354fc5d";

export default node;


text:
#!/usr/bin/env node
'use strict';

/**
 *
 * HTTP middleware
 *
 */

var Stack = require('la-scala');
Stack.errorHandler = function(req, res, err) {
  res.writeHead(200, {'Content-Type': 'application/json'});
  if (err) {
    err = err.stack || err;
  } else {
    err = null;
  }
  res.end(JSON.stringify({error: err, result: null}));
};

function stack() { return [
  // body parser
  Stack.use('body')(),
  // RESTful-ish RPC
  Stack.use('rest')('/rpc/', { context: app.context, jsonrpc: true })
];}

var app = require('./app');

/**
 *
 * Workers
 *
 */

function Worker(port, host) {
  // HTTP server
  this.http = Stack.listen(stack(), {}, port, host);
  // notify
  console.log('Banka listening to http://' + host + ':' + port + '. Use Ctrl+C to stop.');
}

// spawn workers
var w1 = new Worker(60999);

// REPL for introspection
var repl = require('repl').start('node> ').context;
process.stdin.on('close', process.exit);
repl.w1 = w1;


text:
title: Combining Colors
module: topic-09
permalink: /topic-09/combining-color/
---

When we start to mix the ratios of red, green, and blue, we come up with the rest of the colors of the spectrum. Some of the first colors we should consider are the complementary colors of red, green, and blue. To get the complementary color for red, we use full green and blue. This creates cyan.

- Name: cyan;
- RGB: rgb(0, 255, 255);
- Hex: #00ffff;

    Red compliments cyan.

    Cyan compliments red.

Likewise, to get the complimentary colors for green and blue, which are magenta and yellow, respectively, we boost the values of the two other colors.

- Name: magenta;
- RGB: rgb(255, 0, 255);
- Hex: #ff00ff;

    Green compliments magenta.

    Magenta compliments green.

- Name: yellow;
- RGB: rgb(255, 255, 00);
- Hex: #ffff00;

    Blue compliments yellow.

    Yellow compliments blue.

Others colors are obviously some combination of these values. The exact ratios depend on the amounts of red, green, and blue in every value.


text:
package rosas.dataprocessor;

import org.apache.hadoop.hive.ql.exec.UDF;

/**
 * Created by Administrator on 2016/6/3.
 */
public class InteroperabilityParameters_6_UDF  extends UDF {
    public int evaluate(String str,Double value) {
        try {
            String[] list = Common.StrToList(str);
            for (int i = 0; i < list.length; i++) {
                double a=Double.parseDouble(list[i].replace(")","").split(",")[1]);
                if ( a> value) {
                    return 1;
                }
            }
        } catch (Exception ex) {
            return 0;
        }
        return 0;
    }
}


text:
"""cl.result"""

from __future__ import absolute_import
from __future__ import with_statement

from kombu.pools import producers

from .exceptions import clError, NoReplyError

__all__ = ["AsyncResult"]

class AsyncResult(object):
    Error = clError
    NoReplyError = NoReplyError

    def __init__(self, ticket, actor):
        self.ticket = ticket
        self.actor = actor

    def _first(self, replies):
        if replies is not None:
            replies = list(replies)
            if replies:
                return replies[0]
        raise self.NoReplyError("No reply received within time constraint")

    def get(self, **kwargs):
        return self._first(self.gather(**dict(kwargs, limit=1)))

    def gather(self, propagate=True, **kwargs):
        connection = self.actor.connection
        gather = self._gather
        with producers[connection].acquire(block=True) as producer:
            for r in gather(producer.connection, producer.channel, self.ticket,
                            propagate=propagate, **kwargs):
                yield r

    def _gather(self, *args, **kwargs):
        propagate = kwargs.pop("propagate", True)
        return (self.to_python(reply, propagate=propagate)
                    for reply in self.actor._collect_replies(*args, **kwargs))

    def to_python(self, reply, propagate=True):
        try:
            return reply["ok"]
        except KeyError:
            error = self.Error(*reply.get("nok") or ())
            if propagate:
                raise error
            return error


text:
package com.andreadec.musicplayer.ui;

import android.graphics.*;
import androidx.recyclerview.widget.RecyclerView;
import android.view.*;
import android.widget.*;

import com.andreadec.musicplayer.adapters.*;

public class DragDropTouchListener implements RecyclerView.OnItemTouchListener {
    final static int SCROLL_THRESHOLD = 50;
    final static int SCROLL_AMOUNT = 20;

    enum Action {ACTION_NONE, ACTION_DECIDING, ACTION_SORT, ACTION_REMOVE};

    private RecyclerView recyclerView;
    private ImageView overlay;
    private OnItemMovedListener listener;
    private int layoutHeaderId;
    private int handlerId;

    private Action actionInProgress = Action.ACTION_NONE;
    private int initX, initY;

    private MusicPlayerAdapter adapter;

    private View draggingView = null;
    private int adjustY, initialPosition, currentPosition;

    public DragDropTouchListener(final RecyclerView recyclerView, ImageView overlay, int layoutHeaderId, final int handlerId, OnItemMovedListener listener) {
        this.recyclerView = recyclerView;
        this.overlay = overlay;
        this.layoutHeaderId = layoutHeaderId;
        this.listener = listener;
        this.handlerId = handlerId;
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        if(actionInProgress==Action.ACTION_NONE) {
            if(e.getAction()==MotionEvent.ACTION_DOWN) {
                View view = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if(view!=null && isInside(view.findViewById(handlerId), (int)e.getRawX(), (int)e.getRawY())) {
                    dragStart(e.getX(), e.getY());
                    return true;
                }
            }
            return false;
        } else {
            return true;
        }
    }

    private boolean isInside(View handler, int touchX, int touchY) {
        if(handler==null) return false;
        int[] location = new int[2];
        handler.getLocationOnScreen(location);
        return touchX > location[0] && touchX < location[0]+handler.getWidth() &&
                touchY > location[1] && touchY < location[1]+handler.getHeight();
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        int action = e.getAction();
        if(action==MotionEvent.ACTION_UP || action==MotionEvent.ACTION_CANCEL) {
            if(actionInProgress==Action.ACTION_SORT) {
                dragEnd();
            } else {
                deleteEnd((int)e.getX());
            }
        } else {
            if(actionInProgress==Action.ACTION_DECIDING) {
                if (Math.abs(initX - (int)e.getX()) > (Math.abs(initY-(int)e.getY()))) {
                    actionInProgress = Action.ACTION_REMOVE;
                } else {
                    actionInProgress = Action.ACTION_SORT;
                }
            }

            if(actionInProgress==Action.ACTION_SORT) {
                dragProgress((int) e.getY());
            } else {
                deleteProgress((int) e.getX());
            }
        }
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean b) {

    }

    private void dragStart(float x, float y) {
        adapter = (MusicPlayerAdapter)recyclerView.getAdapter();

        draggingView = recyclerView.findChildViewUnder(x, y);
        adjustY = (int)(y-draggingView.getTop());
        initialPosition = recyclerView.getChildPosition(draggingView);
        currentPosition = initialPosition;

        // Copy view to overlay
        Bitmap bitmap = Bitmap.createBitmap(draggingView.getWidth(), draggingView.getHeight(), Bitmap.Config.ARGB_8888);
        draggingView.draw(new Canvas(bitmap));
        overlay.setImageBitmap(bitmap);
        overlay.setTop(0);
        overlay.setLeft(0);
        overlay.setTranslationY(y-adjustY);
        overlay.setTranslationX(0);

        draggingView.setVisibility(View.INVISIBLE);

        initX = (int)x;
        initY = (int)y;
        actionInProgress = Action.ACTION_DECIDING;
    }

    private void dragEnd() {
        overlay.setImageBitmap(null);
        draggingView.setVisibility(View.VISIBLE);
        actionInProgress = Action.ACTION_NONE;
        listener.onItemMoved(initialPosition, currentPosition);
    }

    private void dragProgress(int y) {
        overlay.setTranslationY(y - adjustY);

        if(y<SCROLL_THRESHOLD) {
            //int first = layoutManager.findFirstVisibleItemPosition();
            //if(first>0) recyclerView.scrollToPosition(first-1);
            recyclerView.scrollBy(0, -SCROLL_AMOUNT);
        } else if(y>recyclerView.getBottom()-SCROLL_THRESHOLD) {
            //recyclerView.scrollToPosition(layoutManager.findLastVisibleItemPosition()+1);
            recyclerView.scrollBy(0, SCROLL_AMOUNT);
        }

        View viewUnder = recyclerView.findChildViewUnder(10, y);
        if(viewUnder!=null && !viewUnder.equals(draggingView)) {
            int newPosition = recyclerView.getChildPosition(viewUnder);
            if(viewUnder.getId()==layoutHeaderId) return;
            adapter.swapItems(currentPosition, newPosition);
            currentPosition = newPosition;
        }
    }

    private void deleteProgress(int x) {
        overlay.setTranslationX(x);
    }

    private void deleteEnd(int x) {
        overlay.setImageBitmap(null);
        actionInProgress = Action.ACTION_NONE;
        int recyclerViewWidth = recyclerView.getWidth();
        if(recyclerViewWidth-x < recyclerViewWidth/2) {
            listener.onItemDeleted(adapter.deleteItem(currentPosition));
        } else {
            draggingView.setVisibility(View.VISIBLE);
        }
    }

    public interface OnItemMovedListener {
        void onItemMoved(int from, int to);
        void onItemDeleted(Object item);
    }
}


text:
import JsFile from 'JsFile';
import parseTextProperties from './parse-text-properties';
import parseDrawing from './parse-drawing';
import parsePicture from './parse-picture';
const {Document} = JsFile;
const {merge, clone, nbHyphen, enDash, space, tabAsSpaces} = JsFile.Engine;

export default function parseText (params = {}) {
    const {node, documentData} = params;
    const result = Document.elementPrototype;
    const forEach = [].forEach;

    result.properties.tagName = 'SPAN';

    if (!node || !documentData) {
        return result;
    }

    const textProperties = {
        style: {},
        properties: documentData.styles.defaults.textProperties &&
        clone(documentData.styles.defaults.textProperties.properties) || {}
    };

    forEach.call(node && node.childNodes || [], (childNode) => {
        let element = null;
        const {textContent = '', attributes} = childNode;

        switch (childNode.localName) {
            case 'cr':
                element = Document.elementPrototype;
                element.properties.tagName = 'BR';
                result.children.push(element);
                break;
            case 'br':
                {
                    const type = attributes['w:type'] && attributes['w:type'].value;
                    const clear = attributes['w:clear'] && attributes['w:clear'].value;

                    if (!type || type === 'textWrapping') {
                        element = Document.elementPrototype;

                        if (!clear || clear === 'none' || clear === 'all') {
                            element.properties.tagName = 'BR';
                        }

                        result.children.push(element);
                    }

                    // TODO: parse types 'column' & 'page', parse clear 'left' & 'right'
                    break;
                }
            case 'drawing':
                merge(result, parseDrawing(childNode, documentData));
                break;
            case 'noBreakHyphen':
                result.properties.textContent += nbHyphen;
                break;
            case 'softHyphen':
                result.properties.textContent += enDash;
                break;
            case 'rPr':
                merge(textProperties, parseTextProperties(childNode, documentData));
                break;

            // TODO: parse w:sym. It needs more samples of .docx

            case 't':
                result.properties.textContent += textContent.replace(/\s/g, space);
                break;
            case 'tab':
                result.properties.textContent += tabAsSpaces;
                break;
            case 'pict':
                merge(result, parsePicture(childNode, documentData));
                break;

            default:
            // do nothing
        }
    });

    merge(result, textProperties);
    return result;
}


text:
#include "OgreStableHeaders.h"
#include "OgrePose.h"
#include "OgreHardwareBufferManager.h"

namespace Ogre {
	//---------------------------------------------------------------------
	Pose::Pose(ushort target, const String& name)
		: mTarget(target), mName(name)
	{
	}
	//---------------------------------------------------------------------
	Pose::~Pose()
	{
	}
	//---------------------------------------------------------------------
	void Pose::addVertex(size_t index, const Vector3& offset)
	{
		mVertexOffsetMap[index] = offset;
		mBuffer.setNull();
	}
	//---------------------------------------------------------------------
	void Pose::removeVertex(size_t index)
	{
		VertexOffsetMap::iterator i = mVertexOffsetMap.find(index);
		if (i != mVertexOffsetMap.end())
		{
			mVertexOffsetMap.erase(i);
			mBuffer.setNull();
		}
	}
	//---------------------------------------------------------------------
	void Pose::clearVertexOffsets(void)
	{
		mVertexOffsetMap.clear();
		mBuffer.setNull();
	}
	//---------------------------------------------------------------------
	Pose::ConstVertexOffsetIterator
		Pose::getVertexOffsetIterator(void) const
	{
		return ConstVertexOffsetIterator(mVertexOffsetMap.begin(), mVertexOffsetMap.end());
	}
	//---------------------------------------------------------------------
	Pose::VertexOffsetIterator
		Pose::getVertexOffsetIterator(void)
	{
		return VertexOffsetIterator(mVertexOffsetMap.begin(), mVertexOffsetMap.end());
	}
	//---------------------------------------------------------------------
	const HardwareVertexBufferSharedPtr& Pose::_getHardwareVertexBuffer(size_t numVertices) const
	{
		if (mBuffer.isNull())
		{
			// Create buffer
			mBuffer = HardwareBufferManager::getSingleton().createVertexBuffer(
				VertexElement::getTypeSize(VET_FLOAT3),
				numVertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY);

			float* pFloat = static_cast<float*>(
				mBuffer->lock(HardwareBuffer::HBL_DISCARD));
			// initialise
			memset(pFloat, 0, mBuffer->getSizeInBytes());
			// Set each vertex
			for (VertexOffsetMap::const_iterator i = mVertexOffsetMap.begin();
				i != mVertexOffsetMap.end(); ++i)
			{
				float* pDst = pFloat + (3 * i->first);
				*pDst++ = i->second.x;
				*pDst++ = i->second.y;
				*pDst++ = i->second.z;
			}
			mBuffer->unlock();
		}
		return mBuffer;
	}
	//---------------------------------------------------------------------
	Pose* Pose::clone(void) const
	{
		Pose* newPose = OGRE_NEW Pose(mTarget, mName);
		newPose->mVertexOffsetMap = mVertexOffsetMap;
		// Allow buffer to recreate itself, contents may change anyway
		return newPose;
	}

}


text:
package org.pocketcampus.plugin.news.android.iface;

public interface INewsModel {
}


text:
<?php

namespace ChurchCRM\Slim\Middleware\Request\Auth;

class AddEventsRoleAuthMiddleware extends BaseAuthRoleMiddleware {

    function hasRole()
    {
        return $this->user->isAddEvent();
    }

    function noRoleMessage()
    {
        return gettext('User must have bAddEvent permissions');
    }
}


text:
namespace OsEngine.Market.Servers.Bitfinex.BitfitnexEntity
{
    public class NewOrderPayload
    {
        public string request { get; set; }
        public string nonce { get; set; }
        public string symbol { get; set; }
        public string amount { get; set; }
        public string price { get; set; }
        public string exchange { get; set; }
        public string side { get; set; }
        public string type { get; set; }
    }
}


text:
CrossWalkAndroidStudio
======================

CrossWalk Project inside of Android Studio

Example project for how to setup Crosswalk inside of Android Studio.

Using Crosswalk version 10


text:
package io.selendroid.server.common.exceptions;

public class NoSuchContextException extends RuntimeException {

  public NoSuchContextException(String detailMessage) {
    super(detailMessage);
  }

  public NoSuchContextException(String detailMessage, Throwable throwable) {
    super(detailMessage, throwable);
  }

  public NoSuchContextException(Throwable throwable) {
    super(throwable);
  }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import {WTFDateField} from 'indico/react/components';

window.setupDateWidget = function setupDateWidget(options) {
  options = $.extend(
    true,
    {
      fieldId: null,
      required: false,
      disabled: false,
      allowClear: false,
      earliest: null,
      latest: null,
      linkedField: {
        id: null,
        notBefore: false,
        notAfter: false,
      },
    },
    options
  );

  // Make sure the results dropdown are displayed above the dialog.
  const field = $(`#${options.fieldId}`);
  field.closest('.ui-dialog-content').css('overflow', 'inherit');
  field.closest('.exclusivePopup').css('overflow', 'inherit');

  ReactDOM.render(
    <WTFDateField
      dateId={`${options.fieldId}-datestorage`}
      required={options.required}
      disabled={options.disabled}
      allowClear={options.allowClear}
      earliest={options.earliest}
      latest={options.latest}
      linkedField={options.linkedField}
    />,
    document.getElementById(options.fieldId)
  );
};


text:
require_relative 'helper'

module Psych
  class TestStringTainted < TestCase
    class Tainted < Handler
      attr_reader :tc

      def initialize tc
        @tc = tc
      end

      def start_document version, tags, implicit
        tags.flatten.each do |tag|
          assert_taintedness tag
        end
      end

      def alias name
        assert_taintedness name
      end

      def scalar value, anchor, tag, plain, quoted, style
        assert_taintedness value
        assert_taintedness tag if tag
        assert_taintedness anchor if anchor
      end

      def start_sequence anchor, tag, implicit, style
        assert_taintedness tag if tag
        assert_taintedness anchor if anchor
      end

      def start_mapping anchor, tag, implicit, style
        assert_taintedness tag if tag
        assert_taintedness anchor if anchor
      end

      def assert_taintedness thing, message = "'#{thing}' should be tainted"
        tc.assert thing.tainted?, message
      end
    end

    class Untainted < Tainted
      def assert_taintedness thing, message = "'#{thing}' should not be tainted"
        tc.assert !thing.tainted?, message
      end
    end

    def setup
      handler = Tainted.new self
      @parser = Psych::Parser.new handler
    end

    def test_tags_are_tainted
      assert_taintedness "%TAG !yaml! tag:yaml.org,2002:\n---\n!yaml!str \"foo\""
    end

    def test_alias
      assert_taintedness  "--- &ponies\n- foo\n- *ponies"
    end

    def test_scalar
      assert_taintedness "--- ponies"
    end

    def test_anchor
      assert_taintedness "--- &hi ponies"
    end

    def test_scalar_tag
      assert_taintedness "--- !str ponies"
    end

    def test_seq_start_tag
      assert_taintedness "--- !!seq [ a ]"
    end

    def test_seq_start_anchor
      assert_taintedness "--- &zomg [ a ]"
    end

    def test_seq_mapping_tag
      assert_taintedness "--- !!map { a: b }"
    end

    def test_seq_mapping_anchor
      assert_taintedness "--- &himom { a: b }"
    end

    def assert_taintedness string
      @parser.parse string.taint
    end
  end

  class TestStringUntainted < TestStringTainted
    def setup
      handler = Untainted.new self
      @parser = Psych::Parser.new handler
    end

    def assert_taintedness string
      @parser.parse string
    end
  end

  class TestStringIOUntainted < TestStringTainted
    def setup
      handler = Untainted.new self
      @parser = Psych::Parser.new handler
    end

    def assert_taintedness string
      @parser.parse StringIO.new(string)
    end
  end

  class TestIOTainted < TestStringTainted
    def assert_taintedness string
      Tempfile.create(['something', 'yml']) {|t|
        t.binmode
        t.write string
        t.close
        File.open(t.path, 'r:bom|utf-8') { |f|
          @parser.parse f
        }
      }
    end
  end
end


text:
@interface DWUploadInfoSetupViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic)UITextField *titleTextField;
@property (strong, nonatomic)UITextField *tagTextField;
@property (strong, nonatomic)UITextField *descriptionTextField;
@property (strong, nonatomic)UITextView *descriptionTextView;

@property (strong, nonatomic)UITableView *tableView;

@end

@implementation DWUploadInfoSetupViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.title = @"填写视频信息";
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction:)]; UIBarButtonItem *uploadItem = [[UIBarButtonItem alloc] initWithTitle:@"上传" style:UIBarButtonItemStylePlain target:self action:@selector(uploadAction:)];

    self.navigationItem.rightBarButtonItem = uploadItem;
    self.navigationItem.leftBarButtonItem = cancelItem;
    CGFloat max = MAX(self.view.frame.size.width, self.view.frame.size.height);
    CGFloat min = MIN(self.view.frame.size.width, self.view.frame.size.height);
    CGRect frame = CGRectMake(0, 0, max, min);
    self.tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        return 84;
    }

    return 46;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellId = @"DWUploadInfoSetupViewControllerCellId";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        switch (indexPath.row) {
            case 0:
                self.titleTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 320, 46)];
                self.titleTextField.placeholder = @"标题 ";
                self.titleTextField.delegate = self;
                self.titleTextField.clearButtonMode = UITextFieldViewModeUnlessEditing;
                [cell.contentView addSubview:self.titleTextField];
                break;

            case 1:
                self.tagTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 320, 46)];
                self.tagTextField.placeholder = @"标签";
                self.tagTextField.delegate = self;
                self.titleTextField.clearButtonMode = UITextFieldViewModeUnlessEditing;
                [cell.contentView addSubview:self.tagTextField];
                break;

            case 2:
                self.descriptionTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 84)];
                [cell.contentView addSubview:self.descriptionTextView];
                self.descriptionTextView.textAlignment  = NSTextAlignmentLeft;
                self.descriptionTextView.text = @"视频简介";
                self.descriptionTextView.font = [UIFont systemFontOfSize:14];
                break;

            default:
                break;
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    return cell;
}

# pragma mark - processer

- (void)cancelAction:(UIBarButtonItem *)item
{
    self.isCancel = YES;
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)uploadAction:(UIBarButtonItem *)item
{
    self.videoTitle = self.titleTextField.text;
    self.videoTag = self.tagTextField.text;
    self.videoDescription = self.descriptionTextField.text;

    if (self.videoTitle == nil
        || [self.videoTitle length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"还没写视频标题(⊙o⊙)哦"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil, nil];
        [alert show];

        return;
    }

    [self.navigationController popViewControllerAnimated:NO];
}

# pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{

    [textField resignFirstResponder];

    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 点击view空白处时,关闭键盘
    [self.titleTextField resignFirstResponder];
    [self.tagTextField resignFirstResponder];
    [self.descriptionTextField resignFirstResponder];
}

@end


text:
package de.uniwue.info6.misc;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.SystemUtils;

import de.uniwue.info6.database.map.User;

/**
 *
 *
 * @author Michael
 */
public class StringTools {

  private static SecureRandom random = new SecureRandom();

  /**
   *
   *
   * @param path
   * @return
   */
  public static String shortenUnixHomePath(String path) {
    if (path.startsWith(SystemUtils.USER_HOME)
        && (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC)) {
      path = path.replaceFirst(SystemUtils.USER_HOME, "~");
    }
    return path;
  }

  /**
   *
   *
   * @param path
   * @return
   */
  public static String shortenUnixHomePathReverse(String path) {
    if (path.startsWith("~/") && (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC)) {
      path = path.replace("~/", SystemUtils.USER_HOME + "/");
    }
    return path;
  }

  /**
   *
   *
   * @return
   */
  public static String nextSessionId() {
    return new BigInteger(130, random).toString(32);
  }

  /**
   *
   *
   * @return
   */
  public static String generatePassword(int numBits, int length) {
    return new BigInteger(numBits, random).toString(length);
  }

  /**
   *
   *
   * @param par
   * @return
   */
  public static boolean parseBoolean(String par) {
    if (par.trim().equalsIgnoreCase("true")) {
      return true;
    }
    return false;
  }

  /**
   *
   *
   * @return
   */
  public static String stripHtmlTags(String text) {
    if (text != null) {
      // strip html tags
      text = text.replaceAll("<[^>]*>", "");
    }
    return text;
  }

  /**
   *
   *
   * @param text
   * @param leftIndex
   * @return
   */
  public static boolean trailingCharacter(String text, int index, boolean left) {
    boolean hasValidTrailingCharacter = false;

    if ((left && index == 0) || (!left && index == text.length()))
      return true;

    while ((left && index != 0) || (!left && index != text.length())) {
      Character c = left ? text.charAt(--index) : text.charAt(index++);
      if (!Character.isWhitespace(c)) {
        if (c == '.')
          return left ? false : true;
        if (c == ';' || c == ',' || c == '`' || c == ')' || c == '(')
          hasValidTrailingCharacter = true;
        index = left ? 0 : text.length();
      } else {
        hasValidTrailingCharacter = true;
      }
    }

    if (hasValidTrailingCharacter)
      return true;
    return false;
  }

  /**
   *
   *
   * @param queryText
   * @param tables
   * @param user
   * @return
   */
  public static String addUserPrefix(String queryText, List<String> tables, User user) {
    LinkedList<Integer> substrings = new LinkedList<Integer>();
    int start = 0, end = queryText.length();
    for (String tab : tables) { // q&d fix
      Matcher matcher = Pattern.compile(tab.trim(), Pattern.CASE_INSENSITIVE).matcher(queryText);
      while (matcher.find()) {
        start = matcher.start(0);
        end = matcher.end(0);
        // String group = matcher.group();
        boolean leftCharacterValid = StringTools.trailingCharacter(queryText, start, true);
        boolean rightCharacterValid = StringTools.trailingCharacter(queryText, end, false);
        if (leftCharacterValid && rightCharacterValid) {
          substrings.add(start);
        }
      }
    }

    Collections.sort(substrings);

    for (int i = substrings.size() - 1; i >= 0; i--) {
      Integer sub = substrings.get(i);
      queryText = queryText.substring(0, sub) + user.getId() + "_"
                  + queryText.substring(sub, queryText.length());
    }

    return queryText;
  }

  /**
   *
   *
   * @return
   */
  public static String stripHtmlTagsForQuestion(String text) {
    if (text != null) {
      text = text.replaceAll("(?i)", "");
      text = text.replaceAll("(?i)<javascript.*?</javascript>", "");
      text = text.replaceAll("(?i)", "");

      String REGEX_FIELD = "<[^>]*>";
      Matcher matcher = Pattern.compile(REGEX_FIELD, Pattern.CASE_INSENSITIVE).matcher(text);
      while (matcher.find()) {
        String snippet = matcher.group();
        String snippetNoSpaces = snippet.replaceAll("[\\s\"\'0-9]", "");

        if (!snippetNoSpaces.equals("
") && !snippetNoSpaces.equals("
")
            && !snippetNoSpaces.equals("") && !snippetNoSpaces.equals("")) {

          if (snippetNoSpaces.startsWith("<span")) {
            if (!snippetNoSpaces.equals("<spanstyle=font-style:italic;>")
                && !snippetNoSpaces.equals("<spanstyle=text-decoration:underline;>")
                && !snippetNoSpaces.equals("<spanstyle=text-decoration:line-through;>")
                && !snippetNoSpaces.equals("<spanstyle=color:rgb(,,);>")) {
              text = text.replace(snippet, "");
            }
          } else {
            text = text.replaceFirst(snippet, "");
          }
        }
      }
    }
    return text;
  }

  /**
   *
   *
   * @return
   */
  public static String stripHtmlTagsForScenario(String text) {
    if (text != null) {
      text = text.replaceAll("(?i)", "");
      text = text.replaceAll("(?i)<javascript.*?</javascript>", "");
      text = text.replaceAll("(?i)", "");

      String REGEX_FIELD = "<[^>]*>";
      Matcher matcher = Pattern.compile(REGEX_FIELD, Pattern.CASE_INSENSITIVE).matcher(text);
      while (matcher.find()) {
        String snippet = matcher.group();
        String snippetNoSpaces = snippet.toLowerCase().replaceAll("[\\s\"\'0-9]", "");

        if (!snippetNoSpaces.equals("
") && !snippetNoSpaces.equals("
")
            && !snippetNoSpaces.equals("") && !snippetNoSpaces.equals("")
            && !snippetNoSpaces.equals("") && !snippetNoSpaces.equals("")) {

          if (snippetNoSpaces.startsWith("<span")) {
            if (!snippetNoSpaces.equals("<spanstyle=font-style:italic;>")
                && !snippetNoSpaces.equals("<spanstyle=text-decoration:underline;>")
                && !snippetNoSpaces.equals("<spanstyle=text-decoration:line-through;>")
                && !snippetNoSpaces.equals("<spanstyle=color:rgb(,,);>")
                && !snippetNoSpaces.equals("<spanstyle=font-weight:bold;>")) {
              text = text.replace(snippet, "");
            }
          } else if (snippetNoSpaces.startsWith("<font")) {
            if (!snippetNoSpaces.equals("<fontsize=>")) {
              text = text.replace(snippet, "");
            }
          } else {
            text = text.replaceFirst(snippet, "");
          }
        }
      }
    }
    return text;
  }

  /**
   *
   *
   * @param path
   * @return
   */
  public static String normalizeFileName(String path) {
    String newName = FilenameUtils.removeExtension(path).toLowerCase();
    return normalize(newName);
  }

  /**
   *
   *
   * @param path
   * @return
   */
  public static String deleteDate(String path) {
    if (path != null) {
      return path.replaceAll("[0-9]{4}_[0-9]{2}_[0-9]{2}-[0-9]{2}_[0-9]{2}_[0-9]{2}", "");
    }
    return null;
  }

  /**
   *
   *
   * @param string
   * @param length
   * @return
   */
  public static String trimToLengthIndicator(String s, int length) {
    if (length < 5) {
      return "[...]";
    }
    if (s.length() > 5 && s.length() > length - 5) {
      return s.substring(0, length - 5) + "[...]";
    } else {
      return s;
    }
  }

  /**
   *
   *
   * @param s
   * @param length
   * @return
   */
  public static String trimToLength(String s, int length) {
    if (s.length() > length) {
      return s.substring(0, length);
    } else {
      return s;
    }
  }

  /**
   *
   *
   * @param stringToSearch
   * @param length
   * @return
   */
  public static String findSnippet(String stringToSearch, String stringToFind, int length) {
    try {
      stringToFind = stringToFind.trim();
      stringToSearch = stringToSearch.trim();
      if (!stringToSearch.toLowerCase().contains(stringToFind.toLowerCase())) {
        return trimToLengthIndicator(stringToSearch, length);
      }

      int mainLength = stringToSearch.length();
      int snippetLength = stringToFind.length();
      String end = "[...]";

      if (length > 5 && snippetLength < length) {
        int index = stringToSearch.toLowerCase().indexOf(stringToFind.toLowerCase());

        if (snippetLength < length && snippetLength + 10 > length) {
          if (snippetLength >= length - 5) {
            return stringToFind.substring(0, length - 5) + end;
          } else {
            return stringToFind + end;
          }
        }

        boolean leftTrim = false, rightTrim = false;
        boolean trimRight = false;
        int spaceLeft = 0, spaceRight = 0;

        spaceLeft = index;
        spaceRight = mainLength - (spaceLeft + snippetLength);

        while ((mainLength > length - 10) || (mainLength > length - 5 && index == 0)) {
          if (trimRight || index == 0) {
            if (spaceRight > 0) {
              stringToSearch = stringToSearch.substring(0, stringToSearch.length() - 1);
              rightTrim = true;
            }
            if (spaceLeft > spaceRight || spaceRight == 0) {
              trimRight = false;
            }
          } else {
            if (spaceLeft > 0) {
              stringToSearch = stringToSearch.substring(1, stringToSearch.length());
              leftTrim = true;
            }
            if (spaceLeft <= spaceRight || spaceLeft == 0) {
              trimRight = true;
            }
          }

          mainLength = stringToSearch.length();
          spaceLeft = stringToSearch.toLowerCase().indexOf(stringToFind.toLowerCase());
          spaceRight = mainLength - (spaceLeft + snippetLength);
        }

        if (rightTrim) {
          stringToSearch += end;
        }
        if (leftTrim) {
          stringToSearch = end + stringToSearch;
        }

        return stringToSearch;
      } else {
        return trimToLengthIndicator(stringToSearch, length);
      }
    } catch (Exception e) {
      return stringToSearch;
    }
  }

  /**
   *
   *
   * @param query
   * @return
   */
  public static String extractIDFromAutoComplete(String query) {
    if (query != null) {
      String[] temp = query.split("]:");
      if (temp.length == 2) {
        return temp[0].replace("[", "").trim();
      }
    }
    return null;
  }

  /**
   *
   *
   * @param path
   * @return
   */
  public static String normalize(String path) {
    if (path != null) {
      try {
        String newName = path.toLowerCase();
        // delete date-field
        newName = newName.replaceAll("[ü}]", "ue").replaceAll("[ä]", "ae").replaceAll("[ö]", "oe")
                  .replaceAll("[ß]", "ss").replaceAll("[^a-z0-9&]", "_").replaceAll("[_]{2,}", "_");

        while (newName.endsWith("_")) {
          newName = newName.substring(0, newName.length() - 1);
        }
        while (newName.startsWith("_")) {
          newName = newName.substring(1, newName.length());
        }
        return newName;
      } catch (Exception e) {

      }
    }
    return path;
  }

  /**
   *
   *
   * @param number
   * @param width
   * @return
   */
  public static String zeroPad(int number, int width) {
    if (number < 100) {
      int wrapAt = (int) Math.pow(10, width);
      return String.valueOf(number % wrapAt + wrapAt).substring(1);
    } else {
      return String.valueOf(number);
    }
  }

  /**
   *
   *
   * @param array
   * @return
   */
  public static String arrayToString(Object[] array) {
    if (array != null) {
      StringBuffer arrayString = new StringBuffer();
      for (int i = 0; i < array.length; i++) {
        arrayString.append(zeroPad(i, 3) + " -- " + String.valueOf(array[i]) + "\n");
      }
      return removeLastLineBreak(arrayString.toString());
    }
    return null;
  }

  /**
   *
   *
   * @param string
   * @return
   */
  public static String removeLastLineBreak(String string) {
    if (string.endsWith("\n"))
      return removeLastCharacters(string, 1);
    return string;
  }

  /**
   *
   *
   * @param stringBuffer
   * @param places
   * @return
   */
  public static StringBuffer removeLastCharacters(StringBuffer stringBuffer, int places) {
    return stringBuffer.replace(stringBuffer.length() - places, stringBuffer.length(), "");
  }

  /**
   *
   *
   * @param string
   * @param places
   * @return
   */
  public static String removeLastCharacters(String string, int places) {
    return string.substring(0, string.length() - places);
  }

  /**
   *
   *
   * @param string
   * @param places
   * @return
   */
  public static String removeFirstCharacters(String string, int places) {
    return string.substring(places, string.length());
  }

  /**
   *
   *
   * @param stringBuffer
   * @param places
   * @return
   */
  public static StringBuffer removeFirstCharacters(StringBuffer stringBuffer, int places) {
    return stringBuffer.replace(0, places, "");
  }

  /**
   *
   *
   * @param original
   * @return
   */
  public static String forgetOneWord(final String original) {
    final String[] originalParts = original.split("\\s");
    final Random random = new Random();
    final String originalPart = originalParts[random.nextInt(originalParts.length - 1)];
    final int index = original.indexOf(originalPart);
    return original.substring(0, index) + original.substring(index + originalPart.length(), original.length());
  }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />

注册

			<form class="mui-input-group">

					账号
					<input id='account' type="text" class="mui-input-clear mui-input" placeholder="请输入账号">

					密码
					<input id='password' type="password" class="mui-input-clear mui-input" placeholder="请输入密码">

					确认
					<input id='password_confirm' type="password" class="mui-input-clear mui-input" placeholder="请确认密码">

					邮箱
					<input id='email' type="email" class="mui-input-clear mui-input" placeholder="请输入邮箱">

			</form>

				<button id='reg' class="mui-btn mui-btn-block mui-btn-primary">注册</button>


text:
<svg class="glyph stroked home"><use xlink:href="#stroked-home"></use></svg>

Penerimaan

Penerimaan

		<form action="<?php echo site_url('akuntansi/penerimaan/index'); ?>" method="post">

	        		<a href="<?php echo site_url('akuntansi/penerimaan/reset_search'); ?>"><button class="btn btn-danger" type="button"> Reset</button>

	      		<input type="text" class="form-control" placeholder="No.bukti/No.SPM/Uraian" name="keyword_penerimaan" value="<?php if($this->session->userdata('keyword_penerimaan')) echo $this->session->userdata('keyword_penerimaan'); ?>">

	        		<button class="btn btn-default" type="submit">Cari</button>

	    </form>

		<a href="<?php echo site_url('akuntansi/penerimaan/input_penerimaan'); ?>"><button type="button" class="btn btn-primary">Isi Penerimaan</button>

					NO
					TANGGAL
					NO.BUKTI
					UNIT
					URAIAN
					AKSI

				<?php foreach($query->result() as $result){ ?>

					<?php echo $no; ?>
					<?php echo date("d/m/Y", strtotime($result->tanggal)); ?>
					<?php echo $result->no_bukti; ?>
					UNIVERSITAS
					<?php echo $result->uraian; ?>

						<?php if($this->session->userdata('level')==1){ ?>
							<?php if($result->flag==1 AND $result->status=='revisi'){ ?>
								<a href="<?php echo site_url('akuntansi/penerimaan/edit_penerimaan/'.$result->id_kuitansi_jadi.'/revisi'); ?>"><button type="button" class="btn btn-sm btn-success">Revisi</button>
							<?php }else{ ?>
								<a href="<?php echo site_url('akuntansi/penerimaan/detail_penerimaan/'.$result->id_kuitansi_jadi.'/lihat'); ?>"><button type="button" class="btn btn-sm btn-danger">Lihat</button>
							<?php } ?>
						<?php }else if($this->session->userdata('level')==2){ ?>
							<?php if($result->flag==1 AND ($result->status=='proses' OR $result->status=='direvisi')){ ?>
								<a href="<?php echo site_url('akuntansi/penerimaan/detail_penerimaan/'.$result->id_kuitansi_jadi.'/evaluasi'); ?>"><button type="button" class="btn btn-sm btn-warning">Verifikasi</button>
							<?php }else{ ?>
								<a href="<?php echo site_url('akuntansi/penerimaan/detail_penerimaan/'.$result->id_kuitansi_jadi.'/lihat'); ?>"><button type="button" class="btn btn-sm btn-danger">Lihat</button>
							<?php } ?>
						<?php }else if($this->session->userdata('level')==3 or $this->session->userdata('level')==8){ ?>
							<a href="<?php echo site_url('akuntansi/penerimaan/edit_penerimaan/'.$result->id_kuitansi_jadi); ?>"><button type="button" class="btn btn-sm btn-success"> Edit</button>
						<?php } ?>

				<?php $no++; } ?>

		<?php echo $halaman; ?>

<?php
function get_pengeluaran($id_kuitansi){
	$ci =& get_instance();

	$query = "SELECT SUM(volume*harga_satuan) AS pengeluaran FROM rsa_kuitansi_detail WHERE id_kuitansi='$id_kuitansi'";
	$q = $ci->db->query($query)->result();
	foreach($q as $result){
		return number_format($result->pengeluaran);
	}
}

function get_unit($unit){
	$ci =& get_instance();
	$ci->db2 = $ci->load->database('rba', true);

	$query = "SELECT * FROM unit WHERE kode_unit='$unit'";
	$q = $ci->db2->query($query)->result();
	foreach($q as $result){
		return $result->alias;
	}
}
?>


text:
namespace base {
class ListValue;
}

// Handler class for Version page operations.
class VersionHandler : public web::WebUIIOSMessageHandler {
 public:
  VersionHandler();
  ~VersionHandler() override;

  // content::WebUIMessageHandler implementation.
  void RegisterMessages() override;

  // Callback for the "requestVersionInfo" message. This asynchronously requests
  // the list of variations.
  void HandleRequestVersionInfo(const base::ListValue* args);

 private:
  DISALLOW_COPY_AND_ASSIGN(VersionHandler);
};

#endif  // IOS_CHROME_BROWSER_UI_WEBUI_VERSION_HANDLER_H_


text:
package gov.samhsa.consent2share.service.reference;

import gov.samhsa.consent2share.domain.reference.LanguageCode;
import gov.samhsa.consent2share.domain.reference.LanguageCodeRepository;
import gov.samhsa.consent2share.service.dto.LookupDto;

import java.util.ArrayList;
import java.util.List;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * The Class LanguageCodeServiceImpl.
 */
@Service
@Transactional
public class LanguageCodeServiceImpl implements LanguageCodeService {

	/** The language code repository. */
	@Autowired
	LanguageCodeRepository languageCodeRepository;

	/** The model mapper. */
	@Autowired
	ModelMapper modelMapper;

	/* (non-Javadoc)
	 * @see gov.samhsa.consent2share.service.reference.LanguageCodeService#findAllLanguageCodes()
	 */
	@Override
	public List<LookupDto> findAllLanguageCodes() {
		List<LookupDto> lookups = new ArrayList<LookupDto>();

		List<LanguageCode> languageCodeList = languageCodeRepository.findAll();

		for (LanguageCode entity : languageCodeList) {
			lookups.add(modelMapper.map(entity, LookupDto.class));
		}
		return lookups;
	}
}


text:
using System;
using System.IO;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

using static System.Console;
using static System.Convert;
using static Parca;

/// This is a custom toolbar we add to the form under test.
class AquaCmds : Form {

	const int
		CTRLOFF = 10, //<= Space between controls.
		CTRLH   = 30,
		CTRLTOP = 10;

	const string
		RECORD    = "Record",
		RECORDING = "Recording",
		REPLAY    = "Replay";

	/// Attaches the aqua commands tool bar to the form under test.
	public static void AttachTo(Form host, Lane lane, bool quiet) {
		var cmds = new AquaCmds(host, lane, quiet);
		cmds.Show();
	}

	/// Helper method to create command buttons.
	static Button CreateBtn(string text, Action onClick, Control previous) {
		var btn = new Button();
		if (previous == null) {
			btn.Left = CTRLOFF;
			btn.Top  = CTRLTOP;
		}
		else {
			btn.Left = previous.Left + previous.Width + CTRLOFF;
			btn.Top = previous.Top;
		}

		btn.Text = text;
		btn.Click += (s, e) => {
			onClick();
		};

		return btn;
	}

	static int SumCtrlsWidth(Form f, int offset) {
		int res = 0;
		foreach(Control ctrl in f.Controls)
			res += ctrl.Width + offset;

		return res;
	}

	void SetPositionOnScreen(Form host) {
		var screen = Screen.FromControl(host);
		Height = (CTRLTOP * 2) + CTRLH;
		Width = SumCtrlsWidth(this, CTRLOFF) + CTRLOFF;

		StartPosition = FormStartPosition.Manual;
		int x = screen.Bounds.Width / 2 - Width / 2;
		int y = 0;
		Location = new Point(x, y);
	}

	static void Replay (string script, Form host, bool quiet) {
		try {
			var inter = new Interpreter();
			inter.Eval(script, host, quiet);
		}
		catch(Exception ex) {
			MessageBox.Show(ex.Message);
		}
	}

	static string GetInitDir() =>
		Path.GetFullPath(Directory.GetCurrentDirectory());

	static string OpenScript() {
		using (var ofd = new OpenFileDialog()) {
			ofd.InitialDirectory = GetInitDir();
			ofd.Filter = "Quality assurance test files (*.qat)|*.qat";
			if (ofd.ShowDialog() == DialogResult.OK) {
				var script = new StringBuilder();
				using (var sr = new StreamReader(ofd.OpenFile())) {
					while(sr.Peek() > 0)
						script.AppendLine(sr.ReadLine());
				}
				return script.ToString();
			}
		}
		return null;
	}

	/// host is the form under test.
	/// lane is some sort of a timeline where changes and SE are reflected.
	public AquaCmds(Form host, Lane lane, bool quiet) {
		Text = "Aqua";
		// Attach
		// Owner = host;
		// Commands
		Button btnRec = null, btnRep = null, btnStop, btnNotes, btnSave;// btnOpen
		Action record, replay, stop, save, takeNote, reset;

		takeNote = ()=> Write("TODO: Add notes.\n");

		reset = () => {
			btnRep.Text    = REPLAY;
			btnRec.Text    = RECORD;
			btnRep.Enabled = true;
			btnRec.Enabled = true;

			lane.IsRecording = false;
		};

		replay = ()=> {
			if (lane.IsRecording) {
				MessageBox.Show("Can't replay while recording.");
				return;
			}

			var script = OpenScript();
			btnRec.Enabled = false;
			Replay(script, host, quiet);
		};

		record = ()=> {
			// TODO: Warn the user when there is an unsaved session. i.e:
			//       Unsaved changes 'll be lost. Wanna save before
			//       start a new session? (or something like that).
			//
			//Each record session have to start fresh.
			// lane.Clear();
			lane.IsRecording = true;
			// =======================================
			btnRec.Text    = RECORDING;
			btnRep.Enabled = false;
		};

		stop = () => {
			reset();
		};

		save = () => {
			if (lane.MovesCount == 0) {
				MessageBox.Show("No moves.");
				return;
			}

			var src = lane.CreateScript();

			using (var sfd = new SaveFileDialog()) {
				sfd.InitialDirectory = GetInitDir();

				sfd.Filter = "Quality assurance test files (*.qat)|*.qat";
				if (sfd.ShowDialog() != DialogResult.OK)
					return;

				Stream strm = null;
				if ((strm = sfd.OpenFile()) != null) {
					using (var sw = new StreamWriter(strm)) {
						sw.Write(src);
						sw.Close();
					}
					strm.Close();
				}
			}
			reset();
		};

		btnRec   = CreateBtn(RECORD, record, null);
		btnRep   = CreateBtn("Replay", replay, btnRec);
		btnStop  = CreateBtn("Stop",   stop, btnRep);
		btnNotes = CreateBtn("Notes",  takeNote, btnStop);
		// btnOpen  = CreateBtn("Open",   open, btnNotes);
		btnSave  = CreateBtn("Save",   save, btnNotes);

		Controls.Add(btnRec);
		Controls.Add(btnRep);
		Controls.Add(btnStop);
		Controls.Add(btnNotes);
		// Controls.Add(btnOpen);
		Controls.Add(btnSave);

		// Position
		FormBorderStyle = FormBorderStyle.None;
		SetPositionOnScreen(host);
	}

}