text:
// The URL:true below prevents jshint error "Redefinition or 'URL'."
/* globals URL:true */

var path          = require('path'),
    _             = require('underscore'),
    fs            = require('fs'),
    shell         = require('shelljs'),
    platforms     = require('../platforms/platforms'),
    events        = require('cordova-common').events,
    request       = require('request'),
    config        = require('./config'),
    HooksRunner   = require('../hooks/HooksRunner'),
    zlib          = require('zlib'),
    tar           = require('tar'),
    URL           = require('url'),
    Q             = require('q'),
    npm           = require('npm'),
    npmhelper     = require('../util/npm-helper'),
    unpack        = require('../util/unpack'),
    util          = require('./util'),
    gitclone      = require('../gitclone'),
    stubplatform  = {
        url    : undefined,
        version: undefined,
        altplatform: undefined,
        subdirectory: ''
    };

exports.cordova = cordova;
exports.cordova_git = cordova_git;
exports.git_clone = git_clone_platform;
exports.cordova_npm = cordova_npm;
exports.npm_cache_add = npm_cache_add;
exports.custom = custom;
exports.based_on_config = based_on_config;

function Platform(platformString) {
    var name,
        platform,
        parts,
        version;
    if (platformString.indexOf('@') != -1) {
        parts = platformString.split('@');
        name = parts[0];
        version = parts[1];
    } else {
        name = platformString;
    }
    platform = _.extend({}, platforms[name]);
    this.name = name;
    this.version = version || platform.version;
    this.packageName = 'cordova-' + name;
    this.source = 'source' in platform ? platform.source : 'npm';
}

// Returns a promise for the path to the lazy-loaded directory.
function based_on_config(project_root, platform, opts) {
    var custom_path = config.has_custom_path(project_root, platform);
    if (custom_path) {
        var dot_file = config.read(project_root),
            mixed_platforms = _.extend({}, platforms);
        mixed_platforms[platform] = _.extend({}, mixed_platforms[platform], dot_file.lib && dot_file.lib[platform] || {});
        return module.exports.custom(mixed_platforms, platform);
    } else {
        return module.exports.cordova(platform, opts);
    }
}

// Returns a promise for the path to the lazy-loaded directory.
function cordova(platform, opts) {
    platform = new Platform(platform);
    var use_git = platform.source === 'git';
    if ( use_git ) {
        return module.exports.cordova_git(platform);
    } else {
        return module.exports.cordova_npm(platform);
    }
}

function cordova_git(platform) {
    var mixed_platforms = _.extend({}, platforms),
        plat;
    if (!(platform.name in platforms)) {
        return Q.reject(new Error('Cordova library "' + platform.name + '" not recognized.'));
    }
    plat = mixed_platforms[platform.name];
    plat.id = 'cordova';

    // We can't use a version range when getting from git, so if we have a range, find the latest release on npm that matches.
    return util.getLatestMatchingNpmVersion(platform.packageName, platform.version).then(function (version) {
        plat.version = version;
        if (/^...*:/.test(plat.url)) {
            plat.url = plat.url + ';a=snapshot;h=' + version + ';sf=tgz';
        }
        return module.exports.custom(mixed_platforms, platform.name);
    });
}

function cordova_npm(platform) {
    if ( !(platform.name in platforms) ) {
        return Q.reject(new Error('Cordova library "' + platform.name + '" not recognized.'));
    }
    // Check if this version was already downloaded from git, if yes, use that copy.
    // TODO: remove this once we fully switch to npm workflow.
    var platdir = platforms[platform.name].altplatform || platform.name;
    // If platform.version specifies a *range*, we need to determine what version we'll actually get from npm (the
    // latest version that matches the range) to know what local directory to look for.
    return util.getLatestMatchingNpmVersion(platform.packageName, platform.version).then(function (version) {
        var git_dload_dir = path.join(util.libDirectory, platdir, 'cordova', version);
        if (fs.existsSync(git_dload_dir)) {
            var subdir = platforms[platform.name].subdirectory;
            if (subdir) {
                git_dload_dir = path.join(git_dload_dir, subdir);
            }
            events.emit('verbose', 'Platform files for "' + platform.name + '" previously downloaded not from npm. Using that copy.');
            return Q(git_dload_dir);
        }

        // Note that because the version of npm we use internally doesn't support caret versions, in order to allow them
        // from the command line and in config.xml, we use the actual version returned by getLatestMatchingNpmVersion().
        var pkg = platform.packageName + '@' + version;
        return exports.npm_cache_add(pkg);
    });
}

// Equivalent to a command like
// npm cache add cordova-android@3.5.0
// Returns a promise that resolves to directory containing the package.
function npm_cache_add(pkg) {
    var npm_cache_dir = path.join(util.libDirectory, 'npm_cache');
    // 'cache-min' is the time in seconds npm considers the files fresh and
    // does not ask the registry if it got a fresher version.
    var platformNpmConfig = {
        'cache-min': 3600*24,
        cache: npm_cache_dir
    };

    return npmhelper.loadWithSettingsThenRestore(platformNpmConfig, function () {
        return Q.ninvoke(npm.commands, 'cache', ['add', pkg])
        .then(function (info) {
            var pkgDir = path.resolve(npm.cache, info.name, info.version, 'package');
            // Unpack the package that was added to the cache (CB-8154)
            var package_tgz = path.resolve(npm.cache, info.name, info.version, 'package.tgz');
            return unpack.unpackTgz(package_tgz, pkgDir);
        });
    });
}

// Returns a promise for the path to the lazy-loaded directory.
function custom(platforms, platform) {
    var plat;
    var id;
    var uri;
    var url;
    var version;
    var subdir;
    var platdir;
    var download_dir;
    var tmp_dir;
    var lib_dir;
    var isUri;
    if (!(platform in platforms)) {
        return Q.reject(new Error('Cordova library "' + platform + '" not recognized.'));
    }

    plat = _.extend({}, stubplatform, platforms[platform]);
    version = plat.version;
    // Older tools can still provide uri (as opposed to url) as part of extra
    // config to create, it should override the default url provided in
    // platfroms.js
    url = plat.uri || plat.url;
    id = plat.id;
    subdir = plat.subdirectory;
    platdir = plat.altplatform || platform;
    // Return early for already-cached remote URL, or for local URLs.
    uri = URL.parse(url);
    isUri = uri.protocol && uri.protocol[1] != ':'; // second part of conditional is for awesome windows support. fuuu windows
    if (isUri) {
        download_dir = path.join(util.libDirectory, platdir, id, version);
        lib_dir = path.join(download_dir, subdir);
        if (fs.existsSync(download_dir)) {
            events.emit('verbose', id + ' library for "' + platform + '" already exists. No need to download. Continuing.');
            return Q(lib_dir);
        }
    } else {
        // Local path.
        lib_dir = path.join(url, subdir);
        return Q(lib_dir);
    }

    return HooksRunner.fire('before_library_download', {
        platform:platform,
        url:url,
        id:id,
        version:version
    }).then(function() {
        var uri = URL.parse(url);
        var d = Q.defer();
        npm.load(function(err) {
            // Check if NPM proxy settings are set. If so, include them in the request() call.
            var proxy;
            if (uri.protocol == 'https:') {
                proxy = npm.config.get('https-proxy');
            } else if (uri.protocol == 'http:') {
                proxy = npm.config.get('proxy');
            }
            var strictSSL = npm.config.get('strict-ssl');

            // Create a tmp dir. Using /tmp is a problem because it's often on a different partition and sehll.mv()
            // fails in this case with "EXDEV, cross-device link not permitted".
            var tmp_subidr = 'tmp_' + id + '_' + process.pid + '_' + (new Date()).valueOf();
            tmp_dir = path.join(util.libDirectory, 'tmp', tmp_subidr);
            shell.rm('-rf', tmp_dir);
            shell.mkdir('-p', tmp_dir);

            var size = 0;
            var request_options = {url:url};
            if (proxy) {
                request_options.proxy = proxy;
            }
            if (typeof strictSSL == 'boolean') {
                request_options.strictSSL = strictSSL;
            }
            events.emit('verbose', 'Requesting ' + JSON.stringify(request_options) + '...');
            events.emit('log', 'Downloading ' + id + ' library for ' + platform + '...');
            var req = request.get(request_options, function(err, res, body) {
                if (err) {
                    shell.rm('-rf', tmp_dir);
                    d.reject(err);
                } else if (res.statusCode != 200) {
                    shell.rm('-rf', tmp_dir);
                    d.reject(new Error('HTTP error ' + res.statusCode + ' retrieving version ' + version + ' of ' + id + ' for ' + platform));
                } else {
                    size = body.length;
                }
            });
            req.pipe(zlib.createUnzip())
            .on('error', function(err) {
                // Sometimes if the URL is bad (most likely unavailable version), and git-wip-us.apache.org is
                // particularly slow at responding, we hit an error because of bad data piped to zlib.createUnzip()
                // before we hit the request.get() callback above (with a 404 error). Handle that gracefully. It is
                // likely that we will end up calling d.reject() for an HTTP error in the request() callback above, but
                // in case not, reject with a useful error here.
                d.reject(new Error('Unable to fetch platform ' + platform + '@' + version + ': Error: version not found.'));
            })
            .pipe(tar.Extract({path:tmp_dir}))
            .on('error', function(err) {
                shell.rm('-rf', tmp_dir);
                d.reject(err);
            })
            .on('end', function() {
                events.emit('verbose', 'Downloaded, unzipped and extracted ' + size + ' byte response.');
                events.emit('log', 'Download complete');
                var entries = fs.readdirSync(tmp_dir);
                var entry = path.join(tmp_dir, entries[0]);
                shell.mkdir('-p', download_dir);
                shell.mv('-f', path.join(entry, '*'), download_dir);
                shell.rm('-rf', tmp_dir);
                d.resolve(HooksRunner.fire('after_library_download', {
                    platform:platform,
                    url:url,
                    id:id,
                    version:version,
                    path: lib_dir,
                    size:size,
                    symlink:false
                }));
            });
        });
        return d.promise.then(function () { return lib_dir; });
    });
}

// Returns a promise
function git_clone_platform(git_url, branch) {
    // Create a tmp dir. Using /tmp is a problem because it's often on a different partition and sehll.mv()
    // fails in this case with "EXDEV, cross-device link not permitted".
    var tmp_subidr = 'tmp_cordova_git_' + process.pid + '_' + (new Date()).valueOf();
    var tmp_dir = path.join(util.libDirectory, 'tmp', tmp_subidr);
    shell.rm('-rf', tmp_dir);
    shell.mkdir('-p', tmp_dir);

    return HooksRunner.fire('before_platform_clone', {
        repository: git_url,
        location: tmp_dir
    }).then(function () {
        var branchToCheckout = branch || 'master';
        return gitclone.clone(git_url, branchToCheckout, tmp_dir);
    }).then(function () {
        HooksRunner.fire('after_platform_clone', {
            repository: git_url,
            location: tmp_dir
        });
        return tmp_dir;
    }).fail(function (err) {
        shell.rm('-rf', tmp_dir);
        return Q.reject(err);
    });
}


text:
<?php

namespace Acme\HellooBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AcmeHellooBundle extends Bundle
{
}

redpajama_set_name: RedPajamaGithub


text:
from jax.numpy import fft as fft
from jax.numpy import linalg as linalg

from jax._src.device_array import DeviceArray as DeviceArray

