text:
package io.reactivex.internal.operators.observable;

import io.reactivex.internal.functions.ObjectHelper;
import java.util.*;
import java.util.concurrent.Callable;

import io.reactivex.*;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.internal.disposables.*;
import io.reactivex.internal.functions.Functions;
import io.reactivex.internal.fuseable.FuseToObservable;
import io.reactivex.plugins.RxJavaPlugins;

public final class ObservableToListSingle<T, U extends Collection<? super T>>
extends Single<U> implements FuseToObservable<U> {

    final ObservableSource<T> source;

    final Callable<U> collectionSupplier;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public ObservableToListSingle(ObservableSource<T> source, final int defaultCapacityHint) {
        this.source = source;
        this.collectionSupplier = (Callable)Functions.createArrayList(defaultCapacityHint);
    }

    public ObservableToListSingle(ObservableSource<T> source, Callable<U> collectionSupplier) {
        this.source = source;
        this.collectionSupplier = collectionSupplier;
    }

    @Override
    public void subscribeActual(SingleObserver<? super U> t) {
        U coll;
        try {
            coll = ObjectHelper.requireNonNull(collectionSupplier.call(), "The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources.");
        } catch (Throwable e) {
            Exceptions.throwIfFatal(e);
            EmptyDisposable.error(e, t);
            return;
        }
        source.subscribe(new ToListObserver<T, U>(t, coll));
    }

    @Override
    public Observable<U> fuseToObservable() {
        return RxJavaPlugins.onAssembly(new ObservableToList<T, U>(source, collectionSupplier));
    }

    static final class ToListObserver<T, U extends Collection<? super T>> implements Observer<T>, Disposable {
        final SingleObserver<? super U> downstream;

        U collection;

        Disposable upstream;

        ToListObserver(SingleObserver<? super U> actual, U collection) {
            this.downstream = actual;
            this.collection = collection;
        }

        @Override
        public void onSubscribe(Disposable d) {
            if (DisposableHelper.validate(this.upstream, d)) {
                this.upstream = d;
                downstream.onSubscribe(this);
            }
        }

        @Override
        public void dispose() {
            upstream.dispose();
        }

        @Override
        public boolean isDisposed() {
            return upstream.isDisposed();
        }

        @Override
        public void onNext(T t) {
            collection.add(t);
        }

        @Override
        public void onError(Throwable t) {
            collection = null;
            downstream.onError(t);
        }

        @Override
        public void onComplete() {
            U c = collection;
            collection = null;
            downstream.onSuccess(c);
        }
    }
}


text:
References
==========

.. [Aylward2016] Aylward, S. R., McCormick, M. M., Kang H. J., Razzaque, S.,
  R. Kwitt, R., and M. Niethammer. Ultrasound spectroscopy. 2016 IEEE International
  Symposium on Biomedical Imaging: From Nano to Macro, ISBI 2016 - Proceedings.
  Prague, Czech Republic. 1013-1016. 2016.
  http://dx.doi.org/10.1109/ISBI.2016.7493437.

.. [Fedorov2012] Fedorov A., Beichel R., Kalpathy-Cramer J., Finet J.,
  Fillion-Robin J-C., Pujol S., Bauer C., Jennings D., Fennessy F., Sonka M.,
  Buatti J., Aylward S.R., Miller J.V., Pieper S., Kikinis R. 3D Slicer as an
  Image Computing Platform for the Quantitative Imaging Network. Magnetic
  Resonance Imaging 2012; July PMID: 22770690.

.. [Lasso2014] Lasso A., Heffter T., Rankin A., Pinter C., Ungi T., Fichtinger
  G. 2014. PLUS: open-source toolkit for ultrasound-guided intervention systems.
  IEEE transactions on bio-medical engineering 61:2527–2537.
  http://dx.doi.org/10.1109/TBME.2014.2322864

.. [McCormick2010] McCormick, M. An Open Source, Fast Ultrasound B-Mode
  Implementation for Commodity Hardware. Insight Journal. 2010 January-June. URL:
  http://hdl.handle.net/10380/3159

.. [McCormick2014] McCormick, M., Liu, X., Jomier, J., Marion, C. Ibanez, L.
  ITK: Enabling Reproducible Research and Open Science.  Front. Neuroinform. 8:13. 2014.
  http://dx.doi.org/10.3389/fninf.2014.00013. PMID: 24600387. PMCID: PMC3929840.

.. [Palmeri2016] Palmeri M., Glass T., Gupta R., McCormick M., Brown A.,
  Polascik T., Rosenzweig S., Buck A., Nightingale K., "Comparison between 3D ARFI
  imaging and mpMRI in detecting clinically-significant prostate cancer lesions," 2016
  IEEE International Ultrasonics Symposium (IUS), Tours, 2016, pp. 1-4.
  http://dx.doi.org/10.1109/ULTSYM.2016.7728618

redpajama_set_name: RedPajamaGithub


text:
<subscriber city="Plunk" state="WA" zip="98059">
  <name>John Smith</name>
  <street>12345 Happy Lane</street>
</subscriber>


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

using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Menu;
using Senparc.Weixin.MP;
using Senparc.Weixin.HttpUtility;
using Senparc.Weixin.Helpers;

namespace Wechat.Menu
{
    class Program
    {
        static void Main(string[] args)
        {
#if SETTING
            string appId = System.Configuration.ConfigurationManager.AppSettings["AppId"].ToString();
            string appSecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
            string appWebUrl = System.Configuration.ConfigurationManager.AppSettings["AppWebUrl"].ToString();
#else
            string appId = "wx4df221a4e9845aea";
            string appSecret = "c2c6e3220de9609c79e3d1f425bba0fb";
            string appHost = "http://recruit.casco.com.cn";

#endif

            var appOauth2 = appHost + "/oauth";
            var appUrl =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect",
                                appId, appOauth2.UrlEncode(), "code", "snsapi_userinfo", "1");

            ButtonGroup btGroup = new ButtonGroup();
            var serviceButton = new SingleViewButton() {
                name = "在线服务",
                url = appUrl
            };
            var userButton = new SubButton() { name = "个人中心" };
            userButton.sub_button.Add(new SingleClickButton()
            {
                name = "账号绑定",
                type = ButtonType.click.ToString(),
                key = "UserBind"
            });
            userButton.sub_button.Add(new SingleClickButton()
            {
                name = "个人信息",
                type = ButtonType.click.ToString(),
                key = "UserInfo"
            });

            btGroup.button.Add(serviceButton);
            btGroup.button.Add(userButton);

            var accessToken = AccessTokenContainer.TryGetToken(appId, appSecret);
            WxJsonResult result = CommonApi.CreateMenu(accessToken, btGroup);
            if (result.errmsg != null && result.errmsg != "ok")
            {
                Console.WriteLine(result.errmsg);
                Console.WriteLine("------------------->Build Error!");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Success!");
                Console.ReadKey();
            }

        }
    }
}


text:
package org.motechproject.commcare.web;

import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpStatus;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.motechproject.commcare.domain.AppStructureResponseJson;
import org.motechproject.commcare.domain.CommcareApplication;
import org.motechproject.commcare.domain.CommcareApplicationJson;
import org.motechproject.commcare.repository.AllCommcareApplications;
import org.motechproject.commons.api.json.MotechJsonReader;
import org.springframework.test.web.server.MockMvc;
import org.springframework.test.web.server.setup.MockMvcBuilders;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;

public class SchemaControllerTest {

    @Mock
    private AllCommcareApplications allCommcareApplications;

    @InjectMocks
    private SchemaController schemaController = new SchemaController();

    private MockMvc controller;

    private MotechJsonReader motechJsonReader = new MotechJsonReader();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Before
    public void setUp() throws Exception {
        initMocks(this);

        controller = MockMvcBuilders.standaloneSetup(schemaController).build();
    }

    @Test
    public void shouldReturnAppStructure() throws Exception {
        List<CommcareApplicationJson> apps = application();
        List<CommcareApplication> appsFromDatabase = convert(apps);
        when(allCommcareApplications.getAll()).thenReturn(appsFromDatabase);

        final String expectedResponse = objectMapper.writeValueAsString(apps);

        controller.perform(
                get("/schema")
        ).andExpect(
                status().is(HttpStatus.SC_OK)
        ).andExpect(
                content().type("application/json;charset=UTF-8")
        ).andExpect(
                content().string(expectedResponse)
        );
    }

    private List<CommcareApplication> convert(List<CommcareApplicationJson> apps) {
        List<CommcareApplication> result = new ArrayList();
        for (CommcareApplicationJson app : apps) {
            result.add(new CommcareApplication(app.getApplicationName(), app.getResourceUri(), app.getModules()));
        }
        return result;
    }

    private List<CommcareApplicationJson> application() throws IOException {
        try (InputStream in = getClass().getClassLoader().getResourceAsStream("json/service/appStructure.json")) {
            Type appStructureResponseType = new TypeToken<AppStructureResponseJson>() {}.getType();
            return ((AppStructureResponseJson) motechJsonReader.readFromStream(in, appStructureResponseType))
                    .getApplications();
        }
    }
}


text:
import inheritedPropertyDescriptor = require( './index' );

// TESTS //

// The function returns a property descriptor...
{
	inheritedPropertyDescriptor( { 'beep': 2.0, 'foo': 3.14 }, 'toString' ); // $ExpectType TypedPropertyDescriptor<any> | null
	inheritedPropertyDescriptor( { 'beep': false, 'foo': true }, 'toString' ); // $ExpectType TypedPropertyDescriptor<any> | null
}

// The compiler throws an error if the function is provided a second argument which is not a string or symbol...
{
	inheritedPropertyDescriptor( { 'beep': 2.0, 'foo': 3.14 }, true ); // $ExpectError
	inheritedPropertyDescriptor( { 'beep': 2.0, 'foo': 3.14 }, 3.12 ); // $ExpectError
	inheritedPropertyDescriptor( { 'beep': 2.0, 'foo': 3.14 }, [] ); // $ExpectError
	inheritedPropertyDescriptor( { 'beep': 2.0, 'foo': 3.14 }, {} ); // $ExpectError
	inheritedPropertyDescriptor( { 'beep': 2.0, 'foo': 3.14 }, ( x: number ): number => x * 2 ); // $ExpectError
}

// The compiler throws an error if the function is provided an incorrect number of arguments...
{
	inheritedPropertyDescriptor(); // $ExpectError
	inheritedPropertyDescriptor( {}, 2 ); // $ExpectError
}


text:
set -e

mkdir -p compiled
cp -r docker docker-compose.yml db-config.php compiled/
tre make.lisp


text:
package ru.job4j.area;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.number.IsCloseTo.closeTo;

/**
* TriangleTest class.
* @author Yury Chuksin (chuksin.yury@gmail.com)
* @since 17.01.2017
*/
public class TriangleTest {

	/**
	* Making object Triangle.
	* @param a first point of this triangle
	* @param a second point of this triangle
	* @param a third point of this triangle
	*/
	private Triangle trOne = new Triangle(new Point(-2, 0), new Point(2, -5), new Point(3, 3));

	/**
	* Cheking value of this triangle area.
	*/
	private final double chekS = 18.5;

	/**
	* whenDoAreaMethodThenCalculatesAreaOfTriangle calculates area of this triangle.
	*/
	@Test
	public void whenDoAreaMethodThenCalculatesAreaOfTriangle() {
		double result = this.trOne.area();
		assertThat(chekS, is(closeTo(result, 0.1)));
	}
}


