text:
/*
 * This is the method for dealing with BSD disklabels.  It has been
 * extensively (by my standards at least) commented, in the vain hope that
 * it will serve as the source in future copy&paste operations.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/geom/geom_bsd.c 235480 2012-05-15 17:21:46Z avg $");

#include <sys/param.h>
#include <sys/endian.h>
#include <sys/systm.h>
#include <sys/sysctl.h>
#include <sys/kernel.h>
#include <sys/fcntl.h>
#include <sys/conf.h>
#include <sys/bio.h>
#include <sys/malloc.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/md5.h>
#include <sys/errno.h>
#include <sys/disklabel.h>
#include <sys/gpt.h>
#include <sys/proc.h>
#include <sys/sbuf.h>
#include <sys/uuid.h>
#include <geom/geom.h>
#include <geom/geom_slice.h>

FEATURE(geom_bsd, "GEOM BSD disklabels support");

#define	BSD_CLASS_NAME "BSD"

#define ALPHA_LABEL_OFFSET	64
#define HISTORIC_LABEL_OFFSET	512

#define LABELSIZE (148 + 16 * MAXPARTITIONS)

static void g_bsd_hotwrite(void *arg, int flag);
/*
 * Our private data about one instance.  All the rest is handled by the
 * slice code and stored in its softc, so this is just the stuff
 * specific to BSD disklabels.
 */
struct g_bsd_softc {
	off_t	labeloffset;
	off_t	mbroffset;
	off_t	rawoffset;
	struct disklabel ondisk;
	u_char	label[LABELSIZE];
	u_char	labelsum[16];
};

/*
 * Modify our slicer to match proposed disklabel, if possible.
 * This is where we make sure we don't do something stupid.
 */
static int
g_bsd_modify(struct g_geom *gp, u_char *label)
{
	int i, error;
	struct partition *ppp;
	struct g_slicer *gsp;
	struct g_consumer *cp;
	struct g_bsd_softc *ms;
	u_int secsize, u;
	off_t rawoffset, o;
	struct disklabel dl;
	MD5_CTX md5sum;

	g_topology_assert();
	gsp = gp->softc;
	ms = gsp->softc;

	error = bsd_disklabel_le_dec(label, &dl, MAXPARTITIONS);
	if (error) {
		return (error);
	}

	/* Get dimensions of our device. */
	cp = LIST_FIRST(&gp->consumer);
	secsize = cp->provider->sectorsize;

	/* ... or a smaller sector size. */
	if (dl.d_secsize < secsize) {
		return (EINVAL);
	}

	/* ... or a non-multiple sector size. */
	if (dl.d_secsize % secsize != 0) {
		return (EINVAL);
	}

	/* Historical braindamage... */
	rawoffset = (off_t)dl.d_partitions[RAW_PART].p_offset * dl.d_secsize;

	for (i = 0; i < dl.d_npartitions; i++) {
		ppp = &dl.d_partitions[i];
		if (ppp->p_size == 0)
			continue;
	        o = (off_t)ppp->p_offset * dl.d_secsize;

		if (o < rawoffset)
			rawoffset = 0;
	}

	if (rawoffset != 0 && (off_t)rawoffset != ms->mbroffset)
		printf("WARNING: %s expected rawoffset %jd, found %jd\n",
		    gp->name,
		    (intmax_t)ms->mbroffset/dl.d_secsize,
		    (intmax_t)rawoffset/dl.d_secsize);

	/* Don't munge open partitions. */
	for (i = 0; i < dl.d_npartitions; i++) {
		ppp = &dl.d_partitions[i];

	        o = (off_t)ppp->p_offset * dl.d_secsize;
		if (o == 0)
			o = rawoffset;
		error = g_slice_config(gp, i, G_SLICE_CONFIG_CHECK,
		    o - rawoffset,
		    (off_t)ppp->p_size * dl.d_secsize,
		     dl.d_secsize,
		    "%s%c", gp->name, 'a' + i);
		if (error)
			return (error);
	}

	/* Look good, go for it... */
	for (u = 0; u < gsp->nslice; u++) {
		ppp = &dl.d_partitions[u];
	        o = (off_t)ppp->p_offset * dl.d_secsize;
		if (o == 0)
			o = rawoffset;
		g_slice_config(gp, u, G_SLICE_CONFIG_SET,
		    o - rawoffset,
		    (off_t)ppp->p_size * dl.d_secsize,
		     dl.d_secsize,
		    "%s%c", gp->name, 'a' + u);
	}

	/* Update our softc */
	ms->ondisk = dl;
	if (label != ms->label)
		bcopy(label, ms->label, LABELSIZE);
	ms->rawoffset = rawoffset;

	/*
	 * In order to avoid recursively attaching to the same
	 * on-disk label (it's usually visible through the 'c'
	 * partition) we calculate an MD5 and ask if other BSD's
	 * below us love that label.  If they do, we don't.
	 */
	MD5Init(&md5sum);
	MD5Update(&md5sum, ms->label, sizeof(ms->label));
	MD5Final(ms->labelsum, &md5sum);

	return (0);
}

/*
 * This is an internal helper function, called multiple times from the taste
 * function to try to locate a disklabel on the disk.  More civilized formats
 * will not need this, as there is only one possible place on disk to look
 * for the magic spot.
 */

static int
g_bsd_try(struct g_geom *gp, struct g_slicer *gsp, struct g_consumer *cp, int secsize, struct g_bsd_softc *ms, off_t offset)
{
	int error;
	u_char *buf;
	struct disklabel *dl;
	off_t secoff;

	/*
	 * We need to read entire aligned sectors, and we assume that the
	 * disklabel does not span sectors, so one sector is enough.
	 */
	secoff = offset % secsize;
	buf = g_read_data(cp, offset - secoff, secsize, NULL);
	if (buf == NULL)
		return (ENOENT);

	/* Decode into our native format. */
	dl = &ms->ondisk;
	error = bsd_disklabel_le_dec(buf + secoff, dl, MAXPARTITIONS);
	if (!error)
		bcopy(buf + secoff, ms->label, LABELSIZE);

	/* Remember to free the buffer g_read_data() gave us. */
	g_free(buf);

	ms->labeloffset = offset;
	return (error);
}

/*
 * This function writes the current label to disk, possibly updating
 * the alpha SRM checksum.
 */

static int
g_bsd_writelabel(struct g_geom *gp, u_char *bootcode)
{
	off_t secoff;
	u_int secsize;
	struct g_consumer *cp;
	struct g_slicer *gsp;
	struct g_bsd_softc *ms;
	u_char *buf;
	uint64_t sum;
	int error, i;

	gsp = gp->softc;
	ms = gsp->softc;
	cp = LIST_FIRST(&gp->consumer);
	/* Get sector size, we need it to read data. */
	secsize = cp->provider->sectorsize;
	secoff = ms->labeloffset % secsize;
	if (bootcode == NULL) {
		buf = g_read_data(cp, ms->labeloffset - secoff, secsize, &error);
		if (buf == NULL)
			return (error);
		bcopy(ms->label, buf + secoff, sizeof(ms->label));
	} else {
		buf = bootcode;
		bcopy(ms->label, buf + ms->labeloffset, sizeof(ms->label));
	}
	if (ms->labeloffset == ALPHA_LABEL_OFFSET) {
		sum = 0;
		for (i = 0; i < 63; i++)
			sum += le64dec(buf + i * 8);
		le64enc(buf + 504, sum);
	}
	if (bootcode == NULL) {
		error = g_write_data(cp, ms->labeloffset - secoff, buf, secsize);
		g_free(buf);
	} else {
		error = g_write_data(cp, 0, bootcode, BBSIZE);
	}
	return(error);
}

/*
 * If the user tries to overwrite our disklabel through an open partition
 * or via a magicwrite config call, we end up here and try to prevent
 * footshooting as best we can.
 */
static void
g_bsd_hotwrite(void *arg, int flag)
{
	struct bio *bp;
	struct g_geom *gp;
	struct g_slicer *gsp;
	struct g_slice *gsl;
	struct g_bsd_softc *ms;
	u_char *p;
	int error;

	g_topology_assert();
	/*
	 * We should never get canceled, because that would amount to a removal
	 * of the geom while there was outstanding I/O requests.
	 */
	KASSERT(flag != EV_CANCEL, ("g_bsd_hotwrite cancelled"));
	bp = arg;
	gp = bp->bio_to->geom;
	gsp = gp->softc;
	ms = gsp->softc;
	gsl = &gsp->slices[bp->bio_to->index];
	p = (u_char*)bp->bio_data + ms->labeloffset
	    - (bp->bio_offset + gsl->offset);
	error = g_bsd_modify(gp, p);
	if (error) {
		g_io_deliver(bp, EPERM);
		return;
	}
	g_slice_finish_hot(bp);
}

/*-
 * This start routine is only called for non-trivial requests, all the
 * trivial ones are handled autonomously by the slice code.
 * For requests we handle here, we must call the g_io_deliver() on the
 * bio, and return non-zero to indicate to the slice code that we did so.
 * This code executes in the "DOWN" I/O path, this means:
 *    * No sleeping.
 *    * Don't grab the topology lock.
 *    * Don't call biowait, g_getattr(), g_setattr() or g_read_data()
 */
static int
g_bsd_ioctl(struct g_provider *pp, u_long cmd, void *data, int fflag, struct thread *td)
{
	struct g_geom *gp;
	struct g_bsd_softc *ms;
	struct g_slicer *gsp;
	u_char *label;
	int error;

	gp = pp->geom;
	gsp = gp->softc;
	ms = gsp->softc;

	switch(cmd) {
	case DIOCGDINFO:
		/* Return a copy of the disklabel to userland. */
		bsd_disklabel_le_dec(ms->label, data, MAXPARTITIONS);
		return(0);
	case DIOCBSDBB: {
		struct g_consumer *cp;
		u_char *buf;
		void *p;
		int error, i;
		uint64_t sum;

		if (!(fflag & FWRITE))
			return (EPERM);
		/* The disklabel to set is the ioctl argument. */
		buf = g_malloc(BBSIZE, M_WAITOK);
		p = *(void **)data;
		error = copyin(p, buf, BBSIZE);
		if (!error) {
			/* XXX: Rude, but supposedly safe */
			DROP_GIANT();
			g_topology_lock();
			/* Validate and modify our slice instance to match. */
			error = g_bsd_modify(gp, buf + ms->labeloffset);
			if (!error) {
				cp = LIST_FIRST(&gp->consumer);
				if (ms->labeloffset == ALPHA_LABEL_OFFSET) {
					sum = 0;
					for (i = 0; i < 63; i++)
						sum += le64dec(buf + i * 8);
					le64enc(buf + 504, sum);
				}
				error = g_write_data(cp, 0, buf, BBSIZE);
			}
			g_topology_unlock();
			PICKUP_GIANT();
		}
		g_free(buf);
		return (error);
	}
	case DIOCSDINFO:
	case DIOCWDINFO: {
		if (!(fflag & FWRITE))
			return (EPERM);
		label = g_malloc(LABELSIZE, M_WAITOK);
		/* The disklabel to set is the ioctl argument. */
		bsd_disklabel_le_enc(label, data);

		DROP_GIANT();
		g_topology_lock();
		/* Validate and modify our slice instance to match. */
		error = g_bsd_modify(gp, label);
		if (error == 0 && cmd == DIOCWDINFO)
			error = g_bsd_writelabel(gp, NULL);
		g_topology_unlock();
		PICKUP_GIANT();
		g_free(label);
		return(error);
	}
	default:
		return (ENOIOCTL);
	}
}

