text:
const $q     = require('../node_modules/q/q');
const Worker = require('./Worker');

var HttpServer = function () {
    this.pid = {
        node: null,
        java: null
    };
};

HttpServer.prototype.getNodePid = function () {
    return this.pid.node;
};

HttpServer.prototype.getJavaPid = function () {
    return this.pid.java;
};

HttpServer.prototype.nodeIsStarted = function () {
    return this.pid.node !== null;
};

HttpServer.prototype.javaIsStarted = function () {
    return this.pid.java !== null;
};

HttpServer.prototype.javaIsDisabled = function () {
    if (process.env.HTTP_SERVER_JAVA_DISABLED === 'undefined') {
        return false;
    }

    var validValues = [
        '1',
        'true',
        'yes',
        'on'
    ];

    var currentValue = process.env.HTTP_SERVER_JAVA_DISABLED;

    return validValues.indexOf(currentValue.toLowerCase()) > -1;
};

HttpServer.prototype.isStarted = function () {
    return this.nodeIsStarted() && (this.javaIsStarted() || this.javaIsDisabled());
};

HttpServer.prototype.start = function (callbackSuccess, callbackError) {
    var executeNodeServer = function () {
        var executor = new Worker();

        var cmd  = 'node';
        var args = [
            './node_modules/http-server/bin/http-server',
            executor.plataformIsWindows() ? 'c:/' : '/',
            '8080'
        ];

        var deferred = $q.defer();

        executor.executeCommand(cmd, args).then(function (childProcess) {
            childProcess.on('close', function (code) {
                console.log('Node: ChildProcess was closed with the exit code ' + code);
            });

            executor.filter(childProcess, function (line) {
                if (line.indexOf('Hit CTRL-C to stop the server') != -1) {
                    deferred.resolve(childProcess.pid);
                }
            });
        }, function (command, args, errorCode) {
            deferred.reject(command, args, errorCode);
        });

        return deferred.promise;
    };

    var executeJavaServer = function () {
        var executor = new Worker();

        var cmd  = 'java';
        var args = [
            '-jar',
            './target/comparator-0.0.1-SNAPSHOT.jar'
        ];

        var deferred = $q.defer();

        var showLine = false;

        var deferred = $q.defer();

        executor.executeCommand(cmd, args).then(function (childProcess) {
            childProcess.on('close', function (code) {
                console.log('Java: ChildProcess was closed with the exit code ' + code);
            });

            executor.filter(childProcess, function (line) {
                if (showLine === true) {
                    console.info(line);
                }

                if (line.indexOf('Started App in') != -1) {
                    showLine = true;
                    deferred.resolve(childProcess.pid);
                }
            });
        }, function (command, args, errorCode) {
            deferred.reject(command, args, errorCode);
        });

        return deferred.promise;
    };

    var self = this;

    if (this.javaIsDisabled()) {
        return executeNodeServer().then(function (processId) {
            self.pid.node = processId;
            callbackSuccess(processId, null);
        }, function (command, args, errorCode) {
            callbackError(command, args, errorCode);
        });
    } else {
        return $q.all([
            executeNodeServer(),
            executeJavaServer()
        ]).then(function (processIds) {
            self.pid.node = processIds[0];
            self.pid.java = processIds[1];
            callbackSuccess(processIds[0], processIds[1]);
        }, function (errors) {
            callbackError(errors);
        });
    }
};

module.exports = HttpServer;


text:
Creates and returns a hmac object, a cryptographic hmac with the given
algorithm and key.

It is a [stream][0] that is both readable and writable. The
written data is used to compute the hmac. Once the writable side of
the stream is ended, use the `read()` method to get the computed
digest. The legacy `update` and `digest` methods are also supported.

`algorithm` is dependent on the available algorithms supported by
OpenSSL - see createHash above. `key` is the hmac key to be used.

[0]: stream.html

redpajama_set_name: RedPajamaGithub


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.content;

import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.vespa.config.content.core.StorDistributormanagerConfig;
import com.yahoo.vespa.config.content.core.StorServerConfig;
import com.yahoo.document.select.DocumentSelector;
import com.yahoo.document.select.parser.ParseException;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.metrics.MetricsmanagerConfig;
import com.yahoo.vespa.model.builder.xml.dom.ModelElement;
import com.yahoo.vespa.model.builder.xml.dom.VespaDomBuilder;
import com.yahoo.vespa.model.content.cluster.ContentCluster;
import org.w3c.dom.Element;

import java.util.logging.Logger;

/**
 * Generates distributor-specific configuration.
 */
public class DistributorCluster extends AbstractConfigProducer<Distributor> implements
        StorDistributormanagerConfig.Producer,
        StorServerConfig.Producer,
        MetricsmanagerConfig.Producer {

    public static final Logger log = Logger.getLogger(DistributorCluster.class.getPackage().toString());

    private record GcOptions(int interval, String selection) { }

    private final ContentCluster parent;
    private final BucketSplitting bucketSplitting;
    private final GcOptions gc;
    private final boolean hasIndexedDocumentType;
    private final int maxActivationInhibitedOutOfSyncGroups;
    private final boolean useTwoPhaseDocumentGc;

    public static class Builder extends VespaDomBuilder.DomConfigProducerBuilder<DistributorCluster> {

        ContentCluster parent;

        public Builder(ContentCluster parent) {
            this.parent = parent;
        }

        private String prepareGCSelection(ModelElement documentNode, String selectionString) throws ParseException {
            DocumentSelector s = new DocumentSelector(selectionString);
            boolean enableGC = false;
            if (documentNode != null) {
                enableGC = documentNode.booleanAttribute("garbage-collection", false);
            }
            if (!enableGC) {
                return null;
            }

            return s.toString();
        }

        private int getGCInterval(ModelElement documentNode) {
            int gcInterval = 3600;
            if (documentNode != null) {
                gcInterval = documentNode.integerAttribute("garbage-collection-interval", gcInterval);
            }
            return gcInterval;
        }

        private GcOptions parseGcOptions(ModelElement documentNode) {
            String gcSelection = parent.getRoutingSelector();
            int gcInterval;
            try {
                if (gcSelection != null) {
                    gcSelection = prepareGCSelection(documentNode, gcSelection);
                }
                gcInterval = getGCInterval(documentNode);
            } catch (ParseException e) {
                throw new IllegalArgumentException("Failed to parse garbage collection selection", e);
            }
            return new GcOptions(gcInterval, gcSelection);
        }

        private boolean documentModeImpliesIndexing(String mode) {
            return "index".equals(mode);
        }

        private boolean clusterContainsIndexedDocumentType(ModelElement documentsNode) {
            return documentsNode != null
                    && documentsNode.subElements("document").stream()
                    .anyMatch(node -> documentModeImpliesIndexing(node.stringAttribute("mode")));
        }

        @Override
        protected DistributorCluster doBuild(DeployState deployState, AbstractConfigProducer<?> ancestor, Element producerSpec) {
            final ModelElement clusterElement = new ModelElement(producerSpec);
            final ModelElement documentsNode = clusterElement.child("documents");
            final GcOptions gc = parseGcOptions(documentsNode);
            final boolean hasIndexedDocumentType = clusterContainsIndexedDocumentType(documentsNode);
            int maxInhibitedGroups = deployState.getProperties().featureFlags().maxActivationInhibitedOutOfSyncGroups();
            boolean useTwoPhaseDocumentGc = deployState.getProperties().featureFlags().useTwoPhaseDocumentGc();

            return new DistributorCluster(parent,
                    new BucketSplitting.Builder().build(new ModelElement(producerSpec)), gc,
                    hasIndexedDocumentType,
                    maxInhibitedGroups, useTwoPhaseDocumentGc);
        }
    }

    private DistributorCluster(ContentCluster parent, BucketSplitting bucketSplitting,
                               GcOptions gc, boolean hasIndexedDocumentType,
                               int maxActivationInhibitedOutOfSyncGroups,
                               boolean useTwoPhaseDocumentGc)
    {
        super(parent, "distributor");
        this.parent = parent;
        this.bucketSplitting = bucketSplitting;
        this.gc = gc;
        this.hasIndexedDocumentType = hasIndexedDocumentType;
        this.maxActivationInhibitedOutOfSyncGroups = maxActivationInhibitedOutOfSyncGroups;
        this.useTwoPhaseDocumentGc = useTwoPhaseDocumentGc;
    }

    @Override
    public void getConfig(StorDistributormanagerConfig.Builder builder) {
        if (gc.selection != null) {
            builder.garbagecollection(new StorDistributormanagerConfig.Garbagecollection.Builder()
                    .selectiontoremove("not (" + gc.selection + ")")
                    .interval(gc.interval));
        }
        builder.enable_revert(parent.getPersistence().supportRevert());
        builder.disable_bucket_activation(!hasIndexedDocumentType);
        builder.max_activation_inhibited_out_of_sync_groups(maxActivationInhibitedOutOfSyncGroups);
        builder.enable_two_phase_garbage_collection(useTwoPhaseDocumentGc);

        bucketSplitting.getConfig(builder);
    }

    @Override
    public void getConfig(MetricsmanagerConfig.Builder builder) {
        ContentCluster.getMetricBuilder("log", builder).
                addedmetrics("vds.distributor.docsstored").
                addedmetrics("vds.distributor.bytesstored").
                addedmetrics("vds.idealstate.delete_bucket.done_ok").
                addedmetrics("vds.idealstate.merge_bucket.done_ok").
                addedmetrics("vds.idealstate.split_bucket.done_ok").
                addedmetrics("vds.idealstate.join_bucket.done_ok").
                addedmetrics("vds.idealstate.buckets_rechecking");
    }

    @Override
    public void getConfig(StorServerConfig.Builder builder) {
        builder.root_folder("");
        builder.cluster_name(parent.getName());
        builder.is_distributor(true);
    }

    public String getClusterName() {
        return parent.getName();
    }
}


text:
from typing import Any

import numpy as np

from pandas._libs import index as libindex, lib
from pandas._typing import Dtype, Label
from pandas.util._decorators import cache_readonly, doc

from pandas.core.dtypes.cast import astype_nansafe
from pandas.core.dtypes.common import (
    is_bool,
    is_bool_dtype,
    is_dtype_equal,
    is_extension_array_dtype,
    is_float,
    is_float_dtype,
    is_integer_dtype,
    is_scalar,
    is_signed_integer_dtype,
    is_unsigned_integer_dtype,
    needs_i8_conversion,
    pandas_dtype,
)
from pandas.core.dtypes.generic import (
    ABCFloat64Index,
    ABCInt64Index,
    ABCRangeIndex,
    ABCSeries,
    ABCUInt64Index,
)
from pandas.core.dtypes.missing import isna

from pandas.core import algorithms
import pandas.core.common as com
from pandas.core.indexes.base import Index, maybe_extract_name
from pandas.core.ops import get_op_result_name

_num_index_shared_docs = dict()

