text:
package org.apache.jackrabbit.j2ee;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import junit.framework.TestCase;

import org.apache.catalina.startup.Tomcat;
import org.apache.commons.io.FileUtils;
import org.apache.http.conn.HttpHostConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class TomcatIT extends TestCase {

    static {
        SLF4JBridgeHandler.install();
    }

    private static Logger LOG = LoggerFactory.getLogger(TomcatIT.class);

    private URL url;

    private Tomcat tomcat;

    private WebClient client;

    protected void setUp() throws Exception {
        File war = null;
        for (File f : new File("target").listFiles()) {
            if (f.isDirectory() && new File(f, "WEB-INF/web.xml").isFile()) {
                war = f;
                break;
            }
        }
        assertNotNull(war);

        File bootstrap = new File("target", "bootstrap.properties");
        bootstrap.delete();
        RepositoryAccessServlet.bootstrapOverride = bootstrap.getPath();
        RepositoryStartupServlet.bootstrapOverride = bootstrap.getPath();

        File baseDir = new File("target", "tomcat");
        FileUtils.deleteQuietly(baseDir);

        File repoDir = new File("target", "repository");
        FileUtils.deleteQuietly(repoDir);

        url = new URL("http://localhost:12856/");

        tomcat = new Tomcat();
        tomcat.setSilent(true);
        tomcat.setBaseDir(baseDir.getPath());
        tomcat.setHostname(url.getHost());
        tomcat.setPort(url.getPort());

        tomcat.addWebapp("", war.getAbsolutePath());

        tomcat.start();

        client = new WebClient();
    }

    public void testTomcat() throws Exception {
        HtmlPage page = null;

        try {
            page = client.getPage(url);
        } catch (HttpHostConnectException e) {
            // sometimes on jenkins there are connections exceptions.
            // ignoring the rest of the test in this case
            LOG.error("Failed connecting to tomcat", e);
            return;
        }

        assertEquals("Content Repository Setup", page.getTitleText());

        page = submitNewRepositoryForm(page);
        assertEquals("Content Repository Ready", page.getTitleText());

        page = page.getAnchorByText("home").click();
        assertEquals("Apache Jackrabbit JCR Server", page.getTitleText());
    }

    private HtmlPage submitNewRepositoryForm(HtmlPage page) throws IOException {
        for (HtmlForm form : page.getForms()) {
            for (HtmlInput mode : form.getInputsByName("mode")) {
                if ("new".equals(mode.getValueAttribute())) {
                    for (HtmlInput home : form.getInputsByName("repository_home")) {
                        home.setValueAttribute("target/repository");
                        for (HtmlElement submit : form.getElementsByAttribute("input", "type", "submit")) {
                            return submit.click();
                        }
                    }
                }
            }
        }
        fail();
        return null;
    }

    protected void tearDown() throws Exception {
        client.closeAllWindows();

        tomcat.stop();
    }

}


