text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using IronPython.Runtime;
using IronPython.Runtime.Operations;

namespace NumpyDotNet
{
    /// <summary>
    /// A multi-array iterator.
    /// </summary>
    public class broadcast : Wrapper, IEnumerator<PythonTuple>
    {
        public broadcast(params object[] args) {
            try {
                BeingCreated = this;
                core = NpyCoreApi.MultiIterFromObjects(args);
            } finally {
                BeingCreated = null;
            }
        }

        [ThreadStatic]
        internal static broadcast BeingCreated;

        internal IntPtr Iter {
            get {
                return core;
            }
        }

        public int numiter {
            get {
                return Marshal.ReadInt32(core + NpyCoreApi.MultiIterOffsets.off_numiter);
            }
        }

        public long[] dims {
            get {
                return NpyCoreApi.GetArrayDims(this, true);
            }
        }

        public object size {
            get {
                return Marshal.ReadIntPtr(core + NpyCoreApi.MultiIterOffsets.off_size).ToPython();
            }
        }

        public object index {
            get {
                return Marshal.ReadIntPtr(core + NpyCoreApi.MultiIterOffsets.off_index).ToPython();
            }
        }

        private long getIndex() {
            return Marshal.ReadIntPtr(core + NpyCoreApi.MultiIterOffsets.off_index).ToInt64();
        }

        private void setIndex(long value) {
            Marshal.WriteIntPtr(core + NpyCoreApi.MultiIterOffsets.off_index, (IntPtr)value);
        }

        public int nd {
            get {
                return Marshal.ReadInt32(core + NpyCoreApi.MultiIterOffsets.off_nd);
            }
        }

        public PythonTuple shape {
            get {
                int ndim = nd;
                long[] result = new long[ndim];
                IntPtr dims = core + NpyCoreApi.MultiIterOffsets.off_dimensions;
                for (int i = 0; i < ndim; i++) {
                    result[i] = Marshal.ReadIntPtr(dims).ToInt64();
                    dims += IntPtr.Size;
                }
                return new PythonTuple(result);
            }
        }

        public PythonTuple iters {
            get {
                return new PythonTuple(this.Iters);
            }
        }

        public flatiter[] Iters {
            get {
                int n = numiter;
                flatiter[] result = new flatiter[n];
                IntPtr iters = core + NpyCoreApi.MultiIterOffsets.off_iters;
                for (int i = 0; i < n; i++) {
                    result[i] = NpyCoreApi.ToInterface<flatiter>(Marshal.ReadIntPtr(iters));
                    iters += IntPtr.Size;
                }
                return result;
            }
        }

        private flatiter iter(int i) {
            IntPtr iter = core + NpyCoreApi.MultiIterOffsets.off_iters + i * IntPtr.Size;
            return NpyCoreApi.ToInterface<flatiter>(Marshal.ReadIntPtr(iter));
        }

        public void reset() {
            Reset();
        }

        public PythonTuple Current {
            get {
                int n = numiter;
                object[] result = new object[n];
                for (int i = 0; i < n; i++) {
                    result[i] = iter(i).Current;
                }
                return new PythonTuple(result);
            }
        }

        object System.Collections.IEnumerator.Current {
            get {
                int n = numiter;
                object[] result = new object[n];
                for (int i = 0; i < n; i++) {
                    result[i] = iter(i).Current;
                }
                return new PythonTuple(result);
            }
        }

        public bool MoveNext() {
            bool result = false;
            int n = numiter;
            setIndex(getIndex() + 1);
            for (int i = 0; i < n; i++) {
                result = iter(i).MoveNext();
            }
            return result;
        }

        public void Reset() {
            int n = numiter;
            setIndex(-1);
            for (int i = 0; i < n; i++) {
                iter(i).Reset();
            }
        }
    }
}


text:
package org.microbule.logging.decorator;

import javax.inject.Named;
import javax.inject.Singleton;

import org.apache.cxf.feature.LoggingFeature;
import org.microbule.config.api.Config;
import org.microbule.spi.JaxrsProxyDecorator;
import org.microbule.spi.JaxrsServerDecorator;
import org.microbule.spi.JaxrsServiceDescriptor;

@Singleton
@Named("loggingDecorator")
public class LoggingDecorator implements JaxrsServerDecorator, JaxrsProxyDecorator {
//----------------------------------------------------------------------------------------------------------------------
// JaxrsServiceDecorator Implementation
//----------------------------------------------------------------------------------------------------------------------

    @Override
    public void decorate(JaxrsServiceDescriptor descriptor, Config config) {
        descriptor.addFeature(new LoggingFeature());
    }

    @Override
    public String name() {
        return "logging";
    }
}

redpajama_set_name: RedPajamaGithub


text:
class CreateSettings < ActiveRecord::Migration
  def change
    create_table :settings do |t|
      t.string :key
      t.string :value

      t.timestamps null: false
    end
  end
end


text:
<?php if ($this->getParameterValue('list.object_actions')): ?>

<?php foreach ($this->getParameterValue('list.object_actions') as $actionName => $params): ?>
  <?php echo $this->addCredentialCondition($this->getLinkToAction($actionName, $params, true), $params) ?>
<?php endforeach; ?>

<?php endif; ?>


text:
package achilles

/**
 * Created by panda on 3/24/15.
 */

import akka.actor.Actor
import akka.actor.Actor.Receive
import breeze.linalg._

trait Node {
  def nodeType(): String
  def compute(): Unit

  def timestamp(): Long
}

class TopicNode(val topicId: Long) extends Node {
  var topicCount: Int = ???
  override def nodeType(): String = "topic"
  override def compute(): Unit = ???

  override def timestamp(): Long = ???
}

class TermTopicLink(val termId: Long, val topicId: Long) extends Node {
  var topicCount: Long = 0

  override def nodeType(): String = ???

  override def compute(): Unit = ???

  override def timestamp(): Long = ???
}


text:
if ! type -P android &> /dev/null; then
    echo "Error: 'android' utility is not in your path."
    echo "  Did you forget to setup the SDK?"
    exit 1
fi

projectname=`sed -n 's,.*name="app_name">\(.*\)<.*,\1,p' res/values/strings.xml`

android update project --path . --name $projectname --subprojects


text:
/* */
'use strict';
var SyntheticEvent = require("./SyntheticEvent");
var getEventTarget = require("./getEventTarget");
var UIEventInterface = {
  view: function(event) {
    if (event.view) {
      return event.view;
    }
    var target = getEventTarget(event);
    if (target != null && target.window === target) {
      return target;
    }
    var doc = target.ownerDocument;
    if (doc) {
      return doc.defaultView || doc.parentWindow;
    } else {
      return window;
    }
  },
  detail: function(event) {
    return event.detail || 0;
  }
};
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) {
  SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;


text:
/* Layout settings for starting with a component */

/* Sets the app component position */
.sapUiOpaComponent {
	margin-left: 20%;
}

/* Sets the qunit wrapper position and causes the proper positioning of all elements inside.
   Enables the vertical scrolling */
.sapUiOpaBodyComponent #qunit {
	position: fixed;
	left: 0;
	width: 20%;
	height: 100%;
	overflow-y: scroll;
}

/* Allows the line break */
.sapUiOpaBodyComponent #qunit-tests .runtime {
	float: none;
}

/* Sets the message dialog position */
/* Have to use important flag because the style property is set directly to element */
.sapUiOpaBodyComponent .sapMDialog {
	left: 50% !important;
}

/* Sets the message toast position */
/* Have to use important flag because the style property is set directly to element */
.sapUiOpaBodyComponent .sapMMessageToast {
	left: 60% !important;
}

/* Sets the blocklayer position */
.sapUiOpaBodyComponent #sap-ui-blocklayer-popup {
	top: 0;
	left: 20%;
}

/* Layout settings for starting in a frame */
.opaFrame {
	width: 100%;
	height: 100%;
	position: absolute;
	opacity: 0.7;
	bottom: -20%;
	right: -20%;
	top: 0;
	transform: scale(0.6) ;
}

/* The :hover selector is used to select elements (in our case the OPA-Frame) when you mouse over them */
.opaFrame:hover {
	opacity: 1;
}


text:
#include <Furrovine++/BufferData.h>
#include <Furrovine++/Graphics/IndexElementFormat.h>
#include <Furrovine++/Graphics/IndexElementSize.h>

namespace Furrovine { namespace Graphics {

	class IndexBufferData : public BufferData {
	private:
		ulword indexcount;
		IndexElementFormat format;

	public:

		template <typename TContainer>
		IndexBufferData ( TContainer&& container, IndexElementFormat format );

		template <typename TContainer>
		IndexBufferData ( TContainer&& container, ulword count );

		template <typename TContainer>
		IndexBufferData ( TContainer&& container, ulword count, IndexElementFormat format );

		furrovineapi IndexBufferData ( IndexBufferData&& mov );
		furrovineapi IndexBufferData& operator= ( IndexBufferData&& mov );

		furrovineapi ulword IndexCount () const;

		furrovineapi IndexElementFormat IndexFormat () const;

	};

}}

#endif // FURROVINEINDEXBUFFERDATA_DECL_H


text:
package org.archive.crawler.datamodel;

import java.util.logging.Logger;

import org.apache.commons.collections.Closure;
import org.apache.commons.httpclient.URIException;
import org.archive.crawler.framework.CrawlController;
import org.archive.crawler.settings.SettingsHandler;
import org.archive.util.ObjectIdentityCache;
import org.archive.util.ObjectIdentityMemCache;
import org.archive.util.Supplier;

/**
 * Server and Host cache.
 * @author stack
 * @version $Date: 2009-11-09 23:40:30 +0000 (Mon, 09 Nov 2009) $, $Revision: 6635 $
 */
public class ServerCache {
    private static Logger logger =
        Logger.getLogger(ServerCache.class.getName());

    protected SettingsHandler settingsHandler = null;

    /**
     * hostname[:port] -> CrawlServer.
     * Set in the initialization.
     */
    protected ObjectIdentityCache<String,CrawlServer> servers = null;

    /**
     * hostname -> CrawlHost.
     * Set in the initialization.
     */
    protected ObjectIdentityCache<String,CrawlHost> hosts = null;

    /**
     * Constructor.
     * Shutdown access to the default constructor by making it protected.
     */
    protected ServerCache() {
        super();
    }

    /**
     * This constructor creates a ServerCache that is all memory-based using
     * Hashtables.  Used for unit testing only
     * (Use {@link #ServerCache(CrawlController)} when crawling).
     * @param sh
     * @throws Exception
     */
    public ServerCache(final SettingsHandler sh)
    throws Exception {
        this.settingsHandler = sh;
        this.servers = new ObjectIdentityMemCache<CrawlServer>();
        this.hosts = new ObjectIdentityMemCache<CrawlHost>();
    }

    /**
     * Create a ServerCache that uses the given CrawlController to initialize the
     * maps of servers and hosts.
     * @param c
     * @throws Exception
     */
    public ServerCache(final CrawlController c)
    throws Exception {
        this.settingsHandler = c.getSettingsHandler();
        this.servers = c.getBigMap("servers", CrawlServer.class);
        this.hosts = c.getBigMap("hosts", CrawlHost.class);
    }