class NumericIndex(Index):
    """
    Provide numeric type operations.

    This is an abstract class.
    """

    _is_numeric_dtype = True

    def __new__(cls, data=None, dtype=None, copy=False, name=None):
        cls._validate_dtype(dtype)
        name = maybe_extract_name(name, data, cls)

        # Coerce to ndarray if not already ndarray or Index
        if not isinstance(data, (np.ndarray, Index)):
            if is_scalar(data):
                raise cls._scalar_data_error(data)

            # other iterable of some kind
            if not isinstance(data, (ABCSeries, list, tuple)):
                data = list(data)

            data = np.asarray(data, dtype=dtype)

        if issubclass(data.dtype.type, str):
            cls._string_data_error(data)

        if copy or not is_dtype_equal(data.dtype, cls._default_dtype):
            subarr = np.array(data, dtype=cls._default_dtype, copy=copy)
            cls._assert_safe_casting(data, subarr)
        else:
            subarr = data

        if subarr.ndim > 1:
            # GH#13601, GH#20285, GH#27125
            raise ValueError("Index data must be 1-dimensional")

        subarr = np.asarray(subarr)
        return cls._simple_new(subarr, name=name)

    @classmethod
    def _validate_dtype(cls, dtype: Dtype) -> None:
        if dtype is None:
            return
        validation_metadata = {
            "int64index": (is_signed_integer_dtype, "signed integer"),
            "uint64index": (is_unsigned_integer_dtype, "unsigned integer"),
            "float64index": (is_float_dtype, "float"),
            "rangeindex": (is_signed_integer_dtype, "signed integer"),
        }

        validation_func, expected = validation_metadata[cls._typ]
        if not validation_func(dtype):
            raise ValueError(
                f"Incorrect `dtype` passed: expected {expected}, received {dtype}"
            )

    @doc(Index._maybe_cast_slice_bound)
    def _maybe_cast_slice_bound(self, label, side, kind):
        assert kind in ["loc", "getitem", None]

        # we will try to coerce to integers
        return self._maybe_cast_indexer(label)

    @doc(Index._shallow_copy)
    def _shallow_copy(self, values=None, name: Label = lib.no_default):
        if values is not None and not self._can_hold_na and values.dtype.kind == "f":
            name = self.name if name is lib.no_default else name
            # Ensure we are not returning an Int64Index with float data:
            return Float64Index._simple_new(values, name=name)
        return super()._shallow_copy(values=values, name=name)

    def _convert_for_op(self, value):
        """
        Convert value to be insertable to ndarray.
        """
        if is_bool(value) or is_bool_dtype(value):
            # force conversion to object
            # so we don't lose the bools
            raise TypeError

        return value

    def _convert_tolerance(self, tolerance, target):
        tolerance = np.asarray(tolerance)
        if target.size != tolerance.size and tolerance.size > 1:
            raise ValueError("list-like tolerance size must match target index size")
        if not np.issubdtype(tolerance.dtype, np.number):
            if tolerance.ndim > 0:
                raise ValueError(
                    f"tolerance argument for {type(self).__name__} must contain "
                    "numeric elements if it is list type"
                )
            else:
                raise ValueError(
                    f"tolerance argument for {type(self).__name__} must be numeric "
                    f"if it is a scalar: {repr(tolerance)}"
                )
        return tolerance

    @classmethod
    def _assert_safe_casting(cls, data, subarr):
        """
        Subclasses need to override this only if the process of casting data
        from some accepted dtype to the internal dtype(s) bears the risk of
        truncation (e.g. float to int).
        """
        pass

    @property
    def is_all_dates(self) -> bool:
        """
        Checks that all the labels are datetime objects.
        """
        return False

    @doc(Index.insert)
    def insert(self, loc: int, item):
        # treat NA values as nans:
        if is_scalar(item) and isna(item):
            item = self._na_value
        return super().insert(loc, item)

    def _union(self, other, sort):
        # Right now, we treat union(int, float) a bit special.
        # See https://github.com/pandas-dev/pandas/issues/26778 for discussion
        # We may change union(int, float) to go to object.
        # float | [u]int -> float  (the special case)
        # <T>   | <T>    -> T
        # <T>   | <U>    -> object
        needs_cast = (is_integer_dtype(self.dtype) and is_float_dtype(other.dtype)) or (
            is_integer_dtype(other.dtype) and is_float_dtype(self.dtype)
        )
        if needs_cast:
            first = self.astype("float")
            second = other.astype("float")
            return first._union(second, sort)
        else:
            return super()._union(other, sort)

_num_index_shared_docs[
    "class_descr"
] = """
    Immutable ndarray implementing an ordered, sliceable set. The basic object
    storing axis labels for all pandas objects. %(klass)s is a special case
    of `Index` with purely %(ltype)s labels. %(extra)s.

    Parameters
    ----------
    data : array-like (1-dimensional)
    dtype : NumPy dtype (default: %(dtype)s)
    copy : bool
        Make a copy of input ndarray.
    name : object
        Name to be stored in the index.

    Attributes
    ----------
    None

    Methods
    -------
    None

    See Also
    --------
    Index : The base pandas Index type.

    Notes
    -----
    An Index instance can **only** contain hashable objects.
"""

_int64_descr_args = dict(klass="Int64Index", ltype="integer", dtype="int64", extra="")

class IntegerIndex(NumericIndex):
    """
    This is an abstract class for Int64Index, UInt64Index.
    """

    _default_dtype: np.dtype

    def __contains__(self, key) -> bool:
        """
        Check if key is a float and has a decimal. If it has, return False.
        """
        hash(key)
        try:
            if is_float(key) and int(key) != key:
                return False
            return key in self._engine
        except (OverflowError, TypeError, ValueError):
            return False

    @property
    def inferred_type(self) -> str:
        """
        Always 'integer' for ``Int64Index`` and ``UInt64Index``
        """
        return "integer"

    @property
    def asi8(self) -> np.ndarray:
        # do not cache or you'll create a memory leak
        return self._values.view(self._default_dtype)

class Int64Index(IntegerIndex):
    __doc__ = _num_index_shared_docs["class_descr"] % _int64_descr_args

    _typ = "int64index"
    _can_hold_na = False
    _engine_type = libindex.Int64Engine
    _default_dtype = np.dtype(np.int64)

    def _wrap_joined_index(self, joined, other):
        name = get_op_result_name(self, other)
        return Int64Index(joined, name=name)

    @classmethod
    def _assert_safe_casting(cls, data, subarr):
        """
        Ensure incoming data can be represented as ints.
        """
        if not issubclass(data.dtype.type, np.signedinteger):
            if not np.array_equal(data, subarr):
                raise TypeError("Unsafe NumPy casting, you must explicitly cast")

    def _is_compatible_with_other(self, other) -> bool:
        return super()._is_compatible_with_other(other) or all(
            isinstance(obj, (ABCInt64Index, ABCFloat64Index, ABCRangeIndex))
            for obj in [self, other]
        )

Int64Index._add_numeric_methods()
Int64Index._add_logical_methods()

_uint64_descr_args = dict(
    klass="UInt64Index", ltype="unsigned integer", dtype="uint64", extra=""
)

class UInt64Index(IntegerIndex):
    __doc__ = _num_index_shared_docs["class_descr"] % _uint64_descr_args

    _typ = "uint64index"
    _can_hold_na = False
    _engine_type = libindex.UInt64Engine
    _default_dtype = np.dtype(np.uint64)

    @doc(Index._convert_arr_indexer)
    def _convert_arr_indexer(self, keyarr):
        # Cast the indexer to uint64 if possible so that the values returned
        # from indexing are also uint64.
        dtype = None
        if is_integer_dtype(keyarr) or (
            lib.infer_dtype(keyarr, skipna=False) == "integer"
        ):
            dtype = np.uint64

        return com.asarray_tuplesafe(keyarr, dtype=dtype)

    @doc(Index._convert_index_indexer)
    def _convert_index_indexer(self, keyarr):
        # Cast the indexer to uint64 if possible so
        # that the values returned from indexing are
        # also uint64.
        if keyarr.is_integer():
            return keyarr.astype(np.uint64)
        return keyarr

    def _wrap_joined_index(self, joined, other):
        name = get_op_result_name(self, other)
        return UInt64Index(joined, name=name)

    @classmethod
    def _assert_safe_casting(cls, data, subarr):
        """
        Ensure incoming data can be represented as uints.
        """
        if not issubclass(data.dtype.type, np.unsignedinteger):
            if not np.array_equal(data, subarr):
                raise TypeError("Unsafe NumPy casting, you must explicitly cast")

    def _is_compatible_with_other(self, other) -> bool:
        return super()._is_compatible_with_other(other) or all(
            isinstance(obj, (ABCUInt64Index, ABCFloat64Index)) for obj in [self, other]
        )

UInt64Index._add_numeric_methods()
UInt64Index._add_logical_methods()

_float64_descr_args = dict(
    klass="Float64Index", dtype="float64", ltype="float", extra=""
)

class Float64Index(NumericIndex):
    __doc__ = _num_index_shared_docs["class_descr"] % _float64_descr_args

    _typ = "float64index"
    _engine_type = libindex.Float64Engine
    _default_dtype = np.float64

    @property
    def inferred_type(self) -> str:
        """
        Always 'floating' for ``Float64Index``
        """
        return "floating"

    @doc(Index.astype)
    def astype(self, dtype, copy=True):
        dtype = pandas_dtype(dtype)
        if needs_i8_conversion(dtype):
            raise TypeError(
                f"Cannot convert Float64Index to dtype {dtype}; integer "
                "values are required for conversion"
            )
        elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype):
            # TODO(jreback); this can change once we have an EA Index type
            # GH 13149
            arr = astype_nansafe(self._values, dtype=dtype)
            return Int64Index(arr, name=self.name)
        return super().astype(dtype, copy=copy)

    # ----------------------------------------------------------------
    # Indexing Methods

    @doc(Index._should_fallback_to_positional)
    def _should_fallback_to_positional(self) -> bool:
        return False

    @doc(Index._convert_slice_indexer)
    def _convert_slice_indexer(self, key: slice, kind: str):
        assert kind in ["loc", "getitem"]

        # We always treat __getitem__ slicing as label-based
        # translate to locations
        return self.slice_indexer(key.start, key.stop, key.step, kind=kind)

    # ----------------------------------------------------------------

    def _format_native_types(
        self, na_rep="", float_format=None, decimal=".", quoting=None, **kwargs
    ):
        from pandas.io.formats.format import FloatArrayFormatter

        formatter = FloatArrayFormatter(
            self._values,
            na_rep=na_rep,
            float_format=float_format,
            decimal=decimal,
            quoting=quoting,
            fixed_width=False,
        )
        return formatter.get_result_as_array()

    def equals(self, other) -> bool:
        """
        Determines if two Index objects contain the same elements.
        """
        if self is other:
            return True

        if not isinstance(other, Index):
            return False

        # need to compare nans locations and make sure that they are the same
        # since nans don't compare equal this is a bit tricky
        try:
            if not isinstance(other, Float64Index):
                other = self._constructor(other)
            if not is_dtype_equal(self.dtype, other.dtype) or self.shape != other.shape:
                return False
            left, right = self._values, other._values
            return ((left == right) | (self._isnan & other._isnan)).all()
        except (TypeError, ValueError):
            return False

    def __contains__(self, other: Any) -> bool:
        hash(other)
        if super().__contains__(other):
            return True

        return is_float(other) and np.isnan(other) and self.hasnans

    @doc(Index.get_loc)
    def get_loc(self, key, method=None, tolerance=None):
        if is_bool(key):
            # Catch this to avoid accidentally casting to 1.0
            raise KeyError(key)

        if is_float(key) and np.isnan(key):
            nan_idxs = self._nan_idxs
            if not len(nan_idxs):
                raise KeyError(key)
            elif len(nan_idxs) == 1:
                return nan_idxs[0]
            return nan_idxs

        return super().get_loc(key, method=method, tolerance=tolerance)

    @cache_readonly
    def is_unique(self) -> bool:
        return super().is_unique and self._nan_idxs.size < 2

    @doc(Index.isin)
    def isin(self, values, level=None):
        if level is not None:
            self._validate_index_level(level)
        return algorithms.isin(np.array(self), values)

    def _is_compatible_with_other(self, other) -> bool:
        return super()._is_compatible_with_other(other) or all(
            isinstance(
                obj, (ABCInt64Index, ABCFloat64Index, ABCUInt64Index, ABCRangeIndex),
            )
            for obj in [self, other]
        )

