text:
function($element, $scope, serviceInfo, $stateParams, $timeout, $window, toastr, codeService, ScrollbarService) {
    var vm = {};
    var timer;
    var stepsChart;
    var detailScrollbar;
    $scope.vm = vm;

    vm.maxHeight = ($window.innerHeight - 300) + 'px';
    var resizeFun = function() {
        $scope.$apply(function() {
            vm.maxHeight = ($window.innerHeight - 300) + 'px';
        });
    };
    angular.element($window).on('resize', resizeFun);
    $scope.$on('$destroy', function(e) {
        angular.element($window).off('resize', resizeFun);
        if (timer !== null)
            $timeout.cancel(timer);
    });

    vm.viewSource = function(event) {

        var $this = angular.element(event.currentTarget);
        var ns = $this.attr('jns');
        var name = $this.text();
        codeService.viewCode(ns, name);
    };

    vm.switchArea = function(event) {
        var ele = event.currentTarget;
        var contentEle = d3.select(ele.nextElementSibling);
        var icoEle = d3.select(ele).select('i');
        var isHidden = contentEle.style('display') == 'none';
        contentEle.style('display', isHidden ? '' : 'none');
        icoEle.attr('class', isHidden ? 'fa fa-caret-down' : 'fa fa-caret-right');

    };

    vm.msgHtml = '';

    var urlPattern = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
    var lastTime = {};
    var formatMsg = function(m) {

        if (m.indexOf('[ERROR]') >= 0) {
            m = '' + m + '';
        } else if (m.indexOf('[WARN]') >= 0) {
            m = '' + m + '';
        }

        return m.replace(/\n/g, "
").replace(urlPattern, function(m) {
            return '' + m + '';
        }).replace(/([\t\s]at\s+)([^\(]+)\(([a-z0-9_\$]+\.java\:\d+)\)/gi, function(match, m1, m2, m3) {
            var tmp = m2.split('.');
            var ns;
            if (tmp.length > 3) {
                ns = tmp.slice(0, tmp.length - 2).join('.');
            }

            return m1 + m2 + '(' + m3 + ')';
        }).replace(/^#@#(.+)/, function(match, m1, m2) {

            var timeIndex = m1.lastIndexOf('#');
            var time = new Date(m1.substr(timeIndex + 1));
            var title = m1.substr(0, timeIndex);
            var metaIndex = title.lastIndexOf('@?');
            var meta = {};
            var metaHtml = '';
            if (metaIndex > 0) {
                meta = VIUtil.queryToObj(title.substr(metaIndex + 1));
                title = title.substr(0, metaIndex);
            }

            for (var a in meta) {

                if (a != ' ') {
                    metaHtml += '' + a + ':' + meta[a] + '';
                }
            }

            if ((/^Begin/).test(title)) {
                lastTime[title.substr(6)] = time;
                return '
' + title + metaHtml + '
';
            } else {
                return title + '
 cost: ' + VIUtil.calculateRunTime(time - lastTime[title.substr(4)]) + '' + metaHtml + '
';
            }
        });

    };

    serviceInfo.getComponentInfo($stateParams.id).then(function(data) {
        data.cost = VIUtil.calculateRunTime(data.cost);
        vm.data = data;
        //Uninitiated,Running,Success,Failure

        vm.statusClass = 'status-running';

        var messages = vm.data.messages;

        var html = '';
        for (var i = 0; i < messages.length; i++) {
            var m = messages[i];
            html += formatMsg(m);
        }

        vm.msgHtml = html;

        switch (data.status) {
            case 'Success':
                vm.statusClass = 'status-normal';
                break;
            case 'Failure':
                vm.statusClass = 'status-failed';
                break;
        }

        //nv.addGraph(function() {
        stepsChart = nv.models.stepsChart();
        stepsChart.stepClick(function(d) {
            detailScrollbar.update();
            var ele = document.getElementById(d.id);
            detailScrollbar.scrollTo(0, ele.offsetTop);
        });

        var myScrollbar = ScrollbarService.getInstance('ignitestatusScrollbar');
        myScrollbar.then(function(x) {

            detailScrollbar = x;
        });
        stepsChart.currentIndex(data.currentPluginIndex).currentStatus(data.status);
        d3.select('svg')
            .datum(data.infos)
            .call(stepsChart);

        nv.utils.windowResize(stepsChart.update);
        //   return stepsChart;
        //});
        if (data.status == 'Running') {
            timer = $timeout(updateData, 1000);
        }

    });

    function updateData() {

        serviceInfo.doComponentMethod($stateParams.id, 'getLastStatus', {
            'req': {
                'msgIndex': vm.data.messages.length
            }
        }).then(function(data) {

            switch (data.status) {
                case 'Success':
                    vm.statusClass = 'status-normal';
                    break;
                case 'Failure':
                    vm.statusClass = 'status-failed';
                    break;
            }
            vm.data.status = data.status;
            vm.data.cost = VIUtil.calculateRunTime(data.cost);
            vm.data.currentPluginIndex = data.currentPluginIndex;

            stepsChart.updateStatus(data.currentPluginIndex, data.status);
            var html = '';
            angular.forEach(data.messages, function(value) {
                //vm.data.messages.push(value);
                var toastType = 'info';
                html += formatMsg(value);
                if (value.length > 3) {
                    if (value.indexOf('[WARN]') >= 0) {
                        toastType = 'warning';
                    } else if (value.indexOf('[ERROR]') >= 0) {
                        toastType = 'error';
                        value = value.substr(0, value.indexOf('\r\n'));
                    }
                    if ((/^#@#(.+)/).test(value)) {
                        value = value.substr(3);
                    }
                    toastr[toastType](value);
                }

            });
            vm.msgHtml += html;
            detailScrollbar.update();

            if (data.status == 'Running') {
                timer = $timeout(updateData, 1000);
            }

        });

    }

}