    /**
     * Get the {@link CrawlServer} associated with name,
     * creating if necessary.
     * @param serverKey Server name we're to return server for.
     * @return CrawlServer instance that matches the passed server name.
     */
    public CrawlServer getServerFor(final String serverKey) {
        CrawlServer cserver = servers.getOrUse(
                serverKey,
                new Supplier<CrawlServer>() {
                    public CrawlServer get() {
                        String skey = new String(serverKey); // ensure private minimal key
                        CrawlServer cs = new CrawlServer(skey);
                        cs.setSettingsHandler(settingsHandler);
                        return cs;
                    }});
        return cserver;
    }

    /**
     * Get the {@link CrawlServer} associated with curi.
     * @param cauri CandidateURI we're to get server from.
     * @return CrawlServer instance that matches the passed CandidateURI.
     */
    public CrawlServer getServerFor(CandidateURI cauri) {
        CrawlServer cs = null;
        try {
            String key = CrawlServer.getServerKey(cauri);
            // TODOSOMEDAY: make this robust against those rare cases
            // where authority is not a hostname.
            if (key != null) {
                cs = getServerFor(key);
            }
        } catch (URIException e) {
            logger.severe(e.getMessage() + ": " + cauri);
            e.printStackTrace();
        } catch (NullPointerException npe) {
            logger.severe(npe.getMessage() + ": " + cauri);
            npe.printStackTrace();
        }
        return cs;
    }

    /**
     * Get the {@link CrawlHost} associated with name.
     * @param hostname Host name we're to return Host for.
     * @return CrawlHost instance that matches the passed Host name.
     */
    public CrawlHost getHostFor(final String hostname) {
        if (hostname == null || hostname.length() == 0) {
            return null;
        }
        CrawlHost host = hosts.getOrUse(
                hostname,
                new Supplier<CrawlHost>() {
                    public CrawlHost get() {
                        String hkey = new String(hostname); // ensure private minimal key
                        return new CrawlHost(hkey);
                    }});
        return host;
    }

    /**
     * Get the {@link CrawlHost} associated with curi.
     * @param cauri CandidateURI we're to return Host for.
     * @return CandidateURI instance that matches the passed Host name.
     */
    public CrawlHost getHostFor(CandidateURI cauri) {
        CrawlHost h = null;
        try {
            String hostKey;
            if (cauri.getUURI().getScheme().equals("dns")) {
                hostKey = "dns:";
            } else {
                hostKey = cauri.getUURI().getReferencedHost();
            }
            h = getHostFor(hostKey);
        } catch (URIException e) {
            e.printStackTrace();
        }
        return h;
    }

    /**
     * @param serverKey Key to use doing lookup.
     * @return True if a server instance exists.
     */
    public boolean containsServer(String serverKey) {
        return (CrawlServer) servers.get(serverKey) != null;
    }

    /**
     * @param hostKey Key to use doing lookup.
     * @return True if a host instance exists.
     */
    public boolean containsHost(String hostKey) {
        return (CrawlHost) hosts.get(hostKey) != null;
    }

    /**
     * Called when shutting down the cache so we can do clean up.
     */
    public void cleanup() {
        if (this.hosts != null) {
            // If we're using a bdb bigmap, the call to clear will
            // close down the bdb database.
            this.hosts.close();
            this.hosts = null;
        }
        if (this.servers != null) {
            this.servers.close();
            this.servers = null;
        }
    }

    public void forAllHostsDo(Closure c) {
        for(String host : hosts.keySet()) {
            c.execute(hosts.get(host));
        }
    }
}


text:
module Slather
  module CoverageService
    module SimpleOutput

      def coverage_file_class
        if input_format == "profdata"
          Slather::ProfdataCoverageFile
        else
          Slather::CoverageFile
        end
      end
      private :coverage_file_class

      def post
        total_project_lines = 0
        total_project_lines_tested = 0
        coverage_files.each do |coverage_file|
          # ignore lines that don't count towards coverage (comments, whitespace, etc). These are nil in the array.

          lines_tested = coverage_file.num_lines_tested
          total_lines = coverage_file.num_lines_testable
          percentage = decimal_f([coverage_file.percentage_lines_tested])

          total_project_lines_tested += lines_tested
          total_project_lines += total_lines

          puts "#{coverage_file.source_file_pathname_relative_to_repo_root}: #{lines_tested} of #{total_lines} lines (#{percentage}%)"
        end

        # check if there needs to be custom reporting based on the ci service
        if ci_service == :teamcity
          # TeamCity Build Statistic Reporting
          #
          # Reporting format ##teamcity[buildStatisticValue key='<valueTypeKey>' value='<value>']
          # key='CodeCoverageAbsLCovered' is total number of lines covered
          # key='CodeCoverageAbsLTotal' is total number of lines
          #
          # Sources:
          # - https://confluence.jetbrains.com/display/TCDL/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-ReportingBuildStatistics
          # - https://confluence.jetbrains.com/display/TCDL/Custom+Chart#CustomChart-listOfDefaultStatisticValues
          puts "##teamcity[buildStatisticValue key='CodeCoverageAbsLCovered' value='%i']" % total_project_lines_tested
          puts "##teamcity[buildStatisticValue key='CodeCoverageAbsLTotal' value='%i']" % total_project_lines
        end

        total_percentage = decimal_f([(total_project_lines_tested / total_project_lines.to_f) * 100.0])
        puts "Tested #{total_project_lines_tested}/#{total_project_lines} statements"
        puts "Test Coverage: #{total_percentage}%"
      end

    end
  end
end