text:
/*	author:@shivkrthakur  */
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
            int[] userReturnDate = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
            int[] actualReturnDate = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);

            if (userReturnDate[2] == actualReturnDate[2])
            {
                if (userReturnDate[1] == actualReturnDate[1])
                {
                    if (userReturnDate[0] > actualReturnDate[0])
                    {
                        int days = userReturnDate[0] - actualReturnDate[0];
                        Console.WriteLine(15 * days);
                        return;
                    }
                }
                else if (userReturnDate[1] > actualReturnDate[1])
                {
                    int monthsLate = userReturnDate[1] - actualReturnDate[1];
                    Console.WriteLine(500 * monthsLate);
                    return;
                }
            }
            else if (userReturnDate[2] > actualReturnDate[2])
            {
                Console.WriteLine("10000");
                return;
            }
            Console.WriteLine("0");
    }
}


text:
<ui>
    <menubar name="MainMenu">
        <menu name="ToolsMenu" action="ToolsMenuAction">
            <menu name="Audioscrobbler" action="AudioscrobblerAction">
                    <menuitem name="AudioscrobblerEnable" action="AudioscrobblerEnableAction" />
                    <menuitem name="AudioscrobblerVisit" action="AudioscrobblerVisitAction" />
            </menu>
        </menu>
    </menubar>
</ui>


text:
export default function ModifiedSurface (Surface) {
  class _ModifiedSurface extends Surface {
    constructor (parent, props, options) {
      super(parent, _monkeyPatchSurfaceProps(parent, props), options)
    }

    setProps (newProps) {
      return super.setProps(_monkeyPatchSurfaceProps(this.parent, newProps))
    }
  }
  return _ModifiedSurface
}

function _monkeyPatchSurfaceProps (parent, props) {
  let newProps = Object.assign({}, props)
  if (props.model && !props.node) {
    const model = props.model
    switch (model.type) {
      case 'collection': {
        newProps.containerPath = model._path
        break
      }
      default: {
        // TODO: do we really need this anymore?
        if (model._node) {
          newProps.node = model._node
        }
      }
    }
  }
  return newProps
}


text:
This role installs and configures `rsyslog` (4.6.x).

`rsyslog` collects logs on each node and sends it to the `rsyslog` server,
where it gets processed by `hekad`.

See http://rsyslog.com/ for details.

# Example Playbook

An example of how to use this role:

    - hosts: all
      roles:
         - { role: rsyslog }

# License

MIT

# Author Information

Christian Trabold <typo3@christian-trabold.de>


text:
#ifndef COMPAT_H
#define COMPAT_H

#if defined (HAVE_INTTYPES_H) && (defined(__osf__) || defined(_HPUX_SOURCE))
#  include <inttypes.h>
#endif

/* well, this is obviously wrong since it assumes it's 64bit, but older
   GCCs don't define it and we really want it. */
#ifndef LLONG_MAX
#  define LLONG_MAX 9223372036854775807LL
#endif

#ifndef __cplusplus
#ifdef HAVE__BOOL
typedef _Bool bool;
#else
typedef int bool;
#endif
#endif

#if defined (HAVE_UOFF_T)
/* native support */
#elif defined (UOFF_T_INT)
typedef unsigned int uoff_t;
#elif defined (UOFF_T_LONG)
typedef unsigned long uoff_t;
#elif defined (UOFF_T_LONG_LONG)
typedef unsigned long long uoff_t;
#else
#  error uoff_t size not set
#endif

#ifndef HAVE_UINTMAX_T
#  if SIZEOF_LONG_LONG > 0
typedef unsigned long long uintmax_t;
#  else
typedef unsigned long uintmax_t;
#  endif
#endif

#ifndef HAVE_UINT_FAST32_T
#  if SIZEOF_INT >= 4
typedef unsigned int uint_fast32_t;
#  else
typedef unsigned long uint_fast32_t;
#  endif
#endif

#ifndef HAVE_SOCKLEN_T
typedef int socklen_t;
#endif

#ifdef HAVE_SYS_SYSMACROS_H
#  include <sys/sysmacros.h>
#  ifdef HAVE_SYS_MKDEV_H
#    include <sys/mkdev.h> /* UnixWare */
#  endif
#  define CMP_DEV_T(a, b) (major(a) == major(b) && minor(a) == minor(b))
#elif !defined (DEV_T_STRUCT)
#  define CMP_DEV_T(a, b) ((a) == (b))
#else
#  error I do not know how to compare dev_t
#endif

#ifdef HAVE_STAT_XTIM
#  define HAVE_ST_NSECS
#  define ST_ATIME_NSEC(st) ((unsigned long)(st).st_atim.tv_nsec)
#  define ST_MTIME_NSEC(st) ((unsigned long)(st).st_mtim.tv_nsec)
#  define ST_CTIME_NSEC(st) ((unsigned long)(st).st_ctim.tv_nsec)
#elif defined (HAVE_STAT_XTIMESPEC)
#  define HAVE_ST_NSECS
#  define ST_ATIME_NSEC(st) ((unsigned long)(st).st_atimespec.tv_nsec)
#  define ST_MTIME_NSEC(st) ((unsigned long)(st).st_mtimespec.tv_nsec)
#  define ST_CTIME_NSEC(st) ((unsigned long)(st).st_ctimespec.tv_nsec)
#else
#  define ST_ATIME_NSEC(st) 0UL
#  define ST_MTIME_NSEC(st) 0UL
#  define ST_CTIME_NSEC(st) 0UL
#endif

#ifdef HAVE_ST_NSECS
/* TRUE if a nanosecond timestamp from struct stat matches another nanosecond.
   If nanoseconds aren't supported in struct stat, returns always TRUE (useful
   with NFS if some hosts support nanoseconds and others don't). */
#  define ST_NTIMES_EQUAL(ns1, ns2) ((ns1) == (ns2))
#else
#  define ST_NTIMES_EQUAL(ns1, ns2) TRUE
#endif

#define CMP_ST_MTIME(st1, st2) \
	((st1)->st_mtime == (st2)->st_mtime && \
	 ST_NTIMES_EQUAL(ST_MTIME_NSEC(*(st1)), ST_MTIME_NSEC(*(st2))))
#define CMP_ST_CTIME(st1, st2) \
	((st1)->st_ctime == (st2)->st_ctime && \
	 ST_NTIMES_EQUAL(ST_CTIME_NSEC(*(st1)), ST_CTIME_NSEC(*(st2))))

/* strcasecmp(), strncasecmp() */
#ifndef HAVE_STRCASECMP
#  ifdef HAVE_STRICMP
#    define strcasecmp stricmp
#    define strncasecmp strnicmp
#  else
#    define strcasecmp i_my_strcasecmp
#    define strncasecmp i_my_strncasecmp
int i_my_strcasecmp(const char *s1, const char *s2);
int i_my_strncasecmp(const char *s1, const char *s2, size_t max_chars);
#  endif
#endif

#ifndef HAVE_INET_ATON
#  include <sys/socket.h>
#  include <netinet/in.h>
#  include <arpa/inet.h>
#  define inet_aton i_my_inet_aton
int i_my_inet_aton(const char *cp, struct in_addr *inp);
#endif

#ifndef HAVE_VSYSLOG
#  define vsyslog i_my_vsyslog
void i_my_vsyslog(int priority, const char *format, va_list args);
#endif

#ifndef HAVE_GETPAGESIZE
#  define getpagesize i_my_getpagesize
int i_my_getpagesize(void);
#endif

#ifndef HAVE_FDATASYNC
#  define fdatasync fsync
#endif

struct const_iovec {
	const void *iov_base;
	size_t iov_len;
};

#ifndef HAVE_STRUCT_IOVEC
struct iovec {
	void *iov_base;
	size_t iov_len;
};
#endif

/* IOV_MAX should be in limits.h nowadays. Linux still (2005) requires
   defining _XOPEN_SOURCE to get that value. UIO_MAXIOV works with it though,
   so use it instead. 16 is the lowest acceptable value for all OSes. */
#ifndef IOV_MAX
#  include <sys/uio.h>
#  ifdef UIO_MAXIOV
#    define IOV_MAX UIO_MAXIOV
#  else
#    define IOV_MAX 16
#  endif
#endif

#ifndef HAVE_WRITEV
#  define writev i_my_writev
struct iovec;
ssize_t i_my_writev(int fd, const struct iovec *iov, int iov_len);
#endif

#if !defined(HAVE_PREAD) || defined(PREAD_WRAPPERS) || defined(PREAD_BROKEN)
#  ifndef IN_COMPAT_C
#    define pread i_my_pread
#    define pwrite i_my_pwrite
#  endif
ssize_t i_my_pread(int fd, void *buf, size_t count, off_t offset);
ssize_t i_my_pwrite(int fd, const void *buf, size_t count, off_t offset);
#endif

#ifndef HAVE_SETEUID
#  define seteuid i_my_seteuid
int i_my_seteuid(uid_t euid);
#endif

#ifndef HAVE_SETEGID
#  define setegid i_my_setegid
int i_my_setegid(gid_t egid);
#endif

#ifndef HAVE_LIBGEN_H
#  define basename i_my_basename
char *i_my_basename(char *path);
#endif

#ifndef HAVE_STRTOULL
#  define strtoull i_my_strtoull
unsigned long long int i_my_strtoull(const char *nptr, char **endptr, int base);
#endif
#ifndef HAVE_STRTOLL
#  define strtoll i_my_strtoll
unsigned long long int i_my_strtoll(const char *nptr, char **endptr, int base);
#endif

#ifdef HAVE_OLD_VSNPRINTF
#  include <stdio.h>
#  define vsnprintf i_my_vsnprintf
int i_my_vsnprintf(char *str, size_t size, const char *format, va_list ap);
#endif

#ifndef HAVE_CLOCK_GETTIME
#  include <time.h>
#  undef CLOCK_REALTIME
#  define CLOCK_REALTIME 1
#  define clock_gettime i_my_clock_gettime
int i_my_clock_gettime(int clk_id, struct timespec *tp);
#endif

/* ctype.h isn't safe with signed chars,
   use our own instead if really needed */
#define i_toupper(x) ((char) toupper((int) (unsigned char) (x)))
#define i_tolower(x) ((char) tolower((int) (unsigned char) (x)))
#define i_isalnum(x) isalnum((int) (unsigned char) (x))
#define i_isalpha(x) isalpha((int) (unsigned char) (x))
#define i_isascii(x) isascii((int) (unsigned char) (x))
#define i_isblank(x) isblank((int) (unsigned char) (x))
#define i_iscntrl(x) iscntrl((int) (unsigned char) (x))
#define i_isdigit(x) isdigit((int) (unsigned char) (x))
#define i_isgraph(x) isgraph((int) (unsigned char) (x))
#define i_islower(x) islower((int) (unsigned char) (x))
#define i_isprint(x) isprint((int) (unsigned char) (x))
#define i_ispunct(x) ispunct((int) (unsigned char) (x))
#define i_isspace(x) isspace((int) (unsigned char) (x))
#define i_isupper(x) isupper((int) (unsigned char) (x))
#define i_isxdigit(x) isxdigit((int) (unsigned char) (x))

#ifndef EOVERFLOW
#  define EOVERFLOW ERANGE
#endif

#ifdef EDQUOT
#  define ENOSPACE(errno) ((errno) == ENOSPC || (errno) == EDQUOT)
#else
#  define ENOSPACE(errno) ((errno) == ENOSPC)
#endif