Float64Index._add_numeric_methods()
Float64Index._add_logical_methods_disabled()


text:
package org.mongodb.morphia;

import org.mongodb.morphia.annotations.IndexOptions;
import org.mongodb.morphia.annotations.Text;

class TextBuilder extends AnnotationBuilder<Text> implements Text {
    @Override
    public Class<Text> annotationType() {
        return Text.class;
    }

    @Override
    public IndexOptions options() {
        return get("options");
    }

    @Override
    public int value() {
        return get("value");
    }

    TextBuilder options(final IndexOptions options) {
        put("options", options);
        return this;
    }

    TextBuilder value(final int value) {
        put("value", value);
        return this;
    }

}


text:
  return require('__main__');
});


text:
package com.twitter.sdk.android.tweetui;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.widget.ImageView;

import java.util.Locale;

public final class TestUtils {

    private TestUtils() {}

    /**
     * Sets global locale
     * @param locale Locale to set
     */
    public static Locale setLocale(Context context, Locale locale) {
        final Resources res = context.getResources();
        final Configuration config = res.getConfiguration();
        final Locale originalLocale = config.locale;

        Locale.setDefault(locale);
        config.locale = locale;
        res.updateConfiguration(config, res.getDisplayMetrics());
        return originalLocale;
    }

    /**
     * Gets the color of the ImageView's ColorDrawable or 0 for API < 11.
     * @param imageView an ImageView with a ColorDrawable
     * @return int color of the ImageView
     */
    @TargetApi(11)
    public static int getDrawableColor(ImageView imageView) {
        if (Build.VERSION.SDK_INT >= 11) {
            final ColorDrawable drawable = (ColorDrawable) imageView.getDrawable();
            return drawable.getColor();
        }
        return 0;
    }
}


text:
from __future__ import division

from models import *
from utils import *

from euclid import *
from itertools import *
from xml.dom import minidom

def load_level(path):
    document = minidom.parse(path)
    svg_element = document.getElementsByTagName('svg')[0]
    width = float(svg_element.getAttribute('width'))
    height = float(svg_element.getAttribute('height'))
    description_element = document.getElementsByTagName('dc:description')[0]
    description = description_element.childNodes[0].nodeValue
    description_data = parse_style(description)
    world_width = float(description_data['width'])
    gravity = float(description_data.get('gravity', '10'))
    scale = world_width / width
    world_height = height * scale
    level_model = LevelModel()
    level_model.lower_bound = 0, 0
    level_model.upper_bound = world_width, world_height
    level_model.gravity = 0, -gravity
    transform = (Matrix3.new_scale(scale, -scale) *
                 Matrix3.new_translate(0, -height))
    for child_node in svg_element.childNodes:
        if child_node.nodeType == minidom.Node.ELEMENT_NODE:
            parse_element(child_node, transform, level_model)
    return level_model

def get_bodies_at_point(world, point):
    segment = b2.b2Segment()
    segment.p1 = tuple(point)
    segment.p2 = tuple(point)
    count, shapes = world.Raycast(segment, 1000, True, None)
    return list(set(s.GetBody() for s in shapes))

def get_bodies_at_line_segment(world, line_segment):
    bodies_1 = get_bodies_at_point(world, line_segment.p1)
    bodies_2 = get_bodies_at_point(world, line_segment.p2)
    if len(bodies_1) == 1 and len(bodies_2) == 2:
        bodies_2.remove(bodies_1[0])
    if len(bodies_1) == 2 and len(bodies_2) == 1:
        bodies_1.remove(bodies_2[0])
    return bodies_1[0], bodies_2[0]

def load_vehicle(path, level_model):
    document = minidom.parse(path)
    svg_element = document.getElementsByTagName('svg')[0]
    width = float(svg_element.getAttribute('width'))
    height = float(svg_element.getAttribute('height'))
    description_element = document.getElementsByTagName('dc:description')[0]
    description = description_element.childNodes[0].nodeValue
    world_width = float(parse_style(description)['width'])
    scale = world_width / width
    world_height = height * scale
    transform = (Matrix3.new_translate(*level_model.start) *
                 Matrix3.new_scale(scale, -scale) *
                 Matrix3.new_translate(0, -height))
    for child_node in svg_element.childNodes:
        if child_node.nodeType == minidom.Node.ELEMENT_NODE:
            parse_element(child_node, transform, level_model)

def parse_style(style):
    lines = (l.strip() for l in style.split(';'))
    pairs = (l.split(':') for l in lines if l)
    return dict((k.strip(), v.strip()) for k, v in pairs)

def parse_transform(transform_str):
    name, args = transform_str.split('(')
    name = name.strip()
    args = map(float, args.rstrip(')').split(','))
    if name == 'translate':
        return Matrix3.new_translate(*args)
    elif name == 'matrix':
        transform = Matrix3()
        transform[0:2] = args[0:2]
        transform[3:5] = args[2:4]
        transform[6:8] = args[4:6]
        return transform
    elif name == 'scale':
        return Matrix3.new_scale(*args)
    else:
        log('parse_transform(): unsupported SVG transform: %s' % name)
        return Matrix3.new_identity()

def parse_element(element, transform, level_model):
    transform_str = element.getAttribute('transform')
    if transform_str:
        transform = transform * parse_transform(transform_str)
    element_data = parse_element_data(element)
    if element_data.get('type') == 'revolute-joint':
        parse_revolute_joint_element(element, transform, level_model,
                                     element_data)
    elif element.nodeName == 'g':
        for child_node in element.childNodes:
            if child_node.nodeType == minidom.Node.ELEMENT_NODE:
                parse_element(child_node, transform, level_model)
    elif element.nodeName == 'path':
        if element.getAttribute('sodipodi:type') == 'arc':
            body_model = BodyModel()
            body_model.id = element.getAttribute('id')
            level_model.body_models.append(body_model)
            parse_circle_element(element, transform, level_model, body_model)
        else:
            parse_path_element(element, transform, level_model)
    elif element.nodeName == 'rect':
        body_model = BodyModel()
        body_model.id = element.getAttribute('id')
        level_model.body_models.append(body_model)
        parse_rect_element(element, transform, level_model, body_model)
    elif element.nodeName not in ('sodipodi:namedview', 'defs', 'metadata'):
        log('parse_element(): unsupported SVG element: %s' % element.nodeName)

def parse_element_data(element):
    for child_node in element.childNodes:
        if (child_node.nodeType == minidom.Node.ELEMENT_NODE and
            child_node.nodeName == 'desc'):
            return parse_style(child_node.childNodes[0].nodeValue)
    return {}

def parse_line_segment_element(element, transform):
    path = element.getAttribute('d').replace(',', ' ').strip()
    points = path.lstrip('M').split('L')
    assert len(points) == 2
    points = [Point2(*map(float, p.split())) for p in points]
    return transform * LineSegment2(*points)

def parse_polygon(path):
    path = path.strip().lstrip('M')
    closed = path.endswith('z')
    vertices = [Point2(*map(float, p.replace(',', ' ').split()))
                for p in path.rstrip('z').split('L')]
    return vertices, closed

def parse_revolute_joint_element(element, transform, level_model,
                                 element_data):
    x = float(element.getAttribute('sodipodi:cx'))
    y = float(element.getAttribute('sodipodi:cy'))
    revolute_joint_model = RevoluteJointModel()
    revolute_joint_model.anchor = transform * Point2(x, y)
    level_model.joint_models.append(revolute_joint_model)

def parse_distance_joint_element(element, transform, level_model):
    line_segment = parse_line_segment_element(element, transform)
    distance_joint_model = DistanceJointModel()
    distance_joint_model.anchor_1 = line_segment.p1
    distance_joint_model.anchor_2 = line_segment.p2
    level_model.joint_models.append(distance_joint_model)

def parse_prismatic_joint_element(element, transform, level_model):
    line_segment = parse_line_segment_element(element, transform)
    prismatic_joint_model = PrismaticJointModel()
    prismatic_joint_model.anchor_1 = line_segment.p1
    prismatic_joint_model.anchor_2 = line_segment.p2
    level_model.joint_models.append(prismatic_joint_model)

def parse_spring_element(element, transform, level_model, element_data):
    line_segment = parse_line_segment_element(element, transform)
    spring_model = SpringModel()
    spring_model.anchor_1 = line_segment.p1
    spring_model.anchor_2 = line_segment.p2
    spring_model.spring_constant = float(element_data.get('spring-constant', '1'))
    spring_model.damping = float(element_data.get('damping', '0'))
    level_model.joint_models.append(spring_model)

def parse_path_element(element, transform, level_model):
    element_data = parse_element_data(element)
    if element_data.get('type') == 'start':
        x = float(element.getAttribute('sodipodi:cx'))
        y = float(element.getAttribute('sodipodi:cy'))
        level_model.start = transform * Point2(x, y)
    elif element_data.get('type') == 'goal':
        x = float(element.getAttribute('sodipodi:cx'))
        y = float(element.getAttribute('sodipodi:cy'))
        level_model.goal = transform * Point2(x, y)
    elif element_data.get('type') == 'distance-joint':
        parse_distance_joint_element(element, transform, level_model)
    elif element_data.get('type') == 'prismatic-joint':
        parse_prismatic_joint_element(element, transform, level_model)
    elif element_data.get('type') == 'spring':
        parse_spring_element(element, transform, level_model, element_data)
    elif element_data.get('type') == 'motor':
        x = float(element.getAttribute('sodipodi:cx'))
        y = float(element.getAttribute('sodipodi:cy'))
        motor_model = MotorModel()
        motor_model.anchor = transform * Point2(x, y)
        motor_model.torque = float(element_data.get('torque', '1'))
        motor_model.damping = float(element_data.get('damping', '0'))
        motor_model.clockwise_key = element_data.get('clockwise-key')
        motor_model.counter_clockwise_key = element_data.get('counter-clockwise-key')
        level_model.joint_models.append(motor_model)
    elif element_data.get('type') == 'camera':
        x = float(element.getAttribute('sodipodi:cx'))
        y = float(element.getAttribute('sodipodi:cy'))
        camera_model = CameraModel()
        camera_model.anchor = transform * Point2(x, y)
        level_model.joint_models.append(camera_model)
    else:
        style = parse_style(element.getAttribute('style'))
        vertices, closed = parse_polygon(element.getAttribute('d'))
        vertices = [transform * v for v in vertices]
        body_model = BodyModel()
        body_model.id = element.getAttribute('id')
        stroke_width = float(style.get('stroke-width', '1'))
        radius = abs(transform * Vector2(stroke_width, 0)) / 2
        kwargs = dict(density=float(element_data.get('density', '0')),
                      friction=float(element_data.get('friction', '0.5')),
                      restitution=float(element_data.get('restitution', '0.5')),
                      group_index=int(element_data.get('group-index', '0')),
                      color=parse_color(style.get('stroke', '#000000')))
        for p1, p2 in izip(vertices[:-1], vertices[1:]):
            polygon_model = PolygonModel(**kwargs)
            v = (p2 - p1).cross()
            v.normalize()
            v *= radius
            polygon_model.vertices = [p1 + v, p2 + v, p2 - v, p1 - v]
            body_model.shape_models.append(polygon_model)
            for center in p1, p2:
                circle_model = CircleModel(center=center, radius=radius, **kwargs)
                body_model.shape_models.append(circle_model)
        level_model.body_models.append(body_model)

def parse_color(color_str):
    if color_str == 'none':
        return 0, 0, 0, 0
    assert len(color_str) == 7
    assert color_str[0] == '#'
    red = int(color_str[1:3], 16) / 255
    green = int(color_str[3:5], 16) / 255
    blue = int(color_str[5:7], 16) / 255
    return red, green, blue, 1