text:
package com.amazonaws.services.codeartifact.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.codeartifact.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * PackageVersionDescription JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PackageVersionDescriptionJsonUnmarshaller implements Unmarshaller<PackageVersionDescription, JsonUnmarshallerContext> {

    public PackageVersionDescription unmarshall(JsonUnmarshallerContext context) throws Exception {
        PackageVersionDescription packageVersionDescription = new PackageVersionDescription();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("format", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setFormat(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("namespace", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setNamespace(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("packageName", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setPackageName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("displayName", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setDisplayName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("version", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setVersion(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("summary", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setSummary(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("homePage", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setHomePage(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("sourceCodeRepository", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setSourceCodeRepository(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("publishedTime", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setPublishedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("licenses", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setLicenses(new ListUnmarshaller<LicenseInfo>(LicenseInfoJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("revision", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setRevision(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("status", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("origin", targetDepth)) {
                    context.nextToken();
                    packageVersionDescription.setOrigin(PackageVersionOriginJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return packageVersionDescription;
    }

    private static PackageVersionDescriptionJsonUnmarshaller instance;

    public static PackageVersionDescriptionJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new PackageVersionDescriptionJsonUnmarshaller();
        return instance;
    }
}


text:
// Generated on Fri Nov 17 19:09:30 MSK 2006
// DTD/Schema  :    hibernate-mapping-3.0.dtd

package com.intellij.hibernate.model.xml.mapping;

import com.intellij.javaee.model.xml.CommonDomModelElement;
import com.intellij.util.xml.GenericAttributeValue;
import javax.annotation.Nonnull;

import java.util.List;

public interface HbmPropertyBase extends CommonDomModelElement, HbmAttributeBase, HbmColumnsHolderBase, HbmTypeHolderBase {

	@Nonnull
	GenericAttributeValue<String> getNode();

	@Nonnull
	GenericAttributeValue<Integer> getLength();

	@Nonnull
	List<HbmMeta> getMetas();
	HbmMeta addMeta();

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__char_file_ofstream_52b.cpp
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-52b.tmpl.cpp
*/
/*
 * @description
 * CWE: 23 Relative Path Traversal
 * BadSource: file Read input from a file
 * GoodSource: Use a fixed file name
 * Sink: ofstream
 *    BadSink : Open the file named in data using ofstream::open()
 * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#define BASEPATH "c:\\temp\\"
#else
#include <wchar.h>
#define BASEPATH "/tmp/"
#endif

#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif

#include <fstream>
using namespace std;

namespace CWE23_Relative_Path_Traversal__char_file_ofstream_52
{

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

/* bad function declaration */
void badSink_c(char * data);

void badSink_b(char * data)
{
    badSink_c(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(char * data);

void goodG2BSink_b(char * data)
{
    goodG2BSink_c(data);
}

#endif /* OMITGOOD */

} /* close namespace */


text:
class ppSingletonsDelete
{
public:
    ~ppSingletonsDelete();
};

#endif  // __PPSINGLETONSDELETE_H


text:
// Copyright (c) 2013-present, febit.org. All Rights Reserved.
package org.febit.wit.util;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

/**
 * @author zqq90
 */
class FileNameUtilTest {

    @Test
    void test() {
        assertEquals("/parent/tmpl.wit", FileNameUtil.concat("/parent/", "tmpl.wit"));
        assertEquals("/parent/tmpl.wit", FileNameUtil.concat("/parent/", "./tmpl.wit"));
        assertEquals("/tmpl.wit", FileNameUtil.concat("/parent/", "../tmpl.wit"));

        assertEquals("/parent/tmpl.wit", FileNameUtil.concat("/parent", "tmpl.wit"));
        assertEquals("/parent/tmpl.wit", FileNameUtil.concat("/parent", "./tmpl.wit"));
        assertEquals("/tmpl.wit", FileNameUtil.concat("/parent", "../tmpl.wit"));

        assertEquals("/tmpl.wit", FileNameUtil.normalize("/parent/../tmpl.wit"));

        assertNull(FileNameUtil.normalize("/../tmpl.wit"));
        assertNull(FileNameUtil.normalize("../tmpl.wit"));
        assertNull(FileNameUtil.normalize("/parent/../../tmpl.wit"));

        assertEquals("/parent/", FileNameUtil.getPath("/parent/tmpl.wit"));
        assertEquals("/", FileNameUtil.getPath("/tmpl.wit"));
    }
}


text:
function login() {
    var formobj=$("#loginForm");
	var loginname=formobj.find("input[name='user_name']");

	if(loginname.val()==""){
		loginname.focus();
		showToast("用户名不能为空");
		return false;
	}
	var postData = 'user_name=' + $.urlencode(loginname.val());

	var password=formobj.find("input[name='password']");
	if(password.val()==""){
		password.focus();
		showToast("密码不能为空");
		return false;
	}
	postData += '&password=' + hex_md5(password.val());

	var logincode=formobj.find("input[name='code']");
	if(logincode.val()==""){
		logincode.focus();
		showToast("验证码不能为空");
		return false;
	}
	postData += '&code=' + $.urlencode(logincode.val());

	simplePost('/login/ajax', postData, {
	    ok : function() {
	        (top || window).location.reload();
	    },
	    notok : function() {
	        change_logincode();
	    },
	    error : function() {
	        change_logincode();
	    }
	});
}

function register() {
    var formobj=$("#registForm");
	var loginname=formobj.find("input[name='user_name']");
	if(loginname.val()==""){
		loginname.focus();
		showToast("用户名不能为空");
		return false;
	}
	var postData = 'user_name=' + $.urlencode(loginname.val());

	var password=formobj.find("input[name='password']");
	if(password.val()==""){
		password.focus();
		showToast("密码不能为空");
		return false;
	}
	var confirm_pwd=formobj.find("input[name='confirm_pwd']");
	if(confirm_pwd.val()==""){
		confirm_pwd.focus();
		showToast("确认密码不能为空");
		return false;
	}
	if (password.val() != confirm_pwd.val()) {
	    confirm_pwd.focus();
		showToast("两次密码不一致");
		return false;
	}
	postData += '&password=' + hex_md5(password.val());

	var truename=formobj.find("input[name='true_name']");
	if(truename.val()==""){
		truename.focus();
		showToast("姓名不能为空");
		return false;
	}
	postData += '&true_name=' + $.urlencode(truename.val());

	var contact=formobj.find("input[name='contact_mobile']");
	if(contact.val()==""){
		contact.focus();
		showToast("联系方式不能为空");
		return false;
	}
	postData += '&contact_mobile=' + $.urlencode(contact.val());

	var logincode=formobj.find("input[name='code']");
	if(logincode.val()==""){
		logincode.focus();
		showToast("验证码不能为空");
		return false;
	}
	postData += '&code=' + $.urlencode(logincode.val());

	simplePost('/register/ajax', postData, {
	    ok : function() {
	        (top || window).location.reload();
	    },
	    notok : function() {
	        change_registcode();
	    },
	    error : function() {
	        change_registcode();
	    }
	});
}

function logout() {
    simplePost('/logout', '', {
	    ok : function() {
	        (top || window).location.reload();
	    }
	});
}

function change_logincode() {
    $("#logincode").get(0).src="/login_vercode?rand="+Math.random();
}

function change_registcode() {
    $("#registcode").get(0).src="/register_vercode?rand="+Math.random();
}

$("#change_registcode").click(function(){
	change_registcode();
});

$("#change_logincode").click(function(){
	change_logincode();
});


text:
=begin

#Psuedocode
-Define a method called acct_groups that accepts and array as an argument
-Count the number of people in the list
-Divide list up into groups of 4 or 5 with a minimum of three people
  -IF list has 5 people or less, then everyone is in the same group
  -ELSE the group is more than 5 people
    -IF number of people can be divided by 5 with a remainder of 0 or >=3,
    divide list into groups of 5
    -IF number of people can be divided by 4 with a remainder of 0 or 3,
    divide list into groups of 4
    -Figure out solution for numbers that for not return 0 when divided by 5
    or 4
=end

#Initial Solution
#MVP will have groups in individual arrays

def acct_groups (array)
  array.shuffle!
  group_size = array.length
  if group_size <= 5
   p array
  elsif group_size % 5 == 0 || group_size % 5 >= 3
   p array.each_slice(5).to_a
  elsif group_size % 4 == 0 || group_size % 4 == 3
   p array.each_slice(4).to_a
  else
   p array.shift(3)
   p array.each_slice(5).to_a
  end
end

=begin

Reflection:
1. What was the most interesting and most difficult part of this challenge?
The group size parameters made this challenge interesting for me. It helped
for me think how I might approach the problem in the real world without a
computer and apply that logic to my pseudocode. Without something to test
against, I had difficulty understanding if I was approaching the problem in
the right way. With so much room for creativity, I can't help but feel like
there is a much more efficient & unique way to solve this problem!

2. Do you feel you are improving in your ability to write pseudocode and break
the problem down?
I feel like I am slowly starting to understand how I need to approach coding
problems. I am still getting used to learning how to generalize my psuedocode,
but it gets a little easier each time.

3. Was your approach for automating this task a good solution? What could have
made it even better?
My solution works, however some of the code looks a bit redundant. I was
unable to refactor it any further and have it run successfully.

4. What data structure did you decide to store the accountability groups in
and why?
Each time the code runs, the original array is shuffled so new groups are
formed. I decided to store my groups in arrays because they each contain a
simple list.

5.What did you learn in the process of refactoring your initial solution? Did
you learn any new Ruby methods?
Refactoring is still a bit difficult for me. Since I am still learning, the
only working solution I am getting so far is pretty close to what my MVP is. I
learned the .slice method and the enumerable each_slice.

=end


text:
/**
 *
 *  You can modify and use this source freely
 *  only for the development of application related Live2D.
 *
 *  (c) Live2D Inc. All rights reserved.
 */

#pragma once

#include "L2DMatrix44.h"
#include <map>
#include <string>

namespace live2d
{
	namespace framework
	{

		class L2DModelMatrix : public L2DMatrix44
		{
		private:
			float    width;
			float    height;

		public:
			L2DModelMatrix(float w,float h);
			~L2DModelMatrix(){}

			void setWidth(float w);
			void setHeight(float h);

			void setPosition(float x,float y){translate(x, y);}
			void setCenterPosition(float x,float y);

			void top(float y){setY(y);}
			void bottom(float y);
			void left(float x){setX(x);}
			void right(float x);

			void centerX(float x);
			void setX(float x){translateX(x);}
			void centerY(float y);
			void setY(float y){translateY(y);}
			void setupLayout(std::map<std::string, float>& layout);
		};
	}
}


text:
"""
This file contains a minimal set of tests for compliance with the extension
array interface test suite, and should contain no other tests.
The test suite for the full functionality of the array is located in
`pandas/tests/arrays/`.

The tests in this file are inherited from the BaseExtensionTests, and only
minimal tweaks should be applied to get the tests passing (by overwriting a
parent method).

Additional tests should either be added to one of the BaseExtensionTests
classes (if they are relevant for the extension interface for all dtypes), or
be added to the array-specific tests in `pandas/tests/arrays/`.

"""
import string

import numpy as np
import pytest

import pandas as pd
from pandas import Categorical
from pandas.api.types import CategoricalDtype
from pandas.tests.extension import base

def make_data():
    while True:
        values = np.random.choice(list(string.ascii_letters), size=100)
        # ensure we meet the requirements
        # 1. first two not null
        # 2. first and second are different
        if values[0] != values[1]:
            break
    return values

@pytest.fixture
def dtype():
    return CategoricalDtype()

@pytest.fixture
def data():
    """Length-100 array for this type.

    * data[0] and data[1] should both be non missing
    * data[0] and data[1] should not gbe equal
    """
    return Categorical(make_data())

@pytest.fixture
def data_missing():
    """Length 2 array with [NA, Valid]"""
    return Categorical([np.nan, 'A'])

@pytest.fixture
def data_for_sorting():
    return Categorical(['A', 'B', 'C'], categories=['C', 'A', 'B'],
                       ordered=True)

@pytest.fixture
def data_missing_for_sorting():
    return Categorical(['A', None, 'B'], categories=['B', 'A'],
                       ordered=True)

@pytest.fixture
def na_value():
    return np.nan

@pytest.fixture
def data_for_grouping():
    return Categorical(['a', 'a', None, None, 'b', 'b', 'a', 'c'])

class TestDtype(base.BaseDtypeTests):
    pass

class TestInterface(base.BaseInterfaceTests):
    @pytest.mark.skip(reason="Memory usage doesn't match")
    def test_memory_usage(self, data):
        # Is this deliberate?
        super(TestInterface, self).test_memory_usage(data)

class TestConstructors(base.BaseConstructorsTests):
    pass

class TestReshaping(base.BaseReshapingTests):
    pass

class TestGetitem(base.BaseGetitemTests):
    skip_take = pytest.mark.skip(reason="GH-20664.")

    @pytest.mark.skip(reason="Backwards compatibility")
    def test_getitem_scalar(self, data):
        # CategoricalDtype.type isn't "correct" since it should
        # be a parent of the elements (object). But don't want
        # to break things by changing.
        super(TestGetitem, self).test_getitem_scalar(data)

    @skip_take
    def test_take(self, data, na_value, na_cmp):
        # TODO remove this once Categorical.take is fixed
        super(TestGetitem, self).test_take(data, na_value, na_cmp)

    @skip_take
    def test_take_negative(self, data):
        super().test_take_negative(data)

    @skip_take
    def test_take_pandas_style_negative_raises(self, data, na_value):
        super().test_take_pandas_style_negative_raises(data, na_value)

    @skip_take
    def test_take_non_na_fill_value(self, data_missing):
        super().test_take_non_na_fill_value(data_missing)

    @skip_take
    def test_take_out_of_bounds_raises(self, data, allow_fill):
        return super().test_take_out_of_bounds_raises(data, allow_fill)

    @pytest.mark.skip(reason="GH-20747. Unobserved categories.")
    def test_take_series(self, data):
        super().test_take_series(data)

    @skip_take
    def test_reindex_non_na_fill_value(self, data_missing):
        super().test_reindex_non_na_fill_value(data_missing)

    @pytest.mark.skip(reason="Categorical.take buggy")
    def test_take_empty(self, data, na_value, na_cmp):
        super().test_take_empty(data, na_value, na_cmp)

    @pytest.mark.skip(reason="test not written correctly for categorical")
    def test_reindex(self, data, na_value):
        super().test_reindex(data, na_value)

class TestSetitem(base.BaseSetitemTests):
    pass

class TestMissing(base.BaseMissingTests):

    @pytest.mark.skip(reason="Not implemented")
    def test_fillna_limit_pad(self, data_missing):
        super().test_fillna_limit_pad(data_missing)

    @pytest.mark.skip(reason="Not implemented")
    def test_fillna_limit_backfill(self, data_missing):
        super().test_fillna_limit_backfill(data_missing)

class TestReduce(base.BaseNoReduceTests):
    pass

class TestMethods(base.BaseMethodsTests):
    @pytest.mark.skip(reason="Unobserved categories included")
    def test_value_counts(self, all_data, dropna):
        return super().test_value_counts(all_data, dropna)

    def test_combine_add(self, data_repeated):
        # GH 20825
        # When adding categoricals in combine, result is a string
        orig_data1, orig_data2 = data_repeated(2)
        s1 = pd.Series(orig_data1)
        s2 = pd.Series(orig_data2)
        result = s1.combine(s2, lambda x1, x2: x1 + x2)
        expected = pd.Series(([a + b for (a, b) in
                               zip(list(orig_data1), list(orig_data2))]))
        self.assert_series_equal(result, expected)

        val = s1.iloc[0]
        result = s1.combine(val, lambda x1, x2: x1 + x2)
        expected = pd.Series([a + val for a in list(orig_data1)])
        self.assert_series_equal(result, expected)

    @pytest.mark.skip(reason="Not Applicable")
    def test_fillna_length_mismatch(self, data_missing):
        super().test_fillna_length_mismatch(data_missing)

    def test_searchsorted(self, data_for_sorting):
        if not data_for_sorting.ordered:
            raise pytest.skip(reason="searchsorted requires ordered data.")

class TestCasting(base.BaseCastingTests):
    pass

class TestArithmeticOps(base.BaseArithmeticOpsTests):

    def test_arith_series_with_scalar(self, data, all_arithmetic_operators):

        op_name = all_arithmetic_operators
        if op_name != '__rmod__':
            super(TestArithmeticOps, self).test_arith_series_with_scalar(
                data, op_name)
        else:
            pytest.skip('rmod never called when string is first argument')

    def test_add_series_with_extension_array(self, data):
        ser = pd.Series(data)
        with pytest.raises(TypeError, match="cannot perform"):
            ser + data

    def _check_divmod_op(self, s, op, other, exc=NotImplementedError):
        return super(TestArithmeticOps, self)._check_divmod_op(
            s, op, other, exc=TypeError
        )

class TestComparisonOps(base.BaseComparisonOpsTests):

    def _compare_other(self, s, data, op_name, other):
        op = self.get_op_from_name(op_name)
        if op_name == '__eq__':
            result = op(s, other)
            expected = s.combine(other, lambda x, y: x == y)
            assert (result == expected).all()

        elif op_name == '__ne__':
            result = op(s, other)
            expected = s.combine(other, lambda x, y: x != y)
            assert (result == expected).all()

        else:
            with pytest.raises(TypeError):
                op(data, other)

class TestParsing(base.BaseParsingTests):
    pass


text:
name              "rsyslog"
maintainer        "Opscode, Inc."
maintainer_email  "cookbooks@opscode.com"
license           "Apache 2.0"
description       "Installs and configures rsyslog"
long_description  IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version           "1.6.1"

recipe            "rsyslog", "Installs rsyslog"
recipe            "rsyslog::client", "Sets up a client to log to a remote rsyslog server"
recipe            "rsyslog::server", "Sets up an rsyslog server"

supports          "ubuntu"
supports          "debian", ">= 5.0"
supports          "redhat", ">= 6.0"

attribute "rsyslog",
  :display_name => "Rsyslog",
  :description => "Hash of Rsyslog attributes",
  :type => "hash"

attribute "rsyslog/log_dir",
  :display_name => "Rsyslog Log Directory",
  :description => "Filesystem location of logs from clients",
  :default => "/srv/rsyslog"

attribute "rsyslog/server",
  :display_name => "Rsyslog Server?",
  :description => "Is this node an rsyslog server?",
  :default => "false"

attribute "rsyslog/server_ip",
  :display_name => "Rsyslog Server IP Address",
  :description => "Set rsyslog server ip address explicitly"

attribute "rsyslog/server_search",
  :display_name => "Rsyslog Server Search Criteria",
  :description => "Set the search criteria for rsyslog server resolving",
  :default => "role:loghost"

attribute "rsyslog/protocol",
  :display_name => "Rsyslog Protocol",
  :description => "Set which network protocol to use for rsyslog",
  :default => "tcp"

attribute "rsyslog/port",
  :display_name => "Rsyslog Port",
  :description => "Port that Rsyslog listens for incoming connections",
  :default => "514"

attribute "rsyslog/remote_logs",
  :display_name => "Remote Logs",
  :description => "Specifies whether redirect all log from client to server",
  :default => "true"

attribute "rsyslog/user",
  :display_name => "User",
  :description => "The owner of Rsyslog config files and directories",
  :default => "root"

attribute "rsyslog/group",
  :display_name => "Group",
  :description => "The group-owner of Rsyslog config files and directories",
  :default => "adm"

attribute "rsyslog/service_name",
  :display_name => "Service name",
  :description => "The name of the service for the platform",
  :default => "rsyslog"

attribute "rsyslog/max_message_size",
  :display_name => "Maximum Rsyslog message size",
  :description => "Specifies the maximum size of allowable Rsyslog messages",
  :default => "2k"

attribute "rsyslog/preserve_fqdn",
  :display_name => "Preserve FQDN",
  :description => "Specifies if the short or full host name will be used. The default off setting is more compatible.",
  :default => "off"

attribute "rsyslog/priv_seperation",
  :display_name => "Privilege separation",
  :description => "Whether or not to make use of Rsyslog privilege separation",
  :default => "false"


text:
namespace GuaranteedRate.Net.Http.HttpService
{
    using System.Net.Http;
    using System.Threading.Tasks;
    using Newtonsoft.Json;

    public static class HttpResponseMessageExtensions
    {
        public static async Task<T> DeserializeAsync<T>(this HttpResponseMessage response)
        {
            if (response == null || response.Content == null)
                return default(T);
            var json = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}


text:
using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Umbraco.Core.Dynamics;

namespace Umbraco.Web.Models
{
    [DataContract(Name = "imageCropData")]
    public class ImageCropData : CaseInsensitiveDynamicObject<ImageCropData>, IEquatable<ImageCropData>
    {
        [DataMember(Name = "alias")]
        public string Alias { get; set; }

        [DataMember(Name = "width")]
        public int Width { get; set; }

        [DataMember(Name = "height")]
        public int Height { get; set; }

        [DataMember(Name = "coordinates")]
        public ImageCropCoordinates Coordinates { get; set; }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(ImageCropData other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return string.Equals(Alias, other.Alias) && Width == other.Width && Height == other.Height && Equals(Coordinates, other.Coordinates);
        }

        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        /// <returns>
        /// true if the specified object  is equal to the current object; otherwise, false.
        /// </returns>
        /// <param name="obj">The object to compare with the current object. </param>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((ImageCropData) obj);
        }

        /// <summary>
        /// Serves as the default hash function.
        /// </summary>
        /// <returns>
        /// A hash code for the current object.
        /// </returns>
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (Alias != null ? Alias.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ Width;
                hashCode = (hashCode*397) ^ Height;
                hashCode = (hashCode*397) ^ (Coordinates != null ? Coordinates.GetHashCode() : 0);
                return hashCode;
            }
        }

        public static bool operator ==(ImageCropData left, ImageCropData right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(ImageCropData left, ImageCropData right)
        {
            return !Equals(left, right);
        }
    }

}


text:
gulp pipe for creating index.js files from directories

# Usage:

in a gulp file

````javascript
var indexJS = require('index-js');

gulp.task('make-indecies', () => {

  var dirs = [
      './app/components',
      './app/mixins'
    ];
  return gulp.src(dirs, { base: './' })
          .pipe(indexJS())
          .pipe(gulp.dest('./dist'));
});
````


text:
static NSString * const RDYNewFeedViewControllerNavigationTitleViewText                = @"新的订阅";
static NSString * const RDYNewFeedViewControllerTextFieldPlaceholderRSSURL             = @"RSS地址";
static NSString * const RDYNewFeedViewControllerTextFieldTableViewCellIdentifier       = @"RDYTextFieldCell";
static NSString * const RDYNewFeedViewControllerConfirmTableViewCellIdentifier         = @"RDYButtonCell";
static NSString * const RDYNewFeedViewControllerTagsTableViewCellIdentifier            = @"RDYTagsCell";

@interface RDYNewFeedViewController ()
<UITableViewDelegate, UITableViewDataSource, RDYTagsViewControllerDelegate>

@property (nonatomic, strong) UITableView    *feedTableView;
@property (nonatomic, copy)   NSString       *urlText;
@property (nonatomic, copy)   NSString       *categoryText;

@end

@implementation RDYNewFeedViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = RDYNewFeedViewControllerNavigationTitleViewText;

    self.feedTableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        [self.view addSubview:tableView];
        tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.rowHeight = 64;

        tableView;
    });
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark - Event response

- (void)confirmButtonClicked {
    if (self.urlText) {
        [self p_parseFeedItem];
    }
    else {
        NSLog(@"url不能为空.");
    }
}

#pragma mark - Private Methods

- (void)p_parseFeedItem {

    __block FeedModel *feed;
    __block BOOL success;

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        feed = (FeedModel *)[[RDYNetworking sharedInstance] fetchFeedFromURL:_urlText];
        if (feed) {
            feed.link = _urlText;
            feed.category = _categoryText;
            success = [[FeedManager sharedInstance] prepareInsertFeedIntoDatabase:feed];
        }
        else {
            success = NO;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){0, 0, 37, 37}];
            hud.customView = label;
            hud.mode = MBProgressHUDModeCustomView;
            label.textAlignment = NSTextAlignmentCenter;
            if (success) {
                label.text = @"😀";
                hud.labelText = @"Success!";
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setBool:NO forKey:@"databaseEmpty"];
                [defaults synchronize];
            }
            else {
                label.text = @"😱";
                hud.labelText = @"Fail!";
            }
        });
        sleep(2);
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hide:YES];
        });
    });
}

#pragma mark - RDYTagsViewControllerDelegate

- (void)tagsViewControllerDidClickedDismissButton:(RDYTagsViewController *)viewController withTagValue:(NSString *)tag {
    if (tag) {
        RDYTagsCell *cell = [_feedTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        [cell setTag:tag];
        self.categoryText = tag;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (0 == indexPath.section && 1 == indexPath.row) {

        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        RDYTagsViewController *toViewController = [RDYTagsViewController new];
        toViewController.delegate = self;
        [self presentViewController:toViewController animated:YES completion:nil];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 0 ? 2 : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (0 == indexPath.section) {
        if (0 == indexPath.row) {
            RDYTextFieldCell *cell = (RDYTextFieldCell *)[tableView dequeueReusableCellWithIdentifier:RDYNewFeedViewControllerTextFieldTableViewCellIdentifier];
            if (!cell) {
                cell = [[RDYTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RDYNewFeedViewControllerTextFieldTableViewCellIdentifier];
            }
            [cell configureCellWithPlaceholder:RDYNewFeedViewControllerTextFieldPlaceholderRSSURL];

            __weak __typeof(self) weakSelf = self;
            cell.textReturnBlock = ^(NSString *text) {
                __strong __typeof(weakSelf) strongSelf = weakSelf;
                if (strongSelf) {
                    strongSelf.urlText = text;
                }
            };

            return cell;
        }
        else {
            RDYTagsCell *cell = (RDYTagsCell *)[tableView dequeueReusableCellWithIdentifier:RDYNewFeedViewControllerTagsTableViewCellIdentifier];
            if (!cell) {
                cell = [[RDYTagsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RDYNewFeedViewControllerTagsTableViewCellIdentifier];
            }
            return cell;
        }
    }
    else if (1 == indexPath.section) {
        RDYButtonCell *cell = (RDYButtonCell *)[tableView dequeueReusableCellWithIdentifier:RDYNewFeedViewControllerConfirmTableViewCellIdentifier];
        if (!cell) {
            cell = [[RDYButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RDYNewFeedViewControllerConfirmTableViewCellIdentifier];
        }

        __weak __typeof(self) weakSelf = self;
        cell.clickBlock = ^{
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            if (strongSelf) {
                [strongSelf confirmButtonClicked];
            }
        };

        return cell;
    }
    else {
        return nil;
    }
}

@end


text:
using System;

namespace SeudoBuild.Pipeline.Modules.SteamDistribute
{
    public class SteamDistributeModule : IDistributeModule
    {
        public string Name { get; } = "Steam";

        public Type StepType { get; } = typeof(SteamDistributeStep);

        public Type StepConfigType { get; } = typeof(SteamDistributeConfig);

        public string StepConfigName { get; } = "Steam Upload";
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>ArduinoRCLib: rc::InputModifier Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ArduinoRCLib

Arduino RC Lib

Main Page

Classes

Files

Examples

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Public Member Functions |
Protected Member Functions |
Protected Attributes |
List of all members

rc::InputModifier Class Reference

Base class for classes having configurable input on which to perform operations.
 More...

#include <InputModifier.h>

Inheritance diagram for rc::InputModifier:

  <map id="rc::InputModifier_map" name="rc::InputModifier_map">
<area href="classrc_1_1_dual_rates.html" title="Class to encapsulate dual rates functionality. " alt="rc::DualRates" shape="rect" coords="0,56,118,80"/>
<area href="classrc_1_1_expo.html" title="Class to encapsulate Expo functionality. " alt="rc::Expo" shape="rect" coords="128,56,246,80"/>
<area href="classrc_1_1_input_to_input_mix.html" title="Class which mixes one input to another. " alt="rc::InputToInputMix" shape="rect" coords="256,56,374,80"/>
<area href="classrc_1_1_throttle_hold.html" title="Class to encapsulate Throttle Hold functionality. " alt="rc::ThrottleHold" shape="rect" coords="384,56,502,80"/>
</map>

Public Member Functions

void 	setIndex (Input p_index)

 	Sets the input index.  More...

Input 	getIndex () const

 	Gets the input index.  More...

Protected Member Functions

 	InputModifier (Input p_index=Input_None)

 	Constructs a InputModifier object.  More...

Protected Attributes

Input 	m_index

 	Index of input to perform modification on.

Detailed Description

Base class for classes having configurable input on which to perform operations.

If a class can modify input, derive from this.

Author

Daniel van den Ouden

Date

Nov-2012

Copyright

Public Domain.

Constructor & Destructor Documentation

          rc::InputModifier::InputModifier
          (
          Input
          p_index = Input_None	)

protected

Constructs a InputModifier object.

Parameters

p_index	Index to use as source input.

Member Function Documentation

          Input rc::InputModifier::getIndex
          (
          	)
           const

Gets the input index.

Returns

Index currently used as source input.

          void rc::InputModifier::setIndex
          (
          Input
          p_index	)

Sets the input index.

Parameters

p_index	Index to use as source input.

The documentation for this class was generated from the following files:

InputModifier.h

InputModifier.cpp

rc

InputModifier

Generated on Sun May 24 2015 18:44:48 for ArduinoRCLib by

     1.8.9.1


text:
from virtool.caches.utils import join_cache_path

def test_join_cache_path(tmp_path, config):
    cache_id = "bar"

    assert join_cache_path(config, cache_id) == tmp_path / "caches" / "bar"


text:
package ru.kbadashvili.part3;

 /**
 * Максимум из двух чисел.
 * @author Konstantin Badashvili (bakongi@protonmail.com)
 * @version $Id$
 * @since 2017
 */
 public class Max {

 	/**
 	* @param first - first.
 	* @param second - second.
 	* @return result - возвращает максимально из двух чисел.
 	*/
 	public int max(int first, int second) {
 		int result;
 		result = first >= second ? first : second;
 		return result;
 	}

 	/**
 	* @param first - first.
 	* @param second - second.
 	* @param third - third.
 	* @return result - возвращает максимально из двух чисел.
 	*/
 	public int max(int first, int second, int third) {
 		return this.max(this.max(first, second), third);
 	}
 }


text:
import type {FilterConfig, Theme} from '../definitions';
import type {RGBA, HSLA} from '../utils/color';
import {parseToHSLWithCache, rgbToHSL, hslToRGB, rgbToString, rgbToHexString} from '../utils/color';
import {scale} from '../utils/math';
import {applyColorMatrix, createFilterMatrix} from './utils/matrix';

interface ColorFunction {
    (hsl: HSLA): HSLA;
}

function getBgPole(theme: Theme) {
    const isDarkScheme = theme.mode === 1;
    const prop: keyof Theme = isDarkScheme ? 'darkSchemeBackgroundColor' : 'lightSchemeBackgroundColor';
    return theme[prop];
}

function getFgPole(theme: Theme) {
    const isDarkScheme = theme.mode === 1;
    const prop: keyof Theme = isDarkScheme ? 'darkSchemeTextColor' : 'lightSchemeTextColor';
    return theme[prop];
}

const colorModificationCache = new Map<ColorFunction, Map<string, string>>();

export function clearColorModificationCache() {
    colorModificationCache.clear();
}

const rgbCacheKeys: Array<keyof RGBA> = ['r', 'g', 'b', 'a'];
const themeCacheKeys: Array<keyof Theme> = ['mode', 'brightness', 'contrast', 'grayscale', 'sepia', 'darkSchemeBackgroundColor', 'darkSchemeTextColor', 'lightSchemeBackgroundColor', 'lightSchemeTextColor'];

function getCacheId(rgb: RGBA, theme: Theme) {
    let resultId = '';
    rgbCacheKeys.forEach((key) => {
        resultId += `${rgb[key]};`;
    });
    themeCacheKeys.forEach((key) => {
        resultId += `${theme[key]};`;
    });
    return resultId;
}

function modifyColorWithCache(rgb: RGBA, theme: Theme, modifyHSL: (hsl: HSLA, pole?: HSLA, anotherPole?: HSLA) => HSLA, poleColor?: string, anotherPoleColor?: string) {
    let fnCache: Map<string, string>;
    if (colorModificationCache.has(modifyHSL)) {
        fnCache = colorModificationCache.get(modifyHSL);
    } else {
        fnCache = new Map();
        colorModificationCache.set(modifyHSL, fnCache);
    }
    const id = getCacheId(rgb, theme);
    if (fnCache.has(id)) {
        return fnCache.get(id);
    }

    const hsl = rgbToHSL(rgb);
    const pole = poleColor == null ? null : parseToHSLWithCache(poleColor);
    const anotherPole = anotherPoleColor == null ? null : parseToHSLWithCache(anotherPoleColor);
    const modified = modifyHSL(hsl, pole, anotherPole);
    const {r, g, b, a} = hslToRGB(modified);
    const matrix = createFilterMatrix(theme);
    const [rf, gf, bf] = applyColorMatrix([r, g, b], matrix);

    const color = (a === 1 ?
        rgbToHexString({r: rf, g: gf, b: bf}) :
        rgbToString({r: rf, g: gf, b: bf, a}));

    fnCache.set(id, color);
    return color;
}

function noopHSL(hsl: HSLA) {
    return hsl;
}

export function modifyColor(rgb: RGBA, theme: FilterConfig) {
    return modifyColorWithCache(rgb, theme, noopHSL);
}

function modifyLightSchemeColor(rgb: RGBA, theme: Theme) {
    const poleBg = getBgPole(theme);
    const poleFg = getFgPole(theme);
    return modifyColorWithCache(rgb, theme, modifyLightModeHSL, poleFg, poleBg);
}

function modifyLightModeHSL({h, s, l, a}: HSLA, poleFg: HSLA, poleBg: HSLA) {
    const isDark = l < 0.5;
    let isNeutral: boolean;
    if (isDark) {
        isNeutral = l < 0.2 || s < 0.12;
    } else {
        const isBlue = h > 200 && h < 280;
        isNeutral = s < 0.24 || (l > 0.8 && isBlue);
    }

    let hx = h;
    let sx = l;
    if (isNeutral) {
        if (isDark) {
            hx = poleFg.h;
            sx = poleFg.s;
        } else {
            hx = poleBg.h;
            sx = poleBg.s;
        }
    }

    const lx = scale(l, 0, 1, poleFg.l, poleBg.l);

    return {h: hx, s: sx, l: lx, a};
}

const MAX_BG_LIGHTNESS = 0.4;

function modifyBgHSL({h, s, l, a}: HSLA, pole: HSLA) {
    const isDark = l < 0.5;
    const isBlue = h > 200 && h < 280;
    const isNeutral = s < 0.12 || (l > 0.8 && isBlue);
    if (isDark) {
        const lx = scale(l, 0, 0.5, 0, MAX_BG_LIGHTNESS);
        if (isNeutral) {
            const hx = pole.h;
            const sx = pole.s;
            return {h: hx, s: sx, l: lx, a};
        }
        return {h, s, l: lx, a};
    }

    let lx = scale(l, 0.5, 1, MAX_BG_LIGHTNESS, pole.l);

    if (isNeutral) {
        const hx = pole.h;
        const sx = pole.s;
        return {h: hx, s: sx, l: lx, a};
    }

    let hx = h;
    const isYellow = h > 60 && h < 180;
    if (isYellow) {
        const isCloserToGreen = h > 120;
        if (isCloserToGreen) {
            hx = scale(h, 120, 180, 135, 180);
        } else {
            hx = scale(h, 60, 120, 60, 105);
        }
    }

    // Lower the lightness, if the resulting
    // hue is in lower yellow spectrum.
    if (hx > 40 && hx < 80) {
        lx *= 0.75;
    }

    return {h: hx, s, l: lx, a};
}

export function modifyBackgroundColor(rgb: RGBA, theme: Theme) {
    if (theme.mode === 0) {
        return modifyLightSchemeColor(rgb, theme);
    }
    const pole = getBgPole(theme);
    return modifyColorWithCache(rgb, {...theme, mode: 0}, modifyBgHSL, pole);
}

const MIN_FG_LIGHTNESS = 0.55;

function modifyBlueFgHue(hue: number) {
    return scale(hue, 205, 245, 205, 220);
}

function modifyFgHSL({h, s, l, a}: HSLA, pole: HSLA) {
    const isLight = l > 0.5;
    const isNeutral = l < 0.2 || s < 0.24;
    const isBlue = !isNeutral && h > 205 && h < 245;
    if (isLight) {
        const lx = scale(l, 0.5, 1, MIN_FG_LIGHTNESS, pole.l);
        if (isNeutral) {
            const hx = pole.h;
            const sx = pole.s;
            return {h: hx, s: sx, l: lx, a};
        }
        let hx = h;
        if (isBlue) {
            hx = modifyBlueFgHue(h);
        }
        return {h: hx, s, l: lx, a};
    }

    if (isNeutral) {
        const hx = pole.h;
        const sx = pole.s;
        const lx = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
        return {h: hx, s: sx, l: lx, a};
    }

    let hx = h;
    let lx: number;
    if (isBlue) {
        hx = modifyBlueFgHue(h);
        lx = scale(l, 0, 0.5, pole.l, Math.min(1, MIN_FG_LIGHTNESS + 0.05));
    } else {
        lx = scale(l, 0, 0.5, pole.l, MIN_FG_LIGHTNESS);
    }

    return {h: hx, s, l: lx, a};
}

export function modifyForegroundColor(rgb: RGBA, theme: Theme) {
    if (theme.mode === 0) {
        return modifyLightSchemeColor(rgb, theme);
    }
    const pole = getFgPole(theme);
    return modifyColorWithCache(rgb, {...theme, mode: 0}, modifyFgHSL, pole);
}

function modifyBorderHSL({h, s, l, a}: HSLA, poleFg: HSLA, poleBg: HSLA) {
    const isDark = l < 0.5;
    const isNeutral = l < 0.2 || s < 0.24;

    let hx = h;
    let sx = s;

    if (isNeutral) {
        if (isDark) {
            hx = poleFg.h;
            sx = poleFg.s;
        } else {
            hx = poleBg.h;
            sx = poleBg.s;
        }
    }

    const lx = scale(l, 0, 1, 0.5, 0.2);

    return {h: hx, s: sx, l: lx, a};
}

export function modifyBorderColor(rgb: RGBA, theme: Theme) {
    if (theme.mode === 0) {
        return modifyLightSchemeColor(rgb, theme);
    }
    const poleFg = getFgPole(theme);
    const poleBg = getBgPole(theme);
    return modifyColorWithCache(rgb, {...theme, mode: 0}, modifyBorderHSL, poleFg, poleBg);
}

export function modifyShadowColor(rgb: RGBA, filter: FilterConfig) {
    return modifyBackgroundColor(rgb, filter);
}

export function modifyGradientColor(rgb: RGBA, filter: FilterConfig) {
    return modifyBackgroundColor(rgb, filter);
}


text:
#include <ovsdb_object.h>
#include <oper/agent_sandesh.h>
#include <ovsdb_types.h>
#include <ovsdb_client.h>
#include <ovsdb_client_tcp.h>
#include <ovs_tor_agent/tor_agent_init.h>
#include <ovs_tor_agent/tor_agent_param.h>

using OVSDB::OvsdbClient;

OvsdbClient::OvsdbClient(OvsPeerManager *manager, int keepalive_interval) :
    peer_manager_(manager), ksync_obj_manager_(KSyncObjectManager::Init()),
    keepalive_interval_(keepalive_interval) {
}

OvsdbClient::~OvsdbClient() {
}

KSyncObjectManager *OvsdbClient::ksync_obj_manager() {
    return ksync_obj_manager_;
}

int OvsdbClient::keepalive_interval() const {
    return keepalive_interval_;
}

void OvsdbClient::Init() {
}

OvsdbClient *OvsdbClient::Allocate(Agent *agent, TorAgentParam *params,
        OvsPeerManager *manager) {
    KSyncObjectManager::Init();
    return (new OvsdbClientTcp(agent, params, manager));
}

/////////////////////////////////////////////////////////////////////////////
// Sandesh routines
/////////////////////////////////////////////////////////////////////////////
void OvsdbClientReq::HandleRequest() const {
    OvsdbClientResp *resp = new OvsdbClientResp();
    SandeshOvsdbClient client_data;
    TorAgentInit *init =
        static_cast<TorAgentInit *>(Agent::GetInstance()->agent_init());
    OvsdbClient *client = init->ovsdb_client();
    client_data.set_protocol(client->protocol());
    client_data.set_server(client->server());
    client_data.set_port(client->port());
    client_data.set_tor_service_node(client->tsn_ip().to_string());
    client->AddSessionInfo(client_data);
    resp->set_client(client_data);
    resp->set_context(context());
    resp->set_more(false);
    resp->Response();
}


text:
package com.tiarebalbi.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.tiarebalbi.entity.Usuario;

/**
 * @author Tiarê Balbi Bonamini
 */
@Component
public class UsuarioValidator implements Validator {

	@Override
	public boolean supports(Class<?> arg0) {
		return Usuario.class.equals(arg0);
	}

	@Override
	public void validate(Object objeto, Errors erros) {
		ValidationUtils.rejectIfEmpty(erros, "nome", "validacao.usuario.nome.empty");
		ValidationUtils.rejectIfEmpty(erros, "email", "validacao.usuario.email.empty");
	}

}


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

namespace P04.Recharge
{
    public interface IRechargeable
    {
        void Recharge();
    }
}


text:
<?php

namespace R_kvstore\Request\V20150101;

class DescribeBackupsRequest extends \RpcAcsRequest
{
	function  __construct()
	{
		parent::__construct("R-kvstore", "2015-01-01", "DescribeBackups", "redisa", "openAPI");
		$this->setMethod("POST");
	}

	private  $resourceOwnerId;

	private  $resourceOwnerAccount;

	private  $ownerAccount;

	private  $backupId;

	private  $endTime;

	private  $startTime;

	private  $ownerId;

	private  $pageNumber;

	private  $instanceId;

	private  $securityToken;

	private  $pageSize;

	public function getResourceOwnerId() {
		return $this->resourceOwnerId;
	}

	public function setResourceOwnerId($resourceOwnerId) {
		$this->resourceOwnerId = $resourceOwnerId;
		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
	}

	public function getResourceOwnerAccount() {
		return $this->resourceOwnerAccount;
	}

	public function setResourceOwnerAccount($resourceOwnerAccount) {
		$this->resourceOwnerAccount = $resourceOwnerAccount;
		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
	}

	public function getOwnerAccount() {
		return $this->ownerAccount;
	}

	public function setOwnerAccount($ownerAccount) {
		$this->ownerAccount = $ownerAccount;
		$this->queryParameters["OwnerAccount"]=$ownerAccount;
	}

	public function getBackupId() {
		return $this->backupId;
	}

	public function setBackupId($backupId) {
		$this->backupId = $backupId;
		$this->queryParameters["BackupId"]=$backupId;
	}

	public function getEndTime() {
		return $this->endTime;
	}

	public function setEndTime($endTime) {
		$this->endTime = $endTime;
		$this->queryParameters["EndTime"]=$endTime;
	}

	public function getStartTime() {
		return $this->startTime;
	}

	public function setStartTime($startTime) {
		$this->startTime = $startTime;
		$this->queryParameters["StartTime"]=$startTime;
	}

	public function getOwnerId() {
		return $this->ownerId;
	}

	public function setOwnerId($ownerId) {
		$this->ownerId = $ownerId;
		$this->queryParameters["OwnerId"]=$ownerId;
	}

	public function getPageNumber() {
		return $this->pageNumber;
	}

	public function setPageNumber($pageNumber) {
		$this->pageNumber = $pageNumber;
		$this->queryParameters["PageNumber"]=$pageNumber;
	}

	public function getInstanceId() {
		return $this->instanceId;
	}

	public function setInstanceId($instanceId) {
		$this->instanceId = $instanceId;
		$this->queryParameters["InstanceId"]=$instanceId;
	}

	public function getSecurityToken() {
		return $this->securityToken;
	}

	public function setSecurityToken($securityToken) {
		$this->securityToken = $securityToken;
		$this->queryParameters["SecurityToken"]=$securityToken;
	}

	public function getPageSize() {
		return $this->pageSize;
	}

	public function setPageSize($pageSize) {
		$this->pageSize = $pageSize;
		$this->queryParameters["PageSize"]=$pageSize;
	}

}


text:
import barcode = require('barcode');
import path = require('path');

var code39 = barcode('code39', {
    data: "it works",
    width: 400,
    height: 100,
});

code39.getStream(function (err, readStream) {
    if (err) throw err;

    // 'readStream' is an instance of ReadableStream
});

var outfile = path.join(__dirname, 'imgs', 'mycode.png');
code39.saveImage(outfile, function (err) {
    if (err) throw err;

    console.log('File has been written!');
});


text:
* Write mocks for the rest of `ICarsRepository` interface (sorting)
* Write missing unit test so that the controller functionality is fully tested


text:
package volume

import (
	"fmt"
	"reflect"

	"k8s.io/kubernetes/pkg/api/v1"
	metav1 "k8s.io/kubernetes/pkg/apis/meta/v1"
	clientset "k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
	"k8s.io/kubernetes/pkg/fields"
	"k8s.io/kubernetes/pkg/watch"

	"hash/fnv"
	"math/rand"
	"strconv"
	"strings"

	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/resource"
	"k8s.io/kubernetes/pkg/util/sets"
)

type RecycleEventRecorder func(eventtype, message string)

// RecycleVolumeByWatchingPodUntilCompletion is intended for use with volume
// Recyclers. This function will save the given Pod to the API and watch it
// until it completes, fails, or the pod's ActiveDeadlineSeconds is exceeded,
// whichever comes first. An attempt to delete a recycler pod is always
// attempted before returning.
//
// In case there is a pod with the same namespace+name already running, this
// function assumes it's an older instance of the recycler pod and watches
// this old pod instead of starting a new one.
//
//  pod - the pod designed by a volume plugin to recycle the volume. pod.Name
//        will be overwritten with unique name based on PV.Name.
//	client - kube client for API operations.
func RecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, kubeClient clientset.Interface, recorder RecycleEventRecorder) error {
	return internalRecycleVolumeByWatchingPodUntilCompletion(pvName, pod, newRecyclerClient(kubeClient, recorder))
}

// same as above func comments, except 'recyclerClient' is a narrower pod API
// interface to ease testing
func internalRecycleVolumeByWatchingPodUntilCompletion(pvName string, pod *v1.Pod, recyclerClient recyclerClient) error {
	glog.V(5).Infof("creating recycler pod for volume %s\n", pod.Name)

	// Generate unique name for the recycler pod - we need to get "already
	// exists" error when a previous controller has already started recycling
	// the volume. Here we assume that pv.Name is already unique.
	pod.Name = "recycler-for-" + pvName
	pod.GenerateName = ""

	stopChannel := make(chan struct{})
	defer close(stopChannel)
	podCh, err := recyclerClient.WatchPod(pod.Name, pod.Namespace, stopChannel)
	if err != nil {
		glog.V(4).Infof("cannot start watcher for pod %s/%s: %v", pod.Namespace, pod.Name, err)
		return err
	}

	// Start the pod
	_, err = recyclerClient.CreatePod(pod)
	if err != nil {
		if errors.IsAlreadyExists(err) {
			glog.V(5).Infof("old recycler pod %q found for volume", pod.Name)
		} else {
			return fmt.Errorf("unexpected error creating recycler pod:  %+v\n", err)
		}
	}
	defer func(pod *v1.Pod) {
		glog.V(2).Infof("deleting recycler pod %s/%s", pod.Namespace, pod.Name)
		if err := recyclerClient.DeletePod(pod.Name, pod.Namespace); err != nil {
			glog.Errorf("failed to delete recycler pod %s/%s: %v", pod.Namespace, pod.Name, err)
		}
	}(pod)

	// Now only the old pod or the new pod run. Watch it until it finishes
	// and send all events on the pod to the PV
	for {
		event := <-podCh
		switch event.Object.(type) {
		case *v1.Pod:
			// POD changed
			pod := event.Object.(*v1.Pod)
			glog.V(4).Infof("recycler pod update received: %s %s/%s %s", event.Type, pod.Namespace, pod.Name, pod.Status.Phase)
			switch event.Type {
			case watch.Added, watch.Modified:
				if pod.Status.Phase == v1.PodSucceeded {
					// Recycle succeeded.
					return nil
				}
				if pod.Status.Phase == v1.PodFailed {
					if pod.Status.Message != "" {
						return fmt.Errorf(pod.Status.Message)
					} else {
						return fmt.Errorf("pod failed, pod.Status.Message unknown.")
					}
				}

			case watch.Deleted:
				return fmt.Errorf("recycler pod was deleted")

			case watch.Error:
				return fmt.Errorf("recycler pod watcher failed")
			}

		case *v1.Event:
			// Event received
			podEvent := event.Object.(*v1.Event)
			glog.V(4).Infof("recycler event received: %s %s/%s %s/%s %s", event.Type, podEvent.Namespace, podEvent.Name, podEvent.InvolvedObject.Namespace, podEvent.InvolvedObject.Name, podEvent.Message)
			if event.Type == watch.Added {
				recyclerClient.Event(podEvent.Type, podEvent.Message)
			}
		}
	}
}

// recyclerClient abstracts access to a Pod by providing a narrower interface.
// This makes it easier to mock a client for testing.
type recyclerClient interface {
	CreatePod(pod *v1.Pod) (*v1.Pod, error)
	GetPod(name, namespace string) (*v1.Pod, error)
	DeletePod(name, namespace string) error
	// WatchPod returns a ListWatch for watching a pod.  The stopChannel is used
	// to close the reflector backing the watch.  The caller is responsible for
	// derring a close on the channel to stop the reflector.
	WatchPod(name, namespace string, stopChannel chan struct{}) (<-chan watch.Event, error)
	// Event sends an event to the volume that is being recycled.
	Event(eventtype, message string)
}

func newRecyclerClient(client clientset.Interface, recorder RecycleEventRecorder) recyclerClient {
	return &realRecyclerClient{
		client,
		recorder,
	}
}

type realRecyclerClient struct {
	client   clientset.Interface
	recorder RecycleEventRecorder
}

func (c *realRecyclerClient) CreatePod(pod *v1.Pod) (*v1.Pod, error) {
	return c.client.Core().Pods(pod.Namespace).Create(pod)
}

func (c *realRecyclerClient) GetPod(name, namespace string) (*v1.Pod, error) {
	return c.client.Core().Pods(namespace).Get(name, metav1.GetOptions{})
}

func (c *realRecyclerClient) DeletePod(name, namespace string) error {
	return c.client.Core().Pods(namespace).Delete(name, nil)
}

func (c *realRecyclerClient) Event(eventtype, message string) {
	c.recorder(eventtype, message)
}

func (c *realRecyclerClient) WatchPod(name, namespace string, stopChannel chan struct{}) (<-chan watch.Event, error) {
	podSelector, _ := fields.ParseSelector("metadata.name=" + name)
	options := v1.ListOptions{
		FieldSelector: podSelector.String(),
		Watch:         true,
	}

	podWatch, err := c.client.Core().Pods(namespace).Watch(options)
	if err != nil {
		return nil, err
	}

	eventSelector, _ := fields.ParseSelector("involvedObject.name=" + name)
	eventWatch, err := c.client.Core().Events(namespace).Watch(v1.ListOptions{
		FieldSelector: eventSelector.String(),
		Watch:         true,
	})
	if err != nil {
		podWatch.Stop()
		return nil, err
	}

	eventCh := make(chan watch.Event, 0)

	go func() {
		defer eventWatch.Stop()
		defer podWatch.Stop()
		defer close(eventCh)

		for {
			select {
			case _ = <-stopChannel:
				return

			case podEvent, ok := <-podWatch.ResultChan():
				if !ok {
					return
				}
				eventCh <- podEvent

			case eventEvent, ok := <-eventWatch.ResultChan():
				if !ok {
					return
				}
				eventCh <- eventEvent
			}
		}
	}()

	return eventCh, nil
}

// CalculateTimeoutForVolume calculates time for a Recycler pod to complete a
// recycle operation. The calculation and return value is either the
// minimumTimeout or the timeoutIncrement per Gi of storage size, whichever is
// greater.
func CalculateTimeoutForVolume(minimumTimeout, timeoutIncrement int, pv *v1.PersistentVolume) int64 {
	giQty := resource.MustParse("1Gi")
	pvQty := pv.Spec.Capacity[v1.ResourceStorage]
	giSize := giQty.Value()
	pvSize := pvQty.Value()
	timeout := (pvSize / giSize) * int64(timeoutIncrement)
	if timeout < int64(minimumTimeout) {
		return int64(minimumTimeout)
	} else {
		return timeout
	}
}

// RoundUpSize calculates how many allocation units are needed to accommodate
// a volume of given size. E.g. when user wants 1500MiB volume, while AWS EBS
// allocates volumes in gibibyte-sized chunks,
// RoundUpSize(1500 * 1024*1024, 1024*1024*1024) returns '2'
// (2 GiB is the smallest allocatable volume that can hold 1500MiB)
func RoundUpSize(volumeSizeBytes int64, allocationUnitBytes int64) int64 {
	return (volumeSizeBytes + allocationUnitBytes - 1) / allocationUnitBytes
}

// GenerateVolumeName returns a PV name with clusterName prefix. The function
// should be used to generate a name of GCE PD or Cinder volume. It basically
// adds "<clusterName>-dynamic-" before the PV name, making sure the resulting
// string fits given length and cuts "dynamic" if not.
func GenerateVolumeName(clusterName, pvName string, maxLength int) string {
	prefix := clusterName + "-dynamic"
	pvLen := len(pvName)

	// cut the "<clusterName>-dynamic" to fit full pvName into maxLength
	// +1 for the '-' dash
	if pvLen+1+len(prefix) > maxLength {
		prefix = prefix[:maxLength-pvLen-1]
	}
	return prefix + "-" + pvName
}

// Check if the path from the mounter is empty.
func GetPath(mounter Mounter) (string, error) {
	path := mounter.GetPath()
	if path == "" {
		return "", fmt.Errorf("Path is empty %s", reflect.TypeOf(mounter).String())
	}
	return path, nil
}

// ChooseZone implements our heuristics for choosing a zone for volume creation based on the volume name
// Volumes are generally round-robin-ed across all active zones, using the hash of the PVC Name.
// However, if the PVCName ends with `-<integer>`, we will hash the prefix, and then add the integer to the hash.
// This means that a StatefulSet's volumes (`claimname-statefulsetname-id`) will spread across available zones,
// assuming the id values are consecutive.
func ChooseZoneForVolume(zones sets.String, pvcName string) string {
	// We create the volume in a zone determined by the name
	// Eventually the scheduler will coordinate placement into an available zone
	var hash uint32
	var index uint32

	if pvcName == "" {
		// We should always be called with a name; this shouldn't happen
		glog.Warningf("No name defined during volume create; choosing random zone")

		hash = rand.Uint32()
	} else {
		hashString := pvcName

		// Heuristic to make sure that volumes in a StatefulSet are spread across zones
		// StatefulSet PVCs are (currently) named ClaimName-StatefulSetName-Id,
		// where Id is an integer index
		lastDash := strings.LastIndexByte(pvcName, '-')
		if lastDash != -1 {
			petIDString := pvcName[lastDash+1:]
			petID, err := strconv.ParseUint(petIDString, 10, 32)
			if err == nil {
				// Offset by the pet id, so we round-robin across zones
				index = uint32(petID)
				// We still hash the volume name, but only the base
				hashString = pvcName[:lastDash]
				glog.V(2).Infof("Detected StatefulSet-style volume name %q; index=%d", pvcName, index)
			}
		}

		// We hash the (base) volume name, so we don't bias towards the first N zones
		h := fnv.New32()
		h.Write([]byte(hashString))
		hash = h.Sum32()
	}

	// Zones.List returns zones in a consistent order (sorted)
	// We do have a potential failure case where volumes will not be properly spread,
	// if the set of zones changes during StatefulSet volume creation.  However, this is
	// probably relatively unlikely because we expect the set of zones to be essentially
	// static for clusters.
	// Hopefully we can address this problem if/when we do full scheduler integration of
	// PVC placement (which could also e.g. avoid putting volumes in overloaded or
	// unhealthy zones)
	zoneSlice := zones.List()
	zone := zoneSlice[(hash+index)%uint32(len(zoneSlice))]

	glog.V(2).Infof("Creating volume for PVC %q; chose zone=%q from zones=%q", pvcName, zone, zoneSlice)
	return zone
}


text:
package org.hibernate.annotations;

import java.lang.annotation.Retention;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Support for {@literal ROWID} mapping feature of Hibernate.
 *
 * @author Steve Ebersole
 */
@java.lang.annotation.Target( { TYPE })
@Retention(RUNTIME)
public @interface RowId {
	/**
	 * Names the {@literal ROWID} identifier
	 *
	 * @return The {@literal ROWID} identifier
	 */
	String value();
}


text:
require_relative 'active_record_extension'

module Backgrounded
  class Railtie < Rails::Railtie
    initializer 'backgrounded.configure' do
      ActiveSupport.on_load(:active_record) do
        include Backgrounded::ActiveRecordExtension
      end
    end
  end
end


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="0; url=/docs/introduction/openziti-is-software">
    <link rel="canonical" href="/docs/introduction/openziti-is-software" />
  </head>
  <script>
    window.location.href = '/docs/introduction/openziti-is-software' + window.location.search + window.location.hash;
  </script>
</html>


text:
namespace boost {
namespace compute {

BOOST_COMPUTE_DECLARE_BUILTIN_FUNCTION(clamp, T (T, T, T), class T)
BOOST_COMPUTE_DECLARE_BUILTIN_FUNCTION(degrees, T (T), class T)
BOOST_COMPUTE_DECLARE_BUILTIN_FUNCTION(radians, T (T), class T)
BOOST_COMPUTE_DECLARE_BUILTIN_FUNCTION(sign, T (T), class T)
BOOST_COMPUTE_DECLARE_BUILTIN_FUNCTION(smoothstep, T (T, T, T), class T)
BOOST_COMPUTE_DECLARE_BUILTIN_FUNCTION(step, T (T, T), class T)

} // end compute namespace
} // end boost namespace

#endif // BOOST_COMPUTE_FUNCTIONAL_COMMON_HPP


text:
require 'stringio'

SILVERLIGHT = false unless defined?(SILVERLIGHT)

if not SILVERLIGHT
  $: << File.expand_path(File.dirname(__FILE__) + '/..')
  $: << File.expand_path(File.dirname(__FILE__) + '/../app')
end

require 'tutorial'
require 'console_tutorial'

if not SILVERLIGHT
  require 'rubygems'
  require 'minitest/spec'
  require 'fileutils'
  require 'html_tutorial'

  MiniTest::Unit.autorun # tests will run using at_exit

  TUTORIAL_ROOT = File.expand_path("..", File.dirname(File.expand_path(__FILE__, FileUtils.pwd)))
end

class MiniTest::Unit::TestCase
  def self.test_order
    :not_random
  end
end

def get_standard_tutorial(file_name)
  path = "app/Tutorials/#{file_name}"
  path = File.expand_path(path, TUTORIAL_ROOT) if not SILVERLIGHT
  Tutorial.get_tutorial path
end

describe "ReplContext" do
  before(:each) do
    @context = Tutorial::ReplContext.new
  end

  it "works with single-line input" do
    assert_equal @context.interact("2+2").result, 4
  end

  it "works with multi-line code" do
    code = ["if true", "101", "else", "102", "end"].join("\n")
    assert_equal @context.interact(code).result, 101
  end

  it "works with multi-line input" do
    result = nil
    ["if true", "101", "else", "102", "end"].each {|i| result = @context.interact i }
    assert_equal result.result, 101
  end

  it "can be reset" do
    ["if true", "101", "else"].each {|i| @context.interact i }
    @context.reset_input
    assert_equal @context.interact("2+2").result, 4
  end
end

describe "ConsoleTutorial" do
  before(:each) do
    @in = StringIO.new
    @out = StringIO.new
    tutorial = get_standard_tutorial('tryruby_tutorial.rb')
    @app = ConsoleTutorial.new tutorial, @in, @out
  end

  it "should early out" do
    @in.string = ["0"].join("\n")
    @app.run
    assert_match @out.string, /Bye!/
  end

  it 'should chose a section' do
    @in.string = ["1", "0", "0"].join("\n")
    @app.run
    assert_match @out.string, /Bye!/
  end
end

# Helper module to programatically create a new spec methods for each task in each chapter
module TutorialTests

  def self.format_interaction_result code, result
    "code = #{code.inspect} #{result}"
  end

  def self.create_tests testcase, tutorial_file
    tutorial = get_standard_tutorial tutorial_file
    context = Tutorial::ReplContext.new
    tutorial.sections.each_index do |s|
      section = tutorial.sections[s]
      section.chapters.each_index do |c|
        chapter = section.chapters[c]
        test_name = "#{section.name} - #{chapter.name}"

        testcase.it(test_name) { TutorialTests.run_test self, context, chapter }
      end
    end
  end

  def self.assert_task_success(spec, task, code, result, success=true)
    res = TutorialTests.format_interaction_result(code, result)
    if success
      spec.assert(task.success?(result, true), res)
    else
      spec.assert(!task.success?(result), res)
    end
  end

  def self.run_test spec, context, chapter
    chapter.tasks.each do |task|
      if not task.should_run? context.bind
        return
      end
      task.setup.call(context.bind) if task.setup
      task.test_hook.call(:before, spec, context.bind) if task.test_hook
      result = context.interact "" # Ensure that the user can try unrelated code snippets without moving to the next task
      if task.code.respond_to? :to_ary
        task.code.each do |code|
          assert_task_success spec, task, "before : #{code}", result, false
          result = context.interact code
        end
        assert_task_success spec, task, task.code.last, result
      else
        assert_task_success spec, task, "before : #{task.code_string}", result, false
        result = context.interact task.code_string
        assert_task_success spec, task, task.code_string, result
      end
      task.test_hook.call(:after, spec, context.bind) if task.test_hook
    end
  end
end

describe "IronRubyTutorial" do
  TutorialTests.create_tests self, 'ironruby_tutorial.rb' if defined? RUBY_ENGINE
end

describe "HostingTutorial" do
  TutorialTests.create_tests self, 'hosting_tutorial.rb' if defined? RUBY_ENGINE
end

describe "TryRubyTutorial" do
  TutorialTests.create_tests self, 'tryruby_tutorial.rb'
end

if not SILVERLIGHT
  describe "HtmlGeneratorTests" do
    it "basically works" do
      tutorial = get_standard_tutorial('tryruby_tutorial.rb')
      html_tutorial = HtmlTutorial.new tutorial
      html = html_tutorial.generate_html
      assert_match %r{
Table of Contents
}, html
    end
  end
end


text:
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.0//EN"
        "http://google-web-toolkit.googlecode.com/svn/releases/2.0/distro-source/core/src/gwt-module.dtd">

<module rename-to="JsInteropCore">

	<source path="core" />
	<source path="webcomponents" />

</module>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KaoriStudio.Core.Collections
{
	/// <summary>
	/// Non-generic wrapper for a System.Collections.Generic.IComparer(T)
	/// </summary>
	/// <typeparam name="T">The value type</typeparam>
	public struct LegacyComparer<T> : IComparer
	{
		/// <summary>
		/// The underlying comparer
		/// </summary>
		public IComparer<T> Comparer { get; set; }

		/// <summary>
		/// Creates a new LegacyComparer
		/// </summary>
		/// <param name="Comparer">The underlying comparer</param>
		public LegacyComparer(IComparer<T> Comparer)
		{
			this.Comparer = Comparer;
		}

		/// <summary>
		/// Compares two values
		/// </summary>
		/// <param name="x">The left hand value</param>
		/// <param name="y">The right hand value</param>
		/// <returns>The compare sign</returns>
		public int Compare(object x, object y)
		{
			return Comparer.Compare((T)x, (T)y);
		}
	}

	/// <summary>
	/// LegacyComparer helper class
	/// </summary>
	public static class LegacyComparer
	{
		/// <summary>
		/// Creates a new LegacyComparer
		/// </summary>
		/// <typeparam name="T">The underlying type</typeparam>
		/// <param name="Comparer">The underlying comparer</param>
		/// <returns>The legacy comparer</returns>
		public static LegacyComparer<T> Create<T>(IComparer<T> Comparer)
		{
			return new LegacyComparer<T>(Comparer);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<application xmlns="http://ns.adobe.com/air/application/2.5">
	<id>Spaz.AIR</id>
    <publisherID>16CB261D461B1CA2027F7C39946115FA2DC8CD7F.1</publisherID>
	<name>Spaz</name>
	<versionNumber>0.9.23</versionNumber>
	<filename>Spaz</filename>
	<description>
		<text xml:lang="en">A microblogging client for Twitter, Identi.ca, and StatusNet</text>
	</description>
	<copyright>Copyright © Funkatron Productions</copyright>
	<initialWindow>
		<content>index.html</content>
		<title>Spaz</title>
		<systemChrome>none</systemChrome>
		<transparent>true</transparent>
		<visible>false</visible>
		<minimizable>true</minimizable>
		<maximizable>true</maximizable>
		<resizable>true</resizable>
		<width>350</width>
		<height>580</height>
		<minSize>310 200</minSize>
		<x>150</x>
		<y>150</y>
	</initialWindow>
	<programMenuFolder>Spaz</programMenuFolder>
	<icon>
		<image128x128>images/spaz-icon-alpha.png</image128x128>
		<image48x48>images/spaz-icon-alpha_48.png</image48x48>
		<image32x32>images/spaz-icon-alpha_32.png</image32x32>
		<image16x16>images/spaz-icon-alpha_16.png</image16x16>
	</icon>
	<customUpdateUI>false</customUpdateUI>
	<allowBrowserInvocation>false</allowBrowserInvocation>
	<supportedProfiles>desktop</supportedProfiles>
</application>


text:
namespace flex
{
	const char* TokenKindToString(TokenKind tokenKind)
	{
		return g_TokenStrings[(u32)tokenKind];
	}

	std::string Token::ToString() const
	{
		StringBuilder stringBuilder;

		switch (kind)
		{
		case TokenKind::IDENTIFIER:
			stringBuilder.Append("identifier '");
			stringBuilder.Append(value);
			stringBuilder.Append("'");
			break;
		case TokenKind::INT_LITERAL:
			stringBuilder.Append("int literal '");
			stringBuilder.Append(value);
			stringBuilder.Append("'");
			break;
		case TokenKind::FLOAT_LITERAL:
			stringBuilder.Append("float literal '");
			stringBuilder.Append(value);
			stringBuilder.Append("'");
			break;
		case TokenKind::TRUE:
			stringBuilder.Append("true");
			break;
		case TokenKind::FALSE:
			stringBuilder.Append("false");
			break;
		case TokenKind::STRING_LITERAL:
			stringBuilder.Append("string literal '");
			stringBuilder.Append(value);
			stringBuilder.Append("'");
			break;
		case TokenKind::CHAR_LITERAL:
			stringBuilder.Append("char literal '");
			stringBuilder.Append(value);
			stringBuilder.Append("'");
			break;
		default:
			stringBuilder.Append(TokenKindToString(kind));
			stringBuilder.Append(" '");
			stringBuilder.Append(value);
			stringBuilder.Append("'");
			break;
		}

		return stringBuilder.ToString();
	}
} // namespace flex


text:
classdef Create < handle
    properties
        serPort
        delay
        cur_mode           % current mode: passive, safe, full
    end

    methods
        function robot = Create(varargin)
        %[serPort] = RoombaInit(my_COM)
        % initializes serial port for use with Roomba
        % COMMport is the number of the comm port
        % ex. RoombaInit(1) sets port = 'COM1'
        % note that it sets baudrate to a default of 57600
        % can be changed (see SCI).
        % An optional time delay can be added after all commands
        % if your code crashes frequently.  15 ms is recommended by irobot
        % By; Joel Esposito, US Naval Academy, 2011

        % This code puts the robot in CONTROL(132) mode, which means does NOT stop
        % when cliff sensors or wheel drops are true; can also run while plugged into charger

            Contrl = 132;

            % Esposito 9/2008

            warning off

            opt.port = '';
            opt.delay = 0.015;

            opt = tb_optparse(opt, varargin);

            robot.delay = opt.delay;

            % clean up any previous instances of the port, can happen...
            for tty = instrfind('port', opt.port)
                if ~isempty(tty)
                    disp(['serPort ' tty.serPort.port 'is in use.   Closing it.'])
                    fclose(tty);
                    delete(tty);
                end
            end

            if opt.verbose
                disp('Establishing connection to Roomba...');
            end

            % defaults at 57600, can change
            robot.serPort = serial(opt.port,'BaudRate', 57600);
            set(robot.serPort,'Terminator','LF')
            set(robot.serPort,'InputBufferSize',100)
            set(robot.serPort, 'Timeout', 1)
            set(robot.serPort, 'ByteOrder','bigEndian');
            set(robot.serPort, 'Tag', 'Roomba')

            robot.serPort

            if opt.verbose
                disp('Opening connection to Roomba...');
            end

            pause(0.5);
            try
            fopen(robot.serPort);
            catch me
                disp('open failed');
                me.message
                return
            end

            %% Confirm two way connumication
            disp('Setting Roomba to Control Mode...');

            % Start! and see if its alive
            robot.mode('passive');

            robot.mode('full');

            % light LEDS
            robot.write([139 25 0 128]);

            % set song 1, default beep
            robot.write([140 1 1 48 20], 0.05);

            % sing it
            robot.write([141 1])

            disp('I am alive if my two outboard lights came on')

            confirmation = robot.read(4, 0.1);
        end

        function msg = read(robot, nbytes, delay)
            msg = fread(robot.serPort, nbytes);
            if nargin > 2
                pause(delay);
            end
        end

        function v = fread(robot, n, type, delay)
            v = fread(robot.serPort, n, type);

            if nargin > 3
                pause(delay);
            else
                pause(robot.delay)
            end
        end

        function write(robot, msg, delay)
            fwrite(robot.serPort, msg);
            fprintf('write: '); disp(msg);

            if nargin > 2
                pause(delay);
            else
                pause(robot.delay)
            end
        end

        function fwrite(robot, val, type, delay)
            fwrite(robot.serPort, val, type);
            disp(['fwrite:' val '(' type ')']);

            if nargin > 3
                pause(delay);
            else
                pause(robot.delay)
            end
        end

        function flush(robot)
            %Flush Buffer
            N = robot.serPort.BytesAvailable();
            while(N ~= 0)
                fread(robot.serPort,N);
                N = robot.serPort.BytesAvailable();
            end
        end

        function delete(robot)
            tty = instrfind('port', robot.serPort.port);
            fclose(tty);
            pause(1)
            delete(tty);
            pause(1)
        end

        function s = char(robot)
            s = sprintf('iCreate robot on port %s', robot.serPort.port);
        end
    end % methods
end % classdef