/* EPERM is returned sometimes if device doesn't support such modification */
#ifdef EROFS
#  define ENOACCESS(errno) \
	((errno) == EACCES || (errno) == EROFS || (errno) == EPERM)
#else
#  define ENOACCESS(errno) ((errno) == EACCES || (errno) == EPERM)
#endif

#define ENOTFOUND(errno) \
	((errno) == ENOENT || (errno) == ENOTDIR || \
	 (errno) == ELOOP || (errno) == ENAMETOOLONG)

#define ECANTLINK(errno) \
	((errno) == EXDEV || (errno) == EMLINK || (errno) == EPERM)

/* EBUSY is given by some NFS implementations */
#define EDESTDIREXISTS(errno) \
	((errno) == EEXIST || (errno) == ENOTEMPTY || (errno) == EBUSY)

/* fstat() returns ENOENT instead of ESTALE with some Linux versions */
#define ESTALE_FSTAT(errno) \
	((errno) == ESTALE || (errno) == ENOENT)

#if !defined(_POSIX_SYNCHRONIZED_IO) && \
    defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
    (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060)
/* OS X Snow Leopard has fdatasync(), but no prototype for it. */
int fdatasync(int);
#endif

/* Try to keep IO operations at least this size */
#ifndef IO_BLOCK_SIZE
#  define IO_BLOCK_SIZE 8192
#endif

#if !defined(PIPE_BUF) && defined(_POSIX_PIPE_BUF)
#  define PIPE_BUF (8 * _POSIX_PIPE_BUF) /* for HURD */
#endif

#endif


text:
require 'chef/mixin/which'
require 'chef/provider/execute'
require 'chef/resource/execute'
require 'poise'

require 'poise_python/python_command_mixin'

module PoisePython
  module Resources
    # (see PythonExecute::Resource)
    # @since 1.0.0
    module PythonExecute
      # A `python_execute` resource to run Python scripts and commands.
      #
      # @provides python_execute
      # @action run
      # @example
      #   python_execute 'myapp.py' do
      #     user 'myuser'
      #   end
      class Resource < Chef::Resource::Execute
        include PoisePython::PythonCommandMixin
        provides(:python_execute)
        actions(:run)
      end

      # The default provider for `python_execute`.
      #
      # @see Resource
      # @provides python_execute
      class Provider < Chef::Provider::Execute
        include Chef::Mixin::Which
        provides(:python_execute)

        private

        # Command to pass to shell_out.
        #
        # @return [String, Array<String>]
        def command
          if new_resource.command.is_a?(Array)
            [new_resource.python] + new_resource.command
          else
            "#{new_resource.python} #{new_resource.command}"
          end
        end

        # Environment variables to pass to shell_out.
        #
        # @return [Hash]
        def environment
          if new_resource.parent_python
            environment = new_resource.parent_python.python_environment
            if new_resource.environment
              environment = environment.merge(new_resource.environment)
            end
            environment
          else
            new_resource.environment
          end
        end

      end
    end
  end
end


text:
export * from './src/echarts';
export * from './src/export';

import './src/chart/line';
import './src/chart/bar';
import './src/chart/pie';
import './src/chart/scatter';
import './src/component/graphic';
import './src/component/tooltip';
import './src/component/axisPointer';
import './src/component/legendScroll';

import './src/component/grid';
import './src/component/title';

import './src/component/markPoint';
import './src/component/markLine';
import './src/component/markArea';
import './src/component/dataZoom';
import './src/component/toolbox';

import 'zrender/src/vml/vml';
import 'zrender/src/svg/svg';


text:
class AddUsersStatsCounters < ActiveRecord::Migration
  def self.up
    add_column :users, :messages_count, :integer, :default => 0
    add_column :users, :subscriptions_count, :integer, :default => 0
    add_column :users, :conversations_count, :integer, :default => 0

    User.reset_column_information
    User.find(:all).each do |u|
      User.update_counters u.id, :messages_count => u.messages.length
      User.update_counters u.id, :subscriptions_count => u.subscriptions.length
      User.update_counters u.id, :conversations_count => u.conversations.length
    end

  end

  def self.down
    remove_column :users, :messages_count
    remove_column :users, :subscriptions_count
    remove_column :users, :conversations_count
  end
end


text:
@implementation IGLUSchema {
    BOOL _valid;
    NSString * _vendor;
    NSString * _name;
    NSString * _format;
    NSString * _version;
    NSDictionary * _schema;
    NSString * _invalidKey;
}

- (id)initWithKey:(NSString *)key andSchema:(NSDictionary *)schema andRegex:(NSRegularExpression *)regex {
    self = [super init];
    if (self) {
        _valid = [self setKeyWithSchemaKey:key andRegex:regex];
        _schema = schema;
    }
    return self;
}

- (BOOL)setKeyWithSchemaKey:(NSString *)key andRegex:(NSRegularExpression *)regex {
    NSTextCheckingResult * match = [regex firstMatchInString:key options:0 range:NSMakeRange(0, [key length])];
    if (match != nil) {
        _vendor  = [key substringWithRange:[match rangeAtIndex:1]];
        _name    = [key substringWithRange:[match rangeAtIndex:2]];
        _format  = [key substringWithRange:[match rangeAtIndex:3]];
        _version = [key substringWithRange:[match rangeAtIndex:4]];
        return YES;
    } else {
        _invalidKey = key;
        return NO;
    }
}

- (void)setSchema:(NSDictionary *)schema {
    _schema = schema;
}

- (BOOL)getValid {
    return _valid;
}

- (NSString *)getVendor {
    return _vendor;
}

- (NSString *)getName {
    return _name;
}

- (NSString *)getFormat {
    return _format;
}

- (NSString *)getVersion {
    return _version;
}

- (NSDictionary *)getSchema {
    return _schema;
}

- (NSString *)getKey {
    if (_valid) {
        return [NSString stringWithFormat:@"%@%@/%@/%@/%@", kIGLUSchemaPrefix, _vendor, _name, _format, _version];
    } else {
        return _invalidKey;
    }
}

@end


text:
PID=
SIGNAL="TERM"
KILLGROUPS=0
KILLSESS=0
VERBOSE=0

usage() {
    cat <<EOF
usage: $0 -p pid -s signal

Sends a signal to a process tree rooted at the specified pid.

Options:
-h      Display this message.
-p      Root pid of tree.
-s      Signal to send (number or symbolic name), default is TERM
-g      Recursively invoke on all processes that are members
        of any encountered process group.
-x      Same as -g, but invoke on processes of encountered sessions.
-v      Be more verbose.
EOF
}

set_union() {
    A="$1"
    B="$2"

    result=$(printf "${A}\n${B}\n" | sort | uniq)
    echo "${result}"
}

set_intersect() {
    A="$1"
    B="$2"

    result=$(printf "${A}\n${B}" \
        | sort | uniq -c | awk '{ if ($1 == 2) print $2 }')

    echo "${result}"
}

set_diff() {
    A="$1"
    B="$2"

    result=$(printf "${A}\n${B}" \
        | sort | uniq -c | awk '{ if ($1 == 1) print $2 }')

    echo "${result}"
}

while getopts "hp:s:gxv" OPTION
do
    HAVEOPT=1
    case ${OPTION} in
        h)
            usage
            exit 0
            ;;
        p)
            PID="${OPTARG}"
            test ${PID} -eq ${PID} >& /dev/null
            if [[ ${?} != 0 ]]; then
              echo "$(basename ${0}): pid should be a number"
              exit 1
            fi
            if [[ ! ${PID} -eq ${PID} ]]; then
                exit 1
            fi
            ;;
        s)
            SIGNAL="${OPTARG}"
            if [[ -z ${SIGNAL} ]]; then
              SIGNAL="TERM"
            fi
            ;;
        g)
            KILLGROUPS=1
            ;;
	x)
	    KILLSESSIONS=1
	    ;;
        v)
            VERBOSE=1
            ;;
        *)  usage
            exit 1
            ;;
    esac
done

if [[ ! ${HAVEOPT} ]]; then
    usage
    exit 127
fi

if [[ -z ${PID} ]]; then
    echo "$(basename ${0}): must specify pid"
    exit 1
fi

# Confirm we get some output from ps.
ps axo ppid,pid >/dev/null 2>&1
if [[ ${?} -ne 0 ]]; then
    echo "$(basename ${0}): failed to capture process tree using 'ps'"
    exit 1
fi

# Confirm we have awk.
ls | awk {'print $1'} >/dev/null 2>&1
if [[ ${?} -ne 0 ]]; then
    echo "$(basename ${0}): failed to detect awk on the system"
    exit 1
fi

PIDS=${PID} # Already processed pids, global variable hack.

killtree() {
    MYPID=${1}

    # Output pid if requested.
    if [[ ${VERBOSE} -eq 1 ]]; then
        printf "\nkilltree on ${MYPID}\n"
    fi

    # Stop the process to keep it from forking while we are killing it
    # since a forked child might get re-parented by init and become
    # impossible to find.
    kill -STOP ${MYPID} >/dev/null 2>&1

    # There is a concern that even though some process is stopped,
    # sending a signal to any of it's children may cause a SIGCLD to
    # be delivered to it which wakes it up (or any other signal maybe
    # delivered). However, from the Open Group standards on "Signal
    # Concepts":
    #
    #   "While a process is stopped, any additional signals that are
    #    sent to the process shall not be delivered until the process
    #    is continued, except SIGKILL which always terminates the
    #    receiving process."
    #
    # In practice, this is not what has been witnessed. Rather, a
    # process that has been stopped will respond to SIGTERM, SIGINT,
    # etc. That being said, we still continue the process below in the
    # event that it doesn't terminate from the sending signal but it
    # also doesn't get continued (as per the specifications above).

    # Now collect all the children.
    CHILDPIDS=$(ps axo ppid,pid | awk '{ if ($1 == '${MYPID}') print $2 }')

    # Optionally collect all processes that are part of the process group.
    GROUPPIDS=""
    if [[ ${KILLGROUPS} -eq 1 ]]; then

	# First get the process group.
        MYPGID=$(ps axo pid,pgid | awk '{ if ($1 == '${MYPID}') print $2 }')

	if [[ ! -z ${MYPGID} ]]; then
            # Now get all members.
            GROUPPIDS=$(ps axo pgid,pid \
                | awk '{ if ($1 == '${MYPGID}') print $2 }')
	fi
    fi

    # Optionally collect all processes that are part of the same session.
    SESSPIDS=""
    if [[ ${KILLSESSIONS} -eq 1 ]]; then

	# First get the process session id.
        MYPSID=$(ps axo pid,sess | awk '{ if ($1 == '${MYPID}') print $2 }')

	if [[ ! -z ${MYPSID} ]]; then
            # Now get all members.
            SESSPIDS=$(ps axo sess,pid \
                | awk '{ if ($1 == "'${MYPSID}'") print $2 }')
	fi
    fi

    # Get out only the unseen pids.
    # NEW = CHILDPIDS U GROUPPIDS U SESSPIDS
    #NEW=$(printf "${CHILDPIDS}\n${GROUPPIDS}\n${SESSPIDS}" | sort | uniq)
    NEW=$(set_union "$(set_union "${CHILDPIDS}" "${GROUPPIDS}")" "${SESSPIDS}")

    # OLD = NEW ^ PIDS
    #OLD=$(printf "${PIDS}\n${NEW}" \
    #    | sort | uniq -c | awk '{ if ($1 == 2) print $2 }')
    OLD=$(set_intersect "${PIDS}" "${NEW}")

    # NEW = NEW - OLD
    #NEW=$(printf "${NEW}\n${OLD}" \
    #    | sort | uniq -c | awk '{ if ($1 == 1) print $2 }')
    NEW=$(set_diff "${NEW}" "${OLD}")

    # Add all the new pids.
    PIDS=$(printf "${NEW}\n${PIDS}" | sort)

    # Now send the signal.
    kill -${SIGNAL} ${MYPID} >/dev/null 2>&1

    # Try and continue the process in case ${SIGNAL} is
    # non-terminating but doesn't continue the process.
    kill -CONT ${MYPID} >/dev/null 2>&1

    for pid in ${NEW}; do
        killtree $pid
    done
}