def parse_circle_element(element, transform, level_model, body_model):
    label = element.getAttribute('inkscape:label')
    element_data = parse_element_data(element)
    style = parse_style(element.getAttribute('style'))

    cx = float(element.getAttribute('sodipodi:cx'))
    cy = float(element.getAttribute('sodipodi:cy'))
    rx = float(element.getAttribute('sodipodi:rx'))
    ry = float(element.getAttribute('sodipodi:ry'))

    circle_model = CircleModel()
    circle_model.center = transform * Point2(cx, cy)
    circle_model.radius = abs(transform * Vector2((rx + ry) / 2, 0))
    circle_model.density = float(element_data.get('density', '0'))
    circle_model.friction = float(element_data.get('friction', '0.5'))
    circle_model.restitution = float(element_data.get('restitution', '0.5'))
    circle_model.group_index = int(element_data.get('group-index', '0'))
    circle_model.color = parse_color(style.get('fill', 'none'))
    body_model.shape_models.append(circle_model)

def parse_rect_element(element, transform, level_model, body_model):
    label = element.getAttribute('inkscape:label')
    element_data = parse_element_data(element)
    style = parse_style(element.getAttribute('style'))

    x = float(element.getAttribute('x'))
    y = float(element.getAttribute('y'))
    width = float(element.getAttribute('width'))
    height = float(element.getAttribute('height'))
    vertices = [Point2(x, y),
                Point2(x, y + height),
                Point2(x + width, y + height),
                Point2(x + width, y)]

    polygon_model = PolygonModel()
    polygon_model.vertices = [tuple(transform * v) for v in vertices]
    polygon_model.density = float(element_data.get('density', '0'))
    polygon_model.friction = float(element_data.get('friction', '0.5'))
    polygon_model.restitution = float(element_data.get('restitution', '0.5'))
    polygon_model.group_index = int(element_data.get('group-index', '0'))
    polygon_model.color = parse_color(style.get('fill', 'none'))
    body_model.shape_models.append(polygon_model)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

        <EditText
            android:id="@+id/game_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/game_session_name_hint"
            android:singleLine="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:id="@+id/button_add"
        android:layout_below="@+id/game_name"
        android:layout_centerHorizontal="true" />

</RelativeLayout>


text:
package com.centurylink.mdw.service.data;

import com.centurylink.mdw.cache.CacheService;
import com.centurylink.mdw.common.service.ServiceException;
import com.centurylink.mdw.config.PropertyManager;
import com.centurylink.mdw.model.asset.api.AssetInfo;
import com.centurylink.mdw.model.listener.Listener;
import com.centurylink.mdw.model.request.ServicePath;
import com.centurylink.mdw.service.api.MdwSwaggerCache;
import com.centurylink.mdw.services.ServiceLocator;
import com.centurylink.mdw.util.log.LoggerUtil;
import com.centurylink.mdw.util.log.StandardLogger;
import com.centurylink.mdw.yaml.YamlLoader;
import io.swagger.models.Swagger;
import org.json.JSONObject;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Caches normalized request paths.  These are stored in response
 * documents for aggregation purposes (whereas full paths are stored
 * in request documents).
 */
public class ServicePaths implements CacheService {

    private static StandardLogger logger = LoggerUtil.getStandardLogger();
    private static List<ServicePath> inboundPaths;
    public static List<ServicePath> getInboundPaths() { return inboundPaths; }

    private static List<ServicePath> outboundPaths;
    public static List<ServicePath> getOutboundPaths() { return outboundPaths; }

    @Override
    public void refreshCache() {
        clearCache();
    }

    @Override
    public void clearCache() {
        inboundPaths = null;
        outboundPaths = null;
    }

    private static synchronized void load() {
        List<ServicePath> inboundPathsTmp = inboundPaths;
        List<ServicePath> outboundPathsTmp;

        if (inboundPathsTmp == null) {

            inboundPathsTmp = new ArrayList<>();
            outboundPathsTmp = new ArrayList<>();

            // default is enabled
            boolean enabled = PropertyManager.getBooleanProperty("mdw.service.paths.cache", true);
            if (enabled) {
                // inbound paths
                Swagger swagger = MdwSwaggerCache.getSwagger("/");
                if (swagger != null) {
                    for (String swaggerPath : swagger.getPaths().keySet()) {
                        inboundPathsTmp.add(new ServicePath(swaggerPath));
                    }
                    Collections.sort(inboundPathsTmp);
                }

                // outbound paths
                try {
                    Map<String, List<AssetInfo>> swaggers = ServiceLocator.getAssetServices().findAssets(asset ->
                            asset.getName().equals("swagger.yaml") || asset.getName().equals("swagger.json")
                    );
                    for (String pkg : swaggers.keySet()) {
                        for (AssetInfo swaggerAsset : swaggers.get(pkg)) {
                            if (swaggerAsset.getExtension().equals("yaml")) {
                                YamlLoader yamlLoader = new YamlLoader(swaggerAsset.getFile());
                                Map yamlPaths = yamlLoader.getMap("paths", yamlLoader.getTop());
                                if (yamlPaths != null) {
                                    String basePath = yamlLoader.get("basePath", (Map) yamlLoader.getTop());
                                    final String base = basePath == null ? "" : basePath;
                                    yamlPaths.keySet().stream().forEach(p ->
                                            outboundPathsTmp.add(new ServicePath(base + p.toString()))
                                    );
                                }
                            } else if (swaggerAsset.getExtension().equals("json")) {
                                String content = new String(Files.readAllBytes(swaggerAsset.getFile().toPath()));
                                JSONObject json = new JSONObject(content);
                                if (json.has("paths")) {
                                    String base = json.optString("basePath");
                                    JSONObject pathsJson = json.getJSONObject("paths");
                                    for (String path : JSONObject.getNames(pathsJson)) {
                                        outboundPathsTmp.add(new ServicePath(base + path));
                                    }
                                }
                            }
                        }
                    }
                } catch (ServiceException | IOException ex) {
                    logger.error(ex.getMessage(), ex);
                }
            } else {
                logger.info("ServicePaths cache disabled");
            }
            inboundPaths = inboundPathsTmp;
            outboundPaths = outboundPathsTmp;
        }
    }

    public static String getInboundResponsePath(Map<String,String> meta) {
        if (inboundPaths == null)
            load();
        String path = meta.get(Listener.METAINFO_REQUEST_PATH);
        if (path == null)
            return null;
        return new ServicePath(path, meta.get(Listener.METAINFO_HTTP_METHOD)).normalize(inboundPaths).toString();
    }

    public static String getOutboundResponsePath(String url, String method) {
        if (outboundPaths == null)
            load();
        if (url == null)
            return null;
        try {
            return getOutboundResponsePath(new URL(url), method);
        }
        catch (MalformedURLException ex) {
            return new ServicePath(url, method).normalize(outboundPaths).toString();
        }
    }

    public static String getOutboundResponsePath(URL url, String method) {
        if (outboundPaths == null)
            load();
        if (url == null)
            return null;
        return new ServicePath(url.getPath(), method).normalize(outboundPaths).toString();
    }
}


text:
namespace Flyweight
{
    using System;
    using System.Windows.Forms;

    using Domain.Flyweight;

    public partial class WindowDemo : Form
    {
        private Random random = new Random();

        public WindowDemo()
        {
            this.InitializeComponent();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            for (int i = 0; i < 20; i++)
            {
                IWindow redWindow = WindowFactory.GetWindow("Red");
                redWindow.Draw(
                    e.Graphics,
                    this.GetRandomNumber(),
                    this.GetRandomNumber(),
                    this.GetRandomNumber(),
                    this.GetRandomNumber());
            }

            for (int i = 0; i < 20; i++)
            {
                IWindow stoneTile = WindowFactory.GetWindow("Blue");
                stoneTile.Draw(
                    e.Graphics,
                    this.GetRandomNumber(),
                    this.GetRandomNumber(),
                    this.GetRandomNumber(),
                    this.GetRandomNumber());
            }

            this.lblObjectCounter.Text = "Total Objects Created : "
                                         + Convert.ToString(RedWindow.ObjectCounter + BlueWindow.ObjectCounter);
        }

        private int GetRandomNumber()
        {
            return (int)this.random.Next(100);
        }

        private void WindowDemo_Load(object sender, EventArgs e)
        {
        }
    }
}


text:
<?php

namespace Flowcode\ShopBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * ProductOrderStatusLogRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ProductOrderStatusLogRepository extends EntityRepository
{

    /**
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function findAllQB()
    {
        $qb = $this->createQueryBuilder('l');
        return $qb;
    }

    /**
     * @param $order
     * @return array()
     */
    public function checkStockModified($order)
    {
        $qb = $this->findAllQB();
        $qb->innerJoin('l.followingStatus', 'fs');

        $qb->where('l.order = :order')->setParameter('order', $order);
        $qb->andWhere('fs.stockModifier = 1');

        return $qb->getQuery()->getResult();
    }

    /**
     * @param $order
     * @return array()
     */
    public function checkOrderCancelledOrDeleted($order)
    {
        $qb = $this->findAllQB();
        $qb->innerJoin('l.followingStatus', 'fs');

        $qb->where('l.order = :order')->setParameter('order', $order);
        $qb->andWhere('fs.orderDeleted = 1 OR fs.orderCanceled = 1');

        return $qb->getQuery()->getResult();
    }
}


text:
<?php
namespace ATWS\AutotaskObjects;

class PriceListServiceBundle extends Entity
{
    // Required
    public $CurrencyID;
    public $ServiceBundleID;
    public $UsesInternalCurrencyPrice;

    // Optional
    public $UnitPrice;
}


text:
/**
 * Asakusa WindGate information models.
 */
package com.asakusafw.lang.compiler.extension.windgate.info;


text:
TEST(VisualStudioUtils, MakeGuid) {
  std::string pattern = "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}";
  std::string guid = MakeGuid(__FILE__, "foo");
  ASSERT_EQ(pattern.size(), guid.size());
  for (size_t i = 0; i < pattern.size(); ++i) {
    if (pattern[i] == 'x')
      ASSERT_TRUE(base::IsAsciiAlpha(guid[i]) || base::IsAsciiDigit(guid[i]));
    else
      ASSERT_EQ(pattern[i], guid[i]);
  }

  // Calling function again should produce the same GUID.
  ASSERT_EQ(guid, MakeGuid(__FILE__, "foo"));

  // GUIDs should be different if path or seed is different.
  ASSERT_NE(guid, MakeGuid(std::string(__FILE__) + ".txt", "foo"));
  ASSERT_NE(guid, MakeGuid(__FILE__, "bar"));
}

