text:
We've made it very easy to track messages and conversations within your Slack bot (built with [bot-kit](https://github.com/howdyai/botkit)), so you can analyze the usage of your bot.

If you have custom needs, you can always fork this project and make modifications.

Read to get started? [Create a free Keen IO account](https://keen.io/signup?s=gh-botkit-readme) to grab your projectId and writeKey.

## Install

Keen IO Bot-Kit is available via NPM.

```bash
npm install keen-botkit --save
```

If you want to use the example code, you can also clone it directly from Git.

```bash
git clone git@github.com:nemo/keen-botkit.git
```

Note that after cloning, you'll have to install the dependencies (which is just [keen-js](https://github.com/keen/keen-js):

```bash
npm install
```

Look at [example section](#example) for how to use the example.

## Usage

The integration works by adding middleware to Botkit using its [middleware system](https://github.com/howdyai/botkit#middleware). We intersect every interaction and send an event to Keen IO.

Specifically, on the `send` and `receive` middleware. To initialize the middleware, you have to pass an initialized Keen IO client from [keen-js](https://github.com/keen/keen-js)):

```javascript
var KeenBotKitIntegration = require('keen-botkit');

// Initialize Keen IO client
var client = new Keen({
    projectId: "<projectId>",
    writeKey: "<writeKey>"
});

// prepare middleware
var receiveMiddleware = KeenBotKitIntegration.botKitReceiveMiddleware(client);
var sendMiddleware = KeenBotKitIntegration.botKitSendMiddleware(client);
```

And then simply apply the middleware to your Botkit controller:

```javascript
var controller = Botkit.slackbot({
    debug: true,
});

controller.middleware.receive.use(receiveMiddleware);
controller.middleware.send.use(sendMiddleware);
```
### Collection Name

By default, the middleware sent events to collections named `message_received` and `message_sends` for received messages and sent messages respectively. You can modify this behavior by passing in a `collection` option:

```javascript
var KeenBotKitIntegration = require('keen-botkit');

var receiveMiddleware = KeenBotKitIntegration.botKitReceiveMiddleware(client, {
  collection: 'user_messages'
});

var sendMiddleware = KeenBotKitIntegration.botKitSendMiddleware(client, {
  collection: 'bot_messages'
});
```

### Payload

In the spirit of customizability, you can modify the payload that is sent to Keen by providing a `payload` object or function to modify the payload before it goes out:

```javascript
var KeenBotKitIntegration = require('keen-botkit');

// Works for both botKitSendMiddleware and botKitReceiveMiddleware
var sendMiddleware = KeenBotKitIntegration.botKitSendMiddleware(client, {
  payload: function(message, callback) {
    // Modify message or pass your own payload
    message._user_id = '10';

    callback(null, message);
  }
});

var sendMiddleware = KeenBotKitIntegration.botKitSendMiddleware(client, {
  payload: {
    static_attribute: 9000
  }
});
```

### Debug

By default, errors are logged. But if you want to get some logs on successful event saves – just pass in `debug: true` as the second argument when you initialize the middleware:

```javascript
var KeenBotKitIntegration = require('keen-botkit');

var receiveMiddleware = KeenBotKitIntegration.botKitReceiveMiddleware(client, {debug: true});
var sendMiddleware = KeenBotKitIntegration.botKitSendMiddleware(client, {debug: true});
```

## Example

There's a short example included in the [slack_bot_example.js](https://github.com/nemo/keen-botkit/blob/master/slack_bot_example.js) file.

Note that you have to get a [Bot token from Slack](http://my.slack.com/services/new/bot) and then run the example from the command line:

```bash
token=<MY TOKEN> node slack_bot_example.js
```

If you want to view the events that are sent to Keen IO on your own account, you should replace the credentials on [line 79](https://github.com/nemo/keen-botkit/blob/master/slack_bot_example.js#L79).

## Contributing

This is an open source project that started within the Keen IO Community - [you can read more about its creator here](https://medium.com/@ngardideh/tracking-conversations-with-botkit-and-keen-io-63a9209a12da#.s11jcdoo8). We'd love future involvement from the community! 💖 If you are interested in getting involved, please see [CONTRIBUTING.md](CONTRIBUTING.md) to get started.


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
  ~
  -->

<Module specificationVersion="1">

    <ModulePrefs title="Twitter - OAuth1 App Example"
                 description="Uses OAuth1 in an App with an OAuth Access Token Proxy"
                 author="Ryan Rutan"
                 authoraffiliation="Jive Software"
                 authoremail="ryan.rutan@jivesoftware.com">

        <Link rel="favicon"    href="images/icon16.png" />
        <Link rel="Icon"       href="images/icon16.png" />
        <Link rel="MediumIcon" href="images/icon48.png" />
        <Link rel="LargeIcon"  href="images/icon128.png" />

        <!-- Commonly used features -->
        <Require feature="dynamic-height" />
        <Require feature="dynamic-width" />
        <Require feature="jive-core-v2" />
        <Require feature="jquery-1.6" />
        <Require feature="osapi"/>
        <Require feature="settitle"/>
        <Require feature="views" />
        <Require feature="setprefs" />
        <Require feature="embedded-experiences"/>
        <Require feature="selection" />
        <Require feature="oauthpopup" />
        <Require feature="jive-core-v2" />
        <Require feature="jive-core-v3"/>
        <Require feature="minimessage"/>
        <Require feature="jive-connects-v1">
            <Param name="alias:twitter-oauth-example|title:Twitter OAuth Example">jive:service://developers.jivesoftware.com/examples/oauth/1/twitter?version=1</Param>
        </Require>

        <!--
        <OAuth>
            <Service name="twitter">
                <Access url="https://api.twitter.com/oauth/access_token" method="POST" />
                <Request url="https://api.twitter.com/oauth/request_token" method="POST" />
                <Authorization url="http://jivedev.ryanrutan.com:18099/oauth/twitter/authorize" />
            </Service>
        </OAuth>
        -->

    </ModulePrefs>

    <Content type="html" view="canvas" href="canvas.jsp" preferred_height="200" />

</Module>

redpajama_set_name: RedPajamaGithub


text:
	_label_

		<button id="_id__download" onclick="download($('#_id_').attr('val'));return false;" class="btn btn-mini btn-inverse" type="button" style="margin-left:30px;margin-top:3px;display:none;">Download</button>
		<button id="_id__upload" onclick="showUploadDialog('_id___rand_','Upload Attachment','_group_',_userId_,'_id_','html','name','all');return false;" class="btn btn-mini btn-inverse" type="button" style="margin-top:3px;">Upload</button>


text:
@import Foundation;

//! Project version number for ExtendedFoundation.
FOUNDATION_EXPORT double ExtendedFoundationVersionNumber;

//! Project version string for ExtendedFoundation.
FOUNDATION_EXPORT const unsigned char ExtendedFoundationVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <ExtendedFoundation/PublicHeader.h>


text:
'use strict';

// YarnDelivery controller
angular.module('yarn-deliveries').controller('YarnDeliveriesController', ['$scope', '$stateParams', '$location', 'Authentication', 'YarnDeliveries',
	function($scope, $stateParams, $location, Authentication, YarnDeliveries) {
		$scope.authentication = Authentication;

		// Create new YarnDelivery
		$scope.create = function() {
			// Create new YarnDelivery object
			var yarndelivery = new YarnDeliveries ({

        dCNo: this.dCNo,

        dCDate: this.dCDate,

        party: this.party,

        jobNo: this.jobNo,

        jobDate: this.jobDate,

        knitter: this.knitter,

        sNo: this.sNo,

        description: this.description,

        colour: this.colour,

        code: this.code,

        rate: this.rate,

        gSM: this.gSM,

        lLength: this.lLength,

        gG: this.gG,

        mill: this.mill,

        count: this.count,

        dIA: this.dIA,

        programmeKgs: this.programmeKgs,

        requiredKgs: this.requiredKgs,

        remarks: this.remarks,

        created: Date.now

			});

			// Redirect after save
			yarndelivery.$save(function(response) {
				$location.path('yarn-deliveries/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing YarnDelivery
		$scope.remove = function(yarndelivery) {
			if ( yarndelivery ) {
				yarndelivery.$remove();

				for (var i in $scope.YarnDeliveries) {
					if ($scope.yarndeliveries [i] === yarndelivery) {
						$scope.yarndeliveries.splice(i, 1);
					}
				}
			} else {
				$scope.yarndelivery.$remove(function() {
					$location.path('yarn-deliveries');
				});
			}
		};

		// Update existing YarnDelivery
		$scope.update = function() {
			var yarndelivery = $scope.yarndelivery;

			yarndelivery.$update(function() {
				$location.path('yarn-deliveries/' + yarndelivery._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of YarnDelivery
		$scope.find = function() {
			$scope.yarndeliveries = YarnDeliveries.query();
		};

		// Find existing YarnDelivery
		$scope.findOne = function() {

      YarnDeliveries.get({
				yarnDeliveryId: $stateParams.yarnDeliveryId
			})
      .$promise.then(function(data) {

        data.dCDate = moment(data.dCDate).format('YYYY-MM-DD');

        data.jobDate = moment(data.jobDate).format('YYYY-MM-DD');

        $scope.yarndelivery = data;
      }, function(reason) {
        console.log('Failed: ' + reason);
      });

		};
	}
]);


text:
package org.assertj.core.error.uri;

import static java.lang.String.format;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.uri.ShouldHaveFragment.shouldHaveFragment;

import java.net.URI;

import org.assertj.core.internal.TestDescription;
import org.junit.jupiter.api.Test;

class ShouldHaveFragment_create_Test {

  @Test
  void should_create_error_message_for_has_fragment() {
    // GIVEN
    URI uri = URI.create("http://assertj.org/news#print");
    // WHEN
    String error = shouldHaveFragment(uri, "foo").create(new TestDescription("TEST"));
    // THEN
    then(error).isEqualTo(format("[TEST] %n" +
                                 "Expecting fragment of%n" +
                                 "  <http://assertj.org/news#print>%n" +
                                 "to be:%n" +
                                 "  <\"foo\">%n" +
                                 "but was:%n" +
                                 "  <\"print\">"));
  }

  @Test
  void should_create_error_message_for_has_no_fragment() {
    // GIVEN
    URI uri = URI.create("http://assertj.org/news#print");
    // WHEN
    String error = shouldHaveFragment(uri, null).create(new TestDescription("TEST"));
    // THEN
    then(error).isEqualTo(format("[TEST] %n" +
                                 "Expecting URI:%n" +
                                 "  <http://assertj.org/news#print>%n" +
                                 "not to have a fragment but had:%n" +
                                 "  <\"print\">"));
  }
}


text:
{% extends 'admin/master.html' %}
{% block body %}

{{gettext('Add a new space:')}}

{% from "_form_helpers.html" import render_field %}

<form action="." method="POST"  class="form-horizontal">

    {{ form.hidden_tag() }}

    {{ render_field(form.url, size = 100) }}

    {% if request_space_name %}

            {{gettext('Space name')}}

                <input type="text" name="space_name"/>
                {{gettext('The provided space was hidden or closed. Please provide a name.')}}

    {% endif %}

    {% if lab_ids %}

{{gettext('Add permissions to the following labs:')}}

        {% for lab_id in lab_ids %}

                        <input name="lab_{{ lab_id }}" type="checkbox" {% if lab_ids[lab_id]['checked'] %}checked="checked"{% endif %}> {{ lab_id }}

                    {{gettext('Permission on')}} {{ lab_ids[lab_id]['name'] }}

        {% endfor %}
    {% endif %}

        <button class="btn btn-primary" name="action" type="submit" value="register">{{gettext('Add space')}}</button>

</form>

{% endblock %}


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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/shape_imgpicker_content_bg"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/img_drive_navi"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="驾车导航"
            android:textColor="@color/new_app_color"
            android:textSize="@dimen/textSize_16" />

        <View style="@style/line_style" />

        <TextView
            android:id="@+id/img_walk_navi"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="步行导航"
            android:textColor="@color/new_app_color"
            android:textSize="@dimen/textSize_16" />

        <View style="@style/line_style" />

        <TextView
            android:id="@+id/img_ride_navi"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:gravity="center"
            android:text="骑行导航"
            android:textColor="@color/new_app_color"
            android:textSize="@dimen/textSize_16" />

    </LinearLayout>

    <TextView
        android:id="@+id/img_cancel_navi"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/shape_imgpicker_content_bg"
        android:gravity="center"
        android:text="取消"
        android:textColor="@color/new_app_color"
        android:textSize="@dimen/textSize_16" />

</LinearLayout>


text:
package org.testng.internal;

import org.testng.ClassMethodMap;
import org.testng.IMethodInstance;
import org.testng.ITestClass;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.internal.thread.ThreadUtil;
import org.testng.xml.XmlSuite;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * FIXME: reduce contention when this class is used through parallel invocation due to
 * invocationCount and threadPoolSize by not invoking the @BeforeClass and @AfterClass
 * which are already invoked on the original method.
 *
 * This class implements Runnable and will invoke the ITestMethod passed in its
 * constructor on its run() method.
 *
 * @author Cedric Beust
 * @author Alexandru Popescu
 */
public class TestMethodWorker implements IMethodWorker {
  // Map of the test methods and their associated instances
  // It has to be a set because the same method can be passed several times
  // and associated to a different instance
  protected IMethodInstance[] m_testMethods;
  protected IInvoker m_invoker = null;
  protected Map<String, String> m_parameters = null;
  protected XmlSuite m_suite = null;
//  protected Map<ITestClass, Set<Object>> m_invokedBeforeClassMethods = null;
//  protected Map<ITestClass, Set<Object>> m_invokedAfterClassMethods = null;
  protected ITestNGMethod[] m_allTestMethods;
  protected List<ITestResult> m_testResults = new ArrayList<ITestResult>();
  protected ConfigurationGroupMethods m_groupMethods = null;
  protected ClassMethodMap m_classMethodMap = null;
  private ITestContext m_testContext = null;

  public TestMethodWorker(IInvoker invoker,
                          IMethodInstance[] testMethods,
                          XmlSuite suite,
                          Map<String, String> parameters,
                          ITestNGMethod[] allTestMethods,
                          ConfigurationGroupMethods groupMethods,
                          ClassMethodMap classMethodMap,
                          ITestContext testContext)
  {
    m_invoker = invoker;
    m_testMethods = testMethods;
    m_suite = suite;
    m_parameters = parameters;
//    m_invokedBeforeClassMethods = invokedBeforeClassMethods;
//    m_invokedAfterClassMethods = invokedAfterClassMethods;
    m_allTestMethods = allTestMethods;
    m_groupMethods = groupMethods;
    m_classMethodMap = classMethodMap;
    m_testContext = testContext;
  }

  /**
   * Retrieves the maximum specified timeout of all ITestNGMethods to
   * be run.
   *
   * @return the max timeout or 0 if no timeout was specified
   */
  public long getMaxTimeOut() {
    long result = 0;
    for (IMethodInstance mi : m_testMethods) {
      ITestNGMethod tm = mi.getMethod();
      if (tm.getTimeOut() > result) {
        result = tm.getTimeOut();
      }
    }

    return result;
  }

  @Override
  public String toString() {
    return "[Worker on thread:" + Thread.currentThread().getId() + " "
    + m_testMethods[0].getMethod() + "]";
  }

  /**
   * Run all the ITestNGMethods passed in through the constructor.
   *
   * @see java.lang.Runnable#run()
   */
  public void run() {
    // Using an index here because we need to tell the invoker
    // the index of the current method
    for (int indexMethod = 0; indexMethod < m_testMethods.length; indexMethod++) {
      ITestNGMethod tm = m_testMethods[indexMethod].getMethod();

      ITestClass testClass = tm.getTestClass();

      invokeBeforeClassMethods(testClass, m_testMethods[indexMethod]);

      //
      // Invoke test method
      //
      try {
        invokeTestMethods(tm, m_testMethods[indexMethod].getInstances(), m_testContext);
      }
      finally {
        invokeAfterClassMethods(testClass, m_testMethods[indexMethod]);
      }
    }
  }

  protected void invokeTestMethods(ITestNGMethod tm, Object[] instances,
      ITestContext testContext)
  {
    // Potential bug here:  we look up the method index of tm among all
    // the test methods (not very efficient) but if this method appears
    // several times and these methods are run in parallel, the results
    // are unpredictable...  Need to think about this more (and make it
    // more efficient)
    List<ITestResult> testResults =
        m_invoker.invokeTestMethods(tm,
            m_allTestMethods,
            indexOf(tm, m_allTestMethods),
            m_suite,
            m_parameters,
            m_groupMethods,
            instances,
            testContext);

    if (testResults != null) {
      m_testResults.addAll(testResults);
    }
  }

  //
  // Invoke the before class methods if not done already
  //
  protected void invokeBeforeClassMethods(ITestClass testClass, IMethodInstance mi) {
    // if no BeforeClass than return immediately
    // used for parallel case when BeforeClass were already invoked
    if( (null == m_classMethodMap) || (null == m_classMethodMap.getInvokedBeforeClassMethods())) {
      return;
    }
    ITestNGMethod[] classMethods= testClass.getBeforeClassMethods();
    if(null == classMethods || classMethods.length == 0) {
      return;
    }

    // the whole invocation must be synchronized as other threads must
    // get a full initialized test object (not the same for @After)
    Map<ITestClass, Set<Object>> invokedBeforeClassMethods= m_classMethodMap.getInvokedBeforeClassMethods();
    synchronized(invokedBeforeClassMethods) {
      Set<Object> instances= invokedBeforeClassMethods.get(testClass);
      if(null == instances) {
        instances= new HashSet<Object>();
        invokedBeforeClassMethods.put(testClass, instances);
      }
      for(Object instance: mi.getInstances()) {
        if (! instances.contains(instance)) {
          instances.add(instance);
          m_invoker.invokeConfigurations(testClass,
                                         testClass.getBeforeClassMethods(),
                                         m_suite,
                                         m_parameters,
                                         null, /* no parameter values */
                                         instance);
        }
      }
    }
  }

  protected void invokeAfterClassMethods(ITestClass testClass, IMethodInstance mi) {
    // if no BeforeClass than return immediately
    // used for parallel case when BeforeClass were already invoked
    if( (null == m_classMethodMap) || (null == m_classMethodMap.getInvokedAfterClassMethods()) ) {
      return;
    }
    ITestNGMethod[] afterClassMethods= testClass.getAfterClassMethods();

    if(null == afterClassMethods || afterClassMethods.length == 0) {
      return;
    }

    //
    // Invoke after class methods if this test method is the last one
    //
    List<Object> invokeInstances= new ArrayList<Object>();
    ITestNGMethod tm= mi.getMethod();
    if (m_classMethodMap.removeAndCheckIfLast(tm)) {
      Map<ITestClass, Set<Object>> invokedAfterClassMethods= m_classMethodMap.getInvokedAfterClassMethods();
      synchronized(invokedAfterClassMethods) {
        Set<Object> instances = invokedAfterClassMethods.get(testClass);
        if(null == instances) {
          instances= new HashSet<Object>();
          invokedAfterClassMethods.put(testClass, instances);
        }
        for(Object inst: mi.getInstances()) {
          if(! instances.contains(inst)) {
            invokeInstances.add(inst);
          }
        }
      }

      for(Object inst: invokeInstances) {
        m_invoker.invokeConfigurations(testClass,
                                       afterClassMethods,
                                       m_suite,
                                       m_parameters,
                                       null, /* no parameter values */
                                       inst);
      }
    }
  }

  protected int indexOf(ITestNGMethod tm, ITestNGMethod[] allTestMethods) {
    for (int i = 0; i < allTestMethods.length; i++) {
      if (allTestMethods[i] == tm) return i;
    }
    return -1;
  }

  public List<ITestResult> getTestResults() {
    return m_testResults;
  }

  private void ppp(String s) {
    Utils.log("TestMethodWorker", 2, ThreadUtil.currentThreadInfo() + ":" + s);
  }

  public void setAllTestMethods(ITestNGMethod[] allTestMethods) {
    m_allTestMethods = allTestMethods;
  }
}

class SingleTestMethodWorker extends TestMethodWorker {
  private static final ConfigurationGroupMethods EMPTY_GROUP_METHODS=
    new ConfigurationGroupMethods(new ITestNGMethod[0],
        new HashMap<String, List<ITestNGMethod>>(), new HashMap<String, List<ITestNGMethod>>());

  public SingleTestMethodWorker(IInvoker invoker,
                                MethodInstance testMethod,
                                XmlSuite suite,
                                Map<String, String> parameters,
                                ITestNGMethod[] allTestMethods,
                                ITestContext testContext)
  {
    super(invoker,
          new MethodInstance[] {testMethod},
          suite,
          parameters,
          allTestMethods,
          EMPTY_GROUP_METHODS,
          null,
          testContext);
  }

  protected void invokeAfterClassMethods(ITestClass testClass, ITestNGMethod tm) {
    // HINT: do nothing
  }

  protected void invokeBeforeClassMethods(ITestClass testClass) {
    // HINT: do nothing
  }
}


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>User/Sign In</title>
        <link rel="stylesheet" type="text/css" href="/restful/css/style.css"/>

Sign In

                userid
                <input type="text" name="userid" id="userid" tabindex="1" placeholder=" UserId">

                password
                <input type="password" name="password" id="password" tabindex="1" placeholder=" Password">

                <input type="button" value="Sign In" onClick="signin()">

                Sign Up


text:
package com.siyeh.ig.inheritance;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.LightProjectDescriptor;
import com.siyeh.ig.LightJavaInspectionTestCase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class MissingOverrideAnnotationInspectionTest extends LightJavaInspectionTestCase {

  public void testSimple() {
    doTest();
  }

  public void testNotAvailable() {
    doTest();
  }

  public void testHierarchy() {
    doTest();
  }

  public void testHierarchy2() {
    doTest();
  }

  public void testNotAvailableMethodInLanguageLevel7() {
    doTest();
  }

  @NotNull
  @Override
  protected LightProjectDescriptor getProjectDescriptor() {
    return new ProjectDescriptor(LanguageLevel.JDK_1_7) {
      @Override
      public Sdk getSdk() {
        return IdeaTestUtil.getMockJdk18();
      }
    };
  }

  @Nullable
  @Override
  protected InspectionProfileEntry getInspection() {
    return new MissingOverrideAnnotationInspection();
  }
}


text:
namespace _3.Wild_farm.Foods
{
    public abstract class Food
    {
        public Food(int quantity)
        {
            this.Quantity = quantity;
        }

        public int Quantity { get; private set; }
    }
}


text:
<?php
return array(
	'console' => array('router' => array('routes' => array(
		'TestModule' => array(
			'options' => array(
				'route' => 'test-module',
				'defaults' => array(
					'controller' => 'TestModule\Controller\Index',
					'action' => 'index'
				)
			)
		)
	))),
	'controllers' => array(
		'invokables' => array(
			'TestModule\Controller\Index' => 'TestModule\Controller\IndexController'
		)
	)
);


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.wearbook.wmessage" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".WMessageHandheldActivity"
            android:label="@string/app_name"
            android:screenOrientation="sensorPortrait"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
import { useState } from 'react'

/**
 *
 * @param {初始值} initial
 * 用来控制 modal等 显示和隐藏 返回: true 或者 false
 */

const useToggle = (initial) => {
  const [ value, setValue ] = useState(initial)
  const toggle = (nextValue) => {
    if (typeof nextValue !== 'undefined') {
      setValue(!!nextValue)
      return
    }
    setValue(!value)
  }
  return [ value, toggle ]
}

export default useToggle


text:
{-# LANGUAGE FlexibleContexts, RankNTypes, CPP #-}
module AWS.EC2.Volume
    ( describeVolumes
    , createVolume
    , deleteVolume
    , attachVolume
    , detachVolume
    , describeVolumeStatus
    , enableVolumeIO
    , describeVolumeAttribute
    , modifyVolumeAttribute
    ) where

import Data.Text (Text)

import Data.XML.Types (Event)
import Data.Conduit
import Control.Applicative
#if MIN_VERSION_conduit(1,1,0)
import Control.Monad.Trans.Resource (MonadThrow, MonadBaseControl, MonadResource)
#endif

import AWS.EC2.Internal
import AWS.EC2.Params
import AWS.EC2.Types
import AWS.EC2.Query
import AWS.Lib.Parser
import AWS.Util

describeVolumes
    :: (MonadResource m, MonadBaseControl IO m)
    => [Text] -- ^ VolumeIds
    -> [Filter] -- ^ Filters
    -> EC2 m (ResumableSource m Volume)
describeVolumes vids filters =
    ec2QuerySource "DescribeVolumes" params $
        itemConduit "volumeSet" volumeSink
  where
    params =
        [ "VolumeId" |.#= vids
        , filtersParam filters
        ]

volumeSink :: MonadThrow m
    => Consumer Event m Volume
volumeSink = Volume
    <$> getT "volumeId"
    <*> getT "size"
    <*> getT "snapshotId"
    <*> getT "availabilityZone"
    <*> getT "status"
    <*> getT "createTime"
    <*> itemsSet "attachmentSet" attachmentSink
    <*> resourceTagSink
    <*> volumeTypeSink

attachmentSink :: MonadThrow m => Consumer Event m AttachmentSetItemResponse
attachmentSink = AttachmentSetItemResponse
    <$> getT "volumeId"
    <*> getT "instanceId"
    <*> getT "device"
    <*> getT "status"
    <*> getT "attachTime"
    <*> getT "deleteOnTermination"

createVolume
    :: (MonadResource m, MonadBaseControl IO m)
    => CreateVolumeRequest
    -> EC2 m Volume
createVolume param =
    ec2Query "CreateVolume" param' volumeSink
  where
    param' = createVolumeParams param

createVolumeParams :: CreateVolumeRequest -> [QueryParam]
createVolumeParams (CreateNewVolume size zone vtype) =
    [ "Size" |= toText size
    , "AvailabilityZone" |= zone
    ] ++ maybe [] volumeTypeParams vtype
createVolumeParams (CreateFromSnapshot sid zone size vtype) =
    [ "SnapshotId" |= sid
    , "AvailabilityZone" |= zone
    , "Size" |=? toText <$> size
    ] ++ maybe [] volumeTypeParams vtype

deleteVolume
    :: (MonadResource m, MonadBaseControl IO m)
    => Text -- ^ VolumeId
    -> EC2 m Bool
deleteVolume = ec2Delete "DeleteVolume" "VolumeId"

attachVolume
    :: (MonadResource m, MonadBaseControl IO m)
    => Text -- ^ VolumeId
    -> Text -- ^ InstanceId
    -> Text -- ^ Device
    -> EC2 m AttachmentSetItemResponse
attachVolume volid iid dev =
    ec2Query "AttachVolume" params attachmentSink
  where
    params =
        [ "VolumeId" |= volid
        , "InstanceId" |= iid
        , "Device" |= dev
        ]

detachVolume
    :: (MonadResource m, MonadBaseControl IO m)
    => Text -- ^ VolumeId
    -> Maybe Text -- ^ InstanceId
    -> Maybe Text -- ^ Device
    -> Maybe Bool -- ^ Force
    -> EC2 m AttachmentSetItemResponse
detachVolume volid iid dev force =
    ec2Query "DetachVolume" params attachmentSink
  where
    params =
        [ "VolumeId" |= volid
        , "InstanceId" |=? iid
        , "Device" |=? dev
        , "Force" |=? toText <$> force
        ]

describeVolumeStatus
    :: (MonadResource m, MonadBaseControl IO m)
    => [Text] -- ^ VolumeId
    -> [Filter] -- ^ Filters
    -> Maybe Text -- ^ next token
    -> EC2 m (ResumableSource m VolumeStatus)
describeVolumeStatus vids filters token =
    ec2QuerySource' "DescribeVolumeStatus" params token $
       itemConduit "volumeStatusSet" $ volumeStatusSink
  where
    params =
        [ "VolumeId" |.#= vids
        , filtersParam filters
        ]

volumeStatusSink :: MonadThrow m
    => Consumer Event m VolumeStatus
volumeStatusSink = VolumeStatus
    <$> getT "volumeId"
    <*> getT "availabilityZone"
    <*> element "volumeStatus" (VolumeStatusInfo
        <$> getT "status"
        <*> itemsSet "details" (VolumeStatusDetail
            <$> getT "name"
            <*> getT "status"
            )
        )
    <*> itemsSet "eventsSet" (VolumeStatusEvent
        <$> getT "eventType"
        <*> getT "eventId"
        <*> getT "description"
        <*> getT "notBefore"
        <*> getT "notAfter"
        )
    <*> itemsSet "actionsSet" (VolumeStatusAction
        <$> getT "code"
        <*> getT "eventType"
        <*> getT "eventId"
        <*> getT "description"
        )

modifyVolumeAttribute
    :: (MonadResource m, MonadBaseControl IO m)
    => Text -- ^ VolumeId
    -> Bool -- ^ AutoEnableIO
    -> EC2 m Bool
modifyVolumeAttribute vid enable =
    ec2Query "ModifyVolumeAttribute" params $ getT "return"
  where
    params =
        [ "VolumeId" |= vid
        , "AutoEnableIO" |.+ "Value" |= boolToText enable
        ]

enableVolumeIO
    :: (MonadResource m, MonadBaseControl IO m)
    => Text -- ^ VolumeId
    -> EC2 m Bool
enableVolumeIO vid =
    ec2Query "EnableVolumeIO" params $ getT "return"
  where
    params = ["VolumeId" |= vid]

-- | return (volumeId, Attribute)
describeVolumeAttribute
    :: (MonadResource m, MonadBaseControl IO m)
    => Text -- ^ VolumeId
    -> VolumeAttributeRequest
    -> EC2 m (Text, VolumeAttribute)
describeVolumeAttribute vid attr =
    ec2Query "DescribeVolumeAttribute" params $ (,)
        <$> getT "volumeId"
        <*> volumeAttributeSink attr
  where
    params =
        [ "VolumeId" |= vid
        , "Attribute" |= s attr
        ]
    s VolumeAttributeRequestAutoEnableIO = "autoEnableIO"
    s VolumeAttributeRequestProductCodes = "productCodes"

volumeAttributeSink
    :: MonadThrow m
    => VolumeAttributeRequest
    -> Consumer Event m VolumeAttribute
volumeAttributeSink VolumeAttributeRequestAutoEnableIO
    = VolumeAttributeAutoEnableIO
    <$> element "autoEnableIO" (getT "value")
volumeAttributeSink VolumeAttributeRequestProductCodes
    = VolumeAttributeProductCodes
    <$> productCodeSink


text:
package org.jolokia.docker.maven.config;

/**
 * Configuration for watching on image changes
 */
public class WatchImageConfiguration {

    /**
     * @parameter
     */
    private int interval = 5000; // default

    /**
     * @parameter
     */
    private WatchMode mode;

    /**
     * @parameter
     */
    private String postGoal;

    /**
     * @parameter
     */
    private String postExec;

    public WatchImageConfiguration() {};

    public int getInterval() {
        return interval;
    }

    public WatchMode getMode() {
        return mode;
    }

    public String getPostGoal() {
        return postGoal;
    }

    public String getPostExec() {
        return postExec;
    }

    public static class Builder {

        private WatchImageConfiguration c = new WatchImageConfiguration();

        public Builder interval(int interval) {
            c.interval = interval;
            return this;
        }

        public Builder mode(String mode) {
            if (mode != null) {
                c.mode = WatchMode.valueOf(mode.toLowerCase());
            }
            return this;
        }

        public Builder postGoal(String goal) {
            c.postGoal = goal;
            return this;
        }

        public WatchImageConfiguration build() {
            return c;
        }
    }

}


text:
<!DOCTYPE html>

    Test for rdar://problem/6937089 Crashes at RenderPart::destroy().

    This test should not crash or cause an assertion failure.

    <embed type="application/x-webkit-test-netscape" ondestroy="destroyed()">


text:
// Copyright 2020 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using BenchmarkDotNet.Running;
using System;

namespace VDrumExplorer.Benchmarks
{
    class Program
    {
        static void Main(string[] args)
        {
            BenchmarkRunner.Run(typeof(Program).Assembly);
        }
    }
}


text:
package com.github.lisicnu.log4android.format.command;

import com.github.lisicnu.log4android.Level;

/**
 * The ClientIdFormatCommand formats the client id.
 *
 * @author Johan Karlsson (johan.karlsson@jayway.se)
 *
 */
public class ClientIdFormatCommand implements FormatCommandInterface {

	/**
	 * @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String,
	 *      String, long, com.github.lisicnu.log4android.Level, Object, Throwable)
	 */
	public String execute(String clientID, String name, long time, Level level,
			Object message, Throwable throwable) {
		return clientID;
	}

	/**
	 * @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String)
	 */
	public void init(String initString) {
		// Do nothing
	}

}


text:
//go:generate bash -c "capnp compile -o- schema.capnp | capnpc-go -promises=false"

/*
capnpc-go is the Cap'n proto code generator for Go.  It reads a
CodeGeneratorRequest from stdin and for a file foo.capnp it writes
foo.capnp.go.  This is usually invoked from `capnp compile -ogo`.

See https://capnproto.org/otherlang.html#how-to-write-compiler-plugins
for more details.
*/
package main

import (
	"bytes"
	"flag"
	"fmt"
	"go/format"
	"io"
	"math"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"unicode"

	"zombiezen.com/go/capnproto2"
)

var (
	genPromises = flag.Bool("promises", true, "generate code for promises")
)

const (
	go_capnproto_import = "zombiezen.com/go/capnproto2"
	server_import       = go_capnproto_import + "/server"
	context_import      = "golang.org/x/net/context"
)

var (
	g_nodes   = make(map[uint64]*node)
	g_imports imports
	g_segment []byte
	g_bufname string
)

type imports struct {
	specs []importSpec
	used  map[string]bool // keyed on import path
}

func (i *imports) init() {
	i.specs = nil
	i.used = make(map[string]bool)

	i.reserve(importSpec{path: go_capnproto_import, name: "capnp"})
	i.reserve(importSpec{path: server_import, name: "server"})
	i.reserve(importSpec{path: context_import, name: "context"})

	i.reserve(importSpec{path: "bufio", name: "bufio"})
	i.reserve(importSpec{path: "bytes", name: "bytes"})
	i.reserve(importSpec{path: "io", name: "io"})
	i.reserve(importSpec{path: "math", name: "math"})
	i.reserve(importSpec{path: "strconv", name: "strconv"})
}

func (i *imports) capnp() string {
	return i.add(importSpec{path: go_capnproto_import, name: "capnp"})
}

func (i *imports) server() string {
	return i.add(importSpec{path: server_import, name: "server"})
}

func (i *imports) context() string {
	return i.add(importSpec{path: context_import, name: "context"})
}

func (i *imports) math() string {
	return i.add(importSpec{path: "math", name: "math"})
}

func (i *imports) strconv() string {
	return i.add(importSpec{path: "strconv", name: "strconv"})
}

func (i *imports) usedImports() []importSpec {
	specs := make([]importSpec, 0, len(i.specs))
	for _, s := range i.specs {
		if i.used[s.path] {
			specs = append(specs, s)
		}
	}
	return specs
}

func (i *imports) byPath(path string) (spec importSpec, ok bool) {
	for _, spec = range i.specs {
		if spec.path == path {
			return spec, true
		}
	}
	return importSpec{}, false
}

func (i *imports) byName(name string) (spec importSpec, ok bool) {
	for _, spec = range i.specs {
		if spec.name == name {
			return spec, true
		}
	}
	return importSpec{}, false
}

func (i *imports) add(spec importSpec) (name string) {
	name = i.reserve(spec)
	i.used[spec.path] = true
	return name
}

// reserve adds an import spec without marking it as used.
func (i *imports) reserve(spec importSpec) (name string) {
	if ispec, ok := i.byPath(spec.path); ok {
		return ispec.name
	}
	if spec.name == "" {
		spec.name = pkgFromImport(spec.path)
	}
	if _, found := i.byName(spec.name); found {
		for base, n := spec.name, uint64(2); ; n++ {
			spec.name = base + strconv.FormatUint(n, 10)
			if _, found = i.byName(spec.name); !found {
				break
			}
		}
	}
	i.specs = append(i.specs, spec)
	return spec.name
}

func pkgFromImport(path string) string {
	if i := strings.LastIndex(path, "/"); i != -1 {
		path = path[i+1:]
	}
	p := []rune(path)
	n := 0
	for _, r := range p {
		if isIdent(r) {
			p[n] = r
			n++
		}
	}
	if n == 0 || !isLower(p[0]) {
		return "pkg" + string(p[:n])
	}
	return string(p[:n])
}

func isLower(r rune) bool {
	return 'a' <= r && r <= 'z' || r == '_'
}

func isIdent(r rune) bool {
	return isLower(r) || 'A' <= r && r <= 'Z' || r >= 0x80 && unicode.IsLetter(r)
}

type importSpec struct {
	path string
	name string
}

func (spec importSpec) String() string {
	if spec.name == "" {
		return strconv.Quote(spec.path)
	}
	return spec.name + " " + strconv.Quote(spec.path)
}

type node struct {
	Node
	pkg   string
	imp   string
	nodes []*node
	Name  string
}

type field struct {
	Field
	Name string
}

func assert(chk bool, format string, a ...interface{}) {
	if !chk {
		panic(assertionError(fmt.Sprintf(format, a...)))
	}
}

type assertionError string

func (ae assertionError) Error() string {
	return string(ae)
}

func copyData(obj capnp.Pointer) staticDataRef {
	m, _, err := capnp.NewMessage(capnp.SingleSegment(nil))
	assert(err == nil, "%v\n", err)
	err = m.SetRoot(obj)
	assert(err == nil, "%v\n", err)
	data, err := m.Marshal()
	assert(err == nil, "%v\n", err)
	var ref staticDataRef
	ref.Start = len(g_segment)
	g_segment = append(g_segment, data...)
	ref.End = len(g_segment)
	return ref
}

type staticDataRef struct {
	Start, End int
}

func (ref staticDataRef) IsValid() bool {
	return ref.Start < ref.End
}

func (ref staticDataRef) String() string {
	return fmt.Sprintf("%s[%d:%d]", g_bufname, ref.Start, ref.End)
}

// Tag types
const (
	defaultTag = iota
	noTag
	customTag
)

type annotations struct {
	Doc       string
	Package   string
	Import    string
	TagType   int
	CustomTag string
	Name      string
}

func parseAnnotations(list Annotation_List) *annotations {
	ann := new(annotations)
	for i, n := 0, list.Len(); i < n; i++ {
		a := list.At(i)
		val, _ := a.Value()
		text, _ := val.Text()
		switch a.Id() {
		case capnp.Doc:
			ann.Doc = text
		case capnp.Package:
			ann.Package = text
		case capnp.Import:
			ann.Import = text
		case capnp.Tag:
			ann.TagType = customTag
			ann.CustomTag = text
		case capnp.Notag:
			ann.TagType = noTag
		case capnp.Name:
			ann.Name = text
		}
	}
	return ann
}

// Tag returns the string value that an enumerant value called name should have.
// An empty string indicates that this enumerant value has no tag.
func (ann *annotations) Tag(name string) string {
	switch ann.TagType {
	case noTag:
		return ""
	case customTag:
		return ann.CustomTag
	case defaultTag:
		fallthrough
	default:
		return name
	}
}

// Rename returns the overridden name from the annotations or the given name
// if no annotation was found.
func (ann *annotations) Rename(given string) string {
	if ann.Name == "" {
		return given
	}
	return ann.Name
}

func findNode(id uint64) *node {
	n := g_nodes[id]
	assert(n != nil, "could not find node 0x%x\n", id)
	return n
}

func (n *node) remoteScope(from *node) string {
	displayName, _ := n.DisplayName()
	fromDisplayName, _ := from.DisplayName()
	assert(n.pkg != "", "missing package declaration for %s", displayName)
	assert(n.imp != "", "missing import declaration for %s", displayName)
	assert(from.imp != "", "missing import declaration for %s", fromDisplayName)

	if n.imp == from.imp {
		return ""
	} else {
		name := g_imports.add(importSpec{path: n.imp, name: n.pkg})
		return name + "."
	}
}

func (n *node) RemoteNew(from *node) string {
	return n.remoteScope(from) + "New" + n.Name
}

func (n *node) RemoteName(from *node) string {
	return n.remoteScope(from) + n.Name
}

func (n *node) resolveName(base, name string, file *node) {
	na, _ := n.Annotations()
	name = parseAnnotations(na).Rename(name)
	if base == "" {
		n.Name = strings.Title(name)
	} else {
		n.Name = base + "_" + name
	}
	n.pkg = file.pkg
	n.imp = file.imp

	if n.Which() != Node_Which_structGroup || !n.StructGroup().IsGroup() {
		file.nodes = append(file.nodes, n)
	}

	nnodes, _ := n.NestedNodes()
	for i := 0; i < nnodes.Len(); i++ {
		nn := nnodes.At(i)
		if ni := g_nodes[nn.Id()]; ni != nil {
			nname, _ := nn.Name()
			ni.resolveName(n.Name, nname, file)
		}
	}

	if n.Which() == Node_Which_structGroup {
		fields, _ := n.StructGroup().Fields()
		for i := 0; i < fields.Len(); i++ {
			f := fields.At(i)
			if f.Which() == Field_Which_group {
				fa, _ := f.Annotations()
				fname, _ := f.Name()
				fname = parseAnnotations(fa).Rename(fname)
				findNode(f.Group().TypeId()).resolveName(n.Name, fname, file)
			}
		}
	} else if n.Which() == Node_Which_interface {
		m, _ := n.Interface().Methods()
		for i := 0; i < m.Len(); i++ {
			mm := m.At(i)
			mname, _ := mm.Name()
			mann, _ := mm.Annotations()
			mname = parseAnnotations(mann).Rename(mname)
			base := n.Name + "_" + mname
			if p := findNode(mm.ParamStructType()); p.ScopeId() == 0 {
				p.resolveName(base, "Params", file)
			}
			if r := findNode(mm.ResultStructType()); r.ScopeId() == 0 {
				r.resolveName(base, "Results", file)
			}
		}
	}
}

type enumval struct {
	Enumerant
	Name   string
	Val    int
	Tag    string
	parent *node
}

func makeEnumval(enum *node, i int, e Enumerant) enumval {
	eann, _ := e.Annotations()
	ann := parseAnnotations(eann)
	name, _ := e.Name()
	name = ann.Rename(name)
	t := ann.Tag(name)
	return enumval{e, name, i, t, enum}
}

func (e *enumval) FullName() string {
	return e.parent.Name + "_" + e.Name
}

func (n *node) defineEnum(w io.Writer) {
	es, _ := n.Enum().Enumerants()
	ev := make([]enumval, es.Len())
	for i := 0; i < es.Len(); i++ {
		e := es.At(i)
		ev[e.CodeOrder()] = makeEnumval(n, i, e)
	}
	nann, _ := n.Annotations()
	templates.ExecuteTemplate(w, "enum", enumParams{
		Node:        n,
		Annotations: parseAnnotations(nann),
		EnumValues:  ev,
	})
}

func (n *node) writeValue(w io.Writer, t Type, v Value) {
	switch t.Which() {
	case Type_Which_void:
		fmt.Fprintf(w, "struct{}{}")

	case Type_Which_interface:
		// The only statically representable interface value is null.
		fmt.Fprintf(w, "%s.Client(nil)", g_imports.capnp())

	case Type_Which_bool:
		assert(v.Which() == Value_Which_bool, "expected bool value")
		if v.Bool() {
			fmt.Fprint(w, "true")
		} else {
			fmt.Fprint(w, "false")
		}

	case Type_Which_uint8, Type_Which_uint16, Type_Which_uint32, Type_Which_uint64:
		fmt.Fprintf(w, "uint%d(%d)", intbits(t.Which()), uintValue(t, v))

	case Type_Which_int8, Type_Which_int16, Type_Which_int32, Type_Which_int64:
		fmt.Fprintf(w, "int%d(%d)", intbits(t.Which()), intValue(t, v))

	case Type_Which_float32:
		assert(v.Which() == Value_Which_float32, "expected float32 value")
		fmt.Fprintf(w, "%s.Float32frombits(0x%x)", g_imports.math(), math.Float32bits(v.Float32()))

	case Type_Which_float64:
		assert(v.Which() == Value_Which_float64, "expected float64 value")
		fmt.Fprintf(w, "%s.Float64frombits(0x%x)", g_imports.math(), math.Float64bits(v.Float64()))

	case Type_Which_text:
		assert(v.Which() == Value_Which_text, "expected text value")
		text, _ := v.Text()
		fmt.Fprintf(w, "%q", text)

	case Type_Which_data:
		assert(v.Which() == Value_Which_data, "expected data value")
		fmt.Fprint(w, "[]byte{")
		data, _ := v.Data()
		for i, b := range data {
			if i > 0 {
				fmt.Fprint(w, ", ")
			}
			fmt.Fprintf(w, "%d", b)
		}
		fmt.Fprint(w, "}")

	case Type_Which_enum:
		assert(v.Which() == Value_Which_enum, "expected enum value")
		en := findNode(t.Enum().TypeId())
		assert(en.Which() == Node_Which_enum, "expected enum type ID")
		enums, _ := en.Enum().Enumerants()
		if val := int(v.Enum()); val >= enums.Len() {
			fmt.Fprintf(w, "%s(%d)", en.RemoteName(n), val)
		} else {
			ev := makeEnumval(en, val, enums.At(val))
			fmt.Fprintf(w, "%s%s", en.remoteScope(n), ev.FullName())
		}

	case Type_Which_structGroup:
		assert(v.Which() == Value_Which_structField, "expected struct value")
		c := g_imports.capnp()
		data, _ := v.StructField()
		fmt.Fprintf(w, "%s{Struct: %s.ToStruct(%s.MustUnmarshalRoot(%v))}", findNode(t.StructGroup().TypeId()).RemoteName(n), c, c, copyData(data))

	case Type_Which_anyPointer:
		assert(v.Which() == Value_Which_anyPointer, "expected pointer value")
		data, _ := v.AnyPointer()
		fmt.Fprintf(w, "%s.MustUnmarshalRoot(%v)", g_imports.capnp(), copyData(data))

	case Type_Which_list:
		assert(v.Which() == Value_Which_list, "expected list value")
		c := g_imports.capnp()
		typ := n.fieldType(t, new(annotations))
		data, _ := v.List()
		fmt.Fprintf(w, "%s{List: %s.ToList(%s.MustUnmarshalRoot(%v))}", typ, c, c, copyData(data))
	}
}

func (n *node) defineAnnotation(w io.Writer) {
	templates.ExecuteTemplate(w, "annotation", annotationParams{
		Node: n,
	})
}

func constIsVar(n *node) bool {
	t, _ := n.Const().Type()
	switch t.Which() {
	case Type_Which_bool, Type_Which_int8, Type_Which_uint8, Type_Which_int16,
		Type_Which_uint16, Type_Which_int32, Type_Which_uint32, Type_Which_int64,
		Type_Which_uint64, Type_Which_text, Type_Which_enum:
		return false
	default:
		return true
	}
}

func defineConstNodes(w io.Writer, nodes []*node) {

	any := false

	for _, n := range nodes {
		if n.Which() == Node_Which_const && !constIsVar(n) {
			if !any {
				fmt.Fprintf(w, "const (\n")
				any = true
			}
			fmt.Fprintf(w, "%s = ", n.Name)
			kt, _ := n.Const().Type()
			kv, _ := n.Const().Value()
			n.writeValue(w, kt, kv)
			fmt.Fprintf(w, "\n")
		}
	}

	if any {
		fmt.Fprintf(w, ")\n")
	}

	any = false

	for _, n := range nodes {
		if n.Which() == Node_Which_const && constIsVar(n) {
			if !any {
				fmt.Fprintf(w, "var (\n")
				any = true
			}
			fmt.Fprintf(w, "%s = ", n.Name)
			kt, _ := n.Const().Type()
			kv, _ := n.Const().Value()
			n.writeValue(w, kt, kv)
			fmt.Fprintf(w, "\n")
		}
	}

	if any {
		fmt.Fprintf(w, ")\n")
	}
}

func (n *node) defineField(w io.Writer, f field) {
	fann, _ := f.Annotations()
	ann := parseAnnotations(fann)
	t, _ := f.Slot().Type()
	def, _ := f.Slot().DefaultValue()
	params := structFieldParams{
		Node:        n,
		Field:       f,
		Annotations: ann,
		FieldType:   n.fieldType(t, ann),
	}
	switch t.Which() {
	case Type_Which_void:
		templates.ExecuteTemplate(w, "structVoidField", params)
	case Type_Which_bool:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_bool, "expected bool default")
		templates.ExecuteTemplate(w, "structBoolField", structBoolFieldParams{
			structFieldParams: params,
			Default:           def.Which() == Value_Which_bool && def.Bool(),
		})

	case Type_Which_uint8, Type_Which_uint16, Type_Which_uint32, Type_Which_uint64:
		templates.ExecuteTemplate(w, "structUintField", structUintFieldParams{
			structFieldParams: params,
			Bits:              intbits(t.Which()),
			Default:           uintFieldDefault(t, def),
		})

	case Type_Which_int8, Type_Which_int16, Type_Which_int32, Type_Which_int64:
		templates.ExecuteTemplate(w, "structIntField", structIntFieldParams{
			structUintFieldParams: structUintFieldParams{
				structFieldParams: params,
				Bits:              intbits(t.Which()),
				Default:           uint64(intFieldDefault(t, def)),
			},
		})

	case Type_Which_enum:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_enum, "expected enum default")
		ni := findNode(t.Enum().TypeId())
		var d uint64
		if def.Which() == Value_Which_enum {
			d = uint64(def.Enum())
		}
		templates.ExecuteTemplate(w, "structIntField", structIntFieldParams{
			structUintFieldParams: structUintFieldParams{
				structFieldParams: params,
				Bits:              16,
				Default:           d,
			},
			EnumName: ni.RemoteName(n),
		})
	case Type_Which_float32:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_float32, "expected float32 default")
		var d uint64
		if def.Which() == Value_Which_float32 && def.Float32() != 0 {
			d = uint64(math.Float32bits(def.Float32()))
		}
		templates.ExecuteTemplate(w, "structFloatField", structUintFieldParams{
			structFieldParams: params,
			Bits:              32,
			Default:           d,
		})

	case Type_Which_float64:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_float64, "expected float64 default")
		var d uint64
		if def.Which() == Value_Which_float64 && def.Float64() != 0 {
			d = math.Float64bits(def.Float64())
		}
		templates.ExecuteTemplate(w, "structFloatField", structUintFieldParams{
			structFieldParams: params,
			Bits:              64,
			Default:           d,
		})

	case Type_Which_text:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_text, "expected text default")
		var d string
		if def.Which() == Value_Which_text {
			d, _ = def.Text()
		}
		templates.ExecuteTemplate(w, "structTextField", structTextFieldParams{
			structFieldParams: params,
			Default:           d,
		})

	case Type_Which_data:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_data, "expected data default")
		var d []byte
		if def.Which() == Value_Which_data {
			d, _ = def.Data()
		}
		templates.ExecuteTemplate(w, "structDataField", structDataFieldParams{
			structFieldParams: params,
			Default:           d,
		})

	case Type_Which_structGroup:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_structField, "expected struct default")
		var defref staticDataRef
		if def.Which() == Value_Which_structField {
			if sf, _ := def.StructField(); capnp.HasData(sf) {
				defref = copyData(sf)
			}
		}
		templates.ExecuteTemplate(w, "structStructField", structObjectFieldParams{
			structFieldParams: params,
			TypeNode:          findNode(t.StructGroup().TypeId()),
			Default:           defref,
		})

	case Type_Which_anyPointer:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_anyPointer, "expected object default")
		var defref staticDataRef
		if def.Which() == Value_Which_anyPointer {
			if p, _ := def.AnyPointer(); capnp.HasData(p) {
				defref = copyData(p)
			}
		}
		templates.ExecuteTemplate(w, "structPointerField", structObjectFieldParams{
			structFieldParams: params,
			Default:           defref,
		})

	case Type_Which_list:
		assert(def.Which() == Value_Which_void || def.Which() == Value_Which_list, "expected list default")
		var defref staticDataRef
		if def.Which() == Value_Which_list {
			if l, _ := def.List(); capnp.HasData(l) {
				defref = copyData(l)
			}
		}
		templates.ExecuteTemplate(w, "structListField", structObjectFieldParams{
			structFieldParams: params,
			Default:           defref,
		})

	case Type_Which_interface:
		templates.ExecuteTemplate(w, "structInterfaceField", params)
	}
}

func (n *node) fieldType(t Type, ann *annotations) string {
	switch t.Which() {
	case Type_Which_bool:
		return "bool"
	case Type_Which_int8:
		return "int8"
	case Type_Which_int16:
		return "int16"
	case Type_Which_int32:
		return "int32"
	case Type_Which_int64:
		return "int64"
	case Type_Which_uint8:
		return "uint8"
	case Type_Which_uint16:
		return "uint16"
	case Type_Which_uint32:
		return "uint32"
	case Type_Which_uint64:
		return "uint64"
	case Type_Which_float32:
		return "float32"
	case Type_Which_float64:
		return "float64"
	case Type_Which_text:
		return "string"
	case Type_Which_data:
		return "[]byte"
	case Type_Which_enum:
		ni := findNode(t.Enum().TypeId())
		return ni.RemoteName(n)
	case Type_Which_structGroup:
		ni := findNode(t.StructGroup().TypeId())
		return ni.RemoteName(n)
	case Type_Which_interface:
		ni := findNode(t.Interface().TypeId())
		return ni.RemoteName(n)
	case Type_Which_anyPointer:
		return g_imports.capnp() + ".Pointer"
	case Type_Which_list:
		switch lt, _ := t.List().ElementType(); lt.Which() {
		case Type_Which_void:
			return g_imports.capnp() + ".VoidList"
		case Type_Which_bool:
			return g_imports.capnp() + ".BitList"
		case Type_Which_int8:
			return g_imports.capnp() + ".Int8List"
		case Type_Which_uint8:
			return g_imports.capnp() + ".UInt8List"
		case Type_Which_int16:
			return g_imports.capnp() + ".Int16List"
		case Type_Which_uint16:
			return g_imports.capnp() + ".UInt16List"
		case Type_Which_int32:
			return g_imports.capnp() + ".Int32List"
		case Type_Which_uint32:
			return g_imports.capnp() + ".UInt32List"
		case Type_Which_int64:
			return g_imports.capnp() + ".Int64List"
		case Type_Which_uint64:
			return g_imports.capnp() + ".UInt64List"
		case Type_Which_float32:
			return g_imports.capnp() + ".Float32List"
		case Type_Which_float64:
			return g_imports.capnp() + ".Float64List"
		case Type_Which_text:
			return g_imports.capnp() + ".TextList"
		case Type_Which_data:
			return g_imports.capnp() + ".DataList"
		case Type_Which_enum:
			ni := findNode(lt.Enum().TypeId())
			return ni.RemoteName(n) + "_List"
		case Type_Which_structGroup:
			ni := findNode(lt.StructGroup().TypeId())
			return ni.RemoteName(n) + "_List"
		case Type_Which_anyPointer, Type_Which_list, Type_Which_interface:
			return g_imports.capnp() + ".PointerList"
		}
	}
	return ""
}

func intFieldDefault(t Type, def Value) int64 {
	if def.Which() == Value_Which_void {
		return 0
	}
	return intValue(t, def)
}

func intValue(t Type, v Value) int64 {
	switch t.Which() {
	case Type_Which_int8:
		assert(v.Which() == Value_Which_int8, "expected int8 value")
		return int64(v.Int8())
	case Type_Which_int16:
		assert(v.Which() == Value_Which_int16, "expected int16 value")
		return int64(v.Int16())
	case Type_Which_int32:
		assert(v.Which() == Value_Which_int32, "expected int32 value")
		return int64(v.Int32())
	case Type_Which_int64:
		assert(v.Which() == Value_Which_int64, "expected int64 value")
		return v.Int64()
	}
	panic("unreachable")
}

func uintFieldDefault(t Type, def Value) uint64 {
	if def.Which() == Value_Which_void {
		return 0
	}
	return uintValue(t, def)
}

func uintValue(t Type, v Value) uint64 {
	switch t.Which() {
	case Type_Which_uint8:
		assert(v.Which() == Value_Which_uint8, "expected uint8 value")
		return uint64(v.Uint8())
	case Type_Which_uint16:
		assert(v.Which() == Value_Which_uint16, "expected uint16 value")
		return uint64(v.Uint16())
	case Type_Which_uint32:
		assert(v.Which() == Value_Which_uint32, "expected uint32 value")
		return uint64(v.Uint32())
	case Type_Which_uint64:
		assert(v.Which() == Value_Which_uint64, "expected uint64 value")
		return v.Uint64()
	}
	panic("unreachable")
}

func intbits(t Type_Which) int {
	switch t {
	case Type_Which_uint8, Type_Which_int8:
		return 8
	case Type_Which_uint16, Type_Which_int16:
		return 16
	case Type_Which_uint32, Type_Which_int32:
		return 32
	case Type_Which_uint64, Type_Which_int64:
		return 64
	}
	return 0
}

func (n *node) codeOrderFields() []field {
	fields, _ := n.StructGroup().Fields()
	numFields := fields.Len()
	mbrs := make([]field, numFields)
	for i := 0; i < numFields; i++ {
		f := fields.At(i)
		fann, _ := f.Annotations()
		fname, _ := f.Name()
		fname = parseAnnotations(fann).Rename(fname)
		mbrs[f.CodeOrder()] = field{Field: f, Name: fname}
	}
	return mbrs
}

func (n *node) defineStructTypes(w io.Writer, baseNode *node) {
	assert(n.Which() == Node_Which_structGroup, "invalid struct node")

	nann, _ := n.Annotations()
	ann := parseAnnotations(nann)
	templates.ExecuteTemplate(w, "structTypes", structTypesParams{
		Node:        n,
		Annotations: ann,
		BaseNode:    baseNode,
	})

	for _, f := range n.codeOrderFields() {
		if f.Which() == Field_Which_group {
			findNode(f.Group().TypeId()).defineStructTypes(w, baseNode)
		}
	}
}

func (n *node) defineStructEnums(w io.Writer) {
	assert(n.Which() == Node_Which_structGroup, "invalid struct node")
	fields := n.codeOrderFields()
	members := make([]field, 0, len(fields))
	es := make(enumString, 0, len(fields))
	for _, f := range fields {
		if f.DiscriminantValue() != Field_noDiscriminant {
			members = append(members, f)
			es = append(es, f.Name)
		}
	}
	if n.StructGroup().DiscriminantCount() > 0 {
		templates.ExecuteTemplate(w, "structEnums", structEnumsParams{
			Node:       n,
			Fields:     members,
			EnumString: es,
		})
	}
	for _, f := range fields {
		if f.Which() == Field_Which_group {
			findNode(f.Group().TypeId()).defineStructEnums(w)
		}
	}
}

func (n *node) defineStructFuncs(w io.Writer) {
	assert(n.Which() == Node_Which_structGroup, "invalid struct node")

	templates.ExecuteTemplate(w, "structFuncs", structFuncsParams{
		Node: n,
	})

	for _, f := range n.codeOrderFields() {
		switch f.Which() {
		case Field_Which_slot:
			n.defineField(w, f)
		case Field_Which_group:
			g := findNode(f.Group().TypeId())
			templates.ExecuteTemplate(w, "structGroup", structGroupParams{
				Node:  n,
				Group: g,
				Field: f,
			})
			g.defineStructFuncs(w)
		}
	}
}

func (n *node) ObjectSize() string {
	assert(n.Which() == Node_Which_structGroup, "ObjectSize for invalid struct node")
	return fmt.Sprintf("%s.ObjectSize{DataSize: %d, PointerCount: %d}", g_imports.capnp(), int(n.StructGroup().DataWordCount())*8, n.StructGroup().PointerCount())
}

func (n *node) defineNewStructFunc(w io.Writer) {
	assert(n.Which() == Node_Which_structGroup, "invalid struct node")

	templates.ExecuteTemplate(w, "newStructFunc", newStructParams{
		Node: n,
	})
}

func (n *node) defineStructList(w io.Writer) {
	assert(n.Which() == Node_Which_structGroup, "invalid struct node")

	templates.ExecuteTemplate(w, "structList", structListParams{
		Node: n,
	})
}

func (n *node) defineStructPromise(w io.Writer) {
	templates.ExecuteTemplate(w, "promise", promiseTemplateParams{
		Node:   n,
		Fields: n.codeOrderFields(),
	})

	for _, f := range n.codeOrderFields() {
		switch f.Which() {
		case Field_Which_slot:
			t, _ := f.Slot().Type()
			if tw := t.Which(); tw == Type_Which_structGroup || tw == Type_Which_interface || tw == Type_Which_anyPointer {
				n.definePromiseField(w, f)
			}
		case Field_Which_group:
			g := findNode(f.Group().TypeId())
			templates.ExecuteTemplate(w, "promiseGroup", promiseGroupTemplateParams{
				Node:  n,
				Field: f,
				Group: g,
			})
			g.defineStructPromise(w)
		}
	}
}

func (n *node) definePromiseField(w io.Writer, f field) {
	slot := f.Slot()
	switch t, _ := slot.Type(); t.Which() {
	case Type_Which_structGroup:
		ni := findNode(t.StructGroup().TypeId())
		params := promiseFieldStructTemplateParams{
			Node:   n,
			Field:  f,
			Struct: ni,
		}
		if def, _ := slot.DefaultValue(); def.Which() == Value_Which_structField {
			if sf, _ := def.StructField(); capnp.HasData(sf) {
				params.Default = copyData(sf)
			}
		}
		templates.ExecuteTemplate(w, "promiseFieldStruct", params)
	case Type_Which_anyPointer:
		templates.ExecuteTemplate(w, "promiseFieldAnyPointer", promiseFieldAnyPointerTemplateParams{
			Node:  n,
			Field: f,
		})
	case Type_Which_interface:
		templates.ExecuteTemplate(w, "promiseFieldInterface", promiseFieldInterfaceTemplateParams{
			Node:      n,
			Field:     f,
			Interface: findNode(t.Interface().TypeId()),
		})
	}
}

type interfaceMethod struct {
	Method
	Interface    *node
	ID           int
	Name         string
	OriginalName string
	Params       *node
	Results      *node
}

func (n *node) methodSet(methods []interfaceMethod) []interfaceMethod {
	ms, _ := n.Interface().Methods()
	for i := 0; i < ms.Len(); i++ {
		m := ms.At(i)
		mname, _ := m.Name()
		mann, _ := m.Annotations()
		methods = append(methods, interfaceMethod{
			Method:       m,
			Interface:    n,
			ID:           i,
			OriginalName: mname,
			Name:         parseAnnotations(mann).Rename(mname),
			Params:       findNode(m.ParamStructType()),
			Results:      findNode(m.ResultStructType()),
		})
	}
	// TODO(light): sort added methods by code order

	supers, _ := n.Interface().Superclasses()
	for i := 0; i < supers.Len(); i++ {
		s := supers.At(i)
		methods = findNode(s.Id()).methodSet(methods)
	}
	return methods
}

func (n *node) defineInterfaceClient(w io.Writer) {
	m := n.methodSet(nil)
	nann, _ := n.Annotations()
	templates.ExecuteTemplate(w, "interfaceClient", interfaceClientTemplateParams{
		Node:        n,
		Annotations: parseAnnotations(nann),
		Methods:     m,
	})
}

func (n *node) defineInterfaceServer(w io.Writer) {
	m := n.methodSet(nil)
	nann, _ := n.Annotations()
	templates.ExecuteTemplate(w, "interfaceServer", interfaceServerTemplateParams{
		Node:        n,
		Annotations: parseAnnotations(nann),
		Methods:     m,
	})
}

type enumString []string

func (es enumString) ValueString() string {
	return strings.Join([]string(es), "")
}

func (es enumString) SliceFor(i int) string {
	n := 0
	for _, v := range es[:i] {
		n += len(v)
	}
	return fmt.Sprintf("[%d:%d]", n, n+len(es[i]))
}

func generateFile(reqf CodeGeneratorRequest_RequestedFile) (generr error) {
	defer func() {
		e := recover()
		if ae, ok := e.(assertionError); ok {
			generr = ae
		} else if e != nil {
			panic(e)
		}
	}()

	f := findNode(reqf.Id())
	var buf bytes.Buffer
	g_imports.init()
	g_segment = make([]byte, 0, 4096)
	g_bufname = fmt.Sprintf("x_%x", f.Id())

	for _, n := range f.nodes {
		if n.Which() == Node_Which_annotation {
			n.defineAnnotation(&buf)
		}
	}

	defineConstNodes(&buf, f.nodes)

	for _, n := range f.nodes {
		switch n.Which() {
		case Node_Which_enum:
			n.defineEnum(&buf)
		case Node_Which_structGroup:
			if !n.StructGroup().IsGroup() {
				n.defineStructTypes(&buf, n)
				n.defineStructEnums(&buf)
				n.defineNewStructFunc(&buf)
				n.defineStructFuncs(&buf)
				n.defineStructList(&buf)
				if *genPromises {
					n.defineStructPromise(&buf)
				}
			}
		case Node_Which_interface:
			n.defineInterfaceClient(&buf)
			n.defineInterfaceServer(&buf)
		}
	}

	fname, _ := reqf.Filename()
	if f.pkg == "" {
		return fmt.Errorf("missing package annotation for %s", fname)
	}

	if dirPath, _ := filepath.Split(fname); dirPath != "" {
		err := os.MkdirAll(dirPath, os.ModePerm)
		if err != nil {
			return err
		}
	}

	var unformatted bytes.Buffer
	fmt.Fprintf(&unformatted, "package %s\n\n", f.pkg)
	fmt.Fprintf(&unformatted, "// AUTO GENERATED - DO NOT EDIT\n\n")
	fmt.Fprintf(&unformatted, "import (\n")
	for _, imp := range g_imports.usedImports() {
		fmt.Fprintf(&unformatted, "%v\n", imp)
	}
	fmt.Fprintf(&unformatted, ")\n")
	unformatted.Write(buf.Bytes())
	if len(g_segment) > 0 {
		fmt.Fprintf(&unformatted, "var %s = []byte{", g_bufname)
		for i, b := range g_segment {
			if i%8 == 0 {
				fmt.Fprintf(&unformatted, "\n")
			}
			fmt.Fprintf(&unformatted, "%d,", b)
		}
		fmt.Fprintf(&unformatted, "\n}\n")
	}
	formatted, err := format.Source(unformatted.Bytes())
	if err != nil {
		fmt.Fprintln(os.Stderr, "Can't format generated code:", err)
		formatted = unformatted.Bytes()
	}

	file, err := os.Create(fname + ".go")
	if err != nil {
		return err
	}
	_, werr := file.Write(formatted)
	cerr := file.Close()
	if werr != nil {
		return err
	}
	if cerr != nil {
		return err
	}
	return nil
}

func main() {
	flag.Parse()

	msg, err := capnp.NewDecoder(os.Stdin).Decode()
	if err != nil {
		fmt.Fprintln(os.Stderr, "capnpc-go: Reading input:", err)
		os.Exit(1)
	}

	req, err := ReadRootCodeGeneratorRequest(msg)
	if err != nil {
		fmt.Fprintln(os.Stderr, "capnpc-go: Reading input:", err)
		os.Exit(1)
	}
	allfiles := []*node{}

	nodes, _ := req.Nodes()
	for i := 0; i < nodes.Len(); i++ {
		ni := nodes.At(i)
		n := &node{Node: ni}
		g_nodes[n.Id()] = n

		if n.Which() == Node_Which_file {
			allfiles = append(allfiles, n)
		}
	}

	for _, f := range allfiles {
		fann, _ := f.Annotations()
		ann := parseAnnotations(fann)
		f.pkg = ann.Package
		f.imp = ann.Import
		nnodes, _ := f.NestedNodes()
		for i := 0; i < nnodes.Len(); i++ {
			nn := nnodes.At(i)
			if ni := g_nodes[nn.Id()]; ni != nil {
				nname, _ := nn.Name()
				ni.resolveName("", nname, f)
			}
		}
	}

	success := true
	reqFiles, _ := req.RequestedFiles()
	for i := 0; i < reqFiles.Len(); i++ {
		reqf := reqFiles.At(i)
		fname, _ := reqf.Filename()
		err := generateFile(reqf)
		if err != nil {
			fmt.Fprintf(os.Stderr, "capnpc-go: Generating Go for %s failed: %v\n", fname, err)
			success = false
		}
	}
	if !success {
		os.Exit(1)
	}
}


text:
QuestionBank::Engine.routes.draw do
  root 'home#index'
  resources :questions do
    member do
      get :redo_question
    end
    collection do
      get :new_bool
      get :new_single_choice
      get :new_mapping
      get :new_multi_choice
      get :new_essay
      get :new_fill
      get :search
      get :do_question
    end
    member do
      post :do_question_validation
    end
  end

  resources :test_papers, shallow: true do
    post :preview, on: :collection
    resources :test_paper_results
  end

  resources :question_records do
    delete :batch_destroy, on: :collection
  end

  resources :question_flaws do
    post :batch_create, on: :collection
    delete :batch_destroy, on: :collection
  end

end


text:
> `npm install --save @types/qs`

# Summary
This package contains type definitions for qs (https://github.com/ljharb/qs).

# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/qs

Additional Details
 * Last updated: Wed, 25 Oct 2017 16:18:55 GMT
 * Dependencies: none
 * Global values: qs

# Credits
These definitions were written by Roman Korneev <https://github.com/RWander>, Leon Yu <https://github.com/leonyu>, Belinda Teh <https://github.com/tehbelinda>, Melvin Lee <https://github.com/zyml>, Arturs Vonda <https://github.com/artursvonda>, Carlos Bonetti <https://github.com/CarlosBonetti>.


text:
import re
from .RnfProfile import RnfProfile

segment_destr_pattern = re.compile(r'^\(([0-9]+),([0-9]+),([FRN]),([0-9]+),([0-9]+)\)$')

class Segment:
    """Class for a single segment in a RNF read name.
	"""

    def __init__(self, genome_id=0, chr_id=0, direction="N", left=0, right=0):
        """
		Args:
			genome_id (int): ID of genome.
			chr_id (int): ID of chromosome.
			direction (str): Direction (F/R/N).
			left (int): Leftmost coordinate.
			right (int): Rightmost coordinate.

		Raises:
			ValueError
		"""

        self.genome_id = int(genome_id)
        self.chr_id = int(chr_id)
        self.direction = direction
        self.left = int(left)
        self.right = int(right)

        if not (self.right == 0 or self.right >= self.left):
            smbl.messages.error(
                "Leftmost coordinate cannot be higher than rightmost coordinate.", program="RNFtools",
                subprogram="RNF format", exception=ValueError
            )

    def stringize(
        self,
        rnf_profile,
    ):
        """Create RNF representation of this segment.

		Args:
			rnf_profile (rnftools.rnfformat.RnfProfile): RNF profile (with widths).
		"""

        coor_width = max(rnf_profile.coor_width, len(str(self.left)), len(str(self.right)))
        return "({},{},{},{},{})".format(
            str(self.genome_id).zfill(rnf_profile.genome_id_width),
            str(self.chr_id).zfill(rnf_profile.chr_id_width), self.direction,
            str(self.left).zfill(coor_width),
            str(self.right).zfill(coor_width)
        )

    def destringize(self, string):
        """Get RNF values for this segment from its textual representation and
		save them into this object.

		Args:
			string (str): Textual representation of a segment.
		"""

        m = segment_destr_pattern.match(string)
        self.genome_id = int(m.group(1))
        self.chr_id = int(m.group(2))
        self.direction = m.group(3)
        self.left = int(m.group(4))
        self.right = int(m.group(5))

    def __str__(self, ):
        rnf_profile = RnfProfile()
        return self.stringize(rnf_profile)


text:
namespace blink {

class ApproximatedDeviceMemory {
 public:
  // Caches the device's physical memory in static members.
  static void BLINK_COMMON_EXPORT Initialize();

  // Returns an approximation of the physical memory rounded to the most
  // significant bit. This information is provided to web-developers to allow
  // them to customize the experience of their page to the possible available
  // device memory.
  static float BLINK_COMMON_EXPORT GetApproximatedDeviceMemory();

  // Override the value of the physical memory for testing.
  static void BLINK_COMMON_EXPORT SetPhysicalMemoryMBForTesting(int64_t);

 private:
  static void CalculateAndSetApproximatedDeviceMemory();

  static float approximated_device_memory_gb_;
  static int64_t physical_memory_mb_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_PUBLIC_COMMON_DEVICE_MEMORY_APPROXIMATED_DEVICE_MEMORY_H_


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

namespace CSharpFunctionalExtensions.ValueTasks
{
    public static partial class ResultExtensions
    {
        public static ValueTask<Result<K, E>> BindWithTransactionScope<T, K, E>(this Result<T, E> self, Func<T, ValueTask<Result<K, E>>> f)
            => WithTransactionScope(() => self.Bind(f));

        public static ValueTask<Result<K>> BindWithTransactionScope<T, K>(this Result<T> self, Func<T, ValueTask<Result<K>>> f)
            => WithTransactionScope(() => self.Bind(f));

        public static ValueTask<Result<K>> BindWithTransactionScope<K>(this Result self, Func<ValueTask<Result<K>>> f)
            => WithTransactionScope(() => self.Bind(f));

        public static ValueTask<Result> BindWithTransactionScope<T>(this Result<T> self, Func<T, ValueTask<Result>> f)
            => WithTransactionScope(() => self.Bind(f));

        public static ValueTask<Result> BindWithTransactionScope(this Result self, Func<ValueTask<Result>> f)
            => WithTransactionScope(() => self.Bind(f));
    }
}
#endif


text:
package com.speakingfish.common.mapper;

import com.speakingfish.common.function.Mapper;

public class ConstMapper<RESULT> implements Mapper<RESULT, Object> {

    protected final RESULT _value;

    public ConstMapper(RESULT value) {
        super();
        _value = value;
    }

    public RESULT apply(Object value) { return _value; }

}


text:
#pragma once

#include "../interactionbase_api.h"

#include "../commands/Command.h"

namespace Interaction {

class INTERACTIONBASE_API CSceneHandlerItemExit : public Command
{
	public:
		CSceneHandlerItemExit();

		virtual bool canInterpret(Visualization::Item* source, Visualization::Item* target,
										  const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>& cursor);
		virtual CommandResult* execute(Visualization::Item* source, Visualization::Item* target,
												 const QStringList& commandTokens,
												 const std::unique_ptr<Visualization::Cursor>& cursor);

		virtual QList<CommandSuggestion*> suggest(Visualization::Item* source, Visualization::Item* target,
																const QString& textSoFar,
																const std::unique_ptr<Visualization::Cursor>& cursor);
};

}


text:
use kvproto::encryptionpb::EncryptedContent;

use super::metadata::*;
use crate::crypter::*;
use crate::{AesGcmCrypter, Error, Iv, Result};

/// An in-memory backend, it saves master key in memory.
pub(crate) struct MemAesGcmBackend {
    pub key: Vec<u8>,
}

impl MemAesGcmBackend {
    pub fn new(key: Vec<u8>) -> Result<MemAesGcmBackend> {
        if key.len() != AesGcmCrypter::KEY_LEN {
            return Err(box_err!(
                "encryption method and key length mismatch, expect {} get {}",
                AesGcmCrypter::KEY_LEN,
                key.len()
            ));
        }
        Ok(MemAesGcmBackend { key })
    }

    pub fn encrypt_content(&self, plaintext: &[u8], iv: Iv) -> Result<EncryptedContent> {
        let mut content = EncryptedContent::default();
        content.mut_metadata().insert(
            MetadataKey::Method.as_str().to_owned(),
            MetadataMethod::Aes256Gcm.as_slice().to_vec(),
        );
        let iv_value = iv.as_slice().to_vec();
        content
            .mut_metadata()
            .insert(MetadataKey::Iv.as_str().to_owned(), iv_value);
        let (ciphertext, gcm_tag) = AesGcmCrypter::new(&self.key, iv).encrypt(plaintext)?;
        content.set_content(ciphertext);
        content.mut_metadata().insert(
            MetadataKey::AesGcmTag.as_str().to_owned(),
            gcm_tag.as_slice().to_owned(),
        );
        Ok(content)
    }

    // On decrypt failure, the rule is to return WrongMasterKey error in case it is possible that
    // a wrong master key has been used, or other error otherwise.
    pub fn decrypt_content(&self, content: &EncryptedContent) -> Result<Vec<u8>> {
        let method = content
            .get_metadata()
            .get(MetadataKey::Method.as_str())
            .ok_or_else(|| {
                // Missing method in metadata. The metadata of the encrypted content is invalid or
                // corrupted.
                Error::Other(box_err!(
                    "metadata {} not found",
                    MetadataKey::Method.as_str()
                ))
            })?;
        if method.as_slice() != MetadataMethod::Aes256Gcm.as_slice() {
            // Currently we only support aes256-gcm. A different method could mean the encrypted
            // content is written by a future version of TiKV, and we don't know how to handle it.
            // Fail immediately instead of fallback to previous key.
            return Err(Error::Other(box_err!(
                "encryption method mismatch, expected {:?} vs actual {:?}",
                MetadataMethod::Aes256Gcm.as_slice(),
                method
            )));
        }
        let key = &self.key;
        let iv_value = content
            .get_metadata()
            .get(MetadataKey::Iv.as_str())
            .ok_or_else(|| {
                // IV is missing. The metadata of the encrypted content is invalid or corrupted.
                Error::Other(box_err!("metadata {} not found", MetadataKey::Iv.as_str()))
            })?;
        let iv = Iv::from_slice(iv_value.as_slice())?;
        let tag = content
            .get_metadata()
            .get(MetadataKey::AesGcmTag.as_str())
            .ok_or_else(|| {
                // Tag is missing. The metadata of the encrypted content is invalid or corrupted.
                Error::Other(box_err!("gcm tag not found"))
            })?;
        let gcm_tag = AesGcmTag::from(tag.as_slice());
        let ciphertext = content.get_content();
        let plaintext = AesGcmCrypter::new(key, iv)
            .decrypt(ciphertext, gcm_tag)
            .map_err(|e|
                // Decryption error, likely caused by mismatched tag. It could be the tag is
                // corrupted, or the encrypted content is fake by an attacker, but more likely
                // it is caused by a wrong master key being used.
                Error::WrongMasterKey(box_err!("decrypt in GCM mode failed: {}", e)))?;
        Ok(plaintext)
    }
}

#[cfg(test)]
mod tests {
    use hex::FromHex;
    use matches::assert_matches;

    use super::*;

    #[test]
    fn test_mem_backend_ase_256_gcm() {
        // See more http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip
        let pt = Vec::from_hex("25431587e9ecffc7c37f8d6d52a9bc3310651d46fb0e3bad2726c8f2db653749")
            .unwrap();
        let ct = Vec::from_hex("84e5f23f95648fa247cb28eef53abec947dbf05ac953734618111583840bd980")
            .unwrap();
        let key = Vec::from_hex("c3d99825f2181f4808acd2068eac7441a65bd428f14d2aab43fefc0129091139")
            .unwrap();
        let iv = Vec::from_hex("cafabd9672ca6c79a2fbdc22").unwrap();

        let backend = MemAesGcmBackend::new(key).unwrap();
        let iv = Iv::from_slice(iv.as_slice()).unwrap();
        let encrypted_content = backend.encrypt_content(&pt, iv).unwrap();
        assert_eq!(encrypted_content.get_content(), ct.as_slice());
        let plaintext = backend.decrypt_content(&encrypted_content).unwrap();
        assert_eq!(plaintext, pt);
    }

    #[test]
    fn test_mem_backend_authenticate() {
        let pt = vec![1u8, 2, 3];
        let key = Vec::from_hex("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
            .unwrap();

        let backend = MemAesGcmBackend::new(key).unwrap();
        let encrypted_content = backend.encrypt_content(&pt, Iv::new_gcm()).unwrap();
        let plaintext = backend.decrypt_content(&encrypted_content).unwrap();
        assert_eq!(plaintext, pt);

        // Must fail is method not found.
        let mut encrypted_content_missing_method = encrypted_content.clone();
        encrypted_content_missing_method
            .mut_metadata()
            .remove(MetadataKey::Method.as_str());
        assert_matches!(
            backend
                .decrypt_content(&encrypted_content_missing_method)
                .unwrap_err(),
            Error::Other(_)
        );

        // Must fail if method is not aes256-gcm.
        let mut encrypted_content_invalid_method = encrypted_content.clone();
        let mut invalid_suffix = b"_invalid".to_vec();
        encrypted_content_invalid_method
            .mut_metadata()
            .get_mut(MetadataKey::Method.as_str())
            .unwrap()
            .append(&mut invalid_suffix);
        assert_matches!(
            backend
                .decrypt_content(&encrypted_content_invalid_method)
                .unwrap_err(),
            Error::Other(_)
        );

        // Must fail if tag not found.
        let mut encrypted_content_missing_tag = encrypted_content.clone();
        encrypted_content_missing_tag
            .mut_metadata()
            .remove(MetadataKey::AesGcmTag.as_str());
        assert_matches!(
            backend
                .decrypt_content(&encrypted_content_missing_tag)
                .unwrap_err(),
            Error::Other(_)
        );

        // Must fail with WrongMasterKey error due to mismatched tag.
        let mut encrypted_content_mismatch_tag = encrypted_content;
        encrypted_content_mismatch_tag
            .mut_metadata()
            .get_mut(MetadataKey::AesGcmTag.as_str())
            .unwrap()[0] ^= 0b11111111u8;
        assert_matches!(
            backend
                .decrypt_content(&encrypted_content_mismatch_tag)
                .unwrap_err(),
            Error::WrongMasterKey(_)
        );
    }
}


text:
import Ember from 'ember';
import DS from 'ember-data';
import config from 'travis/config/environment';

export default DS.RESTAdapter.extend({
  auth: Ember.inject.service(),
  host: config.apiEndpoint,

  sortQueryParams: false,
  coalesceFindRequests: false,
  headers: {
    'Travis-API-Version': '3',
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  ajaxOptions: function(url, type, options) {
    var hash = this._super(...arguments);

    hash.headers = hash.headers || {};

    var token;
    if(token = this.get('auth').token()) {
      hash.headers['Authorization'] = "token " + token;
    }

    return hash;
  },

  // TODO: I shouldn't override this method as it's private, a better way would
  // be to create my own URL generator
  _buildURL: function(modelName, id) {
    var url = [];
    var host = Ember.get(this, 'host');
    var prefix = this.urlPrefix();
    var path;

    if (modelName) {
      path = this.pathForType(modelName, id);
      if (path) { url.push(path); }
    }

    if (id) { url.push(encodeURIComponent(id)); }
    if (prefix) { url.unshift(prefix); }

    url = url.join('/');
    if (!host && url && url.charAt(0) !== '/') {
      url = '/' + url;
    }

    return url;
  },

  pathForType: function(modelName, id) {
    var underscored = Ember.String.underscore(modelName);
    return id ? underscored :  Ember.String.pluralize(underscored);
  }
});


text:
layout: post
microblog: true
audio:
photo: http://microblog.curtclifton.net/uploads/2018/1bf87e7184.jpg
date: 2018-01-03 17:20:53 -0700
guid: http://curt.micro.blog/2018/01/04/arrived-checked-in.html
---
Arrived, checked in, and unloaded. #operationflair complete for now.

<img src="http://microblog.curtclifton.net/uploads/2018/1bf87e7184.jpg" width="600" height="600" />


text:
import re
import os.path
import sys

class tokenizer(object):

    def __init__(self,):

        self.FUNCTION = 1
        self.PRE = 2
        self.POST = 3

        # Substitution vectors
        self.presubvector = []
        self.funcvector = {}
        self.postsubvector = []

        return

    def add_regex(self, filename, op_seq='pre'):
        '''Reads an list of substitution vectors'''
        with open(filename, 'rU') as fp:
            data = fp.read().split('\n')
        findflag = False
        findstr = ''
        for line in data:
            if not line.startswith('#'):
                if findflag:
                    if op_seq == self.PRE or op_seq == 'pre':
                        self.presubvector.append((re.compile(findstr),
                                                  findstr, line))
                    else:
                        self.postsubvector.append((re.compile(findstr),
                                                   findstr, line))
                    findflag = False
                else:
                    findstr = line
                    findflag = True
        return

    def add_abbrev(self, abbrevfile, op_seq='pre'):
        '''
        Computes the contraction of period and adds them to the
        substitution vector
        '''
        with open(abbrevfile, 'rU') as fp:
            data = fp.read().split('\n')
        source = [re.sub('^ \. ', '.', re.sub('\.', ' *\. *', item))
                  for item in data
                  if not item.startswith('#')]
        data = [re.sub('\.$', '. ', item) for item in data
                if not item.startswith('#')]
        subvector = [(re.compile(source[i]), source[i], item)
                     for i, item in enumerate(data)
                     if item.strip() != '']
        if op_seq == self.PRE or op_seq == 'pre':
            self.presubvector += subvector
        else:
            self.postsubvector += subvector
        return

    def add_function_repo(self, funcfile, test=False):
        '''
        Adds all L1 functions to the current object.
        '''
        fnre = re.compile('\ndef (.*)\(')
        with open(funcfile, 'rU') as fp:
            code = '\n' + fp.read()
        funclist = fnre.findall(code)
        funcpath, funcmodule = os.path.split(re.sub('.pyc*$', '', funcfile))
        if funcpath != '':
            sys.path.insert(0, funcpath)
        fn = __import__(funcmodule, globals(), locals(), funclist, -1)
        if test:
            testfn = lambda x: ((x.func_code.co_argcount == 1)
                                and (type('inp') == type(x('inp'))))
        else:
            testfn = lambda x: (x.func_code.co_argcount == 1)
        fndict = {funcmodule + '.' + funcname: getattr(fn, funcname)
                  for funcname in funclist if testfn(getattr(fn, funcname))}
        self.funcvector.update(fndict)
        return

    def add_function(self, fnvectfile, op_seq='pre'):
        with open(fnvectfile, 'rU') as fp:
            data = fp.read().split('\n')
        fnsubvector = [(self.funcvector[item.strip()], item, self.FUNCTION)
                       for item in data if item.strip() != '']
        if op_seq == self.PRE or op_seq == 'pre':
            self.presubvector += fnsubvector
        else:
            self.postsubvector += fnsubvector
        return

    def sub(self, data, op_seq='pre'):
        '''Runs the substitution vector on data'''
        if op_seq == self.PRE or op_seq == 'pre':
            subvector = self.presubvector
        else:
            subvector = self.postsubvector

        for subre, findstr, replacestr in subvector:
            if replacestr == self.FUNCTION:
                if op_seq == self.PRE or op_seq == 'pre':
                    data = subre(data)
                else:
                    data = [subre(item) for item in data]
            else:
                if op_seq == self.PRE:
                    data = subre.sub(replacestr, data)
                else:
                    data = [subre.sub(replacestr, item) for item in data]
        return data

    def tokenize(self, data):
        return self.sub(self.sub(data, self.PRE).split(' '), self.POST)


text:
package herddb.model;

/**
 * A Data-definition-language command. That is a mutation on the schema, for
 * instance creation of a table
 *
 * @author enrico.olivelli
 */
public abstract class DDLStatement extends Statement {

    public DDLStatement(String tableSpace) {
        super(tableSpace);
    }
}


text:
ACCEPTED

#### According to
Paleobiology Database

#### Published in
null

#### Original name
null

### Remarks
null


text:
package org.pmoo.monopoly;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class CalleImpuestosTest {

	CalleImpuestos auxC;
	Jugador auxJ;

	@Before
	public void setUp() throws Exception {
		auxC= new CalleImpuestos("CallePrueba", 4);
		auxJ= new Jugador("JugadorPrueba", 1);
	}

	@After
	public void tearDown() throws Exception {
		auxC= null;
		auxJ= null;
	}

	@Test
	public void testRealizarOperacion() {
		System.out.println("Movemos a JugadorPrueba a la casilla 4 para que tenga que pagar los impuestos.");
		auxJ.actualizarPosicion(4);
		auxC.realizarOperacion(auxJ);
	}

	@Test
	public void testImprimirInfoCalle() {
		System.out.println("Debería imprimir la informacion de la calle.");
		auxC.imprimirInfoCalle();
	}

	@Test
	public void testCalleImpuestos() {
		assertNotNull(auxC);
	}

}


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

namespace MVC4ManyToMany.Models.ViewModels
{
    public class UserProfileViewModel
    {
        public UserProfileViewModel()
        {
            Courses = new Collection<AssignedCourseData>();
        }

        public int UserProfileID { get; set; }
        public string Name { get; set; }
        public virtual ICollection<AssignedCourseData> Courses { get; set; }
    }
}


text:
PyDNApsenac module
==================

.. automodule:: PyDNApsenac
    :members:
    :undoc-members:
    :show-inheritance:


text:
module="ds18b20"
device="ds18b20"
# remove module with rmmod
# and use a pathname, as newer modutils don't look in . by default
/sbin/rmmod ./$module.ko
# remove stale nodes
rm -f /dev/${device}