killtree ${PID}


text:
FUNCTION [ CP, DIST, ROOT ] = KDTREE ( REFERENCE, MODEL )
%
% KDTREE Find closest points using a k-D tree.
%
%  CP = KDTREE( REFERENCE, MODEL ) finds the closest points in
%  REFERENCE for each point in MODEL. The search is performed in an
%  efficient manner by building a k-D tree from the datapoints in
%  REFERENCE, and querying the tree for each datapoint in
%  MODEL.
%
%  Input :
%    REFERENCE is an NxD matrix, where each row is a D-dimensional
%    point. MODEL is an MxD matrix, where each row is a D-dimensional
%    query point.
%
%  Output:
%    CP is the same dimension as MODEL. There is a one-to-one
%    relationship between the rows of MODEL and the rows of CP. The
%    i-th row (point) of CP is a row (point) from REFERENCE which
%    is closest to the i-th row (point) of MODEL. The "closest"
%    metric is defined as the D-dimensional Euclidean (2-norm)
%    distance.
%
%
%  [CP, DIST] = KDTREE( ... ) returns the distances between
%  each row of MODEL and its closest point match from the k-D tree
%  in the vector DIST. DIST(i) corresponds to the i-th row (point)
%  of MODEL.
%
%  The default behavior of the function is that the k-D tree is
%  destroyed when the function returns. If you would like to save
%  the k-D tree in memory for use at a later time for additional
%  queries on the same REFERENCE data, then call the function with
%  an additional output:
%
%      [CP, DIST, ROOT] = KDTREE(REFERENCE, MODEL) where ROOT
%      receives a pointer to the root of the k-D tree.
%
%  Subsequently, use the following call to pass the k-D tree back
%  into the mex function:
%
%      [CP, DIST, ROOT] = KDTREE([], MODEL, ROOT)
%
%  Note that ROOT is again an output, preventing the tree from
%  being removed from memory.
%
%  Ultimately, to clear the k-D tree from memory, pass ROOT as
%  input, but do not receive it as output:
%
%      KDTREE([], [], ROOT)
%
%  Added June 2004: This k-D tree library now handles points
%  with dimension greater than 3.
%
%  See also KDTREEIDX and KDRANGEQUERY.
%
%  Written by / send comments or suggestions to :
%     Guy Shechter
%     guy at jhu dot edu
%     October 2013
%


text:
var	HttpCode = require('./http_codes.js').HttpCodes,
		ContentType = require('./contentType.js').ContentTypes;

exports.Routes = [
	{
		path: '/',
		handle: function(req, res) {
			if (assert(req, res)) {
				if (req.method === 'GET') {
					res.writeHead(HttpCode.OK, {
						'Content-Type': ContentType.text
					});
					res.end('Huzzah!');
				} else {
					res.writeHead(ContentType.NotImplemented, {
						'Content-Type': ContentType.text
					});
					res.end('Method has not been implemented');
				}
			}
		}
	}
];

var assert = function(req, res) {
	if (!req || !req.method) {
		res.writeHead(HttpCode.InternalServerError, {
			'Content-Type': ContentType.text
		});
		res.end('Could not parse request');
		return false;
	}
	return true;
}


text:
package yttlibrary

import (
	"fmt"
	"net"

	"github.com/k14s/starlark-go/starlark"
	"github.com/k14s/starlark-go/starlarkstruct"
	"github.com/k14s/ytt/pkg/orderedmap"
	"github.com/k14s/ytt/pkg/template/core"
)

var (
	// IPAPI describes the contents of "@ytt:ip" module of the ytt standard library.
	IPAPI = starlark.StringDict{
		"ip": &starlarkstruct.Module{
			Name: "ip",
			Members: starlark.StringDict{
				"parse_addr": starlark.NewBuiltin("ip.parse_addr", core.ErrWrapper(ipModule{}.ParseAddr)),
				"parse_cidr": starlark.NewBuiltin("ip.parse_cidr", core.ErrWrapper(ipModule{}.ParseCIDR)),
			},
		},
	}
)

type ipModule struct{}

func (m ipModule) ParseAddr(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	if args.Len() != 1 {
		return starlark.None, fmt.Errorf("expected exactly one argument")
	}

	ipStr, err := core.NewStarlarkValue(args.Index(0)).AsString()
	if err != nil {
		return starlark.None, err
	}

	parsedIP := net.ParseIP(ipStr)
	if parsedIP == nil {
		return starlark.None, fmt.Errorf("invalid IP address: %s", ipStr)
	}
	return (&IPAddrValue{parsedIP, nil}).AsStarlarkValue(), nil
}

// IPAddrValue stores a parsed IP
type IPAddrValue struct {
	addr                 net.IP
	*core.StarlarkStruct // TODO: keep authorship of the interface by delegating instead of embedding
}

const ipAddrTypeName = "ip.addr"

// Type reports the name of this type as seen from a Starlark program (i.e. via the `type()` built-in)
func (av *IPAddrValue) Type() string { return "@ytt:" + ipAddrTypeName }

// AsStarlarkValue converts this instance into a value suitable for use in a Starlark program.
func (av *IPAddrValue) AsStarlarkValue() starlark.Value {
	m := orderedmap.NewMap()
	m.Set("is_ipv4", starlark.NewBuiltin(ipAddrTypeName+".is_ipv4", core.ErrWrapper(av.IsIPv4)))
	m.Set("is_ipv6", starlark.NewBuiltin(ipAddrTypeName+".is_ipv6", core.ErrWrapper(av.IsIPv6)))
	m.Set("string", starlark.NewBuiltin(ipAddrTypeName+".string", core.ErrWrapper(av.string)))
	av.StarlarkStruct = core.NewStarlarkStruct(m)
	return av
}

// ConversionHint provides a hint on how the user can explicitly convert this value to a type that can be automatically encoded.
func (av *IPAddrValue) ConversionHint() string {
	return av.Type() + " does not automatically encode (hint: use .string())"
}

// IsIPv4 is a core.StarlarkFunc that reveals whether this value is an IPv4 address.
func (av *IPAddrValue) IsIPv4(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	if args.Len() != 0 {
		return starlark.None, fmt.Errorf("expected no argument")
	}
	isV4 := av.addr != nil && av.addr.To4() != nil
	return starlark.Bool(isV4), nil
}

// IsIPv6 is a core.StarlarkFunc that reveals whether this value is an IPv6 address.
func (av *IPAddrValue) IsIPv6(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	if args.Len() != 0 {
		return starlark.None, fmt.Errorf("expected no argument")
	}
	isV6 := av.addr != nil && av.addr.To4() == nil
	return starlark.Bool(isV6), nil
}

func (av *IPAddrValue) string(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	if args.Len() != 0 {
		return starlark.None, fmt.Errorf("expected no argument")
	}
	return starlark.String(av.addr.String()), nil
}

// ParseCIDR is a core.StarlarkFunc that extracts the IP address and IP network value from a CIDR expression
func (m ipModule) ParseCIDR(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	if args.Len() != 1 {
		return starlark.None, fmt.Errorf("expected exactly one argument")
	}

	cidrStr, err := core.NewStarlarkValue(args.Index(0)).AsString()
	if err != nil {
		return starlark.None, err
	}

	parsedIP, parsedNet, err := net.ParseCIDR(cidrStr)
	if err != nil {
		return starlark.None, err
	}

	return starlark.Tuple{(&IPAddrValue{parsedIP, nil}).AsStarlarkValue(), (&IPNetValue{parsedNet, nil}).AsStarlarkValue()}, nil
}

// IPNetValue holds the data for an instance of an IP Network value
type IPNetValue struct {
	net                  *net.IPNet
	*core.StarlarkStruct // TODO: keep authorship of the interface by delegating instead of embedding
}

const ipNetTypeName = "ip.net"

// Type reports the name of this type as seen from a Starlark program (i.e. via the `type()` built-in)
func (inv *IPNetValue) Type() string { return "@ytt:" + ipNetTypeName }

// AsStarlarkValue converts this instance into a value suitable for use in a Starlark program.
func (inv *IPNetValue) AsStarlarkValue() starlark.Value {
	m := orderedmap.NewMap()
	m.Set("addr", starlark.NewBuiltin(ipNetTypeName+".addr", core.ErrWrapper(inv.Addr)))
	m.Set("string", starlark.NewBuiltin(ipNetTypeName+".string", core.ErrWrapper(inv.string)))
	inv.StarlarkStruct = core.NewStarlarkStruct(m)
	return inv
}

// ConversionHint provides a hint on how the user can explicitly convert this value to a type that can be automatically encoded.
func (inv *IPNetValue) ConversionHint() string {
	return inv.Type() + " does not automatically encode (hint: use .string())"
}

// Addr is a core.StarlarkFunc that returns the masked address portion of the network value
func (inv *IPNetValue) Addr(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	if args.Len() != 0 {
		return starlark.None, fmt.Errorf("expected no argument")
	}

	ip := &IPAddrValue{inv.net.IP, nil}
	return ip.AsStarlarkValue(), nil
}

func (inv *IPNetValue) string(thread *starlark.Thread, f *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
	if args.Len() != 0 {
		return starlark.None, fmt.Errorf("expected no argument")
	}
	return starlark.String(inv.net.String()), nil
}


text:
PROJECT = example

DEPS = cowboy_trails mixer

dep_mixer   = git https://github.com/inaka/mixer.git  0.1.3
dep_cowboy_trails = git https://github.com/inaka/cowboy-trails 75bf34ba

SHELL_DEPS = sync

dep_sync =  git https://github.com/inaka/sync.git  0.1.3

include erlang.mk

ERLC_OPTS += +'{parse_transform}'

SHELL_OPTS = -name ${PROJECT}@`hostname` -s ${PROJECT} -config rel/sys.config -s sync


text:
from PyQt5 import QtCore, QtWidgets
from sweep import Sweep
import os

class FileList(QtWidgets.QListWidget):
    """
    Contains a list of sweeps to plot.
    """
    def __init__(self, names):
        super().__init__()
        self.names = names
        self.setSortingEnabled(True)
        self.sortItems(order=QtCore.Qt.DescendingOrder)
        self.reload_items()
        self.setCurrentRow(0)

    def reload_items(self):
        self.clear()
        self.set_items()

    def set_items(self):
        for name in self.names:
            item = QtWidgets.QListWidgetItem(name, parent=self)
            self.addItem(item)


text:
package org.I0Itec.zkclient;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

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

public class DistributedQueueTest {

    private ZkServer _zkServer;
    private ZkClient _zkClient;

    @Before
    public void setUp() throws IOException {
        _zkServer = TestUtil.startZkServer("ZkClientTest-testDistributedQueue", 4711);
        _zkClient = _zkServer.getZkClient();
    }

    @After
    public void tearDown() {
        if (_zkServer != null) {
            _zkServer.shutdown();
        }
    }