static int
g_bsd_start(struct bio *bp)
{
	struct g_geom *gp;
	struct g_bsd_softc *ms;
	struct g_slicer *gsp;

	gp = bp->bio_to->geom;
	gsp = gp->softc;
	ms = gsp->softc;
	if (bp->bio_cmd == BIO_GETATTR) {
		if (g_handleattr(bp, "BSD::labelsum", ms->labelsum,
		    sizeof(ms->labelsum)))
			return (1);
	}
	return (0);
}

/*
 * Dump configuration information in XML format.
 * Notice that the function is called once for the geom and once for each
 * consumer and provider.  We let g_slice_dumpconf() do most of the work.
 */
static void
g_bsd_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp, struct g_consumer *cp, struct g_provider *pp)
{
	struct g_bsd_softc *ms;
	struct g_slicer *gsp;

	gsp = gp->softc;
	ms = gsp->softc;
	g_slice_dumpconf(sb, indent, gp, cp, pp);
	if (indent != NULL && pp == NULL && cp == NULL) {
		sbuf_printf(sb, "%s<labeloffset>%jd</labeloffset>\n",
		    indent, (intmax_t)ms->labeloffset);
		sbuf_printf(sb, "%s<rawoffset>%jd</rawoffset>\n",
		    indent, (intmax_t)ms->rawoffset);
		sbuf_printf(sb, "%s<mbroffset>%jd</mbroffset>\n",
		    indent, (intmax_t)ms->mbroffset);
	} else if (pp != NULL) {
		if (indent == NULL)
			sbuf_printf(sb, " ty %d",
			    ms->ondisk.d_partitions[pp->index].p_fstype);
		else
			sbuf_printf(sb, "%s<type>%d</type>\n", indent,
			    ms->ondisk.d_partitions[pp->index].p_fstype);
	}
}

/*
 * The taste function is called from the event-handler, with the topology
 * lock already held and a provider to examine.  The flags are unused.
 *
 * If flags == G_TF_NORMAL, the idea is to take a bite of the provider and
 * if we find valid, consistent magic on it, build a geom on it.
 *
 * There may be cases where the operator would like to put a BSD-geom on
 * providers which do not meet all of the requirements.  This can be done
 * by instead passing the G_TF_INSIST flag, which will override these
 * checks.
 *
 * The final flags value is G_TF_TRANSPARENT, which instructs the method
 * to put a geom on top of the provider and configure it to be as transparent
 * as possible.  This is not really relevant to the BSD method and therefore
 * not implemented here.
 */

static struct uuid freebsd_slice = GPT_ENT_TYPE_FREEBSD;

static struct g_geom *
g_bsd_taste(struct g_class *mp, struct g_provider *pp, int flags)
{
	struct g_geom *gp;
	struct g_consumer *cp;
	int error, i;
	struct g_bsd_softc *ms;
	u_int secsize;
	struct g_slicer *gsp;
	u_char hash[16];
	MD5_CTX md5sum;
	struct uuid uuid;

	g_trace(G_T_TOPOLOGY, "bsd_taste(%s,%s)", mp->name, pp->name);
	g_topology_assert();

	/* We don't implement transparent inserts. */
	if (flags == G_TF_TRANSPARENT)
		return (NULL);

	/*
	 * BSD labels are a subclass of the general "slicing" topology so
	 * a lot of the work can be done by the common "slice" code.
	 * Create a geom with space for MAXPARTITIONS providers, one consumer
	 * and a softc structure for us.  Specify the provider to attach
	 * the consumer to and our "start" routine for special requests.
	 * The provider is opened with mode (1,0,0) so we can do reads
	 * from it.
	 */
	gp = g_slice_new(mp, MAXPARTITIONS, pp, &cp, &ms,
	     sizeof(*ms), g_bsd_start);
	if (gp == NULL)
		return (NULL);

	/* Get the geom_slicer softc from the geom. */
	gsp = gp->softc;

	/*
	 * The do...while loop here allows us to have multiple escapes
	 * using a simple "break".  This improves code clarity without
	 * ending up in deep nesting and without using goto or come from.
	 */
	do {
		/*
		 * If the provider is an MBR we will only auto attach
		 * to type 165 slices in the G_TF_NORMAL case.  We will
		 * attach to any other type.
		 */
		error = g_getattr("MBR::type", cp, &i);
		if (!error) {
			if (i != 165 && flags == G_TF_NORMAL)
				break;
			error = g_getattr("MBR::offset", cp, &ms->mbroffset);
			if (error)
				break;
		}

		/* Same thing if we are inside a PC98 */
		error = g_getattr("PC98::type", cp, &i);
		if (!error) {
			if (i != 0xc494 && flags == G_TF_NORMAL)
				break;
			error = g_getattr("PC98::offset", cp, &ms->mbroffset);
			if (error)
				break;
		}

		/* Same thing if we are inside a GPT */
		error = g_getattr("GPT::type", cp, &uuid);
		if (!error) {
			if (memcmp(&uuid, &freebsd_slice, sizeof(uuid)) != 0 &&
			    flags == G_TF_NORMAL)
				break;
		}

		/* Get sector size, we need it to read data. */
		secsize = cp->provider->sectorsize;
		if (secsize < 512)
			break;

		/* First look for a label at the start of the second sector. */
		error = g_bsd_try(gp, gsp, cp, secsize, ms, secsize);

		/*
		 * If sector size is not 512 the label still can be at
		 * offset 512, not at the start of the second sector. At least
		 * it's true for labels created by the FreeBSD's bsdlabel(8).
		 */
		if (error && secsize != HISTORIC_LABEL_OFFSET)
			error = g_bsd_try(gp, gsp, cp, secsize, ms,
			    HISTORIC_LABEL_OFFSET);

		/* Next, look for alpha labels */
		if (error)
			error = g_bsd_try(gp, gsp, cp, secsize, ms,
			    ALPHA_LABEL_OFFSET);

		/* If we didn't find a label, punt. */
		if (error)
			break;

		/*
		 * In order to avoid recursively attaching to the same
		 * on-disk label (it's usually visible through the 'c'
		 * partition) we calculate an MD5 and ask if other BSD's
		 * below us love that label.  If they do, we don't.
		 */
		MD5Init(&md5sum);
		MD5Update(&md5sum, ms->label, sizeof(ms->label));
		MD5Final(ms->labelsum, &md5sum);

		error = g_getattr("BSD::labelsum", cp, &hash);
		if (!error && !bcmp(ms->labelsum, hash, sizeof(hash)))
			break;

		/*
		 * Process the found disklabel, and modify our "slice"
		 * instance to match it, if possible.
		 */
		error = g_bsd_modify(gp, ms->label);
	} while (0);

	/* Success or failure, we can close our provider now. */
	g_access(cp, -1, 0, 0);

	/* If we have configured any providers, return the new geom. */
	if (gsp->nprovider > 0) {
		g_slice_conf_hot(gp, 0, ms->labeloffset, LABELSIZE,
		    G_SLICE_HOT_ALLOW, G_SLICE_HOT_DENY, G_SLICE_HOT_CALL);
		gsp->hot = g_bsd_hotwrite;
		return (gp);
	}
	/*
	 * ...else push the "self-destruct" button, by spoiling our own
	 * consumer.  This triggers a call to g_slice_spoiled which will
	 * dismantle what was setup.
	 */
	g_slice_spoiled(cp);
	return (NULL);
}

struct h0h0 {
	struct g_geom *gp;
	struct g_bsd_softc *ms;
	u_char *label;
	int error;
};

static void
g_bsd_callconfig(void *arg, int flag)
{
	struct h0h0 *hp;

	hp = arg;
	hp->error = g_bsd_modify(hp->gp, hp->label);
	if (!hp->error)
		hp->error = g_bsd_writelabel(hp->gp, NULL);
}

/*
 * NB! curthread is user process which GCTL'ed.
 */
static void
g_bsd_config(struct gctl_req *req, struct g_class *mp, char const *verb)
{
	u_char *label;
	int error;
	struct h0h0 h0h0;
	struct g_geom *gp;
	struct g_slicer *gsp;
	struct g_consumer *cp;
	struct g_bsd_softc *ms;

	g_topology_assert();
	gp = gctl_get_geom(req, mp, "geom");
	if (gp == NULL)
		return;
	cp = LIST_FIRST(&gp->consumer);
	gsp = gp->softc;
	ms = gsp->softc;
	if (!strcmp(verb, "read mbroffset")) {
		gctl_set_param_err(req, "mbroffset", &ms->mbroffset,
		    sizeof(ms->mbroffset));
		return;
	} else if (!strcmp(verb, "write label")) {
		label = gctl_get_paraml(req, "label", LABELSIZE);
		if (label == NULL)
			return;
		h0h0.gp = gp;
		h0h0.ms = gsp->softc;
		h0h0.label = label;
		h0h0.error = -1;
		/* XXX: Does this reference register with our selfdestruct code ? */
		error = g_access(cp, 1, 1, 1);
		if (error) {
			gctl_error(req, "could not access consumer");
			return;
		}
		g_bsd_callconfig(&h0h0, 0);
		error = h0h0.error;
		g_access(cp, -1, -1, -1);
	} else if (!strcmp(verb, "write bootcode")) {
		label = gctl_get_paraml(req, "bootcode", BBSIZE);
		if (label == NULL)
			return;
		/* XXX: Does this reference register with our selfdestruct code ? */
		error = g_access(cp, 1, 1, 1);
		if (error) {
			gctl_error(req, "could not access consumer");
			return;
		}
		error = g_bsd_writelabel(gp, label);
		g_access(cp, -1, -1, -1);
	} else {
		gctl_error(req, "Unknown verb parameter");
	}

	return;
}

/* Finally, register with GEOM infrastructure. */
static struct g_class g_bsd_class = {
	.name = BSD_CLASS_NAME,
	.version = G_VERSION,
	.taste = g_bsd_taste,
	.ctlreq = g_bsd_config,
	.dumpconf = g_bsd_dumpconf,
	.ioctl = g_bsd_ioctl,
};

DECLARE_GEOM_CLASS(g_bsd_class, g_bsd);


text:
package com.github.ptest.element;

import com.github.ptest.runConfiguration.PTestRunConfiguration;
import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.PsiElement;

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

public abstract class PTestElement<E extends PsiElement> {
    private E myElement;
    private List<String> myErrors = new ArrayList<>();

    public PTestElement(E element) {
        myElement = element;
    }

    public E getValue() {
        return myElement;
    }

    public void addError(String error) {
        myErrors.add(error);
    }

    public List<String> getErrors() {
        return myErrors;
    }

    public abstract boolean setupConfiguration(PTestRunConfiguration configuration);

    public List<PTestElement> getChildren() {
        return null;
    }