text:
'use strict';

var url = require('url');
var urlJoin = require('../lib/url-join');
var loopback = require('loopback');
var express = require('express');
var swagger = require('../lib/swagger');

var request = require('supertest');
var expect = require('chai').expect;

describe('swagger definition', function() {
  describe('basePath', function() {
    // No basepath on resource doc in 1.2
    it('no longer exists on resource doc', function(done) {
      var app = mountSwagger();

      var getReq = getSwaggerResources(app);
      getReq.end(function(err, res) {
        if (err) return done(err);
        expect(res.body.basePath).to.equal(undefined);
        done();
      });
    });

    it('is "http://{host}/api" by default', function(done) {
      var app = mountSwagger();

      var getReq = getAPIDeclaration(app, 'products');
      getReq.end(function(err, res) {
        if (err) return done(err);
        expect(res.body.basePath).to.equal(url.resolve(getReq.url, '/api'));
        done();
      });
    });

    it('is "http://{host}/{basePath}" when basePath is a path', function(done){
      var app = mountSwagger({ basePath: '/api-root'});

      var getReq = getAPIDeclaration(app, 'products');
      getReq.end(function(err, res) {
        if (err) return done(err);
        var apiRoot = url.resolve(getReq.url, '/api-root');
        expect(res.body.basePath).to.equal(apiRoot);
        done();
      });
    });

    it('infers API basePath from app', function(done){
      var app = mountSwagger({}, {apiRoot: '/custom-api-root'});

      var getReq = getAPIDeclaration(app, 'products');
      getReq.end(function(err, res) {
        if (err) return done(err);
        var apiRoot = url.resolve(getReq.url, '/custom-api-root');
        expect(res.body.basePath).to.equal(apiRoot);
        done();
      });
    });

    it('is reachable when explorer mounting location is changed', function(done){
      var explorerRoot = '/erforscher';
      var app = mountSwagger({}, {explorerRoot: explorerRoot});

      var getReq = getSwaggerResources(app, explorerRoot, 'products');
      getReq.end(function(err, res) {
        if (err) return done(err);
        expect(res.body.basePath).to.be.a('string');
        done();
      });
    });

    it('respects a hardcoded protocol (behind SSL terminator)', function(done){
      var app = mountSwagger({protocol: 'https'});

      var getReq = getAPIDeclaration(app, 'products');
      getReq.end(function(err, res) {
        if (err) return done(err);
        var parsed = url.parse(res.body.basePath);
        expect(parsed.protocol).to.equal('https:');
        done();
      });
    });
  });

  describe('Model definition attributes', function() {
    it('Properly defines basic attributes', function(done) {
      var app = mountSwagger();

      var getReq = getAPIDeclaration(app, 'products');
      getReq.end(function(err, res) {
        if (err) return done(err);
        var data = res.body.models.product;
        expect(data.id).to.equal('product');
        expect(data.required.sort()).to.eql(['aNum', 'foo'].sort());
        expect(data.properties.foo.type).to.equal('string');
        expect(data.properties.bar.type).to.equal('string');
        expect(data.properties.aNum.type).to.equal('number');
        // These will be Numbers for Swagger 2.0
        expect(data.properties.aNum.minimum).to.equal('1');
        expect(data.properties.aNum.maximum).to.equal('10');
        // Should be Number even in 1.2
        expect(data.properties.aNum.defaultValue).to.equal(5);
        done();
      });
    });
  });

  function getSwaggerResources(app, restPath, classPath) {
    return request(app)
      .get(urlJoin(restPath || '/explorer', '/resources', classPath || ''))
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200);
  }

  function getAPIDeclaration(app, className) {
    return getSwaggerResources(app, '', urlJoin('/', className));
  }

  function mountSwagger(options, addlOptions) {
    addlOptions = addlOptions || {};
    var app = createLoopbackAppWithModel(addlOptions.apiRoot);
    var swaggerApp = express();
    swagger(app, swaggerApp, options);
    app.use(addlOptions.explorerRoot || '/explorer', swaggerApp);
    return app;
  }

  function createLoopbackAppWithModel(apiRoot) {
    var app = loopback();

    var Product = loopback.Model.extend('product', {
      foo: {type: 'string', required: true},
      bar: 'string',
      aNum: {type: 'number', min: 1, max: 10, required: true, default: 5}
    });
    Product.attachTo(loopback.memory());
    app.model(Product);

    // Simulate a restApiRoot set in config
    app.set('restApiRoot', apiRoot || '/api');
    app.use(app.get('restApiRoot'), loopback.rest());

    return app;
  }
});