TEST(VisualStudioUtils, ParseCompilerOption) {
  CompilerOptions options;
  ParseCompilerOption("/FIinclude.h", &options);
  ParseCompilerOption("/FIC:/path/file.h", &options);
  ASSERT_EQ("include.h;C:/path/file.h;", options.forced_include_files);

  CHECK(options.buffer_security_check.empty());
  ParseCompilerOption("/GS", &options);
  ASSERT_EQ("true", options.buffer_security_check);
  ParseCompilerOption("/GS-", &options);
  ASSERT_EQ("false", options.buffer_security_check);

  CHECK(options.runtime_library.empty());
  ParseCompilerOption("/MD", &options);
  ASSERT_EQ("MultiThreadedDLL", options.runtime_library);
  ParseCompilerOption("/MDd", &options);
  ASSERT_EQ("MultiThreadedDebugDLL", options.runtime_library);
  ParseCompilerOption("/MT", &options);
  ASSERT_EQ("MultiThreaded", options.runtime_library);
  ParseCompilerOption("/MTd", &options);
  ASSERT_EQ("MultiThreadedDebug", options.runtime_library);

  CHECK(options.optimization.empty());
  ParseCompilerOption("/O1", &options);
  ASSERT_EQ("MinSpace", options.optimization);
  ParseCompilerOption("/O2", &options);
  ASSERT_EQ("MaxSpeed", options.optimization);
  ParseCompilerOption("/Od", &options);
  ASSERT_EQ("Disabled", options.optimization);
  ParseCompilerOption("/Ox", &options);
  ASSERT_EQ("Full", options.optimization);

  CHECK(options.additional_options.empty());
  ParseCompilerOption("/TC", &options);
  ASSERT_TRUE(options.additional_options.empty());
  ParseCompilerOption("/TP", &options);
  ASSERT_TRUE(options.additional_options.empty());

  CHECK(options.warning_level.empty());
  ParseCompilerOption("/W0", &options);
  ASSERT_EQ("Level0", options.warning_level);
  ParseCompilerOption("/W1", &options);
  ASSERT_EQ("Level1", options.warning_level);
  ParseCompilerOption("/W2", &options);
  ASSERT_EQ("Level2", options.warning_level);
  ParseCompilerOption("/W3", &options);
  ASSERT_EQ("Level3", options.warning_level);
  ParseCompilerOption("/W4", &options);
  ASSERT_EQ("Level4", options.warning_level);

  CHECK(options.treat_warning_as_error.empty());
  ParseCompilerOption("/WX", &options);
  ASSERT_EQ("true", options.treat_warning_as_error);

  CHECK(options.disable_specific_warnings.empty());
  ParseCompilerOption("/wd1234", &options);
  ParseCompilerOption("/wd56", &options);
  ASSERT_EQ("1234;56;", options.disable_specific_warnings);

  CHECK(options.additional_options.empty());
  ParseCompilerOption("/MP", &options);
  ParseCompilerOption("/bigobj", &options);
  ParseCompilerOption("/Zc:sizedDealloc", &options);
  ASSERT_EQ("/MP /bigobj /Zc:sizedDealloc ", options.additional_options);
}

TEST(VisualStudioUtils, ParseLinkerOption) {
  LinkerOptions options;
  ParseLinkerOption("/SUBSYSTEM:CONSOLE,5.02h", &options);
  ASSERT_EQ("CONSOLE", options.subsystem);

  ParseLinkerOption("/SUBSYSTEM:WINDOWS", &options);
  ASSERT_EQ("WINDOWS", options.subsystem);
}


text:
#ifndef HWLOC_PORT_CUDA_CUDA_RUNTIME_API_H
#define HWLOC_PORT_CUDA_CUDA_RUNTIME_API_H

/* we need to replace any CUDA-related #define that configure may have put in private/autogen/config.h */
#ifndef HWLOC_CONFIGURE_H
#error cuda_runtime_api.h must be included after private/autogen/config.h
#endif
#undef HWLOC_HAVE_CUDA_L2CACHESIZE
#define HWLOC_HAVE_CUDA_L2CACHESIZE 1

typedef unsigned cudaError_t;

struct cudaDeviceProp {
  char * name;
  int pciDomainID;
  int pciBusID;
  int pciDeviceID;
  size_t totalGlobalMem;
  size_t sharedMemPerBlock;
  int major;
  int minor;
  int l2CacheSize;
  int multiProcessorCount;
};

cudaError_t cudaGetDeviceProperties(struct cudaDeviceProp *, int);
cudaError_t cudaGetDeviceCount(int *);

#endif /* HWLOC_PORT_CUDA_CUDA_RUNTIME_API_H */


text:
package proxy

import (
	"bufio"
	"encoding/json"
	"errors"
	"github.com/gorilla/mux"
	"io"
	"log"
	"net"
	"net/http"
	"sync"
	"sync/atomic"
	"time"

	"../rpc"
)

type ProxyServer struct {
	sync.RWMutex
	config        *Config
	miners        MinersMap
	blockTemplate atomic.Value
	instanceId    []byte
	upstream      int32
	upstreams     []*rpc.RPCClient
	validBlocks   uint64
	invalidBlocks uint64

	timeout time.Duration
}

type Session struct {
	enc *json.Encoder
	ip  string
}

const (
	MaxReqSize = 1 * 1024
)

func NewEndpoint(cfg *Config) *ProxyServer {
	proxy := &ProxyServer{config: cfg}

	proxy.upstreams = make([]*rpc.RPCClient, len(cfg.Upstream))
	for i, v := range cfg.Upstream {
		proxy.upstreams[i] = rpc.NewRPCClient(v.Name, v.Url, v.Timeout)
		log.Printf("Upstream: %s => %s", v.Name, v.Url)
	}
	log.Printf("Default upstream: %s => %s", proxy.rpc().Name, proxy.rpc().Url)

	proxy.miners = NewMinersMap()

	timeout, _ := time.ParseDuration(cfg.Proxy.ClientTimeout)
	proxy.timeout = timeout

	proxy.blockTemplate.Store(&BlockTemplate{})
	proxy.fetchBlockTemplate()

	refreshIntv, _ := time.ParseDuration(cfg.Proxy.BlockRefreshInterval)
	refreshTimer := time.NewTimer(refreshIntv)
	log.Printf("Set block refresh every %v", refreshIntv)

	checkIntv, _ := time.ParseDuration(cfg.UpstreamCheckInterval)
	checkTimer := time.NewTimer(checkIntv)

	go func() {
		for {
			select {
			case <-refreshTimer.C:
				proxy.fetchBlockTemplate()
				refreshTimer.Reset(refreshIntv)
			case <-checkTimer.C:
				proxy.checkUpstreams()
				checkTimer.Reset(checkIntv)
			}
		}
	}()

	return proxy
}

func (s *ProxyServer) rpc() *rpc.RPCClient {
	i := atomic.LoadInt32(&s.upstream)
	return s.upstreams[i]
}

func (s *ProxyServer) checkUpstreams() {
	candidate := int32(0)
	backup := false

	for i, v := range s.upstreams {
		if v.Check() && !backup {
			candidate = int32(i)
			backup = true
		}
	}

	if s.upstream != candidate {
		log.Printf("Switching to %v upstream", s.upstreams[candidate].Name)
		atomic.StoreInt32(&s.upstream, candidate)
	}
}

func (s *ProxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		s.writeError(w, 405, "rpc: POST method required, received "+r.Method)
		return
	}
	s.handleClient(w, r)
}

func (s *ProxyServer) handleClient(w http.ResponseWriter, r *http.Request) error {
	ip, _, _ := net.SplitHostPort(r.RemoteAddr)
	cs := &Session{ip: ip, enc: json.NewEncoder(w)}
	defer r.Body.Close()
	connbuff := bufio.NewReaderSize(r.Body, MaxReqSize)

	for {
		data, isPrefix, err := connbuff.ReadLine()
		if isPrefix {
			log.Printf("Socket flood detected")
			return errors.New("Socket flood")
		} else if err == io.EOF {
			break
		}

		if len(data) > 1 {
			var req JSONRpcReq
			err = json.Unmarshal(data, &req)
			if err != nil {
				log.Printf("Malformed request: %v", err)
				return err
			}
			cs.handleMessage(s, r, &req)
		}
	}
	return nil
}

func (cs *Session) handleMessage(s *ProxyServer, r *http.Request, req *JSONRpcReq) {
	if req.Id == nil {
		log.Println("Missing RPC id")
		r.Close = true
		return
	}

	vars := mux.Vars(r)

	// Handle RPC methods
	switch req.Method {
	case "eth_getWork":
		reply, errReply := s.handleGetWorkRPC(cs, vars["diff"], vars["id"])
		if errReply != nil {
			cs.sendError(req.Id, errReply)
			break
		}
		cs.sendResult(req.Id, &reply)
	case "eth_submitWork":
		var params []string
		err := json.Unmarshal(*req.Params, &params)
		if err != nil {
			log.Println("Unable to parse params")
			break
		}
		reply, errReply := s.handleSubmitRPC(cs, vars["diff"], vars["id"], params)
		if errReply != nil {
			err = cs.sendError(req.Id, errReply)
			break
		}
		cs.sendResult(req.Id, &reply)
	case "eth_submitHashrate":
		cs.sendResult(req.Id, true)
	default:
		errReply := s.handleUnknownRPC(cs, req)
		cs.sendError(req.Id, errReply)
	}
}

func (cs *Session) sendResult(id *json.RawMessage, result interface{}) error {
	message := JSONRpcResp{Id: id, Version: "2.0", Error: nil, Result: result}
	return cs.enc.Encode(&message)
}

func (cs *Session) sendError(id *json.RawMessage, reply *ErrorReply) error {
	message := JSONRpcResp{Id: id, Version: "2.0", Error: reply}
	return cs.enc.Encode(&message)
}

func (s *ProxyServer) writeError(w http.ResponseWriter, status int, msg string) {
	w.WriteHeader(status)
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
}

func (s *ProxyServer) currentBlockTemplate() *BlockTemplate {
	return s.blockTemplate.Load().(*BlockTemplate)
}

func (s *ProxyServer) registerMiner(miner *Miner) {
	s.miners.Set(miner.Id, miner)
}


text:
layout: post
date:	2007-10-30 10:13:00
title:  Every available space is up for sale...
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
Revenue...that's the name of the game.

Saw this on the back of the seat as we flew back from Delhi to Bangalore yesterday:

Well, at least the title is witty!

Would I advertise in a space where the hapless passenger had to stare at my ad for 2 hours? I don't think so, but obviously, Spicejet, the airline we were flying, believes that people would be influenced...

I am renting out the back and front of my tee-shirts shortly. Why should I *pay* to have Proline or someone else advertise their name when I can hire out the space and *make* money?

You can contact me..actually you need not contact me, just send the money across...


