text:
package org.gradle.launcher.daemon.protocol;

import org.gradle.api.logging.LogLevel;
import org.gradle.internal.progress.OperationIdentifier;
import org.gradle.internal.serialize.*;
import org.gradle.logging.StyledTextOutput;
import org.gradle.logging.internal.*;

import java.util.List;

public class DaemonMessageSerializer {
    public static Serializer<Message> create() {
        BaseSerializerFactory factory = new BaseSerializerFactory();
        Serializer<LogLevel> logLevelSerializer = factory.getSerializerFor(LogLevel.class);
        Serializer<Throwable> throwableSerializer = factory.getSerializerFor(Throwable.class);
        DefaultSerializerRegistry registry = new DefaultSerializerRegistry();

        registry.register(BuildEvent.class, new BuildEventSerializer());
        registry.register(Failure.class, new FailureSerializer(throwableSerializer));

        // Input events
        registry.register(ForwardInput.class, new ForwardInputSerializer());
        registry.register(CloseInput.class, new CloseInputSerializer());

        // Output events
        registry.register(LogEvent.class, new LogEventSerializer(logLevelSerializer, throwableSerializer));
        registry.register(StyledTextOutputEvent.class, new StyledTextOutputEventSerializer(logLevelSerializer, new ListSerializer<StyledTextOutputEvent.Span>(new SpanSerializer(factory.getSerializerFor(StyledTextOutput.Style.class)))));
        registry.register(ProgressStartEvent.class, new ProgressStartEventSerializer());
        registry.register(ProgressCompleteEvent.class, new ProgressCompleteEventSerializer());
        registry.register(ProgressEvent.class, new ProgressEventSerializer());
        registry.register(LogLevelChangeEvent.class, new LogLevelChangeEventSerializer(logLevelSerializer));
        registry.register(OutputMessage.class, new OutputMessageSerializer(registry.build(OutputEvent.class)));

        // Default for everything else
        registry.useJavaSerialization(Message.class);

        return registry.build(Message.class);
    }

    private static class FailureSerializer implements Serializer<Failure> {
        private final Serializer<Throwable> throwableSerializer;

        public FailureSerializer(Serializer<Throwable> throwableSerializer) {
            this.throwableSerializer = throwableSerializer;
        }

        @Override
        public void write(Encoder encoder, Failure failure) throws Exception {
            throwableSerializer.write(encoder, failure.getValue());
        }

        @Override
        public Failure read(Decoder decoder) throws Exception {
            return new Failure(throwableSerializer.read(decoder));
        }
    }

    private static class BuildEventSerializer implements Serializer<BuildEvent> {
        private final Serializer<Object> payloadSerializer = new DefaultSerializer<Object>();

        @Override
        public void write(Encoder encoder, BuildEvent buildEvent) throws Exception {
            payloadSerializer.write(encoder, buildEvent.getPayload());
        }

        @Override
        public BuildEvent read(Decoder decoder) throws Exception {
            return new BuildEvent(payloadSerializer.read(decoder));
        }
    }

    private static class ProgressStartEventSerializer implements Serializer<ProgressStartEvent> {
        @Override
        public void write(Encoder encoder, ProgressStartEvent event) throws Exception {
            encoder.writeSmallLong(event.getOperationId().getId());
            if (event.getParentId() == null) {
                encoder.writeBoolean(false);
            } else {
                encoder.writeBoolean(true);
                encoder.writeSmallLong(event.getParentId().getId());
            }
            encoder.writeLong(event.getTimestamp());
            encoder.writeString(event.getCategory());
            encoder.writeString(event.getDescription());
            encoder.writeNullableString(event.getShortDescription());
            encoder.writeNullableString(event.getLoggingHeader());
            encoder.writeString(event.getStatus());
        }

        @Override
        public ProgressStartEvent read(Decoder decoder) throws Exception {
            OperationIdentifier id = new OperationIdentifier(decoder.readSmallLong());
            OperationIdentifier parentId = decoder.readBoolean() ? new OperationIdentifier(decoder.readSmallLong()) : null;
            long timestamp = decoder.readLong();
            String category = decoder.readString();
            String description = decoder.readString();
            String shortDescription = decoder.readNullableString();
            String loggingHeader = decoder.readNullableString();
            String status = decoder.readString();
            return new ProgressStartEvent(id, parentId, timestamp, category, description, shortDescription, loggingHeader, status);
        }
    }

    private static class ProgressEventSerializer implements Serializer<ProgressEvent> {
        @Override
        public void write(Encoder encoder, ProgressEvent event) throws Exception {
            encoder.writeSmallLong(event.getOperationId().getId());
            encoder.writeLong(event.getTimestamp());
            encoder.writeString(event.getCategory());
            encoder.writeString(event.getStatus());
        }

        @Override
        public ProgressEvent read(Decoder decoder) throws Exception {
            OperationIdentifier id = new OperationIdentifier(decoder.readSmallLong());
            long timestamp = decoder.readLong();
            String category = decoder.readString();
            String status = decoder.readString();
            return new ProgressEvent(id, timestamp, category, status);
        }
    }

    private static class ProgressCompleteEventSerializer implements Serializer<ProgressCompleteEvent> {
        @Override
        public void write(Encoder encoder, ProgressCompleteEvent event) throws Exception {
            encoder.writeSmallLong(event.getOperationId().getId());
            encoder.writeLong(event.getTimestamp());
            encoder.writeString(event.getCategory());
            encoder.writeString(event.getDescription());
            encoder.writeString(event.getStatus());
        }

        @Override
        public ProgressCompleteEvent read(Decoder decoder) throws Exception {
            OperationIdentifier id = new OperationIdentifier(decoder.readSmallLong());
            long timestamp = decoder.readLong();
            String category = decoder.readString();
            String description = decoder.readString();
            String status = decoder.readString();
            return new ProgressCompleteEvent(id, timestamp, category, description, status);
        }
    }

    private static class LogLevelChangeEventSerializer implements Serializer<LogLevelChangeEvent> {
        private final Serializer<LogLevel> logLevelSerializer;

        public LogLevelChangeEventSerializer(Serializer<LogLevel> logLevelSerializer) {
            this.logLevelSerializer = logLevelSerializer;
        }

        @Override
        public void write(Encoder encoder, LogLevelChangeEvent value) throws Exception {
            logLevelSerializer.write(encoder, value.getNewLogLevel());
        }

        @Override
        public LogLevelChangeEvent read(Decoder decoder) throws Exception {
            LogLevel logLevel = logLevelSerializer.read(decoder);
            return new LogLevelChangeEvent(logLevel);
        }
    }

    private static class LogEventSerializer implements Serializer<LogEvent> {
        private final Serializer<Throwable> throwableSerializer;
        private final Serializer<LogLevel> logLevelSerializer;

        public LogEventSerializer(Serializer<LogLevel> logLevelSerializer, Serializer<Throwable> throwableSerializer) {
            this.logLevelSerializer = logLevelSerializer;
            this.throwableSerializer = throwableSerializer;
        }

        @Override
        public void write(Encoder encoder, LogEvent event) throws Exception {
            encoder.writeLong(event.getTimestamp());
            encoder.writeString(event.getCategory());
            logLevelSerializer.write(encoder, event.getLogLevel());
            encoder.writeString(event.getMessage());
            throwableSerializer.write(encoder, event.getThrowable());
        }

        @Override
        public LogEvent read(Decoder decoder) throws Exception {
            long timestamp = decoder.readLong();
            String category = decoder.readString();
            LogLevel logLevel = logLevelSerializer.read(decoder);
            String message = decoder.readString();
            Throwable throwable = throwableSerializer.read(decoder);
            return new LogEvent(timestamp, category, logLevel, message, throwable);
        }
    }

    private static class SpanSerializer implements Serializer<StyledTextOutputEvent.Span> {
        private final Serializer<StyledTextOutput.Style> styleSerializer;

        public SpanSerializer(Serializer<StyledTextOutput.Style> styleSerializer) {
            this.styleSerializer = styleSerializer;
        }

        @Override
        public void write(Encoder encoder, StyledTextOutputEvent.Span value) throws Exception {
            styleSerializer.write(encoder, value.getStyle());
            encoder.writeString(value.getText());
        }

        @Override
        public StyledTextOutputEvent.Span read(Decoder decoder) throws Exception {
            return new StyledTextOutputEvent.Span(styleSerializer.read(decoder), decoder.readString());
        }
    }

    private static class StyledTextOutputEventSerializer implements Serializer<StyledTextOutputEvent> {
        private final Serializer<LogLevel> logLevelSerializer;
        private final Serializer<List<StyledTextOutputEvent.Span>> spanSerializer;

        public StyledTextOutputEventSerializer(Serializer<LogLevel> logLevelSerializer, Serializer<List<StyledTextOutputEvent.Span>> spanSerializer) {
            this.logLevelSerializer = logLevelSerializer;
            this.spanSerializer = spanSerializer;
        }

        @Override
        public void write(Encoder encoder, StyledTextOutputEvent event) throws Exception {
            encoder.writeLong(event.getTimestamp());
            encoder.writeString(event.getCategory());
            logLevelSerializer.write(encoder, event.getLogLevel());
            spanSerializer.write(encoder, event.getSpans());
        }

        @Override
        public StyledTextOutputEvent read(Decoder decoder) throws Exception {
            long timestamp = decoder.readLong();
            String category = decoder.readString();
            LogLevel logLevel = logLevelSerializer.read(decoder);
            List<StyledTextOutputEvent.Span> spans = spanSerializer.read(decoder);
            return new StyledTextOutputEvent(timestamp, category, logLevel, spans);
        }
    }

    private static class ForwardInputSerializer implements Serializer<ForwardInput> {
        @Override
        public void write(Encoder encoder, ForwardInput message) throws Exception {
            encoder.writeBinary(message.getBytes());
        }

        @Override
        public ForwardInput read(Decoder decoder) throws Exception {
            return new ForwardInput(decoder.readBinary());
        }
    }

    private static class CloseInputSerializer implements Serializer<CloseInput> {
        @Override
        public void write(Encoder encoder, CloseInput value) {
        }

        @Override
        public CloseInput read(Decoder decoder) {
            return new CloseInput();
        }
    }

    private static class OutputMessageSerializer implements Serializer<OutputMessage> {
        private final Serializer<OutputEvent> eventSerializer;

        public OutputMessageSerializer(Serializer<OutputEvent> eventSerializer) {
            this.eventSerializer = eventSerializer;
        }

        @Override
        public void write(Encoder encoder, OutputMessage message) throws Exception {
            eventSerializer.write(encoder, message.getEvent());
        }

        @Override
        public OutputMessage read(Decoder decoder) throws Exception {
            return new OutputMessage(eventSerializer.read(decoder));
        }
    }
}