redpajama_set_name: RedPajamaGithub


text:
package camelinaction;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jcache.JCacheConstants;

/**
 * Route used by both foo and bar server.
 * <p/>
 * This route will expose a HTTP server on localhost port 8080 or 9090 and then update a counter value
 * on the clustered hazelcast data-grid. The HTTP server returns the current counter value.
 */
public class CounterRoute extends RouteBuilder {

    private String name;
    private int port;

    public CounterRoute(String name, int port) {
        this.name = name;
        this.port = port;
    }

    @Override
    public void configure() throws Exception {
        // HTTP service
        fromF("jetty:http://localhost:" + port)

            // get the counter from the cache
            .setHeader(JCacheConstants.KEY, constant("myCounter"))
            .to("jcache:myCache?action=get")

            // update the counter using java code
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    Integer counter = exchange.getIn().getBody(Integer.class);
                    if (counter == null) {
                        counter = 0;
                    }
                    counter++;
                    exchange.getIn().setBody(counter);
                }
            })

            // update the counter in the cache
            .setHeader(JCacheConstants.KEY, constant("myCounter"))
            .to("jcache:myCache?action=put")

            // prepare http response
            .log(name + ": counter is now ${body}")
            .setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
            .transform().simple("Counter is now ${body}\n");
    }

}


text:
require 'rubygems'
require 'bundler'
Bundler.setup(:default)
require 'nakamura/test'
require 'nakamura/file'
require 'nakamura/users'
require 'test/unit.rb'
include SlingUsers
include SlingFile