    @Test(timeout = 15000)
    public void testDistributedQueue() {
        _zkClient.createPersistent("/queue");

        DistributedQueue<Long> distributedQueue = new DistributedQueue<Long>(_zkClient, "/queue");
        distributedQueue.offer(17L);
        distributedQueue.offer(18L);
        distributedQueue.offer(19L);

        assertEquals(Long.valueOf(17L), distributedQueue.poll());
        assertEquals(Long.valueOf(18L), distributedQueue.poll());
        assertEquals(Long.valueOf(19L), distributedQueue.poll());
        assertNull(distributedQueue.poll());
    }

    @Test(timeout = 15000)
    public void testPeek() {
        _zkClient.createPersistent("/queue");

        DistributedQueue<Long> distributedQueue = new DistributedQueue<Long>(_zkClient, "/queue");
        distributedQueue.offer(17L);
        distributedQueue.offer(18L);

        assertEquals(Long.valueOf(17L), distributedQueue.peek());
        assertEquals(Long.valueOf(17L), distributedQueue.peek());
        assertEquals(Long.valueOf(17L), distributedQueue.poll());
        assertEquals(Long.valueOf(18L), distributedQueue.peek());
        assertEquals(Long.valueOf(18L), distributedQueue.poll());
        assertNull(distributedQueue.peek());
    }

    @Test(timeout = 30000)
    public void testMultipleReadingThreads() throws InterruptedException {
        _zkClient.createPersistent("/queue");

        final DistributedQueue<Long> distributedQueue = new DistributedQueue<Long>(_zkClient, "/queue");

        // insert 100 elements
        for (int i = 0; i < 100; i++) {
            distributedQueue.offer(new Long(i));
        }

        // 3 reading threads
        final Set<Long> readElements = Collections.synchronizedSet(new HashSet<Long>());
        List<Thread> threads = new ArrayList<Thread>();
        final List<Exception> exceptions = new Vector<Exception>();

        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            Long value = distributedQueue.poll();
                            if (value == null) {
                                return;
                            }
                            readElements.add(value);
                        }
                    } catch (Exception e) {
                        exceptions.add(e);
                        e.printStackTrace();
                    }
                }
            };
            threads.add(thread);
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        assertEquals(0, exceptions.size());
        assertEquals(100, readElements.size());
    }
}


text:
/**
 * @fileoverview Pixelbox field. Valid characters are ' ', 0 - 9 and #. Fixed size of 16 x 16 pixel.
 *               Modified copy from field_checkbox
 * @author Beate Jost, beate.jost@iais.fraunhofer.de
 */
'use strict';

goog.provide('Blockly.FieldPixelbox');

goog.require('Blockly.FieldTextInput');

/**
 * Class for a checkbox field.
 *
 * @param {string}
 *            state The initial state of the field ('TRUE' or 'FALSE').
 * @param {Function=}
 *            opt_validator A function that is executed when a new option is
 *            selected. Its sole argument is the new checkbox state. If it
 *            returns a value, this becomes the new checkbox state, unless the
 *            value is null, in which case the change is aborted.
 * @extends {Blockly.Field}
 * @constructor
 */
Blockly.FieldPixelbox = function(text, opt_validator) {
    Blockly.FieldPixelbox.superClass_.constructor.call(this, text, opt_validator);
    // force showing number keyboard on mobile devices
    this.inputType = 'number';
};
goog.inherits(Blockly.FieldPixelbox, Blockly.FieldTextInput);

/**
 * Install this pixelbox on a block.
 */
Blockly.FieldPixelbox.prototype.init = function() {
    if (this.fieldGroup_) {
        // Field has already been initialized once.
        return;
    }
    // Build the DOM.
    this.fieldGroup_ = Blockly.createSvgElement('g', {}, null);
    if (!this.visible_) {
        this.fieldGroup_.style.display = 'none';
    }
    this.borderRect_ = Blockly.createSvgElement('rect', {
        'rx' : 2,
        'ry' : 2,
        'x' : -Blockly.BlockSvg.SEP_SPACE_X / 2,
        'y' : 0,
        'height' : 16,
        'width' : 16
    }, this.fieldGroup_, this.sourceBlock_.workspace);
    /** @type {!Element} */
    this.textElement_ = Blockly.createSvgElement('text', {
        'class' : 'blocklyText blocklyPixel',
        'y' : this.size_.height - 12.5
    }, this.fieldGroup_);

    this.updateEditable();
    this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_);
    this.mouseUpWrapper_ = Blockly.bindEvent_(this.fieldGroup_, 'mouseup', this, this.onMouseUp_);
    // Force a render.
    this.updateTextNode_();
    if (Blockly.Events.isEnabled()) {
        Blockly.Events.fire(new Blockly.Events.Change(this.sourceBlock_, 'field', this.name, '', this.getValue()));
    }

    /**
     * Update the text node of this field to display the current text.
     *
     * @private
     */
    Blockly.FieldPixelbox.prototype.updateTextNode_ = function() {
        if (!this.textElement_) {
            // Not rendered yet.
            return;
        }
        var text = this.text_;
        // Empty the text element.
        goog.dom.removeChildren(/** @type {!Element} */(this.textElement_));
        // Replace whitespace with non-breaking spaces so the text doesn't collapse.
        text = text.trim();

        if (!text) {
            // Prevent the field from disappearing if empty.
            text = ' ';
        }
        var textNode = document.createTextNode(text);
        this.textElement_.appendChild(textNode);

        this.size_.width = 16;
    };
};


text:
@implementation UIScrollView (YCYAddition)

//frame
- (CGFloat)ycy_contentWidth {
    return self.contentSize.width;
}
- (void)setYcy_contentWidth:(CGFloat)width {
    self.contentSize = CGSizeMake(width, self.frame.size.height);
}
- (CGFloat)ycy_contentHeight {
    return self.contentSize.height;
}
- (void)setYcy_contentHeight:(CGFloat)height {
    self.contentSize = CGSizeMake(self.frame.size.width, height);
}
- (CGFloat)ycy_contentOffsetX {
    return self.contentOffset.x;
}
- (void)setYcy_contentOffsetX:(CGFloat)x {
    self.contentOffset = CGPointMake(x, self.contentOffset.y);
}
- (CGFloat)ycy_contentOffsetY {
    return self.contentOffset.y;
}
- (void)setYcy_contentOffsetY:(CGFloat)y {
    self.contentOffset = CGPointMake(self.contentOffset.x, y);
}
//