from jax._src.numpy.lax_numpy import (
    ComplexWarning as ComplexWarning,
    NINF as NINF,
    NZERO as NZERO,
    PZERO as PZERO,
    allclose as allclose,
    angle as angle,
    append as append,
    apply_along_axis as apply_along_axis,
    apply_over_axes as apply_over_axes,
    arange as arange,
    argmax as argmax,
    argmin as argmin,
    argsort as argsort,
    argwhere as argwhere,
    around as around,
    array as array,
    array_equal as array_equal,
    array_equiv as array_equiv,
    array_repr as array_repr,
    array_split as array_split,
    array_str as array_str,
    asarray as asarray,
    atleast_1d as atleast_1d,
    atleast_2d as atleast_2d,
    atleast_3d as atleast_3d,
    bartlett as bartlett,
    bfloat16 as bfloat16,
    bincount as bincount,
    blackman as blackman,
    block as block,
    bool_ as bool_,
    broadcast_arrays as broadcast_arrays,
    broadcast_shapes as broadcast_shapes,
    broadcast_to as broadcast_to,
    can_cast as can_cast,
    cdouble as cdouble,
    character as character,
    choose as choose,
    clip as clip,
    column_stack as column_stack,
    complex128 as complex128,
    complex64 as complex64,
    complex_ as complex_,
    complexfloating as complexfloating,
    compress as compress,
    concatenate as concatenate,
    convolve as convolve,
    copy as copy,
    corrcoef as corrcoef,
    correlate as correlate,
    cov as cov,
    cross as cross,
    csingle as csingle,
    delete as delete,
    diag as diag,
    diagflat as diagflat,
    diag_indices as diag_indices,
    diag_indices_from as diag_indices_from,
    diagonal as diagonal,
    diff as diff,
    digitize as digitize,
    dot as dot,
    double as double,
    dsplit as dsplit,
    dstack as dstack,
    dtype as dtype,
    e as e,
    ediff1d as ediff1d,
    einsum as einsum,
    einsum_path as einsum_path,
    empty as empty,
    empty_like as empty_like,
    euler_gamma as euler_gamma,
    expand_dims as expand_dims,
    extract as extract,
    eye as eye,
    finfo as finfo,
    fix as fix,
    flatnonzero as flatnonzero,
    flexible as flexible,
    flip as flip,
    fliplr as fliplr,
    flipud as flipud,
    float16 as float16,
    float32 as float32,
    float64 as float64,
    float_ as float_,
    floating as floating,
    fmax as fmax,
    fmin as fmin,
    frombuffer as frombuffer,
    fromfile as fromfile,
    fromfunction as fromfunction,
    fromiter as fromiter,
    fromstring as fromstring,
    from_dlpack as from_dlpack,
    full as full,
    full_like as full_like,
    gcd as gcd,
    generic as generic,
    geomspace as geomspace,
    get_printoptions as get_printoptions,
    gradient as gradient,
    hamming as hamming,
    hanning as hanning,
    histogram as histogram,
    histogram_bin_edges as histogram_bin_edges,
    histogram2d as histogram2d,
    histogramdd as histogramdd,
    hsplit as hsplit,
    hstack as hstack,
    i0 as i0,
    identity as identity,
    iinfo as iinfo,
    indices as indices,
    inexact as inexact,
    inf as inf,
    inner as inner,
    insert as insert,
    int16 as int16,
    int32 as int32,
    int64 as int64,
    int8 as int8,
    int_ as int_,
    integer as integer,
    interp as interp,
    isclose as isclose,
    iscomplex as iscomplex,
    iscomplexobj as iscomplexobj,
    isreal as isreal,
    isrealobj as isrealobj,
    isscalar as isscalar,
    issubdtype as issubdtype,
    issubsctype as issubsctype,
    iterable as iterable,
    ix_ as ix_,
    kaiser as kaiser,
    kron as kron,
    lcm as lcm,
    lexsort as lexsort,
    linspace as linspace,
    load as load,
    logspace as logspace,
    mask_indices as mask_indices,
    matmul as matmul,
    median as median,
    meshgrid as meshgrid,
    moveaxis as moveaxis,
    msort as msort,
    nan as nan,
    nan_to_num as nan_to_num,
    nanargmax as nanargmax,
    nanargmin as nanargmin,
    nanmedian as nanmedian,
    nanpercentile as nanpercentile,
    nanquantile as nanquantile,
    ndarray as ndarray,
    ndim as ndim,
    newaxis as newaxis,
    nonzero as nonzero,
    number as number,
    object_ as object_,
    ones as ones,
    ones_like as ones_like,
    outer as outer,
    packbits as packbits,
    pad as pad,
    percentile as percentile,
    pi as pi,
    piecewise as piecewise,
    place as place,
    printoptions as printoptions,
    promote_types as promote_types,
    put as put,
    quantile as quantile,
    ravel as ravel,
    ravel_multi_index as ravel_multi_index,
    repeat as repeat,
    reshape as reshape,
    resize as resize,
    result_type as result_type,
    roll as roll,
    rollaxis as rollaxis,
    rot90 as rot90,
    round as round,
    round_ as round_,
    row_stack as row_stack,
    save as save,
    savez as savez,
    searchsorted as searchsorted,
    select as select,
    set_printoptions as set_printoptions,
    shape as shape,
    signedinteger as signedinteger,
    single as single,
    size as size,
    sort as sort,
    sort_complex as sort_complex,
    split as split,
    squeeze as squeeze,
    stack as stack,
    swapaxes as swapaxes,
    take as take,
    take_along_axis as take_along_axis,
    tensordot as tensordot,
    tile as tile,
    trace as trace,
    trapz as trapz,
    transpose as transpose,
    tri as tri,
    tril as tril,
    tril_indices as tril_indices,
    tril_indices_from as tril_indices_from,
    trim_zeros as trim_zeros,
    triu as triu,
    triu_indices as triu_indices,
    triu_indices_from as triu_indices_from,
    trunc as trunc,
    uint as uint,
    uint16 as uint16,
    uint32 as uint32,
    uint64 as uint64,
    uint8 as uint8,
    unpackbits as unpackbits,
    unravel_index as unravel_index,
    unsignedinteger as unsignedinteger,
    unwrap as unwrap,
    vander as vander,
    vdot as vdot,
    vsplit as vsplit,
    vstack as vstack,
    where as where,
    zeros as zeros,
    zeros_like as zeros_like,
    _NOT_IMPLEMENTED,
)

from jax._src.numpy.index_tricks import (
  c_ as c_,
  index_exp as index_exp,
  mgrid as mgrid,
  ogrid as ogrid,
  r_ as r_,
  s_ as s_,
)

from jax._src.numpy.polynomial import (
    poly as poly,
    polyadd as polyadd,
    polyder as polyder,
    polydiv as polydiv,
    polyfit as polyfit,
    polyint as polyint,
    polymul as polymul,
    polysub as polysub,
    polyval as polyval,
    roots as roots,
)

from jax._src.numpy.reductions import (
    alltrue as alltrue,
    amin as amin,
    amax as amax,
    any as any,
    all as all,
    average as average,
    count_nonzero as count_nonzero,
    cumsum as cumsum,
    cumprod as cumprod,
    cumproduct as cumproduct,
    max as max,
    mean as mean,
    min as min,
    nancumsum as nancumsum,
    nancumprod as nancumprod,
    nanmax as nanmax,
    nanmean as nanmean,
    nanmin as nanmin,
    nanprod as nanprod,
    nanstd as nanstd,
    nansum as nansum,
    nanvar as nanvar,
    prod as prod,
    product as product,
    ptp as ptp,
    sometrue as sometrue,
    std as std,
    sum as sum,
    var as var,
)

from jax._src.numpy.setops import (
    in1d as in1d,
    intersect1d as intersect1d,
    isin as isin,
    setdiff1d as setdiff1d,
    setxor1d as setxor1d,
    union1d as union1d,
    unique as unique,
)

from jax._src.numpy.ufuncs import (
    abs as abs,
    absolute as absolute,
    add as add,
    arccos as arccos,
    arccosh as arccosh,
    arcsin as arcsin,
    arcsinh as arcsinh,
    arctan as arctan,
    arctan2 as arctan2,
    arctanh as arctanh,
    bitwise_and as bitwise_and,
    bitwise_not as bitwise_not,
    bitwise_or as bitwise_or,
    bitwise_xor as bitwise_xor,
    cbrt as cbrt,
    ceil as ceil,
    conj as conj,
    conjugate as conjugate,
    copysign as copysign,
    cos as cos,
    cosh as cosh,
    deg2rad as deg2rad,
    degrees as degrees,
    divide as divide,
    divmod as divmod,
    equal as equal,
    exp as exp,
    exp2 as exp2,
    expm1 as expm1,
    fabs as fabs,
    float_power as float_power,
    floor as floor,
    floor_divide as floor_divide,
    fmod as fmod,
    frexp as frexp,
    greater as greater,
    greater_equal as greater_equal,
    heaviside as heaviside,
    hypot as hypot,
    imag as imag,
    invert as invert,
    isfinite as isfinite,
    isinf as isinf,
    isnan as isnan,
    isneginf as isneginf,
    isposinf as isposinf,
    ldexp as ldexp,
    left_shift as left_shift,
    less as less,
    less_equal as less_equal,
    log as log,
    log10 as log10,
    log1p as log1p,
    log2 as log2,
    logaddexp as logaddexp,
    logaddexp2 as logaddexp2,
    logical_and as logical_and,
    logical_not as logical_not,
    logical_or as logical_or,
    logical_xor as logical_xor,
    maximum as maximum,
    minimum as minimum,
    mod as mod,
    modf as modf,
    multiply as multiply,
    negative as negative,
    nextafter as nextafter,
    not_equal as not_equal,
    positive as positive,
    power as power,
    rad2deg as rad2deg,
    radians as radians,
    real as real,
    reciprocal as reciprocal,
    remainder as remainder,
    right_shift as right_shift,
    rint as rint,
    sign as sign,
    signbit as signbit,
    sin as sin,
    sinc as sinc,
    sinh as sinh,
    sqrt as sqrt,
    square as square,
    subtract as subtract,
    tan as tan,
    tanh as tanh,
    true_divide as true_divide,
)

from jax._src.numpy.vectorize import vectorize as vectorize

# Module initialization is encapsulated in a function to avoid accidental
# namespace pollution.
def _init():
  import numpy as np
  from jax._src.numpy import lax_numpy
  from jax._src import util
  # Builds a set of all unimplemented NumPy functions.
  for name, func in util.get_module_functions(np).items():
    if name not in globals():
      _NOT_IMPLEMENTED.append(name)
      globals()[name] = lax_numpy._not_implemented(func, module='numpy')

_init()
del _init


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2017 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

  <include layout="@layout/design_content_appbar_toolbar_collapse_pin"/>

  <com.google.android.material.floatingactionbutton.FloatingActionButton
      android:id="@+id/fab"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="bottom|left"
      android:clickable="true"
      app:layout_insetEdge="left"
      app:srcCompat="@drawable/vector_icon"
      tools:ignore="RtlHardcoded"/>

  <com.google.android.material.floatingactionbutton.FloatingActionButton
      android:id="@+id/fab2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="bottom|left"
      android:clickable="true"
      app:layout_dodgeInsetEdges="left"
      app:srcCompat="@drawable/vector_icon"
      tools:ignore="RtlHardcoded"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
/**
 * This package contains all interfaces related to transformation operators.
 */
package org.gradoop.dataintegration.transformation.impl;


text:
@interface SineMover : NSObject

@property (nonatomic) CGFloat time;
@property (nonatomic) CGFloat currentValue;
@property (nonatomic) CGFloat frequency;
@property (nonatomic) CGFloat amplitude;

- (float)deltaMovement:(NSTimeInterval)interval;

@end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>SpartaHack</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" type="image/png" href="img/favicon.png">

        <link href='http://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

        <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/site.css">

SPARTAHACK