class TC_Kern1045 < Test::Unit::TestCase
  include SlingTest

  def setup
    super
    @fm = FileManager.new(@s)
    @um = UserManager.new(@s)
  end

  def test_search_me
    m = uniqueness()

    # Create some users
    owner = create_user("creator2-#{m}")
    viewer = create_user("manager2-#{m}")
    groupuser = create_user("groupuser2-#{m}")

    @s.switch_user(owner)
    content = uniqueness()
    name = "random-#{content}.txt"
    fileBody = "Add the time to make it sort of random #{Time.now.to_f}."
    res = @fm.upload_pooled_file(name, fileBody, 'text/plain')
    json = JSON.parse(res.body)
    id = json[name]['poolId']

    sleep(5)

    # Search the files that I manage .. should be 1
    res = @s.execute_get(@s.url_for("/var/search/pool/me/manager-all.tidy.json"))
    assert_equal("200",res.code,res.body)
    json = JSON.parse(res.body)
    assert_equal(1, json["results"].length)
    assert_equal(fileBody.length ,json["results"][0]["_length"])

  end

end


text:
import java.io.*;
import java.util.*;
import java.math.*;

public class Main {
  public static void main(String[] args) throws IOException {
    Scanner cin = new Scanner(System.in);
    int t = cin.nextInt();
    while (t-- > 0) {
      BigDecimal a = cin.nextBigDecimal();
      BigDecimal b = cin.nextBigDecimal();
      System.out.println(a.add(b));
    }
  }
}


text:
extern crate uninhabited;

use uninhabited::{
    UninhabitedEnum,
    UninhabitedStruct,
    UninhabitedTupleStruct,
    UninhabitedVariants,
};

// This test checks that uninhabited non-exhaustive types cannot coerce to any type, as the never
// type can.

struct A;

fn can_coerce_never_type_to_anything(x: !) -> A {
    x
}

fn cannot_coerce_empty_enum_to_anything(x: UninhabitedEnum) -> A {
    x //~ ERROR mismatched types
}

fn cannot_coerce_empty_tuple_struct_to_anything(x: UninhabitedTupleStruct) -> A {
    x //~ ERROR mismatched types
}

fn cannot_coerce_empty_struct_to_anything(x: UninhabitedStruct) -> A {
    x //~ ERROR mismatched types
}

fn cannot_coerce_enum_with_empty_variants_to_anything(x: UninhabitedVariants) -> A {
    x //~ ERROR mismatched types
}

fn main() {}


text:
<?php

namespace Ipalaus\OAuth2\Client\Provider;

use League\OAuth2\Client\Provider\ResourceOwnerInterface;

class SpotifyResourceOwner implements ResourceOwnerInterface
{
    /**
     * Raw response
     *
     * @var array
     */
    protected $response;

    /**
     * Creates new resource owner.
     *
     * @param array $response
     */
    public function __construct(array $response = [])
    {
        $this->response = $response;
    }

    /**
     * Get resource owner id.
     *
     * @return string|null
     */
    public function getId()
    {
        return $this->response['id'] ?: null;
    }

    /**
     * Get resource owner birth date.
     *
     * @return string|null
     */
    public function getBirthdate()
    {
        return $this->response['birthdate'] ?: null;
    }

    /**
     * Get resource owner country.
     *
     * @return string|null
     */
    public function getCountry()
    {
        return $this->response['country'] ?: null;
    }

    /**
     * Ger resource owner display name.
     *
     * @return string|null
     */
    public function getDisplayName()
    {
        return $this->response['display_name'] ?: null;
    }

    /**
     * Get resource owner email.
     *
     * @return string|null
     */
    public function getEmail()
    {
        return $this->response['email'] ?: null;
    }

    /**
     * Get resource owner spotify url.
     *
     * @return string|null
     */
    public function getSpotifyUrl()
    {
        if (isset($this->response['external_urls']['spotify'])) {
            return $this->response['external_urls']['spotify'];
        }

        return null;
    }

    /**
     * Get resource owner followers count.
     *
     * @return int|null
     */
    public function getFollowers()
    {
        if(isset($this->response['followers']['total'])) {
            return (int)$this->response['followers']['total'];
        }

        return null;
    }
    /**
     * Get resource owner image.
     *
     * @return string|null
     */
    public function getImage()
    {
        if (isset($this->response['images'][0]['url'])) {
            return $this->response['images'][0]['url'];
        }

        return null;
    }