    public ItemPresentation getPresentation() {
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package me.androidbox.busbymovies.moviedetails;

import android.content.Context;
import android.widget.ImageView;

import com.bumptech.glide.Priority;

import me.androidbox.busbymovies.utils.GlideApp;
import me.androidbox.busbymovies.utils.ImageLoader;

/**
 * Created by steve on 9/19/17.
 */
public class ImageLoaderImp implements ImageLoader {
    public ImageLoaderImp() {}

    @Override
    public void load(final Context context, final String path, final int placeholder, final ImageView imageView, final Priority priority) {
        GlideApp.with(context)
                .load(path)
                .placeholder(placeholder)
                .priority(priority)
                .into(imageView);
    }
}


text:
using System;

namespace VGPrompter {

    public partial class Script {

        [Serializable]
        class VGPReturn : DummyLine { }

    }

}


text:
    fastlane

  deliver •
  snapshot •
  frameit •
  PEM •
  sigh •
  produce •
  cert •
  codes •
  spaceship •
  pilot •
  boarding •
  gym

-------

gym
============

[![Twitter: @KauseFx](https://img.shields.io/badge/contact-@KrauseFx-blue.svg?style=flat)](https://twitter.com/KrauseFx)
[![License](http://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://github.com/fastlane/gym/blob/master/LICENSE)
[![Gem](https://img.shields.io/gem/v/gym.svg?style=flat)](http://rubygems.org/gems/gym)
[![Build Status](https://img.shields.io/travis/fastlane/gym/master.svg?style=flat)](https://travis-ci.org/fastlane/gym)

###### Building your app has never been easier

Get in contact with the developer on Twitter: [@KrauseFx](https://twitter.com/KrauseFx)

-------

    Features •
    Installation •
    Usage •
    Tips •
    Need help?

-------

gym is part of fastlane: connect all deployment tools into one streamlined workflow.

# What's gym?

`gym` builds and packages iOS apps for you. It takes care of all the heavy lifting and makes it super easy to generate a signed `ipa` file :muscle:

`gym` is a replacement for [shenzhen](https://github.com/nomad/shenzhen).

### Before `gym`

```
xcodebuild clean archive -archivePath build/MyApp \
                         -scheme MyApp
xcodebuild -exportArchive \
           -exportFormat ipa \
           -archivePath "build/MyApp.xcarchive" \
           -exportPath "build/MyApp.ipa" \
           -exportProvisioningProfile "ProvisioningProfileName"
```

### With `gym`

```
gym
```

### Why `gym`?

`gym` uses the latest APIs to build and sign your application which results in much faster build times.

              |  Gym Features
--------------------------|------------------------------------------------------------
:rocket:            | `gym` builds 30% faster than other build tools like [shenzhen](https://github.com/nomad/shenzhen)
:checkered_flag: | Beautiful inline build output
:book:     | Helps you resolve common build errors like code signing issues
:mountain_cableway: | Sensible defaults: Automatically detect the project, its schemes and more
:link:  | Works perfectly with [fastlane](https://fastlane.tools) and other tools
:package: | Automatically generates an `ipa` and a compressed `dSYM` file
:bullettrain_side: | Don't remember any complicated build commands, just `gym`
:wrench:  | Easy and dynamic configuration using parameters and environment variables
:floppy_disk:   | Store common build settings in a `Gymfile`
:computer: | All archives are stored and accessible in the Xcode Organizer

![/assets/gymScreenshot.png](/assets/gymScreenshot.png)

-----

![/assets/gym.gif](/assets/gym.gif)

# Installation

This tool is still work in progress. You can already try it by cloning the repo and running

    sudo gem install gym

Make sure, you have the latest version of the Xcode command line tools installed:

    xcode-select --install

# Usage

    gym

That's all you need to build your application. If you want more control, here are some available parameters:

    gym --workspace "Example.xcworkspace" --scheme "AppName" --clean

For a list of all available parameters use

    gym --help

If you run into any issues, use the `verbose` mode to get more information

    gym --verbose

# Gymfile

Since you might want to manually trigger a new build but don't want to specify all the parameters every time, you can store your defaults in a so called `Gymfile`.

Run `gym init` to create a new configuration file. Example:

```ruby
scheme "Example"

sdk "9.0"

clean true

output_directory "./build"    # store the ipa in this folder
output_name "MyApp"           # the name of the ipa file
```

# How does it work?

`gym` uses the latest APIs to build and sign your application. The 2 main components are

- `xcodebuild`
- [xcpretty](https://github.com/supermarin/xcpretty)

When you run `gym` without the `--silent` mode it will print out every command it executes.

To build the archive `gym` uses the following command:

```
set -o pipefail && \
xcodebuild -scheme 'Example' \
-project './Example.xcodeproj' \
-configuration 'Release' \
-destination 'generic/platform=iOS' \
-archivePath '/Users/felixkrause/Library/Developer/Xcode/Archives/2015-08-11/ExampleProductName 2015-08-11 18.15.30.xcarchive' \
archive | xcpretty
```

After building the archive it is being checked by `gym`. If it's valid, it gets packaged up and signed into an `ipa` file.

```
/usr/bin/xcrun /path/to/PackageApplication4Gym -v \
'/Users/felixkrause/Library/Developer/Xcode/Archives/2015-08-11/ExampleProductName 2015-08-11 18.15.30.xcarchive/Products/Applications/name.app' -o \
'/Users/felixkrause/Library/Developer/Xcode/Archives/2015-08-11/ExampleProductName.ipa' \
--sign "identity" --embed "provProfile"
```

Note: the official PackageApplication script is replaced by a custom PackageApplication4Gym script. This script is obtained by applying a [set of patches](https://github.com/fastlane/gym/tree/master/lib/assets/package_application_patches) on the fly to fix some known issues in the official Xcode PackageApplication script.

Afterwards the `ipa` file is moved to the output folder. The `dSYM` file is compressed and moved to the output folder as well.

# Tips
## [`fastlane`](https://fastlane.tools) Toolchain

- [`fastlane`](https://fastlane.tools): Connect all deployment tools into one streamlined workflow
- [`deliver`](https://github.com/KrauseFx/deliver): Upload screenshots, metadata and your app to the App Store
- [`snapshot`](https://github.com/KrauseFx/snapshot): Automate taking localized screenshots of your iOS app on every device
- [`frameit`](https://github.com/KrauseFx/frameit): Quickly put your screenshots into the right device frames
- [`PEM`](https://github.com/KrauseFx/pem): Automatically generate and renew your push notification profiles
- [`produce`](https://github.com/KrauseFx/produce): Create new iOS apps on iTunes Connect and Dev Portal using the command line
- [`cert`](https://github.com/KrauseFx/cert): Automatically create and maintain iOS code signing certificates
- [`codes`](https://github.com/KrauseFx/codes): Create promo codes for iOS Apps using the command line
- [`spaceship`](https://github.com/fastlane/spaceship): Ruby library to access the Apple Dev Center and iTunes Connect
- [`pilot`](https://github.com/fastlane/pilot): The best way to manage your TestFlight testers and builds from your terminal
- [`boarding`](https://github.com/fastlane/boarding): The easiest way to invite your TestFlight beta testers

##### [Like this tool? Be the first to know about updates and new fastlane tools](https://tinyletter.com/krausefx)

## Use the 'Provisioning Quicklook plugin'
Download and install the [Provisioning Plugin](https://github.com/chockenberry/Provisioning).

# Need help?
Please submit an issue on GitHub and provide information about your setup

# License
This project is licensed under the terms of the MIT license. See the LICENSE file.

> This project and all fastlane tools are in no way affiliated with Apple Inc. This project is open source under the MIT license, which means you have full access to the source code and can modify it to fit your own needs. All fastlane tools run on your own computer or server, so your credentials or other sensitive information will never leave your own computer. You are responsible for how you use fastlane tools.


text:
const fs = require("fs");

main();

function main() {

    if (process.argv.length < 3) {
        process.exit(1);
    }

    const infile = process.argv[2];
    const outfile = process.argv.length > 3 ? process.argv[3] : infile;

    let contents = fs.readFileSync(infile, "utf8");
    contents = JSON.parse(contents);

    const regex = /^(?:(?:\/?\.{1,2}\/){0,}|\/)src\//g;

    for (let i = 0; i < contents.sources.length; i++) {
        contents.sources[i] = contents.sources[i].replace(regex, "putz/source/");
    }

    fs.writeFileSync(outfile, JSON.stringify(contents), { encoding: "utf8" });

    process.exit(0);

}


text:
package com.gitblit.client;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;

import com.gitblit.Constants.RpcRequest;
import com.gitblit.models.TeamModel;
import com.gitblit.utils.StringUtils;

/**
 * Users panel displays a list of user accounts and allows management of those
 * accounts.
 *
 * @author James Moger
 *
 */
public abstract class TeamsPanel extends JPanel {

	private static final long serialVersionUID = 1L;

	private final GitblitClient gitblit;

	private HeaderPanel header;

	private JTable table;

	private TeamsTableModel tableModel;

	private TableRowSorter<TeamsTableModel> defaultSorter;

	private JTextField filterTextfield;

	public TeamsPanel(GitblitClient gitblit) {
		super();
		this.gitblit = gitblit;
		initialize();
	}

	private void initialize() {
		JButton refreshTeams = new JButton(Translation.get("gb.refresh"));
		refreshTeams.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				refreshTeams();
			}
		});

		JButton createTeam = new JButton(Translation.get("gb.create"));
		createTeam.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				createTeam();
			}
		});

		final JButton editTeam = new JButton(Translation.get("gb.edit"));
		editTeam.setEnabled(false);
		editTeam.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				editTeam(getSelectedTeams().get(0));
			}
		});

		final JButton delTeam = new JButton(Translation.get("gb.delete"));
		delTeam.setEnabled(false);
		delTeam.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deleteTeams(getSelectedTeams());
			}
		});

		NameRenderer nameRenderer = new NameRenderer();
		tableModel = new TeamsTableModel();
		defaultSorter = new TableRowSorter<TeamsTableModel>(tableModel);
		table = Utils.newTable(tableModel, Utils.DATE_FORMAT);
		String name = table.getColumnName(TeamsTableModel.Columns.Name.ordinal());
		table.getColumn(name).setCellRenderer(nameRenderer);

		int w = 125;
		name = table.getColumnName(TeamsTableModel.Columns.Members.ordinal());
		table.getColumn(name).setMinWidth(w);
		table.getColumn(name).setMaxWidth(w);
		name = table.getColumnName(TeamsTableModel.Columns.Repositories.ordinal());
		table.getColumn(name).setMinWidth(w);
		table.getColumn(name).setMaxWidth(w);

		table.setRowSorter(defaultSorter);
		table.getRowSorter().toggleSortOrder(TeamsTableModel.Columns.Name.ordinal());
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				if (e.getValueIsAdjusting()) {
					return;
				}
				boolean selected = table.getSelectedRow() > -1;
				boolean singleSelection = table.getSelectedRows().length == 1;
				editTeam.setEnabled(singleSelection && selected);
				delTeam.setEnabled(selected);
			}
		});

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					editTeam(getSelectedTeams().get(0));
				}
			}
		});

		filterTextfield = new JTextField();
		filterTextfield.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				filterTeams(filterTextfield.getText());
			}
		});
		filterTextfield.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
				filterTeams(filterTextfield.getText());
			}
		});

		JPanel teamFilterPanel = new JPanel(new BorderLayout(Utils.MARGIN, Utils.MARGIN));
		teamFilterPanel.add(new JLabel(Translation.get("gb.filter")), BorderLayout.WEST);
		teamFilterPanel.add(filterTextfield, BorderLayout.CENTER);

		JPanel teamTablePanel = new JPanel(new BorderLayout(Utils.MARGIN, Utils.MARGIN));
		teamTablePanel.add(teamFilterPanel, BorderLayout.NORTH);
		teamTablePanel.add(new JScrollPane(table), BorderLayout.CENTER);

		JPanel teamControls = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
		teamControls.add(refreshTeams);
		teamControls.add(createTeam);
		teamControls.add(editTeam);
		teamControls.add(delTeam);

		setLayout(new BorderLayout(Utils.MARGIN, Utils.MARGIN));
		header = new HeaderPanel(Translation.get("gb.teams"), "users_16x16.png");
		add(header, BorderLayout.NORTH);
		add(teamTablePanel, BorderLayout.CENTER);
		add(teamControls, BorderLayout.SOUTH);
	}

	@Override
	public void requestFocus() {
		filterTextfield.requestFocus();
	}

	@Override
	public Insets getInsets() {
		return Utils.INSETS;
	}

	protected abstract void updateUsersTable();

	protected void updateTable(boolean pack) {
		tableModel.list.clear();
		tableModel.list.addAll(gitblit.getTeams());
		tableModel.fireTableDataChanged();
		header.setText(Translation.get("gb.teams") + " (" + gitblit.getTeams().size() + ")");
		if (pack) {
			Utils.packColumns(table, Utils.MARGIN);
		}
	}

	private void filterTeams(final String fragment) {
		if (StringUtils.isEmpty(fragment)) {
			table.setRowSorter(defaultSorter);
			return;
		}
		RowFilter<TeamsTableModel, Object> containsFilter = new RowFilter<TeamsTableModel, Object>() {
			public boolean include(Entry<? extends TeamsTableModel, ? extends Object> entry) {
				for (int i = entry.getValueCount() - 1; i >= 0; i--) {
					if (entry.getStringValue(i).toLowerCase().contains(fragment.toLowerCase())) {
						return true;
					}
				}
				return false;
			}
		};
		TableRowSorter<TeamsTableModel> sorter = new TableRowSorter<TeamsTableModel>(tableModel);
		sorter.setRowFilter(containsFilter);
		table.setRowSorter(sorter);
	}

	private List<TeamModel> getSelectedTeams() {
		List<TeamModel> teams = new ArrayList<TeamModel>();
		for (int viewRow : table.getSelectedRows()) {
			int modelRow = table.convertRowIndexToModel(viewRow);
			TeamModel model = tableModel.list.get(modelRow);
			teams.add(model);
		}
		return teams;
	}

	protected void refreshTeams() {
		GitblitWorker worker = new GitblitWorker(TeamsPanel.this, RpcRequest.LIST_TEAMS) {
			@Override
			protected Boolean doRequest() throws IOException {
				gitblit.refreshTeams();
				return true;
			}

			@Override
			protected void onSuccess() {
				updateTable(false);
			}
		};
		worker.execute();
	}

	/**
	 * Displays the create team dialog and fires a SwingWorker to update the
	 * server, if appropriate.
	 *
	 */
	protected void createTeam() {
		EditTeamDialog dialog = new EditTeamDialog(gitblit.getProtocolVersion(),
				gitblit.getSettings());
		dialog.setLocationRelativeTo(TeamsPanel.this);
		dialog.setTeams(gitblit.getTeams());
		dialog.setRepositories(gitblit.getRepositories(), null);
		dialog.setUsers(gitblit.getUsernames(), null);
		dialog.setPreReceiveScripts(gitblit.getPreReceiveScriptsUnused(null),
				gitblit.getPreReceiveScriptsInherited(null), null);
		dialog.setPostReceiveScripts(gitblit.getPostReceiveScriptsUnused(null),
				gitblit.getPostReceiveScriptsInherited(null), null);
		dialog.setVisible(true);
		final TeamModel newTeam = dialog.getTeam();
		if (newTeam == null) {
			return;
		}

		GitblitWorker worker = new GitblitWorker(this, RpcRequest.CREATE_TEAM) {

			@Override
			protected Boolean doRequest() throws IOException {
				boolean success = gitblit.createTeam(newTeam);
				if (success) {
					gitblit.refreshTeams();
					gitblit.refreshUsers();
				}
				return success;
			}

			@Override
			protected void onSuccess() {
				updateTable(false);
				updateUsersTable();
			}

			@Override
			protected void onFailure() {
				showFailure("Failed to execute request \"{0}\" for team \"{1}\".",
						getRequestType(), newTeam.name);
			}
		};
		worker.execute();
	}

	/**
	 * Displays the edit team dialog and fires a SwingWorker to update the
	 * server, if appropriate.
	 *
	 * @param user
	 */
	protected void editTeam(final TeamModel team) {
		EditTeamDialog dialog = new EditTeamDialog(gitblit.getProtocolVersion(), team,
				gitblit.getSettings());
		dialog.setLocationRelativeTo(TeamsPanel.this);
		dialog.setTeams(gitblit.getTeams());
		dialog.setRepositories(gitblit.getRepositories(), team.getRepositoryPermissions());
		dialog.setUsers(gitblit.getUsernames(), team.users == null ? null : new ArrayList<String>(
				team.users));
		dialog.setPreReceiveScripts(gitblit.getPreReceiveScriptsUnused(null),
				gitblit.getPreReceiveScriptsInherited(null), team.preReceiveScripts);
		dialog.setPostReceiveScripts(gitblit.getPostReceiveScriptsUnused(null),
				gitblit.getPostReceiveScriptsInherited(null), team.postReceiveScripts);
		dialog.setVisible(true);
		final TeamModel revisedTeam = dialog.getTeam();
		if (revisedTeam == null) {
			return;
		}

		GitblitWorker worker = new GitblitWorker(this, RpcRequest.EDIT_TEAM) {
			@Override
			protected Boolean doRequest() throws IOException {
				boolean success = gitblit.updateTeam(team.name, revisedTeam);
				if (success) {
					gitblit.refreshTeams();
					gitblit.refreshUsers();
				}
				return success;
			}

			@Override
			protected void onSuccess() {
				updateTable(false);
				updateUsersTable();
			}

			@Override
			protected void onFailure() {
				showFailure("Failed to execute request \"{0}\" for team \"{1}\".",
						getRequestType(), team.name);
			}
		};
		worker.execute();
	}

	protected void deleteTeams(final List<TeamModel> teams) {
		if (teams == null || teams.size() == 0) {
			return;
		}
		StringBuilder message = new StringBuilder("Delete the following teams?\n\n");
		for (TeamModel team : teams) {
			message.append(team.name).append("\n");
		}
		int result = JOptionPane.showConfirmDialog(TeamsPanel.this, message.toString(),
				"Delete Teams?", JOptionPane.YES_NO_OPTION);
		if (result == JOptionPane.YES_OPTION) {
			GitblitWorker worker = new GitblitWorker(this, RpcRequest.DELETE_TEAM) {
				@Override
				protected Boolean doRequest() throws IOException {
					boolean success = true;
					for (TeamModel team : teams) {
						success &= gitblit.deleteTeam(team);
					}
					if (success) {
						gitblit.refreshTeams();
						gitblit.refreshUsers();
					}
					return success;
				}

				@Override
				protected void onSuccess() {
					updateTable(false);
					updateUsersTable();
				}

				@Override
				protected void onFailure() {
					showFailure("Failed to delete specified teams!");
				}
			};
			worker.execute();
		}
	}
}


text:
$:.unshift(File.dirname(__FILE__) + '/../lib')

require 'test/unit'
require File.expand_path(File.join(File.dirname(__FILE__), '../../../../config/environment.rb'))
require 'rubygems'
#require 'active_support/breakpoint'
require 'active_record/fixtures'

config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite'])

load(File.dirname(__FILE__) + "/schema.rb")

Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures/"
$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path)

class Test::Unit::TestCase #:nodoc:
  def create_fixtures(*table_names)
    if block_given?
      Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield }
    else
      Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names)
    end
  end

  # Turn off transactional fixtures if you're working with MyISAM tables in MySQL
  self.use_transactional_fixtures = true

  # Instantiated fixtures are slow, but give you @david where you otherwise would need people(:david)
  self.use_instantiated_fixtures  = false

  # Add more helper methods to be used by all tests here...
  def assert_difference(object, method = nil, difference = 1)
    initial_value = object.send(method)
    yield
    assert_equal initial_value + difference, object.send(method), "#{object}##{method}"
  end

  def assert_no_difference(object, method, &block)
    assert_difference object, method, 0, &block
  end