march 27th - 29th

            Apply

            SPONSOR
            CONTACT US

                SpartaHack is Michigan State University's official hackathon.
                For one weekend, 300 students from a wide range of disciplines and
                skill levels will team up to build creative, innovative technological
                projects from scratch.

                When is SpartaHack?

                Spartahack will take place from Friday, March 27th until Sunday,
                March 29th. You'll have 36 hours to design, code, and build.

                Do I need to know how to code?

                Not at all!  We welcome a wide range of skill levels,
                from newcomer to the experienced programmer.
                Hackathons are a great place to learn a new skill!

                Who can participate?

                Participation is limited to students or those who have
                left school within 2014-2015 school year. As of right now,
                we aren't accepting participants under 18 years of age,
                but we'll keep you updated if that changes!

                How do I register?

                We are now accepting applicants! Head on over to our
                registration page
                to sign up. We look forward to seeing you at SpartaHack!

                Are there registration costs?

                SpartaHack, just like America, is free! We'll feed you, clothe
                you (in a single t-shirt - so bring pants) and deck you out in swag.

                How many students can be on a team?

                Teams can consist of 1 - 4 students. If you don't have a team:
                don't worry! We'll have team formation options on-site.

                Are there prizes?

                Absolutely!  Prizes are awarded for many categories, from the
                Grand Prize, to the Best Use of API.  There is even a First-Time Hacker Prize!

                Can I start the project before the weekend?

                Unfortunately not.  You are welcome to come with ideas beforehand,
                but all your work must be done on site (don't worry, you'll have 36 hours).

                Will you reimburse my travel?

                We are hoping to have an answer to this soon.
                Check back to our website for updates.

                What should I bring?

                You will need a laptop, a student ID/picture ID, toiletries,
                and, of course, your enthusiasm for the weekend.

                How is the hackathon judged?

                Judging will be done by experienced professionals in the industry.
                More details to be released closer to the event!

                Who is organizing this event?

                SpartaHack is organized by a group of Michigan State University students
                dedicated to inspiring more students to get excited about technical innovation.

                Where should I direct further questions?

                Shoot us an email at
                hello@spartahack.com
                if you have any questions or concerns.

Sponsors

            Baked with  by the SpartaHack web team.
            ©, Spartan Hackers.


text:
namespace Thinker {

void NeuralNetwork::print_layers() const
{
    DEBUG("\nInputs [%d nodes]: ", n_inputs);
    print(input_layer);
    DEBUG("Hidden [%d nodes]: ", n_hidden);
    print(hidden_layer);
    DEBUG("Output [%d nodes]: ", n_outputs);
    print(output_layer);
    DEBUG("\n");
}

void NeuralNetwork::print_weights() const
{
    DEBUG("\nInput-to-hidden weights:");
    print(input_weights);
    DEBUG("\nHidden-to-output weights:");
    print(output_weights);
    DEBUG("\nInput-to-hidden deltas:");
    print(hidden_feedback);
    DEBUG("\nHidden-to-output deltas:");
    print(output_feedback);
}

void NeuralNetwork::print(const nerve& n) const
{
    for (unsigned i = 0; i < n.size(); i++) {
        DEBUG("%f ", n[i]);
    }
    DEBUG("\n");
}

void NeuralNetwork::print(const synapse& s) const
{
    for (unsigned i = 0; i < s.size(); i++) {
        for (unsigned j = 0; j < s[i].size(); j++) {
            DEBUG("%f ", s[i][j]);
        }
        DEBUG("\n");
    }
    DEBUG("\n");
}

} // Thinker


text:
class ContainerImage < ApplicationRecord
  include ComplianceMixin
  include MiqPolicyMixin
  include ScanningMixin
  include TenantIdentityMixin

  DOCKER_IMAGE_PREFIX = "docker://"

  belongs_to :container_image_registry
  belongs_to :ext_management_system, :foreign_key => "ems_id"
  has_many :containers
  has_many :container_nodes, -> { distinct }, :through => :containers
  has_many :container_groups, -> { distinct }, :through => :containers
  has_many :container_projects, -> { distinct }, :through => :container_groups
  has_many :guest_applications, :dependent => :destroy
  has_one :computer_system, :as => :managed_entity, :dependent => :destroy
  has_one :operating_system, :through => :computer_system
  has_one :openscap_result, :dependent => :destroy
  has_many :openscap_rule_results, :through => :openscap_result

  serialize :exposed_ports, Hash
  serialize :environment_variables, Hash

  # Needed for scanning & tagging action
  delegate :my_zone, :to => :ext_management_system

  acts_as_miq_taggable
  virtual_column :display_registry, :type => :string

  after_create :raise_creation_event

  def full_name
    result = ""
    result << "#{container_image_registry.full_name}/" unless container_image_registry.nil?
    result << name
    result << ":#{tag}" unless tag.nil?
    result << "@#{digest}" unless digest.nil?
    result
  end

  def operating_system=(value)
    create_computer_system if computer_system.nil?
    computer_system.operating_system = value
  end

  def docker_id
    if image_ref.start_with?(DOCKER_IMAGE_PREFIX)
      return image_ref[DOCKER_IMAGE_PREFIX.length..-1]
    end
  end

  # The guid is required by the smart analysis infrastructure
  alias_method :guid, :docker_id

  def display_registry
    container_image_registry.present? ? container_image_registry.full_name : _("Unknown image source")
  end

  def scan
    ext_management_system.scan_job_create(self)
  end

  def perform_metadata_scan(ost)
    update!(:last_scan_attempt_on => Time.zone.now.utc)
    miq_cnt_group = ext_management_system.scan_entity_create(ost.scanData)
    # TODO: update smart state infrastructure with a better name
    # than scan_via_miq_vm
    scan_via_miq_vm(miq_cnt_group, ost)
  end

  def raise_creation_event
    MiqEvent.raise_evm_event(self, 'containerimage_created', {})
  end

  def has_compliance_policies?
    _, plist = MiqPolicy.get_policies_for_target(self, "compliance", "containerimage_compliance_check")
    !plist.blank?
  end

  def annotate_deny_execution(causing_policy)
    # TODO: support sti and replace check with inplementing only for OpenShift providers
    unless ext_management_system.kind_of?(ManageIQ::Providers::Openshift::ContainerManagerMixin)
      _log.error("#{__method__} only applicable for OpenShift Providers")
      return
    end
    ext_management_system.annotate(
      "image",
      digest,
      "security.manageiq.org/failed-policy" => causing_policy,
      "images.openshift.io/deny-execution"  => "true"
    )
  end

  def openscap_failed_rules_summary
    openscap_rule_results.where(:result => "fail").group(:severity).count.symbolize_keys
  end

  alias_method :perform_metadata_sync, :sync_stashed_metadata
end


text:
Cloud Transformation

We are pioneers in Azure applications and cloud solutions

We have been developing applications on Azure since it was released in 2010. We can help you optimize and manage your cloud solutions, reducing the amount of time required to manage, maintain, and deploy your data. Below are some of our cloud services.

CUSTOM APPLICATIONS

Low cost strategy and high availability

MIGRATE TO AZURE

Migrate existing applications

TRANSITION APPLICATIONS

Revamp existing apps for Azure

AZURE MAINTENANCE

Upgrade and maintain applications on Azure

OPTIMIZATION

Allow faster user access

INDUSTRY COMPLIANCE

Comply with latest industry standards


text:
package bbuzz

import rx.lang.scala.schedulers.ComputationScheduler

/**
 * Consumes tweets of a stream.
 *
 * The user should extend this trait and implement `onTweet`
 * as well as `handleException`
 */
trait TweetConsumer extends TweetObserver {

  final override def onNext(value: Tweet): Unit = onTweet(value)
  final override def onError(error: Throwable): Unit = handleException(error)
  final override def onCompleted(): Unit = ()

  /**
   * Gets called for every tweet that is pulled from the [[bbuzz.TweetProvider]].
   * This method should not block and complete quickly.
   *
   * @param tweet a new [[Tweet]]
   */
  def onTweet(tweet: Tweet): Unit

  /**
   * Gets called when an exception occurred during providing the Tweets.
   * This will be a fatal exception, and tweets will not continue to flow after
   * this exception occurred.
   *
   * @param exception the fatal exception
   */
  def handleException(exception: Throwable): Unit
}

/**
 * Entry point for the app.
 *
 * 1. create an `object`, extending this (`TweetStreaming`)
 * 2. mix-in a proper [[bbuzz.TweetProvider]]
 * 3. provide all desired settings according to the `TweetProvider`
 * 4. implement the methods from [[bbuzz.TweetConsumer]]
 *
 * Example, will scan an Elasticsearch index and print all found tweets.
 *
 * {{{
 * object TweetPrinter extends TweetStreaming with ElasticsearchScanTweets {
 *   def host = "localhost"
 *   def port = 9200
 *   def index = "tweets"
 *
 *   def onTweet(tweet: Tweet) = println(tweet.getText)
 *   def handleException(exception: Throwable) = exception.printStackTrace()
 * }
 * }}}
 *
 * This object's main method can be used to run the app.
 */
abstract class TweetStreaming extends TweetConsumer {
  this: TweetProvider =>

  final def main(args: Array[String]) {
    val ts = tweets
    ts.subscribe(this, ComputationScheduler())
    ts.toBlockingObservable.foreach(_ => ())
  }
}


text:
from unittest.mock import Mock, patch

from django.conf import settings
from moto import mock_s3

from zerver.lib.actions import check_add_realm_emoji
from zerver.lib.avatar_hash import user_avatar_path
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import avatar_disk_path, create_s3_buckets, get_test_image_file
from zerver.lib.transfer import (
    transfer_avatars_to_s3,
    transfer_emoji_to_s3,
    transfer_message_files_to_s3,
    transfer_uploads_to_s3,
)
from zerver.lib.upload import resize_emoji, upload_message_file
from zerver.models import Attachment, RealmEmoji

class TransferUploadsToS3Test(ZulipTestCase):
    @patch("zerver.lib.transfer.transfer_avatars_to_s3")
    @patch("zerver.lib.transfer.transfer_message_files_to_s3")
    @patch("zerver.lib.transfer.transfer_emoji_to_s3")
    def test_transfer_uploads_to_s3(self, m3: Mock, m2: Mock, m1: Mock) -> None:
        transfer_uploads_to_s3(4)

        m1.assert_called_with(4)
        m2.assert_called_with(4)
        m3.assert_called_with(4)

    @mock_s3
    def test_transfer_avatars_to_s3(self) -> None:
        bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]

        self.login("hamlet")
        with get_test_image_file("img.png") as image_file:
            self.client_post("/json/users/me/avatar", {"file": image_file})

        user = self.example_user("hamlet")

        with self.assertLogs(level="INFO"):
            transfer_avatars_to_s3(1)

        path_id = user_avatar_path(user)
        image_key = bucket.Object(path_id)
        original_image_key = bucket.Object(path_id + ".original")
        medium_image_key = bucket.Object(path_id + "-medium.png")

        self.assert_length(list(bucket.objects.all()), 3)
        with open(avatar_disk_path(user), "rb") as f:
            self.assertEqual(image_key.get()["Body"].read(), f.read())
        with open(avatar_disk_path(user, original=True), "rb") as f:
            self.assertEqual(original_image_key.get()["Body"].read(), f.read())
        with open(avatar_disk_path(user, medium=True), "rb") as f:
            self.assertEqual(medium_image_key.get()["Body"].read(), f.read())

    @mock_s3
    def test_transfer_message_files(self) -> None:
        bucket = create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)[0]
        hamlet = self.example_user("hamlet")
        othello = self.example_user("othello")

        upload_message_file("dummy1.txt", len(b"zulip1!"), "text/plain", b"zulip1!", hamlet)
        upload_message_file("dummy2.txt", len(b"zulip2!"), "text/plain", b"zulip2!", othello)

        with self.assertLogs(level="INFO"):
            transfer_message_files_to_s3(1)

        attachments = Attachment.objects.all().order_by("id")

        self.assert_length(list(bucket.objects.all()), 2)
        self.assertEqual(bucket.Object(attachments[0].path_id).get()["Body"].read(), b"zulip1!")
        self.assertEqual(bucket.Object(attachments[1].path_id).get()["Body"].read(), b"zulip2!")

    @mock_s3
    def test_transfer_emoji_to_s3(self) -> None:
        bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]
        othello = self.example_user("othello")
        RealmEmoji.objects.all().delete()

        emoji_name = "emoji.png"

        with get_test_image_file("img.png") as image_file:
            emoji = check_add_realm_emoji(othello.realm, emoji_name, othello, image_file)
        if not emoji:
            raise AssertionError("Unable to add emoji.")

        emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format(
            realm_id=othello.realm_id,
            emoji_file_name=emoji.file_name,
        )

        with self.assertLogs(level="INFO"):
            transfer_emoji_to_s3(1)

        self.assert_length(list(bucket.objects.all()), 2)
        original_key = bucket.Object(emoji_path + ".original")
        resized_key = bucket.Object(emoji_path)

        with get_test_image_file("img.png") as image_file:
            image_data = image_file.read()
        resized_image_data = resize_emoji(image_data)

        self.assertEqual(image_data, original_key.get()["Body"].read())
        self.assertEqual(resized_image_data, resized_key.get()["Body"].read())