    /**
     * Get resource owner product.
     *
     * @return string|null
     */
    public function getProduct()
    {
        return $this->response['product'] ?: null;
    }

    /**
     * Get resource owner type.
     *
     * @return string|null
     */
    public function getType()
    {
        return $this->response['type'] ?: null;
    }

    /**
     * Get resource owner uri.
     *
     * @return string|null
     */
    public function getUri()
    {
        return $this->response['uri'] ?: null;
    }

    /**
     * Return all of the owner details available as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return $this->response;
    }
}


text:
package com.carrotsearch.randomizedtesting;

import static org.junit.Assert.assertTrue;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.carrotsearch.randomizedtesting.annotations.Nightly;
import com.carrotsearch.randomizedtesting.annotations.TestGroup;

/**
 * Nightly mode checks.
 */
public class TestNightlyMode extends WithNestedTestClass {
  public static class Nested extends RandomizedTest {
    @Test
    public void passOnNightlyOnly() {
      assumeRunningNested();
      assertTrue(isNightly());
    }

    @Test @Nightly("Nightly only test case.")
    public void nightlyOnly() throws Exception {
    }
  }

  @Test
  public void invalidValueNightly() {
    System.setProperty(TestGroup.Utilities.getSysProperty(Nightly.class), "invalid-value");
    dailyDefault();
  }

  @Test
  public void nightly() {
    System.setProperty(TestGroup.Utilities.getSysProperty(Nightly.class), "yes");
    checkTestsOutput(2, 0, 0, 0, Nested.class);
  }

  @Test
  public void dailyDefault() {
    checkTestsOutput(2, 0, 1, 1, Nested.class);
  }

  @Before
  public void cleanupBefore() {
    cleanupAfter();
  }

  @After
  public void cleanupAfter() {
    System.clearProperty(TestGroup.Utilities.getSysProperty(Nightly.class));
  }
}


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.ui.widget;

import android.content.Context;
import android.text.Layout;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * A TextView with an accurate width calculation support for multilines.
 * This is used when we want no extra padding on a multiline TextView. The class perform the width
 * calculation in the overwritten OnMeasure() method.
 */
public class TextViewWithTightWrap extends TextView {
    /**
     * Constructing TextViewWithTightWrap programmatically is similar to a normal TextView.
     */
    public TextViewWithTightWrap(Context context) {
        super(context);
    }

    /** Constructor for use from XML. */
    public TextViewWithTightWrap(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /** Constructor for use from XML. */
    public TextViewWithTightWrap(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        Layout layout = getLayout();
        if (layout != null && layout.getLineCount() > 1) {
            int width =
                    getMaxLineWidth(layout) + getCompoundPaddingLeft() + getCompoundPaddingRight();
            int height = getMeasuredHeight();
            if (width < getMeasuredWidth()) {
                super.onMeasure(
                        MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), heightMeasureSpec);
            }
        }
    }

    private int getMaxLineWidth(Layout layout) {
        float maxWidth = 0;
        int lines = layout.getLineCount();
        for (int i = 0; i < lines; i++) {
            maxWidth = Math.max(maxWidth, layout.getLineWidth(i));
        }
        return (int) Math.ceil(maxWidth);
    }
}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :beaches
  has_many :images

  has_many :visits
  has_many :visited_beaches, through: :visits, source: :beach

  has_many :beach_upvotes, dependent: :destroy
  has_many :upvoted_beaches, through: :beach_upvotes, source: :beach
  has_many :beach_downvotes, dependent: :destroy
  has_many :downvoted_beaches, through: :beach_downvotes, source: :beach

  has_many :comment_upvotes, dependent: :destroy
  has_many :upvoted_comments, through: :comment_upvotes, source: :comment
  has_many :comment_downvotes, dependent: :destroy
  has_many :downvoted_comments, through: :comment_downvotes, source: :comment