end

# This class sets a fixed time-point for use in both fixtures declarations and unit tests.  This avoids problems where
# tiny time differences (esp. between fixtures and unit tests) cause tests to fail because the microseconds cross a clock second
# and therefore times are considered different.
class FixedTime
  @@t = Time.now

  def self.time
    @@t
  end
end


text:
package swingman;

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
import java.awt.geom.*;

/**
 * Draws a vertical label by applying an AffineTransform on a JLabel.  Will
 * says this code was written "elsewhere".  This is part of the
 * swingman package, a swing-based replacement of
 * Brookshaw's graph package used previously.
 *
 * @version $Revision: 1.1 $, $Date: 2004/10/07 20:34:26 $.
 * @author Will Fisher and others
 * @see DataTable
 */

/*
 * $Log: VerticalLabelUI.java,v $
 * Revision 1.1  2004/10/07 20:34:26  dstotler
 * Added to repository.
 *
 *
 */

public class VerticalLabelUI extends BasicLabelUI {

	public Dimension getPreferredSize(JComponent c) {
		Dimension dim = super.getPreferredSize(c);
		return (new Dimension(dim.height, dim.width));
	}

	private static Rectangle paintIconR = new Rectangle();
	private static Rectangle paintTextR = new Rectangle();
	private static Rectangle paintViewR = new Rectangle();
	private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
    /**
     * Overrides the parent class paint method, implementing the desired
     * rotation in the process.  The component argument is needed to
     * determine sizes.
     * @param g the graphics context in which the painting is done
     * @param c the component to be repainted
     */
	public void paint(Graphics g, JComponent c) {

		JLabel label = (JLabel)c;
		String text = label.getText();

		FontMetrics fm = g.getFontMetrics();
		paintViewInsets = c.getInsets(paintViewInsets);

		paintViewR.x = paintViewInsets.left;
		paintViewR.y = paintViewInsets.top;

		//use inverted height and width
		paintViewR.height =
			c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
		paintViewR.width =
			c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);

		paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
		paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;

		String clippedText =
			layoutCL(label, fm, text, null, paintViewR, paintIconR, paintTextR);

		Graphics2D g2 = (Graphics2D)g;
		AffineTransform tr = g2.getTransform();

		//rotate
		g2.rotate(- (Math.PI / 2));
		g2.translate(- (c.getHeight()), 0);

		if (text != null) {
			int textX = paintTextR.x;
			int textY = paintTextR.y + fm.getAscent();

			if (label.isEnabled()) {
				paintEnabledText(label, g, clippedText, textX, textY);
			} else {
				paintDisabledText(label, g, clippedText, textX, textY);
			}
		}