- (CGPoint)ycy_topContentOffset
{
    return CGPointMake(0.0f, -self.contentInset.top);
}
- (CGPoint)ycy_bottomContentOffset
{
    return CGPointMake(0.0f, self.contentSize.height + self.contentInset.bottom - self.bounds.size.height);
}
- (CGPoint)ycy_leftContentOffset
{
    return CGPointMake(-self.contentInset.left, 0.0f);
}
- (CGPoint)ycy_rightContentOffset
{
    return CGPointMake(self.contentSize.width + self.contentInset.right - self.bounds.size.width, 0.0f);
}
- (YCYScrollDirection)ycy_ScrollDirection
{
    YCYScrollDirection direction;

    if ([self.panGestureRecognizer translationInView:self.superview].y > 0.0f)
    {
        direction = YCYScrollDirectionUp;
    }
    else if ([self.panGestureRecognizer translationInView:self.superview].y < 0.0f)
    {
        direction = YCYScrollDirectionDown;
    }
    else if ([self.panGestureRecognizer translationInView:self].x < 0.0f)
    {
        direction = YCYScrollDirectionLeft;
    }
    else if ([self.panGestureRecognizer translationInView:self].x > 0.0f)
    {
        direction = YCYScrollDirectionRight;
    }
    else
    {
        direction = YCYScrollDirectionWTF;
    }

    return direction;
}
- (BOOL)ycy_isScrolledToTop
{
    return self.contentOffset.y <= [self ycy_topContentOffset].y;
}
- (BOOL)ycy_isScrolledToBottom
{
    return self.contentOffset.y >= [self ycy_bottomContentOffset].y;
}
- (BOOL)ycy_isScrolledToLeft
{
    return self.contentOffset.x <= [self ycy_leftContentOffset].x;
}
- (BOOL)ycy_isScrolledToRight
{
    return self.contentOffset.x >= [self ycy_rightContentOffset].x;
}
- (void)ycy_scrollToTopAnimated:(BOOL)animated
{
    [self setContentOffset:[self ycy_topContentOffset] animated:animated];
}
- (void)ycy_scrollToBottomAnimated:(BOOL)animated
{
    [self setContentOffset:[self ycy_bottomContentOffset] animated:animated];
}
- (void)ycy_scrollToLeftAnimated:(BOOL)animated
{
    [self setContentOffset:[self ycy_leftContentOffset] animated:animated];
}
- (void)ycy_scrollToRightAnimated:(BOOL)animated
{
    [self setContentOffset:[self ycy_rightContentOffset] animated:animated];
}
- (NSUInteger)ycy_verticalPageIndex
{
    return (self.contentOffset.y + (self.frame.size.height * 0.5f)) / self.frame.size.height;
}
- (NSUInteger)ycy_horizontalPageIndex
{
    return (self.contentOffset.x + (self.frame.size.width * 0.5f)) / self.frame.size.width;
}
- (void)ycy_scrollToVerticalPageIndex:(NSUInteger)pageIndex animated:(BOOL)animated
{
    [self setContentOffset:CGPointMake(0.0f, self.frame.size.height * pageIndex) animated:animated];
}
- (void)ycy_scrollToHorizontalPageIndex:(NSUInteger)pageIndex animated:(BOOL)animated
{
    [self setContentOffset:CGPointMake(self.frame.size.width * pageIndex, 0.0f) animated:animated];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="@color/rp_money_white"
              android:orientation="vertical"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="@dimen/size30px"
        android:layout_marginTop="@dimen/size30px"
        >

        <ImageView
            android:id="@+id/iv_record_avatar_icon"
            android:layout_width="@dimen/size105px"
            android:layout_height="@dimen/size105px"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="@dimen/size45px"
            android:src="@drawable/rp_avatar"
            android:visibility="gone"
            />

        <TextView
            android:id="@+id/tv_money_to_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/size45px"
            android:layout_toRightOf="@id/iv_record_avatar_icon"
            android:ellipsize="end"
            android:maxEms="10"
            android:maxLines="1"
            android:textColor="@color/rp_text_black"
            android:textSize="@dimen/font45px"
            />

        <ImageView
            android:id="@+id/iv_random_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/size18px"
            android:layout_marginTop="@dimen/size9px"
            android:layout_toRightOf="@id/tv_money_to_user"
            android:visibility="gone"
            />

        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/tv_money_to_user"
            android:layout_marginLeft="@dimen/size45px"
            android:layout_marginTop="@dimen/size9px"
            android:layout_toRightOf="@id/iv_record_avatar_icon"
            android:textColor="@color/rp_text_light_grey"
            android:textSize="@dimen/font36px"
            />

        <TextView
            android:id="@+id/tv_item_money_amount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@id/tv_money_to_user"
            android:layout_alignParentRight="true"
            android:layout_marginRight="@dimen/size45px"
            android:textColor="@color/rp_text_black"
            android:textSize="@dimen/font45px"
            />

        <TextView
            android:id="@+id/tv_item_money_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@id/tv_item_money_amount"
            android:layout_marginLeft="@dimen/size45px"
            android:layout_marginRight="@dimen/size45px"
            android:layout_marginTop="@dimen/size9px"
            android:textColor="@color/rp_text_light_grey"
            android:textSize="@dimen/font36px"
            />
    </RelativeLayout>

    <View
        android:id="@+id/view_line_no_head"
        style="@style/DividerStyleNoHead"
        />

    <View
        android:id="@+id/view_line"
        style="@style/DividerStyle"
        android:visibility="gone"/>

</LinearLayout>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Conditional Statements HW</title>
    <link rel="stylesheet" href="styles/styles.css">

Problem 1. Exchange if greater

Write an `if` statement that takes two double variables `a` and `b` and exchanges their values if the
                first one is greater than the second.

As a result print the values `a` and `b`, separated by a space.

        <input type="text" id="problem1a" class="txtInput" placeholder="Input a">
        <input type="text" id="problem1b" class="txtInput" placeholder="Input b">
        <button onclick="pr1()">Run</button>

Problem 2. Multiplication Sign

Write a script that shows the sign (+, - or 0) of the product of three real numbers, without calculating
                it.

Use a sequence of `if` operators.

        <input type="text" id="problem2a" class="txtInput" placeholder="Input a">
        <input type="text" id="problem2b" class="txtInput" placeholder="Input b">
        <input type="text" id="problem2c" class="txtInput" placeholder="Input c">
        <button onclick="pr2()">Run</button>

Problem 3. The biggest of Three

Write a script that finds the biggest of three numbers.

Use nested `if` statements.

        <input type="text" id="problem3a" class="txtInput" placeholder="Input a">
        <input type="text" id="problem3b" class="txtInput" placeholder="Input b">
        <input type="text" id="problem3c" class="txtInput" placeholder="Input c">
        <button onclick="pr3()">Run</button>

Problem 4. Sort 3 numbers

Sort 3 real values in descending order.

Use nested `if` statements.

        <input type="text" id="problem4a" class="txtInput" placeholder="Input a">
        <input type="text" id="problem4b" class="txtInput" placeholder="Input b">
        <input type="text" id="problem4c" class="txtInput" placeholder="Input c">
        <button onclick="pr4()">Run</button>

Problem 5. Digit as word

Write a script that asks for a digit `(0-9)`, and depending on the input, shows the digit as a word (in
                English).

Print `"not a digit"` in case of invalid input.

Use a `switch` statement.

        <input type="text" id="problem5" class="txtInput" placeholder="Input a digit (0-9)">
        <button onclick="pr5()">Run</button>

Problem 6. Quadratic equation

Write a script that reads the coefficients `a`, `b` and `c` of a quadratic equation ax2 + bx
                + c = 0 and solves it (prints its real roots).

Calculates and prints its real roots.

        <input type="text" id="problem6a" class="txtInput" placeholder="Input a">
        <input type="text" id="problem6b" class="txtInput" placeholder="Input b">
        <input type="text" id="problem6c" class="txtInput" placeholder="Input c">
        <button onclick="pr6()">Run</button>

Problem 7. The biggest of five numbers

Write a script that finds the greatest of given 5 variables.

Use nested `if` statements.

        <input type="text" id="problem7a" class="txtInput" placeholder="Input a">
        <input type="text" id="problem7b" class="txtInput" placeholder="Input b">
        <input type="text" id="problem7c" class="txtInput" placeholder="Input c">
        <input type="text" id="problem7d" class="txtInput" placeholder="Input d">
        <input type="text" id="problem7e" class="txtInput" placeholder="Input e">
        <button onclick="pr7()">Run</button>

Problem 8. Number as words

Write a script that converts a number in the range [0…999] to words, corresponding to its English
                pronunciation.

        <input type="text" id="problem8" class="txtInput" placeholder="Input a number (0-999)">
        <button onclick="pr8()">Run</button>


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.Runtime;
using System.IO;
using AWSSDK_DotNet35.UnitTests;
using Amazon.S3.Model;
using Amazon.S3.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Util;
using System.Threading;
using System.Net;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal;

namespace AWSSDK.UnitTests
{
    [TestClass()]
    public class MD5Tests
    {
        [TestMethod]
        public void TestMD5Managed()
        {

            System.Security.Cryptography.MD5 md5;
            try
            {
                md5 = System.Security.Cryptography.MD5.Create();
            }
            catch
            {
                Console.WriteLine("FIPS enabled, exiting test");
                return;
            }

            var md5m = new ThirdParty.MD5.MD5Managed();

            Assert.AreEqual(md5.CanReuseTransform, md5m.CanReuseTransform);
            Assert.AreEqual(md5.CanTransformMultipleBlocks, md5m.CanTransformMultipleBlocks);
            Assert.AreEqual(md5.HashSize, md5m.HashSize);
            Assert.AreEqual(md5.InputBlockSize, md5m.InputBlockSize);
            Assert.AreEqual(md5.OutputBlockSize, md5m.OutputBlockSize);

            var data1 = "foo";
            var data2 = "bar";
            var bytes1 = Encoding.UTF8.GetBytes(data1);
            var bytes2 = Encoding.UTF8.GetBytes(data2);

            //CollectionAssert.AreEqual(md5.Hash, md5m.Hash);
            CollectionAssert.AreEqual(md5.ComputeHash(bytes1), md5m.ComputeHash(bytes1));

            HashMultiple(md5, bytes1, bytes2);
            HashMultiple(md5m, bytes1, bytes2);
            CollectionAssert.AreEqual(md5.Hash, md5m.Hash);

            //HashMultiple(md5, bytes1, bytes2);
            //HashMultiple(md5m, bytes1, bytes2);
            //CollectionAssert.AreEqual(md5.Hash, md5m.Hash);

            md5.Initialize();
            md5m.Initialize();

            Assert.AreEqual(data1, Encoding.UTF8.GetString(bytes1));
            Assert.AreEqual(data2, Encoding.UTF8.GetString(bytes2));

            md5.Clear();
            md5m.Clear();

            Utils.AssertExceptionExpected<ObjectDisposedException>(() => HashMultiple(md5, bytes1, bytes2));
            Utils.AssertExceptionExpected<ObjectDisposedException>(() => HashMultiple(md5m, bytes1, bytes2));
        }

        private static void HashMultiple(System.Security.Cryptography.HashAlgorithm md5, byte[] bytes1, byte[] bytes2)
        {
            int offset = 0;
            // For each block:
            offset += md5.TransformBlock(bytes1, 0, bytes1.Length, bytes1, 0);
            offset += md5.TransformBlock(bytes2, 0, bytes2.Length, bytes2, 0);
            offset += md5.TransformBlock(bytes1, 0, bytes1.Length, null, 0);
            offset += md5.TransformBlock(bytes2, 0, bytes2.Length, null, 0);
            // For last block:
            //md5.TransformFinalBlock(bytes2, 0, bytes2.Length);
            md5.TransformFinalBlock(new byte[0], 0, 0);
        }
    }
}


text:
require "danger/commands/init_helpers/interviewer"
require "danger/ci_source/local_git_repo"
require "yaml"

module Danger
  class Init < Runner
    self.summary = "Helps you set up Danger."
    self.command = "init"

    attr_accessor :ui

    def self.options
      [
        ["--impatient", "'I've not got all day here. Don't add any thematic delays please.'"],
        ["--mousey", "'Don't make me press return to continue the adventure.'"]
      ].concat(super)
    end

    def initialize(argv)
      @bot_name = File.basename(Dir.getwd).split(".").first.capitalize + "Bot"
      super
      @ui = Interviewer.new(cork)
      ui.no_delay = argv.flag?("impatient", false)
      ui.no_waiting = argv.flag?("mousey", false)
    end

    def run
      ui.say "\nOK, thanks #{ENV['LOGNAME']}, have a seat and we'll get you started.\n".yellow
      ui.pause 1

      show_todo_state
      ui.pause 1.4

      setup_dangerfile
      setup_github_account
      setup_access_token
      setup_danger_ci

      info
      thanks
    end

    def show_todo_state
      ui.say "We need to do the following:\n"
      ui.pause 0.6
      ui.say " - [ ] Create a Dangerfile and add a few simple rules."
      ui.pause 0.6
      ui.say " - [#{@account_created ? 'x' : ' '}] Create a GitHub account for Danger to use, for messaging."
      ui.pause 0.6
      ui.say " - [ ] Set up an access token for Danger."
      ui.pause 0.6
      ui.say " - [ ] Set up Danger to run on your CI.\n\n"
    end

    def setup_dangerfile
      dir = Danger.gem_path
      content = File.read(File.join(dir, "lib", "assets", "DangerfileTemplate"))
      File.write("Dangerfile", content)

      ui.header "Step 1: Creating a starter Dangerfile"
      ui.say "I've set up an example Dangerfile for you in this folder.\n"
      ui.pause 1

      ui.say "cat #{Dir.pwd}/Dangerfile\n".blue
      content.lines.each do |l|
        ui.say "  " + l.chomp.green
      end
      ui.say ""
      ui.pause 2

      ui.say "There's a collection of small, simple ideas in here, but Danger is about being able to easily"
      ui.say "iterate. The power comes from you having the ability to codify fixes for some of the problems"
      ui.say "that come up in day to day programming. It can be difficult to try and see those from day 1."

      ui.say "\nIf you'd like to investigate the file, and make some changes - I'll wait here,"
      ui.say "press return when you're ready to move on..."
      ui.wait_for_return
    end

    def setup_github_account
      ui.header "Step 2: Creating a GitHub account"

      ui.say "In order to get the most out of Danger, I'd recommend giving her the ability to post in"
      ui.say "the code-review comment section.\n\n"
      ui.pause 1

      ui.say "IMO, it's best to do this by using the private mode of your browser. Create an account like"
      ui.say "#{@bot_name}, and don't forget a cool robot avatar.\n\n"
      ui.pause 1
      ui.say "Here are great resources for creative commons images of robots:"
      ui.link "https://www.flickr.com/search/?text=robot&license=2%2C3%2C4%2C5%2C6%2C9"
      ui.link "https://www.google.com/search?q=robot&tbs=sur:fmc&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwjgy8-f95jLAhWI7hoKHV_UD00QsAQIMQ&biw=1265&bih=1359"

      ui.say ""
      note_about_clicking_links
      ui.pause 1
      ui.say "\nCool, please press return when you have your account ready (and you've verified the email...)"
      ui.wait_for_return
    end

    def setup_access_token
      ui.header "Step 3: Configuring a GitHub Personal Access Token"

      ui.say "Here's the link, you should open this in the private session where you just created the new GitHub account"
      ui.link "https://github.com/settings/tokens/new"
      ui.pause 1

      @is_open_source = ui.ask_with_answers("For token access rights, I need to know if this is for an Open Source or Closed Source project\n", ["Open", "Closed"])

      if considered_an_oss_repo?
        ui.say "For Open Source projects, I'd recommend giving the token the smallest scope possible."
        ui.say "This means only providing access to " + "public_repo".yellow + " in the token.\n\n"
        ui.pause 1
        ui.say "This token limits Danger's abilities to just writing comments on OSS projects. I recommend"
        ui.say "this because the token can quite easily be extracted from the environment via pull requests."
        ui.say "#{@bot_name} does not need admin access to your repo. So its ability to cause chaos is minimalized.\n"

        ui.say "\nIt is important that you do not store this token in your repository, as GitHub will automatically revoke it when pushed.\n"
      elsif @is_open_source == "closed"
        ui.say "For Closed Source projects, I'd recommend giving the token access to the whole repo scope."
        ui.say "This means only providing access to " + "repo".yellow + ", and its children in the token.\n\n"
        ui.pause 1
        ui.say "It's worth noting that you " + "should not".bold.white + " re-use this token for OSS repos."
        ui.say "Make a new one for those repos with just " + "public_repo".yellow + "."
        ui.pause 1
        ui.say "Additionally, don't forget to add your new GitHub account as a collaborator to your Closed Source project."
      end

      ui.say "\n👍, please press return when you have your token set up..."
      ui.wait_for_return
    end

    def considered_an_oss_repo?
      @is_open_source == "open"
    end

    def current_repo_slug
      @git = GitRepo.new
      repo_matches = @git.origins.match(%r{([\/:])([^\/]+\/[^\/.]+)(?:.git)?$})
      repo_matches[2] || "[Your/Repo]"
    end

    def setup_danger_ci
      ui.header "Step 4: Add Danger for your CI"

      uses_travis if File.exist? ".travis.yml"
      uses_circle if File.exist? "circle.yml"
      unsure_ci unless File.exist?(".travis.yml") || File.exist?(".circle.yml")

      ui.say "\nOK, I'll give you a moment to do this..."
      ui.wait_for_return

      ui.header "Final step: exposing the GitHub token as an environment build variable."
      ui.pause 0.4
      if considered_an_oss_repo?
        ui.say "As you have an Open Source repo, this token should be considered public, otherwise you cannot"
        ui.say "run Danger on pull requests from forks, limiting its use.\n"
        ui.pause 1
      end

      travis_token if File.exist? ".travis.yml"
      circle_token if File.exist? "circle.yml"
      unsure_token unless File.exist?(".travis.yml") || File.exist?(".circle.yml")

      ui.pause 0.6
      ui.say "This is the last step, I can give you a second..."
      ui.wait_for_return
    end

    def uses_travis
      danger = "bundle exec danger".yellow
      config = YAML.load(File.read(".travis.yml"))
      if config["script"]
        ui.say "Add " + "- ".yellow + danger + " as a new step in the " + "script".yellow + " section of your .travis.yml file."
      else
        ui.say "I'd recommend adding " + "script: ".yellow + danger + " to the script section of your .travis.yml file."
      end

      ui.pause 1
      ui.say "You shouldn't use " + "after_success, after_failure, after_script".red + " as they cannot fail your builds."
    end

    def uses_circle
      danger = "- bundle exec danger".yellow
      config = YAML.load(File.read("circle.yml"))

      if config["test"]
        if config["test"]["post"]
          ui.say "Add " + danger + " as a new step in the " + "test:post:".yellow + " section of your circle.yml file."
        else
          ui.say "Add " + danger + " as a new step in the " + "test:override:".yellow + " section of your circle.yml file."
        end
      else
        ui.say "Add this to the bottom of your circle.yml file:"
        ui.say "test:".green
        ui.say "  post:".green
        ui.say "    #{danger}".green
      end
    end

    def unsure_ci
      danger = "bundle exec danger".yellow
      ui.say "As I'm not sure what CI you want to run Danger on based on the files in your repo, I'll just offer some generic"
      ui.say "advice. You want to run " + danger + " after your tests have finished running, it should still be during the testing"
      ui.say "process so the build can fail."
    end

    def travis_token
      # https://travis-ci.org/artsy/eigen/settings
      ui.say "In order to add an environment variable, go to:"
      ui.link "https://travis-ci.org/#{current_repo_slug}/settings"
      ui.say "\nThe name is " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Access Token."
      if @is_open_source
        ui.say 'Make sure to have "Display value in build log" enabled.'
      end
    end

    def circle_token
      # https://circleci.com/gh/artsy/eigen/edit#env-vars
      if considered_an_oss_repo?
        ui.say "Before we start, it's important to be up-front. CircleCI only really has one option to support running Danger"
        ui.say "for forks on OSS repos. It is quite a drastic option, and I want to let you know the best place to understand"
        ui.say "the ramifications of turning on a setting I'm about to advise.\n"
        ui.link "https://circleci.com/docs/fork-pr-builds"
        ui.say "TLDR: If you have anything other than Danger config settings in CircleCI, then you should not turn on the setting."
        ui.say "I'll give you a minute to read it..."
        ui.wait_for_return

        ui.say "On Danger/Danger we turn on " + "Permissive building of fork pull requests".yellow + " this exposes the token to Danger"
        ui.say "You can find this setting at:"
        ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#advanced-settings\n"
        ui.say "I'll hold..."
        ui.wait_for_return
      end

      ui.say "In order to expose an environment variable, go to:"
      ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#env-vars"
      ui.say "The name is " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
    end

    def unsure_token
      ui.say "You need to expose a token called " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
      ui.say "Depending on the CI system, this may need to be done on the machine ( in the " + "~/.bashprofile".yellow + ") or in a web UI somewhere."
    end

    def note_about_clicking_links
      modifier_key = "ctrl"
      clicks = "clicking"

      modifier_key = "cmd ( ⌘ )" if darwin?
      clicks = "double clicking" if darwin? && !ENV["ITERM_SESSION_ID"]

      ui.say "Note: Holding #{modifier_key} and #{clicks} a link will open it in your browser."
    end

    def info
      ui.header "Useful info"
      ui.say "- One of the best ways to test out new rules locally is via " + "bundle exec danger local".yellow + "."
      ui.pause 0.6
      ui.say "- You can have Danger output all of its variables to the console via the " + "--verbose".yellow + " option."
      ui.pause 0.6
      ui.say "- You can look at the following Dangerfiles to get some more ideas:"
      ui.pause 0.6
      ui.link "https://github.com/danger/danger/blob/master/Dangerfile"
      ui.link "https://github.com/artsy/eigen/blob/master/Dangerfile"
      ui.pause 1
    end

    def thanks
      ui.say "\n\n🎉"
      ui.pause 0.6

      ui.say "And you're good to go. Danger is a collaboration between Orta Therox, Gem 'Danger' McShane and Felix Krause."
      ui.say "If you like it, let others know. If you want to know more, follow " + "@orta".yellow + " and " + "@KrauseFx".yellow + " on Twitter."
      ui.say "If you don't like it, help us improve it! xxx"
    end

    def darwin?
      Gem::Platform.local.os == "darwin"
    end
  end
end


text:
namespace extensions {

static const char kHotwordHelperExtensionId[] =
    "dnhpdliibojhegemfjheidglijccjfmc";

class HotwordBrowserTest : public ExtensionBrowserTest {
 public:
  HotwordBrowserTest() : error_console_(NULL) { }
  ~HotwordBrowserTest() override {}

 protected:
  void SetUpInProcessBrowserTestFixture() override {
    ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();

    // Load the hotword_helper extension.
    ComponentLoader::EnableBackgroundExtensionsForTesting();

    // We need to enable the ErrorConsole FeatureSwitch in order to collect
    // errors. This should be enabled on any channel <= Dev, but let's make
    // sure (in case a test is running on, e.g., a beta channel).
    FeatureSwitch::error_console()->SetOverrideValue(
        FeatureSwitch::OVERRIDE_ENABLED);
  }

  void SetUpOnMainThread() override {
    ExtensionBrowserTest::SetUpOnMainThread();

    // Errors are only kept if we have Developer Mode enabled.
    profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);

    error_console_ = ErrorConsole::Get(profile());
    ASSERT_TRUE(error_console_);
  }

  ErrorConsole* error_console() { return error_console_; }

 private:
  // Weak reference to the ErrorConsole.
  ErrorConsole* error_console_;

  DISALLOW_COPY_AND_ASSIGN(HotwordBrowserTest);
};

// Test we silently capture an exception from a message handler's response
// callback. This happens when the caller to chrome.runtime.sendMessage()
// doesn't specify a response callback.
// NOTE(amistry): Test is disabled instead of deleted since the functionality
// may still be required to implement crbug.com/436681
IN_PROC_BROWSER_TEST_F(HotwordBrowserTest, DISABLED_MessageSendResponseError) {
  // Enable error reporting for the hotword helper extension.
  error_console()->SetReportingAllForExtension(kHotwordHelperExtensionId, true);

  ExtensionTestMessageListener doneListener("done", false);
  const Extension* extension = extension_service()->GetExtensionById(
      kHotwordHelperExtensionId, false);
  ASSERT_TRUE(extension);
  const Extension* test_extension = LoadExtension(
      test_data_dir_.AppendASCII("hotword"));
  ASSERT_TRUE(test_extension);

  ASSERT_TRUE(doneListener.WaitUntilSatisfied());
  ASSERT_TRUE(error_console()->GetErrorsForExtension(extension->id()).empty());
}

}  // namespace extensions