text: export { default } from 'pdfjs/components/pdf-document';

redpajama_set_name: RedPajamaGithub


text:
.icon-articlescontainer .x-tree-node-icon {
    background-image: url(../images/cup.png) !important;
}

.articles-grid-date {
  color:#a0a0a0;
  font-family:arial, Helvetica, sans-serif;
  font-size:20px;
  font-weight:bold;
  letter-spacing:-1px;
  line-height:1;
  padding-right:10px;
  text-align:right;
  margin-top: -4px;
}
.articles-grid-date .articles-grid-time {
  display:block;
  font-size:10px;
  font-weight:normal;
  margin-top:5px;
}

.articles-grid-comments {
    background: url(../images/comments-icon.png) top left no-repeat !important;
    height: 22px;
    width: 24px;
    padding: 3px 0 0 3px;
    text-align: center;
}
.articles-grid-comments span {
    font-size: 11px;
    font-weight: bold;
    line-height: 1.3em;
    display: inline-block;
    color: white;
    text-align: center;
}
.articles-comments-col-header {
    margin-left:7px;
}
.main-column a {
  color:#485319;
  line-height:1;
  text-decoration:none;
}
.main-column a:hover {
  color:#7a8f23;
  text-decoration:none;
}
.articles-grid .x-grid3-cell-inner {
  color:#808080;
}