		g2.setTransform(tr);
	}
}


text:
import { URI } from 'vs/base/common/uri';
import * as path from 'path';
import * as fs from 'fs';
import { IChannel, IServerChannel } from 'vs/base/parts/ipc/node/ipc';
import { Event, Emitter } from 'vs/base/common/event';
import { IDownloadService } from 'vs/platform/download/common/download';
import { mkdirp } from 'vs/base/node/pfs';
import { IURITransformer } from 'vs/base/common/uriIpc';

export type UploadResponse = Buffer | string | undefined;

export function upload(uri: URI): Event<UploadResponse> {
	const stream = new Emitter<UploadResponse>();
	const readstream = fs.createReadStream(uri.fsPath);
	readstream.on('data', data => stream.fire(data));
	readstream.on('error', error => stream.fire(error.toString()));
	readstream.on('close', () => stream.fire());
	return stream.event;
}

export class DownloadServiceChannel implements IServerChannel {

	constructor() { }

	listen(_, event: string, arg?: any): Event<any> {
		switch (event) {
			case 'upload': return Event.buffer(upload(URI.revive(arg)));
		}

		throw new Error(`Event not found: ${event}`);
	}

	call(_, command: string): Promise<any> {
		throw new Error(`Call not found: ${command}`);
	}
}

export class DownloadServiceChannelClient implements IDownloadService {

	_serviceBrand: any;

	constructor(private channel: IChannel, private getUriTransformer: () => IURITransformer) { }

	download(from: URI, to: string): Promise<void> {
		from = this.getUriTransformer().transformOutgoing(from);
		const dirName = path.dirname(to);
		let out: fs.WriteStream;
		return new Promise((c, e) => {
			return mkdirp(dirName)
				.then(() => {
					out = fs.createWriteStream(to);
					out.once('close', () => c());
					out.once('error', e);
					const uploadStream = this.channel.listen<UploadResponse>('upload', from);
					const disposable = uploadStream(result => {
						if (result === void 0) {
							disposable.dispose();
							out.end(c);
						} else if (Buffer.isBuffer(result)) {
							out.write(result);
						} else if (typeof result === 'string') {
							disposable.dispose();
							out.end(() => e(result));
						}
					});
				});
		});
	}
}


text:
declare var foo
declare var foo;
declare function foo(): void
declare function foo(): void;
declare function foo<T>(): void;
declare function foo(x: number, y: string): void;
declare class A {}
declare class A<T> extends B<T> { x: number }
declare class A { static foo(): number; static x : string }
declare class A { set fooProp(value: number): void; get fooProp():number }
declare class A { static [ indexer: number]: string }
declare class A { static () : number }
declare class B { (): number }
declare class A mixins B<T>, C {}
declare type A1 = string
declare type T<U> = { [k:string]: U }
declare type B1 = {
  fn?: (foo: string) => void,
}
declare interface I1 { foo: string }
declare interface I2<T> { foo: T }
declare module.exports: { foo: string }
declare opaque type Foo<T>: Bar<T>;
declare opaque type ID;
declare opaque type num: number;
declare opaque type NumArray;
declare var sym: symbol;


text:
<?php
declare(strict_types=1);

// @link http://schemas.triniti.io/json-schema/triniti/canvas/mixin/gallery-block/1-0-2.json#
namespace Triniti\Schemas\Canvas\Mixin\GalleryBlock;

use Gdbots\Pbj\Schema;

/**
 * @method static Schema schema
 * @method mixed fget($fieldName, $default = null)
 */
trait GalleryBlockV1Mixin
{
    public function getUriTemplateVars(): array
    {
        return [
            'etag' => $this->fget('etag'),
            'node_ref' => $this->fget('node_ref'),
        ];
    }
}


text:
// This file is part of Indico.
// Copyright (C) 2002 - 2021 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.

/**
 * Curries the method with the args.
 * @param {Function} method
 * @param {Object} ... args
 * @return {Function}
 */
function curry(method) {
  var args = $A(arguments, 1);
  return function() {
    return method.apply(this, concat(args, arguments));
  };
}

/**
 * Returns a template that invokes an input value on the object with the arguments.
 * @param {Object} self
 * @param {Array} [args]
 * @return {Function} template
 */
function invoker(object, args) {
  args = any(args, []);
  return function Invoke(func) {
    return (arguments.callee.result = func.apply(object, args));
  };
}

/**
 * Creates a sequential invoker from the functions.
 * @param {Function} ... functions
 * @return {Function} sequence
 */
function sequence() {
  var functions = compact(arguments);
  return function Sequence() {
    iterate(functions, invoker(this, $A(arguments)));
  };
}

/**
 * Returns a multi-function with attachable methods.
 * @return {Function} commands
 */
function commands() {
  var methods = new Bag();
  return mixinInstance(
    function() {
      return methods.each(invoker(this, $A(arguments)));
    },
    methods,
    Attachable
  );
}

/**
 * Creates a command from the method and the caption.
 * @param {Function} method
 * @param {String} caption
 * @return {Function} command
 */
function command(method, caption) {
  function Command() {
    return method.apply(this, $A(arguments));
  }
  Command.caption = caption;
  return Command;
}

/**
 * Invokes the method with the arguments if it exists.
 * @param {Function} command
 */
function invoke(method) {
  if (exists(method)) {
    return method.apply(this, $A(arguments, 1));
  }
}

/**
 * Delays execution of the method for the timeout and returns a function to cancel the delayed execution.
 * @param {Function} method
 * @param {Number} timeout
 * @return {Function} cancel
 */
function delay(method, timeout) {
  var id = setTimeout(method, timeout);
  return function() {
    clearTimeout(id);
  };
}

/**
 * Defers execution of the method and returns a function to cancel the deferred execution.
 * @param {Function} method
 * @return {Function} cancel
 */
function defer(method) {
  return delay(method, 1);
}

/**
 * Schedule execution of the method and returns a function to cancel the scheduled execution.
 * @param {Function} method
 * @return {Function} cancel
 */
function schedule(method) {
  if (exists(method.scheduled)) {
    return method.scheduled;
  } else {
    method.scheduled = defer(function() {
      delete method.scheduled;
      method();
    });
    return method.scheduled;
  }
}

function delayedBind(target, key, builder) {
  target[key] = function() {
    var args = $A(arguments);
    var method = builder.apply(this, args);
    target[key] = method;
    return method.apply(this, args);
  };
}


text:
/*!
*
* @file       MLIB_Abs.h
*
* @version    1.0.1.0
*
* @date       Oct-9-2013
*
* @brief      Header file for MLIB_Abs function
*
******************************************************************************/
#ifndef MLIB_ABS_H
#define MLIB_ABS_H
/*!
@if MLIB_GROUP
    @addtogroup MLIB_GROUP
@else
    @defgroup MLIB_GROUP   MLIB
@endif
*/