text:
layout: page
title: Mata 20th Anniversary
date: 2016-05-24
author: Douglas Walter
tags: weekly links, java
status: published
summary: Suspendisse non sagittis lorem, nec scelerisque neque.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 08/02/2018
  endDate: 08/05/2018
  ctyhocn: PLKBHHX
  groupCode: M2A
published: true
---
Etiam euismod, dolor a sagittis dignissim, est augue tristique enim, non luctus odio est sit amet ex. Suspendisse viverra, ante sit amet condimentum viverra, sem est dignissim neque, in finibus nunc odio sit amet purus. Nulla elit mi, condimentum nec nulla vitae, finibus finibus dolor. Cras sagittis tincidunt erat at vestibulum. Suspendisse pretium sapien diam, eu euismod mauris tincidunt nec. Mauris sit amet nulla sit amet odio condimentum cursus ut eget urna. Praesent a sem velit. In at turpis interdum, ornare nisi sed, porttitor mi. Phasellus at tempor sem.

* Morbi nec ex elementum, fermentum erat a, egestas nibh
* Vestibulum pellentesque velit eu massa mattis, eget tincidunt ex pretium.

Praesent id massa tempor, mollis magna quis, dictum libero. Aliquam ac ex urna. Nulla consequat justo dolor, posuere mattis arcu pretium non. Etiam tincidunt volutpat tristique. Fusce sit amet ultricies arcu. Nam eget eros ornare, porttitor augue sit amet, scelerisque eros. Curabitur sed dapibus nunc. Praesent lacinia sem ut mattis tempus. Nunc maximus sit amet erat non facilisis. Quisque laoreet cursus quam vel tempor. Pellentesque in mauris ut urna dictum congue. Suspendisse vel aliquet tellus. Quisque non euismod odio.


text:
class WildflyAs < Formula
  desc "Managed application runtime for building applications"
  homepage "http://wildfly.org/"
  url "https://download.jboss.org/wildfly/12.0.0.Final/wildfly-12.0.0.Final.tar.gz"
  sha256 "42fa41b25a2cbf4782f78fd8c4d537a06acfa60688fcc0ece9299f140c76afe0"

  bottle :unneeded

  depends_on :java => "1.8+"

  def install
    rm_f Dir["bin/*.bat"]
    rm_f Dir["bin/*.ps1"]
    libexec.install Dir["*"]
    mkdir_p libexec/"standalone/log"
  end

  def caveats; <<~EOS
    The home of WildFly Application Server #{version} is:
      #{opt_libexec}
    You may want to add the following to your .bash_profile:
      export JBOSS_HOME=#{opt_libexec}
      export PATH=${PATH}:${JBOSS_HOME}/bin
    EOS
  end

  plist_options :manual => "#{HOMEBREW_PREFIX}/opt/wildfly-as/libexec/bin/standalone.sh --server-config=standalone.xml"

  def plist; <<~EOS
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
      <key>Label</key>
      <string>#{plist_name}</string>
      <key>KeepAlive</key>
      <dict>
        <key>SuccessfulExit</key>
        <false/>
        <key>Crashed</key>
        <true/>
      </dict>
      <key>ProgramArguments</key>
      <array>
        <string>#{opt_libexec}/bin/standalone.sh</string>
        <string>--server-config=standalone.xml</string>
      </array>
      <key>EnvironmentVariables</key>
      <dict>
        <key>JBOSS_HOME</key>
        <string>#{opt_libexec}</string>
        <key>WILDFLY_HOME</key>
        <string>#{opt_libexec}</string>
      </dict>
    </dict>
    </plist>
    EOS
  end

  test do
    ENV["JBOSS_HOME"] = opt_libexec
    system "#{opt_libexec}/bin/standalone.sh --version | grep #{version}"
  end