.articles-panel-spacer .x-panel-body { background: transparent !important; }
.actions a {
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  -o-border-radius:3px;
  -ms-border-radius:3px;
  -khtml-border-radius:3px;
  border-radius:3px;
  background:#dcdcdc;
  background:-moz-linear-gradient(center bottom,#dcdcdc 0%,#fcfcfc 100%) repeat scroll 0 0 transparent;
  background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#fcfcfc),color-stop(100%,#dcdcdc));
  background:-webkit-linear-gradient(center bottom,#dcdcdc 0%,#fcfcfc 100%);
  background:-o-linear-gradient(center bottom,#dcdcdc 0%,#fcfcfc 100%);
  background:-ms-linear-gradient(center bottom,#dcdcdc 0%,#fcfcfc 100%);
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfcfc,endColorstr=#dcdcdc,GradientType=0);
  background:linear-gradient(center bottom,#dcdcdc 0%,#fcfcfc 100%);
  text-shadow:0 1px 0 #ffffff;
  border:1px solid #cccccc;
  color:#888888;
  display:block;
  font-size:11px;
  font-weight:bold;
  font-family:helvetica, arial, freesans, clean, sans-serif;
  padding:6px 8px;
  text-decoration:none;
  cursor:pointer;
}
.actions a:hover {
  background:#e0e0e0;
  background:-moz-linear-gradient(center bottom,#e0e0e0 0%,#fcfcfc 100%) repeat scroll 0 0 transparent;
  background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#fcfcfc),color-stop(100%,#e0e0e0));
  background:-webkit-linear-gradient(center bottom,#e0e0e0 0%,#fcfcfc 100%);
  background:-o-linear-gradient(center bottom,#e0e0e0 0%,#fcfcfc 100%);
  background:-ms-linear-gradient(center bottom,#e0e0e0 0%,#fcfcfc 100%);
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#fcfcfc,endColorstr=#e0e0e0,GradientType=0);
  background:linear-gradient(center bottom,#e0e0e0 0%,#fcfcfc 100%);
  color:#5b7a98;
}
.actions a:active {
  -moz-box-shadow:0 0 3px #aaaaaa inset;
  -webkit-box-shadow:0 0 3px #aaaaaa inset;
  -o-box-shadow:0 0 3px #aaaaaa inset;
  box-shadow:0 0 3px #aaaaaa inset;
  background-color:#ffffff;
  background-image:none;
}
.actions a.orange {
  background:#febb4a;
  background:-moz-linear-gradient(center bottom,#febb4a 0%,#feda71 100%) repeat scroll 0 0 transparent;
  background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#feda71),color-stop(100%,#febb4a));
  background:-webkit-linear-gradient(center bottom,#febb4a 0%,#feda71 100%);
  background:-o-linear-gradient(center bottom,#febb4a 0%,#feda71 100%);
  background:-ms-linear-gradient(center bottom,#febb4a 0%,#feda71 100%);
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#feda71,endColorstr=#febb4a,GradientType=0);
  background:linear-gradient(center bottom,#febb4a 0%,#feda71 100%);
  border-color:#f5b74e #e7a93f #dfa138;
  color:#996633;
  text-shadow:0 1px 0 #fee1a0;
}
.actions a.orange:hover {
  background:#fec95b;
  background:-moz-linear-gradient(center bottom,#fec95b 0%,#fee1a0 100%) repeat scroll 0 0 transparent;
  background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#fee1a0),color-stop(100%,#fec95b));
  background:-webkit-linear-gradient(center bottom,#fec95b 0%,#fee1a0 100%);
  background:-o-linear-gradient(center bottom,#fec95b 0%,#fee1a0 100%);
  background:-ms-linear-gradient(center bottom,#fec95b 0%,#fee1a0 100%);
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#fee1a0,endColorstr=#fec95b,GradientType=0);
  background:linear-gradient(center bottom,#fec95b 0%,#fee1a0 100%);
}

.articles-import-intro {
    font-size: 11px;
    color: #777;
    background-color: #fafafa !important;
    padding: 0 5px;
}

.articles-grid .article-id {
    font-size: 11px;
    font-weight: normal;
    display: block;
    margin-bottom: 3px;
    padding-left: 5px;
    float: left;
    color: #aaa;
}
.articles-grid .main-column a {
    float: left;
}
.articles-grid .article-title-column ul {
    clear: both;
}


text:
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.symbol.wellknown" />

interface SharedArrayBuffer {
    /**
     * Read-only. The length of the ArrayBuffer (in bytes).
     */
    readonly byteLength: number;

    /*
     * The SharedArrayBuffer constructor's length property whose value is 1.
     */
    length: number;
    /**
     * Returns a section of an SharedArrayBuffer.
     */
    slice(begin: number, end?: number): SharedArrayBuffer;
    readonly [Symbol.species]: SharedArrayBuffer;
    readonly [Symbol.toStringTag]: "SharedArrayBuffer";
}

interface SharedArrayBufferConstructor {
    readonly prototype: SharedArrayBuffer;
    new (byteLength: number): SharedArrayBuffer;
}
declare var SharedArrayBuffer: SharedArrayBufferConstructor;

interface ArrayBufferTypes {
    SharedArrayBuffer: SharedArrayBuffer;
}

interface Atomics {
    /**
     * Adds a value to the value at the given position in the array, returning the original value.
     * Until this atomic operation completes, any other read or write operation against the array
     * will block.
     */
    add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;

    /**
     * Stores the bitwise AND of a value with the value at the given position in the array,
     * returning the original value. Until this atomic operation completes, any other read or
     * write operation against the array will block.
     */
    and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;

    /**
     * Replaces the value at the given position in the array if the original value equals the given
     * expected value, returning the original value. Until this atomic operation completes, any
     * other read or write operation against the array will block.
     */
    compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number;

    /**
     * Replaces the value at the given position in the array, returning the original value. Until
     * this atomic operation completes, any other read or write operation against the array will
     * block.
     */
    exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;

    /**
     * Returns a value indicating whether high-performance algorithms can use atomic operations
     * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed
     * array.
     */
    isLockFree(size: number): boolean;

    /**
     * Returns the value at the given position in the array. Until this atomic operation completes,
     * any other read or write operation against the array will block.
     */
    load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number;

    /**
     * Stores the bitwise OR of a value with the value at the given position in the array,
     * returning the original value. Until this atomic operation completes, any other read or write
     * operation against the array will block.
     */
    or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;

    /**
     * Stores a value at the given position in the array, returning the new value. Until this
     * atomic operation completes, any other read or write operation against the array will block.
     */
    store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;

    /**
     * Subtracts a value from the value at the given position in the array, returning the original
     * value. Until this atomic operation completes, any other read or write operation against the
     * array will block.
     */
    sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;

    /**
     * If the value at the given position in the array is equal to the provided value, the current
     * agent is put to sleep causing execution to suspend until the timeout expires (returning
     * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns
     * `"not-equal"`.
     */
    wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out";

    /**
     * Wakes up sleeping agents that are waiting on the given index of the array, returning the
     * number of agents that were awoken.
     * @param typedArray A shared Int32Array.
     * @param index The position in the typedArray to wake up on.
     * @param count The number of sleeping agents to notify. Defaults to +Infinity.
     */
    notify(typedArray: Int32Array, index: number, count?: number): number;

    /**
     * Stores the bitwise XOR of a value with the value at the given position in the array,
     * returning the original value. Until this atomic operation completes, any other read or write
     * operation against the array will block.
     */
    xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number;

    readonly [Symbol.toStringTag]: "Atomics";
}

declare var Atomics: Atomics;


text:
import sys

from .boto3_context import Boto3DeploymentContext
from .boto3_outputs import Boto3OutputStore
from .base import RunBook

class Boto3RunBook(RunBook):
    def __init__(self, profile, artifact_store, manager, selector, pretty_printer):
        RunBook.__init__(self)

        self._profile = profile
        self._artifact_store = artifact_store
        self._manager = manager
        self._selector = selector
        self._ppt = pretty_printer

        selected_deployments = self._manager.query_stacks(
            self._selector.stage_pattern,
            self._selector.stack_pattern)
        selected_stack_keys = list(
            d.stack_key.qualified_name for d in selected_deployments)

        if len(selected_deployments) == 0:
            self._ppt.secho('No stack matches specified pattern.', fg='red')
            self._ppt.secho('Available stacks are:')
            for s in self._manager.query_stacks():
                self._ppt.secho(' {}'.format(s.stack_key.qualified_name))
            sys.exit()

        whole_deployments = self._manager.query_stacks()
        whole_contexts = []
        for deployment in whole_deployments:
            context = Boto3DeploymentContext(
                self._profile, self._artifact_store, deployment, self._ppt)
            if deployment.stack_key.qualified_name in selected_stack_keys:
                self._contexts.append(context)
            whole_contexts.append(context)

        self._output_store = Boto3OutputStore(whole_contexts, self._ppt)

    def pre_run(self, command, context):
        if not command.SKIP_UPDATE_REFERENCES:
            attributes = context.get_parameters_reference()
            self._output_store.collect_stack_outputs(*attributes)
            context.update_parameters_reference(**self._output_store.get_outputs())
        context.make_boto3_parameters()


text:
(function () {
    'use strict';

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

    appRun.$inject = ['routehelper'];

    /* @ngInject */
    function appRun (routehelper){
        routehelper.configureRoutes(getRoutes());
    }

    function getRoutes() {
        return [
            {
                url: '/products',
                config: {
                    title: 'products',
                    controller: 'Products',
                    controllerAs: 'vm',
                    templateUrl: 'app/products/products.html',
                    settings: {
                        nav: 2,
                        content: '<i class="fa fa-gift"></i> Products'
                    }
                }
            },
            {
                url: '/product/:id',
                config: {
                    controller: 'ProductDetail',
                    controllerAs: 'vm',
                    templateUrl: 'app/products/productdetail.html',
                }
            }
        ];
    }
})();


text:
            <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

            </button>
            Shelly

                        Home

                        Tutorials

                        Reference


text:
package cz.zcu.kiv.formgen.model;

import cz.zcu.kiv.formgen.model.constraints.Cardinality;

/**
 * Abstract implementation of the {@link FormItem} interface.
 *
 * @author Jakub Krauz
 */
public abstract class AbstractFormItem implements FormItem {

    /** Type of the form item. */
    protected Type type;

    /** ID of the form item. */
    protected int id;

    /** Name of the form item. */
    protected String name;

    /** Label of the form item. */
    protected String label;

    /** Required flag of the form item. */
    protected boolean required;

    /** Cardinality of the form item. */
    protected Cardinality cardinality;

    /**
     * Constructs a new form item with the given name and type.
     *
     * @param name The name of the form item.
     * @param type The type of the form item.
     */
    public AbstractFormItem(String name, Type type) {
        this.name = name;
        this.type = type;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Type getType() {
        return type;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setType(Type type) {
        this.type = type;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setId(int id) {
        this.id = id;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getId() {
        return id;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setName(String name) {
        this.name = name;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setLabel(String label) {
        this.label = label;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getLabel() {
        return label;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setRequired(boolean required) {
        this.required = required;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isRequired() {
        return required;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setCardinality(Cardinality cardinality) {
        this.cardinality = cardinality;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Cardinality getCardinality() {
        return cardinality;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((cardinality == null) ? 0 : cardinality.hashCode());
        result = prime * result + id;
        result = prime * result + ((label == null) ? 0 : label.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + (required ? 1231 : 1237);
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) { return true; }
        if (obj == null) { return false; }
        if (getClass() != obj.getClass()) { return false; }
        AbstractFormItem other = (AbstractFormItem) obj;
        if (cardinality == null) {
            if (other.cardinality != null) { return false; }
        } else if (!cardinality.equals(other.cardinality)) { return false; }
        if (id != other.id) { return false; }
        if (label == null) {
            if (other.label != null) { return false; }
        } else if (!label.equals(other.label)) { return false; }
        if (name == null) {
            if (other.name != null) { return false; }
        } else if (!name.equals(other.name)) { return false; }
        if (required != other.required) { return false; }
        if (type != other.type) { return false; }
        return true;
    }

}


text:
package channel

import (
	"strings"
	"time"

	cb "github.com/hyperledger/fabric-protos-go/common"
	pb "github.com/hyperledger/fabric-protos-go/peer"
	"github.com/hyperledger/fabric/common/flogging"
	"github.com/hyperledger/fabric/internal/peer/common"
	"github.com/hyperledger/fabric/msp"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
)

var logger = flogging.MustGetLogger("channelCmd")

const (
	EndorserRequired       bool = true
	EndorserNotRequired    bool = false
	OrdererRequired        bool = true
	OrdererNotRequired     bool = false
	PeerDeliverRequired    bool = true
	PeerDeliverNotRequired bool = false
)

var (
	// join related variables.
	genesisBlockPath string

	// create related variables
	channelID     string
	channelTxFile string
	outputBlock   string
	timeout       time.Duration

	// fetch related variables
	bestEffort bool
)

// Cmd returns the cobra command for Node
func Cmd(cf *ChannelCmdFactory) *cobra.Command {
	AddFlags(channelCmd)

	channelCmd.AddCommand(createCmd(cf))
	channelCmd.AddCommand(fetchCmd(cf))
	channelCmd.AddCommand(joinCmd(cf))
	channelCmd.AddCommand(listCmd(cf))
	channelCmd.AddCommand(updateCmd(cf))
	channelCmd.AddCommand(signconfigtxCmd(cf))
	channelCmd.AddCommand(getinfoCmd(cf))

	return channelCmd
}

// AddFlags adds flags for create and join
func AddFlags(cmd *cobra.Command) {
	common.AddOrdererFlags(cmd)
}

var flags *pflag.FlagSet

func init() {
	resetFlags()
}

// Explicitly define a method to facilitate tests
func resetFlags() {
	flags = &pflag.FlagSet{}

	flags.StringVarP(&genesisBlockPath, "blockpath", "b", common.UndefinedParamValue, "Path to file containing genesis block")
	flags.StringVarP(&channelID, "channelID", "c", common.UndefinedParamValue, "In case of a newChain command, the channel ID to create. It must be all lower case, less than 250 characters long and match the regular expression: [a-z][a-z0-9.-]*")
	flags.StringVarP(&channelTxFile, "file", "f", "", "Configuration transaction file generated by a tool such as configtxgen for submitting to orderer")
	flags.StringVarP(&outputBlock, "outputBlock", "", common.UndefinedParamValue, `The path to write the genesis block for the channel. (default ./<channelID>.block)`)
	flags.DurationVarP(&timeout, "timeout", "t", 10*time.Second, "Channel creation timeout")
	flags.BoolVarP(&bestEffort, "bestEffort", "", false, "Whether fetch requests should ignore errors and return blocks on a best effort basis")
}

func attachFlags(cmd *cobra.Command, names []string) {
	cmdFlags := cmd.Flags()
	for _, name := range names {
		if flag := flags.Lookup(name); flag != nil {
			cmdFlags.AddFlag(flag)
		} else {
			logger.Fatalf("Could not find flag '%s' to attach to commond '%s'", name, cmd.Name())
		}
	}
}

var channelCmd = &cobra.Command{
	Use:   "channel",
	Short: "Operate a channel: create|fetch|join|list|update|signconfigtx|getinfo.",
	Long:  "Operate a channel: create|fetch|join|list|update|signconfigtx|getinfo.",
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		common.InitCmd(cmd, args)
		common.SetOrdererEnv(cmd, args)
	},
}

type BroadcastClientFactory func() (common.BroadcastClient, error)

type deliverClientIntf interface {
	GetSpecifiedBlock(num uint64) (*cb.Block, error)
	GetOldestBlock() (*cb.Block, error)
	GetNewestBlock() (*cb.Block, error)
	Close() error
}

// ChannelCmdFactory holds the clients used by ChannelCmdFactory
type ChannelCmdFactory struct {
	EndorserClient   pb.EndorserClient
	Signer           msp.SigningIdentity
	BroadcastClient  common.BroadcastClient
	DeliverClient    deliverClientIntf
	BroadcastFactory BroadcastClientFactory
}

// InitCmdFactory init the ChannelCmdFactory with clients to endorser and orderer according to params
func InitCmdFactory(isEndorserRequired, isPeerDeliverRequired, isOrdererRequired bool) (*ChannelCmdFactory, error) {
	if isPeerDeliverRequired && isOrdererRequired {
		// this is likely a bug during development caused by adding a new cmd
		return nil, errors.New("ERROR - only a single deliver source is currently supported")
	}

	var err error
	cf := &ChannelCmdFactory{}

	cf.Signer, err = common.GetDefaultSignerFnc()
	if err != nil {
		return nil, errors.WithMessage(err, "error getting default signer")
	}

	cf.BroadcastFactory = func() (common.BroadcastClient, error) {
		return common.GetBroadcastClientFnc()
	}

	// for join and list, we need the endorser as well
	if isEndorserRequired {
		// creating an EndorserClient with these empty parameters will create a
		// connection using the values of "peer.address" and
		// "peer.tls.rootcert.file"
		cf.EndorserClient, err = common.GetEndorserClientFnc(common.UndefinedParamValue, common.UndefinedParamValue)
		if err != nil {
			return nil, errors.WithMessage(err, "error getting endorser client for channel")
		}
	}

	// for fetching blocks from a peer
	if isPeerDeliverRequired {
		cf.DeliverClient, err = common.NewDeliverClientForPeer(channelID, cf.Signer, bestEffort)
		if err != nil {
			return nil, errors.WithMessage(err, "error getting deliver client for channel")
		}
	}

	// for create and fetch, we need the orderer as well
	if isOrdererRequired {
		if len(strings.Split(common.OrderingEndpoint, ":")) != 2 {
			return nil, errors.Errorf("ordering service endpoint %s is not valid or missing", common.OrderingEndpoint)
		}
		cf.DeliverClient, err = common.NewDeliverClientForOrderer(channelID, cf.Signer, bestEffort)
		if err != nil {
			return nil, err
		}
	}

	logger.Infof("Endorser and orderer connections initialized")
	return cf, nil
}


text:
"""Tests for the Meteo-France config flow."""
from unittest.mock import patch

from meteofrance_api.model import Place
import pytest

from homeassistant import data_entry_flow
from homeassistant.components.meteo_france.const import (
    CONF_CITY,
    DOMAIN,
    FORECAST_MODE_DAILY,
    FORECAST_MODE_HOURLY,
)
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE
from homeassistant.core import HomeAssistant

from tests.common import MockConfigEntry

CITY_1_POSTAL = "74220"
CITY_1_NAME = "La Clusaz"
CITY_1_LAT = 45.90417
CITY_1_LON = 6.42306
CITY_1_COUNTRY = "FR"
CITY_1_ADMIN = "Rhône-Alpes"
CITY_1_ADMIN2 = "74"
CITY_1 = Place(
    {
        "name": CITY_1_NAME,
        "lat": CITY_1_LAT,
        "lon": CITY_1_LON,
        "country": CITY_1_COUNTRY,
        "admin": CITY_1_ADMIN,
        "admin2": CITY_1_ADMIN2,
    }
)

CITY_2_NAME = "Auch"
CITY_2_LAT = 43.64528
CITY_2_LON = 0.58861
CITY_2_COUNTRY = "FR"
CITY_2_ADMIN = "Midi-Pyrénées"
CITY_2_ADMIN2 = "32"
CITY_2 = Place(
    {
        "name": CITY_2_NAME,
        "lat": CITY_2_LAT,
        "lon": CITY_2_LON,
        "country": CITY_2_COUNTRY,
        "admin": CITY_2_ADMIN,
        "admin2": CITY_2_ADMIN2,
    }
)

CITY_3_NAME = "Auchel"
CITY_3_LAT = 50.50833
CITY_3_LON = 2.47361
CITY_3_COUNTRY = "FR"
CITY_3_ADMIN = "Nord-Pas-de-Calais"
CITY_3_ADMIN2 = "62"
CITY_3 = Place(
    {
        "name": CITY_3_NAME,
        "lat": CITY_3_LAT,
        "lon": CITY_3_LON,
        "country": CITY_3_COUNTRY,
        "admin": CITY_3_ADMIN,
        "admin2": CITY_3_ADMIN2,
    }
)

@pytest.fixture(name="client_single")
def mock_controller_client_single():
    """Mock a successful client."""
    with patch(
        "homeassistant.components.meteo_france.config_flow.MeteoFranceClient",
        update=False,
    ) as service_mock:
        service_mock.return_value.search_places.return_value = [CITY_1]
        yield service_mock

@pytest.fixture(autouse=True)
def mock_setup():
    """Prevent setup."""
    with patch(
        "homeassistant.components.meteo_france.async_setup",
        return_value=True,
    ), patch(
        "homeassistant.components.meteo_france.async_setup_entry",
        return_value=True,
    ):
        yield

@pytest.fixture(name="client_multiple")
def mock_controller_client_multiple():
    """Mock a successful client."""
    with patch(
        "homeassistant.components.meteo_france.config_flow.MeteoFranceClient",
        update=False,
    ) as service_mock:
        service_mock.return_value.search_places.return_value = [CITY_2, CITY_3]
        yield service_mock

@pytest.fixture(name="client_empty")
def mock_controller_client_empty():
    """Mock a successful client."""
    with patch(
        "homeassistant.components.meteo_france.config_flow.MeteoFranceClient",
        update=False,
    ) as service_mock:
        service_mock.return_value.search_places.return_value = []
        yield service_mock

async def test_user(hass, client_single):
    """Test user config."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": SOURCE_USER}
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "user"

    # test with all provided with search returning only 1 place
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_USER},
        data={CONF_CITY: CITY_1_POSTAL},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result["result"].unique_id == f"{CITY_1_LAT}, {CITY_1_LON}"
    assert result["title"] == f"{CITY_1}"
    assert result["data"][CONF_LATITUDE] == str(CITY_1_LAT)
    assert result["data"][CONF_LONGITUDE] == str(CITY_1_LON)

async def test_user_list(hass, client_multiple):
    """Test user config."""

    # test with all provided with search returning more than 1 place
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_USER},
        data={CONF_CITY: CITY_2_NAME},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "cities"

    result = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        user_input={CONF_CITY: f"{CITY_3};{CITY_3_LAT};{CITY_3_LON}"},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result["result"].unique_id == f"{CITY_3_LAT}, {CITY_3_LON}"
    assert result["title"] == f"{CITY_3}"
    assert result["data"][CONF_LATITUDE] == str(CITY_3_LAT)
    assert result["data"][CONF_LONGITUDE] == str(CITY_3_LON)

async def test_import(hass, client_multiple):
    """Test import step."""
    # import with all
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_IMPORT},
        data={CONF_CITY: CITY_2_NAME},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result["result"].unique_id == f"{CITY_2_LAT}, {CITY_2_LON}"
    assert result["title"] == f"{CITY_2}"
    assert result["data"][CONF_LATITUDE] == str(CITY_2_LAT)
    assert result["data"][CONF_LONGITUDE] == str(CITY_2_LON)

async def test_search_failed(hass, client_empty):
    """Test error displayed if no result in search."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_USER},
        data={CONF_CITY: CITY_1_POSTAL},
    )

    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["errors"] == {CONF_CITY: "empty"}

async def test_abort_if_already_setup(hass, client_single):
    """Test we abort if already setup."""
    MockConfigEntry(
        domain=DOMAIN,
        data={CONF_LATITUDE: CITY_1_LAT, CONF_LONGITUDE: CITY_1_LON},
        unique_id=f"{CITY_1_LAT}, {CITY_1_LON}",
    ).add_to_hass(hass)

    # Should fail, same CITY same postal code (import)
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_IMPORT},
        data={CONF_CITY: CITY_1_POSTAL},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
    assert result["reason"] == "already_configured"

    # Should fail, same CITY same postal code (flow)
    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": SOURCE_USER},
        data={CONF_CITY: CITY_1_POSTAL},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
    assert result["reason"] == "already_configured"

async def test_options_flow(hass: HomeAssistant):
    """Test config flow options."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_LATITUDE: CITY_1_LAT, CONF_LONGITUDE: CITY_1_LON},
        unique_id=f"{CITY_1_LAT}, {CITY_1_LON}",
    )
    config_entry.add_to_hass(hass)

    assert config_entry.options == {}

    result = await hass.config_entries.options.async_init(config_entry.entry_id)
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "init"

    # Default
    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert config_entry.options[CONF_MODE] == FORECAST_MODE_DAILY

    # Manual
    result = await hass.config_entries.options.async_init(config_entry.entry_id)
    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={CONF_MODE: FORECAST_MODE_HOURLY},
    )
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert config_entry.options[CONF_MODE] == FORECAST_MODE_HOURLY


text:
using UnityEngine;

namespace KirinoEngine {
    public class AudioManager : MonoBehaviour {
        public AudioSource musicPlayer;
        public AudioSource sfxPlayer;
        public AudioSource voicePlayer;

        public float musicVolume
        {
            get
            {
                musicPlayer.volume = PlayerPrefs.GetFloat("Music Volume", 1.0f);
                return musicPlayer.volume;
            }
            set
            {
                PlayerPrefs.SetFloat("Music Volume", value);
                musicPlayer.volume = value;
            }
        }

        public float voiceVolume
        {
            get
            {
                voicePlayer.volume = PlayerPrefs.GetFloat("Voice Volume", 1.0f);
                return voicePlayer.volume;
            }
            set
            {
                PlayerPrefs.SetFloat("Voice Volume", value);
                voicePlayer.volume = value;
            }
        }

        public float sfxVolume
        {
            get
            {
                sfxPlayer.volume = PlayerPrefs.GetFloat("SFX Volume", 1.0f);
                return sfxPlayer.volume;
            }
            set
            {
                PlayerPrefs.SetFloat("SFX Volume", value);
                sfxPlayer.volume = value;
            }
        }

        public bool musicMute
        {
            get
            {
                var muteInt = PlayerPrefs.GetInt("Music Mute", 0);
                var mute = muteInt == 1 ? true : false;

                musicPlayer.mute = mute;

                return mute;
            }

            set
            {
                musicPlayer.mute = value;
                var muteInt = value ? 1 : 0;
                PlayerPrefs.SetInt("Music Mute", muteInt);
            }
        }

        public bool voiceMute
        {
            get
            {
                var muteInt = PlayerPrefs.GetInt("Voice Mute", 0);
                var mute = muteInt == 1 ? true : false;

                voicePlayer.mute = mute;

                return mute;
            }

            set
            {
                voicePlayer.mute = value;
                var muteInt = value ? 1 : 0;
                PlayerPrefs.SetInt("Voice Mute", muteInt);
            }
        }

        public bool sfxMute
        {
            get
            {
                var muteInt = PlayerPrefs.GetInt("SFX Mute", 0);
                var mute = muteInt == 1 ? true : false;

                sfxPlayer.mute = mute;

                return mute;
            }

            set
            {
                sfxPlayer.mute = value;
                var muteInt = value ? 1 : 0;
                PlayerPrefs.SetInt("SFX Mute", muteInt);
            }
        }

        private void Awake() {
            if (!musicPlayer || !sfxPlayer || !voicePlayer)
            {
                Debug.LogWarning("AudioSource for AudioManager is not assigned!");
            }
            else
            {
                musicPlayer.mute = musicMute;
                voicePlayer.mute = voiceMute;
                sfxPlayer.mute = sfxMute;

                musicPlayer.volume = musicVolume;
                voicePlayer.volume = voiceVolume;
                sfxPlayer.volume = sfxVolume;
            }

            musicPlayer.loop = true;
            sfxPlayer.loop = false;
            voicePlayer.loop = false;
        }

        public void StopMusic() {
            musicPlayer.Stop();
        }

        public void PlayMusic(AudioClip music) {
            if (music != musicPlayer.clip) musicPlayer.clip = music;

            if (!musicPlayer.isPlaying) musicPlayer.Play();
        }

        public void PlaySoundEffect(AudioClip sfx) {
            sfxPlayer.clip = sfx;
            sfxPlayer.Play();
        }

        public void PlayVoice(AudioClip voice) {
            voicePlayer.clip = voice;
            voicePlayer.Play();
        }

    }
}


text:
/  serverCertificateErrors;
@property (readonly) id<NSFastEnumeration> /*WSCCCertificate*/  serverIntermediateCertificates;
- (NSString *)toString;
@end

#endif // __WWHHttpTransportInformation_DEFINED__

// Windows.Web.Http.HttpStringContent
#ifndef __WWHHttpStringContent_DEFINED__
#define __WWHHttpStringContent_DEFINED__

WINRT_EXPORT
@interface WWHHttpStringContent : RTObject <WWHIHttpContent, WFIClosable, WFIStringable>
+ (WWHHttpStringContent *)createFromString:(NSString *)content ACTIVATOR;
+ (WWHHttpStringContent *)createFromStringWithEncoding:(NSString *)content encoding:(WSSUnicodeEncoding)encoding ACTIVATOR;
+ (WWHHttpStringContent *)createFromStringWithEncodingAndMediaType:(NSString *)content encoding:(WSSUnicodeEncoding)encoding mediaType:(NSString *)mediaType ACTIVATOR;
@property (readonly) WWHHHttpContentHeaderCollection * headers;
- (void)bufferAllAsyncWithSuccess:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsBufferAsyncWithSuccess:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsInputStreamAsyncWithSuccess:(void (^)(RTObject<WSSIInputStream>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsStringAsyncWithSuccess:(void (^)(NSString *))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (BOOL)tryComputeLength:(uint64_t*)length;
- (void)writeToStreamAsync:(RTObject<WSSIOutputStream>*)outputStream success:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)close;
- (NSString *)toString;
@end

#endif // __WWHHttpStringContent_DEFINED__

// Windows.Web.Http.HttpBufferContent
#ifndef __WWHHttpBufferContent_DEFINED__
#define __WWHHttpBufferContent_DEFINED__

WINRT_EXPORT
@interface WWHHttpBufferContent : RTObject <WWHIHttpContent, WFIClosable, WFIStringable>
+ (WWHHttpBufferContent *)createFromBuffer:(RTObject<WSSIBuffer>*)content ACTIVATOR;
+ (WWHHttpBufferContent *)createFromBufferWithOffset:(RTObject<WSSIBuffer>*)content offset:(unsigned)offset count:(unsigned)count ACTIVATOR;
@property (readonly) WWHHHttpContentHeaderCollection * headers;
- (void)bufferAllAsyncWithSuccess:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsBufferAsyncWithSuccess:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsInputStreamAsyncWithSuccess:(void (^)(RTObject<WSSIInputStream>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsStringAsyncWithSuccess:(void (^)(NSString *))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (BOOL)tryComputeLength:(uint64_t*)length;
- (void)writeToStreamAsync:(RTObject<WSSIOutputStream>*)outputStream success:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)close;
- (NSString *)toString;
@end

#endif // __WWHHttpBufferContent_DEFINED__

// Windows.Web.Http.HttpStreamContent
#ifndef __WWHHttpStreamContent_DEFINED__
#define __WWHHttpStreamContent_DEFINED__

WINRT_EXPORT
@interface WWHHttpStreamContent : RTObject <WWHIHttpContent, WFIClosable, WFIStringable>
+ (WWHHttpStreamContent *)createFromInputStream:(RTObject<WSSIInputStream>*)content ACTIVATOR;
@property (readonly) WWHHHttpContentHeaderCollection * headers;
- (void)bufferAllAsyncWithSuccess:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsBufferAsyncWithSuccess:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsInputStreamAsyncWithSuccess:(void (^)(RTObject<WSSIInputStream>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsStringAsyncWithSuccess:(void (^)(NSString *))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (BOOL)tryComputeLength:(uint64_t*)length;
- (void)writeToStreamAsync:(RTObject<WSSIOutputStream>*)outputStream success:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)close;
- (NSString *)toString;
@end

#endif // __WWHHttpStreamContent_DEFINED__

// Windows.Web.Http.HttpFormUrlEncodedContent
#ifndef __WWHHttpFormUrlEncodedContent_DEFINED__
#define __WWHHttpFormUrlEncodedContent_DEFINED__

WINRT_EXPORT
@interface WWHHttpFormUrlEncodedContent : RTObject <WWHIHttpContent, WFIClosable, WFIStringable>
// Could not generate Create (Can't marshal Windows.Foundation.Collections.IKeyValuePair`2<String,String>)
@property (readonly) WWHHHttpContentHeaderCollection * headers;
- (void)bufferAllAsyncWithSuccess:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsBufferAsyncWithSuccess:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsInputStreamAsyncWithSuccess:(void (^)(RTObject<WSSIInputStream>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsStringAsyncWithSuccess:(void (^)(NSString *))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (BOOL)tryComputeLength:(uint64_t*)length;
- (void)writeToStreamAsync:(RTObject<WSSIOutputStream>*)outputStream success:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)close;
- (NSString *)toString;
@end

#endif // __WWHHttpFormUrlEncodedContent_DEFINED__

// Windows.Web.Http.HttpMultipartContent
#ifndef __WWHHttpMultipartContent_DEFINED__
#define __WWHHttpMultipartContent_DEFINED__

WINRT_EXPORT
@interface WWHHttpMultipartContent : RTObject <WWHIHttpContent, WFIClosable, WFIStringable>
+ (WWHHttpMultipartContent *)createWithSubtype:(NSString *)subtype ACTIVATOR;
+ (WWHHttpMultipartContent *)createWithSubtypeAndBoundary:(NSString *)subtype boundary:(NSString *)boundary ACTIVATOR;
+ (instancetype)create ACTIVATOR;
@property (readonly) WWHHHttpContentHeaderCollection * headers;
- (void)bufferAllAsyncWithSuccess:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsBufferAsyncWithSuccess:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsInputStreamAsyncWithSuccess:(void (^)(RTObject<WSSIInputStream>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsStringAsyncWithSuccess:(void (^)(NSString *))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (BOOL)tryComputeLength:(uint64_t*)length;
- (void)writeToStreamAsync:(RTObject<WSSIOutputStream>*)outputStream success:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)close;
- (void)add:(RTObject<WWHIHttpContent>*)content;
- (NSString *)toString;
@end

#endif // __WWHHttpMultipartContent_DEFINED__

// Windows.Web.Http.HttpMultipartFormDataContent
#ifndef __WWHHttpMultipartFormDataContent_DEFINED__
#define __WWHHttpMultipartFormDataContent_DEFINED__

WINRT_EXPORT
@interface WWHHttpMultipartFormDataContent : RTObject <WWHIHttpContent, WFIClosable, WFIStringable>
+ (WWHHttpMultipartFormDataContent *)createWithBoundary:(NSString *)boundary ACTIVATOR;
+ (instancetype)create ACTIVATOR;
@property (readonly) WWHHHttpContentHeaderCollection * headers;
- (void)bufferAllAsyncWithSuccess:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsBufferAsyncWithSuccess:(void (^)(RTObject<WSSIBuffer>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsInputStreamAsyncWithSuccess:(void (^)(RTObject<WSSIInputStream>*))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)readAsStringAsyncWithSuccess:(void (^)(NSString *))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (BOOL)tryComputeLength:(uint64_t*)length;
- (void)writeToStreamAsync:(RTObject<WSSIOutputStream>*)outputStream success:(void (^)(uint64_t))success progress:(void (^)(uint64_t))progress failure:(void (^)(NSError*))failure;
- (void)close;
- (void)add:(RTObject<WWHIHttpContent>*)content;
- (void)addWithName:(RTObject<WWHIHttpContent>*)content name:(NSString *)name;
- (void)addWithNameAndFileName:(RTObject<WWHIHttpContent>*)content name:(NSString *)name fileName:(NSString *)fileName;
- (NSString *)toString;
@end

#endif // __WWHHttpMultipartFormDataContent_DEFINED__

// Windows.Web.Http.HttpCookieManager
#ifndef __WWHHttpCookieManager_DEFINED__
#define __WWHHttpCookieManager_DEFINED__

WINRT_EXPORT
@interface WWHHttpCookieManager : RTObject
- (BOOL)setCookie:(WWHHttpCookie *)cookie;
- (BOOL)setCookieWithThirdParty:(WWHHttpCookie *)cookie thirdParty:(BOOL)thirdParty;
- (void)deleteCookie:(WWHHttpCookie *)cookie;
- (WWHHttpCookieCollection *)getCookies:(WFUri *)uri;
@end

#endif // __WWHHttpCookieManager_DEFINED__


text:
<?php

namespace OskarD\Tests\App;

use OskarD\JsonApiModel\ApiModel;

class Comment extends ApiModel
{

}


text:
package zyu19.libs.action.chain.tests;

import org.junit.Assert;
import org.junit.Test;
import zyu19.libs.action.chain.ActionChain;
import zyu19.libs.action.chain.ExceptionList;
import zyu19.libs.action.chain.config.ThreadPolicy;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * This is just a simple test to illustrate ExceptionList
 * Created by zyu on 3/11/16.
 */
public class ExceptionOutputTest {

    static Random random = new Random();
    static BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    static ThreadPolicy threadPolicy = new ThreadPolicy(runnable -> queue.add(runnable), Executors.newCachedThreadPool());
    static ActionChain chain = new ActionChain(threadPolicy);

    @Test(timeout =  2000)
    public void Main() {

        PrintStream stderr = System.err;

        ByteArrayOutputStream errContent = new ByteArrayOutputStream();
        System.setErr(new PrintStream(errContent));

        // Test: more than 2 types
        Integer nullInt = null;
        int[] stage = new int[]{0};
        int[] numEx = new int[]{0};

        chain.clear(null
        ).then(random.nextBoolean(), obj -> {
            Object ret = ActionChain.all(new ActionChain(threadPolicy).thenConsume(random.nextBoolean(), xxx -> {
                System.out.println(nullInt + 1);
            }).start(), new ActionChain(threadPolicy).thenConsume(random.nextBoolean(), xxx -> {
                System.out.println(nullInt + 1);
            }).start(), new ActionChain(threadPolicy).thenConsume(random.nextBoolean(), xxx -> {
                System.out.println(nullInt + 1);
            }).start(), new ActionChain(threadPolicy).thenConsume(random.nextBoolean(), xxx -> {
                System.out.println(nullInt + 1);
            }).start());
            Thread.sleep(500);
            return ret;
        }).start(obj -> {
            Assert.fail("Should not reach this line.");
        });

        StringBuilder builder = new StringBuilder();

        // Simulate the Android Looper class
        while (!queue.isEmpty())
            try {
                System.err.flush();
                builder.append(errContent.toString());
                if(builder.toString().contains(ExceptionList.messageTag)) {
                    System.out.println("Finished");
                    break;
                }
                else queue.take().run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
}


text:
package com.spaceproject.components;

import com.badlogic.ashley.core.Component;

public class SeedComponent implements Component {
    public long seed;
}


text:
package com.example.util;

import com.example.model.FileInfo;

/**
 * @author Liangshi.cn@gmail.com
 */
public class Printer {

    public static void printFileInfo(final FileInfo fileInfo) {
        p(getNameAndType(fileInfo));
        p(getLength(fileInfo));
        p(getSize(fileInfo));
        p(getCompression(fileInfo));
    }

    private static String getNameAndType(final FileInfo fileInfo) {
        return String.format("name: %s, type: %s", fileInfo.getName(), fileInfo.getType());
    }

    private static String getLength(final FileInfo fileInfo) {
        return String.format("length: %s", fileInfo.getLength());
    }

    private static String getSize(final FileInfo fileInfo) {
        return String.format("size: %s X %s", fileInfo.getWidth(), fileInfo.getHeight());
    }

    private static String getCompression(final FileInfo fileInfo) {
        return String.format("compression: %s%", fileInfo.getCompression());
    }

    public static void p(String s) {
        System.out.println(s);
    }
}


text:
import BIDMat.{CMat,CSMat,DMat,Dict,FMat,FND,GMat,GDMat,GIMat,GLMat,GSMat,GSDMat,HMat,IDict,Image,IMat,LMat,Mat,SMat,SBMat,SDMat}
import BIDMat.MatFunctions._
import BIDMat.SciFunctions._
import BIDMat.Solvers._
import BIDMat.Plotting._
import BIDMach.Learner
import BIDMach.models.{DNN,FM,GLM,KMeans,KMeansw,LDA,LDAgibbs,Model,NMF,SFA}
import BIDMach.datasources.{DataSource,MatDS,FilesDS,SFilesDS}
import BIDMach.mixins.{CosineSim,Perplexity,Top,L1Regularizer,L2Regularizer}
import BIDMach.updaters.{ADAGrad,Batch,BatchNorm,IncMult,IncNorm,Telescoping}
import BIDMach.causal.{IPTW}

Mat.checkMKL
Mat.checkCUDA


text:
package org.apache.geronimo.interop.rmi.iiop;

public abstract class StringSeqHelper
{
    public static java.lang.String[] clone
        (java.lang.String[] _value)
    {
        if (_value == null)
        {
            return null;
        }
        int _16 = _value.length;
        java.lang.String[] _clone = new java.lang.String[_16];
        for (int _17 = 0; _17 < _16; _17++)
        {
            _clone[_17] = _value[_17];
        }
        return _clone;
    }

    public static java.lang.String[] read
        (org.omg.CORBA.portable.InputStream _input)
    {
        int _18 = _input.read_ulong();
        java.lang.String[] value = new java.lang.String[_18];
        for (int _19 = 0; _19 < _18; _19++)
        {
            value[_19] = _input.read_string();
        }
        return value;
    }

    public static void write
        (org.omg.CORBA.portable.OutputStream _output,
        java.lang.String[] value)
    {
        if (value == null)
        {
            value = new java.lang.String[0];
        }
        int _20 = value.length;
        _output.write_ulong(_20);
        for (int _21 = 0; _21 < _20; _21++)
        {
            _output.write_string(value[_21]);
        }
    }

    public static org.omg.CORBA.TypeCode _type;

    public static org.omg.CORBA.TypeCode type()
    {
        if (_type == null)
        {
            org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
            _type = orb.create_sequence_tc(0, orb.get_primitive_tc(org.omg.CORBA.TCKind.tk_string));
        }
        return _type;
    }

    public static void insert
        (org.omg.CORBA.Any any,
        java.lang.String[] value)
    {
        org.omg.CORBA.portable.OutputStream output = any.create_output_stream();
        write(output, value);
        any.read_value(output.create_input_stream(), type());
    }

    public static java.lang.String[] extract
        (org.omg.CORBA.Any any)
    {
        if (! any.type().equal(type()))
        {
            throw new org.omg.CORBA.BAD_OPERATION();
        }
        return read(any.create_input_stream());
    }

    public static java.lang.String id()
    {
        return "IDL:org/apache/geronimo/interop/rmi/iiop/StringSeq:1.0";
    }
}


text:
# BEGIN-INTERNAL-SCRIPT-BLOCK
# Script:
# 	Sif - Python Create Hostname in NIOS

# Script-Description:
# 	'https://jsonplaceholder.typicode.com/users'

# END-INTERNAL-SCRIPT-BLOCK

# BEGIN-SCRIPT-BLOCK
#
# Script-Filter:
#     true
#
# Script-Variables:
#     $gmuser string 'Grid Master Username'
#     $gmpassword password 'Grid Master Password'
#     $gmipaddress string '192.168.1.2'
#
# END-SCRIPT-BLOCK

from infoblox_netmri.easy import NetMRIEasy
import requests, json

requests.packages.urllib3.disable_warnings()
# This values will be provided by NetMRI before execution
defaults = {
    'api_url': api_url,
    'http_username': http_username,
    'http_password': http_password,
    'job_id': job_id,
    'device_id': device_id,
    'batch_id': batch_id
}

# Create NetMRI context manager. It will close session after execution
with NetMRIEasy(**defaults) as easy:
    device = device_devicename
    our_ip = device_deviceipdotted
    data = {
    	"name": "host3.aaa.com",
    	"ipv4addrs": [
    		{
    			"ipv4addr": our_ip
    		}
    	]
    }
    print (data)
    headers = {'Content-type': 'application/json'}
    url = "https://{}/wapi/v2.5/record:host".format(gmipaddress)
    r = requests.request("POST", url, verify=False,  data=json.dumps(data), headers=headers, auth=(gmuser, gmpassword))
    print (r.text)


text:
var Offshore = require('../../../lib/offshore'),
    assert = require('assert');

describe('Model', function() {
  describe('association', function() {
    describe('getter', function() {

      /////////////////////////////////////////////////////
      // TEST SETUP
      ////////////////////////////////////////////////////

      var collection;

      before(function(done) {
        var offshore = new Offshore();

        var User = Offshore.Collection.extend({
          connection: 'my_foo',
          tableName: 'person',
          attributes: {
            preferences: {
              collection: 'preference',
              via: 'user'
            }
          }
        });

        var Preference = Offshore.Collection.extend({
          connection: 'my_foo',
          tableName: 'preference',
          attributes: {
            user: {
              model: 'person'
            }
          }
        });

        offshore.loadCollection(User);
        offshore.loadCollection(Preference);

        var _values = [
          { preferences: [{ foo: 'bar' }, { foo: 'foobar' }] },
          { preferences: [{ foo: 'a' }, { foo: 'b' }] },
        ];

        var adapterDef = {
          identity: 'foo',
          join: function(con, col, criteria, cb) { return cb(null, _values); },
        };

        adapterDef.find = adapterDef.join;

        var connections = {
          'my_foo': {
            adapter: 'foobar'
          }
        };

        offshore.initialize({ adapters: { foobar: adapterDef }, connections: connections }, function(err, colls) {
          if(err) done(err);
          collection = colls.collections.person;
          done();
        });
      });

      /////////////////////////////////////////////////////
      // TEST METHODS
      ////////////////////////////////////////////////////

      it('should have a getter for preferences', function(done) {
        collection.find().exec(function(err, data) {
          if(err) return done(err);

          assert(Array.isArray(data[0].preferences));
          assert(data[0].preferences.length == 2);
          assert(data[0].preferences[0].foo === 'bar');

          assert(Array.isArray(data[1].preferences));
          assert(data[1].preferences.length == 2);
          assert(data[1].preferences[0].foo === 'a');

          done();
        });
      });

      it('should have special methods on the preference key', function(done) {
        collection.find().exec(function(err, data) {
          if(err) return done(err);

          assert(typeof data[0].preferences.add == 'function');
          assert(typeof data[0].preferences.remove == 'function');

          assert(typeof data[1].preferences.add == 'function');
          assert(typeof data[1].preferences.remove == 'function');

          done();
        });
      });

    });
  });
});


text:
package rainbownlp.analyzer.evaluation.classification;

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

import rainbownlp.analyzer.evaluation.ICrossfoldValidator;
import rainbownlp.machinelearning.LearnerEngine;
import rainbownlp.machinelearning.MLExample;
import rainbownlp.util.FileUtil;
import rainbownlp.util.ConfigurationUtil;

public class CrossValidation implements ICrossfoldValidator {

	LearnerEngine mlModel;
	public CrossValidation(LearnerEngine learningEngine)
	{
		mlModel = learningEngine;
	}
	public EvaluationResult crossValidation(List<MLExample> examples, int folds) throws Exception
	{

		int foldCount = examples.size()/folds;
		ArrayList<EvaluationResult> results =
			new ArrayList<EvaluationResult>();
		for(int foldIndex = 0;foldIndex<folds;foldIndex++)
		{
			ConfigurationUtil.crossFoldCurrent = foldIndex+1;
			int start_index = foldIndex*foldCount;
			int end_index = (foldIndex+1)*foldCount;
			if(end_index>=examples.size())
				end_index = examples.size();

//			HibernateUtil.startTransaction();

			List<MLExample> train_set = new ArrayList<MLExample>();
			for(int i=0;i<start_index;i++)
				train_set.add(examples.get(i).clone());
			for(int i=end_index;i<examples.size();i++)
				train_set.add(examples.get(i).clone());

			mlModel.train(train_set);
			train_set = null;
			System.gc();

			List<MLExample> test_set = new ArrayList<MLExample>();
			for(int i=start_index;i<end_index;i++)
				test_set.add(examples.get(i).clone());

			mlModel.test(test_set);

//			HibernateUtil.endTransaction();
			results.add(Evaluator.getEvaluationResult(test_set));
		}

		HashMap<String, ResultRow>
			evaluationAverageResult =
			new HashMap<String,
				ResultRow>();
		for(EvaluationResult fold_result : results)
		{
			for(String evaluated_class: fold_result.evaluationResultByClass.keySet())
			{
				ResultRow row =
					fold_result.evaluationResultByClass.get(evaluated_class);
				ResultRow averageRow =
					evaluationAverageResult.get(evaluated_class);
				if(averageRow==null)
					evaluationAverageResult.put(evaluated_class,row);
				else{
					averageRow.FN += row.FN;
					averageRow.FP += row.FP;
					averageRow.TN += row.TN;
					averageRow.TP += row.TP;
				}
			}
		}
		for(String evaluated_class: evaluationAverageResult.keySet())
		{
			ResultRow averageRow =
				evaluationAverageResult.get(evaluated_class);
			FileUtil.logLine("Class: "+evaluated_class);
			averageRow.print();
		}
		EvaluationResult er = new EvaluationResult();
		er.evaluationResultByClass = evaluationAverageResult;

		ConfigurationUtil.crossFoldCurrent = 0;

		return er;
	}
	@Override
	public LearnerEngine getLearnerEngine() {
		return mlModel;
	}
}


text:
namespace base {
class TaskRunner;
}

namespace suggestions {

// Factory for iOS specific implementation of image_fetcher::ImageDecoder.
std::unique_ptr<image_fetcher::ImageDecoder> CreateIOSImageDecoder(
    scoped_refptr<base::TaskRunner> task_runner);

}  // namespace suggestions

#endif  // IOS_CHROME_BROWSER_SUGGESTIONS_IOS_IMAGE_DECODER_IMPL_H_


text:
package com.beyondar.android.util.math.geom;

/**
 * Represents a geometric ray, compound of a {@link Point3} and a
 * {@link Vector3}
 *
 *
 */
public class Ray {

	private Point3 point;
	private Vector3 vector;

	/**
	 * Constructs a ray from a point and a vector
	 *
	 * @param p
	 *            the point
	 * @param v
	 *            the vector
	 */
	public Ray(Point3 p, Vector3 v) {
		this.point = p;
		this.vector = v;
	}

	/**
	 * Constructs a ray from a point and a vector. The point is defined as
	 * (0,0,0)
	 *
	 * @param v
	 *            the vector
	 */
	public Ray(Vector3 v) {
		this.point = new Point3(0, 0, 0);
		this.vector = v;

	}

	/**
	 * Constructs a ray from a point and a vector. The point is defined as
	 * (0,0,0)
	 *
	 * @param v
	 *            the vector
	 */
	public Ray(float vec_x, float vec_y, float vec_z) {
		this.point = new Point3(0, 0, 0);
		this.vector = new Vector3(vec_x, vec_y, vec_z);

	}

	/**
	 * Returns the point in the ray that corresponds to the given t parameter
	 *
	 * @param t
	 *            t parameter
	 * @return the corresponding point
	 */
	public Point3 getPoint(float t) {
		Point3 p = new Point3(t * vector.x, t * vector.y, t * vector.z);
		p.add(point);
		return p;
	}

	/**
	 * Returns the starting point for this ray
	 *
	 * @return the starting point for this ray
	 */
	public Point3 getPoint() {
		return point;
	}

	/**
	 * Returns the vector defining the ray
	 *
	 * @return the vector defining the ray
	 */
	public Vector3 getVector() {
		return vector;
	}

	public void setVector(float x, float y, float z) {
		this.vector.set(x, y, z);
	}

	public Ray clone() {
		return new Ray(point, vector);
	}

	public void copy(Ray ray){
		point.copy(ray.point);

		ray.vector.x = vector.x;
		ray.vector.x = vector.x;
		ray.vector.x = vector.x;
	}

	private static Ray r = new Ray(new Point3(0, 0, 0), new Vector3(0, 0, 0));

	public static Ray getVolatileRay(Point3 p, Vector3 v) {
		r.point = p;
		r.vector = v;
		return r;
	}

}


text:
import os

from tests import test_client_credentials, create_unique_name, test_root_site_url
from tests.sharepoint.sharepoint_case import SPTestCase

from office365.sharepoint.changes.query import ChangeQuery
from office365.sharepoint.files.file import File
from office365.sharepoint.lists.list import List
from office365.sharepoint.lists.creation_information import ListCreationInformation
from office365.sharepoint.lists.template_type import ListTemplateType
from office365.sharepoint.pages.template_file_type import TemplateFileType
from office365.sharepoint.webs.web import Web

def normalize_response(response):
    content = response.decode("utf-8")
    if (content[0] == content[-1]) and content.startswith(("'", '"')):
        return content[1:-1]
    return content

class TestSharePointFile(SPTestCase):
    content_placeholder = create_unique_name("1234567890 abcdABCD")
    file_entries = [
        {"Name": "Sample.txt", "Type": "Text"},
        {"Name": "SharePoint User Guide.docx", "Type": "Binary"}
    ]
    target_list = None  # type: List
    target_file = None  # type: File

    @classmethod
    def setUpClass(cls):
        super(TestSharePointFile, cls).setUpClass()
        cls.target_list = cls.ensure_list(cls.client.web,
                                          ListCreationInformation(
                                              create_unique_name("Archive Documents"),
                                              None,
                                              ListTemplateType.DocumentLibrary))

    @classmethod
    def tearDownClass(cls):
        cls.target_list.delete_object().execute_query()

    def test1_upload_files(self):
        for entry in self.file_entries:
            path = "{0}/../data/{1}".format(os.path.dirname(__file__), entry["Name"])
            if entry["Type"] == "Binary":
                file_content = self.read_file_as_binary(path)
            else:
                file_content = self.read_file_as_text(path)
            target_folder = self.__class__.target_list.root_folder
            uploaded_file = target_folder.upload_file(entry["Name"], file_content).execute_query()
            self.assertEqual(uploaded_file.name, entry["Name"])

    def test2_upload_large_file(self):
        path = "{0}/../data/big_buck_bunny.mp4".format(os.path.dirname(__file__))
        file_size = os.path.getsize(path)
        size_1mb = 1000000
        result_file = self.__class__.target_list.root_folder.files.create_upload_session(path, size_1mb).execute_query()
        self.assertEqual(file_size, int(result_file.length))

    def test3_get_first_file(self):
        files = self.__class__.target_list.root_folder.files.top(1).get().execute_query()
        self.assertEqual(len(files), 1)
        self.__class__.target_file = files[0]

    def test4_get_file_from_absolute_url(self):
        file_abs_url = test_root_site_url + self.__class__.target_file.serverRelativeUrl
        file = File.from_url(file_abs_url).with_credentials(test_client_credentials).get().execute_query()
        self.assertIsNotNone(file.serverRelativeUrl)

    def test5_create_file_anon_link(self):
        file_url = self.__class__.target_file.serverRelativeUrl
        result = Web.create_anonymous_link(self.client, file_url, False).execute_query()
        self.assertIsNotNone(result.value)

    def test6_load_file_metadata(self):
        list_item = self.__class__.target_file.listItemAllFields.expand(["File"]).get().execute_query()
        self.assertIsInstance(list_item.file, File)

    def test7_load_file_metadata_alt(self):
        list_item = self.__class__.target_file.listItemAllFields
        self.client.load(list_item, ["File"])
        self.client.execute_query()
        self.assertIsInstance(list_item.file, File)

    def test8_update_file_content(self):
        """Test file upload operation"""
        files = self.__class__.target_list.root_folder.files.get().execute_query()
        for file_upload in files:
            response = File.save_binary(self.client, file_upload.properties["ServerRelativeUrl"],
                                        self.content_placeholder)
            self.assertTrue(response.ok)

    def test9_update_file_metadata(self):
        """Test file update metadata"""
        list_item = self.__class__.target_file.listItemAllFields  # get metadata
        list_item.set_property('Title', 'Updated')
        list_item.update().execute_query()

    def test_10_list_file_versions(self):
        """Test file update metadata"""
        file_with_versions = self.__class__.target_file.expand(["Versions"]).get().execute_query()
        self.assertGreater(len(file_with_versions.versions), 0)

    def test_11_delete_file_version(self):
        versions = self.__class__.target_file.versions.top(1).get().execute_query()
        self.assertEqual(len(versions), 1)
        self.assertIsNotNone(versions[0].resource_path)
        versions[0].delete_object().execute_query()

    def test_12_delete_file_version_by_id(self):
        versions = self.__class__.target_file.versions.top(1).get().execute_query()
        self.assertEqual(len(versions), 1)
        ver_id = versions[0].id
        versions.delete_by_id(ver_id).execute_query()

    def test_13_download_file(self):
        """Test file upload operation"""
        files = self.__class__.target_list.root_folder.files.get().execute_query()
        for file in files:  # type: File
            content = file.read()
            enc_content = normalize_response(content)
            self.assertEqual(enc_content, self.content_placeholder)

    def test_14_copy_file(self):
        files = self.__class__.target_list.root_folder.files.get().execute_query()
        for cur_file in files:  # type: File
            file_url = cur_file.serverRelativeUrl
            path, file_name = os.path.split(file_url)
            new_file_url = '/'.join([path, "copied_" + file_name])
            cur_file.copyto(new_file_url, True).execute_query()

            moved_file = self.client.web.get_file_by_server_relative_url(new_file_url).get().execute_query()
            self.assertEqual(new_file_url, moved_file.serverRelativeUrl)

    def test_15_move_file(self):
        files = self.__class__.target_list.root_folder.files.get().execute_query()
        for cur_file in files:
            file_url = cur_file.properties["ServerRelativeUrl"]
            path, file_name = os.path.split(file_url)
            new_file_url = '/'.join([path, "moved_" + file_name])
            cur_file.moveto(new_file_url, 1).execute_query()

            moved_file = self.client.web.get_file_by_server_relative_url(new_file_url).get().execute_query()
            self.assertEqual(new_file_url, moved_file.properties["ServerRelativeUrl"])

    def test_16_recycle_first_file(self):
        """Test file upload operation"""
        files = self.__class__.target_list.root_folder.files.get().execute_query()
        files_count = len(files)
        if files_count > 0:
            first_file = files[0]
            first_file.recycle()
            first_file.execute_query()
            files_after = self.__class__.target_list.root_folder.files.get().execute_query()
            self.assertEqual(len(files) - 1, len(files_after))

    def test_17_create_template_file(self):
        target_folder = self.__class__.target_list.root_folder.get().execute_query()
        file_url = '/'.join([target_folder.serverRelativeUrl, "WikiPage.aspx"])
        file_new = self.__class__.target_list.root_folder.files.add_template_file(file_url, TemplateFileType.WikiPage)
        self.client.execute_query()
        self.assertEqual(file_new.serverRelativeUrl, file_url)
        self.__class__.target_file = file_new

    def test_18_get_folder_changes(self):
        changes = self.__class__.target_file.listItemAllFields.get_changes(ChangeQuery(item=True)).execute_query()
        self.assertGreater(len(changes), 0)

    def test_19_delete_files(self):
        files_to_delete = self.__class__.target_list.root_folder.files.get().execute_query()
        for file_to_delete in files_to_delete:  # type: File
            file_to_delete.delete_object().execute_query()

        file_col = self.__class__.target_list.root_folder.files.get().execute_query()
        self.assertEqual(len(file_col), 0)


text:
try {
  var each = require('each');
} catch (e) {
  var each = require('each-component');
}

/**
 * Map an array or object.
 *
 * @param {Array|Object} obj
 * @param {Function} iterator
 * @return {Mixed}
 */

module.exports = function map (obj, iterator) {
  var arr = [];
  each(obj, function (o) {
    arr.push(iterator.apply(null, arguments));
  });
  return arr;
};


text:
package org.wit.fddl;

import static org.junit.Assert.assertEquals;

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

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import org.wit.fddl.datahandle.DataHandleUtil;
import org.wit.fddl.sql.SeperatorSymbol;
import org.wit.fddl.sql.SqlKeyWords;

public class CommonsTest {

	@Test
	public void testCopyProperties(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", 111);
		map.put("name", "ff");
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		list.add(map);
		List<Person> result = DataHandleUtil.mapToList(list, Person.class);
		assertEquals("Person [id=111, name=ff]",StringUtils.join(result, ","));
	}

	@Test
	public void testCopyPropertiesForFieldMap(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id1", 111);
		map.put("name", "ff");
		Map<String,String> fieldMap = new HashMap<String,String>();
		fieldMap.put("id1", "id");
		//fieldMap.put("name1", "name");

		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		list.add(map);
		List<Person> result = DataHandleUtil.mapToList(list, Person.class,fieldMap);

		assertEquals("Person [id=111, name=ff]",StringUtils.join(result, ","));
	}

	@Test
	public void testStringBuffer(){

	    String upperField = "password as pwd".toUpperCase();
	    int asIndex = upperField.indexOf(SqlKeyWords.AS);
	    System.out.println(asIndex);
	    while(asIndex!=-1){
	        boolean result = upperField.charAt(asIndex-1) == SeperatorSymbol.EMPTY.charAt(0)
	        && upperField.charAt(asIndex + 2) == SeperatorSymbol.EMPTY.charAt(0);
	        System.out.println(result);
	        if(result){
	            break;
	        }
	        asIndex+=2;
	        if(asIndex>upperField.length()){
	            asIndex = upperField.length();
	        }
	        asIndex = upperField.indexOf(SqlKeyWords.AS,asIndex);
	    }
	}

	@Test
	public void testTimeStap(){
		Map<Integer,Long> map = new HashMap<Integer,Long>();
		map.put(1, 0L);
		map.put(2, 3L);
		for(Entry<Integer,Long> entry: map.entrySet()){
		    if(entry.getValue()==0L){
		        continue;
		    }
		    System.out.println(entry.getValue());
		}
	}

	public static class Person{
		int id;
		String name;
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}

		@Override
		public String toString() {
			return "Person [id=" + id + ", name=" + name + "]";
		}

	}
}


text:
package net.sourceforge.plantuml.elk.proxy.core.math;

import net.sourceforge.plantuml.elk.proxy.ElkObjectProxy;
import net.sourceforge.plantuml.elk.proxy.Reflect;

public class ElkPadding implements ElkObjectProxy {

	public final Object obj;

	public ElkPadding(double top, double right, double bottom, double left) {
		this.obj = Reflect.newInstance("org.eclipse.elk.core.math.ElkPadding", top, right, bottom, left);
	}

	@Override
	public Object getTrueObject() {
		return obj;
	}

}


text:
package rest;

import entity.Flight;
import service.FlightService;

import javax.ejb.EJB;
import javax.inject.Singleton;
import javax.ws.rs.*;
import java.util.List;

@Path("flights")
@Singleton
public class FlightResource {

    private FlightService service;

    @EJB
    void setFlightService(FlightService service) { //intentional default access
        this.service = service;
    }

    @GET
    @Produces("application/json")
    public List<Flight> getFlights() {
        return service.getFlights();
    }

    @GET
    @Produces("application/json")
    @Path("{id}")
    public Flight getFlight(@PathParam("id") long id) {
        if (!service.exists(id))
            throw new NotFoundException("flight with id:" + id + " does not exist.");
        return service.getFlight(id);
    }

    @DELETE
    @Path("{id}")
    public void deleteFlight(@PathParam("id") long id) {
        if (!service.exists(id))
            throw new NotFoundException("flight with id:" + id + " does not exist.");
        service.removeFlight(id);
    }

    @POST
    @Consumes("application/json")
    @Produces("application/json")
    public Flight createFlight(Flight flight) {
        return service.addFlight(flight);
    }

    @PUT
    @Consumes("application/json")
    @Produces("application/json")
    @Path("{id}")
    public Flight updateFlight(@PathParam("id") long id, Flight flight) {
        if (!service.exists(id))
            throw new NotFoundException("flight with id:" + id + " does not exist.");
        return service.updateFlight(id, flight);
    }

}


text:
{% extends "base.html" %}
{% import "_macros.html" as macros %}

{% block title %}Following of {{ user_dict.get('username') }}{% endblock %}

{% block page_content %}

        {% if current_user_id == current_user.id %}

My Following:

        {% else %}

{{ user_dict.get('username') }} is Following:

        {% endif %}

User	Since

        {% for following_dict in following %}

                     {{ following_dict.get('username') }}

            {{ moment(following_dict.get('timestamp')).format('L') }}

                {% if current_user_id == current_user.id %}
                    Unfollow
                {% endif %}

        {% endfor %}

        {{ macros.pagination_widget(pagination, 'main.following', id=user_dict.get('_id')) }}

{% endblock %}


text:
/**
 * @file
 * @brief Bethesda Softworks VID Video Decoder
 * @author Nicholas Tung [ntung (at. ntung com] (2007-03)
 * @sa http://wiki.multimedia.cx/index.php?title=Bethsoft_VID
 * @sa http://www.svatopluk.com/andux/docs/dfvid.html
 */

#include "libavutil/common.h"
#include "dsputil.h"
#include "bethsoftvideo.h"
#include "bytestream.h"

typedef struct BethsoftvidContext {
    AVFrame frame;
} BethsoftvidContext;

static av_cold int bethsoftvid_decode_init(AVCodecContext *avctx)
{
    BethsoftvidContext *vid = avctx->priv_data;
    vid->frame.reference = 1;
    vid->frame.buffer_hints = FF_BUFFER_HINTS_VALID |
        FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
    avctx->pix_fmt = PIX_FMT_PAL8;
    return 0;
}

static void set_palette(AVFrame * frame, const uint8_t * palette_buffer)
{
    uint32_t * palette = (uint32_t *)frame->data[1];
    int a;
    for(a = 0; a < 256; a++){
        palette[a] = AV_RB24(&palette_buffer[a * 3]) * 4;
    }
    frame->palette_has_changed = 1;
}

static int bethsoftvid_decode_frame(AVCodecContext *avctx,
                              void *data, int *data_size,
                              AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    BethsoftvidContext * vid = avctx->priv_data;
    char block_type;
    uint8_t * dst;
    uint8_t * frame_end;
    int remaining = avctx->width;          // number of bytes remaining on a line
    const int wrap_to_next_line = vid->frame.linesize[0] - avctx->width;
    int code;
    int yoffset;

    if (avctx->reget_buffer(avctx, &vid->frame)) {
        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
        return -1;
    }
    dst = vid->frame.data[0];
    frame_end = vid->frame.data[0] + vid->frame.linesize[0] * avctx->height;

    switch(block_type = *buf++){
        case PALETTE_BLOCK:
            set_palette(&vid->frame, buf);
            return 0;
        case VIDEO_YOFF_P_FRAME:
            yoffset = bytestream_get_le16(&buf);
            if(yoffset >= avctx->height)
                return -1;
            dst += vid->frame.linesize[0] * yoffset;
    }

    // main code
    while((code = *buf++)){
        int length = code & 0x7f;

        // copy any bytes starting at the current position, and ending at the frame width
        while(length > remaining){
            if(code < 0x80)
                bytestream_get_buffer(&buf, dst, remaining);
            else if(block_type == VIDEO_I_FRAME)
                memset(dst, buf[0], remaining);
            length -= remaining;      // decrement the number of bytes to be copied
            dst += remaining + wrap_to_next_line;    // skip over extra bytes at end of frame
            remaining = avctx->width;
            if(dst == frame_end)
                goto end;
        }

        // copy any remaining bytes after / if line overflows
        if(code < 0x80)
            bytestream_get_buffer(&buf, dst, length);
        else if(block_type == VIDEO_I_FRAME)
            memset(dst, *buf++, length);
        remaining -= length;
        dst += length;
    }
    end:

    *data_size = sizeof(AVFrame);
    *(AVFrame*)data = vid->frame;

    return buf_size;
}

static av_cold int bethsoftvid_decode_end(AVCodecContext *avctx)
{
    BethsoftvidContext * vid = avctx->priv_data;
    if(vid->frame.data[0])
        avctx->release_buffer(avctx, &vid->frame);
    return 0;
}

AVCodec bethsoftvid_decoder = {
    .name = "bethsoftvid",
    .type = AVMEDIA_TYPE_VIDEO,
    .id = CODEC_ID_BETHSOFTVID,
    .priv_data_size = sizeof(BethsoftvidContext),
    .init = bethsoftvid_decode_init,
    .close = bethsoftvid_decode_end,
    .decode = bethsoftvid_decode_frame,
    .capabilities = CODEC_CAP_DR1,
    .long_name = NULL_IF_CONFIG_SMALL("Bethesda VID video"),
};


text:
package org.jadice.recordmapper;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class MappingException extends Exception {
  private static final long serialVersionUID = 1L;
  private final List<Mapping> ctx = new LinkedList<Mapping>();

  public MappingException(final Mapping ctx, final String message, final Throwable cause) {
    super(cause instanceof MappingException ? message + ": " + ((MappingException) cause).rawMessage() : message,
        cause);

    if (cause instanceof MappingException)
      this.ctx.addAll(0, ((MappingException) cause).ctx);

    this.ctx.add(0, ctx);
  }

  public MappingException(final Mapping ctx, final String message) {
    super(message);
    this.ctx.add(0, ctx);
  }

  public MappingException(final Mapping ctx, final Throwable cause) {
    super(cause instanceof MappingException ? ((MappingException) cause).rawMessage() : cause.getLocalizedMessage(),
        cause);

    if (cause instanceof MappingException)
      this.ctx.addAll(0, ((MappingException) cause).ctx);

    this.ctx.add(0, ctx);
  }

  public MappingException(final String message) {
    super(message);
  }

  public MappingException(final String message, final Throwable cause) {
    super(message, cause);
  }

  @Override
  public String getMessage() {
    return super.getMessage() + formatContext();
  }

  private String rawMessage() {
    return super.getMessage();
  }

  private String formatContext() {
    return "\n  @" + ctx.stream().map(Object::toString).collect(Collectors.joining(" -> "));
  }
}


text:
import os
import sys
import unittest
import grade_histogram

class GradingToolTests(unittest.TestCase):

	def setUp(self):
		self.data_directory = os.path.join(sys.path[0], 'test_data')
		self.output_directory = os.path.join(sys.path[0], 'test_output')

	def tearDown(self):
		pass

	def test_create_histogram_csv(self):
		grades_csv = os.path.join(self.data_directory,'grades.csv')
		grade_field = 'grades'
		output = os.path.join(self.output_directory, 'test_histogram.png')

		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades PNG')
		self.assertTrue(success)

		output = os.path.join(self.output_directory, 'test_histogram.pdf')
		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades PDF')
		self.assertTrue(success)

		output = os.path.join(self.output_directory, 'test_histogram.jpg')
		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades JPG')
		self.assertTrue(success)

	def test_create_histogram_xls(self):
		grades_csv = os.path.join(self.data_directory,'grades.xls')
		grade_field = 'grades'
		output = os.path.join(self.output_directory, 'test_histogram.png')

		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades PNG')
		self.assertTrue(success)

		output = os.path.join(self.output_directory, 'test_histogram.pdf')
		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades PDF')
		self.assertTrue(success)

		output = os.path.join(self.output_directory, 'test_histogram.jpg')
		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades JPG')
		self.assertTrue(success)

	def test_create_histogram_xlsx(self):
		grades_csv = os.path.join(self.data_directory,'grades.xlsx')
		grade_field = 'grades'
		output = os.path.join(self.output_directory, 'test_histogram.png')

		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades PNG')
		self.assertTrue(success)

		output = os.path.join(self.output_directory, 'test_histogram.pdf')
		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades PDF')
		self.assertTrue(success)

		output = os.path.join(self.output_directory, 'test_histogram.jpg')
		success = grade_histogram.create_histogram(grades_csv, grade_field, output, 'Grades JPG')
		self.assertTrue(success)

if __name__ == '__main__':
	unittest.main()


text:
from .build import build_lr_scheduler, build_optimizer, get_default_optimizer_params
from .lr_scheduler import WarmupCosineLR, WarmupMultiStepLR, LRMultiplier, WarmupParamScheduler

__all__ = [k for k in globals().keys() if not k.startswith("_")]


text:
namespace dsn {
namespace log {
    void dsnutil_cpp_log_EXPORT init(const std::string& filename = "");
}
}

#endif // INIT_H