  def not_visited
    Beach.all.select{|beach| !beach.visitors.include?(self)}
  end

end


text:
<?php

namespace Micayael\FileCloudManager\AdminBundle\Form\Type;

use Doctrine\ORM\EntityRepository;
use FOS\UserBundle\Form\Type\RegistrationFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ClienteType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nombre')
            ->add('apellido')
            ->add('activo', 'checkbox', array(
                'label' => '¿Habilitar Usuario?',
                'required' => false,
//                    'data' => false
            ))
            ->add('usuario', new RegistrationFormType('Micayael\FileCloudManager\AdminBundle\Entity\Usuario'))
            ->add('save', 'submit', array('label' => 'Grabar'))
            ->add('saveAndAdd', 'submit', array('label' => 'Grabar y Crear Otro'));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'Micayael\FileCloudManager\AdminBundle\Entity\Cliente',
                'cascade_validation' => true,
            )
        );
    }

    public function getName()
    {
        return 'cliente';
    }
}


text:
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }} - Energietechnik, Mietgeneratoren, Notstrom{% endif %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="{{ site.keywords }}">
    <meta name="description" content="{{ site.description }}">
    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

    <link rel="stylesheet" href="{{ "/style.css" | prepend: site.baseurl }}">

    <!-- Custom Fonts -->
    <link rel="stylesheet" href="{{ "/css/font-awesome/css/font-awesome.min.css" | prepend: site.baseurl }}">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>


text:
package com.futureprocessing.documentjuggler.update.command;

import com.futureprocessing.documentjuggler.update.RootUpdateBuilder;
import com.futureprocessing.documentjuggler.update.UpdateBuilder;
import com.mongodb.BasicDBObject;
import org.junit.Test;

import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;

public class AddToSetCollectionUpdateCommandTest {

    private static final String FIELD = "testField";
    private static final String VALUE_1 = "SomeValue";
    private static final String VALUE_2 = "AnotherValue";

    private UpdateCommand command = new AddToSetCollectionUpdateCommand(FIELD);

    @Test
    public void shouldAddToSet() {
        // given
        UpdateBuilder builder = new RootUpdateBuilder();

        // when
        command.update(builder, new Object[]{asList(VALUE_1, VALUE_2)});

        // then
        BasicDBObject expected = new BasicDBObject("$addToSet", new BasicDBObject(FIELD, new BasicDBObject("$each", asList(VALUE_1, VALUE_2))));
        assertThat(builder.getDocument()).isEqualTo(expected);
    }

}


text:
import sys

from ddb_ngsflow import pipeline

def run_delly2_single(job, config, name, input_bam):
    """Run delly2 for structural variant detection. As delly2 is parallelized on the level of samples,
    we use a single-threaded version
    :param config: The configuration dictionary.
    :type config: dict.
    :param sample: sample name.
    :type sample: str.
    :param input_bam: The input_bam file name to process.
    :type input_bam: str.
    :returns:  str -- The merged Delly output vcf file name.
    """

    delly_vcfs = list()
    delly_command_core = ("{}".format(config['delly']['bin']),
                          "-x",
                          "{}".format(config['delly']['exclude']),
                          "-g",
                          "{}".format(config['reference']))

    for mut_type in ["DEL", "DUP", "TRA", "INV"]:
        output_vcf = "{sample}.{type}.vcf".format(sample=name, type=mut_type)
        logfile = "{sample}.{type}.log".format(sample=name, type=mut_type)

        delly_vcfs.append(output_vcf)

        delly_command = list()
        delly_command.append(delly_command_core)
        delly_command.append("-t",
                             "{}".format(mut_type),
                             "-o",
                             "{}".format(output_vcf),
                             "{}".format(input_bam))

        job.fileStore.logToMaster("Running Delly: {}\n".format(delly_command))
        pipeline.run_and_log_command(" ".join(delly_command), logfile)

    job.fileStore.logToMaster("Merging delly output with command: {}\n".format(merge_command))
    pipeline.run_and_log_command(" ".join(merge_command), merge_log)

    return merged_vcf


text:
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCommunicationLib.Communication.MarionetteComands
{
    public class SwitchToWindowCommand : MarionetteDebuggerCommand
    {
        public SwitchToWindowCommand(string name, int id = 0, string commandName = "switchToWindow") : base(id, commandName)
        {
            Name = name;
        }
        public string Name { get; set; }
        public override void ProcessResponse(JToken response)
        {
            base.ProcessResponse(response);
        }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(
                new object[]
                {
                   0,
                   Id,
                   CommandName,
                   new {
                        name = Name
                   }

                });

        }
    }
}