text:
import warnings

import numpy as np
import pytest
from scipy import linalg
from sklearn.base import clone
from sklearn.model_selection import train_test_split
from sklearn.utils._testing import assert_allclose
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import ignore_warnings
from sklearn.utils._testing import TempMemmap
from sklearn.utils.fixes import np_version, parse_version
from sklearn.utils import check_random_state
from sklearn.exceptions import ConvergenceWarning
from sklearn import linear_model, datasets
from sklearn.linear_model._least_angle import _lars_path_residues
from sklearn.linear_model import LassoLarsIC, lars_path
from sklearn.linear_model import Lars, LassoLars, LarsCV, LassoLarsCV

# TODO: use another dataset that has multiple drops
diabetes = datasets.load_diabetes()
X, y = diabetes.data, diabetes.target
G = np.dot(X.T, X)
Xy = np.dot(X.T, y)
n_samples = y.size

# FIXME: 'normalize' to be removed in 1.4
filterwarnings_normalize = pytest.mark.filterwarnings(
    "ignore:The default of 'normalize'"
)

# FIXME: 'normalize' to be removed in 1.4
@pytest.mark.parametrize(
    "LeastAngleModel", [Lars, LassoLars, LarsCV, LassoLarsCV, LassoLarsIC]
)
@pytest.mark.parametrize(
    "normalize, n_warnings", [(True, 0), (False, 0), ("deprecated", 1)]
)
def test_assure_warning_when_normalize(LeastAngleModel, normalize, n_warnings):
    # check that we issue a FutureWarning when normalize was set
    rng = check_random_state(0)
    n_samples = 200
    n_features = 2
    X = rng.randn(n_samples, n_features)
    X[X < 0.1] = 0.0
    y = rng.rand(n_samples)

    model = LeastAngleModel(normalize=normalize)
    with pytest.warns(None) as record:
        model.fit(X, y)

    record = [r for r in record if r.category == FutureWarning]
    assert len(record) == n_warnings

def test_simple():
    # Principle of Lars is to keep covariances tied and decreasing

    # also test verbose output
    from io import StringIO
    import sys

    old_stdout = sys.stdout
    try:
        sys.stdout = StringIO()

        _, _, coef_path_ = linear_model.lars_path(X, y, method="lar", verbose=10)

        sys.stdout = old_stdout

        for i, coef_ in enumerate(coef_path_.T):
            res = y - np.dot(X, coef_)
            cov = np.dot(X.T, res)
            C = np.max(abs(cov))
            eps = 1e-3
            ocur = len(cov[C - eps < abs(cov)])
            if i < X.shape[1]:
                assert ocur == i + 1
            else:
                # no more than max_pred variables can go into the active set
                assert ocur == X.shape[1]
    finally:
        sys.stdout = old_stdout

def test_simple_precomputed():
    # The same, with precomputed Gram matrix

    _, _, coef_path_ = linear_model.lars_path(X, y, Gram=G, method="lar")

    for i, coef_ in enumerate(coef_path_.T):
        res = y - np.dot(X, coef_)
        cov = np.dot(X.T, res)
        C = np.max(abs(cov))
        eps = 1e-3
        ocur = len(cov[C - eps < abs(cov)])
        if i < X.shape[1]:
            assert ocur == i + 1
        else:
            # no more than max_pred variables can go into the active set
            assert ocur == X.shape[1]

def _assert_same_lars_path_result(output1, output2):
    assert len(output1) == len(output2)
    for o1, o2 in zip(output1, output2):
        assert_allclose(o1, o2)

@pytest.mark.parametrize("method", ["lar", "lasso"])
@pytest.mark.parametrize("return_path", [True, False])
def test_lars_path_gram_equivalent(method, return_path):
    _assert_same_lars_path_result(
        linear_model.lars_path_gram(
            Xy=Xy, Gram=G, n_samples=n_samples, method=method, return_path=return_path
        ),
        linear_model.lars_path(X, y, Gram=G, method=method, return_path=return_path),
    )

def test_x_none_gram_none_raises_value_error():
    # Test that lars_path with no X and Gram raises exception
    Xy = np.dot(X.T, y)
    with pytest.raises(ValueError):
        linear_model.lars_path(None, y, Gram=None, Xy=Xy)

def test_all_precomputed():
    # Test that lars_path with precomputed Gram and Xy gives the right answer
    G = np.dot(X.T, X)
    Xy = np.dot(X.T, y)
    for method in "lar", "lasso":
        output = linear_model.lars_path(X, y, method=method)
        output_pre = linear_model.lars_path(X, y, Gram=G, Xy=Xy, method=method)
        for expected, got in zip(output, output_pre):
            assert_array_almost_equal(expected, got)

# FIXME: 'normalize' to be removed in 1.4
@filterwarnings_normalize
@pytest.mark.filterwarnings("ignore: `rcond` parameter will change")
# numpy deprecation
def test_lars_lstsq():
    # Test that Lars gives least square solution at the end
    # of the path
    X1 = 3 * X  # use un-normalized dataset
    clf = linear_model.LassoLars(alpha=0.0)
    clf.fit(X1, y)
    # Avoid FutureWarning about default value change when numpy >= 1.14
    rcond = None if np_version >= parse_version("1.14") else -1
    coef_lstsq = np.linalg.lstsq(X1, y, rcond=rcond)[0]
    assert_array_almost_equal(clf.coef_, coef_lstsq)

@pytest.mark.filterwarnings("ignore:`rcond` parameter will change")
# numpy deprecation
def test_lasso_gives_lstsq_solution():
    # Test that Lars Lasso gives least square solution at the end
    # of the path
    _, _, coef_path_ = linear_model.lars_path(X, y, method="lasso")
    coef_lstsq = np.linalg.lstsq(X, y)[0]
    assert_array_almost_equal(coef_lstsq, coef_path_[:, -1])

def test_collinearity():
    # Check that lars_path is robust to collinearity in input
    X = np.array([[3.0, 3.0, 1.0], [2.0, 2.0, 0.0], [1.0, 1.0, 0]])
    y = np.array([1.0, 0.0, 0])
    rng = np.random.RandomState(0)

    f = ignore_warnings
    _, _, coef_path_ = f(linear_model.lars_path)(X, y, alpha_min=0.01)
    assert not np.isnan(coef_path_).any()
    residual = np.dot(X, coef_path_[:, -1]) - y
    assert (residual ** 2).sum() < 1.0  # just make sure it's bounded

    n_samples = 10
    X = rng.rand(n_samples, 5)
    y = np.zeros(n_samples)
    _, _, coef_path_ = linear_model.lars_path(
        X,
        y,
        Gram="auto",
        copy_X=False,
        copy_Gram=False,
        alpha_min=0.0,
        method="lasso",
        verbose=0,
        max_iter=500,
    )
    assert_array_almost_equal(coef_path_, np.zeros_like(coef_path_))

def test_no_path():
    # Test that the ``return_path=False`` option returns the correct output
    alphas_, _, coef_path_ = linear_model.lars_path(X, y, method="lar")
    alpha_, _, coef = linear_model.lars_path(X, y, method="lar", return_path=False)

    assert_array_almost_equal(coef, coef_path_[:, -1])
    assert alpha_ == alphas_[-1]

def test_no_path_precomputed():
    # Test that the ``return_path=False`` option with Gram remains correct
    alphas_, _, coef_path_ = linear_model.lars_path(X, y, method="lar", Gram=G)
    alpha_, _, coef = linear_model.lars_path(
        X, y, method="lar", Gram=G, return_path=False
    )

    assert_array_almost_equal(coef, coef_path_[:, -1])
    assert alpha_ == alphas_[-1]

def test_no_path_all_precomputed():
    # Test that the ``return_path=False`` option with Gram and Xy remains
    # correct
    X, y = 3 * diabetes.data, diabetes.target
    G = np.dot(X.T, X)
    Xy = np.dot(X.T, y)
    alphas_, _, coef_path_ = linear_model.lars_path(
        X, y, method="lasso", Xy=Xy, Gram=G, alpha_min=0.9
    )
    alpha_, _, coef = linear_model.lars_path(
        X, y, method="lasso", Gram=G, Xy=Xy, alpha_min=0.9, return_path=False
    )

    assert_array_almost_equal(coef, coef_path_[:, -1])
    assert alpha_ == alphas_[-1]

@filterwarnings_normalize
@pytest.mark.parametrize(
    "classifier", [linear_model.Lars, linear_model.LarsCV, linear_model.LassoLarsIC]
)
def test_lars_precompute(classifier):
    # Check for different values of precompute
    G = np.dot(X.T, X)

    clf = classifier(precompute=G)
    output_1 = ignore_warnings(clf.fit)(X, y).coef_
    for precompute in [True, False, "auto", None]:
        clf = classifier(precompute=precompute)
        output_2 = clf.fit(X, y).coef_
        assert_array_almost_equal(output_1, output_2, decimal=8)

def test_singular_matrix():
    # Test when input is a singular matrix
    X1 = np.array([[1, 1.0], [1.0, 1.0]])
    y1 = np.array([1, 1])
    _, _, coef_path = linear_model.lars_path(X1, y1)
    assert_array_almost_equal(coef_path.T, [[0, 0], [1, 0]])

@filterwarnings_normalize
def test_rank_deficient_design():
    # consistency test that checks that LARS Lasso is handling rank
    # deficient input data (with n_features < rank) in the same way
    # as coordinate descent Lasso
    y = [5, 0, 5]
    for X in ([[5, 0], [0, 5], [10, 10]], [[10, 10, 0], [1e-32, 0, 0], [0, 0, 1]]):
        # To be able to use the coefs to compute the objective function,
        # we need to turn off normalization
        lars = linear_model.LassoLars(0.1, normalize=False)
        coef_lars_ = lars.fit(X, y).coef_
        obj_lars = 1.0 / (2.0 * 3.0) * linalg.norm(
            y - np.dot(X, coef_lars_)
        ) ** 2 + 0.1 * linalg.norm(coef_lars_, 1)
        coord_descent = linear_model.Lasso(0.1, tol=1e-6)
        coef_cd_ = coord_descent.fit(X, y).coef_
        obj_cd = (1.0 / (2.0 * 3.0)) * linalg.norm(
            y - np.dot(X, coef_cd_)
        ) ** 2 + 0.1 * linalg.norm(coef_cd_, 1)
        assert obj_lars < obj_cd * (1.0 + 1e-8)