#ifdef __cplusplus
extern "C" {
#endif

/**
* @page misra_violations MISRA-C:2004 violations
*
* @section MLIB_Abs_h_REF_1
* Violates MISRA 2004 Required Rule 19.4, Disallowed definition for macro.
* To allow the user utilize the benefits of using all three supported implementation of each
* function in user application, the macro dispatcher inevitably requires use of disallowed macro
* definition.
*
* @section MLIB_Abs_h_REF_2
* Violates MISRA 2004 Advisory Rule 19.7, Function-like macro defined.
* To allow the user utilize the benefits of using all three supported implementation of each
* function in user application, the macro dispatcher inevitably requires the function-like macro
* definition.
*
* @section MLIB_Abs_h_REF_3
* Violates MISRA 2004 Required Rule 19.10, Unparenthesized macro parameter in definition of macro.
* To allow the user utilize the benefits of using all three supported implementation of each
* function in user application, the macro dispatcher inevitably requires use of unparenthesized
* macro parameters.
*
* @section MLIB_Abs_h_REF_4
* Violates MISRA 2004 Advisory Rule 19.13, #/##' operator used in macro.
* To allow the user utilize the benefits of using all three supported implementation of each
* function in user application, the macro dispatcher inevitably requires use of '#/##' operators.
*
* @section MLIB_Abs_h_REF_5
* Violates MISRA 2004 Required Rule 8.5, Object/function definition in header file.
* Allowing the inline functions significantly increase the speed of the library thus the lowest
* layer (MLIB) is implemented as inline. This approach removes the overhead caused by standard
* function calling.
*/
#include "SWLIBS_Defines.h"

/****************************************************************************
* Defines and macros            (scope: module-local)
****************************************************************************/
#ifndef  _MATLAB_BAM_CREATE
  /*
  * @violates @ref MLIB_Abs_h_REF_1 MISRA 2004 Required Rule 19.4, Disallowed definition for macro.
  * @violates @ref MLIB_Abs_h_REF_2 MISRA 2004 Advisory Rule 19.7, Function-like macro defined.
  * @violates @ref MLIB_Abs_h_REF_3 MISRA 2004 Required Rule 19.10, Unparenthesized macro parameter
  * in definition of macro.
  */
  #define MLIB_Abs(...)     macro_dispatcher(MLIB_Abs, __VA_ARGS__)(__VA_ARGS__)     /*!< This function returns absolute value of input parameter. */

  #if (SWLIBS_DEFAULT_IMPLEMENTATION == SWLIBS_DEFAULT_IMPLEMENTATION_F32)
    /*
    * @violates @ref MLIB_Abs_h_REF_1 MISRA 2004 Required Rule 19.4, Disallowed definition for
    * macro.
    * @violates @ref MLIB_Abs_h_REF_2 MISRA 2004 Advisory Rule 19.7, Function-like macro defined.
    * @violates @ref MLIB_Abs_h_REF_3 MISRA 2004 Required Rule 19.10, Unparenthesized macro
    * parameter in definition of macro.
    */
    /** @remarks Implements DMLIB00006 */
    #define MLIB_Abs_Dsptchr_1(In)     MLIB_Abs_Dsptchr_2(In,F32)     /*!< Function dispatcher for MLIB_Abs_Dsptchr_1, do not modify!!! */
  #endif
  #if (SWLIBS_DEFAULT_IMPLEMENTATION == SWLIBS_DEFAULT_IMPLEMENTATION_F16)
    /*
    * @violates @ref MLIB_Abs_h_REF_1 MISRA 2004 Required Rule 19.4, Disallowed definition for
    * macro.
    * @violates @ref MLIB_Abs_h_REF_2 MISRA 2004 Advisory Rule 19.7, Function-like macro defined.
    * @violates @ref MLIB_Abs_h_REF_3 MISRA 2004 Required Rule 19.10, Unparenthesized macro
    * parameter in definition of macro.
    */
    /** @remarks Implements DMLIB00006 */
    #define MLIB_Abs_Dsptchr_1(In)     MLIB_Abs_Dsptchr_2(In,F16)     /*!< Function dispatcher for MLIB_Abs_Dsptchr_1, do not modify!!! */
  #endif

  /*
  * @violates @ref MLIB_Abs_h_REF_1 MISRA 2004 Required Rule 19.4, Disallowed definition for macro.
  * @violates @ref MLIB_Abs_h_REF_2 MISRA 2004 Advisory Rule 19.7, Function-like macro defined.
  * @violates @ref MLIB_Abs_h_REF_3 MISRA 2004 Required Rule 19.10, Unparenthesized macro parameter
  * in definition of macro.
  */
  #define MLIB_Abs_Dsptchr_2(In,Impl)    MLIB_Abs_Dsptchr_(In,Impl)     /*!< Function dispatcher for MLIB_Abs_Dsptchr_2, do not modify!!! */

  /*
  * @violates @ref MLIB_Abs_h_REF_1 MISRA 2004 Required Rule 19.4, Disallowed definition for macro.
  * @violates @ref MLIB_Abs_h_REF_2 MISRA 2004 Advisory Rule 19.7, Function-like macro defined.
  * @violates @ref MLIB_Abs_h_REF_4 MISRA 2004 Advisory Rule 19.13, #/##' operator used in macro.
  */
  /** @remarks Implements DMLIB00008 */
  #define MLIB_Abs_Dsptchr_(In,Impl)     MLIB_Abs_##Impl(In)            /*!< Function dispatcher for MLIB_Abs_Dsptchr_, do not modify!!! */
#endif

/****************************************************************************
* Typedefs and structures       (scope: module-local)
****************************************************************************/

/****************************************************************************
* Exported function prototypes
****************************************************************************/

/****************************************************************************
* Inline functions
****************************************************************************/

/****************************************************************************
* Implementation variant: 32-bit fractional
****************************************************************************/
/***************************************************************************/
/*!
@ingroup    MLIB_GROUP

@brief        This function returns absolute value of input parameter.

@param[in]    f32In      Input value.

@return       Absolute value of input parameter.

@details      This inline function returns the absolute value of input parameter. The input value as well as output value
              is considered as 32-bit fractional data type. The output saturation is not implemented in this function,
              thus in case the absolute value of input parameter is outside the (-1, 1) interval, the output value will
              overflow without any detection.

              \par

              The output of the function is defined by the following simple equation:
              \anchor eq1_Abs_F32
              \image rtf absEq1_f32.math "MLIB_Abs_Eq1"

@note         Due to effectivity reason this function is implemented as inline and thus is not ANSI-C compliant.

@par Re-entrancy
              The function is re-entrant.

@par Code Example
\code
#include "mlib.h"

Frac32 f32In;
Frac32 f32Out;

void main(void)
{
    // input value = -0.25
    f32In = FRAC32(-0.25);

    // output should be FRAC32(0.25)
    f32Out = MLIB_Abs_F32(f32In);

    // output should be FRAC32(0.25)
    f32Out = MLIB_Abs(f32In, F32);

    // ##############################################################
    // Available only if 32-bit fractional implementation selected
    // as default
    // ##############################################################

    // output should be FRAC32(0.25)
    f32Out = MLIB_Abs(f32In);
}
\endcode
****************************************************************************/
/** @remarks Implements DMLIB00007, DMLIB00000, DMLIB00003, DMLIB00005 */
static inline Frac32 MLIB_Abs_F32(register Frac32 f32In)
/*
* @violates @ref MLIB_Abs_h_REF_5 MISRA 2004 Required Rule 8.5, Object/function definition in header
* file.
*/
{
  /** @remarks Implements DMLIB00004 */
  return((f32In < (Frac32)0) ? (-f32In) : (f32In));
}

/****************************************************************************
* Implementation variant: 16-bit fractional
****************************************************************************/
/***************************************************************************/
/*!
@ingroup    MLIB_GROUP

@brief        This function returns absolute value of input parameter.

@param[in]    f16In      Input value.

@return       Absolute value of input parameter.

@details      This inline function returns the absolute value of input parameter. The input value as well as output value
              is considered as 16-bit fractional data type. The output saturation is not implemented in this function,
              thus in case the absolute value of input parameter is outside the (-1, 1) interval, the output value will
              overflow without any detection.

              \par

              The output of the function is defined by the following simple equation:
              \anchor eq1_Abs_F16
              \image rtf absEq1_f16.math "MLIB_Abs_Eq1"

@note         Due to effectivity reason this function is implemented as inline and thus is not ANSI-C compliant.

@par Re-entrancy
              The function is re-entrant.

@par Code Example
\code
#include "mlib.h"

Frac16 f16In;
Frac16 f16Out;

void main(void)
{
    // input value = -0.25
    f16In = FRAC16(-0.25);

    // output should be FRAC16(0.25)
    f16Out = MLIB_Abs_F16(f16In);

    // output should be FRAC16(0.25)
    f16Out = MLIB_Abs(f16In, F16);

    // ##############################################################
    // Available only if 16-bit fractional implementation selected
    // as default
    // ##############################################################

    // output should be FRAC16(0.25)
    f16Out = MLIB_Abs(f16In);
}
\endcode
****************************************************************************/
/** @remarks Implements DMLIB00007, DMLIB00000, DMLIB00002, DMLIB00005 */
static inline Frac16 MLIB_Abs_F16(register Frac16 f16In)
/*
* @violates @ref MLIB_Abs_h_REF_5 MISRA 2004 Required Rule 8.5, Object/function definition in header
* file.
*/
{
  /** @remarks Implements DMLIB00004 */
  return((f16In < (Frac16)0) ? (-f16In) : (f16In));
}

#ifdef __cplusplus
}
#endif

#endif /* MLIB_ABS_H */


text:
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/metric/cli'
#require 'pg'
require 'socket'

class PostgresStatsTableMetrics < Sensu::Plugin::Metric::CLI::Graphite

  option :user,
         :description => "Postgres User",
         :short       => '-u USER',
         :long        => '--user USER'

  option :password,
         :description => "Postgres Password",
         :short       => '-p PASS',
         :long        => '--password PASS'

  option :hostname,
         :description => "Hostname to login to",
         :short       => '-h HOST',
         :long        => '--hostname HOST',
         :default     => 'localhost'

  option :port,
         :description => "Database port",
         :short       => '-P PORT',
         :long        => '--port PORT',
         :default     => 5432

  option :db,
         :description => "Database name",
         :short       => '-d DB',
         :long        => '--db DB',
         :default     => 'postgres'

  option :scope,
         :description => "Scope, see http://www.postgresql.org/docs/9.2/static/monitoring-stats.html",
         :short       => '-s SCOPE',
         :long        => '--scope SCOPE',
         :default     => 'user'

  option :scheme,
         :description => "Metric naming scheme, text to prepend to $queue_name.$metric",
         :long        => "--scheme SCHEME",
         :default     => "#{Socket.gethostname}.postgresql"

  def run
    timestamp = Time.now.to_i

    auth = "PGPASSWORD=#{ config[:password] }"
    flags = "-h #{ config[:hostname] } -p #{ config[:port] } -d #{ config[:db] } -U #{ config[:user] } -t -c"
    con = "#{ auth } psql #{ flags }"

    request = [
        "select sum(seq_scan) as seq_scan, sum(seq_tup_read) as seq_tup_read,",
        "sum(idx_scan) as idx_scan, sum(idx_tup_fetch) as idx_tup_fetch,",
        "sum(n_tup_ins) as n_tup_ins, sum(n_tup_upd) as n_tup_upd, sum(n_tup_del) as n_tup_del,",
        "sum(n_tup_hot_upd) as n_tup_hot_upd, sum(n_live_tup) as n_live_tup, sum(n_dead_tup) as n_dead_tup",
        "from pg_stat_user_tables"
    ]

    res = `#{ con } "#{ request.join(' ') };"`

    res.split("\n").each do |row|
      next if row.empty?

      data_arr = row.split("|")

      output "#{config[:scheme]}.statstable.#{config[:db]}.seq_scan", data_arr[0].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.seq_tup_read", data_arr[1].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.idx_scan", data_arr[2].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.idx_tup_fetch", data_arr[3].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.n_tup_ins", data_arr[4].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.n_tup_upd", data_arr[5].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.n_tup_del", data_arr[6].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.n_tup_hot_upd", data_arr[7].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.n_live_tup", data_arr[8].strip, timestamp
      output "#{config[:scheme]}.statstable.#{config[:db]}.n_dead_tup", data_arr[9].strip, timestamp
    end

    ok

  end

end


text:
"""Create / interact with Google Cloud RuntimeConfig connections."""

from google.cloud import _http

from google.cloud.runtimeconfig import __version__

_CLIENT_INFO = _http.CLIENT_INFO_TEMPLATE.format(__version__)

class Connection(_http.JSONConnection):
    """A connection to Google Cloud RuntimeConfig via the JSON REST API.

    :type client: :class:`~google.cloud.runtimeconfig.client.Client`
    :param client: The client that owns the current connection.
    """

    API_BASE_URL = "https://runtimeconfig.googleapis.com"
    """The base of the API call URL."""

    API_VERSION = "v1beta1"
    """The version of the API, used in building the API call's URL."""

    API_URL_TEMPLATE = "{api_base_url}/{api_version}{path}"
    """A template for the URL of a particular API call."""

    _EXTRA_HEADERS = {_http.CLIENT_INFO_HEADER: _CLIENT_INFO}


text:
namespace Sitecore.Foundation.SitecoreExtensions.Repositories
{
  public interface IRenderingPropertiesRepository
  {
    T Get<T>();
  }
}


text:
package com.linkedin.pinot.core.plan;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linkedin.pinot.common.request.AggregationInfo;
import com.linkedin.pinot.core.common.Operator;
import com.linkedin.pinot.core.operator.MProjectionOperator;
import com.linkedin.pinot.core.operator.UReplicatedProjectionOperator;
import com.linkedin.pinot.core.operator.query.BAggregationFunctionOperator;

/**
 * AggregationFunctionPlanNode takes care of how to apply one aggregation
 * function for given data sources.
 */
public class AggregationFunctionPlanNode implements PlanNode {
  private static final Logger LOGGER = LoggerFactory.getLogger("QueryPlanLog");
  private final AggregationInfo _aggregationInfo;
  private final ProjectionPlanNode _projectionPlanNode;
  private final boolean _hasDictionary;

  public AggregationFunctionPlanNode(AggregationInfo aggregationInfo, ProjectionPlanNode projectionPlanNode, boolean hasDictionary) {
    _aggregationInfo = aggregationInfo;
    _projectionPlanNode = projectionPlanNode;
    _hasDictionary = hasDictionary;
  }

  @Override
  public Operator run() {
    return new BAggregationFunctionOperator(_aggregationInfo, new UReplicatedProjectionOperator(
        (MProjectionOperator) _projectionPlanNode.run()), _hasDictionary);
  }

  @Override
  public void showTree(String prefix) {
    LOGGER.debug(prefix + "Operator: BAggregationFunctionOperator");
    LOGGER.debug(prefix + "Argument 0: Aggregation  - " + _aggregationInfo);
    LOGGER.debug(prefix + "Argument 1: Projection - Shown Above");
  }

}


text:
import * as types from '../constants/ActionTypes'
import fetch from 'isomorphic-fetch'

export function setClient(client) {
  return (dispatch) => (
     dispatch({
      'type': types.SET_CLIENT,
      client,
    })
  )
}

export function toggleSidebar(sideOpen) {
  return (dispatch) => (
    dispatch({
      'type': types.TOGGLE_SIDEBAR,
      sideOpen,
    })
  )
}