text:
package scoverage

import java.io.{File => SupportFile}
import java.io.{FileFilter => SupportFileFilter}
import java.io.{FileWriter => SupportFileWriter}

import scala.collection.concurrent.TrieMap
import scala.io.{Source => SupportSource}

object Platform {
  type ThreadSafeMap[A, B] = TrieMap[A, B]
  lazy val ThreadSafeMap = TrieMap

  type File = SupportFile
  type FileWriter = SupportFileWriter
  type FileFilter = SupportFileFilter

  lazy val Source = SupportSource

  def insecureRandomUUID() = java.util.UUID.randomUUID()

}


text:
using Kubeless.Core.Interfaces;
using Kubeless.Core.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Kubeless.Core.Tests.Utils
{
    public static class FunctionCreator
    {
        private static IFunctionSettings BuildFunctionSettings(string functionFile, string moduleName, string functionHandler, string requirementsFile = "")
        {
            var basePath = Path.GetDirectoryName(functionFile);
            var baseName = Path.GetFileNameWithoutExtension(functionFile);

            var assembly = new BinaryContent(Path.Combine(basePath, $"{baseName}.dll"));

            return new FunctionSettings(moduleName, functionHandler, assembly);
        }

        public static IFunction CreateFunction(string functionFile, string requirementsFile = "", string moduleName = "module", string functionHandler = "handler")
        {
            var settings = BuildFunctionSettings(functionFile, moduleName, functionHandler, requirementsFile);
            return new Function(settings);
        }
    }
}


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

using Docker.DotNet;
using Microsoft.Azure.Management.ContainerInstance.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.Storage.Fluent;
using Microsoft.Azure.Management.Storage.Fluent.Models;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using System;

namespace ManageWithManualAzureFileShareMountCreation
{
    public class Program
    {
        private static readonly Region region = Region.USEast;

        private async static void CreateFileShare(string saName, string storageAccountKey, string shareName)
        {
            CloudFileShare cloudFileShare = CloudStorageAccount.Parse(
                $"DefaultEndpointsProtocol=https;AccountName={saName};AccountKey={storageAccountKey};EndpointSuffix=core.windows.net")
                .CreateCloudFileClient()
                .GetShareReference(shareName);
            await cloudFileShare.CreateAsync();
        }