@filterwarnings_normalize
def test_lasso_lars_vs_lasso_cd():
    # Test that LassoLars and Lasso using coordinate descent give the
    # same results.
    X = 3 * diabetes.data

    alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso")
    lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8)
    for c, a in zip(lasso_path.T, alphas):
        if a == 0:
            continue
        lasso_cd.alpha = a
        lasso_cd.fit(X, y)
        error = linalg.norm(c - lasso_cd.coef_)
        assert error < 0.01

    # similar test, with the classifiers
    for alpha in np.linspace(1e-2, 1 - 1e-2, 20):
        clf1 = linear_model.LassoLars(alpha=alpha, normalize=False).fit(X, y)
        clf2 = linear_model.Lasso(alpha=alpha, tol=1e-8).fit(X, y)
        err = linalg.norm(clf1.coef_ - clf2.coef_)
        assert err < 1e-3

    # same test, with normalized data
    X = diabetes.data
    X = X - X.sum(axis=0)
    X /= np.linalg.norm(X, axis=0)
    alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso")
    lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8)
    for c, a in zip(lasso_path.T, alphas):
        if a == 0:
            continue
        lasso_cd.alpha = a
        lasso_cd.fit(X, y)
        error = linalg.norm(c - lasso_cd.coef_)
        assert error < 0.01

@filterwarnings_normalize
def test_lasso_lars_vs_lasso_cd_early_stopping():
    # Test that LassoLars and Lasso using coordinate descent give the
    # same results when early stopping is used.
    # (test : before, in the middle, and in the last part of the path)
    alphas_min = [10, 0.9, 1e-4]

    X = diabetes.data

    for alpha_min in alphas_min:
        alphas, _, lasso_path = linear_model.lars_path(
            X, y, method="lasso", alpha_min=alpha_min
        )
        lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8)
        lasso_cd.alpha = alphas[-1]
        lasso_cd.fit(X, y)
        error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_)
        assert error < 0.01

    # same test, with normalization
    X = diabetes.data - diabetes.data.sum(axis=0)
    X /= np.linalg.norm(X, axis=0)

    for alpha_min in alphas_min:
        alphas, _, lasso_path = linear_model.lars_path(
            X, y, method="lasso", alpha_min=alpha_min
        )
        lasso_cd = linear_model.Lasso(tol=1e-8)
        lasso_cd.alpha = alphas[-1]
        lasso_cd.fit(X, y)
        error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_)
        assert error < 0.01

@filterwarnings_normalize
def test_lasso_lars_path_length():
    # Test that the path length of the LassoLars is right
    lasso = linear_model.LassoLars()
    lasso.fit(X, y)
    lasso2 = linear_model.LassoLars(alpha=lasso.alphas_[2])
    lasso2.fit(X, y)
    assert_array_almost_equal(lasso.alphas_[:3], lasso2.alphas_)
    # Also check that the sequence of alphas is always decreasing
    assert np.all(np.diff(lasso.alphas_) < 0)

def test_lasso_lars_vs_lasso_cd_ill_conditioned():
    # Test lasso lars on a very ill-conditioned design, and check that
    # it does not blow up, and stays somewhat close to a solution given
    # by the coordinate descent solver
    # Also test that lasso_path (using lars_path output style) gives
    # the same result as lars_path and previous lasso output style
    # under these conditions.
    rng = np.random.RandomState(42)

    # Generate data
    n, m = 70, 100
    k = 5
    X = rng.randn(n, m)
    w = np.zeros((m, 1))
    i = np.arange(0, m)
    rng.shuffle(i)
    supp = i[:k]
    w[supp] = np.sign(rng.randn(k, 1)) * (rng.rand(k, 1) + 1)
    y = np.dot(X, w)
    sigma = 0.2
    y += sigma * rng.rand(*y.shape)
    y = y.squeeze()
    lars_alphas, _, lars_coef = linear_model.lars_path(X, y, method="lasso")

    _, lasso_coef2, _ = linear_model.lasso_path(X, y, alphas=lars_alphas, tol=1e-6)

    assert_array_almost_equal(lars_coef, lasso_coef2, decimal=1)

@filterwarnings_normalize
def test_lasso_lars_vs_lasso_cd_ill_conditioned2():
    # Create an ill-conditioned situation in which the LARS has to go
    # far in the path to converge, and check that LARS and coordinate
    # descent give the same answers
    # Note it used to be the case that Lars had to use the drop for good
    # strategy for this but this is no longer the case with the
    # equality_tolerance checks
    X = [[1e20, 1e20, 0], [-1e-32, 0, 0], [1, 1, 1]]
    y = [10, 10, 1]
    alpha = 0.0001

    def objective_function(coef):
        return 1.0 / (2.0 * len(X)) * linalg.norm(
            y - np.dot(X, coef)
        ) ** 2 + alpha * linalg.norm(coef, 1)

    lars = linear_model.LassoLars(alpha=alpha, normalize=False)
    warning_message = "Regressors in active set degenerate."
    with pytest.warns(ConvergenceWarning, match=warning_message):
        lars.fit(X, y)
    lars_coef_ = lars.coef_
    lars_obj = objective_function(lars_coef_)

    coord_descent = linear_model.Lasso(alpha=alpha, tol=1e-4)
    cd_coef_ = coord_descent.fit(X, y).coef_
    cd_obj = objective_function(cd_coef_)

    assert lars_obj < cd_obj * (1.0 + 1e-8)

@filterwarnings_normalize
def test_lars_add_features():
    # assure that at least some features get added if necessary
    # test for 6d2b4c
    # Hilbert matrix
    n = 5
    H = 1.0 / (np.arange(1, n + 1) + np.arange(n)[:, np.newaxis])
    clf = linear_model.Lars(fit_intercept=False).fit(H, np.arange(n))
    assert np.all(np.isfinite(clf.coef_))

@filterwarnings_normalize
def test_lars_n_nonzero_coefs(verbose=False):
    lars = linear_model.Lars(n_nonzero_coefs=6, verbose=verbose)
    lars.fit(X, y)
    assert len(lars.coef_.nonzero()[0]) == 6
    # The path should be of length 6 + 1 in a Lars going down to 6
    # non-zero coefs
    assert len(lars.alphas_) == 7

@filterwarnings_normalize
@ignore_warnings
def test_multitarget():
    # Assure that estimators receiving multidimensional y do the right thing
    Y = np.vstack([y, y ** 2]).T
    n_targets = Y.shape[1]
    estimators = [
        linear_model.LassoLars(),
        linear_model.Lars(),
        # regression test for gh-1615
        linear_model.LassoLars(fit_intercept=False),
        linear_model.Lars(fit_intercept=False),
    ]

    for estimator in estimators:
        estimator.fit(X, Y)
        Y_pred = estimator.predict(X)
        alphas, active, coef, path = (
            estimator.alphas_,
            estimator.active_,
            estimator.coef_,
            estimator.coef_path_,
        )
        for k in range(n_targets):
            estimator.fit(X, Y[:, k])
            y_pred = estimator.predict(X)
            assert_array_almost_equal(alphas[k], estimator.alphas_)
            assert_array_almost_equal(active[k], estimator.active_)
            assert_array_almost_equal(coef[k], estimator.coef_)
            assert_array_almost_equal(path[k], estimator.coef_path_)
            assert_array_almost_equal(Y_pred[:, k], y_pred)

@filterwarnings_normalize
def test_lars_cv():
    # Test the LassoLarsCV object by checking that the optimal alpha
    # increases as the number of samples increases.
    # This property is not actually guaranteed in general and is just a
    # property of the given dataset, with the given steps chosen.
    old_alpha = 0
    lars_cv = linear_model.LassoLarsCV()
    for length in (400, 200, 100):
        X = diabetes.data[:length]
        y = diabetes.target[:length]
        lars_cv.fit(X, y)
        np.testing.assert_array_less(old_alpha, lars_cv.alpha_)
        old_alpha = lars_cv.alpha_
    assert not hasattr(lars_cv, "n_nonzero_coefs")

@filterwarnings_normalize
def test_lars_cv_max_iter(recwarn):
    warnings.simplefilter("always")
    with np.errstate(divide="raise", invalid="raise"):
        X = diabetes.data
        y = diabetes.target
        rng = np.random.RandomState(42)
        x = rng.randn(len(y))
        X = diabetes.data
        X = np.c_[X, x, x]  # add correlated features
        lars_cv = linear_model.LassoLarsCV(max_iter=5, cv=5)
        lars_cv.fit(X, y)
    # Check that there is no warning in general and no ConvergenceWarning
    # in particular.
    # Materialize the string representation of the warning to get a more
    # informative error message in case of AssertionError.
    recorded_warnings = [str(w) for w in recwarn]
    # FIXME: when 'normalize' is removed set exchange below for:
    # assert len(recorded_warnings) == []
    assert len(recorded_warnings) == 1
    assert "normalize' will be set to False in version 1.2" in recorded_warnings[0]

@filterwarnings_normalize
def test_lasso_lars_ic():
    # Test the LassoLarsIC object by checking that
    # - some good features are selected.
    # - alpha_bic > alpha_aic
    # - n_nonzero_bic < n_nonzero_aic
    lars_bic = linear_model.LassoLarsIC("bic")
    lars_aic = linear_model.LassoLarsIC("aic")
    rng = np.random.RandomState(42)
    X = diabetes.data
    X = np.c_[X, rng.randn(X.shape[0], 5)]  # add 5 bad features
    lars_bic.fit(X, y)
    lars_aic.fit(X, y)
    nonzero_bic = np.where(lars_bic.coef_)[0]
    nonzero_aic = np.where(lars_aic.coef_)[0]
    assert lars_bic.alpha_ > lars_aic.alpha_
    assert len(nonzero_bic) < len(nonzero_aic)
    assert np.max(nonzero_bic) < diabetes.data.shape[1]

    # test error on unknown IC
    lars_broken = linear_model.LassoLarsIC("<unknown>")

    with pytest.raises(ValueError):
        lars_broken.fit(X, y)

def test_lars_path_readonly_data():
    # When using automated memory mapping on large input, the
    # fold data is in read-only mode
    # This is a non-regression test for:
    # https://github.com/scikit-learn/scikit-learn/issues/4597
    splitted_data = train_test_split(X, y, random_state=42)
    with TempMemmap(splitted_data) as (X_train, X_test, y_train, y_test):
        # The following should not fail despite copy=False
        _lars_path_residues(X_train, y_train, X_test, y_test, copy=False)

def test_lars_path_positive_constraint():
    # this is the main test for the positive parameter on the lars_path method
    # the estimator classes just make use of this function

    # we do the test on the diabetes dataset

    # ensure that we get negative coefficients when positive=False
    # and all positive when positive=True
    # for method 'lar' (default) and lasso

    err_msg = "Positive constraint not supported for 'lar' coding method."
    with pytest.raises(ValueError, match=err_msg):
        linear_model.lars_path(
            diabetes["data"], diabetes["target"], method="lar", positive=True
        )

    method = "lasso"
    _, _, coefs = linear_model.lars_path(
        X, y, return_path=True, method=method, positive=False
    )
    assert coefs.min() < 0

    _, _, coefs = linear_model.lars_path(
        X, y, return_path=True, method=method, positive=True
    )
    assert coefs.min() >= 0

# now we gonna test the positive option for all estimator classes

default_parameter = {"fit_intercept": False}

estimator_parameter_map = {
    "LassoLars": {"alpha": 0.1},
    "LassoLarsCV": {},
    "LassoLarsIC": {},
}

