text:
package com.paypal.svcs.types.ap;

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

import com.paypal.svcs.types.ap.RefundInfo;

/**
 *
 */
public class RefundInfoList{

	/**
	 *
	 *@Required
	 */
	private List<RefundInfo> refundInfo = new ArrayList<RefundInfo>();

	/**
	 * Default Constructor
	 */
	public RefundInfoList (){
	}

	/**
	 * Getter for refundInfo
	 */
	 public List<RefundInfo> getRefundInfo() {
	 	return refundInfo;
	 }

	/**
	 * Setter for refundInfo
	 */
	 public void setRefundInfo(List<RefundInfo> refundInfo) {
	 	this.refundInfo = refundInfo;
	 }

	public static com.paypal.svcs.types.ap.RefundInfoList createInstance(Map<String, String> map, String prefix, int index) {
		com.paypal.svcs.types.ap.RefundInfoList refundInfoList = null;
		int i = 0;
		if (index != -1) {
				if (prefix != null && prefix.length() != 0 && !prefix.endsWith(".")) {
					prefix = prefix + "(" + index + ").";
				}
		} else {
			if (prefix != null && prefix.length() != 0 && !prefix.endsWith(".")) {
				prefix = prefix + ".";
			}
		}

		i = 0;
		while(true) {
			RefundInfo refundInfo =  RefundInfo.createInstance(map, prefix + "refundInfo", i);
			if (refundInfo != null) {
				refundInfoList = (refundInfoList == null) ? new com.paypal.svcs.types.ap.RefundInfoList() : refundInfoList;
				refundInfoList.getRefundInfo().add(refundInfo);
				i++;
			} else {
				break;
			}
		}
		return refundInfoList;
	}

}


text:
/*
 * Particle.cpp
 *
 *  Created on: Nov 1, 2012
 *      Author: arturo
 */

#include "Particle.h"
#include "ofAppRunner.h"
#include "ofGraphics.h"

ofParameter<float> Particle::acc;
ofParameter<int> Particle::msGrow;
ofParameter<int> Particle::msStay;
ofParameter<int> Particle::msDissolve;
ofParameter<float> Particle::sizePerSecond;
int Particle::screenHeight=35;

Particle::Particle(const ofVec2f & pos, const ofColor & color)
:pos(pos)
,size(0)
,alive(true)
,color(color)
,originalColor(color)
,timeCreated(ofGetElapsedTimeMillis())
{
}

void Particle::update(u_long now){
	u_long timeDiff = now - timeCreated;
	if(timeDiff<msGrow){
		float pct = 1-double(timeDiff)/(double)msGrow;
		color.set(ofLerp(originalColor.r,0,pct),
			ofLerp(originalColor.g,33,pct),
			ofLerp(originalColor.b,67,pct));
	}else if(timeDiff>msGrow+msStay && timeDiff<=msGrow+msStay+msDissolve){
		float pct = 1-double(msGrow+msStay+msDissolve-timeDiff)/(double)msDissolve;
		color.set(ofLerp(originalColor.r,0,pct),
				ofLerp(originalColor.g,33,pct),
				ofLerp(originalColor.b,67,pct));
	}else if(timeDiff>msGrow+msStay+msDissolve){
		alive = false;
	}
	u_long totalTime = msGrow+msStay+msDissolve;
	float pct = double(timeDiff)/double(totalTime);
	pct=sqrt(pct);
	size = pct*double(totalTime)*double(sizePerSecond)/1000.;
	//vel.y += acc*ofGetLastFrameTime();
	//pos += vel*ofGetLastFrameTime();
}

void Particle::draw(){
	ofFill();
	ofSetColor(color);
	ofEllipse(pos,size*.5*640./20.,size*.5*480./10.);
}

redpajama_set_name: RedPajamaGithub


text:
const fs = require('fs');
const Bluebird = require('bluebird');

Bluebird.promisifyAll(fs)

//STEP 1: read file sync
/*console.time('sync');
console.log('start');
const data = fs.readFileSync('./data.txt', {encoding: 'utf8'})
console.log(data); // hello world
console.log('end');
console.timeEnd('sync');*/

//STEP 2: read file async

/*console.time('sync');
console.log('start');
fs.readFile('./data.txt', {encoding: 'utf8'}, (error, data) => {
    console.error(error);
    console.log(data); // hello world
});
console.log('end');
console.timeEnd('sync');*/

console.time('sync');
console.log('start');
const file1Promise = fs.readFileAsync('./data.txt', {encoding: 'utf8'});
const file2Promise = fs.readFileAsync('./data2.txt', {encoding: 'utf8'});

const allPromises = Bluebird.all([file1Promise, file2Promise]).then((data) => {
    console.log(data);
});

allPromises.catch((error) => {
    console.log(error);
});

console.log('end');
console.timeEnd('sync');