text:
"""
    lantz.drivers.rgblasersystems.minilasevo
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :copyright: 2015 by Lantz Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""

from pyvisa import constants

from lantz import Feat
from lantz.messagebased import MessageBasedDriver
from lantz.errors import InstrumentError

class MiniLasEvo(MessageBasedDriver):
    """Driver for any RGB Lasersystems MiniLas Evo laser.
    """

    DEFAULTS = {'ASRL': {'write_termination': '\r\n',
                         'read_termination': '\r\n',
                         'baud_rate': 57600,
                         'bytesize': 8,
                         'parity': constants.Parity.none,
                         'stop_bits': constants.StopBits.one,
                         'encoding': 'ascii'
                        }}

    #: flow control flags
    #RTSCTS = False
    #DSRDTR = False
    #XONXOFF = False

    def query(self, command, *, send_args=(None, None),
              recv_args=(None, None)):
        """Send query to the laser and return the answer, after handling
        possible errors.

        :param command: command to be sent to the instrument
        :type command: string

        :param send_args: (termination, encoding) to override class defaults
        :param recv_args: (termination, encoding) to override class defaults
        """
        ans = super().query(command, send_args=send_args, recv_args=recv_args)
        # TODO: Echo handling
        code = ans[0]
        if code != 0:
            if code == '1':
                raise InstrumentError('Command invalid')
            elif code == '2':
                raise InstrumentError('Wrong number of parameters')
            elif code == '3':
                raise InstrumentError('Parameter value is out of range')
            elif code == '4':
                raise InstrumentError('Unlocking code is wrong')
            elif code == '5':
                raise InstrumentError('Device is locked for this command')
            elif code == '6':
                raise InstrumentError('This function is not supported')
            elif code == '7':
                raise InstrumentError('Timeout while reading command (60 s)')
            elif code == '8':
                raise InstrumentError('This value is currently not available')

        ans = ans[2:]
        # TODO: Code reporting?
        return ans

    @Feat(read_once=True)
    def idn(self):
        """Identification of the device
        """
        manufacturer = self.query('DM?')
        device = self.query('DT?')
        serial = self.query('DS?')
        ans = manufacturer + ', ' + device + ', serial number ' + serial
        return ans

    @Feat()
    def status(self):
        """Current device status
        """
        ans = self.query('S?')
        if ans == '0x10':
            ans = 'Temperature of laser head is ok'
        elif ans == '0x01':
            ans = 'Laser system is active, radiation can be emitted'
        elif ans == '0x02':
            ans = '(reserved)'
        elif ans == '0x04':
            ans = 'The interlock is open'
        elif ans == '0x08':
            ans = self.query('E?')
            if ans == '0x01':
                ans = 'Temperature of laser head is too high'
            elif ans == '0x02':
                ans = 'Temperature of laser head is too low'
            elif ans == '0x04':
                ans = 'Temperature-sensor connection is broken'
            elif ans == '0x08':
                ans = 'Temperature sensor cable is shortened'
            elif ans == '0x40':
                ans = 'Current for laser head is too high'
            elif ans == '0x80':
                ans = 'Internal error (laser system cannot be activated)'
        return ans

    @Feat()
    def operating_hours(self):
        """Total operating hours [hhhh:mm]
        """
        return self.query('R?')

    @Feat()
    def software_version(self):
        """Software version
        """
        return self.query('DO?')

    @Feat(read_once=True)
    def emission_wavelenght(self):
        """Emission wavelenght in nm
        """
        return self.query('DW?')

    @Feat()
    def available_features(self):
        """Available features (reserved for future use)
        """
        return self.query('DF?')

    @Feat()
    def control_mode(self):
        """Active current (power) control
        """
        ans = self.query('DC?')
        if ans == 'ACC':
            ans = 'Active current control'
        else:
            ans = 'Active power control'
        return ans

    # TEMPERATURE

    @Feat()
    def temperature(self):
        """Current temperature in ºC
        """
        return self.query('T?')

    @Feat(read_once=True)
    def temperature_min(self):
        """Lowest operating temperature in ºC
        """
        return self.query('LTN?')

    @Feat(read_once=True)
    def temperature_max(self):
        """Highest operating temperature in ºC
        """
        return self.query('LTP?')

    # ENABLED REQUEST

    @Feat(values={True: '1', False: '0'})
    def enabled(self):
        """Method for turning on the laser
        """
        return self.query('O?')

    @enabled.setter
    def enabled(self, value):
        self.query('O=' + value)

    # LASER POWER

    def initialize(self):
        super().initialize()
        self.power = 0
        self.feats.power.limits = (0, self.maximum_power.magnitude)

    @Feat(units='mW')
    def maximum_power(self):
        """Gets the maximum emission power of the laser
        """
        return float(self.query('LP?'))

    @Feat(units='mW')
    def power_sp(self):
        """Gets and sets the emission power
        """
        return float(self.query('P?'))

    @power_sp.setter
    def power(self, value):
        self.query('P={:.1f}'.format(value))

if __name__ == '__main__':
    import argparse
    import lantz.log

    parser = argparse.ArgumentParser(description='Test Kentech HRI')
    parser.add_argument('-i', '--interactive', action='store_true',
                        default=False, help='Show interactive GUI')
    parser.add_argument('-p', '--port', type=str, default='17',
                        help='Serial port to connect to')

    args = parser.parse_args()
    lantz.log.log_to_screen(lantz.log.DEBUG)
    with MiniLasEvo(args.port) as inst:
        if args.interactive:
            from lantz.ui.app import start_test_app
            start_test_app(inst)
        else:
            # Add your test code here
            print('Non interactive mode')
            """inst.power = 0
            inst.temperature
            print(inst.power)
            inst.power = 0
            print(inst.idn)
            """


text:
module Toygun
  class TaskTransition < Sequel::Model
    plugin :timestamps, update_on_create: true

    def_dataset_method :latest do
      order(:step.desc).first
    end

    def duration
      Time.now - created_at
    end
  end

  class Task < Sequel::Model
    plugin :single_table_inheritance, :name
    plugin :timestamps, update_on_create: true

    one_to_many :transitions, key: :task_uuid, primary_key: :uuid, order: Sequel.desc(:step), class: TaskTransition

    include State::InstanceMethods

    plugin ModelAttributes

    def self.state name, &block
      task_states[name] = block
      self
    end

    def self.task_states
      @task_states ||= {}
    end

    def self.has_state?(new_state)
      State.builtin_states.include?(new_state) || self.task_states.include?(new_state)
    end

    def_dataset_method :active do
        exclude(state: State::STOP)
    end

    def start(**opts)
      if state == State::NEW
        transition self.class.task_states.first[0], opts
     end
    end

    def tick
      return if state == State::STOP
      raise State::Panic if state == State::PANIC
      start if state == State::NEW

      if block = self.class.task_states[state]
        instance_eval &block
      else
        raise State::Missing, "Missing state defintion for #{state} in #{self.class}"
      end
    end

    def self.find_recent_for(resource)
      self.where(resource_uuid: resource.uuid).order_by(Sequel.desc(:created_at, nulls: :last)).first
    end

    def self.find_or_create_for(resource)
      self.db.transaction do
        if Locks.pg_try_advisory_xact_lock(self, resource.uuid)
          task = self.where(resource_uuid: resource.uuid).order_by(Sequel.desc(:created_at, nulls: :last)).first
          if task.nil?
            task = self.create(resource_uuid: resource.uuid) do |t|
              t.state = State::STOP
              t.attrs = {}
            end
          end
          task
        end
      end
    end

    def self.start_for(resource, **opts)
      db.transaction do
        if Locks.pg_try_advisory_xact_lock(self, resource.uuid)
          task = self.where(resource_uuid: resource.uuid).exclude(state: State::STOP).order_by(Sequel.desc(:created_at, nulls: :last)).first
          if task.nil?
            task = self.create(resource_uuid: resource.uuid) do |t|
              t.state = State::NEW
              t.attrs = opts
            end
          end
          task
        end
      end
    end

    def self.define_task_on(resource, name, &block)
      class_name = name.to_s.split(/_/).map{ |word| word.capitalize }.join('').sub("!","")
      resource_name = resource.to_s.split('::')[-1].split(/(?=[A-Z]+)/).map(&:downcase).join("_").to_sym

      resource.class_eval "class #{class_name} < #{self}; end"

      t = resource.const_get(class_name)

      t.class_eval do
        many_to_one :resource, class: resource, key: :resource_uuid, primary_key: :uuid
        alias_method resource_name, :resource if resource_name != 'resource'
      end

      t.class_eval &block

      resource.class_eval do
        define_method(name.to_s+"_task") do
          t.find_or_create_for(self)
        end

        def_dataset_method("#{name}_tasks") do
         t.where('resource_uuid in ?', self.select(:uuid))
        end

        define_method(name) do |**opts|
          task = t.start_for(self, **opts)
        end

        def_dataset_method("#{name}") do |**opts|
          all.each do |resource|
            t.start_for(resource, **opts)
          end
        end

        define_method(name.to_s+"_running?") do
          task = t.find_recent_for(self)
          task && task.running?
        end

        def_dataset_method("#{name}_running?") do
          t.where('foreign_uuid in ?', self.select(:uuid)).exclude(state: State::STOP).count > 0
        end
      end

      t
    end
  end
end


text:
if [ "$(id -u)" != "0" ]; then
        echo "Sorry, you are not root."
        exit 1
fi

INIT_DIR_DEST=/etc/init.d
BIN_DIR_DEST=/usr/bin

INIT_SCRIPT=./init.d_script/selena
BIN_SCRIPT=./bin/selena_agent.py

SELENA_SVC=`basename ${INIT_SCRIPT}`
SELENA_BIN=`basename ${BIN_SCRIPT}`

# Stop the selena agent from starting on boot
command -v update-rc.d >/dev/null 2>&1 || { echo "*** Couldn't find 'update-rc.d'. Make sure it is installed on your system."; exit 1; }
update-rc.d ${SELENA_SVC} remove

# Stop any running instances of Selena
service ${SELENA_SVC} status | grep running
[[ $? -eq 0 ]] && {  echo "*** Stopping gracefully the selena agent process (SIGTERM)"; service ${SELENA_SVC} stop; }
PID=`ps aux | grep python | grep ${SELENA_BIN} | awk '{print $2}'`
[[ -n "${PID}" ]] && { echo "*** Force-killing the selena agent process (SIGKILL)"; kill -9 ${PID}; }

# Remove the init script and the executable
[[ -f ${INIT_DIR_DEST}/${SELENA_SVC} ]] && rm ${INIT_DIR_DEST}/${SELENA_SVC}
[[ -f ${BIN_DIR_DEST}/${SELENA_BIN} ]] && rm ${BIN_DIR_DEST}/${SELENA_BIN}

echo "*** DONE"


text:
import { expect } from 'chai'
import { Jenkins } from '../../src/provider/Jenkins'
import { Tester } from '../Tester'

describe('/POST jenkins', () => {
    it('deploy', async () => {
        const res = await Tester.test(new Jenkins(), 'jenkins.json', null)
        expect(res).to.not.be.null
        expect(res!.embeds).to.be.an('array').that.has.length(1)
    })
})


text:
module.exports = {
  description: "",
  ns: "react-material-ui",
  type: "ReactNode",
  dependencies: {
    npm: {
      "material-ui/svg-icons/device/settings-system-daydream": require('material-ui/svg-icons/device/settings-system-daydream')
    }
  },
  name: "DeviceSettingsSystemDaydream",
  ports: {
    input: {},
    output: {
      component: {
        title: "DeviceSettingsSystemDaydream",
        type: "Component"
      }
    }
  }
}


text:
class SimplePublishing
  attr_accessor :id, :name

  def initialize(name)
    @id = 1
    @name = name
  end

  def columbo_actor
    {uid: 1, label: 'label', type: 'simple'}
  end

  def as_json
    {id: @id, name: @name}
  end
end

class PublishingWithNoActor
  include Columbo::Resource

  attr_accessor :id, :name

  def initialize(name)
    @id = 1
    @name = name
  end

  def as_json
    {id: @id, name: @name}
  end
end

class PublishingWithOverride
  include Columbo::Resource

  attr_accessor :id, :name

  def initialize(name)
    @id = 1
    @name = name
  end

  def columbo_payload
    as_json.merge({message: 'automatically added by columbo resource'})
  end

  def columbo_resource_label
    'columbo resource label override'
  end

  def columbo_actor
    {uid: 1, label: 'label', type: 'simple'}
  end

  def as_json
    {id: @id, name: @name}
  end
end


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Foundation for Sites Testing</title>
    <link href="../motion-ui/dist/motion-ui.css" rel="stylesheet" />
    <link href="../assets/css/foundation.css" rel="stylesheet" />

Breadcrumbs

Home

Features

Gene Splicing

                Current:  Cloning


text:
[![PlatformIO CI](https://github.com/mortenfyhn/coffee-scales/actions/workflows/main.yml/badge.svg)](https://github.com/mortenfyhn/coffee-scales/actions/workflows/main.yml)

Kitchen scales, built for drip coffee brewing.

* 0.1 gram precision.
* Very quick response.
* Auto-starting brew timer.

Current prototype looks something like this:

![A breadboard prototype in action](https://i.imgur.com/RPn1dWZ.jpg)

## Build and run

To build and run the code:

1. Install PlatformIO Core and shell commands: https://docs.platformio.org/en/latest/core/installation.html
2. `pio run --environment nano328 --target upload`

More environments are defined in `platformio.ini`.

## Hardware
* A 1 kg straight bar load cell connected through an HX711 load cell amplifier.
* Two 4-digit 7-segment displays driven by TM1637 LED drivers.
* An Arduino Nano, might get replaced by a suitable MCU.


text:
import * as raw from "./raw";
import Engine from "./engine";
export { Engine };
export declare function fromYAMLFilePath(configPath: string): Engine;
export declare function fromYAML(configPath: string, yamlContent: string): Engine;
export declare function fromRowConfig(configPath: string, rawConfig: raw.Config): Engine;


text:
import numpy as np
import geopy
from Greengraph.map import Map

class Greengraph(object):
    def __init__(self, start, end):
        self.start=start
        self.end=end
        self.geocoder=geopy.geocoders.GoogleV3(domain="maps.google.co.uk")
    def geolocate(self, place):
        return self.geocoder.geocode(place,exactly_one=False)[0][1]
    def location_sequence(self, start,end,steps):
        lats = np.linspace(start[0], end[0], steps)
        longs = np.linspace(start[1],end[1], steps)
        return np.vstack([lats, longs]).transpose()
    def green_between(self, steps):
        return [Map(*location).count_green()
            for location in self.location_sequence(
            self.geolocate(self.start),
            self.geolocate(self.end), steps)]


text:
package io.tetrapod.core;

import io.tetrapod.core.rpc.*;

import java.util.*;
import java.util.concurrent.*;

/**
 * Thread safe message dispatcher class.
 */
public class MessageHandlers {

   private final Map<Long, List<SubscriptionAPI>> map = new ConcurrentHashMap<>();
   private final List<SubscriptionAPI> empty = new ArrayList<>();

   public List<SubscriptionAPI> get(int contractId, int structId) {
      List<SubscriptionAPI> list = map.get(makeKey(contractId, structId));
      return list == null ? empty : list;
   }

   public void add(Contract subscription, SubscriptionAPI handler) {
      for (Structure s : subscription.getMessages()) {
         add(s, handler);
      }
   }

   public void add(Structure s, SubscriptionAPI handler) {
      List<SubscriptionAPI> list = ensure(makeKey(s.getContractId(), s.getStructId()));
      list.add(handler);
   }

   private List<SubscriptionAPI> ensure(long key) {
      List<SubscriptionAPI> list = map.get(key);
      if (list == null) {
         list = new CopyOnWriteArrayList<>(); // good for concurrent reads >> writes
         map.put(key, list);
      }
      return list;
   }

   private long makeKey(int contractId, int structId) {
      return ((long) contractId << 32) | structId;
   }

}


text:
defaults write com.apple.Finder FXPreferredViewStyle Nlsv

# Fix the lack of key repeat
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false

# Show the ~/Library folder.
chflags nohidden ~/Library


text:
class TKalmanFilter
{
	public:
		TKalmanFilter(const cv::Point3f &p, float dt = 0.05, float Accel_noise_mag = 0.5);
		cv::Point3f GetPrediction();
		cv::Point3f Update(const cv::Point3f &p);
	//	void adjustPrediction(const Eigen::Transform<double, 3, Eigen::Isometry> &delta_robot);
		void adjustPrediction(const cv::Point3f &delta_pos);
	private:
		cv::KalmanFilter kalman;
};


text:
{% for social in site.social %}

   {{ social.title }}

{% endfor %}


text:
! Stokes vector related routines
!
! ------------------------------------------------------------------------------
! Copyright (c) 2009-13, Thomas P. Robitaille
!
! All rights reserved.
!
! Redistribution and use in source and binary forms, with or without
! modification, are permitted provided that the following conditions are met:
!
!  * Redistributions of source code must retain the above copyright notice, this
!    list of conditions and the following disclaimer.
!
!  * Redistributions in binary form must reproduce the above copyright notice,
!    this list of conditions and the following disclaimer in the documentation
!    and/or other materials provided with the distribution.
!
! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
! DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
! FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
! SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
! OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
! ------------------------------------------------------------------------------

module type_stokes

  implicit none
  save

  private

  integer,parameter :: sp = selected_real_kind(p=6,r=37)
  integer,parameter :: dp = selected_real_kind(p=15,r=307)

  public :: stokes_dp
  type stokes_dp
     real(dp) :: I,U,Q,V
  end type stokes_dp

  public :: stokes_sp
  type stokes_sp
     real(sp) :: I,U,Q,V
  end type stokes_sp

  public :: operator(+)
  interface operator(+)
     module procedure add_stokes_sp
     module procedure add_stokes_dp
  end interface operator(+)

  public :: operator(-)
  interface operator(-)
     module procedure sub_stokes_sp
     module procedure sub_stokes_dp
  end interface operator(-)

  public :: operator(*)
  interface operator(*)
     module procedure scalar_stokes_mult_sp,stokes_scalar_mult_sp,stokes_stokes_mult_sp
     module procedure scalar_stokes_mult_dp,stokes_scalar_mult_dp,stokes_stokes_mult_dp
  end interface operator(*)

  public :: operator(/)
  interface operator(/)
     module procedure scalar_stokes_div_sp,stokes_scalar_div_sp
     module procedure scalar_stokes_div_dp,stokes_scalar_div_dp
  end interface operator(/)

  public :: operator(**)
  interface operator(**)
     module procedure pow_stokes_sp
     module procedure pow_stokes_dp
  end interface operator(**)

contains

  !!@FOR real(sp):sp real(dp):dp

  !**********************************************************************!
  ! Stokes addition
  !**********************************************************************!

  type(stokes_<T>) function add_stokes_<T>(a,b) result(s)

    implicit none

    type(stokes_<T>),intent(in) :: a,b

    s%I = a%I + b%I
    s%Q = a%Q + b%Q
    s%U = a%U + b%U
    s%V = a%V + b%V

  end function add_stokes_<T>

  !**********************************************************************!
  ! Stokes subtraction
  !**********************************************************************!

  type(stokes_<T>) function sub_stokes_<T>(a,b) result(s)

    implicit none

    type(stokes_<T>),intent(in) :: a,b

    s%I = a%I - b%I
    s%Q = a%Q - b%Q
    s%U = a%U - b%U
    s%V = a%V - b%V

  end function sub_stokes_<T>

  !**********************************************************************!
  ! Scalar * Stokes
  !**********************************************************************!

  type(stokes_<T>) function scalar_stokes_mult_<T>(a,b) result(s)

    implicit none

    @T,intent(in)               :: a
    type(stokes_<T>),intent(in) :: b

    s%I = a * b%I
    s%Q = a * b%Q
    s%U = a * b%U
    s%V = a * b%V

  end function scalar_stokes_mult_<T>

  type(stokes_<T>) function stokes_scalar_mult_<T>(a,b) result(s)

    implicit none

    type(stokes_<T>),intent(in) :: a
    @T,intent(in)               :: b

    s%I = a%I * b
    s%Q = a%Q * b
    s%U = a%U * b
    s%V = a%V * b

  end function stokes_scalar_mult_<T>

    type(stokes_<T>) function stokes_stokes_mult_<T>(a,b) result(s)

    implicit none

    type(stokes_<T>),intent(in) :: a, b

    s%I = a%I * b%I
    s%Q = a%Q * b%Q
    s%U = a%U * b%U
    s%V = a%V * b%V

  end function stokes_stokes_mult_<T>

  !**********************************************************************!
  ! Scalar / Stokes
  !**********************************************************************!

  type(stokes_<T>) function scalar_stokes_div_<T>(a,b) result(s)

    implicit none

    @T,intent(in)               :: a
    type(stokes_<T>),intent(in) :: b

    s%I = a / b%I
    s%Q = a / b%Q
    s%U = a / b%U
    s%V = a / b%V

  end function scalar_stokes_div_<T>

  type(stokes_<T>) function stokes_scalar_div_<T>(a,b) result(s)

    implicit none

    type(stokes_<T>),intent(in) :: a
    @T,intent(in)               :: b

    s%I = a%I / b
    s%Q = a%Q / b
    s%U = a%U / b
    s%V = a%V / b

  end function stokes_scalar_div_<T>

  !**********************************************************************!
  ! Stokes power
  !**********************************************************************!

  type(stokes_<T>) function pow_stokes_<T>(a,power) result(s)

    implicit none

    type(stokes_<T>),intent(in) :: a
    real(<T>),intent(in) :: power

    s%I = a%I ** power
    s%Q = a%Q ** power
    s%U = a%U ** power
    s%V = a%V ** power

  end function pow_stokes_<T>

  !!@END FOR

end module type_stokes


text:
description = """
Robocop, the moderation bot of ReSwitched.
"""

# import dependencies
import os
from discord.ext import commands
import discord
import datetime
import json, asyncio
import copy
import configparser
import traceback
import sys
import os
import re

# sets working directory to bot's folder
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)

# read config for token
config = configparser.ConfigParser()
config.read("config.ini")

os.makedirs("data", exist_ok=True)
# create warnsv2.json if it doesn't exist, and convert warns.json if needed
if not os.path.isfile("data/warnsv2.json"):
    if os.path.isfile("data/warns.json"):
        print("Converting warns.json to warnsv2 format")
        with open("data/warns.json", "r") as f:
            warns = json.load(f)
        warnsv2 = {}
        for user_id, info in warns.items():
            warnsv2[user_id] = {"name": info["name"], "warns": []}
            for w_idx in range(len(info["warns"])):
                warnsv2[user_id]["warns"].append(info["warns"][str(w_idx + 1)])
        with open("data/warnsv2.json", "w") as f:
            json.dump(warnsv2, f)
    else:
        with open("data/warnsv2.json", "w") as f:
            f.write("{}")

# create restrictions.json if it doesn't exist
if not os.path.isfile("data/restrictions.json"):
    with open("data/restrictions.json", "w") as f:
        f.write("{}")

# create helpers.json if it doesn't exist
if not os.path.isfile("data/helpers.json"):
    with open("data/helpers.json", "w") as f:
        f.write("{}")

# create timebans.json if it doesn't exist
if not os.path.isfile("data/timebans.json"):
    with open("data/timebans.json", "w") as f:
        f.write("{}")

prefix = ['!', '.']
bot = commands.Bot(command_prefix=prefix, description=description, pm_help=None)

bot.actions = []  # changes messages in mod-/server-logs

# http://stackoverflow.com/questions/3411771/multiple-character-replace-with-python
chars = "\\`*_<>#@:~"
def escape_name(name):
    name = str(name)
    for c in chars:
        if c in name:
            name = name.replace(c, "\\" + c)
    return name.replace("@", "@\u200b")  # prevent mentions
bot.escape_name = escape_name

bot.pruning = False  # used to disable leave logs if pruning, maybe.

# mostly taken from https://github.com/Rapptz/discord.py/blob/async/discord/ext/commands/bot.py
@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, discord.ext.commands.errors.CommandNotFound):
        pass  # ...don't need to know if commands don't exist
    if isinstance(error, discord.ext.commands.errors.CheckFailure):
        await bot.send_message(ctx.message.channel, "{} You don't have permission to use this command.".format(ctx.message.author.mention))
    elif isinstance(error, discord.ext.commands.errors.MissingRequiredArgument):
        formatter = commands.formatter.HelpFormatter()
        await bot.send_message(ctx.message.channel, "{} You are missing required arguments.\n{}".format(ctx.message.author.mention, formatter.format_help_for(ctx, ctx.command)[0]))
    else:
        if ctx.command:
            await bot.send_message(ctx.message.channel, "An error occured while processing the `{}` command.".format(ctx.command.name))
        print('Ignoring exception in command {}'.format(ctx.command), file=sys.stderr)
        traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)

bot.all_ready = False
bot._is_all_ready = asyncio.Event(loop=bot.loop)
async def wait_until_all_ready():
    """Wait until the entire bot is ready."""
    await bot._is_all_ready.wait()
bot.wait_until_all_ready = wait_until_all_ready

@bot.event
async def on_ready():
    if bot.all_ready:
        return
    # this bot should only ever be in one server anyway
    for server in bot.servers:
        print("{} has started! {} has {:,} members!".format(bot.user.name, server.name, server.member_count))
        bot.server = server

        bot.config = config

        # channels
        bot.welcome_channel = discord.utils.get(server.channels, name="newcomers")
        bot.announcements_channel = discord.utils.get(server.channels, name="news")
        bot.mods_channel = discord.utils.get(server.channels, name="server-logs")
        bot.modlogs_channel = discord.utils.get(server.channels, name="server-logs")
        bot.serverlogs_channel = discord.utils.get(server.channels, name="server-logs")

        bot.community_channels = (
            discord.utils.get(server.channels, name="switch-hacking-general"),
            discord.utils.get(server.channels, name="homebrew-development"),
            discord.utils.get(server.channels, name="off-topic"),
            discord.utils.get(server.channels, name="creative-content"),
            discord.utils.get(server.channels, name="hardware-mods")
        )

        # TODO: remove some of these roles that are useless on Reswitched. need to find their use around the bot first.
        # roles
        bot.staff_role = discord.utils.get(server.roles, name="mod")
        bot.halfop_role = discord.utils.get(server.roles, name="hop")
        bot.op_role = discord.utils.get(server.roles, name="OP")
        bot.superop_role = discord.utils.get(server.roles, name="moderator")
        bot.owner_role = discord.utils.get(server.roles, name="wizards")
        bot.unprobated_role = discord.utils.get(server.roles, name="participant")
        bot.muted_role = discord.utils.get(server.roles, name="Muted")
        bot.nohelp_role = discord.utils.get(server.roles, name="hackers")
        bot.nomemes_role = discord.utils.get(server.roles, name="No-Memes")
        bot.noembed_role = discord.utils.get(server.roles, name="No-Embed")
        bot.team_role = discord.utils.get(server.roles, name="team")

        bot.private_role = discord.utils.get(server.roles, name="private")
        bot.hacker_role = discord.utils.get(server.roles, name="hacker")
        bot.community_role = discord.utils.get(server.roles, name="community")
        bot.bot_management_role = discord.utils.get(server.roles, name='bot management')
        bot.everyone_role = server.default_role

        bot.staff_ranks = {
            "HalfOP": bot.halfop_role,
            "OP": bot.op_role,
            "moderator": bot.superop_role,
            "Wizards": bot.owner_role,
        }

        # load timebans
        with open("data/timebans.json", "r") as f:
            timebans = json.load(f)
        bot.timebans = {}
        timebans_i = copy.copy(timebans)
        for user_id, timestamp in timebans_i.items():
            found = False
            for user in await bot.get_bans(server):
                if user.id == user_id:
                    bot.timebans[user_id] = [user, datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S"), False]  # last variable is "notified", for <=30 minute notifications
                    found = True
                    break
            if not found:
                timebans.pop(user_id) # somehow not in the banned list anymore so let's just remove it
        with open("data/timebans.json", "w") as f:
            json.dump(timebans, f)

        bot.all_ready = True
        bot._is_all_ready.set()

        msg = "{} has started! {} has {:,} members!".format(bot.user.name, server.name, server.member_count)
        if len(failed_addons) != 0:
            msg += "\n\nSome addons failed to load:\n"
            for f in failed_addons:
                msg += "\n{}: `{}: {}`".format(*f)
        await bot.send_message(bot.serverlogs_channel, msg)

        break

# loads extensions
addons = [
    'addons.blah',
    'addons.events',
    'addons.extras',
    'addons.kickban',
    'addons.load',
    'addons.lockdown',
    'addons.logs',
    'addons.loop',
    'addons.mod',
    'addons.links',
    'addons.err',
    'addons.nxerr',
    'addons.mod_warn',
    'addons.probation_bot',
    'addons.meme'
]

failed_addons = []

for extension in addons:
    try:
        bot.load_extension(extension)
    except Exception as e:
        print('{} failed to load.\n{}: {}'.format(extension, type(e).__name__, e))
        failed_addons.append([extension, type(e).__name__, e])

# Execute
print('Bot directory: ', dir_path)
bot.run(config['Main']['token'])


text:
<?php

namespace Test\Namespace;

class testRuleNotAppliesToMethodWithinNamespaceByDefault {
    public function __construct($test = 'Test') {
        var_dump($test);
    }
}


text:
layout: post
title: "angular-zxcvbn v1.0.0"
categories:
- English
- angular
- javascript
- directive
- zxcvbn
---
I wrote a very simple `angular.js` directive for the [`zxcvbn` library](https://github.com/dropbox/zxcvbn).

You can give it a try with a live demo on [`plnkr`](http://plnkr.co/9wTZgR) and grab the code either from [github](https://github.com/ghostbar/angular-zxcvbn) or install it with:

    bower install angular-zxcvbn


text:
<?php

namespace Neokike\LaravelElasticsearchQueryBuilder\Queries\Boosting;

use Neokike\LaravelElasticsearchQueryBuilder\Exceptions\DuplicatedSearchConstraintException;
use Neokike\LaravelElasticsearchQueryBuilder\Exceptions\InvalidArgumentException;
use Neokike\LaravelElasticsearchQueryBuilder\Exceptions\NotEnoughArgumentsException;
use Neokike\LaravelElasticsearchQueryBuilder\Interfaces\QueryInterface;

class BoostingQuery implements QueryInterface
{
    protected $positive;
    protected $negative;
    /**
     * @var null
     */
    private $negative_boost;

    public function __construct($negative_boost)
    {
        if (!is_float($negative_boost))
            throw new InvalidArgumentException('the negative boost must be a float value');

        $this->negative_boost = $negative_boost;
    }

    public function setPositive($query)
    {
        if (!$query instanceof QueryInterface)
            throw new InvalidArgumentException;

        if ($this->positive)
            throw new DuplicatedSearchConstraintException('positive condition have been already defined');

        $this->positive = $query;

        return $this;
    }

    public function setNegative($query)
    {
        if (!$query instanceof QueryInterface)
            throw new InvalidArgumentException;

        if ($this->negative)
            throw new DuplicatedSearchConstraintException('negative condition have been already defined');

        $this->negative = $query;

        return $this;
    }

    public function toArray()
    {
        if (!$this->positive || !$this->negative || !$this->negative_boost)
            throw new NotEnoughArgumentsException('You have to define positive, negative and negative boost in the boosting query');

        return [
            'boosting' => [
                'positive'       => $this->positive->toArray(),
                'negative'       => $this->negative->toArray(),
                'negative_boost' => $this->negative_boost
            ]
        ];
    }

    public function toJson()
    {
        return json_encode($this->toArray());
    }

    /**
     * get property value
     * @param $propertyName
     * @return $this->$propertyName || null
     */
    public function __get($propertyName)
    {
        if (property_exists($this, $propertyName)) {
            return $this->$propertyName;
        }

        return null;
    }
}


text:
import { inject, async, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { StackedBarChartComponent } from './stacked-bar-chart';
import { CommonService } from '../../shared/common.service';
import { MockCommonService } from "../../testing/common-service-mock";

let comp: StackedBarChartComponent;
let fixture: ComponentFixture<StackedBarChartComponent>;
let de: DebugElement;
let el: HTMLElement;
let commonService, spy;
let windowMock: Window = <any>{
    uv: {
        chart: function() {
            return 'stacked-bar-chart called';
        }
    }
};
let window;

describe('stacked bar chart component', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [StackedBarChartComponent],
            providers: [
                { provide: CommonService, useClass: MockCommonService },
                { provide: Window, useValue: windowMock }
            ]
        });
        fixture = TestBed.createComponent(StackedBarChartComponent);
        comp = fixture.componentInstance;

        // commonService actually injected into the component
        commonService = fixture.debugElement.injector.get(CommonService);
        window = fixture.debugElement.injector.get(Window);

        de = fixture.debugElement.query(By.css('#stacked-bar-div'));
        el = de.nativeElement;
    });

    it('should verify that the component is blank before ngOnInit fires', () => {
        expect(el.textContent).toBeFalsy();
    });

    it('should verify that the component contains the graph after ngOnInit', () => {
        // console.log('Window.uv.chart: ' + window.uv.chart);
        // fixture.detectChanges();
        // let svg = fixture.debugElement.query(By.css('svg'));
        // expect(svg).toBeDefined();
    });

});


text:
\newcolumntype{s}{>{\hsize=.21\hsize}X}
\newcolumntype{f}{>{\hsize=.37\hsize}X}
\newcolumntype{m}{>{\hsize=.42\hsize}X}

\begin{longtable}{s f m X}
				\rowcolor{orange!85} Version & Date & Author & Description \\
				\endhead
				1.0.0 & 2016-05-12 & \emph{Responsible} \newline Bonato Paolo & Document approved. \\
				0.1.0 & 2016-05-12 & \emph{Verifier} \newline Padovan Paolo & Document verified. \\
				0.0.2 & 2016-05-12 & \emph{Designer} \newline Bortolazzo Matteo & Document completed. \\
				0.0.1 & 2016-05-11 & \emph{Designer} \newline Maino Elia & Created document structure, written the introduction and the server application section. \\
				\bottomrule
			\caption{History log}
\end{longtable}


text:
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using ProBuilder2.Common;
using ProBuilder2.MeshOperations;
using System.Linq;

namespace ProBuilder2.EditorCommon
{

	/**
	 * When building the project, remove all references to pb_Objects.
	 */
	public class pb_ScenePostProcessor
	{
		[PostProcessScene]
		public static void OnPostprocessScene()
		{
			Material invisibleFaceMaterial = (Material)Resources.Load("Materials/InvisibleFace");

			/**
			 * Hide nodraw faces if present.
			 */
			foreach(pb_Object pb in GameObject.FindObjectsOfType(typeof(pb_Object)))
			{
				if(pb.GetComponent<MeshRenderer>() == null)
					continue;

				if( pb.GetComponent<MeshRenderer>().sharedMaterials.Any(x => x != null && x.name.Contains("NoDraw")) )
				{
					Material[] mats = pb.GetComponent<MeshRenderer>().sharedMaterials;

					for(int i = 0; i < mats.Length; i++)
					{
						if(mats[i].name.Contains("NoDraw"))
							mats[i] = invisibleFaceMaterial;
					}

					pb.GetComponent<MeshRenderer>().sharedMaterials = mats;
				}
			}

			if(EditorApplication.isPlayingOrWillChangePlaymode)
				return;

			foreach(pb_Object pb in GameObject.FindObjectsOfType(typeof(pb_Object)))
			{
				GameObject go = pb.gameObject;

				pb_Entity entity = pb.gameObject.GetComponent<pb_Entity>();

				if( entity == null )
					continue;

				if(entity.entityType == EntityType.Collider || entity.entityType == EntityType.Trigger)
					go.GetComponent<MeshRenderer>().enabled = false;

				// clear hideflags on prefab meshes
				if(pb.msh != null)
					pb.msh.hideFlags = HideFlags.None;

				if(!pb_Preferences_Internal.GetBool(pb_Constant.pbStripProBuilderOnBuild))
				   return;

				pb.dontDestroyMeshOnDelete = true;

				GameObject.DestroyImmediate( pb );
				GameObject.DestroyImmediate( go.GetComponent<pb_Entity>() );

			}
		}
	}
}