export function fetchFireSuccess(json) {
  return {
    'type': types.FETCH_FIRE_SUCCESS,
    'fire': json,
  }
}

export function fetchFire() {
  const API = process.env.API || 'http://localhost:3000/api'

  return (dispatch) => (
    fetch(`${API}/getDB`)
      .then((response) => response.json())
      .then((json) => dispatch(fetchFireSuccess(json)))
      .catch((error) => console.log(error))
  )
}


text:
<!DOCTYPE html>

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

    <title>Restful Objects</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/simple-sidebar.css" rel="stylesheet">

                        Restful Objects

                    Download

                    Implementations

                    Feedback

                    License

The Restful Objects specification defines a set of RESTful resources, and corresponding JSON representations, for accessing and manipulating a domain object model. The current version of the spec is v1.0.0.

The spec defines a uniform interface to the domain objects. This uniformity is expressed in terms of the format of URLs, use of standard HTTP methods, standard and custom HTTP headers, standard HTTP return codes, use of JSON representations, the concept of a representation type to allow the dynamic handling by clients, standard attributes within JSON representations, and standard representation of links between representations.

The Restful Objects spec is at a higher-level of abstraction than, say, the JAX-RS specifications for Java platform, or the WCF specifications on .NET. Specifically, the domain objects that it exposes as resources are thought of in similar terms to UML, in that they consist of properties (holding either a scalar value or reference), collections (holding a vector of references), and actions (whereby the object can execute business logic).

Restful Objects is agnostic as to the nature of the server-side state that it exposes, in that it may be used either to expose domain entities (Customer, Order, Product) or may be used to expose use cases/commands (CheckIntoFlight, CancelOrder).

Finally, the spec is designed to support clients that use HATEOAS (hypertext as the engine of application state) with opaque URI values, and also those that prefer to use templated URIs.

                        Toggle Menu


text:
std::vector<Xml::Node *>
Xsl::ForEach::operator () (Xml::Element const * context,
    Xml::Document const & xslDoc, Xml::Element const * forEachElement, Xml::Log & xslLog) const
{
    app_assert(context != nullptr);
    app_assert(forEachElement != nullptr);

    std::vector<Xml::Node *> resultNodes;

    auto matchingNodes = context->select(forEachElement->attribute("select"));
   // std::cerr << "====>" << matchingNodes.size() << std::endl;
    for (auto node : matchingNodes)
    {
        app_assert(node != nullptr);

        auto returnedNodes = Xsl::applyTemplate(node, xslDoc, forEachElement, xslLog);

        resultNodes.reserve(resultNodes.size() + returnedNodes.size());

        for (auto resultNode : returnedNodes)
        {
            app_assert(resultNode != nullptr);

            resultNodes.push_back(resultNode);
        }
    }

    return resultNodes;
}


text:
"""
    Name: mobile_bt.py
    Author: Francis T
    Description:
        Source code for the Mobile Node Bluetooth link controller
"""
from bluetooth import *
import json

class MobileNode():
    def __init__(self):
        self.server_sock = BluetoothSocket(RFCOMM)
        self.client_sock = None
        self.connected = False
        return

    def init_socket(self, timeout=180.0):
        # Bind socket to a port and listen
        self.server_sock.bind(("", PORT_ANY))

        # Configure the socket to listening mode
        self.server_sock.listen(1)

        # Configure timeout for incoming connections (default: 180 secs)
        self.server_sock.settimeout(timeout)
        return True

    def is_connected(self):
        return self.connected

    def listen(self):
        try:
            self.client_sock, client_info = self.server_sock.accept()
        except BluetoothError:
            return False

        if client_info == None:
            return False

        print("Connection accepted from " + str(client_info))
        self.connected = True
        return True

    def receive_data(self):
        if self.connected == False:
            print("Not connected")
            return False

        if self.client_sock == None:
            print("No clients to receive data from")
            return None

        try:
            data = self.client_sock.recv(2056)
        except BluetoothError:
            self.connected = False
            return None

        if data == None:
            return None

        print("Data received [%s]" % data)

        return data

    def send_response(self, resp_data):
        if self.connected == False:
            print("Not connected")
            return False

        if self.client_sock == None:
            print("No clients to respond to")
            return False

        print("Sending response...")
        try:
            self.client_sock.send(resp_data)
        except BluetoothError as e:
            print("Send failed: {}".format(str(e)))
            self.connected = False
            return False

        print("RESPONSE [%s]" % resp_data)

        return True

    def disconnect(self):
        if self.client_sock == None:
            print("No clients to disconnect from")
            return False

        self.client_sock.close()
        self.connected = False
        return True

    def destroy(self):
        self.server_sock.close()
        self.connected = False
        return


text:
Parse Error: Line 1: Illegal import declaration
for file E:\src\music-fest-schedule\app\routes\Schedule\Index.jsx


text:
package net.jitse.apollo.utilities;

import net.md_5.bungee.api.ChatColor;

/**
 * @auhor Jitse B.
 * @since 10.24.2017
 */
public class Chat {

    public static String format(String input) {
        return ChatColor.translateAlternateColorCodes('&', input);
    }
}


text:
var crypto = require('crypto');
var fs = require('fs');
var http = require('http');
var path = require('path');
var async = require('async');

var saveState = {};
var webroot, port;

var startPlayingWhenOneBigGroup;

// for say
var groupToRejoin;

function playfile(player, values, callback) {

  // Create backup preset to restore this player
  var state = player.getState();

  var filename = values[0],
      volume = values[1] || state.volume;

  var backupPreset = {
      "players": [
          {"roomName": player.roomName, "volume": state.volume}
      ],
      "state": state.playerState,
      "uri": player.avTransportUri,
      'trackNo': state.trackNo,
      'elapsedTime': state.elapsedTime
  }

  if (player.coordinator.uuid == player.uuid) {
    // This one is coordinator, you will need to rejoin
    // remember which group you were part of.
    groupToRejoin = getGroupByCoordinator(player.discovery.zones, player.coordinator);
  }

  console.log("playing " + filename + " at volume " + volume );

  // Use the preset action to play the tts file
  var ttsPreset = {
      "players": [
          {"roomName": player.roomName, "volume": volume}
      ],
      "state": "playing",
      "playMode": "NORMAL"
  }

  player.on('transport-state', transportStateClosure(player, [backupPreset]));

  playLocalFile(ttsPreset, filename, player.discovery);

  callback();
}

function getGroupByCoordinator(zones, coordinator) {
  for (var i = 0; i < zones.length; i++) {
    var zone = zones[i];
    if (coordinator.uuid == zone.uuid) {
      return zone.id;
    }
  }
}

function getGroupCoordinatorByID(zones, id) {
  for (var i = 0; i < zones.length; i++) {
    var zone = zones[i];
    if (id == zone.id) {
      return zone.uuid;
    }
  }
}

function playLocalFile(preset, filename, discovery, callback) {
    var uri = "http://" + discovery.localEndpoint + ":" + port + "/sounds/" + filename;
    preset.uri = uri;
    discovery.applyPreset(preset, callback);
}

function transportStateClosure(player, backupPresets) {
  var hasStartedPlaying = false;
  return function listener(state) {

    if (player.state.currentState == "PLAYING") {
      hasStartedPlaying = true;
      return;
    }

    if (hasStartedPlaying && player.state.currentState == "STOPPED") {
      var asyncSeries = [];
      backupPresets.forEach(function (backupPreset) {
        asyncSeries.push(function (preset) {
          return function (callback) {

            if (groupToRejoin) {
             // player was broken out, need to rejoin right coordinator
              preset.uri = 'x-rincon:' + getGroupCoordinatorByID(player.discovery.zones, groupToRejoin);
            }

            player.discovery.applyPreset(preset, function (error, result) {
              callback(error, result);
            });
          };
        }(backupPreset));
      });

      async.series(asyncSeries, function (err, result) {
        if (err)
          console.error('error in async series when applying backup', err, result)
      })
      player.removeListener('transport-state', listener);
    }
  }
}

function saveAll(player) {
  var discovery = player.discovery;
  var backupPresets = [];
  discovery.getZones().forEach(function (zone) {
      var player = discovery.getPlayerByUUID(zone.uuid);
      var state = player.getState();
      var preset = {
        'players': [
            {'roomName': player.roomName, 'volume': state.volume}
        ],
        'state': player.state.currentState,
        'uri': player.avTransportUri,
        'playMode': 'NORMAL',
        'trackNo': state.trackNo,
        'elapsedTime': state.elapsedTime
      }

      zone.members.forEach(function (p) {
        if (player.uuid != p.uuid)
          preset.players.push({roomName: p.roomName, volume: p.state.volume });
      });

      backupPresets.push(preset);

  });

  return backupPresets;
}

function topologyChanged(e) {
  if (startPlayingWhenOneBigGroup && e.length == 1) {
    // is one big group now, play
    coordinator.play();
  }
}

module.exports = function (api) {
  webroot = path.resolve(__dirname + '/../../static');
  port = api.getPort();
  api.registerAction('qplay', playfile);

  // register permanent eventlistener
  api.discovery.on('topology-change', topologyChanged);
}


text:
/**
 * Webpack config.
 */

var path        = require('path');
var webpack     = require('webpack');
var assetsPath  = path.join('src', 'assets', 'js');
var modulesPath = path.join('src', 'assets', 'js', 'packages');

module.exports = {
  context: path.resolve(assetsPath),
  entry: './main.js',
  output: {
    filename: './main.min.js',
    path: path.resolve(assetsPath)
  },
  resolve: {
    extensions: ['', '.js'],
    root: path.resolve(modulesPath)
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader'
      }
    ]
  },
  plugins: [new webpack.optimize.UglifyJsPlugin({ output: {comments: false} })]
};


text:
import requests
import re
from bs4 import BeautifulSoup

def get_soup(url):
    """
    @param: url of site to be scraped
    """
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')

    print "type: ", type(soup)
    return soup

get_soup("http://abc.net.au/radionational/podcasts")

def get_playable_podcast(soup):
    """
    @param: parsed html page
    """
    subjects = []

    for content in soup.find_all('div', class_= "cs-teaser"):

        try:
            link = content.find('a', {'class': 'ico ico-download'})
            link = link.get('href')
            print "\n\nLink: ", link

            title = content.find('h3', {'class': 'title'})
            title = title.get_text()

            desc = content.find('div', {'class': 'summary'})
            desc = desc.get_text()

            thumbnail = content.find('img')
            thumbnail = thumbnail.get('src')
        except AttributeError:
            continue

        item = {
                'url': link,
                'title': title,
                'desc': desc,
                'thumbnail': thumbnail
        }

        #needto check that item is not null here
        subjects.append(item)

    return subjects

def get_podcast_heading(soup):
    """
    @para: parsed html page
    """
    subjects = []

    for content in soup.find_all('div', class_= 'header'):

        link = content.find('a')
        link = link.get('href')
        link = "http://abc.net.au" + link

        title = content.find('h3')
        title = title.get_text()

        item = {
                'url': link,
                'title': title
        }

        subjects.append(item)

    return subjects