@filterwarnings_normalize
def test_estimatorclasses_positive_constraint():
    # testing the transmissibility for the positive option of all estimator
    # classes in this same function here
    default_parameter = {"fit_intercept": False}

    estimator_parameter_map = {
        "LassoLars": {"alpha": 0.1},
        "LassoLarsCV": {},
        "LassoLarsIC": {},
    }
    for estname in estimator_parameter_map:
        params = default_parameter.copy()
        params.update(estimator_parameter_map[estname])
        estimator = getattr(linear_model, estname)(positive=False, **params)
        estimator.fit(X, y)
        assert estimator.coef_.min() < 0
        estimator = getattr(linear_model, estname)(positive=True, **params)
        estimator.fit(X, y)
        assert min(estimator.coef_) >= 0

@filterwarnings_normalize
def test_lasso_lars_vs_lasso_cd_positive():
    # Test that LassoLars and Lasso using coordinate descent give the
    # same results when using the positive option

    # This test is basically a copy of the above with additional positive
    # option. However for the middle part, the comparison of coefficient values
    # for a range of alphas, we had to make an adaptations. See below.

    # not normalized data
    X = 3 * diabetes.data

    alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso", positive=True)
    lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8, positive=True)
    for c, a in zip(lasso_path.T, alphas):
        if a == 0:
            continue
        lasso_cd.alpha = a
        lasso_cd.fit(X, y)
        error = linalg.norm(c - lasso_cd.coef_)
        assert error < 0.01

    # The range of alphas chosen for coefficient comparison here is restricted
    # as compared with the above test without the positive option. This is due
    # to the circumstance that the Lars-Lasso algorithm does not converge to
    # the least-squares-solution for small alphas, see 'Least Angle Regression'
    # by Efron et al 2004. The coefficients are typically in congruence up to
    # the smallest alpha reached by the Lars-Lasso algorithm and start to
    # diverge thereafter.  See
    # https://gist.github.com/michigraber/7e7d7c75eca694c7a6ff

    for alpha in np.linspace(6e-1, 1 - 1e-2, 20):
        clf1 = linear_model.LassoLars(
            fit_intercept=False, alpha=alpha, normalize=False, positive=True
        ).fit(X, y)
        clf2 = linear_model.Lasso(
            fit_intercept=False, alpha=alpha, tol=1e-8, positive=True
        ).fit(X, y)
        err = linalg.norm(clf1.coef_ - clf2.coef_)
        assert err < 1e-3

    # normalized data
    X = diabetes.data - diabetes.data.sum(axis=0)
    X /= np.linalg.norm(X, axis=0)
    alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso", positive=True)
    lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8, positive=True)
    for c, a in zip(lasso_path.T[:-1], alphas[:-1]):  # don't include alpha=0
        lasso_cd.alpha = a
        lasso_cd.fit(X, y)
        error = linalg.norm(c - lasso_cd.coef_)
        assert error < 0.01

@filterwarnings_normalize
def test_lasso_lars_vs_R_implementation():
    # Test that sklearn LassoLars implementation agrees with the LassoLars
    # implementation available in R (lars library) under the following
    # scenarios:
    # 1) fit_intercept=False and normalize=False
    # 2) fit_intercept=True and normalize=True

    # Let's generate the data used in the bug report 7778
    y = np.array([-6.45006793, -3.51251449, -8.52445396, 6.12277822, -19.42109366])
    x = np.array(
        [
            [0.47299829, 0, 0, 0, 0],
            [0.08239882, 0.85784863, 0, 0, 0],
            [0.30114139, -0.07501577, 0.80895216, 0, 0],
            [-0.01460346, -0.1015233, 0.0407278, 0.80338378, 0],
            [-0.69363927, 0.06754067, 0.18064514, -0.0803561, 0.40427291],
        ]
    )

    X = x.T

    ###########################################################################
    # Scenario 1: Let's compare R vs sklearn when fit_intercept=False and
    # normalize=False
    ###########################################################################
    #
    # The R result was obtained using the following code:
    #
    # library(lars)
    # model_lasso_lars = lars(X, t(y), type="lasso", intercept=FALSE,
    #                         trace=TRUE, normalize=FALSE)
    # r = t(model_lasso_lars$beta)
    #

    r = np.array(
        [
            [
                0,
                0,
                0,
                0,
                0,
                -79.810362809499026,
                -83.528788732782829,
                -83.777653739190711,
                -83.784156932888934,
                -84.033390591756657,
            ],
            [0, 0, 0, 0, -0.476624256777266, 0, 0, 0, 0, 0.025219751009936],
            [
                0,
                -3.577397088285891,
                -4.702795355871871,
                -7.016748621359461,
                -7.614898471899412,
                -0.336938391359179,
                0,
                0,
                0.001213370600853,
                0.048162321585148,
            ],
            [
                0,
                0,
                0,
                2.231558436628169,
                2.723267514525966,
                2.811549786389614,
                2.813766976061531,
                2.817462468949557,
                2.817368178703816,
                2.816221090636795,
            ],
            [
                0,
                0,
                -1.218422599914637,
                -3.457726183014808,
                -4.021304522060710,
                -45.827461592423745,
                -47.776608869312305,
                -47.911561610746404,
                -47.914845922736234,
                -48.039562334265717,
            ],
        ]
    )

    model_lasso_lars = linear_model.LassoLars(
        alpha=0, fit_intercept=False, normalize=False
    )
    model_lasso_lars.fit(X, y)
    skl_betas = model_lasso_lars.coef_path_

    assert_array_almost_equal(r, skl_betas, decimal=12)
    ###########################################################################

    ###########################################################################
    # Scenario 2: Let's compare R vs sklearn when fit_intercept=True and
    # normalize=True
    #
    # Note: When normalize is equal to True, R returns the coefficients in
    # their original units, that is, they are rescaled back, whereas sklearn
    # does not do that, therefore, we need to do this step before comparing
    # their results.
    ###########################################################################
    #
    # The R result was obtained using the following code:
    #
    # library(lars)
    # model_lasso_lars2 = lars(X, t(y), type="lasso", intercept=TRUE,
    #                           trace=TRUE, normalize=TRUE)
    # r2 = t(model_lasso_lars2$beta)

    r2 = np.array(
        [
            [0, 0, 0, 0, 0],
            [0, 0, 0, 8.371887668009453, 19.463768371044026],
            [0, 0, 0, 0, 9.901611055290553],
            [
                0,
                7.495923132833733,
                9.245133544334507,
                17.389369207545062,
                26.971656815643499,
            ],
            [0, 0, -1.569380717440311, -5.924804108067312, -7.996385265061972],
        ]
    )

    model_lasso_lars2 = linear_model.LassoLars(alpha=0, normalize=True)
    model_lasso_lars2.fit(X, y)
    skl_betas2 = model_lasso_lars2.coef_path_

    # Let's rescale back the coefficients returned by sklearn before comparing
    # against the R result (read the note above)
    temp = X - np.mean(X, axis=0)
    normx = np.sqrt(np.sum(temp ** 2, axis=0))
    skl_betas2 /= normx[:, np.newaxis]

    assert_array_almost_equal(r2, skl_betas2, decimal=12)
    ###########################################################################

@filterwarnings_normalize
@pytest.mark.parametrize("copy_X", [True, False])
def test_lasso_lars_copyX_behaviour(copy_X):
    """
    Test that user input regarding copy_X is not being overridden (it was until
    at least version 0.21)

    """
    lasso_lars = LassoLarsIC(copy_X=copy_X, precompute=False)
    rng = np.random.RandomState(0)
    X = rng.normal(0, 1, (100, 5))
    X_copy = X.copy()
    y = X[:, 2]
    lasso_lars.fit(X, y)
    assert copy_X == np.array_equal(X, X_copy)

@filterwarnings_normalize
@pytest.mark.parametrize("copy_X", [True, False])
def test_lasso_lars_fit_copyX_behaviour(copy_X):
    """
    Test that user input to .fit for copy_X overrides default __init__ value

    """
    lasso_lars = LassoLarsIC(precompute=False)
    rng = np.random.RandomState(0)
    X = rng.normal(0, 1, (100, 5))
    X_copy = X.copy()
    y = X[:, 2]
    lasso_lars.fit(X, y, copy_X=copy_X)
    assert copy_X == np.array_equal(X, X_copy)

@filterwarnings_normalize
@pytest.mark.parametrize("est", (LassoLars(alpha=1e-3), Lars()))
def test_lars_with_jitter(est):
    # Test that a small amount of jitter helps stability,
    # using example provided in issue #2746

    X = np.array([[0.0, 0.0, 0.0, -1.0, 0.0], [0.0, -1.0, 0.0, 0.0, 0.0]])
    y = [-2.5, -2.5]
    expected_coef = [0, 2.5, 0, 2.5, 0]

    # set to fit_intercept to False since target is constant and we want check
    # the value of coef. coef would be all zeros otherwise.
    est.set_params(fit_intercept=False)
    est_jitter = clone(est).set_params(jitter=10e-8, random_state=0)

    est.fit(X, y)
    est_jitter.fit(X, y)

    assert np.mean((est.coef_ - est_jitter.coef_) ** 2) > 0.1
    np.testing.assert_allclose(est_jitter.coef_, expected_coef, rtol=1e-3)

def test_X_none_gram_not_none():
    with pytest.raises(ValueError, match="X cannot be None if Gram is not None"):
        lars_path(X=None, y=[1], Gram="not None")

def test_copy_X_with_auto_gram():
    # Non-regression test for #17789, `copy_X=True` and Gram='auto' does not
    # overwrite X
    rng = np.random.RandomState(42)
    X = rng.rand(6, 6)
    y = rng.rand(6)

    X_before = X.copy()
    linear_model.lars_path(X, y, Gram="auto", copy_X=True, method="lasso")
    # X did not change
    assert_allclose(X, X_before)

@pytest.mark.parametrize(
    "LARS, has_coef_path, args",
    (
        (Lars, True, {}),
        (LassoLars, True, {}),
        (LassoLarsIC, False, {}),
        (LarsCV, True, {}),
        # max_iter=5 is for avoiding ConvergenceWarning
        (LassoLarsCV, True, {"max_iter": 5}),
    ),
)
@pytest.mark.parametrize("dtype", (np.float32, np.float64))
@filterwarnings_normalize
def test_lars_dtype_match(LARS, has_coef_path, args, dtype):
    # The test ensures that the fit method preserves input dtype
    rng = np.random.RandomState(0)
    X = rng.rand(6, 6).astype(dtype)
    y = rng.rand(6).astype(dtype)

    model = LARS(**args)
    model.fit(X, y)
    assert model.coef_.dtype == dtype
    if has_coef_path:
        assert model.coef_path_.dtype == dtype
    assert model.intercept_.dtype == dtype

@pytest.mark.parametrize(
    "LARS, has_coef_path, args",
    (
        (Lars, True, {}),
        (LassoLars, True, {}),
        (LassoLarsIC, False, {}),
        (LarsCV, True, {}),
        # max_iter=5 is for avoiding ConvergenceWarning
        (LassoLarsCV, True, {"max_iter": 5}),
    ),
)
@filterwarnings_normalize
def test_lars_numeric_consistency(LARS, has_coef_path, args):
    # The test ensures numerical consistency between trained coefficients
    # of float32 and float64.
    rtol = 1e-5
    atol = 1e-5

    rng = np.random.RandomState(0)
    X_64 = rng.rand(6, 6)
    y_64 = rng.rand(6)

    model_64 = LARS(**args).fit(X_64, y_64)
    model_32 = LARS(**args).fit(X_64.astype(np.float32), y_64.astype(np.float32))

    assert_allclose(model_64.coef_, model_32.coef_, rtol=rtol, atol=atol)
    if has_coef_path:
        assert_allclose(model_64.coef_path_, model_32.coef_path_, rtol=rtol, atol=atol)
    assert_allclose(model_64.intercept_, model_32.intercept_, rtol=rtol, atol=atol)