        /**
         * Azure Container Instance sample for managing container instances with Azure File Share mount.
         *    - Create a storage account and an Azure file share resource
         *    - Create an Azure container instance using Docker image "seanmckenna/aci-hellofiles" with a mount to the file share from above
         *    - Retrieve container log content
         *    - Delete the container group resource
         */
        public static void RunSample(IAzure azure)
        {
            string rgName = SdkContext.RandomResourceName("rgACI", 15);
            string aciName = SdkContext.RandomResourceName("acisample", 20);
            string saName = SdkContext.RandomResourceName("sa", 20);
            string shareName = SdkContext.RandomResourceName("fileshare", 20);
            string containerImageName = "seanmckenna/aci-hellofiles";
            string volumeMountName = "aci-helloshare";

            try
            {
                //=============================================================
                // Create a new storage account and an Azure file share resource

                IStorageAccount storageAccount = azure.StorageAccounts.Define(saName)
                    .WithRegion(region)
                    .WithNewResourceGroup(rgName)
                    .Create();

                StorageAccountKey storageAccountKey = storageAccount.GetKeys()[0];

                CreateFileShare(saName, storageAccountKey.Value, shareName);

                //=============================================================
                // Create a container group with one container instance of default CPU core count and memory size
                //   using public Docker image "seanmckenna/aci-hellofiles" which mounts the file share created previously
                //   as read/write shared container volume.
                IContainerGroup containerGroup = azure.ContainerGroups.Define(aciName)
                    .WithRegion(region)
                    .WithNewResourceGroup(rgName)
                    .WithLinux()
                    .WithPublicImageRegistryOnly()
                    .DefineVolume(volumeMountName)
                        .WithExistingReadWriteAzureFileShare(shareName)
                        .WithStorageAccountName(saName)
                        .WithStorageAccountKey(storageAccountKey.Value)
                        .Attach()
                    .DefineContainerInstance(aciName)
                        .WithImage(containerImageName)
                        .WithExternalTcpPort(80)
                        .WithVolumeMountSetting(volumeMountName, "/aci/logs/")
                        .Attach()
                    .Create();

                Utilities.Print(containerGroup);

                SdkContext.DelayProvider.Delay(20000);
                Utilities.Log("Container instance IP address: " + containerGroup.IPAddress);

                //=============================================================
                // Check the container instance logs

                containerGroup = azure.ContainerGroups.GetByResourceGroup(rgName, aciName);
                string logContent = containerGroup.GetLogContent(aciName);
                Utilities.Log($"Logs for container instance: {aciName}\n{logContent}");

                //=============================================================
                // Remove the container group

                azure.ContainerGroups.DeleteById(containerGroup.Id);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.BeginDeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (Exception)
                {
                    Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
                }
            }
        }

        public static void Main(string[] args)
        {
            try
            {
                //=================================================================
                // Authenticate
                AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));

                var azure = Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithDefaultSubscription();

                // Print selected subscription
                Utilities.Log("Selected subscription: " + azure.SubscriptionId);

                RunSample(azure);
            }
            catch (Exception ex)
            {
                Utilities.Log(ex);
            }
        }
    }
}


text:
aizuddinmanap@gmail.com

### Register free 6 month trial of Google Developers.
* Enable Google Prediction API and Google Cloud Storage.
* Generate Client ID with Service Account Type

### Upload Training Data

In this step you will upload a file of training data to your Google Cloud Storage account.

* Upload the file(language_id.txt) to Google Cloud Storage:
* Go to the Google Developers Console.
* Select the project under which to store the data.
* Select the "Cloud Storage" tab.
* Click "New Bucket" or select an existing bucket.
* Click on the bucket to which to upload the file, and click "Upload"
* Create a new bucket by clicking New Bucket.
* Select the bucket and click Upload, and upload the language_id.txt file from your computer.
* Copy the bucket/path name of your file from the path column in the Google Cloud Storage Manager. For example: mybucket/language_id.txt

### composer update
Run:

```sh
composer update
```

### Train the System

The next step is to train the system against the training data that you uploaded.

Run:

```sh
http://localhost/php-google-prediction/train.php
```

### Send Queries

Now you're ready to send queries to your model. Queries are always in the format of a single row of training data, minus the first column. Your training data had two columns: language_label, phrase_in_that_language; therefore a query against this data consists of a single column: a phrase in a language that you want to identify. Your phrase must be in one of the languages used in your training data. Google Prediction replies with its best guess at the language of your phrase.

Run:

```sh
http://localhost/php-google-prediction/predict.php
```

### License
----

MIT

aizuddinmanap@gmail.com


text:
"""1846. Maximum Element After Decreasing and Rearranging
https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/
"""
from typing import List

class Solution:
    def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:
        arr.sort()
        arr[0] = 1
        for i in range(1, len(arr)):
            if arr[i] - arr[i - 1] > 1:
                arr[i] = arr[i - 1] + 1
        return arr[-1]

    def maximumElementAfterDecrementingAndRearranging2(self, arr: List[int]) -> int:
        n = len(arr)
        cnt = [0] * (n + 1)
        for num in arr:
            if num <= n:
                cnt[num] += 1
            else:
                cnt[n] += 1
        miss = 0
        for i in range(1, n + 1):
            if cnt[i] == 0:
                miss += 1
            else:
                miss -= min(cnt[i] - 1, miss)
        return n - miss