text:
![HBC Digital logo](https://raw.githubusercontent.com/gilt/Cleanroom/master/Assets/hbc-digital-logo.png)
![Gilt Tech logo](https://raw.githubusercontent.com/gilt/Cleanroom/master/Assets/gilt-tech-logo.png)

# MBToolbox

The Mockingbird Toolbox is an Objective-C-based set of general-purpose utility code for use in iOS, macOS, tvOS and watchOS applications.

The Mockingbird Toolbox is the lowest-level module in the Gilt Groupe's open source Mockingbird project.

MBToolbox is part of the Mockingbird Library from [Gilt Tech](http://tech.gilt.com).

### Xcode compatibility

This is the `master` branch. It **requires Xcode 9.0** to compile.

#### Current status

Branch|Build status
--------|------------------------
[`master`](https://github.com/emaloney/MBToolbox)|[![Build status: master branch](https://travis-ci.org/emaloney/MBToolbox.svg?branch=master)](https://travis-ci.org/emaloney/MBToolbox)

### License

MBToolbox is distributed under [the MIT license](https://github.com/emaloney/MBToolbox/blob/master/LICENSE).

MBToolbox is provided for your use—free-of-charge—on an as-is basis. We make no guarantees, promises or apologies. *Caveat developer.*

### Adding MBToolbox to your project

[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

The simplest way to integrate MBToolbox is with the [Carthage](https://github.com/Carthage/Carthage) dependency manager.

First, add this line to your [`Cartfile`](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile):

```
github "emaloney/MBToolbox" ~> 3.0.0
```

Then, use the `carthage` command to [update your dependencies](https://github.com/Carthage/Carthage#upgrading-frameworks).

Finally, you'll need to [integrate MBToolbox into your project](https://github.com/emaloney/MBToolbox/blob/master/INTEGRATION.md) in order to use [the API](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/index.html) it provides.

Once successfully integrated, just add the following statement to any Objective-C file where you want to use MBToolbox:

```objc
@import MBToolbox;
```

See [the Integration document](https://github.com/emaloney/MBToolbox/blob/master/INTEGRATION.md) for additional details on integrating MBToolbox into your project.

## MBToolbox Reference

The Mockingbird Toolbox includes the following tools, which are compatible with all four Apple platforms—iOS, macOS, tvOS and watchOS—except where noted otherwise:

### Battery & Power Monitoring

The [`MBBatteryMonitor`](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBBatteryMonitor.html) class (iOS only) reports the device's power status and battery level, and also posts events through the `NSNotificationCenter` when these values change.

### Network Monitoring

The [`MBNetworkMonitor`](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBNetworkMonitor.html) class (iOS, macOS, tvOS) provides details about the current status of the network, including:

* Whether the device currently has network connectivity
* Whether the device is currently connected via wifi

On iOS, the class also provides carrier information, such as:

* Whether the device has an associated cellular carrier account
* Whether the device is currently connected through a cellular carrier
* The type of the current cellular connection, if any (eg. GPRS, Edge, HSDPA, LTE, etc.)

The `MBNetworkMonitor` can also be configured to post `NSNotificationCenter` events as network status changes occur.

### Caching

Mockingbird Toolbox provides a simple but extensible caching architecture.

The base of this architecture is provided by [`MBThreadsafeCache`](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBThreadsafeCache.html), which implements a basic memory cache that can be safely shared across threads.

The `MBThreadsafeCache` does not implement an expiration policy. Instead, cache instances can be configured to purge themselves in response to memory warnings.

The [`MBFilesystemCache`](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBFilesystemCache.html) is a subclass of `MBThreadsafeCache` that adds a filesystem backing store to the memory cache.

The storage behavior of an `MBFilesystemCache` instance can be customized through the use of an `MBFilesystemCacheDelegate`. Delegates can be used to override serialization and deserialization of cache objects, and for controlling whether or not a given object is stored in the memory or filesystem component of the cache.

The `MBFilesystemCache` implements an age-based expiration mechanism, but the class also provides ample hooks for subclasses to supply alternate implementations.

### Concurrency & Threading

[The `MBConcurrentReadWriteCoordinator` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBConcurrentReadWriteCoordinator.html) uses Grand Central Dispatch to provide an efficient mechanism for enforcing orderly read/write access to a shared resource. The coordinator ensures that concurrent access to the shared resource follows consistent rules.

[The `MBThreadLocalStorage` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBThreadLocalStorage.html) provides an interface for safely sharing thread-local storage among unrelated units of code.

To prevent key clashes between different code using thread-local storage, values are accessed by specifying the requesting `Class`. Classes can store multiple values by providing an additional key string for each value.

The `MBThreadLocalStorage` class also provides methods that allow treating thread-local storage as a lock-free cache. Objects that are expensive to create, such as `NSDateFormatter` instances, can be cached in thread-local storage without incurring the locking overhead required by a shared object cache like `MBThreadsafeCache`.

### Regular Expressions

To simplify working with regular expressions on iOS, macOS, tvOS and watchOS, the Mockingbird Toolbox provides [an `NSString` class extension](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/NSString+MBRegex.html) and [an `NSMutableString` class extension](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/NSMutableString+MBRegex.html) to help create, manipulate, and execute regular expressions.

These extensions make use of [the `MBRegexCache` singleton](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBRegexCache.html) for caching regular expressions, which can be expensive to create.

### Message Digests

[The `MBMessageDigest` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBMessageDigest.html) provides a high-level API for generating MD5 and SHA-1 secure one-way hashes (also known as *message digests*). Message digests can be created from strings, `NSData` instances, byte arrays, and files.

Class extensions for [`NSString`](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/NSString+MBMessageDigest.html) and [`NSData`](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/NSData+MBMessageDigest.html) are also provided to simplify creating message digests from existing objects.

### Network Activity Indicator

The network activity indicator appearing in an iOS device's status bar is a shared resource the use of which needs to be coordinated if you have, say, multiple network operations running simultaneously on several threads.

The Toolbox provides [the `MBNetworkIndicator` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBNetworkIndicator.html) class (iOS only) to coordinate use of the status bar's network activity indicator.

### Colors

The Toolbox contains [a `UIColor` class extension](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/UIColor+MBToolbox.html) for iOS and tvOS that:

- Determines whether a color is opaque
- Determines whether a color is *light* or *dark* (depending on its brightness value)
- Can create an appropriate highlight color for a given color
- Can create a new color by adjusting an existing color's brightness

The `MBColorTools.h` header file defines a set of macro functions for creating `UIColor` and `CGColorRef` instances from individual 8-bit RGB and RGBA components, as well as from RGB and RGBA hexadecimal values.

### Images

The Toolbox contains a `UIImage` class extension compatible with iOS and tvOS that adds [methods for scaling images](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/UIImage+MBImageScaling.html), as well as [a `UIView` class extension](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/UIView+MBSnapshotImage.html) for capturing the contents of a view as a `UIImage`, `CIImage` or `CGImageRef`.

### Bitmaps

[The `MBBitmapPixelPlane` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBBitmapPixelPlane.html) represents a plane of pixels that can be accessed individually, regardless of the underlying pixel format. This allows direct extraction and manipulation of pixel data within a bitmap.

Empty `MBBitmapPixelPlane` instances can be created directly and populated manually. Instances can also be created using a source `UIImage`, `CGImage` or a bitmap-based `CGContextRef`.

You can use `MBBitmapPixelPlane` on iOS, macOS and tvOS.

### Runtime Services

Certain services available at runtime are expensive to leave enabled for the duration of an application's lifetime.

For example, just having the `UIDevice`'s `batteryMonitoringEnabled` property always set to `YES` can cause *additional* battery drain, because an app that would otherwise remain suspended in the background will instead be periodically activated to process `UIDeviceBatteryLevelDidChangeNotification` and `UIDeviceBatteryStateDidChangeNotification` event notifications.

The best practice for such services is to leave them disabled until they're needed, and then to disable them immediately once they're needed no longer.

If multiple units of code need access to these services, some mechanism is needed to coordinate when these services should be enabled and disabled.

[The `MBServiceManager` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBServiceManager.html) is designed for such cases.

Classes that provide interfaces for shared services adopt [the `MBService` protocol](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Protocols/MBService.html), and clients that need access to that service coordinate by *attaching to* and *detaching from* that service through the `MBServiceManager`.

The `MBBatteryMonitor` and `MBNetworkMonitor` classes are implemented as services in order to minimize their impact on the user's device.

### Rounded Rectangles

[The `MBRoundedRectTools` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBRoundedRectTools.html) provides a set of tools for handling rounded rectangles, including methods to help size corner radii based on rectangle size, and methods for creating `CGPathRef`s that can be used to draw rounded rectangles.

### String Formatting

Mockingbird Toolbox provides [an `NSString` class extension](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/NSString+MBIndentation.html) with methods to indent the individual lines within a string using a single tab, multiple tabs, or an arbitrary prefix string.

The static inline C function `MBForceString()` takes an `id` as a parameter and is guaranteed to return a non-`nil` `NSString`.

The static inline C function `MBTrimString()` takes an `id` as a parameter and is guaranteed to return a non-`nil` `NSString` with no leading or trailing whitespace or newline characters.

[The `MBFieldListFormatter` class](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Classes/MBFieldListFormatter.html) can be used to create lists of fields that are displayed in an easy-to-read format when rendered in a monospaced font.

### String Measurement

For iOS and tvOS, there's also [a `UIFont` class extension](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/Categories/UIFont+MBStringSizing.html) that provides a simple API for performing common text measurement tasks.

### ...and more

There's even more to Mockingbird Toolbox, but we want to leave you with at least a few treats to find on your own!

Discover more in the API documentation below, and also in the freely-available [Mockingbird Toolbox source code](https://github.com/emaloney/MBToolbox/).

### API documentation

For detailed information on using MBToolbox, [API documentation](https://rawgit.com/emaloney/MBToolbox/master/Documentation/API/index.html) is available.

## About

Over the years, Gilt Groupe has used and refined Mockingbird Library as the base for its various Apple Platform projects.

Mockingbird began life as AppFramework, created by Jesse Boyes.

AppFramework found a home at Gilt Groupe and eventually became Mockingbird Library.

In recent years, Mockingbird Library has been developed and maintained by Evan Maloney.

### Acknowledgements

API documentation is generated using [appledoc](http://gentlebytes.com/appledoc/) from [Gentle Bytes](http://gentlebytes.com/).


text:
if test ! $(which brew); then
    echo "Installing homebrew..."
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi

# Update homebrew recipes
printf "Update recipes? [Y/n]: " && read ANS
if [ "${ANS}" = "Y" ]; then
    brew update
fi

# Upgrade all
printf "Upgrade? [Y/n]: " && read ANS
if [ "${ANS}" = "Y" ]; then
    brew upgrade
fi

# Add Repository
brew tap homebrew/dupes
brew tap homebrew/versions
brew tap homebrew/binary
brew tap thoughtbot/formulae
brew tap caskroom/fonts
brew tap caskroom/versions
brew tap xoebus/homebrew-cloudfoundry

packages=(

    # GNU core utilities (those that come with OS X are outdated)
    coreutils

    # GNU `find`, `locate`, `updatedb`, and `xargs`, g-prefixed
    findutils

    # recent versions of some OS X tools
    homebrew/dupes/grep
    #apple-gcc42

    # Shell
    zsh
    bash

    # Multiplexe
    tmux
    reattach-to-user-namespace

    # Git
    git
    hub
    gitsh
    gist
    tig

    # Image
    imagemagick

    # Utils
    autoconf
    proctools
    automake
    rmtrash
    wget
    curl
    tree
    openssl
    libyaml
    readline
    markdown
    nkf
    ag
    direnv

    # Languages
    rbenv
    ruby-build
    go
    python3
    ghc
    scala

    #Database
    mysql
    postgres

    #CF
    spiff

    #Java
    jenv

    #Kubernetes
    kubernetes-cli
)

echo "installing binaries..."
brew install ${packages[@]} && brew cleanup

# Casks
brew cask

# Apps
apps=(

    # Launcher
    alfred

    # Browser
    google-chrome

    # Terminal
    iterm2

    # Communication
    slack
    skype

    # VM
    virtualbox
    vagrant
    vagrant-manager

    # etc ...
    google-backup-and-sync
    flux
)

# Install apps to /Applications
echo "installing apps..."
brew cask install --appdir="/Applications" ${apps[@]}

# We need to link it
brew cask alfred link

# fonts
fonts=(
    font-m-plus
    font-source-code-pro
    font-clear-sans
    font-roboto
    font-fontawesome
)

# install fonts
echo "installing fonts..."
brew cask install ${fonts[@]}

echo  "Installaling Java"
brew cask install java


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pdelvo.Minecraft.Network;

namespace Pdelvo.Minecraft.Protocol.Packets
{
    /// <summary>
    /// </summary>
    /// <remarks>
    /// </remarks>
    [PacketUsage(PacketUsage.ServerToClient)]
    public class CreateScoreboard : Packet
    {
        public string ScoreboardName { get; set; }
        public string ScoreboardDispayText { get; set; }

        /// <summary>
        /// 0: Create/ 1: Remove
        /// </summary>
        public byte CreateRemove { get; set; }

        /// <summary>
        ///   Initializes a new instance of the <see cref="CreateScoreboard" /> class.
        /// </summary>
        /// <remarks>
        /// </remarks>
        public CreateScoreboard()
        {
            Code = 0xCE;
        }

        /// <summary>
        ///   Receives the specified reader.
        /// </summary>
        /// <param name="reader"> The reader. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnReceive(BigEndianStream reader, int version)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            ScoreboardName = reader.ReadString16 ();
            ScoreboardDispayText = reader.ReadString16 ();
            CreateRemove = reader.ReadByte ();
        }

        /// <summary>
        ///   Sends the specified writer.
        /// </summary>
        /// <param name="writer"> The writer. </param>
        /// <param name="version"> The version. </param>
        /// <remarks>
        /// </remarks>
        protected override void OnSend(BigEndianStream writer, int version)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");
            writer.Write(Code);

            writer.Write(ScoreboardName);
            writer.Write(ScoreboardDispayText);
            writer.Write(CreateRemove);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <include
        layout="@layout/layout_beeeon_toolbar"
        />
</android.support.design.widget.AppBarLayout>


text:
package org.apache.camel.component.hdfs;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.ScheduledPollEndpoint;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;

/**
 * For reading/writing from/to an HDFS filesystem using Hadoop 1.x.
 */
@UriEndpoint(scheme = "hdfs", title = "HDFS", syntax = "hdfs:hostName:port/path", consumerClass = HdfsConsumer.class, label = "hadoop,file")
public class HdfsEndpoint extends ScheduledPollEndpoint {

    @UriParam
    private final HdfsConfiguration config;

    @SuppressWarnings("deprecation")
    public HdfsEndpoint(String endpointUri, CamelContext context) throws URISyntaxException {
        super(endpointUri, context);
        this.config = new HdfsConfiguration();
        this.config.parseURI(new URI(endpointUri));
    }

    @Override
    public Consumer createConsumer(Processor processor) throws Exception {
        config.checkConsumerOptions();
        HdfsConsumer answer = new HdfsConsumer(this, processor, config);
        configureConsumer(answer);
        return answer;
    }

    @Override
    public Producer createProducer() {
        config.checkProducerOptions();
        return new HdfsProducer(this, config);
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public HdfsConfiguration getConfig() {
        return config;
    }

}


text:
#import "MessageMil2525cSampleAppDelegate.h"
#import "MessageMil2525cSampleViewController.h"

@implementation MessageMil2525cSampleAppDelegate

@synthesize window;
@synthesize viewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Override point for customization after app launch
    [window setRootViewController:viewController];
    [window makeKeyAndVisible];
}

- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}

@end


text:
package org.flowable.cmmn.test.runtime;

import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import org.flowable.cmmn.api.CallbackTypes;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.engine.impl.runtime.CmmnRuntimeServiceImpl;
import org.flowable.cmmn.engine.test.CmmnDeployment;
import org.flowable.cmmn.engine.test.FlowableCmmnTestCase;
import org.flowable.cmmn.engine.test.impl.CmmnJobTestHelper;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * This class tests {@link CmmnRuntimeServiceImpl} implementation
 */
public class CmmnRuntimeServiceTest extends FlowableCmmnTestCase {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    @CmmnDeployment(resources = "org/flowable/cmmn/test/runtime/oneTaskCase.cmmn")
    public void createCaseInstanceWithCallBacks() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            callbackId("testCallBackId").
            callbackType(CallbackTypes.CASE_ADHOC_CHILD).
            start();

        // in fact it must be possible to set any callbackType and Id
        assertThat(caseInstance.getCallbackType(), is(CallbackTypes.CASE_ADHOC_CHILD));
        assertThat(caseInstance.getCallbackId(), is("testCallBackId"));
    }

    @Test
    @CmmnDeployment(resources = "org/flowable/cmmn/test/runtime/oneTaskCase.cmmn")
    public void createCaseInstanceWithoutCallBacks() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            start();

        // default values for callbacks are null
        assertThat(caseInstance.getCallbackType(), nullValue());
        assertThat(caseInstance.getCallbackId(), nullValue());
    }

    @Test
    @CmmnDeployment(resources = "org/flowable/cmmn/test/runtime/oneTaskCase.cmmn")
    public void updateCaseName() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            start();

        // default name is empty
        assertThat(caseInstance.getName(), nullValue());

        cmmnRuntimeService.setCaseInstanceName(caseInstance.getId(), "My case name");

        caseInstance = cmmnRuntimeService.createCaseInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertEquals(caseInstance.getName(), "My case name");
    }

    @Test
    @CmmnDeployment(resources = "org/flowable/cmmn/test/runtime/oneTaskCase.cmmn")
    public void updateCaseNameSetEmpty() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            start();

        // default name is empty
        assertThat(caseInstance.getName(), nullValue());

        cmmnRuntimeService.setCaseInstanceName(caseInstance.getId(), "My case name");

        caseInstance = cmmnRuntimeService.createCaseInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertEquals(caseInstance.getName(), "My case name");

        cmmnRuntimeService.setCaseInstanceName(caseInstance.getId(), null);

        caseInstance = cmmnRuntimeService.createCaseInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
        assertThat(caseInstance.getName(), nullValue());
    }

    @Test
    @CmmnDeployment(resources = "org/flowable/cmmn/test/runtime/oneTaskCase.cmmn")
    public void createCaseInstanceAsync() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            startAsync();

        assertThat(caseInstance, is(notNullValue()));
        assertThat("Plan items are created asynchronously", this.cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).count(), is(0l));

        CmmnJobTestHelper.waitForJobExecutorToProcessAllJobs(cmmnEngineConfiguration, 1000, 100, true);
        assertThat(this.cmmnRuntimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).count(), is(1l));
    }

    @Test
    public void createCaseInstanceAsyncWithoutDef() {
        expectedException.expect(FlowableIllegalArgumentException.class);
        expectedException.expectMessage("caseDefinitionKey and caseDefinitionId are null");

        cmmnRuntimeService.createCaseInstanceBuilder().
            startAsync();
    }

    @Test
    public void createCaseInstanceAsyncWithNonExistingDefKey() {
        expectedException.expect(FlowableObjectNotFoundException.class);
        expectedException.expectMessage("No case definition found for key nonExistingDefinition");

        cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("nonExistingDefinition").
            startAsync();
    }

    @Test
    public void createCaseInstanceAsyncWithNonExistingDefId() {
        expectedException.expect(FlowableObjectNotFoundException.class);
        expectedException.expectMessage("No case definition found for id nonExistingDefinition");

        cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionId("nonExistingDefinition").
            startAsync();
    }

    @Test
    @CmmnDeployment(resources = "org/flowable/cmmn/test/runtime/oneTaskCase.cmmn")
    public void createCaseInstanceWithFallBack() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            tenantId("flowable").
            fallbackToDefaultTenant().
            start();

        assertThat(caseInstance, is(notNullValue()));
    }

    @Test
    public void createCaseInstanceWithFallBack_DefinitionNotFound() {
        this.expectedException.expect(FlowableObjectNotFoundException.class);
        this.expectedException.expectMessage("Case definition was not found by key 'oneTaskCase'. Fallback to default tenant was also used.");

        cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            tenantId("flowable").
            fallbackToDefaultTenant().
            start();
    }

    @Test
    @CmmnDeployment(resources = "org/flowable/cmmn/test/runtime/oneTaskCase.cmmn")
    public void createCaseInstanceAsyncWithFallBack() {
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            tenantId("flowable").
            fallbackToDefaultTenant().
            startAsync();

        assertThat(caseInstance, is(notNullValue()));
    }

    @Test
    public void createCaseInstanceAsyncWithFallBack_DefinitionNotFound() {
        this.expectedException.expect(FlowableObjectNotFoundException.class);
        this.expectedException.expectMessage("Case definition was not found by key 'oneTaskCase'. Fallback to default tenant was also used.");

        cmmnRuntimeService.createCaseInstanceBuilder().
            caseDefinitionKey("oneTaskCase").
            tenantId("flowable").
            fallbackToDefaultTenant().
            startAsync();
    }

}


text:
package kubeletconfig

import (
	"fmt"
	"path/filepath"
	"time"

	apiv1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	clientset "k8s.io/client-go/kubernetes"
	v1core "k8s.io/client-go/kubernetes/typed/core/v1"
	"k8s.io/client-go/tools/cache"
	"k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig"
	"k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig/validation"

	"k8s.io/kubernetes/pkg/kubelet/kubeletconfig/checkpoint"
	"k8s.io/kubernetes/pkg/kubelet/kubeletconfig/checkpoint/store"
	"k8s.io/kubernetes/pkg/kubelet/kubeletconfig/status"
	utillog "k8s.io/kubernetes/pkg/kubelet/kubeletconfig/util/log"
	utilpanic "k8s.io/kubernetes/pkg/kubelet/kubeletconfig/util/panic"
	utilfs "k8s.io/kubernetes/pkg/util/filesystem"
)

const (
	storeDir = "store"
	// TODO(mtaufen): We may expose this in a future API, but for the time being we use an internal default,
	// because it is not especially clear where this should live in the API.
	configTrialDuration = 10 * time.Minute
)

// Controller manages syncing dynamic Kubelet configurations
// For more information, see the proposal: https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node/dynamic-kubelet-configuration.md
type Controller struct {
	// defaultConfig is the configuration to use if no initConfig is provided
	defaultConfig *kubeletconfig.KubeletConfiguration

	// pendingConfigSource; write to this channel to indicate that the config source needs to be synced from the API server
	pendingConfigSource chan bool

	// configOk manages the KubeletConfigOk condition that is reported in Node.Status.Conditions
	configOk status.ConfigOkCondition

	// informer is the informer that watches the Node object
	informer cache.SharedInformer

	// checkpointStore persists config source checkpoints to a storage layer
	checkpointStore store.Store
}

// NewController constructs a new Controller object and returns it. Directory paths must be absolute.
func NewController(defaultConfig *kubeletconfig.KubeletConfiguration, dynamicConfigDir string) *Controller {
	return &Controller{
		defaultConfig: defaultConfig,
		// channels must have capacity at least 1, since we signal with non-blocking writes
		pendingConfigSource: make(chan bool, 1),
		configOk:            status.NewConfigOkCondition(),
		checkpointStore:     store.NewFsStore(utilfs.DefaultFs{}, filepath.Join(dynamicConfigDir, storeDir)),
	}
}

// Bootstrap attempts to return a valid KubeletConfiguration based on the configuration of the Controller,
// or returns an error if no valid configuration could be produced. Bootstrap should be called synchronously before StartSync.
func (cc *Controller) Bootstrap() (*kubeletconfig.KubeletConfiguration, error) {
	utillog.Infof("starting controller")

	// ALWAYS validate the local config. This makes incorrectly provisioned nodes an error.
	// It must be valid because it is the default last-known-good config.
	utillog.Infof("validating local config")
	if err := validation.ValidateKubeletConfiguration(cc.defaultConfig); err != nil {
		return nil, fmt.Errorf("local config failed validation, error: %v", err)
	}

	// ensure the filesystem is initialized
	if err := cc.initializeDynamicConfigDir(); err != nil {
		return nil, err
	}

	assigned, curSource, reason, err := cc.loadAssignedConfig(cc.defaultConfig)
	if err == nil {
		// set the status to indicate we will use the assigned config
		if curSource != nil {
			cc.configOk.Set(fmt.Sprintf(status.CurRemoteMessageFmt, curSource.APIPath()), reason, apiv1.ConditionTrue)
		} else {
			cc.configOk.Set(status.CurLocalMessage, reason, apiv1.ConditionTrue)
		}

		// update the last-known-good config if necessary, and start a timer that
		// periodically checks whether the last-known good needs to be updated
		// we only do this when the assigned config loads and passes validation
		// wait.Forever will call the func once before starting the timer
		go wait.Forever(func() { cc.checkTrial(configTrialDuration) }, 10*time.Second)

		return assigned, nil
	} // Assert: the assigned config failed to load, parse, or validate

	// TODO(mtaufen): consider re-attempting download when a load/verify/parse/validate
	// error happens outside trial period, we already made it past the trial so it's probably filesystem corruption
	// or something else scary (unless someone is using a 0-length trial period)
	// load from checkpoint

	// log the reason and error details for the failure to load the assigned config
	utillog.Errorf(fmt.Sprintf("%s, error: %v", reason, err))

	// load the last-known-good config
	lkg, lkgSource, err := cc.loadLastKnownGoodConfig(cc.defaultConfig)
	if err != nil {
		return nil, err
	}

	// set the status to indicate that we had to roll back to the lkg for the reason reported when we tried to load the assigned config
	if lkgSource != nil {
		cc.configOk.Set(fmt.Sprintf(status.LkgRemoteMessageFmt, lkgSource.APIPath()), reason, apiv1.ConditionFalse)
	} else {
		cc.configOk.Set(status.LkgLocalMessage, reason, apiv1.ConditionFalse)
	}

	// return the last-known-good config
	return lkg, nil
}

// StartSync launches the controller's sync loops if `client` is non-nil and `nodeName` is non-empty.
// It will always start the Node condition reporting loop, and will also start the dynamic conifg sync loops
// if dynamic config is enabled on the controller. If `nodeName` is empty but `client` is non-nil, an error is logged.
func (cc *Controller) StartSync(client clientset.Interface, eventClient v1core.EventsGetter, nodeName string) {
	if client == nil {
		utillog.Infof("nil client, will not start sync loops")
		return
	} else if len(nodeName) == 0 {
		utillog.Errorf("cannot start sync loops with empty nodeName")
		return
	}

	// start the ConfigOk condition sync loop
	go utilpanic.HandlePanic(func() {
		utillog.Infof("starting ConfigOk condition sync loop")
		wait.JitterUntil(func() {
			cc.configOk.Sync(client, nodeName)
		}, 10*time.Second, 0.2, true, wait.NeverStop)
	})()

	cc.informer = newSharedNodeInformer(client, nodeName,
		cc.onAddNodeEvent, cc.onUpdateNodeEvent, cc.onDeleteNodeEvent)
	// start the informer loop
	// Rather than use utilruntime.HandleCrash, which doesn't actually crash in the Kubelet,
	// we use HandlePanic to manually call the panic handlers and then crash.
	// We have a better chance of recovering normal operation if we just restart the Kubelet in the event
	// of a Go runtime error.
	go utilpanic.HandlePanic(func() {
		utillog.Infof("starting Node informer sync loop")
		cc.informer.Run(wait.NeverStop)
	})()

	// start the config source sync loop
	go utilpanic.HandlePanic(func() {
		utillog.Infof("starting config source sync loop")
		wait.JitterUntil(func() {
			cc.syncConfigSource(client, eventClient, nodeName)
		}, 10*time.Second, 0.2, true, wait.NeverStop)
	})()

}

// loadAssignedConfig loads the Kubelet's currently assigned config,
// based on the setting in the local checkpoint store.
// It returns the loaded configuration, the checkpoint store's config source record,
// a clean success or failure reason that can be reported in the status, and any error that occurs.
// If the local config should be used, it will be returned. You should validate local before passing it to this function.
func (cc *Controller) loadAssignedConfig(local *kubeletconfig.KubeletConfiguration) (*kubeletconfig.KubeletConfiguration, checkpoint.RemoteConfigSource, string, error) {
	source, err := cc.checkpointStore.Current()
	if err != nil {
		return nil, nil, fmt.Sprintf(status.CurFailLoadReasonFmt, "unknown"), err
	}
	// nil source is the signal to use the local config
	if source == nil {
		return local, source, status.CurLocalOkayReason, nil
	}
	// load KubeletConfiguration from checkpoint
	kc, err := cc.checkpointStore.Load(source)
	if err != nil {
		return nil, source, fmt.Sprintf(status.CurFailLoadReasonFmt, source.APIPath()), err
	}
	if err := validation.ValidateKubeletConfiguration(kc); err != nil {
		return nil, source, fmt.Sprintf(status.CurFailValidateReasonFmt, source.APIPath()), err
	}
	return kc, source, status.CurRemoteOkayReason, nil
}

// loadLastKnownGoodConfig loads the Kubelet's last-known-good config,
// based on the setting in the local checkpoint store.
// It returns the loaded configuration, the checkpoint store's config source record,
// and any error that occurs.
// If the local config should be used, it will be returned. You should validate local before passing it to this function.
func (cc *Controller) loadLastKnownGoodConfig(local *kubeletconfig.KubeletConfiguration) (*kubeletconfig.KubeletConfiguration, checkpoint.RemoteConfigSource, error) {
	source, err := cc.checkpointStore.LastKnownGood()
	if err != nil {
		return nil, nil, fmt.Errorf("unable to determine last-known-good config, error: %v", err)
	}
	// nil source is the signal to use the local config
	if source == nil {
		return local, source, nil
	}
	// load from checkpoint
	kc, err := cc.checkpointStore.Load(source)
	if err != nil {
		return nil, source, fmt.Errorf("%s, error: %v", fmt.Sprintf(status.LkgFailLoadReasonFmt, source.APIPath()), err)
	}
	if err := validation.ValidateKubeletConfiguration(kc); err != nil {
		return nil, source, fmt.Errorf("%s, error: %v", fmt.Sprintf(status.LkgFailValidateReasonFmt, source.APIPath()), err)
	}
	return kc, source, nil
}

// initializeDynamicConfigDir makes sure that the storage layers for various controller components are set up correctly
func (cc *Controller) initializeDynamicConfigDir() error {
	utillog.Infof("ensuring filesystem is set up correctly")
	// initializeDynamicConfigDir local checkpoint storage location
	return cc.checkpointStore.Initialize()
}

// checkTrial checks whether the trial duration has passed, and updates the last-known-good config if necessary
func (cc *Controller) checkTrial(duration time.Duration) {
	// when the trial period is over, the assigned config becomes the last-known-good
	if trial, err := cc.inTrial(duration); err != nil {
		utillog.Errorf("failed to check trial period for assigned config, error: %v", err)
	} else if !trial {
		utillog.Infof("assigned config passed trial period, will set as last-known-good")
		if err := cc.graduateAssignedToLastKnownGood(); err != nil {
			utillog.Errorf("failed to set last-known-good to assigned config, error: %v", err)
		}
	}
}

// inTrial returns true if the time elapsed since the last modification of the current config does not exceed `trialDur`, false otherwise
func (cc *Controller) inTrial(trialDur time.Duration) (bool, error) {
	now := time.Now()
	t, err := cc.checkpointStore.CurrentModified()
	if err != nil {
		return false, err
	}
	if now.Sub(t) <= trialDur {
		return true, nil
	}
	return false, nil
}

// graduateAssignedToLastKnownGood sets the last-known-good in the checkpointStore
// to the same value as the current config maintained by the checkpointStore
func (cc *Controller) graduateAssignedToLastKnownGood() error {
	current, err := cc.checkpointStore.Current()
	if err != nil {
		return err
	}
	err = cc.checkpointStore.SetLastKnownGood(current)
	if err != nil {
		return err
	}
	return nil
}


text:
package com.s4game.server.public_.room.entity;

import java.sql.Timestamp;

import com.s4game.core.data.AbsVersion;
import com.s4game.core.data.IEntity;

/**
 * @Author zeusgooogle@gmail.com
 * @sine 2016年9月17日 下午12:12:02
 *
 */
public class Room extends AbsVersion implements IEntity {

    /**
     *
     */
    private static final long serialVersionUID = 5764691377281646396L;

    private long id;

    private String userRoleId;

    /**
     * 房间状态
     */
    private int status;

    /**
     * 总回合数
     */
    private int maxRound;

    /**
     * 当前回合 <= round
     */
    private int curRound;

    /**
     * 是否连中
     */
    private boolean serial;

    /**
     * 是否强制胡牌
     */
    private boolean win;

    private Timestamp createTime;

    private Timestamp logUpdateTime;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUserRoleId() {
        return userRoleId;
    }

    public void setUserRoleId(String userRoleId) {
        this.userRoleId = userRoleId;
    }

    public int getMaxRound() {
        return maxRound;
    }

    public void setMaxRound(int maxRound) {
        this.maxRound = maxRound;
    }

    public boolean isSerial() {
        return serial;
    }

    public void setSerial(boolean serial) {
        this.serial = serial;
    }

    public boolean isWin() {
        return win;
    }

    public void setWin(boolean win) {
        this.win = win;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public int getCurRound() {
        return curRound;
    }

    public void setCurRound(int curRound) {
        this.curRound = curRound;
    }

    public Timestamp getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }

    public Timestamp getLogUpdateTime() {
        return logUpdateTime;
    }

    public void setLogUpdateTime(Timestamp logUpdateTime) {
        this.logUpdateTime = logUpdateTime;
    }

    @Override
    public String getPirmaryKeyName() {
        return "id";
    }

    @Override
    public Object getPrimaryKeyValue() {
        return getId();
    }

    @Override
    public IEntity copy() {
        Room room = new Room();
        room.setId(getId());
        room.setUserRoleId(getUserRoleId());
        room.setStatus(getStatus());
        room.setMaxRound(getMaxRound());
        room.setCurRound(getCurRound());
        room.setSerial(isSerial());
        room.setWin(isWin());
        room.setStatus(getStatus());

        room.setCreateTime(getCreateTime());
        room.setLogUpdateTime(getLogUpdateTime());

        return room;
    }

}


text:
require File.join(File.dirname(__FILE__), "../test_helper")
begin
  require "test/unit"
rescue NameError
  require "minitest"
end

if defined?(Minitest::Test)
  LoofahTestBaseClass = Minitest::Test
else
  LoofahTestBaseClass = Test::Unit::TestCase
end

class PostsTest < LoofahTestBaseClass
  def test_loofah_scrubbing
    post = Post.new :title => "<script>yo dawg</script>", :body => "<script>omgwtfbbq</script>"
    post.valid?
    assert_equal "<script>yo dawg</script>", post.title
    assert_equal "omgwtfbbq", post.body
  end

  def test_no_xss_foliation
    assert ! Post.xss_foliated?
  end
end


text:
@interface RKMacroObject (Compatibility)

- (void)playMacro;

@end


text:
pbc.globalFunctionD['print'] = function(py2block, func, args, keywords, starargs, kwargs, node){
    if (args.length === 1 && keywords.length === 1
        && py2block.identifier(keywords[0].arg) === "end"
        && keywords[0].value._astname === "Str"
        //&& py2block.Str_value(keywords[0].value) === ""
    ){  if(py2block.Str_value(keywords[0].value) === ""){
        var argblock = py2block.convert(args[0]);
        return [block("system_print_inline", func.lineno, {}, {
            'VAR':argblock
        }, {
            "inline": "false"
        })];
        }
        else{
            var argblock = py2block.convert(args[0]);
            return [block("system_print_end", func.lineno, {
            }, {
                'VAR':argblock,
                'END':py2block.convert(keywords[0].value)
            }, {
                "inline": "true"
            })];
        }
    }else if (args.length === 1 && keywords.length === 0) {
        var argblock = py2block.convert(args[0]);
        return [block("system_print", func.lineno, {}, {
            'VAR':argblock
        }, {
            "inline": "false"
        })];
    }else if (args.length != 1 && keywords.length === 0) { //print()
        var d = py2block.convertElements("ADD", args);

        return [block("system_print_many", node.lineno, {
        }, d, {
            "inline": "true",
        }, {
            "@items":args.length
        })];

    }else{
        throw new Error("Incorrect number of arguments");
    }
}

pbc.globalFunctionD['input'] = function(py2block, func, args, keywords, starargs, kwargs, node){
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    var argblock = py2block.convert(args[0]);
    return block("system_input", func.lineno, {}, {
        'VAR':argblock
    }, {
        "inline": "false"
    });
}
pbc.assignD.get('UART')['check_assign'] = function(py2block, node, targets, value) {
    if(value._astname != "Call" || value.func._astname != "Attribute" || value.func.value._astname != "Name"){
        return false;
    }
    var moduleName = py2block.Name_str(value.func.value);
    var funcName = py2block.identifier(value.func.attr);
    if(value._astname === "Call" && moduleName === "machine"
        && funcName === "UART" && value.args.length === 2)
        return true;
    return false;
}

pbc.assignD.get('UART')['create_block'] = function(py2block, node, targets, value){
    pbc.pinType = "serial_print";
    var pinblock = py2block.identifier(value.args[0].n);
    var countblock = py2block.identifier(value.args[1].n);
    pbc.pinType = null;
    return block("serial_softserial", node.lineno, {
        "mode":pinblock,
        'baudrate':countblock
    }, { },
    {
        "inline":"true"
    }
    );
}

function serial_write(mode){
function converter(py2block, func, args, keywords, starargs, kwargs, node){
    if (args.length !== 1) {
        throw new Error("Incorrect number of arguments");
    }
    var astname = args[0]._astname;
    if(astname === "Call"){
        if(args[0].func._astname == "Name" && py2block.Name_str(args[0].func) === "str"){ //serial.write(str("XXX"))
            return [block("serial_print", func.lineno, {
                    "mode":mode
                }, {
                    "CONTENT":py2block.convert(args[0].args[0]),
                }, {
                    "inline": "false"
                })];
        }
    }else if(astname === "BinOp"){
        if(args[0].op.name === "Add" && args[0].right._astname === "Str"
            && py2block.Str_value(args[0].right) === "\r\n"
            && args[0].left._astname === "Call" && args[0].left.func._astname == "Name"
            && py2block.Name_str(args[0].left.func) === "str"
        ){
            if(args[0].left.args[0]._astname === "Call"
                && args[0].left.args[0].func._astname === "Name"
                && py2block.Name_str(args[0].left.args[0].func) in {"hex":16,"bin":2,"oct":8}){
                //serial.write(str(hex(XX)) + "\r\n")
                pbc.inScope = "lcd_init";
                var numblock=py2block.convert(args[0].left.args[0].args[0]);
                pbc.inScope=null;
                return [block("serial_print_hex", func.lineno, {
                     "mode":mode,
                    "STAT":py2block.Name_str(args[0].left.args[0].func),
                }, {
                    "CONTENT":numblock,
                }, {
                    "inline": "true"
                })];
            }else{
                return [block("serial_println", func.lineno, {
                     "mode":mode
                }, {  //serial.write(str("XX") + "\r\n")
                    "CONTENT": py2block.convert(args[0].left.args[0]),
                }, {
                    "inline": "false"
                })];
            }
        }
    }
    return [block("serial_print", func.lineno, {}, {
            "CONTENT":py2block.convert(args[0]),
        }, {
            "inline": "true"
        })];
}
return converter
}
pbc.moduleFunctionD.get('uart0')['write'] = serial_write('0')
pbc.moduleFunctionD.get('uart1')['write'] = serial_write('1')
pbc.moduleFunctionD.get('uart2')['write'] = serial_write('2')

pbc.assignD.get('uart0')['check_assign'] = function (py2block, node, targets, value) {
    var funcName = py2block.identifier(value.func.id);
    if (value._astname === "Call"&& funcName === "UART" && value.args.length === 2)
        return true;
    return false;
}
pbc.assignD.get('uart0')['create_block'] = function (py2block, node, targets, value) {
    pbc.pinType = 'serial_print';
    var argblock1 = py2block.convert(value.args[1])
    mode=targets[0].id.v
    if (mode=="uart0"){
        mode='0'
    }
    else if(mode=="uart1"){
        mode='1'
    }
    else if(mode=="uart2"){
        mode='2'
    }
    return block("serial_softserial", node.lineno, {
            "mode":mode
        }, {
            "CONTENT":py2block.convert(value.args[0]),
            "TEXT":argblock1,
        }, {
            "inline": "true"
        });
}

function getSerial(mode,fun_type){
    function converter(py2block, func, args, keywords, starargs, kwargs, node){
        if(args.length !==0){
            throw new Error("Incorrect number of arguments");
        }
        return block(fun_type, func.lineno, {
            "mode":mode
        }, {
        }, {
        "inline": "true"
       });
    }
     return converter;
}
pbc.moduleFunctionD.get('uart0')['any'] = getSerial('0','serial_any')
pbc.moduleFunctionD.get('uart1')['any'] = getSerial('1','serial_any')
pbc.moduleFunctionD.get('uart2')['any'] = getSerial('2','serial_any')
pbc.moduleFunctionD.get('uart0')['read'] = getSerial('0','serial_readstr')
pbc.moduleFunctionD.get('uart1')['read'] = getSerial('1','serial_readstr')
pbc.moduleFunctionD.get('uart2')['read'] = getSerial('2','serial_readstr')
pbc.moduleFunctionD.get('uart0')['readline'] = getSerial('0','serial_readline')
pbc.moduleFunctionD.get('uart1')['readline'] = getSerial('1','serial_readline')
pbc.moduleFunctionD.get('uart2')['readline'] = getSerial('2','serial_readline')


text:
  <button class="close-button" aria-label="Close menu" type="button" data-close>
    ×
  </button>

      Showcase

Foundation Showcase

Brands

Case Studies

Blog

Buzz

About Foundation

      Develop

Frameworks

Foundation for Sites

Foundation for Email

Develop

HTML Templates

Resources

Building Blocks

Yeti Launch

Contribute

      Tutorials

Tutorials

Lessons

Courses

Custom Training

Certification

Responsive Reading

      Get Involved

Connect

PLZ Halp

Foundation Forum

Events

FAQs

Contribute

Yetinauts

      Docs

Sites Docs

Apps Docs

Email Docs

Getting Started

  <button class="close-button" aria-label="Close menu" type="button" data-close>
    ×
  </button>

Foundation

Dot

ZURB

Com

Slash

Sites


text:
define(["require", "exports"], function (require, exports) {
    "use strict";
    var RouterStub = (function () {
        function RouterStub() {
        }
        RouterStub.prototype.configure = function (handler) {
            handler(this);
        };
        RouterStub.prototype.map = function (routes) {
            this.routes = routes;
        };
        return RouterStub;
    }());
    describe('the App module', function () {
        var sut, mockedRouter;
        beforeEach(function () {
            mockedRouter = new RouterStub();
            sut.configureRouter(mockedRouter, mockedRouter);
        });
        it('contains a router property', function () {
            expect(sut.router).toBeDefined();
        });
        it('configures the router title', function () {
            expect(sut.router.title).toEqual('Aurelia');
        });
        it('should have a welcome route', function () {
            expect(sut.router.routes).toContain({ route: ['', 'welcome'], name: 'welcome', moduleId: 'welcome', nav: true, title: 'Welcome' });
        });
        it('should have a users route', function () {
            expect(sut.router.routes).toContain({ route: 'users', name: 'users', moduleId: 'users', nav: true, title: 'Github Users' });
        });
        it('should have a child router route', function () {
            expect(sut.router.routes).toContain({ route: 'child-router', name: 'child-router', moduleId: 'child-router', nav: true, title: 'Child Router' });
        });
    });
});
//# sourceMappingURL=app.spec.js.map


text:
Chapter 1-4 examples
====================

IPAT Data
---------

This example is shown in Chapter 1.9, page 33-34.

.. nbplot::

    >>> import permute.data as data
    >>> from permute.core import one_sample, two_sample
    >>> from permute.ksample import k_sample, bivariate_k_sample
    >>> from permute.utils import get_prng
    >>> import numpy as np

    >>> prng = get_prng(2019426)
    >>> ipat = data.ipat()
    >>> ipat_res = one_sample(ipat.ya, ipat.yb, stat='mean', alternative='greater', seed=prng)
    >>> print("P-value:", round(ipat_res[0], 4))
    P-value: 0.0002

Job Satisfaction Data
---------------------

This example is shown in Chapter 1.10.3, page 41-42.

.. nbplot::

    >>> job = data.job()
    >>> job_res = two_sample(job.x[job.y == 1], job.x[job.y == 2], stat='mean', reps = 10**5, alternative='greater', seed=prng)
    >>> print("P-value:", round(job_res[0], 4))
    P-value: 0.0003

Worms Data
----------

This example is shown in Chapter 1.11.12, page 47-48.

.. nbplot::

    >>> worms = data.worms()
    >>> res = k_sample(worms.x, worms.y, stat='one-way anova', seed=prng)
    >>> print("ANOVA p-value:", round(res[0], 4))
    ANOVA p-value: 0.0107

Testosterone Data
-----------------

This example is shown in Chapter 2.6.1, page 92-93.

.. nbplot::

    >>> testosterone = data.testosterone()
    >>> x = np.hstack(testosterone.tolist())
    >>> group1 = np.hstack([[i]*5 for i in range(len(testosterone))])
    >>> group2 = np.array(list(range(5))*len(testosterone))
    >>> print(len(group1), len(group2), len(x))
    55 55 55
    >>> res = bivariate_k_sample(x, group1, group2, reps=5000, seed=prng)
    >>> print("ANOVA p-value:", round(res[0], 4))
    ANOVA p-value: 0.0002

Massaro-Blair Data
------------------
This example is shown in Chapter 4.6, page 240.

.. nbplot::

    >>> from permute.npc import npc
    >>> mb = data.massaro_blair()
    >>> sam1 = mb.y[mb.group == 1]
    >>> sam2 = mb.y[mb.group == 2]
    >>> first_moment = two_sample(sam1, sam2, alternative='two-sided', reps=5000, keep_dist=True, seed=42)
    >>> second_moment = two_sample(sam1**2, sam2**2, alternative='two-sided', reps=5000, keep_dist=True, seed=423)
    >>> partial_pvalues = np.array([first_moment[0], second_moment[0]])
    >>> print("Partial p-values:", round(first_moment[0], 3), round(second_moment[0], 3))
    Partial p-values: 0.022 0.01

    >>> npc_distr = np.vstack([first_moment[2], second_moment[2]]).T
    >>> global_p = npc(partial_pvalues, np.abs(npc_distr))
    >>> print("Global p-value:", round(global_p, 4))
    Global p-value: 0.002

Fly Data
--------

This example is shown in Chapter 4.6, page 253.

::

    fly = data.fly()
    vars = fly.dtype.names[1:]
    results = {}
    for col in vars:
        sam1 = fly[col][fly.group == 0]
        sam2 = fly[col][fly.group == 1]
        if col == 'x7':
            results[str(col)] = two_sample(sam1, sam2, keep_dist=True, seed=prng, plus1=True, reps=10**4)
        else:
            results[str(col)] = two_sample(sam1, sam2, keep_dist=True, alternative = 'less', seed=prng, plus1=True, reps=10**4)
    partial_pvalues = np.array(list(map(lambda col: results[col][0], vars)))
    print(np.round(partial_pvalues, 3))
    [0.027 0.226 0.    0.391 0.    0.413 0.098]

    npc_distr = np.array(list(map(lambda col: results[col][2], vars))).T
    npc_distr.shape
    (10000, 7)
    alternatives = ['greater']*6 + ['less']*1
    fisher = npc(partial_pvalues, npc_distr, alternatives=alternatives)
    liptak = npc(partial_pvalues, npc_distr, alternatives=alternatives, combine = 'liptak')
    tippett = npc(partial_pvalues, npc_distr, alternatives=alternatives, combine='tippett')
    print("Fisher combined p-value:", fisher)
    Fisherer combined p-value: 0.0
    print("Liptak combined p-value:", liptak)
    Liptak combined p-value: 0.0
    print("Tippett combined p-value:", tippett)
    Tippett combined p-value: 0.0

Post-hoc conditional power analysis
-----------------------------------

These examples come from Chapter 3.2.1, pages 139-141.

::

    # IPAT data
    alpha = 0.01
    prng = get_prng(78943501)
    effect_est = ipat_res[1]
    print("Estimated difference in means:", effect_est)
    Estimated difference in means: 3.1

    z = ipat.ya - ipat.yb - effect_est
    simulated_pvalues = np.zeros(1000)
    for i in range(1000):
        prng.shuffle(z)
        sim_sam = z.copy() + effect_est
        simulated_pvalues[i] = one_sample(sim_sam, stat='mean', alternative='greater', seed=1234, reps=1000)[0]
    power = np.mean(simulated_pvalues <= alpha)
    print("Estimated power:", power)
    Estimated power: 1.0

    # Job data
    effect_est = job_res[1]
    print("Estimated difference in means:", effect_est)
    Estimated difference in means: 17.29166666666667

    xnorm = job.x
    xnorm[job.y == 1] = job.x[job.y == 1] - effect_est
    simulated_pvalues = np.zeros(1000)
    for i in range(1000):
        prng.shuffle(xnorm)
        sim_sam = xnorm.copy()
        sim_sam[job.y==1] = sim_sam[job.y==1] + effect_est
        simulated_pvalues[i] = two_sample(sim_sam[job.y == 1], sim_sam[job.y == 2], stat='mean', reps = 10**3, alternative='greater', seed=1234)[0]
    power = np.mean(simulated_pvalues <= alpha)
    print("Estimated power:", power)
    Estimated power: 0.96


text:
#import "RelatedRecordEditingSampleViewController.h"

#import <ArcGIS/ArcGIS.h>
#import "NotesViewController.h"
#import "LoadingView.h"

//this is the url for the basemap.
#define kBaseMapServiceURL @"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"

//url for the incidents layer
#define kIncidentsLayerURL @"http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/SanFrancisco/311Incidents/FeatureServer/0"

#pragma mark - Class Extension

@interface RelatedRecordEditingSampleViewController()

@property (nonatomic, strong) IBOutlet AGSMapView *mapView;
@property (nonatomic, strong) AGSFeatureLayer *incidentsLayer;
@property (nonatomic, strong) AGSPopupsContainerViewController* popupVC;
@property (nonatomic, strong) UIBarButtonItem* customActionButton;
@property (nonatomic, strong) LoadingView* loadingView;

@end

#pragma mark - Implementation

@implementation RelatedRecordEditingSampleViewController

@synthesize mapView = _mapView;
@synthesize incidentsLayer = _incidentsLayer;
@synthesize popupVC = _popupVC;
@synthesize loadingView = _loadingView;
@synthesize customActionButton = _customActionButton;

#pragma mark -  UIView methods

// in iOS7 this gets called and hides the status bar so the view does not go under the top iPhone status bar
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)viewDidLoad {

    //creating a tiled service with the base map url
    NSURL *mapUrl = [NSURL URLWithString:kBaseMapServiceURL];
	AGSTiledMapServiceLayer *tiledLyr = [AGSTiledMapServiceLayer tiledMapServiceLayerWithURL:mapUrl];

    //add the tiled layer to the map view
	[self.mapView addMapLayer:tiledLyr withName:@"Tiled Layer"];

    //Zooming to an initial envelope with the specified spatial reference of the map.
    //this is the San Francisco extent.
	AGSSpatialReference *sr = [AGSSpatialReference spatialReferenceWithWKID:102100];
	AGSEnvelope *env = [AGSEnvelope envelopeWithXmin:-13639984
                                                ymin:4537387
                                                xmax:-13606734
                                                ymax:4558866
									spatialReference:sr];
	[self.mapView zoomToEnvelope:env animated:YES];

    //Set up the map view
    self.mapView.callout.delegate = self;

    //setup the incidents layer as a feature layer and add it to the map
    self.incidentsLayer = [AGSFeatureLayer featureServiceLayerWithURL:[NSURL URLWithString:kIncidentsLayerURL] mode:AGSFeatureLayerModeOnDemand];
    self.incidentsLayer.outFields = [NSArray arrayWithObject:@"*"];
    self.incidentsLayer.calloutDelegate = self.incidentsLayer;

    [self.mapView addMapLayer:self.incidentsLayer withName:@"Incidents"];

    //setting the custom action button which will be later used to display related notes of an incident
    self.customActionButton  = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"pencil.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(displayIncidentNotes)];

    [super viewDidLoad];
}

#pragma mark - AGSCalloutDelegate methods

- (void) didClickAccessoryButtonForCallout:		(AGSCallout *) 	callout {

    AGSGraphic* graphic = (AGSGraphic*)callout.representedObject;
    self.incidentsLayer = (AGSFeatureLayer*) graphic.layer;

    //Show popup for the graphic because the user tapped on the callout accessory button
    //this is a client side popup based on the graphic that was selected.
    AGSPopupInfo *info = [AGSPopupInfo popupInfoForGraphic:graphic];
    self.popupVC = [[AGSPopupsContainerViewController alloc] initWithPopupInfo:info graphic:graphic usingNavigationControllerStack:NO];
    self.popupVC.delegate = self;
    self.popupVC.actionButton = self.customActionButton; //set the custom action button.
    self.popupVC.modalTransitionStyle =  UIModalTransitionStyleFlipHorizontal;

    //If iPad, use a modal presentation style
    if([[AGSDevice currentDevice] isIPad])
        self.popupVC.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:self.popupVC animated:YES completion:nil];

}

#pragma mark -  AGSPopupsContainerDelegate methods

- (void)popupsContainerDidFinishViewingPopups:(id) popupsContainer {
    //dismiss the popups view controller
    [self dismissViewControllerAnimated:YES completion:nil];
    self.popupVC = nil;
}

#pragma mark - Helper

- (void) warnUserOfErrorWithMessage:(NSString*) message {
    //Display an alert to the user
    [[[UIAlertView alloc] initWithTitle:@"Error" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
}

- (void)displayIncidentNotes
{
    //get the current popup.
    AGSPopup *currentPopup = self.popupVC.currentPopup;

    BOOL exists;
    //obtain the OID of the current popup graphic
    NSNumber *incidentOID = [NSNumber numberWithInt:[currentPopup.graphic attributeAsIntegerForKey:@"objectid" exists:&exists]];

    //instantiate the notes view to show the related notes
    NotesViewController *controller = [[NotesViewController alloc] initWithIncidentOID:incidentOID incidentLayer:self.incidentsLayer];
    controller.delegate = self;
    [self.popupVC presentViewController:controller animated:YES completion:nil];
}

#pragma mark - NotesViewControllerDelegate

- (void)didFinishWithNotes
{
    //dismiss the notes view.
    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark -

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    self.customActionButton = nil;
}

@end


text:
package org.apache.flink.formats.avro.registry.confluent;

import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.formats.avro.AvroRowDataDeserializationSchema;
import org.apache.flink.formats.avro.AvroRowDataSerializationSchema;
import org.apache.flink.formats.avro.AvroToRowDataConverters;
import org.apache.flink.formats.avro.RowDataToAvroConverters;
import org.apache.flink.formats.avro.typeutils.AvroSchemaConverter;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.CatalogTableImpl;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.connector.sink.DynamicTableSink;
import org.apache.flink.table.connector.source.DynamicTableSource;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.factories.FactoryUtil;
import org.apache.flink.table.factories.TestDynamicTableFactory;
import org.apache.flink.table.runtime.connector.source.ScanRuntimeProviderContext;
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
import org.apache.flink.table.types.logical.RowType;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

import static org.apache.flink.core.testutils.FlinkMatchers.containsCause;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

/**
 * Tests for the {@link RegistryAvroFormatFactory}.
 */
public class RegistryAvroFormatFactoryTest {
	private static final TableSchema SCHEMA = TableSchema.builder()
			.field("a", DataTypes.STRING())
			.field("b", DataTypes.INT())
			.field("c", DataTypes.BOOLEAN())
			.build();
	private static final RowType ROW_TYPE = (RowType) SCHEMA.toRowDataType().getLogicalType();
	private static final String SUBJECT = "test-subject";
	private static final String REGISTRY_URL = "http://localhost:8081";

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void testDeserializationSchema() {
		final AvroRowDataDeserializationSchema expectedDeser =
				new AvroRowDataDeserializationSchema(
						ConfluentRegistryAvroDeserializationSchema.forGeneric(
								AvroSchemaConverter.convertToSchema(ROW_TYPE),
								REGISTRY_URL),
						AvroToRowDataConverters.createRowConverter(ROW_TYPE),
						InternalTypeInfo.of(ROW_TYPE));

		final DynamicTableSource actualSource = createTableSource(getDefaultOptions());
		assertThat(actualSource, instanceOf(TestDynamicTableFactory.DynamicTableSourceMock.class));
		TestDynamicTableFactory.DynamicTableSourceMock scanSourceMock =
				(TestDynamicTableFactory.DynamicTableSourceMock) actualSource;

		DeserializationSchema<RowData> actualDeser = scanSourceMock.valueFormat
				.createRuntimeDecoder(
						ScanRuntimeProviderContext.INSTANCE,
						SCHEMA.toRowDataType());

		assertEquals(expectedDeser, actualDeser);
	}

	@Test
	public void testSerializationSchema() {
		final AvroRowDataSerializationSchema expectedSer =
				new AvroRowDataSerializationSchema(
						ROW_TYPE,
						ConfluentRegistryAvroSerializationSchema.forGeneric(
								SUBJECT,
								AvroSchemaConverter.convertToSchema(ROW_TYPE),
								REGISTRY_URL),
						RowDataToAvroConverters.createRowConverter(ROW_TYPE));

		final DynamicTableSink actualSink = createTableSink(getDefaultOptions());
		assertThat(actualSink, instanceOf(TestDynamicTableFactory.DynamicTableSinkMock.class));
		TestDynamicTableFactory.DynamicTableSinkMock sinkMock =
				(TestDynamicTableFactory.DynamicTableSinkMock) actualSink;

		SerializationSchema<RowData> actualSer = sinkMock.valueFormat
				.createRuntimeEncoder(
						null,
						SCHEMA.toRowDataType());

		assertEquals(expectedSer, actualSer);
	}

	@Test
	public void testMissingSubjectForSink() {
		thrown.expect(ValidationException.class);
		thrown.expect(
				containsCause(
						new ValidationException("Option avro-confluent.schema-registry.subject "
								+ "is required for serialization")));

		final Map<String, String> options =
				getModifiedOptions(opts -> opts.remove("avro-confluent.schema-registry.subject"));

		createTableSink(options);
	}

	// ------------------------------------------------------------------------
	//  Utilities
	// ------------------------------------------------------------------------

	/**
	 * Returns the full options modified by the given consumer {@code optionModifier}.
	 *
	 * @param optionModifier Consumer to modify the options
	 */
	private Map<String, String> getModifiedOptions(Consumer<Map<String, String>> optionModifier) {
		Map<String, String> options = getDefaultOptions();
		optionModifier.accept(options);
		return options;
	}

	private Map<String, String> getDefaultOptions() {
		final Map<String, String> options = new HashMap<>();
		options.put("connector", TestDynamicTableFactory.IDENTIFIER);
		options.put("target", "MyTarget");
		options.put("buffer-size", "1000");

		options.put("format", RegistryAvroFormatFactory.IDENTIFIER);
		options.put("avro-confluent.schema-registry.subject", SUBJECT);
		options.put("avro-confluent.schema-registry.url", REGISTRY_URL);
		return options;
	}

	private DynamicTableSource createTableSource(Map<String, String> options) {
		return FactoryUtil.createTableSource(
				null,
				ObjectIdentifier.of("default", "default", "t1"),
				new CatalogTableImpl(SCHEMA, options, "mock source"),
				new Configuration(),
				RegistryAvroFormatFactoryTest.class.getClassLoader());
	}

	private DynamicTableSink createTableSink(Map<String, String> options) {
		return FactoryUtil.createTableSink(
				null,
				ObjectIdentifier.of("default", "default", "t1"),
				new CatalogTableImpl(SCHEMA, options, "mock sink"),
				new Configuration(),
				RegistryAvroFormatFactoryTest.class.getClassLoader());
	}
}


text:
ALTER TABLE `?:conf_class_descriptions` CHANGE `lang_code` `lang_code` char(2) NOT NULL DEFAULT '';
UPDATE `?:conf_class_descriptions` SET `lang_code` = LOWER(`lang_code`);
UPDATE `?:conf_class_descriptions` SET `lang_code` = 'sl' WHERE `lang_code` = 'si';
ALTER TABLE `?:conf_group_descriptions` CHANGE `lang_code` `lang_code` char(2) NOT NULL DEFAULT '';
UPDATE `?:conf_group_descriptions` SET `lang_code` = LOWER(`lang_code`);
UPDATE `?:conf_group_descriptions` SET `lang_code` = 'sl' WHERE `lang_code` = 'si';
ALTER TABLE `?:conf_step_descriptions` CHANGE `lang_code` `lang_code` char(2) NOT NULL DEFAULT '';
UPDATE `?:conf_step_descriptions` SET `lang_code` = LOWER(`lang_code`);
UPDATE `?:conf_step_descriptions` SET `lang_code` = 'sl' WHERE `lang_code` = 'si';


text:
require 'pork'
require 'pork/more'
extend Pork::API
Pork.loaded
Pork.autorun


text:
package endpoints

import "context"

import "github.com/go-kit/kit/endpoint"

import "github.com/go-kit/kit/cmd/kitgen/testdata/underscores/default/service"

type FooRequest struct {
	I int
}
type FooResponse struct {
	I   int
	Err error
}

func MakeFooEndpoint(s service.Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(FooRequest)
		i, err := s.Foo(ctx, req.I)
		return FooResponse{I: i, Err: err}, nil
	}
}

type Endpoints struct {
	Foo endpoint.Endpoint
}


text:
__author__ = 'Tom Schaul, tom@idsia.ch'

from random import choice

from captureplayer import CapturePlayer

class RandomCapturePlayer(CapturePlayer):
    """ do random moves in the capture game"""

    def getAction(self):
        return [self.color, choice(self.game.getLegals(self.color))]


text:
#region S# License

#endregion S# License
namespace StockSharp.Algo.Derivatives
{
	using System;
	using System.Collections.Generic;

	using StockSharp.BusinessEntities;
	using StockSharp.Messages;
	using StockSharp.Localization;

	/// <summary>
	/// The synthetic positions builder.
	/// </summary>
	public class Synthetic
	{
		private readonly Security _security;
		private readonly ISecurityProvider _provider;

		/// <summary>
		/// Initializes a new instance of the <see cref="Synthetic"/>.
		/// </summary>
		/// <param name="security">The instrument (the option or the underlying asset).</param>
		/// <param name="provider">The provider of information about instruments.</param>
		public Synthetic(Security security, ISecurityProvider provider)
		{
			if (security == null)
				throw new ArgumentNullException(nameof(security));

			if (provider == null)
				throw new ArgumentNullException(nameof(provider));

			_security = security;
			_provider = provider;
		}

		private Security Option
		{
			get
			{
				_security.CheckOption();
				return _security;
			}
		}

		/// <summary>
		/// To get the synthetic position to buy the option.
		/// </summary>
		/// <returns>The synthetic position.</returns>
		public KeyValuePair<Security, Sides>[] Buy()
		{
			return Position(Sides.Buy);
		}

		/// <summary>
		/// To get the synthetic position to sale the option.
		/// </summary>
		/// <returns>The synthetic position.</returns>
		public KeyValuePair<Security, Sides>[] Sell()
		{
			return Position(Sides.Sell);
		}

		/// <summary>
		/// To get the synthetic position for the option.
		/// </summary>
		/// <param name="side">The main position direction.</param>
		/// <returns>The synthetic position.</returns>
		public KeyValuePair<Security, Sides>[] Position(Sides side)
		{
			var asset = Option.GetUnderlyingAsset(_provider);

			return new[]
			{
				new KeyValuePair<Security, Sides>(asset, Option.OptionType == OptionTypes.Call ? side : side.Invert()),
				new KeyValuePair<Security, Sides>(Option.GetOppositeOption(_provider), side)
			};
		}

		/// <summary>
		/// To get the option position for the underlying asset synthetic buy.
		/// </summary>
		/// <param name="strike">Strike.</param>
		/// <returns>The option position.</returns>
		public KeyValuePair<Security, Sides>[] Buy(decimal strike)
		{
			return Buy(strike, GetExpiryDate());
		}

		/// <summary>
		/// To get the option position for the underlying asset synthetic buy.
		/// </summary>
		/// <param name="strike">Strike.</param>
		/// <param name="expiryDate">The date of the option expiration.</param>
		/// <returns>The option position.</returns>
		public KeyValuePair<Security, Sides>[] Buy(decimal strike, DateTimeOffset expiryDate)
		{
			return Position(strike, expiryDate, Sides.Buy);
		}

		/// <summary>
		/// To get the option position for synthetic sale of the base asset.
		/// </summary>
		/// <param name="strike">Strike.</param>
		/// <returns>The option position.</returns>
		public KeyValuePair<Security, Sides>[] Sell(decimal strike)
		{
			return Sell(strike, GetExpiryDate());
		}

		/// <summary>
		/// To get the option position for synthetic sale of the base asset.
		/// </summary>
		/// <param name="strike">Strike.</param>
		/// <param name="expiryDate">The date of the option expiration.</param>
		/// <returns>The option position.</returns>
		public KeyValuePair<Security, Sides>[] Sell(decimal strike, DateTimeOffset expiryDate)
		{
			return Position(strike, expiryDate, Sides.Sell);
		}

		/// <summary>
		/// To get the option position for the synthetic base asset.
		/// </summary>
		/// <param name="strike">Strike.</param>
		/// <param name="expiryDate">The date of the option expiration.</param>
		/// <param name="side">The main position direction.</param>
		/// <returns>The option position.</returns>
		public KeyValuePair<Security, Sides>[] Position(decimal strike, DateTimeOffset expiryDate, Sides side)
		{
			var call = _security.GetCall(_provider, strike, expiryDate);
			var put = _security.GetPut(_provider, strike, expiryDate);

			return new[]
			{
				new KeyValuePair<Security, Sides>(call, side),
				new KeyValuePair<Security, Sides>(put, side.Invert())
			};
		}

		private DateTimeOffset GetExpiryDate()
		{
			if (_security.ExpiryDate == null)
				throw new InvalidOperationException(LocalizedStrings.Str712);

			return _security.ExpiryDate.Value;
		}
	}
}


text:
/**
 * Encodes a list of strings to a single string.
 *
 * @param {string[]} strs
 * @return {string}
 */
var encode = function(strs) {
  return strs.reduce((res, str) => res += `${str.length}|${str}`, '');
};

/**
 * Decodes a single string to a list of strings.
 *
 * @param {string} s
 * @return {string[]}
 */
var decode = function(s) {
  const res = [];
  for (let ii = 0; ii < s.length; ii++) {
    const brk = s.indexOf('|', ii);
    const size = parseInt(s.slice(ii, brk));
    res.push(s.substr(brk + 1, size));
    ii = brk + size;
  }
  return res;
};

/**
 * Your functions will be called as such:
 * decode(encode(strs));
 */

console.log(['test', '"', '\'', '\\'])
console.log(decode(encode(['test', '"', '\'', '\\'])));

console.log([])
console.log(decode(encode([])));

console.log(['test'])
console.log(decode(encode(['test'])));