text:
//if reset is set, clear the count, else, count++
if (IN.reset) {
  shared.count = 0;
  console.log("reset the count", IN, shared.count);
} else {
  shared.count = shared.count + 1;
  console.log("count", IN, shared.count);
}

sendOUT({
  count:shared.count
});


text:
using LiteNetLib;
using LiteNetLib.Utils;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;

namespace LibSample
{
    class SerializerTest
    {
        [Serializable] //Just for test binary formatter
        private struct SampleNetSerializable : INetSerializable
        {
            public int Value;

            public void Serialize(NetDataWriter writer)
            {
                writer.Put(Value);
            }

            public void Deserialize(NetDataReader reader)
            {
                Value = reader.GetInt();
            }
        }

        [Serializable] //Just for test binary formatter
        private class SamplePacket
        {
            public string SomeString { get; set; }
            public float SomeFloat { get; set; }
            public int[] SomeIntArray { get; set; }
            public SomeVector2 SomeVector2 { get; set; }
            public SomeVector2[] SomeVectors { get; set; }
            public string EmptyString { get; set; }
            public SampleNetSerializable TestObj { get; set; }

            public override string ToString()
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("SomeString: " + SomeString);
                sb.AppendLine("SomeFloat: " + SomeFloat);
                sb.AppendLine("SomeIntArray: ");
                for (int i = 0; i < SomeIntArray.Length; i++)
                {
                    sb.AppendLine(" " + SomeIntArray[i]);
                }
                sb.AppendLine("SomeVector2 X: " + SomeVector2);
                sb.AppendLine("SomeVectors: ");
                for (int i = 0; i < SomeVectors.Length; i++)
                {
                    sb.AppendLine(" " + SomeVectors[i]);
                }
                sb.AppendLine("EmptyString: " + EmptyString);
                sb.AppendLine("TestObj value: " + TestObj.Value);
                return sb.ToString();
            }
        }

        [Serializable] //Just for test binary formatter
        private struct SomeVector2
        {
            public int X;
            public int Y;

            public SomeVector2(int x, int y)
            {
                X = x;
                Y = y;
            }

            public override string ToString()
            {
                return "X: " + X + ", Y: " + Y;
            }

            public static void Serialize(NetDataWriter writer, SomeVector2 vector)
            {
                writer.Put(vector.X);
                writer.Put(vector.Y);
            }

            public static SomeVector2 Deserialize(NetDataReader reader)
            {
                SomeVector2 res = new SomeVector2();
                res.X = reader.GetInt();
                res.Y = reader.GetInt();
                return res;
            }
        }

        private class ClientListener : INetEventListener
        {
            private readonly NetSerializer _serializer;

            public ClientListener()
            {
                _serializer = new NetSerializer();
                _serializer.RegisterCustomType<SampleNetSerializable>();
                _serializer.RegisterCustomType( SomeVector2.Serialize, SomeVector2.Deserialize );
            }

            public void OnPeerConnected(NetPeer peer)
            {
                Console.WriteLine("[Client] connected to: {0}:{1}", peer.EndPoint.Host, peer.EndPoint.Port);
                SamplePacket sp = new SamplePacket
                {
                    SomeFloat = 3.42f,
                    SomeIntArray = new[] {6, 5, 4},
                    SomeString = "Test String",
                    SomeVector2 = new SomeVector2(4, 5),
                    SomeVectors = new[] {new SomeVector2(1, 2), new SomeVector2(3, 4)},
                    TestObj = new SampleNetSerializable { Value = 5 }
                };

                byte[] data = _serializer.Serialize(sp);
                Console.WriteLine("Sending to server (length {0}):\n{1}", data.Length, sp);
                peer.Send(data, SendOptions.ReliableOrdered);
            }

            public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
            {
                Console.WriteLine("[Client] disconnected: " + disconnectInfo.Reason);
            }

            public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode)
            {
                Console.WriteLine("[Client] error! " + socketErrorCode);
            }

            public void OnNetworkReceive(NetPeer peer, NetDataReader reader)
            {

            }

            public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
            {

            }

            public void OnNetworkLatencyUpdate(NetPeer peer, int latency)
            {

            }
        }

        private class ServerListener : INetEventListener
        {
            public NetManager Server;
            private readonly NetSerializer _netSerializer;

            public ServerListener()
            {
                _netSerializer = new NetSerializer();
                _netSerializer.RegisterCustomType( SomeVector2.Serialize, SomeVector2.Deserialize );
                _netSerializer.RegisterCustomType<SampleNetSerializable>();

                //user data support
                _netSerializer.SubscribeReusable<SamplePacket, NetPeer>(OnSamplePacketReceived);
            }

            private void OnSamplePacketReceived(SamplePacket samplePacket, NetPeer peer)
            {
                Console.WriteLine("[Server] ReceivedPacket from {0}:\n{1}", peer.EndPoint, samplePacket);
            }

            public void OnPeerConnected(NetPeer peer)
            {
                Console.WriteLine("[Server] Peer connected: " + peer.EndPoint);
                var peers = Server.GetPeers();
                foreach (var netPeer in peers)
                {
                    Console.WriteLine("ConnectedPeersList: id={0}, ep={1}", netPeer.ConnectId, netPeer.EndPoint);
                }
            }

            public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
            {
                Console.WriteLine("[Server] Peer disconnected: " + peer.EndPoint + ", reason: " + disconnectInfo.Reason);
            }

            public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode)
            {
                Console.WriteLine("[Server] error: " + socketErrorCode);
            }

            public void OnNetworkReceive(NetPeer peer, NetDataReader reader)
            {
                Console.WriteLine("[Server] received data. Processing...");
                _netSerializer.ReadAllPackets(reader, peer);
            }

            public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType)
            {
                Console.WriteLine("[Server] ReceiveUnconnected: {0}", reader.GetString(100));
            }

            public void OnNetworkLatencyUpdate(NetPeer peer, int latency)
            {

            }
        }

        private ClientListener _clientListener;
        private ServerListener _serverListener;

        private void TestPerformance()
        {
            const int LoopLength = 100000;
            //Test serializer performance
            Stopwatch stopwatch = new Stopwatch();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream memoryStream = new MemoryStream();
            NetDataWriter netDataWriter = new NetDataWriter();

            SamplePacket samplePacket = new SamplePacket
            {
                SomeFloat = 0.3f,
                SomeString = "TEST",
                SomeIntArray = new [] { 1, 2, 3 },
                SomeVector2 = new SomeVector2(1, 2),
                SomeVectors = new [] { new SomeVector2(3,4), new SomeVector2(5,6) }
            };

            NetSerializer netSerializer = new NetSerializer();
            netSerializer.RegisterCustomType<SampleNetSerializable>();
            netSerializer.RegisterCustomType( SomeVector2.Serialize, SomeVector2.Deserialize );

            //Prewarm cpu
            for (int i = 0; i < 10000000; i++)
            {
                double c = Math.Sin(i);
            }

            //Test binary formatter
            stopwatch.Start();
            for (int i = 0; i < LoopLength; i++)
            {
                binaryFormatter.Serialize(memoryStream, samplePacket);
            }
            stopwatch.Stop();
            Console.WriteLine("BinaryFormatter time: " + stopwatch.ElapsedMilliseconds + " ms");

            //Test NetSerializer
            stopwatch.Restart();
            for (int i = 0; i < LoopLength; i++)
            {
                netSerializer.Serialize(netDataWriter, samplePacket);
            }
            stopwatch.Stop();
            Console.WriteLine("NetSerializer first run time: " + stopwatch.ElapsedMilliseconds + " ms");

            //Test NetSerializer
            netDataWriter.Reset();
            stopwatch.Restart();
            for (int i = 0; i < LoopLength; i++)
            {
                netSerializer.Serialize(netDataWriter, samplePacket);
            }
            stopwatch.Stop();
            Console.WriteLine("NetSerializer second run time: " + stopwatch.ElapsedMilliseconds + " ms");

            //Test RAW
            netDataWriter.Reset();
            stopwatch.Restart();
            for (int i = 0; i < LoopLength; i++)
            {
                netDataWriter.Put(samplePacket.SomeFloat);
                netDataWriter.Put(samplePacket.SomeString);
                netDataWriter.PutArray(samplePacket.SomeIntArray);
                netDataWriter.Put(samplePacket.SomeVector2.X);
                netDataWriter.Put(samplePacket.SomeVector2.Y);
                netDataWriter.Put(samplePacket.SomeVectors.Length);
                for (int j = 0; j < samplePacket.SomeVectors.Length; j++)
                {
                    netDataWriter.Put(samplePacket.SomeVectors[j].X);
                    netDataWriter.Put(samplePacket.SomeVectors[j].Y);
                }
                netDataWriter.Put(samplePacket.EmptyString);
                netDataWriter.Put(samplePacket.TestObj.Value);
            }
            stopwatch.Stop();
            Console.WriteLine("DataWriter (raw put method calls) time: " + stopwatch.ElapsedMilliseconds + " ms");
        }

        public void Run()
        {
            TestPerformance();

            //Server
            _serverListener = new ServerListener();

            NetManager server = new NetManager(_serverListener, 2, "myapp1");
            if (!server.Start(9050))
            {
                Console.WriteLine("Server start failed");
                Console.ReadKey();
                return;
            }
            _serverListener.Server = server;

            //Client
            _clientListener = new ClientListener();

            NetManager client = new NetManager(_clientListener, "myapp1");
            client.MergeEnabled = true;
            if (!client.Start())
            {
                Console.WriteLine("Client1 start failed");
                return;
            }
            client.Connect("127.0.0.1", 9050);

            while (!Console.KeyAvailable)
            {
                client.PollEvents();
                server.PollEvents();
                Thread.Sleep(15);
            }

            client.Stop();
            server.Stop();
            Console.ReadKey();
            Console.WriteLine("ServStats:\n BytesReceived: {0}\n PacketsReceived: {1}\n BytesSent: {2}\n PacketsSent: {3}",
                server.BytesReceived,
                server.PacketsReceived,
                server.BytesSent,
                server.PacketsSent);
            Console.WriteLine("ClientStats:\n BytesReceived: {0}\n PacketsReceived: {1}\n BytesSent: {2}\n PacketsSent: {3}",
                client.BytesReceived,
                client.PacketsReceived,
                client.BytesSent,
                client.PacketsSent);
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}


text:
/**
 * Luokka sisaltaa JPA-sailot, eli rajapinnat, jotka vastaavat
 * @Entity-annotaatioilla merkittyjen luokkien olioiden
 * tallentamisen tietokantaan ja vastaavasti tietokannasta haettujen rivien
 * muuntamisen @Entity-annotaatiolla merkittyjen luokkien olioiksi.
 */
package sotechat.repo;


text:
twAdminGuardPlugin
==================

Integration of twAdminPlugin with sfGuardPlugin

Installation
------------

  * Install and configure sfGuardPlugin

  * Install and configure twAdminPlugin

Secure your application
-----------------------

To secure a symfony application:

  * Enable the module `twGuardAuth` in `settings.yml`

``` yaml
all:
  .settings:
    enabled_modules: [..., twGuardAuth]
```

  * Change the default login and secure modules in `settings.yml`

``` yaml
login_module:   twGuardAuth
login_action:   signin

secure_module:  twGuardAuth
secure_action:  secure
```

  * Optionally add the following routing rules to `routing.yml`