end


text:
package ru.job4j.set;

import org.junit.Test;

import java.util.Iterator;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Task Set.
 *
 * @author Dmitriy Bobrov (bobrov.dmitriy@gmail.com)
 * @since 28.07.2017
 */

public class LinkedSetTest {
    /**
     * Simple Add.
     */
    @Test
    public void whenAddValueToLinkedSetWithoutDuplicate() {
        LinkedSet<Integer> linkedSet = new LinkedSet<>();
        boolean result = linkedSet.add(1);
        boolean expected = true;
        assertThat(result, is(expected));
    }

    /**
     * Check duplicate.
     */
    @Test
    public void whenAddValueToLinkedSetWithDuplicate() {
        LinkedSet<Integer> linkedSet = new LinkedSet<>();
        linkedSet.add(1);
        boolean result = linkedSet.add(1);
        boolean expected = false;
        assertThat(result, is(expected));
    }

    /**
     * Check remove when value is exist.
     */
    @Test
    public void whenDeleteExistValue() {
        LinkedSet<Integer> linkedSet = new LinkedSet<>();
        linkedSet.add(1);
        linkedSet.add(2);
        boolean result = linkedSet.remove(2);
        boolean expected = true;
        assertThat(result, is(expected));
    }

    /**
     * Check remove when value isn't exist.
     */
    @Test
    public void whenDeleteNonExistValue() {
        LinkedSet<Integer> linkedSet = new LinkedSet<>();
        linkedSet.add(1);
        linkedSet.add(2);
        boolean result = linkedSet.remove(3);
        boolean expected = false;
        assertThat(result, is(expected));
    }

    /**
     * Test iterator.
     */
    @Test
    public void testIterationInRealCondition() {
        Integer result = 0;
        LinkedSet<Integer> linkedSet = new LinkedSet<>();
        Iterator<Integer> iterator = linkedSet.iterator();
        for (int i = 0; i < 10; i++) {
            linkedSet.add(i);
        }
        while (iterator.hasNext()) {
            result = iterator.next();
        }
        Integer expected = 9;
        assertThat(result, is(expected));
    }
}


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

using CookComputing.XmlRpc;

namespace XenAPI
{
    /// <summary>
    /// A VM crashdump
    /// First published in XenServer 4.0.
    /// </summary>
    public partial class Crashdump : XenObject<Crashdump>
    {
        public Crashdump()
        {
        }

        public Crashdump(string uuid,
            XenRef<VM> VM,
            XenRef<VDI> VDI,
            Dictionary<string, string> other_config)
        {
            this.uuid = uuid;
            this.VM = VM;
            this.VDI = VDI;
            this.other_config = other_config;
        }

        /// <summary>
        /// Creates a new Crashdump from a Proxy_Crashdump.
        /// </summary>
        /// <param name="proxy"></param>
        public Crashdump(Proxy_Crashdump proxy)
        {
            this.UpdateFromProxy(proxy);
        }

        public override void UpdateFrom(Crashdump update)
        {
            uuid = update.uuid;
            VM = update.VM;
            VDI = update.VDI;
            other_config = update.other_config;
        }

        internal void UpdateFromProxy(Proxy_Crashdump proxy)
        {
            uuid = proxy.uuid == null ? null : (string)proxy.uuid;
            VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM);
            VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI);
            other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
        }

        public Proxy_Crashdump ToProxy()
        {
            Proxy_Crashdump result_ = new Proxy_Crashdump();
            result_.uuid = (uuid != null) ? uuid : "";
            result_.VM = (VM != null) ? VM : "";
            result_.VDI = (VDI != null) ? VDI : "";
            result_.other_config = Maps.convert_to_proxy_string_string(other_config);
            return result_;
        }

        /// <summary>
        /// Creates a new Crashdump from a Hashtable.
        /// </summary>
        /// <param name="table"></param>
        public Crashdump(Hashtable table)
        {
            uuid = Marshalling.ParseString(table, "uuid");
            VM = Marshalling.ParseRef<VM>(table, "VM");
            VDI = Marshalling.ParseRef<VDI>(table, "VDI");
            other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
        }

        public bool DeepEquals(Crashdump other)
        {
            if (ReferenceEquals(null, other))
                return false;
            if (ReferenceEquals(this, other))
                return true;

            return Helper.AreEqual2(this._uuid, other._uuid) &&
                Helper.AreEqual2(this._VM, other._VM) &&
                Helper.AreEqual2(this._VDI, other._VDI) &&
                Helper.AreEqual2(this._other_config, other._other_config);
        }

        public override string SaveChanges(Session session, string opaqueRef, Crashdump server)
        {
            if (opaqueRef == null)
            {
                System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
                return "";
            }
            else
            {
                if (!Helper.AreEqual2(_other_config, server._other_config))
                {
                    Crashdump.set_other_config(session, opaqueRef, _other_config);
                }

                return null;
            }
        }
        /// <summary>
        /// Get a record containing the current state of the given crashdump.
        /// First published in XenServer 4.0.
        /// Deprecated since Unreleased.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        [Deprecated("Unreleased")]
        public static Crashdump get_record(Session session, string _crashdump)
        {
            return new Crashdump((Proxy_Crashdump)session.proxy.crashdump_get_record(session.uuid, (_crashdump != null) ? _crashdump : "").parse());
        }

        /// <summary>
        /// Get a reference to the crashdump instance with the specified UUID.
        /// First published in XenServer 4.0.
        /// Deprecated since Unreleased.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_uuid">UUID of object to return</param>
        [Deprecated("Unreleased")]
        public static XenRef<Crashdump> get_by_uuid(Session session, string _uuid)
        {
            return XenRef<Crashdump>.Create(session.proxy.crashdump_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
        }

        /// <summary>
        /// Get the uuid field of the given crashdump.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        public static string get_uuid(Session session, string _crashdump)
        {
            return (string)session.proxy.crashdump_get_uuid(session.uuid, (_crashdump != null) ? _crashdump : "").parse();
        }

        /// <summary>
        /// Get the VM field of the given crashdump.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        public static XenRef<VM> get_VM(Session session, string _crashdump)
        {
            return XenRef<VM>.Create(session.proxy.crashdump_get_vm(session.uuid, (_crashdump != null) ? _crashdump : "").parse());
        }

        /// <summary>
        /// Get the VDI field of the given crashdump.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        public static XenRef<VDI> get_VDI(Session session, string _crashdump)
        {
            return XenRef<VDI>.Create(session.proxy.crashdump_get_vdi(session.uuid, (_crashdump != null) ? _crashdump : "").parse());
        }

        /// <summary>
        /// Get the other_config field of the given crashdump.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        public static Dictionary<string, string> get_other_config(Session session, string _crashdump)
        {
            return Maps.convert_from_proxy_string_string(session.proxy.crashdump_get_other_config(session.uuid, (_crashdump != null) ? _crashdump : "").parse());
        }

        /// <summary>
        /// Set the other_config field of the given crashdump.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        /// <param name="_other_config">New value to set</param>
        public static void set_other_config(Session session, string _crashdump, Dictionary<string, string> _other_config)
        {
            session.proxy.crashdump_set_other_config(session.uuid, (_crashdump != null) ? _crashdump : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
        }

        /// <summary>
        /// Add the given key-value pair to the other_config field of the given crashdump.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        /// <param name="_key">Key to add</param>
        /// <param name="_value">Value to add</param>
        public static void add_to_other_config(Session session, string _crashdump, string _key, string _value)
        {
            session.proxy.crashdump_add_to_other_config(session.uuid, (_crashdump != null) ? _crashdump : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
        }

        /// <summary>
        /// Remove the given key and its corresponding value from the other_config field of the given crashdump.  If the key is not in that Map, then do nothing.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        /// <param name="_key">Key to remove</param>
        public static void remove_from_other_config(Session session, string _crashdump, string _key)
        {
            session.proxy.crashdump_remove_from_other_config(session.uuid, (_crashdump != null) ? _crashdump : "", (_key != null) ? _key : "").parse();
        }

        /// <summary>
        /// Destroy the specified crashdump
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        public static void destroy(Session session, string _crashdump)
        {
            session.proxy.crashdump_destroy(session.uuid, (_crashdump != null) ? _crashdump : "").parse();
        }

        /// <summary>
        /// Destroy the specified crashdump
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_crashdump">The opaque_ref of the given crashdump</param>
        public static XenRef<Task> async_destroy(Session session, string _crashdump)
        {
            return XenRef<Task>.Create(session.proxy.async_crashdump_destroy(session.uuid, (_crashdump != null) ? _crashdump : "").parse());
        }

        /// <summary>
        /// Return a list of all the crashdumps known to the system.
        /// First published in XenServer 4.0.
        /// Deprecated since Unreleased.
        /// </summary>
        /// <param name="session">The session</param>
        [Deprecated("Unreleased")]
        public static List<XenRef<Crashdump>> get_all(Session session)
        {
            return XenRef<Crashdump>.Create(session.proxy.crashdump_get_all(session.uuid).parse());
        }

        /// <summary>
        /// Get all the crashdump Records at once, in a single XML RPC call
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        public static Dictionary<XenRef<Crashdump>, Crashdump> get_all_records(Session session)
        {
            return XenRef<Crashdump>.Create<Proxy_Crashdump>(session.proxy.crashdump_get_all_records(session.uuid).parse());
        }

        /// <summary>
        /// Unique identifier/object reference
        /// </summary>
        public virtual string uuid
        {
            get { return _uuid; }
            set
            {
                if (!Helper.AreEqual(value, _uuid))
                {
                    _uuid = value;
                    Changed = true;
                    NotifyPropertyChanged("uuid");
                }
            }
        }
        private string _uuid;

        /// <summary>
        /// the virtual machine
        /// </summary>
        public virtual XenRef<VM> VM
        {
            get { return _VM; }
            set
            {
                if (!Helper.AreEqual(value, _VM))
                {
                    _VM = value;
                    Changed = true;
                    NotifyPropertyChanged("VM");
                }
            }
        }
        private XenRef<VM> _VM;

        /// <summary>
        /// the virtual disk
        /// </summary>
        public virtual XenRef<VDI> VDI
        {
            get { return _VDI; }
            set
            {
                if (!Helper.AreEqual(value, _VDI))
                {
                    _VDI = value;
                    Changed = true;
                    NotifyPropertyChanged("VDI");
                }
            }
        }
        private XenRef<VDI> _VDI;

        /// <summary>
        /// additional configuration
        /// First published in XenServer 4.1.
        /// </summary>
        public virtual Dictionary<string, string> other_config
        {
            get { return _other_config; }
            set
            {
                if (!Helper.AreEqual(value, _other_config))
                {
                    _other_config = value;
                    Changed = true;
                    NotifyPropertyChanged("other_config");
                }
            }
        }
        private Dictionary<string, string> _other_config;
    }
}