text:
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Apache.Arrow.Tests
{
    /// <summary>
    /// The <see cref="TestDateAndTimeData"/> class holds example dates and times useful for testing.
    /// </summary>
    internal static class TestDateAndTimeData
    {
        private static readonly DateTime _earliestDate = new DateTime(1, 1, 1);
        private static readonly DateTime _latestDate = new DateTime(9999, 12, 31);

        private static readonly DateTime[] _exampleDates =
        {
            _earliestDate, new DateTime(1969, 12, 31), new DateTime(1970, 1, 1), new DateTime(1970, 1, 2),
            new DateTime(1972, 6, 30), new DateTime(2015, 6, 30), new DateTime(2016, 12, 31), new DateTime(2020, 2, 29),
            new DateTime(2020, 7, 1), _latestDate,
        };

        private static readonly TimeSpan[] _exampleTimes =
        {
            new TimeSpan(0, 0, 1), new TimeSpan(12, 0, 0), new TimeSpan(23, 59, 59),
        };

        private static readonly DateTimeKind[] _exampleKinds =
        {
            DateTimeKind.Local, DateTimeKind.Unspecified, DateTimeKind.Utc,
        };

        private static readonly TimeSpan[] _exampleOffsets =
        {
            TimeSpan.FromHours(-2),
            TimeSpan.Zero,
            TimeSpan.FromHours(2),
        };

        /// <summary>
        /// Gets a collection of example dates (i.e. with a zero time component), of all different kinds.
        /// </summary>
        public static IEnumerable<DateTime> ExampleDates =>
            from date in _exampleDates
            from kind in _exampleKinds
            select DateTime.SpecifyKind(date, kind);

        /// <summary>
        /// Gets a collection of example date/times, of all different kinds.
        /// </summary>
        public static IEnumerable<DateTime> ExampleDateTimes =>
            from date in _exampleDates
            from time in _exampleTimes
            from kind in _exampleKinds
            select DateTime.SpecifyKind(date.Add(time), kind);

        /// <summary>
        /// Gets a collection of example date time offsets.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<DateTimeOffset> ExampleDateTimeOffsets =>
            from date in _exampleDates
            from time in _exampleTimes
            from offset in _exampleOffsets
            where !(date == _earliestDate && offset.Ticks > 0)
            where !(date == _latestDate && offset.Ticks < 0)
            select new DateTimeOffset(date.Add(time), offset);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package guitests;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import seedu.flexitrack.testutil.TypicalTestTasks;

public class CommandBoxTest extends FlexiTrackGuiTest {

    @Test
    public void commandBox_commandSucceeds_textCleared() {
        commandBox.runCommand(TypicalTestTasks.homework2.getAddCommand());
        assertEquals(commandBox.getCommandInput(), "");
    }

    @Test
    public void commandBox_commandFails_textStays() {
        commandBox.runCommand("invalid command");
        assertEquals(commandBox.getCommandInput(), "invalid command");
        // TODO: confirm the text box color turns to red
    }

}


text:
KANColle ExPedition ToolSets

## Changelog

### 0.1.2 (pending)

- support for A1 A2 A3 B1
- (TODO) support for B2
- (TODO) implement a page for general info & version number & changelog


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Choneco</logradouro><bairro>Vila Ré</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>03657060</cep></feed>


text:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import copy

class Prob:

    def __init__(self, filename):

        print "Begin Loading..."
        sys.stdout.flush()
        self.load(filename)

    def printto(self, args):
        self.output = self.output + str(args)

    def smooth_data(self, l,smooth=3):
        result = []
        for id in xrange(len(l)):
            start = max(0, id - smooth)
            finish = min(len(l)-1, id+smooth)
            res = 0.0
            for tmp in xrange(start, finish+1):
                res +=l[tmp]
            res = res * (1./ float(finish - start + 1))
            result.append(res)
        return result

    def smooth(self, smooth = 1):
        for word in self.data.keys():
            for sense in self.data[word]:
                self.data[word][sense] = self.smooth_data(self.data[word][sense])

    def load(self, filename):
        self.data = {}
        with open(filename) as fin:
            while True:
                line = fin.readline()
                if not line:
                    break

                words = line.strip().split()
                word = words[0]
                self.data[word] = {}
                sense_number = int(words[1])
                for _ in range(sense_number):
                    words = fin.readline().strip().split()
                    sense = int(words[0])
                    self.data[word][sense] = {}
                    self.data[word][sense] = [float(item) * 100 for item in words[1:]]

    def search(self, word, smooth = 3):
        if word not in self.data:
            return "\"\""
        data_items = copy.deepcopy(self.data[word])
        print data_items
        for key in data_items.keys():
            data_items[key] = self.smooth_data(data_items[key], smooth)
        print data_items

        self.output = ""
        with open("./templates/data.tsv", "w") as fout:
            self.printto("date")
            result = data_items.keys()
            for result_item in result:
                self.printto("\\t")
                self.printto(result_item)
                l = len(data_items[result_item])
            for i in range(l):
                self.printto("\\n")
                self.printto(1950+i)
                for result_item in result:
                    self.printto("\\t")
                    self.printto(data_items[result_item][i])
        return "\""+self.output +"\""

if __name__=="__main__":
    s = Prob("./../NewData/rmrb.prob.all")
    while True:
        word = raw_input("Please input a word :  ")
        if word == "EXIT":
            break
        print s.search(word)


text:
package com.egzosn.pay.common.http;

import com.egzosn.pay.common.bean.CertStoreType;

import java.io.*;

/**
 * HTTP 配置
 * @author egan
 *  <pre>
 * email egzosn@gmail.com
 * date 2017/3/3 20:48
 *  </pre>
 */
public class HttpConfigStorage {
    /**
     * http代理地址
     */
    private String httpProxyHost;
    /**
     * 代理端口
     */
    private int httpProxyPort;
    /**
     * 请求授权用户名
     */
    private String authUsername;
    /**
     * 请求授权密码
     */
    private String authPassword;

    /**
     * 证书存储类型
     * @see #keystore 是否为https请求所需的证书(PKCS12)的地址,默认为地址,否则为证书信息串,文件流
     */
    private CertStoreType certStoreType = CertStoreType.PATH;

    /**
     * https请求所需的证书(PKCS12)
     * 证书内容
     */
    private Object keystore;
    /**
     * 证书对应的密码
     */
    private String storePassword;
    /**
     * 最大连接数
     */
    private int maxTotal = 0;
    /**
     * 默认的每个路由的最大连接数
     */
    private int defaultMaxPerRoute = 0;
    /**
     * 默认使用的响应编码
     */
    private String charset;

    private int socketTimeout = -1;

    private int connectTimeout = -1;

    /**
     * http代理地址
     * @return http代理地址
     */
    public String getHttpProxyHost() {
        return httpProxyHost;
    }

    public void setHttpProxyHost(String httpProxyHost) {
        this.httpProxyHost = httpProxyHost;
    }

    /**
     *   代理端口
     * @return 代理端口
     */
    public int getHttpProxyPort() {
        return httpProxyPort;
    }

    public void setHttpProxyPort(int httpProxyPort) {
        this.httpProxyPort = httpProxyPort;
    }

    /**
     * 请求授权用户名
     * @return 用户名
     */
    public String getAuthUsername() {
        return authUsername;
    }

    public void setAuthUsername(String authUsername) {
        this.authUsername = authUsername;
    }
    /**
     * 请求授权密码
     * @return 密码
     */
    public String getAuthPassword() {
        return authPassword;
    }

    public void setAuthPassword(String authPassword) {
        this.authPassword = authPassword;
    }

    public CertStoreType getCertStoreType() {
        return certStoreType;
    }

    public void setCertStoreType(CertStoreType certStoreType) {
        this.certStoreType = certStoreType;
    }

    /**
     * 获取证书信息
     * @return 证书信息 根据 {@link #getCertStoreType()}进行区别地址与信息串
     * @throws IOException 找不到文件异常
     */
    public InputStream getKeystoreInputStream() throws IOException {
        if (null == keystore) {
            return null;
        }
        return certStoreType.getInputStream(keystore);
    }
    /**
     * 获取证书信息
     * @return 证书信息 根据 {@link #getCertStoreType()}进行区别地址与信息串
     */
    public Object getKeystore() {
        return  keystore;
    }
    /**
     * 获取证书信息 证书地址
     * @return 证书信息 根据 {@link #getCertStoreType()}进行区别地址与信息串
     */
    public String getKeystoreStr() {
        return (String) keystore;
    }

    /**
     * 设置证书字符串信息或证书绝对地址
     * @param keystore 证书信息字符串信息或证书绝对地址
     */
    public void setKeystore(String keystore) {
        this.keystore = keystore;
    }
    /**
     * 设置证书字符串信息输入流
     * @param keystore 证书信息 输入流
     */
    public void setKeystore(InputStream keystore) {
        this.keystore = keystore;
    }

    /**
     * 证书对应的密码
     * @return 密码
     */
    public String getStorePassword() {
        return storePassword;
    }

    public void setStorePassword(String storePassword) {
        this.storePassword = storePassword;
    }

    public int getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public int getDefaultMaxPerRoute() {
        return defaultMaxPerRoute;
    }

    public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {
        this.defaultMaxPerRoute = defaultMaxPerRoute;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public int getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }
}


text:
package org.apache.flex.compiler.internal.fxg.dom.types;

/**
 * The InterpolationMethod enumeration determines how colors are interpolated
 * across a gradient.
 *
 * The enumeration order is significant and matches the SWF specification for
 * the InterpolationMode property of the GRADIENT structure.
 *
 * <pre>
 *   0 = rgb
 *   1 = linearRGB
 * </pre>
 */
public enum InterpolationMethod
{
    /**
     * The enum representing an 'rgb' interpolation type.
     */
    RGB,

    /**
     * The enum representing a 'linearRGB' interpolation type.
     */
    LINEAR_RGB;
}


text:
define(['exports', 'module', './function/debounce', './function/identity', './function/negate', './function/noop', './function/toProp', './function/toMax', './function/toMin', './function/toSum', './function/toUnique'], function (exports, module, _functionDebounce, _functionIdentity, _functionNegate, _functionNoop, _functionToProp, _functionToMax, _functionToMin, _functionToSum, _functionToUnique) {
    'use strict';

    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

    var _debounce = _interopRequireDefault(_functionDebounce);

    var _identity = _interopRequireDefault(_functionIdentity);

    var _negate = _interopRequireDefault(_functionNegate);

    var _noop = _interopRequireDefault(_functionNoop);

    var _toProp = _interopRequireDefault(_functionToProp);

    var _toMax = _interopRequireDefault(_functionToMax);

    var _toMin = _interopRequireDefault(_functionToMin);

    var _toSum = _interopRequireDefault(_functionToSum);

    var _toUnique = _interopRequireDefault(_functionToUnique);

    /*
    * Utility functions for generating helper functions
    */

    module.exports = {
        // debounce function calls to reduce impact of event spamming
        debounce: _debounce['default'],

        // return first argument, useful for filtering out falsy values
        // identity(myObject) === myObject
        identity: _identity['default'],

        // converts a functions to one that returns its opposite
        // isAuthenticated(userId); // false
        // var isUnauthenticated = negate(isAuthenticated);
        // isUnauthenticated(userId); // true
        negate: _negate['default'],

        // do nothing, useful for function placeholders or functional programming
        // (callback || noop)(callbackArgs);
        noop: _noop['default'],

        // useful for passing into mapping functions
        // var userIds = users.map(toProp('id'));
        toProp: _toProp['default'],

        // useful for finding max in array
        // var total = [0, 1, 2, 3].reduce(toMax());
        // returns 3
        toMax: _toMax['default'],

        // useful for finding max in array
        // var total = [0, 1, 2, 3].reduce(toMin());
        // returns 0
        toMin: _toMin['default'],

        // useful for adding up properties of an array
        // var total = [0, 1, 2, 3].reduce(toSum());
        // returns 6
        toSum: _toSum['default'],

        // useful for filtering out duplicates
        // var activeUsers = recentLoginIds.filter(toUnique());
        toUnique: _toUnique['default']
    };
});


text:
set -ue

DOWNLOAD_BASE_URL=https://google-api-python-client.googlecode.com/files
DOWNLOAD_FILENAME=google-api-python-client-gae-1.2.zip
EXTRACT_DIRECTORY=api-python-client

SCRIPT_DIR=$( dirname $0)
ROOT_DIR=$( dirname $SCRIPT_DIR)

if [ ! -d $ROOT_DIR/$EXTRACT_DIRECTORY ]
then
  echo -e "\n*** Downloading $DOWNLOAD_BASE_URL/$DOWNLOAD_FILENAME ***\n"
  curl -s $DOWNLOAD_BASE_URL/$DOWNLOAD_FILENAME -o /tmp/$DOWNLOAD_FILENAME || exit
  echo "Done"

  echo -e "\n*** Extracting /tmp/$DOWNLOAD_FILENAME into $ROOT_DIR/$EXTRACT_DIRECTORY ***\n"
  #mkdir $ROOT_DIR/$EXTRACT_DIRECTORY
  unzip -q /tmp/$DOWNLOAD_FILENAME -d $ROOT_DIR/$EXTRACT_DIRECTORY
  echo "Done"
fi


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.ComponentModel.Composition;
using Microsoft.Common.Core.Shell;
using Microsoft.Languages.Editor.DragDrop;
using Microsoft.R.Components.ContentTypes;
using Microsoft.R.Components.InteractiveWorkflow;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.DragDrop;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.R.Editor.DragDrop {
    [Export(typeof(IDropHandlerProvider))]
    [ContentType(RContentTypeDefinition.ContentType)]
    [DropFormat(DataObjectFormats.VSProjectItems)]
    [Name("RDropHandlerProvider")]
    [Order(Before = "DefaultFileDropHandler")]
    internal sealed class DropHandlerProvider : IDropHandlerProvider {
        private readonly ICoreShell _shell;
        private readonly IRInteractiveWorkflowProvider _workflowProvider;

        [ImportingConstructor]
        public DropHandlerProvider(ICoreShell shell, IRInteractiveWorkflowProvider workflowProvider) {
            _shell = shell;
            _workflowProvider = workflowProvider;
        }

        public IDropHandler GetAssociatedDropHandler(IWpfTextView wpfTextView)
        => wpfTextView.Properties.GetOrCreateSingletonProperty(() => new DropHandler(wpfTextView, _shell.Services, _workflowProvider));
    }
}


text:
package info.armado.ausleihe.admin.remote.services

import info.armado.ausleihe.admin.transport.dataobjects.IdentityCardDTO
import info.armado.ausleihe.admin.transport.responses.{AddIdentityCardsResponseDTO, VerifyIdentityCardsResponseDTO}
import info.armado.ausleihe.admin.util.DTOExtensions.{IdentityCardDTOExtension, IdentityCardExtension}
import info.armado.ausleihe.database.access.IdentityCardDao
import info.armado.ausleihe.database.barcode.{Barcode, ValidBarcode, ValidateBarcode}
import info.armado.ausleihe.database.dataobjects.Prefix
import javax.enterprise.context.RequestScoped
import javax.inject.Inject
import javax.transaction.Transactional
import javax.ws.rs._
import javax.ws.rs.core.{MediaType, Response}

@Path("/identity-cards")
@RequestScoped
class IdentityCardService {
  @Inject
  var identityCardDao: IdentityCardDao = _

  /**
    * Adds a list of identity cards to the database.
    * Before the identity cards are added, the input data is first verified and validated.
    * If at least one input entry is invalid, because for example its barcode is already contained in the database,
    * the whole method terminates and no identity card is added to the database.
    * In both the successful and the unsuccessful cases, an [[AddIdentityCardsResponseDTO]] object is returned
    *
    * @param identityCardDtos The identity cards to be added
    * @return A response object, containing the result of the operation
    */
  @PUT
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Path("/add")
  @Transactional
  def addIdentityCards(identityCardDtos: Array[IdentityCardDTO]): AddIdentityCardsResponseDTO = verify(identityCardDtos) match {
    case VerifyIdentityCardsResponseDTO(true, Array(), Array()) => {
      // convert IdentityCardDTO objects to IdentityCard objects
      val identityCards = identityCardDtos.map(_.toIdentityCard)

      // insert the IdentityCard objects into the database
      identityCardDao.insert(identityCards)

      // send success result to the client
      AddIdentityCardsResponseDTO(true)
    }
    case VerifyIdentityCardsResponseDTO(false, alreadyExistingBarcodes, duplicateBarcodes) => {
      // the given identity card information are not valid
      AddIdentityCardsResponseDTO(alreadyExistingBarcodes, duplicateBarcodes)
    }
    case _ => throw new WebApplicationException(Response.Status.PRECONDITION_FAILED);
  }

  private def verify(identityCardDtos: Array[IdentityCardDTO]): VerifyIdentityCardsResponseDTO = {
    // find entries with wrong or already existing barcodes
    val alreadyExistingIdentityCardBarcodes = identityCardDtos.filter(identityCards => ValidateBarcode(identityCards.barcode) match {
      case ValidBarcode(barcode@Barcode(Prefix.IdentityCards, _, _)) => identityCardDao.exists(barcode)
      case _ => true
    }).map(_.barcode)

    // find all duplicate barcodes
    var duplicateIdentityCardBarcodes = identityCardDtos
      .map(_.barcode).groupBy(identity).collect { case (x, Array(_, _, _*)) => x }.toArray

    VerifyIdentityCardsResponseDTO(alreadyExistingIdentityCardBarcodes, duplicateIdentityCardBarcodes)
  }

  /**
    * Selects all identity cards from the database
    *
    * @return An array containing all identity cards inside the database
    */
  @GET
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Path("/all")
  @Transactional
  def selectAllIdentityCards(): Array[IdentityCardDTO] =
    identityCardDao.selectAll().map(_.toIdentityCardDTO).toArray

  /**
    * Selects all identity cards from the database, that have a barcode, which is contained in the given `barcodes` array.
    * If no identity cards can be found for a given barcode, the barcode is ignored
    *
    * @param barcodes An array containing the barcodes of all queried identity cards
    * @return An array containing the found identity cards belonging to the given barcodes
    */
  @POST
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Path("/select")
  @Transactional
  def selectIdentityCards(barcodes: Array[String]): Array[IdentityCardDTO] =
    barcodes.flatMap(barcode => ValidateBarcode(barcode) match {
      case ValidBarcode(barcode@Barcode(Prefix.IdentityCards, _, _)) => identityCardDao.selectByBarcode(barcode)
      case _ => None
    }).map(_.toIdentityCardDTO)

  /**
    * Verifies a given list of identity cards, if they:
    * - don't already exist in the database
    *
    * @param identityCards The identity card information to be checked
    * @return A response wrapping a [[VerifyIdentityCardsResponseDTO]] object
    */
  @PUT
  @Produces(Array(MediaType.APPLICATION_JSON))
  @Consumes(Array(MediaType.APPLICATION_JSON))
  @Path("/verify")
  @Transactional
  def verifyIdentityCards(identityCards: Array[IdentityCardDTO]): VerifyIdentityCardsResponseDTO = verify(identityCards)
}


text:
require "liquid"
require_relative "helpers"

module Jekyll

  # Liquid tag for simplistic HTML gallery catalog

  class SVGCatalog < Liquid::Tag

    def initialize(tag, text, tokens)
      super

      # Split tag text for catalog parameters. Not robust!

      @params  = text.split(/\s*\/\/\s*/)
      @height  = (@params[0] || "110").strip.to_i
      @columns = (@params[1] || "4").strip.to_i

      # Setup Liquid template file

      liquid    = template_file(__dir__, "catalog")
      @template = File.read(liquid)
    end

    def render(context)

      # Find the galleries root directory

      site = context.registers[:site]
      root = site.config["galleries"]
      root = "#{__dir__}/../#{root}"
      base = site.config["baseurl"]

      # Collate gallery directories

      catalog = galleries_under(root).map do |dir|
        sample = sample_dir(dir, "svg")
        file   = deploy_path(sample)

        {"file"    => file,
         "dir"     => deploy_gallery(file),
         "base"    => base,
         "height"  => @height,
         "count"   => file_count(dir, "svg"),
         "caption" => gallery_name(dir)}
      end

      # Generate catalog HTML from Liquid template

      parsed = Liquid::Template.parse(@template)
      parsed.render("catalog" => catalog)
    end
  end
end

Liquid::Template.register_tag('SVG_catalog', Jekyll::SVGCatalog)


text:
<Alloy>
	<Window id="login" title="Login" class="loginContainer" onOpen="doOpen" >
		<Label id='loginText'></Label>
		<View id="lvContainer" >
			<TextField id="email" class='tfWrapper' hintText="Email" />
			<TextField id="password" class='tfWrapper' hintText="Password" passwordMask="true"/>
			<View class="centerHelper">
				<Button id="doLoginBtn" color="#fff" title="Login" />
			</View>
		</View>
	</Window>
</Alloy>


text:
- host, host cpu : Executes the HIP runtime API and is capable of initiating kernel launches to one or more devices.
- default device : Each host thread maintains a "default device".
Most HIP runtime APIs (including memory allocation, copy commands, kernel launches) do not use accept an explicit device
argument but instead implicitly use the default device.
The default device can be set with hipSetDevice.

- "active host thread" - the thread which is running the HIP APIs.

- completion_future becomes ready. "Completes".

- hcc = Heterogeneous Compute Compiler (https://bitbucket.org/multicoreware/hcc/wiki/Home).

- hipify tools - tools to convert CUDA(R) code to portable C++ code (https://github.com/ROCm-Developer-Tools/HIPIFY).
- hipconfig - tool to report various configuration properties of the target platform.

- nvcc = nvcc compiler, do not capitalize.
- hcc  = heterogeneous compute compiler, do not capitalize.


text:
namespace aliyun {
struct CmsQueryMetricTopNRequestType {
  std::string project;
  std::string metric;
  std::string period;
  std::string start_time;
  std::string end_time;
  std::string dimensions;
  std::string value_key;
  std::string top;
  std::string extend;
};
struct CmsQueryMetricTopNResponseType {
  std::vector<std::string> datapoints;
  std::string code;
  std::string message;
  std::string success;
  std::string trace_id;
};
} // end namespace
#endif


text:
/******************************************************************************/
/** \file       Lm75.c
 *******************************************************************************
 *
 *  \brief      This module allows to read the temperature of an attached lm75
 *              device.
 *

 *              The LM75A is an industry-standard digital temperature sensor
 *              with an integrated Sigma-Delta analog-to-digital converter and
 *              I2C interface. The LM75A provides 9-bit digital temperature
 *              readings with an accuracy of +/-2°C from -25°C to 100°C and
 *              +/-3°C over -55°C to 125°C. The temperature data output of the
 *              LM75 is available at all times via the I2C bus.
 *
 *  \author     wht4
 *
 *  \date       August 2013
 *
 *  \remark     Last Modification
 *               \li wht4, August 2013, Created
 *
 ******************************************************************************/
/*
 *  functions  global:
 *              readTempLm75
 *  functions  local:
 *              .
 *
 ******************************************************************************/

//----- Header-Files -----------------------------------------------------------
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "Lm75.h"
#include "Log.h"

//----- Macros -----------------------------------------------------------------
#define LM75_MAX_BUFFER    ( 64 )

//----- Data types -------------------------------------------------------------

//----- Function prototypes ----------------------------------------------------

//----- Data -------------------------------------------------------------------

//----- Implementation ---------------------------------------------------------

/*******************************************************************************
 *  function :    readTempLm75
 ******************************************************************************/
/** \brief        Read the temperature of the attached LM75 device
 *

 *                The LM75 is attached over I2C with the device address
 *                LM75_ADDR. The temperature data output of the LM75 is
 *                available at all times as a 9-bit value via the I2C bus.
 *                See warnings!
 *
 *  \type         global
 *
 *  \param[out]   ps32Temp   Temperature in degree celsius
 *
 *  \return

 *                BBB_SUCCESS      on success
 *                BBB_FILE_OPEN    File could not be opened
 *                BBB_FILE_IOCTL   Error in device control
 *                BBB_FILE_READ    Failed to read temperature value
 *

 *
 *  \warning      Accessing the LM75A continuously without waiting at least one
 *                conversion time between communications will prevent the device
 *                from updating the Temperature Register with a new temperature
 *                conversion result. Consequently, the LM75A should not be
 *                accessed continuously with a wait time of less than 300ms.
 *
 ******************************************************************************/
BBBError readTempLm75(int32_t *ps32Temp) {

    int fd;
    uint8_t u8Buffer[2];
    BBBError error = BBB_SUCCESS;

    if ((fd = open(LM75_DEVICE, O_RDWR)) < 0) {
        ERRORPRINT("Failed to open the bus " LM75_DEVICE);
        error = BBB_FILE_OPEN;

    } else {

        if (ioctl(fd, I2C_SLAVE, LM75_ADDR) < 0) {
            ERRORPRINT("Failed to acquire bus access " LM75_DEVICE);
            error = BBB_FILE_IOCTL;
        } else {

            /* Set read pointer to address 0x00 */
            write(fd, (char) 0x00, 1);

            /* Temperature data is represented by a 9-bit, two's complement   */
            /* word with an LSB (Least Significant Bit) equal to 0.5Grad      */
            /* Celcius:                                                       */
            /* +125Grad       0 1111 1010             0FAh                    */
            /* +25Grad        0 0011 0010             032h                    */
            /* +0.5Grad       0 0000 0001             001h                    */
            /* 0Grad          0 0000 0000             000h                    */
            /* −0.5Grad       1 1111 1111             1FFh                    */
            /* −25Grad        1 1100 1110             1CEh                    */
            /* −55Grad        1 1001 0010             192h                    */
            /* The first data byte is the most significant byte with most     */
            /* significant bit first                                          */
            if(read(fd, u8Buffer, 2) == 2) {

                *ps32Temp = 0;
                if((u8Buffer[0] & 0x80) > 0) {
                    *ps32Temp = 0xffffff00;
                }
                *ps32Temp |= (u8Buffer[0] & 0x7f) << 1;
                *ps32Temp |= ((u8Buffer[1] >> 7) & 1);
                /* Currently we are not interested in half degrees */
                *ps32Temp = *ps32Temp >> 1;

            } else {
                ERRORPRINT("Failed to read from LM75 at bus " LM75_DEVICE);
                error = BBB_FILE_READ;
            }

            close(fd);
        }
    }

    return(error);
}


text:
package com.ctrip.hermes.metaservice.service;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.transaction.CuratorTransactionBridge;
import org.apache.curator.utils.EnsurePath;
import org.apache.curator.utils.PathUtils;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidal.lookup.annotation.Inject;
import org.unidal.lookup.annotation.Named;

import com.ctrip.hermes.core.service.SystemClockService;
import com.ctrip.hermes.meta.entity.Topic;
import com.ctrip.hermes.metaservice.zk.ZKClient;
import com.ctrip.hermes.metaservice.zk.ZKPathUtils;
import com.ctrip.hermes.metaservice.zk.ZKSerializeUtils;

/**
 * @author Leo Liang(jhliang@ctrip.com)
 *
 */
@Named(type = ZookeeperService.class)
public class DefaultZookeeperService implements ZookeeperService {
	private static final Logger log = LoggerFactory.getLogger(DefaultZookeeperService.class);

	@Inject
	private ZKClient m_zkClient;

	@Inject
	private SystemClockService m_systemClockService;

	public void setZkClient(ZKClient zkClient) {
		m_zkClient = zkClient;
	}

	public void setSystemClockService(SystemClockService systemClockService) {
		m_systemClockService = systemClockService;
	}

	@Override
	public void ensureConsumerLeaseZkPath(Topic topic) {

		try {
			ensurePath(ZKPathUtils.getConsumerLeaseRootZkPath());
			List<String> paths = ZKPathUtils.getConsumerLeaseZkPaths(topic);

			for (String path : paths) {
				ensurePath(path);
			}
		} catch (Exception e) {
			log.error("Exception occurred in ensureConsumerLeaseZkPath", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void updateZkBaseMetaVersion(long version) throws Exception {
		ensurePath(ZKPathUtils.getBaseMetaVersionZkPath());

		m_zkClient.get().setData()
		      .forPath(ZKPathUtils.getBaseMetaVersionZkPath(), ZKSerializeUtils.serialize(version));
	}

	@Override
	public void deleteConsumerLeaseTopicParentZkPath(String topicName) {
		String path = ZKPathUtils.getConsumerLeaseTopicParentZkPath(topicName);

		try {
			deleteChildren(path, true);
		} catch (Exception e) {
			log.error("Exception occurred in deleteConsumerLeaseZkPath", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void deleteConsumerLeaseZkPath(Topic topic, String consumerGroupName) {
		List<String> paths = ZKPathUtils.getConsumerLeaseZkPaths(topic, consumerGroupName);
		String topicParentPath = ZKPathUtils.getConsumerLeaseTopicParentZkPath(topic.getName());

		long now = m_systemClockService.now();

		for (String path : paths) {
			try {
				m_zkClient.get().inTransaction()//
				      .delete().forPath(path)//
				      .and().setData().forPath(topicParentPath, ZKSerializeUtils.serialize(now))//
				      .and().commit();
			} catch (Exception e) {
				log.error("Exception occurred in deleteConsumerLeaseZkPath", e);
				throw new RuntimeException(e);
			}
		}

	}

	private void deleteChildren(String path, boolean deleteSelf) throws Exception {
		PathUtils.validatePath(path);

		CuratorFramework client = m_zkClient.get();
		Stat stat = client.checkExists().forPath(path);
		if (stat != null) {
			List<String> children = client.getChildren().forPath(path);
			for (String child : children) {
				String fullPath = ZKPaths.makePath(path, child);
				deleteChildren(fullPath, true);
			}

			if (deleteSelf) {
				try {
					client.delete().forPath(path);
				} catch (KeeperException.NotEmptyException e) {
					// someone has created a new child since we checked ... delete again.
					deleteChildren(path, true);
				} catch (KeeperException.NoNodeException e) {
					// ignore... someone else has deleted the node it since we checked
				}

			}
		}
	}

	@Override
	public void ensureBrokerLeaseZkPath(Topic topic) {
		List<String> paths = ZKPathUtils.getBrokerLeaseZkPaths(topic);

		for (String path : paths) {
			try {
				ensurePath(path);
			} catch (Exception e) {
				log.error("Exception occurred in ensureBrokerLeaseZkPath", e);
				throw new RuntimeException(e);
			}
		}

	}

	@Override
	public void deleteBrokerLeaseTopicParentZkPath(String topicName) {
		String path = ZKPathUtils.getBrokerLeaseTopicParentZkPath(topicName);

		try {
			deleteChildren(path, true);
		} catch (Exception e) {
			log.error("Exception occurred in deleteConsumerLeaseZkPath", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void persist(String path, byte[] data, String... touchPaths) throws Exception {
		try {
			ensurePath(path);

			if (touchPaths != null && touchPaths.length > 0) {
				for (String touchPath : touchPaths) {
					ensurePath(touchPath);
				}
			}

			CuratorTransactionBridge curatorTransactionBridge = m_zkClient.get().inTransaction().setData()
			      .forPath(path, data);

			long now = m_systemClockService.now();
			if (touchPaths != null && touchPaths.length > 0) {
				for (String touchPath : touchPaths) {
					curatorTransactionBridge.and().setData().forPath(touchPath, ZKSerializeUtils.serialize(now));
				}
			}

			curatorTransactionBridge.and().commit();

		} catch (Exception e) {
			log.error("Exception occurred in persist", e);
			throw e;
		}
	}

	public void ensurePath(String path) throws Exception {
		EnsurePath ensurePath = m_zkClient.get().newNamespaceAwareEnsurePath(path);
		ensurePath.ensure(m_zkClient.get().getZookeeperClient());
	}

	@Override
	public void deleteMetaServerAssignmentZkPath(String topicName) {
		long now = m_systemClockService.now();

		try {
			ensurePath(ZKPathUtils.getMetaServerAssignmentZkPath(topicName));

			m_zkClient.get().inTransaction()
			      //
			      .delete().forPath(ZKPathUtils.getMetaServerAssignmentZkPath(topicName))
			      //
			      .and().setData()
			      .forPath(ZKPathUtils.getMetaServerAssignmentRootZkPath(), ZKSerializeUtils.serialize(now))//
			      .and().commit();
		} catch (Exception e) {
			log.error("Exception occurred in deleteMetaServerAssignmentZkPath", e);
			throw new RuntimeException(e);
		}
	}

}


text:
@interface StreamParser () {
#if __has_feature(objc_arc_weak)
    __weak id delegate;
#else
    __unsafe_unretained id delegate;
#endif
    dispatch_queue_t delegateQueue;
    NSMutableData *byteParsed;
    int _minDataLength;
    unsigned char _type;
    unsigned char _extension;
    unsigned char _version;
    UInt16 _check;
}

@end

#define SOCKET_HEAD_LEN 13 //1 + 1 + 4 + 1 + 4 + 2 version type len extension salt check
#define SALT_LEN 4

@implementation StreamParser

- (id)initWithDelegate:(id)aDelegate delegateQueue:(id)aDelegateQueue {
    delegate = aDelegate;
    delegateQueue = aDelegateQueue;
    byteParsed = [[NSMutableData alloc] init];
    _minDataLength = SOCKET_HEAD_LEN;
    _type = 0xff;
    _version = 0xff;
    _extension = 0xff;
    return self;
}

- (void)checkVersion {

}

- (void)parseData:(NSData *)data {
    [byteParsed appendBytes:[data bytes] length:[data length]];

    if (byteParsed.length >= 1) {
        [self checkVersion];
    }

    NSLog(@"byteParsed len:%ld", byteParsed.length);
    while ([byteParsed length] >= SOCKET_HEAD_LEN) {
        if (_type == 0xff || _extension == 0xff) {
            [byteParsed getBytes:&_version range:NSMakeRange(0, sizeof(_version))];
            [byteParsed getBytes:&_type range:NSMakeRange(sizeof(_version), sizeof(_type))];
            [byteParsed getBytes:&_minDataLength range:NSMakeRange(sizeof(_version) + sizeof(_type), sizeof(_minDataLength))];
            [byteParsed getBytes:&_extension range:NSMakeRange(sizeof(_version) + sizeof(_type) + sizeof(_minDataLength), sizeof(_extension))];
            [byteParsed getBytes:&_check range:NSMakeRange(SALT_LEN + sizeof(_version) + sizeof(_type) + sizeof(_minDataLength) + sizeof(_extension), sizeof(_check))];

            if (![self checkBytes]) {
                //clear data
                [byteParsed setLength:0];

                //reverse
                _minDataLength = SOCKET_HEAD_LEN;
                _type = 0xff;
                _extension = 0xff;
                _version = 0xff;
                if (delegate && [delegate respondsToSelector:@selector(IllegalData)]) {
                    [delegate IllegalData];
                }
                break;
            }

            _minDataLength = NSSwapHostIntToBig(_minDataLength);
            NSLog(@"willreadlen:%d", _minDataLength);
        }

        if (_type < 0xff && _extension < 0xff) {
            if ([byteParsed length] < _minDataLength + SOCKET_HEAD_LEN) {
                break;
            }
            NSData *thisData = [byteParsed subdataWithRange:NSMakeRange(1, _minDataLength + SOCKET_HEAD_LEN - 1)];
            //to do
            if (delegate && [delegate respondsToSelector:@selector(parserDidReadStanza:thisData:)]) {
                __strong id theDelegate = delegate;

                Message *msg = [[Message alloc] init];
                [msg unpack:thisData];
                [theDelegate parserDidReadStanza:msg thisData:thisData];
            }
            if ([byteParsed length] >= SOCKET_HEAD_LEN + _minDataLength) {
                [byteParsed setData:[byteParsed subdataWithRange:NSMakeRange(SOCKET_HEAD_LEN + _minDataLength, [byteParsed length] - SOCKET_HEAD_LEN - _minDataLength)]];
            }

            _minDataLength = SOCKET_HEAD_LEN;
            _type = 0xff;
            _extension = 0xff;
            _version = 0xff;
        }
    }

}

- (void)handleData:(NSData *)data {
    [byteParsed appendBytes:[data bytes] length:[data length]];
    while ([byteParsed length] >= SOCKET_HEAD_LEN) {
        if (_type == 0xff || _extension == 0xff) {
            [byteParsed getBytes:&_version range:NSMakeRange(0, sizeof(_version))];
            [byteParsed getBytes:&_type range:NSMakeRange(sizeof(_version), sizeof(_type))];
            [byteParsed getBytes:&_minDataLength range:NSMakeRange(sizeof(_version) + sizeof(_type), sizeof(_minDataLength))];
            [byteParsed getBytes:&_extension range:NSMakeRange(sizeof(_version) + sizeof(_type) + sizeof(_minDataLength), sizeof(_extension))];
            [byteParsed getBytes:&_check range:NSMakeRange(SALT_LEN + sizeof(_version) + sizeof(_type) + sizeof(_minDataLength) + sizeof(_extension), sizeof(_check))];
            _minDataLength = NSSwapHostIntToBig(_minDataLength);

            if (![self checkBytes]) {

                [byteParsed setLength:0];

                _minDataLength = SOCKET_HEAD_LEN;
                _type = 0xff;
                _extension = 0xff;
                _version = 0xff;
                if (delegate && [delegate respondsToSelector:@selector(IllegalData)]) {
                    [delegate IllegalData];
                }
                break;
            }

            if (_type == 0xff || _extension == 0xff) {
                break;
            }
        }

        if (_type < 0xff && _extension < 0xff) {
            if ([byteParsed length] < _minDataLength + SOCKET_HEAD_LEN) {
                break;
            }
            NSData *thisData = [byteParsed subdataWithRange:NSMakeRange(1, _minDataLength + SOCKET_HEAD_LEN - 1)];
            //to do
            if (delegate && [delegate respondsToSelector:@selector(parserDidReadThisData:)]) {
                __strong id theDelegate = delegate;
                [theDelegate parserDidReadThisData:thisData];
            }

            if ([byteParsed length] >= SOCKET_HEAD_LEN + _minDataLength) {
                [byteParsed setData:[byteParsed subdataWithRange:NSMakeRange(SOCKET_HEAD_LEN + _minDataLength, [byteParsed length] - SOCKET_HEAD_LEN - _minDataLength)]];
            }

            _minDataLength = SOCKET_HEAD_LEN;
            _type = 0xff;
            _extension = 0xff;
            _version = 0xff;
        }
    }

}

- (BOOL)checkBytes {

    NSMutableData *checkData = [NSMutableData dataWithData:[byteParsed subdataWithRange:NSMakeRange(1, 10)]];

    UInt8 j = 0xc0;
    NSData *data1 = [[NSData alloc] initWithBytes:&j length:sizeof(j)];
    [checkData appendData:data1];

    UInt8 i = 0x2E;
    NSData *data2 = [[NSData alloc] initWithBytes:&i length:sizeof(i)];
    [checkData appendData:data2];

    UInt8 n = 0xC7;

    NSData *data3 = [[NSData alloc] initWithBytes:&n length:sizeof(n)];
    [checkData appendData:data3];

    NSData *checkDataMd5 = [checkData md5Data];

    NSData *checkTwoBytes = [checkDataMd5 subdataWithRange:NSMakeRange(0, 2)];

    NSData *serverCheckBytes = [NSData dataWithBytes:&_check length:sizeof(_check)];
    return [checkTwoBytes isEqualToData:serverCheckBytes];
}

- (void)revert {
    byteParsed = [[NSMutableData alloc] init];
    _type = 0xff;
    _version = 0xff;
    _extension = 0xff;
}

@end


text:
using Gem.Network.Handlers;
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Linq;
using Seterlund.CodeGuard;
using Gem.Network.Builders;
using Autofac;
using System.Collections.Generic;
using Gem.Network.Factories;
using Gem.Network.Events;
using Gem.Network.Messages;
using Gem.Network.Client;

namespace Gem.Network.Fluent
{
   using Extensions;

    public class MessageFlowBuilder : IMessageFlowBuilder
    {

        #region Fields

        private readonly string profile;

        private readonly MessageType messageType;

        private MessageFlowArguments messageFlowArgs;

        private readonly byte Id;

        #endregion

        #region Constructor

        public MessageFlowBuilder(string profile,MessageType messageType)
        {
            this.profile = profile;
            this.Id = GemNetwork.GetMesssageId(profile);
            this.messageType = messageType;
            this.messageFlowArgs = new MessageFlowArguments();
        }

        #endregion

        #region IMessageFlowBuilder Implementation

        public INetworkEvent AndHandleWith<T>(T objectToHandle, Expression<Func<T, Delegate>> methodToHandle)
        {
            var methodInfo = methodToHandle.GetMethodInfo();
            var types = methodInfo.GetParameters().Select(x => x.ParameterType).ToList();

            Guard.That(types.All(x => x.IsPrimitive || x == typeof(string)), "All types should be primitive");

            var properties = RuntimePropertyInfo.GetPropertyInfo(types.ToArray());

            SetDynamicPoco(properties);
            SetMessageHandler(properties.Select(x => RuntimePropertyInfo.GetPrimitiveTypeAlias(x.PropertyType)).ToList(), objectToHandle, methodInfo.Name);
            var argumentsDisposable = GemClient.MessageFlow[profile,messageType].Add(messageFlowArgs);
            SetDynamicEvent(argumentsDisposable);

            messageFlowArgs.IncludesLocalTime = false;
            GemClient.MessageFlow[profile, messageType].SubscribeEvent(messageFlowArgs.ID);

            return messageFlowArgs.EventRaisingclass;
        }

        #endregion

        #region MessageFlow Setup

        private void SetMessageHandler(List<string> propertyNames, object invoker, string functionName)
        {
            var handlerType = Dependencies.Container.Resolve<IMessageHandlerFactory>()
                                          .Create(propertyNames, "handler" + Id, functionName);

            messageFlowArgs.MessageHandler = Activator.CreateInstance(handlerType, invoker) as IMessageHandler;
        }

        private void SetDynamicPoco(List<RuntimePropertyInfo> properties)
        {
            var newType = Dependencies.Container.Resolve<IPocoFactory>().Create(properties, "poco" + Id);

            messageFlowArgs.MessagePoco = newType;
        }

        private void SetDynamicEvent(IDisposable argumentDisposable)
        {
            messageFlowArgs.EventRaisingclass = Dependencies.Container.Resolve<IEventFactory>().Create(messageFlowArgs.MessagePoco, argumentDisposable,messageFlowArgs.ID);
        }

        #endregion

    }
}


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:property-placeholder location="classpath:applicationContext.properties"/>

    <!-- 开启controller注解支持 -->
    <!-- 注意事项请参考:http://jinnianshilongnian.iteye.com/blog/1762632 -->
    <context:component-scan base-package="com.quanix.app.integration.server.**.web" use-default-filters="false">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation"
                                expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

    <!--<mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="com.github.zhangkaitao.shiro.chapter23.web.bind.method.CurrentUserMethodArgumentResolver"/>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>-->

    <!-- 当在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
    <mvc:default-servlet-handler/>

    <!-- 静态资源映射 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>

    <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:order="1">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="contentType" value="text/html"/>
        <property name="prefix" value=""/>
        <property name="suffix" value=""/>
    </bean>

    <!-- 控制器异常处理 -->
    <bean id="exceptionHandlerExceptionResolver" class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
    </bean>

    <import resource="applicationContext-shiro.xml"/>
    <import resource="applicationContext-remote.xml"/>

</beans>


text:
#include "CCPACSWingCellPositionSpanwise.h"

#include "CCPACSWingCell.h"
#include "CCPACSWingCells.h"
#include "CCPACSWingShell.h"
#include "CCPACSWingCSStructure.h"
#include "CTiglWingStructureReference.h"
#include "CTiglError.h"
#include "tigletaxsifunctions.h"

namespace tigl
{

namespace {
    // return uid of wing structure reference, or the empty string when not all parents are defined
    std::string tryGetWingStructureReferenceUID(CCPACSWingCell* parent)
    {
        if (!parent || !parent->GetParent() || !parent->GetParent()->GetParent() || !parent->GetParent()->GetParent()->GetParent()) {
            return "";
        }
        return CTiglWingStructureReference(*parent->GetParent()->GetParent()->GetParent()).GetUID();
    }
}

CCPACSWingCellPositionSpanwise::CCPACSWingCellPositionSpanwise(CCPACSWingCell* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSCellPositioningSpanwise(parent, uidMgr) {}

CCPACSWingCellPositionSpanwise::InputType CCPACSWingCellPositionSpanwise::GetInputType() const {
    if (m_contourCoordinate_choice1) {
        return Contour;
    }
    if (m_eta1_choice2 && m_eta2_choice2)
        return Eta;
    if (m_ribDefinitionUID_choice3 && m_ribNumber_choice3)
        return Rib;
    throw CTiglError("Invalid spanwise cell positioning", TIGL_XML_ERROR);
}

void CCPACSWingCellPositionSpanwise::SetEta1(double eta1) {
    const std::string uid = tryGetWingStructureReferenceUID(m_parent);
    GetEta1_choice2(CreateIfNotExists).SetEta(eta1);
    GetEta1_choice2(CreateIfNotExists).SetReferenceUID(uid);
    m_ribNumber_choice3 = boost::none;
    m_ribDefinitionUID_choice3 = boost::none;

    InvalidateParent();
}

void CCPACSWingCellPositionSpanwise::SetEta2(double eta2) {
    const std::string uid = tryGetWingStructureReferenceUID(m_parent);
    GetEta2_choice2(CreateIfNotExists).SetEta(eta2);
    GetEta2_choice2(CreateIfNotExists).SetReferenceUID(uid);
    m_ribNumber_choice3 = boost::none;
    m_ribDefinitionUID_choice3 = boost::none;

    InvalidateParent();
}

// get and set Eta definition
void CCPACSWingCellPositionSpanwise::SetEta(double eta1, double eta2)
{
    const std::string uid = tryGetWingStructureReferenceUID(m_parent);
    SetEta(eta1, uid, eta2, uid);
}

void CCPACSWingCellPositionSpanwise::SetEta(double eta1, const std::string& eta1RefUid, double eta2,
                                            const std::string& eta2RefUid)
{
    GetEta1_choice2(CreateIfNotExists).SetEta(eta1);
    GetEta1_choice2(CreateIfNotExists).SetReferenceUID(eta1RefUid);
    GetEta2_choice2(CreateIfNotExists).SetEta(eta2);
    GetEta2_choice2(CreateIfNotExists).SetReferenceUID(eta2RefUid);

    m_ribNumber_choice3 = boost::none;
    m_ribDefinitionUID_choice3 = boost::none;

    InvalidateParent();
}

void CCPACSWingCellPositionSpanwise::GetEta(double& eta1, double& eta2) const {
    std::tie(eta1, eta2) = GetEta();
}

std::pair<double, double> CCPACSWingCellPositionSpanwise::GetEta() const {
    if (GetInputType() != Eta) {
        throw CTiglError("CCPACSWingCellPositionSpanwise::GetEta method called, but position is defined via ribDefinitionUID!");
    }

    const CCPACSEtaIsoLine& etaIso1 = m_eta1_choice2.value();
    const CCPACSEtaIsoLine& etaIso2 = m_eta2_choice2.value();
    // special handling for testing
    if (etaIso1.GetReferenceUID().empty() && etaIso2.GetReferenceUID().empty()) {
        return std::make_pair(etaIso1.GetEta(), etaIso2.GetEta());
    }
    const double eta1 = transformEtaToCSOrTed(etaIso1, m_parent->GetUIDManager());
    const double eta2 = transformEtaToCSOrTed(etaIso2, m_parent->GetUIDManager());
    return std::make_pair(eta1, eta2);
}

void CCPACSWingCellPositionSpanwise::SetRib(const std::string& ribUId, int nRib) {
    m_eta1_choice2 = boost::none;
    m_eta2_choice2 = boost::none;
    m_ribNumber_choice3 = nRib;
    m_ribDefinitionUID_choice3 = ribUId;

    InvalidateParent();
}

void CCPACSWingCellPositionSpanwise::SetRibDefinitionUID(const std::string& ribUId) {
    m_eta1_choice2 = boost::none;
    m_eta2_choice2 = boost::none;
    m_ribDefinitionUID_choice3 = ribUId;

    InvalidateParent();
}

void CCPACSWingCellPositionSpanwise::SetRibNumber(int nRib) {
    m_eta1_choice2 = boost::none;
    m_eta2_choice2 = boost::none;
    m_ribNumber_choice3 = nRib;

    InvalidateParent();
}

void CCPACSWingCellPositionSpanwise::GetRib(std::string& ribUid, int& ribNumber) const {
    //std::tie(ribUid, ribNumber) = GetRib();
    std::pair<std::string, int> ribDefinition = GetRib();
    ribUid = ribDefinition.first;
    ribNumber = ribDefinition.second;
}

std::pair<std::string, int> CCPACSWingCellPositionSpanwise::GetRib() const {
    if (GetInputType() != Rib) {
        throw CTiglError("CCPACSWingCellPositionSpanwise::GetRib method called, but position is defined via eta1/eta2!");
    }
    return std::make_pair(m_ribDefinitionUID_choice3.value(), m_ribNumber_choice3.value());
}

void CCPACSWingCellPositionSpanwise::InvalidateParent()
{
    if (GetParent()) {
        GetParent()->Invalidate();
    }
}

}


text:
@interface WMFCVLInvalidationContext : UICollectionViewLayoutInvalidationContext

@property (nonatomic, copy) UICollectionViewLayoutAttributes *originalLayoutAttributes;
@property (nonatomic, copy) UICollectionViewLayoutAttributes *preferredLayoutAttributes;
@property (nonatomic) BOOL boundsDidChange;

@end


text:
<bill session="110" type="s" number="2574" updated="2009-01-09T17:13:27-05:00">
	<status><introduced date="1201669200" datetime="2008-01-30"/></status>

	<introduced date="1201669200" datetime="2008-01-30"/>
	<titles>
		<title type="short" as="introduced">Mortgage Refinancing Initiative Act of 2008</title>
		<title type="official" as="introduced">A bill to amend the Internal Revenue Code of 1986 to allow the use of qualified mortgage revenue bonds for refinancing mortgages and to provide a temporary increase in the volume cap for such bonds.</title>
	</titles>
	<sponsor id="300022"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1201669200" datetime="2008-01-30"><text>Read twice and referred to the Committee on Finance.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	1/30/2008--Introduced.
Mortgage Refinancing Initiative Act of 2008 - Amends the Internal Revenue Code to: (1) allow, until December 31, 2009, proceeds of qualified mortgage bonds to be used to refinance an existing mortgage; and (2) increase in 2008 and 2009 the national limitation amount for such bonds.

</bill>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Saasprin.Core.Model;
using Saasprin.Core.Interfaces;
using System.Web;
using System.IO;

using Saasprin.Interfaces;
using Saasprin.Model;
using Saasprin.Services.Model;
using Saasprin.Infrastructure;
using Saasprin.Model;

namespace Saasprin.Services
{
    public class InvoiceService
    {
        public EmailService emailService;
        public InvoiceService(IInvoiceStorage invoiceStorage, ICompanyStorage companyStorage, IUserStorage userStorage)
        {
            this.emailService = new EmailService();
            this.InvoiceStorage = invoiceStorage;
            this.CompanyStorage = companyStorage;
            this.UserStorage = userStorage;
        }
        public IInvoiceStorage InvoiceStorage { set; get; }
        public ICompanyStorage CompanyStorage { set; get; }
        public IUserStorage UserStorage { set; get; }

        public async Task<bool> UploadInvoice(Invoice invoice, Stream fileContents, string fileContentType, string id)
        {
               if(id == null)
                   throw new Saasprin.Model.ArgumentNullException("id");
               if (invoice == null)
                   throw new Saasprin.Model.ArgumentNullException("invoice");
               if (fileContents == null)
                   throw new Saasprin.Model.ArgumentNullException("fileContents");

            invoice.FileId = await this.InvoiceStorage.UploadFile(fileContents, fileContentType);
            if (invoice.FileId != null)
            {

                return await this.InvoiceStorage.SaveInvoice(invoice, id);
            }
            return false;
        }

        public async Task<byte[]> Download(string id)
        {
            if (id == null)
                throw new Saasprin.Model.ArgumentNullException("id");

            return await this.InvoiceStorage.DownloadInvoice(id);
        }

        public void SendUploadNotification(Invoice invoice)
        {
             Company company = CompanyStorage.GetCompanyForInvoiceId(invoice.Id);
             List<User> users = UserStorage.GetUsersForCompany(company.Id);
             List<User> accountants = users.Where(u => u.Type.Equals("accountant")).ToList();

             Email email = new Email();

             foreach (var accountant in accountants)
             {
                 email.EmailIds.Add(accountant.Username);
             }
             email.Subject = Configuration.NEW_INVOICE_UPLOADED_EMAIL_SUBJECT;
             email.TemaplateName = Configuration.NEW_INVOICE_UPLOADED_TEMPLATE;
             email.Placeholders.Add("provider", invoice.Provider);
             email.Placeholders.Add("amount", invoice.Amount.ToString());
             email.Placeholders.Add("company", company.Name);

             emailService.SendEmail(email);

        }

        public async Task<List<Invoice>> GetInvoicesAsync(string companyId, string month, string year)
        {
            int yearInt, monthInt = 0;
            if (int.TryParse(year, out yearInt) == false || int.TryParse(month, out monthInt) == false
                || yearInt < 1900 || yearInt > 9999 || monthInt < 1 || monthInt > 12)
                throw new InvalidArgumentException("Invalid month or year provided.");

            var startDate = new DateTime(yearInt, monthInt, 1);
            var endDate = new DateTime(yearInt, monthInt, DateTime.DaysInMonth(yearInt, monthInt));

            return await this.InvoiceStorage.GetInvoicesAsync(companyId, startDate, endDate);
        }

        public async Task<Invoice> GetInvoiceAsync(string invoiceId)
        {
            return await this.InvoiceStorage.GetInvoiceAsync(invoiceId);
        }
    }
}


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

namespace Bonobo
{
    public class SpriteAnimator : MonoBehaviour
    {
        public delegate void SpriteAnimatorEventHandler(SpriteAnimator animBehaviour, string animName);
        public event SpriteAnimatorEventHandler AnimFinished;

        [System.Serializable]
        public class AnimDetails
        {
            [SerializeField]
            public UIAtlas m_spriteAtlas;
            [SerializeField]
            public string m_name;
            [SerializeField]
            public string m_prefix;
            [SerializeField]
            public int m_numFrames;
            [SerializeField]
            public int m_startFrame;
            [SerializeField]
            public bool m_toLetter;
            [SerializeField]
            public float m_fps;
            [SerializeField]
            public bool m_loop;
            [SerializeField]
            public bool m_isReverse;
            [SerializeField]
            public string m_sequencedAnimation;
            [SerializeField]
            public float m_sequenceDelay;
        }

        [SerializeField]
        AnimDetails[] m_availableAnimations;
        [SerializeField]
        UISprite m_sprite;
        [SerializeField]
        string m_format = "{0:00}";
        [SerializeField]
        bool m_startOn = true;
        [SerializeField]
        private List<string> m_randomAnimationNames;
        [SerializeField]
        private Vector2 m_randomDelayRange = new Vector2(2, 5);

        int m_currentAnimation = 0;
        float m_currentT;
        int m_currentFrame;

        bool m_playAnim;

        bool m_isWaiting = false;
        string m_waitingAnimationName;

        bool m_isWaitingToPlay = false;

        void OnEnable()
        {
            if (m_isWaitingToPlay)
            {
                StartCoroutine("PlayRandom");
            }
        }

        void Start()
        {
            if(m_sprite == null)
            {
                m_sprite = GetComponent<UISprite>() as UISprite;
            }

            if (string.IsNullOrEmpty(m_format))
            {
                m_format = "{0}";
            }

            m_playAnim = m_startOn;

            if (m_playAnim && m_randomAnimationNames.Count > 0)
            {
                PlayAnimation(m_randomAnimationNames[UnityEngine.Random.Range(0, m_randomAnimationNames.Count)], true);
            }
        }

        public void Stop()
        {
            StopAllCoroutines();
            m_playAnim = false;
            m_isWaitingToPlay = false;
        }

        public void StopRandom()
        {
            StopCoroutine("PlayRandom");
            m_isWaitingToPlay = false;
        }

        IEnumerator PlayRandom()
        {
            m_isWaitingToPlay = true;

            yield return new WaitForSeconds(UnityEngine.Random.Range(m_randomDelayRange.x, m_randomDelayRange.y));

            m_isWaitingToPlay = false;

            if (m_randomAnimationNames.Count > 0)
            {
                PlayAnimation(m_randomAnimationNames[UnityEngine.Random.Range(0, m_randomAnimationNames.Count)], true);
            }
        }

        public bool IsPlaying()
        {
            return m_playAnim && m_currentAnimation > -1 && m_currentAnimation < m_availableAnimations.Length;
        }

        int GetAnimIndex(string animName)
        {
            return Array.FindIndex(m_availableAnimations, x => x.m_name == animName);
        }

        public bool HasAnim(string animName)
        {
            return GetAnimIndex(animName) != -1;
        }

        public void PlayAnimation(string animName, bool waitForEnd = true)
        {
            StopAllCoroutines();

            if (waitForEnd && IsPlaying())
            {
                m_waitingAnimationName = animName;
                m_isWaiting = true;
            }
            else
            {
                m_waitingAnimationName = "";

                int animIndex = GetAnimIndex(animName);

                if(animIndex != -1)
                {
                    m_currentAnimation = animIndex;
                    m_currentFrame = 0;

                    AnimDetails ad = m_availableAnimations[m_currentAnimation];

                    if (ad.m_spriteAtlas != null)
                    {
                        m_sprite.atlas = ad.m_spriteAtlas;
                    }

                    SetSpriteName();

                    m_playAnim = true;
                }
            }
        }

        IEnumerator PlaySequencedAnimation(AnimDetails ad)
        {
            m_isWaitingToPlay = true;

            yield return new WaitForSeconds(ad.m_sequenceDelay);

            m_isWaitingToPlay = false;

            PlayAnimation(ad.m_sequencedAnimation, false);
        }

        void Update ()
        {
            if (IsPlaying())
            {
                AnimDetails ad = m_availableAnimations[m_currentAnimation];

                m_currentT += Time.deltaTime * ad.m_fps;
                if (m_currentT > 1)
                {
                    m_currentT -= 1;

                    if(Mathf.Abs(m_currentFrame) < Mathf.Abs(ad.m_numFrames))
                    {
                        SetSpriteName();

                        if(ad.m_isReverse)
                        {
                            --m_currentFrame;
                        }
                        else
                        {
                            ++m_currentFrame;
                        }
                    }
                    else
                    {
                        if(!String.IsNullOrEmpty(ad.m_sequencedAnimation) && HasAnim(ad.m_sequencedAnimation))
                        {
                            m_playAnim = false;
                            StartCoroutine(PlaySequencedAnimation(ad));
                        }
                        else if(m_isWaiting)
                        {
                            m_isWaiting = false;
                            PlayAnimation(m_waitingAnimationName, false);
                        }
                        else if(ad.m_loop)
                        {
                            m_currentFrame = 0;
                        }
                        else
                        {
                            m_playAnim = false;

                            if(m_randomAnimationNames.Count > 0)
                            {
                                StartCoroutine("PlayRandom");
                            }

                            if(AnimFinished != null)
                            {
                                AnimFinished(this, ad.m_name);
                            }
                        }
                    }
                }
            }
        }

        void SetSpriteName()
        {
            int frame = m_currentFrame + m_availableAnimations[m_currentAnimation].m_startFrame;
            string frameString = string.Format(m_format, frame);

            if (m_availableAnimations[m_currentAnimation].m_toLetter)
            {
                frameString = ((char)('a' + frame)).ToString();
            }

            m_sprite.spriteName = m_availableAnimations [m_currentAnimation].m_prefix + frameString;
        }
    }
}


text:
NAMESPACE_BEGIN(monoco)

class mstr : public std::string, public mbj
{
public:
	mstr() {}
	mstr(const char* cstr): string(cstr) {}
	mstr(const string& str): string(str) {}
	mstr(const mstr& other): string(other) {}

	virtual string type_name() const {return "msrt";}
	virtual std::size_t size() const {return string::size();}
};

NAMESPACE_END(monoco)

namespace std {
	template <>
	struct hash<monoco::mstr>
	{
		std::size_t operator()(const monoco::mstr& str) const
			{
				return 1;
			}
	};
}

#endif


text:
// Generated on 2014-12-22 using generator-angular 0.7.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-config')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    grunt.registerTask('serve', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['connect:dist:keepalive']);
        }

        if (target === 'build') {
            return grunt.task.run(['build', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'compass',
            //'concurrent:server',
            'autoprefixer',
            'connect:livereload',
            'watch'
        ]);
    });

    grunt.registerTask('default', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'concurrent:server',
            'autoprefixer',
            'newer:jshint',
            'watch'
        ]);
    });

    grunt.registerTask('server', function () {
        grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
        grunt.task.run(['serve']);
    });

    grunt.registerTask('test', [
        'clean:server',
        'concurrent:test',
        'autoprefixer',
        'connect:test',
        'karma:unit'
    ]);

    grunt.registerTask('test-chrome', [
        'clean:server',
        'concurrent:test',
        'autoprefixer',
        'connect:test',
        'karma:chrome'
    ]);

    grunt.registerTask('build', [
        'clean:dist',
        'useminPrepare',
        'compass',
        'autoprefixer',
        'concat',
        'ngAnnotate:dist',
        'copy:dist',
        'cssmin',
        'uglify',
        //'rev',
        'revision',
        'regex-replace',
        'usemin',
        'htmlmin'
    ]);

    grunt.registerTask('ci', [
        'newer:jshint',
        'test',
        'build'
    ]);
};


text:
"""Perform joint genotyping using GATK HaplotypeCaller with gVCF inputs

Handles merging of large batch sizes using CombineGVCFs and
joint variant calling with GenotypeGVCFs.
"""

import toolz as tz

from bcbio import broad, utils
from bcbio.distributed.transaction import file_transaction
from bcbio.pipeline import datadict as dd
from bcbio.variation import bamprep

def run_region(data, region, vrn_files, out_file):
    """Perform variant calling on gVCF inputs in a specific genomic region.
    """
    vrn_files = _batch_gvcfs(data, region, vrn_files, dd.get_ref_file(data), out_file)
    return _run_genotype_gvcfs(data, region, vrn_files, dd.get_ref_file(data), out_file)

# ## gVCF joint genotype calling

def _run_genotype_gvcfs(data, region, vrn_files, ref_file, out_file):
    if not utils.file_exists(out_file):
        broad_runner = broad.runner_from_config(data["config"])
        with file_transaction(data, out_file) as tx_out_file:
            assoc_files = tz.get_in(("genome_resources", "variation"), data, {})
            if not assoc_files: assoc_files = {}
            params = ["-T", "GenotypeGVCFs",
                      "-R", ref_file, "-o", tx_out_file,
                      "-L", bamprep.region_to_gatk(region)]
            for vrn_file in vrn_files:
                params += ["--variant", vrn_file]
            if assoc_files.get("dbsnp"):
                params += ["--dbsnp", assoc_files["dbsnp"]]
            broad_runner.new_resources("gatk-haplotype")
            cores = dd.get_cores(data)
            if cores > 1:
                params += ["-nt", str(cores)]
                memscale = {"magnitude": 0.9 * cores, "direction": "increase"}
            else:
                memscale = None
            broad_runner.run_gatk(params, memscale=memscale)
    return out_file

# ## gVCF batching

MAX_BATCH = 200  # Recommended sample count from GATK team where we should use CombineGVCFs

def _batch_gvcfs(data, region, vrn_files, ref_file, out_file=None):
    """Perform batching of gVCF files if above recommended input count.
    """
    if out_file is None:
        out_file = vrn_files[0]
    if len(vrn_files) >= MAX_BATCH:
        out = []
        for i, batch_vrn_files in enumerate(tz.partition_all(MAX_BATCH, vrn_files)):
            base, ext = utils.splitext_plus(out_file)
            batch_out_file = "%s-b%s%s" % (base, i, ext)
            out.append(_run_combine_gvcfs(batch_vrn_files, region, ref_file, batch_out_file, data))
        return _batch_gvcfs(data, region, out, ref_file)
    else:
        return vrn_files

def _run_combine_gvcfs(vrn_files, region, ref_file, out_file, data):
    if not utils.file_exists(out_file):
        broad_runner = broad.runner_from_config(data["config"])
        with file_transaction(data, out_file) as tx_out_file:
            params = ["-T", "CombineGVCFs", "-R", ref_file, "-o", tx_out_file,
                      "-L", bamprep.region_to_gatk(region)]
            for vrn_file in vrn_files:
                params += ["--variant", vrn_file]
            cores = dd.get_cores(data)
            memscale = {"magnitude": 0.9 * cores, "direction": "increase"} if cores > 1 else None
            broad_runner.new_resources("gatk-haplotype")
            broad_runner.run_gatk(params, memscale=memscale)
    return out_file


text:
#include "config.h"
#include "MainThread.h"

#include "CurrentTime.h"
#include "Deque.h"
#include "Functional.h"
#include "StdLibExtras.h"
#include "Threading.h"
#include <wtf/ThreadSpecific.h>

#if PLATFORM(CHROMIUM)
#error Chromium uses a different main thread implementation
#endif

namespace WTF {

struct FunctionWithContext {
    MainThreadFunction* function;
    void* context;
    ThreadCondition* syncFlag;

    FunctionWithContext(MainThreadFunction* function = 0, void* context = 0, ThreadCondition* syncFlag = 0)
        : function(function)
        , context(context)
        , syncFlag(syncFlag)
    {
    }
    bool operator == (const FunctionWithContext& o)
    {
        return function == o.function
            && context == o.context
            && syncFlag == o.syncFlag;
    }
};

class FunctionWithContextFinder {
public:
    FunctionWithContextFinder(const FunctionWithContext& m) : m(m) {}
    bool operator() (FunctionWithContext& o) { return o == m; }
    FunctionWithContext m;
};

typedef Deque<FunctionWithContext> FunctionQueue;

static bool callbacksPaused; // This global variable is only accessed from main thread.
#if !PLATFORM(MAC)
static ThreadIdentifier mainThreadIdentifier;
#endif

static Mutex& mainThreadFunctionQueueMutex()
{
    DEFINE_STATIC_LOCAL(Mutex, staticMutex, ());
    return staticMutex;
}

static FunctionQueue& functionQueue()
{
    DEFINE_STATIC_LOCAL(FunctionQueue, staticFunctionQueue, ());
    return staticFunctionQueue;
}

#if !PLATFORM(MAC)

void initializeMainThread()
{
    static bool initializedMainThread;
    if (initializedMainThread)
        return;
    initializedMainThread = true;

    mainThreadIdentifier = currentThread();

    mainThreadFunctionQueueMutex();
    initializeMainThreadPlatform();
    initializeGCThreads();
}

#else

static pthread_once_t initializeMainThreadKeyOnce = PTHREAD_ONCE_INIT;

static void initializeMainThreadOnce()
{
    mainThreadFunctionQueueMutex();
    initializeMainThreadPlatform();
}

void initializeMainThread()
{
    pthread_once(&initializeMainThreadKeyOnce, initializeMainThreadOnce);
}

static void initializeMainThreadToProcessMainThreadOnce()
{
    mainThreadFunctionQueueMutex();
    initializeMainThreadToProcessMainThreadPlatform();
}

void initializeMainThreadToProcessMainThread()
{
    pthread_once(&initializeMainThreadKeyOnce, initializeMainThreadToProcessMainThreadOnce);
}
#endif

// 0.1 sec delays in UI is approximate threshold when they become noticeable. Have a limit that's half of that.
static const double maxRunLoopSuspensionTime = 0.05;

void dispatchFunctionsFromMainThread()
{
    ASSERT(isMainThread());

    if (callbacksPaused)
        return;

    double startTime = currentTime();

    FunctionWithContext invocation;
    while (true) {
        {
            MutexLocker locker(mainThreadFunctionQueueMutex());
            if (!functionQueue().size())
                break;
            invocation = functionQueue().takeFirst();
        }

        invocation.function(invocation.context);
        if (invocation.syncFlag) {
            MutexLocker locker(mainThreadFunctionQueueMutex());
            invocation.syncFlag->signal();
        }

        // If we are running accumulated functions for too long so UI may become unresponsive, we need to
        // yield so the user input can be processed. Otherwise user may not be able to even close the window.
        // This code has effect only in case the scheduleDispatchFunctionsOnMainThread() is implemented in a way that
        // allows input events to be processed before we are back here.
        if (currentTime() - startTime > maxRunLoopSuspensionTime) {
            scheduleDispatchFunctionsOnMainThread();
            break;
        }
    }
}

void callOnMainThread(MainThreadFunction* function, void* context)
{
    ASSERT(function);
    bool needToSchedule = false;
    {
        MutexLocker locker(mainThreadFunctionQueueMutex());
        needToSchedule = functionQueue().size() == 0;
        functionQueue().append(FunctionWithContext(function, context));
    }
    if (needToSchedule)
        scheduleDispatchFunctionsOnMainThread();
}

void callOnMainThreadAndWait(MainThreadFunction* function, void* context)
{
    ASSERT(function);

    if (isMainThread()) {
        function(context);
        return;
    }

    ThreadCondition syncFlag;
    Mutex& functionQueueMutex = mainThreadFunctionQueueMutex();
    MutexLocker locker(functionQueueMutex);
    functionQueue().append(FunctionWithContext(function, context, &syncFlag));
    if (functionQueue().size() == 1)
        scheduleDispatchFunctionsOnMainThread();
    syncFlag.wait(functionQueueMutex);
}

void cancelCallOnMainThread(MainThreadFunction* function, void* context)
{
    ASSERT(function);

    MutexLocker locker(mainThreadFunctionQueueMutex());

    FunctionWithContextFinder pred(FunctionWithContext(function, context));

    while (true) {
        // We must redefine 'i' each pass, because the itererator's operator=
        // requires 'this' to be valid, and remove() invalidates all iterators
        FunctionQueue::iterator i(functionQueue().findIf(pred));
        if (i == functionQueue().end())
            break;
        functionQueue().remove(i);
    }
}

static void callFunctionObject(void* context)
{
    Function<void ()>* function = static_cast<Function<void ()>*>(context);
    (*function)();
    delete function;
}

void callOnMainThread(const Function<void ()>& function)
{
    callOnMainThread(callFunctionObject, new Function<void ()>(function));
}

void setMainThreadCallbacksPaused(bool paused)
{
    ASSERT(isMainThread());

    if (callbacksPaused == paused)
        return;

    callbacksPaused = paused;

    if (!callbacksPaused)
        scheduleDispatchFunctionsOnMainThread();
}

#if !PLATFORM(MAC)
bool isMainThread()
{
    return currentThread() == mainThreadIdentifier;
}
#endif

#if ENABLE(PARALLEL_GC)
static ThreadSpecific<bool>* isGCThread;
#endif

void initializeGCThreads()
{
#if ENABLE(PARALLEL_GC)
    isGCThread = new ThreadSpecific<bool>();
#endif
}

#if ENABLE(PARALLEL_GC)
void registerGCThread()
{
    if (!isGCThread) {
        // This happens if we're running in a process that doesn't care about
        // MainThread.
        return;
    }

    **isGCThread = true;
}

bool isMainThreadOrGCThread()
{
    if (isGCThread->isSet() && **isGCThread)
        return true;

    return isMainThread();
}
#elif PLATFORM(MAC)
// This is necessary because JavaScriptCore.exp doesn't support preprocessor macros.
bool isMainThreadOrGCThread()
{
    return isMainThread();
}
#endif

} // namespace WTF


text:
process.env.TZ = 'UTC'
var expect = require('chai').expect
var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase
var ini_get = require('../../../../src/php/info/ini_get') // eslint-disable-line no-unused-vars,camelcase
var strpbrk = require('../../../../src/php/strings/strpbrk.js') // eslint-disable-line no-unused-vars,camelcase

describe('src/php/strings/strpbrk.js (tested in test/languages/php/strings/test-strpbrk.js)', function () {
  it('should pass example 1', function (done) {
    var expected = 'is is a Simple text.'
    var result = strpbrk('This is a Simple text.', 'is')
    expect(result).to.deep.equal(expected)
    done()
  })
})


text:
<bill session="110" type="h" number="5056" updated="2009-01-09T03:25:34-05:00">
	<status><introduced date="1200546000" datetime="2008-01-17"/></status>

	<introduced date="1200546000" datetime="2008-01-17"/>
	<titles>
		<title type="short" as="introduced">Iran Diplomatic Accountability Act of 2008</title>
		<title type="official" as="introduced">To provide for the appointment of a high-level United States representative or special envoy for Iran for the purpose of easing tensions and normalizing relations between the United States and Iran.</title>
	</titles>
	<sponsor id="400237"/>
	<cosponsors>
		<cosponsor id="400227" joined="2008-01-17"/>
		<cosponsor id="400080" joined="2008-01-22"/>
		<cosponsor id="400295" joined="2008-01-17"/>
		<cosponsor id="400262" joined="2008-02-06"/>
		<cosponsor id="400312" joined="2008-07-08"/>
		<cosponsor id="400387" joined="2008-01-22"/>
		<cosponsor id="400436" joined="2008-01-17"/>
		<cosponsor id="400422" joined="2008-01-17"/>
		<cosponsor id="400178" joined="2008-01-17"/>
		<cosponsor id="412239" joined="2008-01-29"/>
		<cosponsor id="400204" joined="2008-01-22"/>
		<cosponsor id="400033" joined="2008-02-13"/>
		<cosponsor id="400240" joined="2008-07-08"/>
		<cosponsor id="400301" joined="2008-01-17"/>
		<cosponsor id="400163" joined="2008-01-23"/>
		<cosponsor id="400100" joined="2008-05-13"/>
	</cosponsors>
	<actions>
		<action date="1200546000" datetime="2008-01-17"><text>Referred to the House Committee on Foreign Affairs.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	1/17/2008--Introduced.<br/>Iran Diplomatic Accountability Act of 2008 - Directs: (1) the President to appoint a high-level U.S. representative or special envoy for Iran for the purpose of easing tensions and normalizing relations between the United States and Iran; and (2) the Secretary of State to establish a Department of State office to support the work of such representative or special envoy.
	</summary>
</bill>


text:
<?php
namespace Application\Service;

interface UserService
{
	/**
	 * User Subscribe to the system the first time user log in with supported SSO
	 *
	 * @param array [email, family_name, given_name, picture]
	 * @return User
	 */
	public function subscribeUser($userInfo);

	/**
	 * Create a User
	 *
	 * @param array [email, family_name, given_name, picture]
	 * @param string $role
	 * @return User
	 */
	public function create($infoOfUser, $role);

	/**
	 * Find a User by id
	 *
	 * @param mixed $id
	 * @return User
	 */
	public function findUser($id);

	/**
	 * Find a User by Email
	 *
	 * @param string $email
	 * @return User
	 */
	public function findUserByEmail($email);

	/**
	 * Find users by $filters
	 * @param String $filters["kanbanizeUsername"]
	 * @return User[]
	 */
	public function findUsers($filters);
}


text:
from thefuck.utils import for_app

@for_app('grep')
def match(command):
    return 'is a directory' in command.stderr.lower()

def get_new_command(command):
    return u'grep -r {}'.format(command.script[5:])


text:
package com.android.tools.idea.welcome.install;

import com.android.sdklib.devices.Storage;
import com.android.sdklib.repository.FullRevision;
import com.android.tools.idea.welcome.config.FirstRunWizardMode;
import com.google.common.collect.Iterables;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.PathUtil;
import org.jetbrains.android.sdk.AndroidSdkUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.List;

/**
 * The goal is to keep all defaults in one place so it is easier to update
 * them as needed.
 */
public class FirstRunWizardDefaults {
  public static final String HAXM_DOCUMENTATION_URL =
    "https://software.intel.com/android/articles/intel-hardware-accelerated-execution-manager";
  public static final String HAXM_WINDOWS_INSTALL_URL =
    "https://software.intel.com/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows";
  public static final String HAXM_MAC_INSTALL_URL =
    "https://software.intel.com/android/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-mac-os-x";
  public static final String KVM_LINUX_INSTALL_URL =
    "https://software.intel.com/blogs/2012/03/12/how-to-start-intel-hardware-assisted-virtualization-hypervisor-on-linux-to-speed-up-intel-android-x86-emulator";
  public static final JavaSdkVersion MIN_JDK_VERSION = JavaSdkVersion.JDK_1_7;

  private FirstRunWizardDefaults() {
    // Do nothing
  }

  /**
   * @return Recommended memory allocation given the computer RAM size
   */
  public static int getRecommendedHaxmMemory(long memorySize) {
    final long GB = Storage.Unit.GiB.getNumberOfBytes();
    final long defaultMemory;
    if (memorySize > 4 * GB) {
      defaultMemory = 2 * GB;
    }
    else {
      if (memorySize > 2 * GB) {
        defaultMemory = GB;
      }
      else {
        defaultMemory = GB / 2;
      }
    }
    return (int)(defaultMemory / Haxm.UI_UNITS.getNumberOfBytes());
  }

  /**
   * @return Android SDK download URL
   */
  @NotNull
  public static String getSdkDownloadUrl() {
    String url = System.getProperty("android.sdkurl");
    if (!StringUtil.isEmptyOrSpaces(url)) {
      File file = new File(url);
      if (file.isFile()) {
        // Can't use any path => URL utilities as they don't add two slashes
        // after the protocol as required by IJ downloader
        return LocalFileSystem.PROTOCOL_PREFIX + PathUtil.toSystemIndependentName(file.getAbsolutePath());
      }
      else {
        System.err.println("File " + file.getAbsolutePath() + " does not exist.");
      }
    }
    String downloadUrl = AndroidSdkUtils.getSdkDownloadUrl();
    if (downloadUrl == null) {
      throw new IllegalStateException("Unsupported OS");
    }
    return downloadUrl;
  }

  /**
   * @return Default Android SDK install location
   */
  @NotNull
  private static File getDefaultSdkLocation() {
    String userHome = System.getProperty("user.home");
    String path;
    if (SystemInfo.isWindows) {
      path = FileUtil.join(userHome, "AppData", "Local", "Android", "Sdk");
    }
    else if (SystemInfo.isMac) {
      path = FileUtil.join(userHome, "Library", "Android", "sdk");
    }
    else if (SystemInfo.isLinux) {
      path = FileUtil.join(userHome, "Android", "Sdk");
    }
    else {
      throw new IllegalStateException("Unsupported OS");
    }
    return new File(path);
  }

  /**
   * Returns initial SDK location. That will be the SDK location from the installer
   * handoff file in the handoff case, sdk location location from the preference if set
   * or platform-dependant default path.
   */
  @NotNull
  public static File getInitialSdkLocation(@NotNull FirstRunWizardMode mode) {
    File dest = mode.getSdkLocation();
    if (dest != null) {
      return dest;
    }
    else {
      List<Sdk> sdks = AndroidSdkUtils.getAllAndroidSdks();
      Sdk sdk = Iterables.getFirst(sdks, null);
      if (sdk != null) {
        VirtualFile homeDirectory = sdk.getHomeDirectory();
        if (homeDirectory != null) {
          return VfsUtilCore.virtualToIoFile(homeDirectory);
        }
      }
      return getDefaultSdkLocation();
    }
  }

}


text:
@KartoffelCheetah 's first website's repo.

I uploaded my first website so you can have a look at it or do what you want with it.
Feel free to use it for your own website if you like. I already added some images as placeholders.

Please note that the server is set in development mode. Do not run it directly in production environment. This is intentional, because it is likely that future users will first want to develop.
**Before going into production please switch to production mode! Or (better) use some production ready WSGI server on top like described below.**

## Dependencies:

- ImageMagick, Python3 and Flask installed on your computer.
- Optionally install npm and Node.js if you wish to edit the Stylus stylesheets.
- @Deevad 's [Pepper&Carrot Fonts](https://github.com/Deevad/peppercarrot_fonts)
- [JQuery-3.2.1](http://jquery.com/) (included)

**Note:** favicons were generated by @RealFaviconGenerator 's [RealFaviconGenerator](https://realfavicongenerator.net/).

## Installation:

In the following I assume you have Python3 with Flask installed.

Navigate to the chosen folder to clone the repo:

```git clone https://github.com/KartoffelCheetah/personal-website-001.git```

```
personal-website-001
│  server.py        # ./server.py will run the development server
│  main.py          # ./main.py is the interface for common tasks
│  db.py            # these are the function defs of the db
|  IMfunctions.py   # IMAGE MAGICK functions for image manipulation
|  console_paint.py          # Terminal colorizer
|  console_paint_presets.py  # Local presets for terminal colorizer
│  package.json
│  LICENSE
│  README.md
└───templates
          # jinja templates
└───staging_area
          # place here images before making them public
└───static
          # static files to serve
```

You need to clone [Pepper&Carrot Fonts](https://github.com/Deevad/peppercarrot_fonts):

```cd ./personal-website-001/static/ && mkdir fonts && cd fonts && git clone https://github.com/Deevad/peppercarrot_fonts```

**Optional:**
If you prefer to use Stylus instead of pure CSS install npm and Node.
Then use `npm run styl` to run the compiler from the main directory. For details check the [package.json](./package.json) file.

**Set up database:**
1. Put your drawigns inside [staging_area/drawings/](./staging_area/drawings)
2. Put your photos inside [staging_area/photos/](./staging_area/photos/)<some_subdir>/
3. Run [main.py](./main.py) and select Create database
4. Run [main.py](./main.py) and select Create Staging file
5. Edit the staing file
6. Run [main.py](./main.py) and select Use Staging file

To run the development server just run [server.py](./server.py).

**You set up everything for a development server.**

To set up a production server you need additional WSGI tools.
Install [gunicorn](http://gunicorn.org/) for example.
```pip3 install gunicorn```
Then just use something like ```gunicorn -w 4 server:app```.


text:
"""
Writes mean utterance count data in tabular format.
"""

__author__ = "Todd Shore <errantlinguist+github@gmail.com>"
__copyright__ = "Copyright 2018 Todd Shore"
__license__ = "Apache License, Version 2.0"

import argparse
import csv
import statistics
import sys
from typing import Iterable, Sequence

import pandas as pd

from tangrams_analysis import game_utterances
from tangrams_analysis import session_data as sd

class UtteranceCounter(object):

	@staticmethod
	def __count_utts(session_datum: sd.SessionData,
					 session_round_utt_df_factory: game_utterances.SessionGameRoundUtteranceSequenceFactory) -> pd.Series:
		round_utt_df = session_round_utt_df_factory(session_datum)
		# Just use the "true" referent rows for extra safety in case something weird happens with the counts otherwise
		round_utt_df = round_utt_df.loc[round_utt_df["REFERENT"] == True]
		utt_counts = round_utt_df[session_round_utt_df_factory.UTTERANCE_SEQUENCE_COL_NAME].transform(
			lambda utts: len(utts))
		return utt_counts

	def __init__(self):
		pass

	def __call__(self, session_data: Iterable[sd.SessionData]) -> Sequence[int]:
		result = []
		session_round_utt_df_factory = game_utterances.SessionGameRoundUtteranceSequenceFactory()
		for session_datum in session_data:
			utt_counts = self.__count_utts(session_datum, session_round_utt_df_factory)
			result.extend(utt_counts)
		return result

def __create_argparser() -> argparse.ArgumentParser:
	result = argparse.ArgumentParser(
		description="Writes mean utterance count data in tabular format.")
	result.add_argument("inpaths", metavar="INPATH", nargs='+',
						help="The paths to search for session data.")
	return result

def __main(args):
	inpaths = args.inpaths
	print("Looking for session data underneath {}.".format(inpaths), file=sys.stderr)
	infile_session_data = sd.walk_session_data(inpaths)
	utt_counter = UtteranceCounter()
	utt_counts = utt_counter((session_datum for (_, session_datum) in infile_session_data))

	# https://pythonconquerstheuniverse.wordpress.com/2011/05/08/newline-conversion-in-python-3/
	writer = csv.writer(sys.stdout, dialect=csv.excel_tab, lineterminator="\n")
	writer.writerow(("DESC", "VALUE"))
	writer.writerow(("Total rounds", len(utt_counts)))
	writer.writerow(("Mean utts per round", statistics.mean(utt_counts)))
	writer.writerow(("Median utts per round", statistics.median(utt_counts)))
	writer.writerow(("Stdev", statistics.stdev(utt_counts)))

if __name__ == "__main__":
	__main(__create_argparser().parse_args())


text:
package com.thaiopensource.relaxng.edit;

public class ExternalRefPattern extends Pattern
{
  private String uri;
  private String ns;
  private String href;
  private String baseUri;

  public ExternalRefPattern (final String uri)
  {
    this.uri = uri;
  }

  public String getUri ()
  {
    return uri;
  }

  public void setUri (final String uri)
  {
    this.uri = uri;
  }

  public String getNs ()
  {
    return ns;
  }

  public void setNs (final String ns)
  {
    this.ns = ns;
  }

  public String getHref ()
  {
    return href;
  }

  public void setHref (final String href)
  {
    this.href = href;
  }

  public String getBaseUri ()
  {
    return baseUri;
  }

  public void setBaseUri (final String baseUri)
  {
    this.baseUri = baseUri;
  }

  @Override
  public <T> T accept (final PatternVisitor <T> visitor)
  {
    return visitor.visitExternalRef (this);
  }
}