``` yaml
sf_guard_signin:
  url:   /login
  param: { module: twGuardAuth, action: signin }

sf_guard_signout:
  url:   /logout
  param: { module: twGuardAuth, action: signout }

sf_guard_password:
  url:   /request_password
  param: { module: twGuardAuth, action: password }
```

  You can customize the `url` parameter of each route.
  N.B.: You must have a `@homepage` routing rule (used when a user sign out)

  These routes are automatically registered by the plugin if the module `sfGuardAuth`
  is enabled unless you defined `tw_admin_guard_plugin_routes_register` to false
  in the `app.yml` configuration file:

``` yaml
all:
  tw_admin_guard_plugin:
    routes_register: false
```

  * Secure some modules or your entire application in `security.yml`

``` yaml
default:
  is_secure: on
```

  * You're done. Now, if you try to access a secure page, you will be redirected
    to the login page.
    If you have loaded the default fixture file, try to login with `admin` as
    username and `admin` as password.

Manage your users, permissions and groups
-----------------------------------------

To be able to manage your users, permissions and groups, `sfGuardPlugin` comes
with 3 modules that can be integrated in your backend application.
These modules are auto-generated thanks to the symfony admin generator.

  * Enable the modules in `settings.yml`

``` yaml
all:
  .settings:
    enabled_modules: [..., twAdmin]
```

  * Access the modules with the default route:

        http://www.example.com/backend.php/tw_guard_user

**Rest is the same like in sfGuardPlugin Documentation**


text:
package aerospike

import (
	"fmt"
	"reflect"

	"github.com/aerospike/aerospike-client-go/types"
)

func init() {
	packObjectReflect = concretePackObjectReflect
}

func concretePackObjectReflect(cmd BufferEx, obj interface{}, mapKey bool) (int, error) {
	// check for array and map
	rv := reflect.ValueOf(obj)
	switch reflect.TypeOf(obj).Kind() {
	case reflect.Array, reflect.Slice:
		if mapKey && reflect.TypeOf(obj).Kind() == reflect.Slice {
			return 0, types.NewAerospikeError(types.SERIALIZE_ERROR, fmt.Sprintf("Maps, Slices, and bounded arrays other than Bounded Byte Arrays are not supported as Map keys. Value: %#v", obj))
		}
		// pack bounded array of bytes differently
		if reflect.TypeOf(obj).Kind() == reflect.Array && reflect.TypeOf(obj).Elem().Kind() == reflect.Uint8 {
			l := rv.Len()
			arr := make([]byte, l)
			for i := 0; i < l; i++ {
				arr[i] = rv.Index(i).Interface().(uint8)
			}
			return packBytes(cmd, arr)
		}

		l := rv.Len()
		arr := make([]interface{}, l)
		for i := 0; i < l; i++ {
			arr[i] = rv.Index(i).Interface()
		}
		return packIfcList(cmd, arr)
	case reflect.Map:
		if mapKey {
			return 0, types.NewAerospikeError(types.SERIALIZE_ERROR, fmt.Sprintf("Maps, Slices, and bounded arrays other than Bounded Byte Arrays are not supported as Map keys. Value: %#v", obj))
		}
		l := rv.Len()
		amap := make(map[interface{}]interface{}, l)
		for _, i := range rv.MapKeys() {
			amap[i.Interface()] = rv.MapIndex(i).Interface()
		}
		return packIfcMap(cmd, amap)
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return packObject(cmd, rv.Int(), false)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return packObject(cmd, rv.Uint(), false)
	case reflect.Bool:
		return packObject(cmd, rv.Bool(), false)
	case reflect.String:
		return packObject(cmd, rv.String(), false)
	case reflect.Float32, reflect.Float64:
		return packObject(cmd, rv.Float(), false)
	}

	return 0, types.NewAerospikeError(types.SERIALIZE_ERROR, fmt.Sprintf("Type `%#v` not supported to pack.", obj))
}


text:
FactoryBot.define do
  factory :stock_movement, class: Spree::StockMovement do
    quantity { 1 }
    action   { 'sold' }
    stock_item
  end

  trait :received do
    action { 'received' }
  end
end


text:
package com.thinkbiganalytics.spark;

import com.thinkbiganalytics.spark.conf.LivyWranglerConfig;
import org.apache.spark.SparkContext;
import org.apache.spark.sql.SQLContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 */
public class LivyWrangler {
    private static final Logger logger = LoggerFactory.getLogger(LivyWrangler.class);

    /**
     * Livy will initialize each session by calling this method
     *
     * @param sc         the spark context that was created by Livy
     * @param sqlContext the sqlContext as created by Livy
     * @return a spring application context with services needed for wrangling
     */
    public static ApplicationContext createSpringContext(SparkContext sc, SQLContext sqlContext) {
        logger.info("Creating Spring application context for Livy");

        LivyWranglerConfig.setSparkContext(sc);
        LivyWranglerConfig.setSqlContext(sqlContext);

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.getEnvironment().setActiveProfiles("kylo-livy");
        context.register(LivyWranglerConfig.class);
        context.refresh();

        return context;
    }

} // end class


text:
package mux

import (
	"io"

	waterfall_grpc_pb "github.com/google/waterfall/proto/waterfall_go_grpc"
)

// Message implements stream.MessageReadWriteCloser interface
type Message struct{}

// BuildMsg returns a new message that can be sent through a forwarding stream.
func (sm Message) BuildMsg() interface{} {
	return new(waterfall_grpc_pb.Message)
}

// GetBytes reads the bytes from the message.
func (sm Message) GetBytes(m interface{}) ([]byte, error) {
	msg, ok := m.(*waterfall_grpc_pb.Message)
	if !ok {
		// this never happens
		panic("incorrect type")
	}

	if len(msg.Payload) == 0 {
		return nil, io.EOF
	}
	return msg.Payload, nil
}

// SetBytes sets the meessage bytes.
func (sm Message) SetBytes(m interface{}, b []byte) {
	msg, ok := m.(*waterfall_grpc_pb.Message)
	if !ok {
		// this never happens
		panic("incorrect type")
	}

	msg.Payload = b
}

// CloseMsg returns a new message to notify the other side that the stream is closed.
func (sm Message) CloseMsg() interface{} {
	return &waterfall_grpc_pb.Message{}
}


text:
opensnap-quicktile
==================

What's that?
------------
Opensnap brings the Aero Snap feature to Openbox using quicktile.

Does this work with other window managers?
------------------------------------------
Probably. This is most likely going to be dependant on quicktile.

Dependencies?
-------------
Just quicktile and gtk3 as far as I know. I only use Arch Linux and have not tested this on other distros yet.

Future:
------
Everything seems to do exactly what I want. Make suggestions.

Installing
----------
If you want to install opensnap-quicktile. from source first make sure you have git installed. (Or fetch a zip file: https://github.com/lawl/opensnap/archive/master.zip)

Install from AUR:

    yaourt -S opensnap-quicktile-git

Fetch via git:

    git clone https://github.com/Pr0Wolf29/opensnap-quicktile.git

Fetch via zip:

    wget https://github.com/Pr0Wolf29/opensnap-quicktile/archive/master.zip
    unzip master.zip

Make sure you have all prerequisits:

    sudo apt-get install build-essential libx11-dev libgtk-3-dev
    I have no idea how to install quicktile on apt systems.

And finally build and install it:

    cd opensnap-quicktile*
    make

And now start opensnap-quicktile by

    bin/opensnap-quicktile --daemon


text:
<!-- Auto Generated Below -->

## Properties

| Property      | Attribute     | Description | Type     | Default     |
| ------------- | ------------- | ----------- | -------- | ----------- |
| `placeholder` | `placeholder` |             | `string` | `undefined` |

## Events

| Event      | Description | Type               |
| ---------- | ----------- | ------------------ |
| `search`   |             | `CustomEvent<any>` |
| `selected` |             | `CustomEvent<any>` |

## Methods

### `setItems(items: IAutoCompleteItem[]) => Promise<void>`

#### Returns

Type: `Promise<void>`

----------------------------------------------

*Built with [StencilJS](https://stenciljs.com/)*


text:
import argparse

from . import model

if __name__ == "__main__":

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--train_data_path",
        help="GCS or local path to training data",
        required=True
    )
    parser.add_argument(
        "--train_epochs",
        help="Steps to run the training job for (default: 5)",
        type=int,
        default=10
    )
    parser.add_argument(
        "--eval_data_path",
        help="GCS or local path to evaluation data",
        required=True
    )
    parser.add_argument(
        "--output_dir",
        help="GCS location to write checkpoints and export models",
        required=True
    )
    parser.add_argument(
        "--log_dir",
        help="GCS location to write Tensorboard logs",
        required=True
    )
    parser.add_argument(
        "--job-dir",
        help="This is not used by our model, but it is required by gcloud",
    )
    hparams = parser.parse_args().__dict__

    model.train_and_evaluate(hparams)


text:
/**
 * @author Kyle Brown <blackbarn@gmail.com>
 * @since 10/15/13 9:39 AM
 */
var settingService = require('../setting');
var StatefulSetting = require('../setting/stateful-setting');
var PostProcessService = require('./post-process');

//create stateful setting object for newznab
var postProcessSettings = new StatefulSetting({
    frequency: 'postProcessor:frequency',
    downloadDirectory: 'postProcessor:downloadDirectory',
    destinationDirectory: 'postProcessor:destinationDirectory',
    folderFormat: 'postProcessor:folderFormat',
    fileFormat: 'postProcessor:fileFormat',
    keepOriginalFiles: 'postProcessor:keepOriginalFiles',
    directoryPermissions: 'postProcessor:directoryPermissions',
    opfName: 'postProcessor:opfName'
});

var postProcessService = new PostProcessService(postProcessSettings.get());

postProcessSettings.on('updated', function (options) {
    "use strict";
    postProcessService.updateSettings(options);
});

module.exports = postProcessService;


text:
import MySQLdb as ms

myDB = ms.connect(host = "raj.cjvevq7bmlpd.eu-central-1.rds.amazonaws.com", user = "raj", passwd = "Rajashekar123", db = "rajDB")
cur = myDB.cursor()
cur.execute("select * from sampel")
query = cur.fetchall()
print query

cur.close()
myDB.close()


text:
require 'vk/api/methods'

module Vk
  module API
    class Friends < Vk::Schema::Namespace
      module Methods
        # Returns a list of user IDs of the current user's recently added friends.
        class GetRecent < Schema::Method
          # @!group Properties

          self.open = false
          self.method = 'friends.getRecent'

          # @method initialize(arguments)
          #   @param [Hash] arguments
          #   @option arguments [Integer] :count Number of recently added friends to return.
          #   @return [Friends::Methods::GetRecent]

          # @!group Arguments

          # @return [Integer] Number of recently added friends to return.
          attribute :count, API::Types::Coercible::Int.optional.default(100)
        end
      end
    end
  end
end


text:
package common

import (
	"testing"
)

func TestValidateOnFail(t *testing.T) {
	type testcase struct {
		input       string
		expectError bool
	}

	testcases := []testcase{
		{"", false},
		{"error", false},
		{"default_value", false},
		{"ciphertext", false},
		{"gibberish", true},
	}

	for _, testcase := range testcases {
		err := ValidateOnFail(ResponseOnFail(testcase.input))

		if testcase.expectError && err == nil {
			t.Fatalf("[%s] expected error but found nothing", testcase.input)
		} else if !testcase.expectError && err != nil {
			t.Fatalf("[%s] expected not errors, but found %s", testcase.input, err)
		}
	}
}


text:
package org.m4m.samples.controls;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;

public class GameGLSurfaceView extends GLSurfaceView {
    public GameGLSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setEGLContextClientVersion(2);
    }
}