def compile_playable_podcast(playable_podcast):
    """
    @para: list containing dict of key/values pairs for playable podcasts
    """
    items = []

    for podcast in playable_podcast:
        items.append({
            'label': podcast['title'],
            'thumbnail': podcast['thumbnail'],
            'path': podcast['url'],
            'info': podcast['desc'],
            'is_playable': True,
    })

    return items


text:
package org.apache.drill.exec.store.mock;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.exec.exception.OutOfMemoryException;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.expr.TypeHelper;
import org.apache.drill.exec.ops.OperatorContext;
import org.apache.drill.exec.physical.impl.OutputMutator;
import org.apache.drill.exec.physical.impl.ScanBatch;
import org.apache.drill.exec.record.MaterializedField;
import org.apache.drill.exec.store.AbstractRecordReader;
import org.apache.drill.exec.store.mock.MockTableDef.MockColumn;
import org.apache.drill.exec.store.mock.MockTableDef.MockScanEntry;
import org.apache.drill.exec.vector.AllocationHelper;
import org.apache.drill.exec.vector.ValueVector;

/**
 * Extended form of the mock record reader that uses generator class
 * instances to create the mock values. This is a work in progress.
 * Generators exist for a few simple required types. One also exists
 * to generate strings that contain dates.
 * <p>
 * The definition is provided inside the sub scan used to create the
 * {@link ScanBatch} used to create this record reader.
 */

public class ExtendedMockRecordReader extends AbstractRecordReader {

  private ValueVector[] valueVectors;
  private int batchRecordCount;
  private int recordsRead;

  private final MockScanEntry config;
  private final ColumnDef fields[];

  public ExtendedMockRecordReader(MockScanEntry config) {
    this.config = config;

    fields = buildColumnDefs();
  }

  private ColumnDef[] buildColumnDefs() {
    List<ColumnDef> defs = new ArrayList<>();

    // Look for duplicate names. Bad things happen when the same name
    // appears twice. We must do this here because some tests create
    // a physical plan directly, meaning that this is the first
    // opportunity to review the column definitions.

    Set<String> names = new HashSet<>();
    MockColumn cols[] = config.getTypes();
    for (int i = 0; i < cols.length; i++) {
      MockTableDef.MockColumn col = cols[i];
      if (names.contains(col.name)) {
        throw new IllegalArgumentException("Duplicate column name: " + col.name);
      }
      names.add(col.name);
      int repeat = Math.min(1, col.getRepeatCount());
      if (repeat == 1) {
        defs.add(new ColumnDef(col));
      } else {
        for (int j = 0; j < repeat; j++) {
          defs.add(new ColumnDef(col, j+1));
        }
      }
    }
    ColumnDef[] defArray = new ColumnDef[defs.size()];
    defs.toArray(defArray);
    return defArray;
  }

  private int getEstimatedRecordSize() {
    int size = 0;
    for (int i = 0; i < fields.length; i++) {
      size += fields[i].width;
    }
    return size;
  }

  @Override
  public void setup(OperatorContext context, OutputMutator output) throws ExecutionSetupException {
    try {
      final int estimateRowSize = getEstimatedRecordSize();
      valueVectors = new ValueVector[fields.length];
      int batchSize = config.getBatchSize();
      if (batchSize == 0) {
        batchSize = 10 * 1024 * 1024;
      }
      batchRecordCount = Math.max(1, batchSize / estimateRowSize);
      batchRecordCount = Math.min(batchRecordCount, Character.MAX_VALUE);

      for (int i = 0; i < fields.length; i++) {
        final ColumnDef col = fields[i];
        final MajorType type = col.getConfig().getMajorType();
        final MaterializedField field = MaterializedField.create(col.getName(), type);
        final Class<? extends ValueVector> vvClass = TypeHelper.getValueVectorClass(field.getType().getMinorType(), field.getDataMode());
        valueVectors[i] = output.addField(field, vvClass);
      }
    } catch (SchemaChangeException e) {
      throw new ExecutionSetupException("Failure while setting up fields", e);
    }
  }

  @Override
  public int next() {
    if (recordsRead >= this.config.getRecords()) {
      return 0;
    }

    final int recordSetSize = Math.min(batchRecordCount, this.config.getRecords() - recordsRead);
    recordsRead += recordSetSize;
    for (int i = 0; i < recordSetSize; i++) {
      int j = 0;
      for (final ValueVector v : valueVectors) {
        fields[j++].generator.setValue(v, i);
      }
    }

    return recordSetSize;
  }

  @Override
  public void allocate(Map<String, ValueVector> vectorMap) throws OutOfMemoryException {
    try {
      for (final ValueVector v : vectorMap.values()) {
        AllocationHelper.allocate(v, Character.MAX_VALUE, 50, 10);
      }
    } catch (NullPointerException e) {
      throw new OutOfMemoryException();
    }
  }

  @Override
  public void close() { }
}


text:
class MainWindow:public Tempest::Window {
  public:
    MainWindow( Tempest::AbstractAPI& api );

  protected:
    Tempest::Device               device;
    Tempest::TextureHolder        texHolder;
    Tempest::VertexBufferHolder   vboHolder;
    Tempest::IndexBufferHolder    iboHolder;

    Tempest::ShaderProgramHolder  shHolder;

    Tempest::Texture2d             texture;

    Tempest::SpritesHolder         spHolder;
    Tempest::SurfaceRender         uiRender;

    void paintEvent( Tempest::PaintEvent& e );

    void render();
    void resizeEvent( Tempest::SizeEvent& e );
  };

#endif // MAINWINDOW_H


text:
var socket = io();

  var flip=true;

function tap(data) {
  var x = document.getElementById('recording');
  var w = data<2000 ? (data/2000 * 100) : 100;
  setwidth(w);
  if (flip==true) {
      x.style.backgroundColor = '#f9f9f9';
      flip=false;
  } else {
      x.style.backgroundColor = '#ffffff';
      flip=true;
  }
}
function setwidth(val) {
  console.log(val);
  var vu = document.getElementById('vu');;
  vu.style.width = val + "%";
}

socket.on('tap', function(data) {
  tap(data);
});

window.addEventListener("load", function(){
  var startButton = document.getElementById('start');
  var stopButton = document.getElementById('stop');
  if (stopButton) { stopButton.disabled = true; }
  var createLink = document.getElementById('toggle');

  var recording = document.getElementById('recording')
  if (recording) {recording.style.display = 'none';}

  var createpanel = document.getElementById('createpanel');
  if (createpanel) {createpanel.style.display = 'none';}
  var testButton = document.getElementById('test');

  if (testButton) {
    testButton.addEventListener('click', function() {
      socket.emit("tap","tap");
    });
  }
  if (startButton) {
    startButton.addEventListener('click', function() {
      //data can be an object by doing this:
      var RecObj = {};
      RecObj.name = document.getElementById('name').value;
      RecObj.desc = document.getElementById('desc').value;
      if (RecObj.name=="") {
        alert ("Please name your recording, and try again")
      } else {
        socket.emit("start",RecObj);
        startButton.disabled = true;
        stopButton.disabled = false;
        document.getElementById('recording').style.display = 'block';
      }
      //socket.emit("command",{variable,variable});
    });
  }

  if (stopButton) {
    stopButton.addEventListener('click', function() {
      socket.emit("stop","stop");
      startButton.disabled = false;
      stopButton.disabled = true;
      location.reload();
    });
  }

  if (createLink) {
    createLink.addEventListener('click', function() {
      var x = document.getElementById('createpanel');
      if (x.style.display === 'none') {
          x.style.display = 'block';
      } else {
          x.style.display = 'none';
      }
    });
  }

});


text:
"""Models relating to the per-exploration file system."""

__author__ = 'Sean Lip'

import os

import core.storage.base_model.gae_models as base_models
import feconf
import utils

from google.appengine.ext import ndb

class FileMetadataSnapshotMetadataModel(base_models.BaseSnapshotMetadataModel):
    """Class for storing the file metadata snapshot commit history."""
    pass

class FileMetadataSnapshotContentModel(base_models.BaseSnapshotContentModel):
    """Class for storing the content of the file metadata snapshots."""
    pass

class FileMetadataModel(base_models.VersionedModel):
    """File metadata model, keyed by exploration id and absolute file name."""
    SNAPSHOT_METADATA_CLASS = FileMetadataSnapshotMetadataModel
    SNAPSHOT_CONTENT_CLASS = FileMetadataSnapshotContentModel

    # The size of the file.
    size = ndb.IntegerProperty(indexed=False)

    def get_new_id(cls, entity_name):
        raise NotImplementedError

    @classmethod
    def get_undeleted(cls):
        return cls.get_all().filter(cls.deleted == False).fetch(
            feconf.DEFAULT_QUERY_LIMIT)

    @classmethod
    def _construct_id(cls, exploration_id, filepath):
        return utils.vfs_construct_path('/', exploration_id, filepath)

    @classmethod
    def create(cls, exploration_id, filepath):
        model_id = cls._construct_id(exploration_id, filepath)
        return cls(id=model_id, deleted=False)

    @classmethod
    def get_model(cls, exploration_id, filepath, strict=False):
        model_id = cls._construct_id(exploration_id, filepath)
        return super(FileMetadataModel, cls).get(model_id, strict=strict)

    @classmethod
    def get_version(cls, exploration_id, filepath, version_number):
        model_id = cls._construct_id(exploration_id, filepath)
        return super(FileMetadataModel, cls).get_version(
            model_id, version_number)

    def commit(self, committer_id, commit_cmds):
        return super(FileMetadataModel, self).commit(
            committer_id, '', commit_cmds)

class FileSnapshotMetadataModel(base_models.BaseSnapshotMetadataModel):
    """Class for storing the file snapshot commit history."""
    pass

class FileSnapshotContentModel(base_models.BaseSnapshotContentModel):
    """Class for storing the content of the file snapshots."""

    # Overwrite the superclass member to use a BlobProperty for raw strings.
    content = ndb.BlobProperty(indexed=False)

class FileModel(base_models.VersionedModel):
    """File data model, keyed by exploration id and absolute file name."""
    SNAPSHOT_METADATA_CLASS = FileSnapshotMetadataModel
    SNAPSHOT_CONTENT_CLASS = FileSnapshotContentModel

    # The contents of the file.
    content = ndb.BlobProperty(indexed=False)

    def _reconstitute(self, snapshot_blob):
        """Manually overwrite the superclass method."""
        self.content = snapshot_blob
        return self

    def _compute_snapshot(self):
        """Manually overwrite the superclass method."""
        return self.content

    def get_new_id(cls, entity_name):
        raise NotImplementedError

    @classmethod
    def _construct_id(cls, exploration_id, filepath):
        return utils.vfs_construct_path('/', exploration_id, filepath)

    @classmethod
    def create(cls, exploration_id, filepath):
        model_id = cls._construct_id(exploration_id, filepath)
        return cls(id=model_id, deleted=False)

    @classmethod
    def get_model(cls, exploration_id, filepath, strict=False):
        model_id = cls._construct_id(exploration_id, filepath)
        return super(FileModel, cls).get(model_id, strict=strict)

    def commit(self, committer_id, commit_cmds):
        return super(FileModel, self).commit(committer_id, '', commit_cmds)

    @classmethod
    def get_version(cls, exploration_id, filepath, version_number):
        model_id = cls._construct_id(exploration_id, filepath)
        return super(FileModel, cls).get_version(model_id, version_number)