text:
package org.elasticsearch.indices;

import org.apache.lucene.store.LockObtainFailedException;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.AliasAction;
import org.elasticsearch.cluster.metadata.IndexGraveyard;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.io.FileSystemUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.gateway.GatewayMetaState;
import org.elasticsearch.gateway.LocalAllocateDangledIndices;
import org.elasticsearch.gateway.MetaStateService;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardPath;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.elasticsearch.test.IndexSettingsModule;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;

public class IndicesServiceTests extends ESSingleNodeTestCase {

    public IndicesService getIndicesService() {
        return getInstanceFromNode(IndicesService.class);
    }

    public NodeEnvironment getNodeEnvironment() {
        return getInstanceFromNode(NodeEnvironment.class);
    }

    @Override
    protected boolean resetNodeAfterTest() {
        return true;
    }

    public void testCanDeleteIndexContent() throws IOException {
        final IndicesService indicesService = getIndicesService();
        IndexSettings idxSettings = IndexSettingsModule.newIndexSettings("test", Settings.builder()
                .put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
                .put(IndexMetaData.SETTING_DATA_PATH, "/foo/bar")
                .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 4))
                .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, randomIntBetween(0, 3))
                .build());
        assertFalse("shard on shared filesystem", indicesService.canDeleteIndexContents(idxSettings.getIndex(), idxSettings));

        final IndexMetaData.Builder newIndexMetaData = IndexMetaData.builder(idxSettings.getIndexMetaData());
        newIndexMetaData.state(IndexMetaData.State.CLOSE);
        idxSettings = IndexSettingsModule.newIndexSettings(newIndexMetaData.build());
        assertTrue("shard on shared filesystem, but closed, so it should be deletable",
            indicesService.canDeleteIndexContents(idxSettings.getIndex(), idxSettings));
    }

    public void testCanDeleteShardContent() {
        IndicesService indicesService = getIndicesService();
        IndexMetaData meta = IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(
                1).build();
        IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("test", meta.getSettings());
        ShardId shardId = new ShardId(meta.getIndex(), 0);
        assertFalse("no shard location", indicesService.canDeleteShardContent(shardId, indexSettings));
        IndexService test = createIndex("test");
        shardId = new ShardId(test.index(), 0);
        assertTrue(test.hasShard(0));
        assertFalse("shard is allocated", indicesService.canDeleteShardContent(shardId, test.getIndexSettings()));
        test.removeShard(0, "boom");
        assertTrue("shard is removed", indicesService.canDeleteShardContent(shardId, test.getIndexSettings()));
        ShardId notAllocated = new ShardId(test.index(), 100);
        assertFalse("shard that was never on this node should NOT be deletable",
            indicesService.canDeleteShardContent(notAllocated, test.getIndexSettings()));
    }

    public void testDeleteIndexStore() throws Exception {
        IndicesService indicesService = getIndicesService();
        IndexService test = createIndex("test");
        ClusterService clusterService = getInstanceFromNode(ClusterService.class);
        IndexMetaData firstMetaData = clusterService.state().metaData().index("test");
        assertTrue(test.hasShard(0));

        try {
            indicesService.deleteIndexStore("boom", firstMetaData, clusterService.state());
            fail();
        } catch (IllegalStateException ex) {
            // all good
        }

        GatewayMetaState gwMetaState = getInstanceFromNode(GatewayMetaState.class);
        MetaData meta = gwMetaState.loadMetaState();
        assertNotNull(meta);
        assertNotNull(meta.index("test"));
        assertAcked(client().admin().indices().prepareDelete("test"));

        meta = gwMetaState.loadMetaState();
        assertNotNull(meta);
        assertNull(meta.index("test"));

        test = createIndex("test");
        client().prepareIndex("test", "type", "1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
        client().admin().indices().prepareFlush("test").get();
        assertHitCount(client().prepareSearch("test").get(), 1);
        IndexMetaData secondMetaData = clusterService.state().metaData().index("test");
        assertAcked(client().admin().indices().prepareClose("test"));
        ShardPath path = ShardPath.loadShardPath(logger, getNodeEnvironment(), new ShardId(test.index(), 0), test.getIndexSettings());
        assertTrue(path.exists());

        try {
            indicesService.deleteIndexStore("boom", secondMetaData, clusterService.state());
            fail();
        } catch (IllegalStateException ex) {
            // all good
        }

        assertTrue(path.exists());

        // now delete the old one and make sure we resolve against the name
        try {
            indicesService.deleteIndexStore("boom", firstMetaData, clusterService.state());
            fail();
        } catch (IllegalStateException ex) {
            // all good
        }
        assertAcked(client().admin().indices().prepareOpen("test"));
        ensureGreen("test");
    }

    public void testPendingTasks() throws Exception {
        IndicesService indicesService = getIndicesService();
        IndexService test = createIndex("test");

        assertTrue(test.hasShard(0));
        ShardPath path = test.getShardOrNull(0).shardPath();
        assertTrue(test.getShardOrNull(0).routingEntry().started());
        ShardPath shardPath = ShardPath.loadShardPath(logger, getNodeEnvironment(), new ShardId(test.index(), 0), test.getIndexSettings());
        assertEquals(shardPath, path);
        try {
            indicesService.processPendingDeletes(test.index(), test.getIndexSettings(), new TimeValue(0, TimeUnit.MILLISECONDS));
            fail("can't get lock");
        } catch (LockObtainFailedException ex) {

        }
        assertTrue(path.exists());

        int numPending = 1;
        if (randomBoolean()) {
            indicesService.addPendingDelete(new ShardId(test.index(), 0), test.getIndexSettings());
        } else {
            if (randomBoolean()) {
                numPending++;
                indicesService.addPendingDelete(new ShardId(test.index(), 0), test.getIndexSettings());
            }
            indicesService.addPendingDelete(test.index(), test.getIndexSettings());
        }
        assertAcked(client().admin().indices().prepareClose("test"));
        assertTrue(path.exists());

        assertEquals(indicesService.numPendingDeletes(test.index()), numPending);
        assertTrue(indicesService.hasUncompletedPendingDeletes());

        // shard lock released... we can now delete
        indicesService.processPendingDeletes(test.index(), test.getIndexSettings(), new TimeValue(0, TimeUnit.MILLISECONDS));
        assertEquals(indicesService.numPendingDeletes(test.index()), 0);
        assertFalse(indicesService.hasUncompletedPendingDeletes());
        assertFalse(path.exists());

        if (randomBoolean()) {
            indicesService.addPendingDelete(new ShardId(test.index(), 0), test.getIndexSettings());
            indicesService.addPendingDelete(new ShardId(test.index(), 1), test.getIndexSettings());
            indicesService.addPendingDelete(new ShardId("bogus", "_na_", 1), test.getIndexSettings());
            assertEquals(indicesService.numPendingDeletes(test.index()), 2);
            assertTrue(indicesService.hasUncompletedPendingDeletes());
            // shard lock released... we can now delete
            indicesService.processPendingDeletes(test.index(), test.getIndexSettings(), new TimeValue(0, TimeUnit.MILLISECONDS));
            assertEquals(indicesService.numPendingDeletes(test.index()), 0);
            assertTrue(indicesService.hasUncompletedPendingDeletes()); // "bogus" index has not been removed
        }
        assertAcked(client().admin().indices().prepareOpen("test"));

    }

    public void testVerifyIfIndexContentDeleted() throws Exception {
        final Index index = new Index("test", UUIDs.randomBase64UUID());
        final IndicesService indicesService = getIndicesService();
        final NodeEnvironment nodeEnv = getNodeEnvironment();
        final MetaStateService metaStateService = getInstanceFromNode(MetaStateService.class);

        final ClusterService clusterService = getInstanceFromNode(ClusterService.class);
        final Settings idxSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                                                        .put(IndexMetaData.SETTING_INDEX_UUID, index.getUUID())
                                                        .build();
        final IndexMetaData indexMetaData = new IndexMetaData.Builder(index.getName())
                                                             .settings(idxSettings)
                                                             .numberOfShards(1)
                                                             .numberOfReplicas(0)
                                                             .build();
        metaStateService.writeIndex("test index being created", indexMetaData);
        final MetaData metaData = MetaData.builder(clusterService.state().metaData()).put(indexMetaData, true).build();
        final ClusterState csWithIndex = new ClusterState.Builder(clusterService.state()).metaData(metaData).build();
        try {
            indicesService.verifyIndexIsDeleted(index, csWithIndex);
            fail("Should not be able to delete index contents when the index is part of the cluster state.");
        } catch (IllegalStateException e) {
            assertThat(e.getMessage(), containsString("Cannot delete index"));
        }

        final ClusterState withoutIndex = new ClusterState.Builder(csWithIndex)
                                                          .metaData(MetaData.builder(csWithIndex.metaData()).remove(index.getName()))
                                                          .build();
        indicesService.verifyIndexIsDeleted(index, withoutIndex);
        assertFalse("index files should be deleted", FileSystemUtils.exists(nodeEnv.indexPaths(index)));
    }

    public void testDanglingIndicesWithAliasConflict() throws Exception {
        final String indexName = "test-idx1";
        final String alias = "test-alias";
        final IndicesService indicesService = getIndicesService();
        final ClusterService clusterService = getInstanceFromNode(ClusterService.class);
        final IndexService test = createIndex(indexName);

        // create the alias for the index
        AliasAction action = new AliasAction(AliasAction.Type.ADD, indexName, alias);
        IndicesAliasesRequest request = new IndicesAliasesRequest().addAliasAction(action);
        client().admin().indices().aliases(request).actionGet();
        final ClusterState originalState = clusterService.state();

        // try to import a dangling index with the same name as the alias, it should fail
        final LocalAllocateDangledIndices dangling = getInstanceFromNode(LocalAllocateDangledIndices.class);
        final Settings idxSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                                                       .put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID())
                                                       .build();
        final IndexMetaData indexMetaData = new IndexMetaData.Builder(alias)
                                                             .settings(idxSettings)
                                                             .numberOfShards(1)
                                                             .numberOfReplicas(0)
                                                             .build();
        DanglingListener listener = new DanglingListener();
        dangling.allocateDangled(Arrays.asList(indexMetaData), listener);
        listener.latch.await();
        assertThat(clusterService.state(), equalTo(originalState));

        // remove the alias
        action = new AliasAction(AliasAction.Type.REMOVE, indexName, alias);
        request = new IndicesAliasesRequest().addAliasAction(action);
        client().admin().indices().aliases(request).actionGet();

        // now try importing a dangling index with the same name as the alias, it should succeed.
        listener = new DanglingListener();
        dangling.allocateDangled(Arrays.asList(indexMetaData), listener);
        listener.latch.await();
        assertThat(clusterService.state(), not(originalState));
        assertNotNull(clusterService.state().getMetaData().index(alias));

        // cleanup
        indicesService.deleteIndex(test.index(), "finished with test");
    }

    /**
     * This test checks an edge case where, if a node had an index (lets call it A with UUID 1), then
     * deleted it (so a tombstone entry for A will exist in the cluster state), then created
     * a new index A with UUID 2, then shutdown, when the node comes back online, it will look at the
     * tombstones for deletions, and it should proceed with trying to delete A with UUID 1 and not
     * throw any errors that the index still exists in the cluster state.  This is a case of ensuring
     * that tombstones that have the same name as current valid indices don't cause confusion by
     * trying to delete an index that exists.
     * See https://github.com/elastic/elasticsearch/issues/18054
     */
    public void testIndexAndTombstoneWithSameNameOnStartup() throws Exception {
        final String indexName = "test";
        final Index index = new Index(indexName, UUIDs.randomBase64UUID());
        final IndicesService indicesService = getIndicesService();
        final Settings idxSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
                                         .put(IndexMetaData.SETTING_INDEX_UUID, index.getUUID())
                                         .build();
        final IndexMetaData indexMetaData = new IndexMetaData.Builder(index.getName())
                                                .settings(idxSettings)
                                                .numberOfShards(1)
                                                .numberOfReplicas(0)
                                                .build();
        final Index tombstonedIndex = new Index(indexName, UUIDs.randomBase64UUID());
        final IndexGraveyard graveyard = IndexGraveyard.builder().addTombstone(tombstonedIndex).build();
        final MetaData metaData = MetaData.builder().put(indexMetaData, true).indexGraveyard(graveyard).build();
        final ClusterState clusterState = new ClusterState.Builder(new ClusterName("testCluster")).metaData(metaData).build();
        // if all goes well, this won't throw an exception, otherwise, it will throw an IllegalStateException
        indicesService.verifyIndexIsDeleted(tombstonedIndex, clusterState);
    }

    private static class DanglingListener implements LocalAllocateDangledIndices.Listener {
        final CountDownLatch latch = new CountDownLatch(1);

        @Override
        public void onResponse(LocalAllocateDangledIndices.AllocateDangledResponse response) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable e) {
            latch.countDown();
        }
    }

}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('ahjo', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='agendaitem',
            name='ahjo_id',
            field=models.IntegerField(db_index=True, unique=True),
        ),
        migrations.AlterField(
            model_name='agendaitem',
            name='resolution',
            field=models.CharField(choices=[('PASSED_UNCHANGED', 'Passed as drafted'), ('PASSED_VOTED', 'Passed after a vote'), ('PASSED_REVISED', 'Passed revised by presenter'), ('PASSED_MODIFIED', 'Passed modified'), ('REJECTED', 'Rejected'), ('NOTED', 'Noted as informational'), ('RETURNED', 'Returned to preparation'), ('REMOVED', 'Removed from agenda'), ('TABLED', 'Tabled'), ('ELECTION', 'Election'), ('UNKNOWN', 'Unknown')], max_length=20, verbose_name='Resolution'),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
#ifndef PITH_SEND_INCLUDED
#define PITH_SEND_INCLUDED

#include "../pith/context.h"
#include "../pith/pattern.h"
#include "../pith/repltype.h"
#include "../pith/store.h"
#include "../pith/osdep/pipe.h"

#ifndef TCPSTREAM
#define TCPSTREAM void
#endif

#define	MIME_VER	"MIME-Version: 1.0\015\012"

#define UNKNOWN_CHARSET		"X-UNKNOWN"

#define OUR_HDRS_LIST		"X-Our-Headers"

/*
 * Redraft flags...
 */
#define	REDRAFT_NONE	0
#define	REDRAFT_PPND	0x01
#define	REDRAFT_DEL	0x02
#define	REDRAFT_HTML	0x04

/*
 * Child posting control structure
 */
typedef struct post_s {
    int		pid;		/* proc id of child doing posting */
    int		status;		/* child's exit status */
    char       *fcc;		/* fcc we may have copied */
} POST_S;

/*------------------------------
  Structures and enum used to expand the envelope structure to
  support user defined headers. PINEFIELDs are sort of used for two
  different purposes. The main use is to store information about headers
  in pine_send. There is a pf for every header. It is also used for the
  related task of parsing the customized-hdrs and role->cstm headers and
  storing information about those.
  ----*/

typedef enum {FreeText, Address, Fcc,
	      Attachment, Subject, TypeUnknown} FieldType;
typedef enum {NoMatch = 0,		/* no match for this header */
	      UseAsDef=1,		/* use only if no value set yet */
	      Combine=2,		/* combine if News, To, Cc, Bcc, else
					   replace existing value */
	      Replace=3} CustomType;	/* replace existing value */

typedef struct pine_field {
    char     *name;			/* field's literal name		    */
    FieldType type;			/* field's type			    */
    unsigned  canedit:1;		/* allow editing of this field	    */
    unsigned  writehdr:1;		/* write rfc822 header for field    */
    unsigned  localcopy:1;		/* copy to fcc or postponed	    */
    unsigned  rcptto:1;			/* send to this if type Address	    */
    unsigned  posterr:1;		/* posting error occured in field   */
    /* the next three fields are used only for customized-hdrs and friends */
    unsigned  standard:1;		/* this hdr already in pf_template  */
    CustomType cstmtype;		/* for customized-hdrs and r->cstm  */
    char     *val;			/* field's config'd value	    */
    ADDRESS **addr;			/* used if type is Address	    */
    char     *scratch;			/* scratch pointer for Address type */
    char    **text;			/* field's free text form	    */
    char     *textbuf;			/* need to free this when done	    */
    void     *extdata;			/* hook for extra data pointer	    */
    struct pine_field *next;		/* next pine field		    */
} PINEFIELD;

typedef struct {
    ENVELOPE   *env;		/* standard c-client envelope		*/
    PINEFIELD  *local;		/* this is all of the headers		*/
    PINEFIELD  *custom;		/* ptr to start of custom headers	*/
    PINEFIELD **sending_order;	/* array giving writing order of hdrs	*/
} METAENV;

/*
 * Return values for check_address()
 */
#define CA_OK	  0		/* Address is OK                           */
#define CA_EMPTY  1		/* Address is OK, but no deliverable addrs */
#define CA_BAD   -1		/* Address is bogus                        */

/*
 * call_mailer bigresult_f flags
 */
#define	CM_BR_VERBOSE	0x01
#define	CM_BR_ERROR	0x02

/*
 * call_mailer flags
 */
#define	CM_NONE		0x00
#define	CM_VERBOSE	0x01	/* request verbose mode */
#define CM_DSN_NEVER	0x02	/* request NO DSN */
#define CM_DSN_DELAY	0x04	/* DSN delay notification */
#define CM_DSN_SUCCESS	0x08	/* DSN success notification */
#define CM_DSN_FULL	0x10	/* DSN full notificiation */
#define CM_DSN_SHOW	0x20	/* show DSN result (place holder) */

#ifdef	DEBUG_PLUS
#define	TIME_STAMP(str, l)	{ \
				  struct timeval  tp; \
				  struct timezone tzp; \
				  if(gettimeofday(&tp, &tzp) == 0) \
				    dprint((l, \
					   "\nKACHUNK (%s) : %.8s.%3.3ld\n", \
					   str, ctime(&tp.tv_sec) + 11, \
					   tp.tv_usec));\
				}
#else	/* !DEBUG_PLUS */
#define	TIME_STAMP(str, l)
#endif	/* !DEBUG_PLUS */

/*
 * Most number of errors call_mailer should report
 */
#define MAX_ADDR_ERROR 2  /* Only display 2 address errors */

#define	FCC_SOURCE	CharStar

struct local_message_copy {
    STORE_S  *so;
    unsigned  text_only:1;
    unsigned  all_written:1;
    unsigned  text_written:1;
};

#define TONAME "To"
#define CCNAME "cc"
#define SUBJNAME "Subject"
#define PRIORITYNAME "X-Priority"

/*
 * Note, these are in the same order in the he_template and pf_template arrays.
 * The typedef is just a way to get these variables automatically defined in order.
 */
typedef enum {	  N_AUTHRCVD = 0
		, N_FROM
		, N_REPLYTO
		, N_TO
		, N_CC
		, N_BCC
		, N_NEWS
		, N_FCC
		, N_LCC
		, N_ATTCH
		, N_SUBJ
		, N_REF
		, N_DATE
		, N_INREPLY
		, N_MSGID
		, N_PRIORITY
		, N_USERAGENT
		, N_NOBODY
		, N_POSTERR
		, N_RPLUID
		, N_RPLMBOX
		, N_SMTP
		, N_NNTP
		, N_CURPOS
		, N_OURREPLYTO
		, N_OURHDRS
		, N_SENDER
} dummy_enum;

typedef struct {
    int   val;
    char *desc;
} PRIORITY_S;

/* ugly globals we'd like to get rid of */
extern struct local_message_copy lmc;
extern char verbose_requested;
extern unsigned char dsn_requested;
extern PRIORITY_S priorities[];
extern PINEFIELD pf_template[];

/* exported protoypes */
int         postponed_stream(MAILSTREAM **, char *, char *, int);
int	    redraft_work(MAILSTREAM **, long, ENVELOPE **, BODY **, char **, char **,
			 REPLY_S **, REDRAFT_POS_S **, PINEFIELD **, ACTION_S **, int, STORE_S *);
int	    redraft_cleanup(MAILSTREAM **, int, int);
void	    simple_header_parse(char *, char **, char **);
REPLY_S    *build_reply_uid(char *);
METAENV	   *pine_new_env(ENVELOPE *, char **, char ***, PINEFIELD *);
void	    pine_free_env(METAENV **);
int	    check_addresses(METAENV *);
void	    update_answered_flags(REPLY_S *);
ADDRESS	   *phone_home_from(void);
unsigned int phone_home_hash(char *);
int         call_mailer(METAENV *, BODY *, char **, int, void (*)(char *, int),
			void (*)(PIPE_S *, int, void *));
int         write_postponed(METAENV *, BODY *);
int         commence_fcc(char *, CONTEXT_S **, int);
int         wrapup_fcc(char *, CONTEXT_S *, METAENV *, BODY *);
STORE_S	   *open_fcc(char *, CONTEXT_S **, int, char *, char *);
int	    write_fcc(char *, CONTEXT_S *, STORE_S *, MAILSTREAM *, char *, char *);
BODY	   *first_text_8bit(BODY *);
ADDRESS    *generate_from(void);
void	    set_mime_type_by_grope(BODY *);
void	    set_charset_possibly_to_ascii(BODY *, char *);
void	    set_parameter(PARAMETER **, char *, char *);
void        pine_encode_body(BODY *);
int         pine_header_line(char *, METAENV *, char *, soutr_t, TCPSTREAM *, int, int);
char       *encode_header_value(char *, size_t, unsigned char *, char *, int);
int	    pine_address_line(char *, METAENV *, ADDRESS *, soutr_t, TCPSTREAM *, int, int);
long        pine_rfc822_header(METAENV *, BODY *, soutr_t, TCPSTREAM *);
long        pine_rfc822_output(METAENV *, BODY *, soutr_t, TCPSTREAM *);
void	    pine_free_body(BODY **);
long	    send_body_size(BODY *);
void	    pine_smtp_verbose_out(char *);
int         pine_header_forbidden(char *);
int         hdr_is_in_list(char *, PINEFIELD *);
int         count_custom_hdrs_pf(PINEFIELD *, int);
int         count_custom_hdrs_list(char **);
CustomType  set_default_hdrval(PINEFIELD *, PINEFIELD *);
FieldType   pine_header_standard(char *);
void        customized_hdr_setup(PINEFIELD *, char **, CustomType);
void        add_defaults_from_list(PINEFIELD *, char **);
PINEFIELD  *parse_custom_hdrs(char **, CustomType);
PINEFIELD  *combine_custom_headers(PINEFIELD *, PINEFIELD *);
void        free_customs(PINEFIELD *);
int         encode_whole_header(char *, METAENV *);
int         news_poster(METAENV *, BODY *, char **, void (*)(PIPE_S *, int, void *));
PINEFIELD  *set_priority_header(METAENV *header, char *value);
void        pine_free_body_data(BODY *);
void        free_charsetchecker(void);
long        pine_rfc822_output_body(BODY *,soutr_t,TCPSTREAM *);
int	    pine_write_body_header(BODY *, soutr_t, TCPSTREAM *);

#endif /* PITH_SEND_INCLUDED */


text:
from decimal import Decimal

from django.db import models
from django.utils.translation import ugettext as _

class AbstractProductRecord(models.Model):
    u"""
    A record of a how popular a product is.

    This used be auto-merchandising to display the most popular
    products.
    """

    product = models.OneToOneField('product.Item')

    # Data used for generating a score
    num_views = models.PositiveIntegerField(default=0)
    num_basket_additions = models.PositiveIntegerField(default=0)
    num_purchases = models.PositiveIntegerField(default=0, db_index=True)

    # Product score - used within search
    score = models.FloatField(default=0.00)

    class Meta:
        abstract = True
        ordering = ['-num_purchases']

    def __unicode__(self):
        return u"Record for '%s'" % self.product

class AbstractUserRecord(models.Model):
    u"""
    A record of a user's activity.
    """

    user = models.OneToOneField('auth.User')

    # Browsing stats
    num_product_views = models.PositiveIntegerField(default=0)
    num_basket_additions = models.PositiveIntegerField(default=0)

    # Order stats
    num_orders = models.PositiveIntegerField(default=0, db_index=True)
    num_order_lines = models.PositiveIntegerField(default=0, db_index=True)
    num_order_items = models.PositiveIntegerField(default=0, db_index=True)
    total_spent = models.DecimalField(decimal_places=2, max_digits=12, default=Decimal('0.00'))
    date_last_order = models.DateTimeField(blank=True, null=True)

    class Meta:
        abstract = True

class AbstractUserProductView(models.Model):

    user = models.ForeignKey('auth.User')
    product = models.ForeignKey('product.Item')
    date_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True

    def __unicode__(self):
        return u"%s viewed '%s'" % (self.user, self.product)

class AbstractUserSearch(models.Model):

    user = models.ForeignKey('auth.User')
    query = models.CharField(_("Search term"), max_length=255, db_index=True)
    date_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True
        verbose_name_plural = _("User search queries")

    def __unicode__(self):
        return u"%s searched for '%s'" % (self.user, self.query)


text:
title: vm coredump
category: feature
authors: doron, sfeng
wiki_category: Feature
wiki_title: Features/vm coredump
wiki_revision_count: 2
wiki_last_updated: 2013-02-21
---

# vm coredump

## Coredump support in VDSM

### Summary

This feature adds [1](http://en.wikipedia.org/wiki/Core_dump) support to VDSM. The feature will dump the core of a domain on a given file for analysis. It will be especially useful when used with high availability.

### Owner

*   Name: [ShaoHe Feng](User:Shaohef)
*   Email: <shaohef@linux.vnet.ibm.com>

### Current status

*   Status: the patch was under review. [dump the core of a VM](http://gerrit.ovirt.org/#/c/7329).
*   Last updated: ,

### Detailed Description

### Benefit to oVirt

Users will be able to dump the core of a VM on a given file when their VMs crash. This will be especially important for highly available servers.

### Dependencies / Related Features

This feature depends on the libvirt (already support)

### Documentation / External references

For libvirt support, please see [libvirt's documentation on virDomainCoreDump API](http://libvirt.org/html/libvirt-libvirt.html#virDomainCoreDump).

#### User Interface

def coreDump(self, to, params):

         """
         dump a VM to a designated file.
         :param to: a string designates the dump file
         :param params: a dictionary containing:
             *post-action* - The action taken after core dump, which is
                             'crash', 'live', or 'reset'.
                             crash: crash the VM after core dump.
                             live: perform a live core dump.
                             reset: reset the VM after core dump.
             *bypass-cache* - avoid file system cache when saving.
             *memory-only* - dump VM's memory only.
         """

### Comments and Discussion

Please comment on the [Discussion page](Talk:Features/).

<Category:Feature> <Category:SLA> <Category:VDSM>


text:
namespace Merchello.Providers.Payment.Braintree
{
    using System.Diagnostics.CodeAnalysis;

    using AutoMapper;

    using global::Braintree;

    using Merchello.Core;
    using Merchello.Core.Models;
    using Merchello.Providers.Models;
    using Merchello.Providers.Payment.Braintree.Models;
    using Merchello.Providers.Payment.Models;

    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;

    using Umbraco.Core.Logging;

    using Constants = Merchello.Providers.Constants;

    /// <summary>
    /// Utility extensions that assist in mapping and serializing/de-serializing models
    /// </summary>
    [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed. Suppression is OK here.")]
    public static class MappingExtensions
    {

        #region Address

        /// <summary>
        /// Converts a braintree address to a <see cref="IAddress"/>.
        /// </summary>
        /// <param name="address">
        /// The address.
        /// </param>
        /// <param name="addressType">
        /// The address type.
        /// </param>
        /// <returns>
        /// The <see cref="IAddress"/>.
        /// </returns>
        public static IAddress ToAddress(this global::Braintree.Address address, AddressType addressType)
        {
            return new Core.Models.Address()
                       {
                           Name = string.Format("{0} {1}", address.FirstName, address.LastName),
                           Address1 = address.StreetAddress,
                           Locality = address.Locality,
                           Region = address.Region,
                           PostalCode = address.PostalCode,
                           CountryCode = address.CountryCodeAlpha2,
                           AddressType = addressType
                       };
        }

        #endregion

        #region BraintreeProviderSettings and BraintreeGateway

        /// <summary>
        /// Maps a <see cref="BraintreeProviderSettings"/> as a <see cref="BraintreeGateway"/>
        /// </summary>
        /// <param name="settings">
        /// The settings.
        /// </param>
        /// <returns>
        /// The <see cref="BraintreeGateway"/>.
        /// </returns>
        public static BraintreeGateway AsBraintreeGateway(this BraintreeProviderSettings settings)
        {
            return new BraintreeGateway(settings.EnvironmentType.AsEnvironment(), settings.MerchantId, settings.PublicKey, settings.PrivateKey);
        }

        /// <summary>
        /// Maps an <see cref="EnvironmentType"/> to an <see cref="Environment"/>.
        /// </summary>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <returns>
        /// The <see cref="Environment"/>.
        /// </returns>
        private static Environment AsEnvironment(this EnvironmentType type)
        {
            switch (type)
            {
                case EnvironmentType.Development:
                    return Environment.DEVELOPMENT;

                case EnvironmentType.Production:
                    return Environment.PRODUCTION;

                case EnvironmentType.Qa:
                    return Environment.QA;

                default:
                    return Environment.SANDBOX;
            }
        }

        #endregion

        #region DescriptorRequest

        /// <summary>
        /// Maps a
        /// </summary>
        /// <param name="descriptor">
        /// The descriptor.
        /// </param>
        /// <returns>
        /// The <see cref="DescriptorRequest"/>.
        /// </returns>
        public static DescriptorRequest AsDescriptorRequest(this MerchantDescriptor descriptor)
        {
            var mapped = Mapper.Map<DescriptorRequest>(descriptor);

            mapped.Name = mapped.Name.Replace(" ", "*");

            if (mapped.Name.Length < 22)
            {
                mapped.Name = mapped.Name.PadRight(22, '*');
            }
            else
            {
                mapped.Name = mapped.Name.Substring(0, 21);
            }
            return mapped;
        }

        /// <summary>
        /// Provides and indication if any values have been set in <see cref="MerchantDescriptor"/>
        /// </summary>
        /// <param name="descriptor">
        /// The descriptor.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool HasValues(this MerchantDescriptor descriptor)
        {
            var values = new[] { descriptor.Name, descriptor.Url, descriptor.Phone };
            var all = string.Join(" ", values).Trim();

            return !string.IsNullOrEmpty(all);
        }

        /// <summary>
        /// Provides and indication if any values have been set in <see cref="DescriptorRequest"/>
        /// </summary>
        /// <param name="descriptor">
        /// The descriptor.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool HasValues(this DescriptorRequest descriptor)
        {
            var values = new[] { descriptor.Name, descriptor.Url, descriptor.Phone };
            var all = string.Join(" ", values).Trim();

            return !string.IsNullOrEmpty(all);
        }

        #endregion

        #region ExtendedData

        /// <summary>
        /// Serializes and saves a <see cref="Transaction"/> in extended data
        /// </summary>
        /// <param name="extendedData">
        /// The extended data.
        /// </param>
        /// <param name="transaction">
        /// The transaction.
        /// </param>
        public static void SetBraintreeTransaction(this ExtendedDataCollection extendedData, Transaction transaction)
        {
            extendedData.SetValue(Constants.Braintree.ExtendedDataKeys.BraintreeTransaction, JsonConvert.SerializeObject(transaction));
        }

        /// <summary>
        /// Deserializes and returns a <see cref="Transaction"/> from the extended data collection
        /// </summary>
        /// <param name="extendedData">
        /// The extended data.
        /// </param>
        /// <returns>
        /// The <see cref="Transaction"/>.
        /// </returns>
        public static TransactionReference GetBraintreeTransaction(this ExtendedDataCollection extendedData)
        {
            return extendedData.ContainsKey(Constants.Braintree.ExtendedDataKeys.BraintreeTransaction)
                ? JsonConvert.DeserializeObject<TransactionReference>(
                    extendedData.GetValue(Constants.Braintree.ExtendedDataKeys.BraintreeTransaction))
                : null;
        }

        #endregion
    }
}


text:
using System.Collections.Generic;
using Graphite.Core.Domain;

namespace Graphite.Core.Contracts.Services{
  public interface ITagTasks{
    Tag GetTagByName(string tagname);
    IEnumerable<Tag> GetAllTags();
  }
}


text:
import Home from './Home';
import { connect } from 'react-redux';
import {
  receiveEncryptedMessage,
  createUser,
  openModal,
  closeModal,
  toggleWindowFocus,
  toggleSoundEnabled,
  toggleNotificationEnabled,
  toggleNotificationAllowed,
  toggleSocketConnected,
  receiveUnencryptedMessage,
  sendUnencryptedMessage,
  sendEncryptedMessage,
  setLanguage,
} from 'actions';
import WithNewMessageNotification from './WithNewMessageNotification';

const mapStateToProps = state => {
  const me = state.room.members.find(m => m.id === state.user.id);

  return {
    activities: state.activities.items,
    userId: state.user.id,
    username: state.user.username,
    publicKey: state.user.publicKey,
    privateKey: state.user.privateKey,
    members: state.room.members.filter(m => m.username && m.publicKey),
    roomId: state.room.id,
    roomLocked: state.room.isLocked,
    modalComponent: state.app.modalComponent,
    iAmOwner: Boolean(me && me.isOwner),
    faviconCount: state.app.unreadMessageCount,
    soundIsEnabled: state.app.soundIsEnabled,
    notificationIsEnabled: state.app.notificationIsEnabled,
    notificationIsAllowed: state.app.notificationIsAllowed,
    socketConnected: state.app.socketConnected,
    language: state.app.language,
    translations: state.app.translations,
  };
};

const mapDispatchToProps = {
  receiveEncryptedMessage,
  createUser,
  openModal,
  closeModal,
  toggleWindowFocus,
  toggleSoundEnabled,
  toggleNotificationEnabled,
  toggleNotificationAllowed,
  toggleSocketConnected,
  receiveUnencryptedMessage,
  sendUnencryptedMessage,
  sendEncryptedMessage,
  setLanguage,
};

export default WithNewMessageNotification(connect(mapStateToProps, mapDispatchToProps)(Home));


text:
package com.example.android.tv.recommendations;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.media.tv.TvContractCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.android.tv.recommendations.model.MockDatabase;
import com.example.android.tv.recommendations.model.Subscription;
import com.example.android.tv.recommendations.util.TvUtil;

import java.util.Arrays;
import java.util.List;

/*
 * Displays subscriptions that can be added to the main launcher's channels.
 */
public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    private static final int MAKE_BROWSABLE_REQUEST_CODE = 9001;

    private Button mTvSubscribeButton;
    private Button mVideoClipSubscribeButton;
    private Button mCatVideosSubscribeButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTvSubscribeButton = (Button) findViewById(R.id.subscribe_tv_button);
        mVideoClipSubscribeButton = (Button) findViewById(R.id.subscribe_video_button);
        mCatVideosSubscribeButton = (Button) findViewById(R.id.subscribe_cat_videos_button);

        final Subscription tvShowSubscription =
                MockDatabase.getTvShowSubscription(getApplicationContext());
        setupButtonState(mTvSubscribeButton, tvShowSubscription);

        final Subscription videoSubscription =
                MockDatabase.getVideoSubscription(getApplicationContext());
        setupButtonState(mVideoClipSubscribeButton, videoSubscription);

        final Subscription catVideosSubscription =
                MockDatabase.getCatVideosSubscription(getApplicationContext());
        setupButtonState(mCatVideosSubscribeButton, catVideosSubscription);

        TvUtil.scheduleSyncingChannel(this);
    }

    private void setupButtonState(Button button, final Subscription subscription) {
        boolean channelExists = subscription.getChannelId() > 0L;
        button.setEnabled(!channelExists);
        button.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new AddChannelTask(getApplicationContext()).execute(subscription);
                    }
                });
    }

    private class AddChannelTask extends AsyncTask<Subscription, Void, Long> {

        private final Context mContext;

        AddChannelTask(Context context) {
            this.mContext = context;
        }

        @Override
        protected Long doInBackground(Subscription... varArgs) {
            List<Subscription> subscriptions = Arrays.asList(varArgs);
            if (subscriptions.size() != 1) {
                return -1L;
            }
            Subscription subscription = subscriptions.get(0);
            // TODO: step 16 create channel. Replace declaration with code from code lab.
            long channelId = TvUtil.createChannel(mContext, subscription);

            subscription.setChannelId(channelId);
            MockDatabase.saveSubscription(mContext, subscription);
            // Scheduler listen on channel's uri. Updates after the user interacts with the system
            // dialog.
            TvUtil.scheduleSyncingProgramsForChannel(getApplicationContext(), channelId);
            return channelId;
        }

        @Override
        protected void onPostExecute(Long channelId) {
            super.onPostExecute(channelId);
            promptUserToDisplayChannel(channelId);
        }
    }

    private void promptUserToDisplayChannel(long channelId) {
        // TODO: step 17 prompt user.
        Intent intent = new Intent(TvContractCompat.ACTION_REQUEST_CHANNEL_BROWSABLE);
        intent.putExtra(TvContractCompat.EXTRA_CHANNEL_ID, channelId);
        try {
            this.startActivityForResult(intent, MAKE_BROWSABLE_REQUEST_CODE);
        } catch (ActivityNotFoundException e) {
            Log.e(TAG, "Could not start activity: " + intent.getAction(), e);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // TODO step 18 handle response
        if (resultCode == RESULT_OK) {
            Toast.makeText(this, R.string.channel_added, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, R.string.channel_not_added, Toast.LENGTH_LONG).show();
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viert" content="width=device-width, initial-scale=1">
    <title>{{ site.title }}{% if page.title %} {{ page.title }} {% endif %}</title>
    <link href="http://cdn.bootcss.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="http://cdn.bootcss.com/animate.css/3.4.0/animate.min.css" rel="stylesheet">
    <link href="{{ site.baseurl }}/assets/css/ct.min.css" rel="stylesheet">
    <link href="{{ site.baseurl }}/assets/css/docs.css" rel="stylesheet">
</head>

<body>
    <!--header code -->
    {% include header.html %}
    <!--docs code-->
    {{ content }}
    {% include footer.html %}
</body>
</html>


text:
property :config, Hash, default: lazy { ::Mash.new }, sensitive: true
property :api_client, ::Nexus3::Api, identity: true, default: lazy { ::Nexus3::Api.default(node) }

load_current_value do
  begin
    cfg = ::JSON.parse(api_client.run_script('get_outbound_proxy', nil))
    current_value_does_not_exist! if !cfg.respond_to?(:empty?) || cfg.empty?
    config cfg
    ::Chef::Log.debug "Config is: #{config}"
  # We rescue here because during the first run, the repository will not exist yet, so we let Chef know that
  # the resource has to be created.
  rescue LoadError, ::Nexus3::ApiError => e
    ::Chef::Log.warn "A '#{e.class}' occured: #{e.message}"
    current_value_does_not_exist!
  end
end

action :create do
  init

  converge_if_changed do
    nexus3_api "upsert_outbound_proxy #{new_resource.name}" do
      script_name 'upsert_outbound_proxy'
      args new_resource.config
      action %i[create run]
      api_client new_resource.api_client
      sensitive true

      content ::Nexus3::Scripts.groovy_content('upsert_outbound_proxy', node)
    end
  end
end

action :delete do
  init

  nexus3_api "delete_outbound_proxy #{new_resource.name}" do
    action %i[create run]
    script_name 'delete_outbound_proxy'
    content ::Nexus3::Scripts.groovy_content('delete_outbound_proxy', node)

    api_client new_resource.api_client

    not_if { current_resource.nil? }
  end
end

action_class do
  def init
    nexus3_api "get_outbound_proxy #{new_resource.name}" do
      action :create
      script_name 'get_outbound_proxy'
      api_client new_resource.api_client

      content ::Nexus3::Scripts.groovy_content('get_outbound_proxy', node)
    end
  end
end


text:
#include <sys/printk.h>
#include "dummy_parent.h"

static uint32_t store_value;
uint32_t parent_power_state;

static int dummy_transfer(const struct device *dev, uint32_t cmd,
			  uint32_t *val)
{
	printk("transfer()\n");

	if (cmd == DUMMY_PARENT_WR) {
		store_value = *val;
	} else {
		*val = store_value;
	}

	return 0;
}

static uint32_t dummy_get_power_state(const struct device *dev)
{
	return parent_power_state;
}

static int dummy_suspend(const struct device *dev)
{
	printk("parent suspending..\n");
	parent_power_state = DEVICE_PM_SUSPEND_STATE;

	return 0;
}

static int dummy_resume_from_suspend(const struct device *dev)
{
	printk("parent resuming..\n");
	parent_power_state = DEVICE_PM_ACTIVE_STATE;

	return 0;
}

static int dummy_parent_pm_ctrl(const struct device *dev,
				uint32_t ctrl_command,
				void *context, device_pm_cb cb, void *arg)
{
	int ret = 0;

	switch (ctrl_command) {
	case DEVICE_PM_SET_POWER_STATE:
		if (*((uint32_t *)context) == DEVICE_PM_ACTIVE_STATE) {
			ret = dummy_resume_from_suspend(dev);
		} else {
			ret = dummy_suspend(dev);
		}
		break;
	case DEVICE_PM_GET_POWER_STATE:
		*((uint32_t *)context) = dummy_get_power_state(dev);
		break;
	default:
		ret = -EINVAL;

	}

	cb(dev, ret, context, arg);
	return ret;
}

static const struct dummy_parent_api funcs = {
	.transfer = dummy_transfer,
};

int dummy_parent_init(const struct device *dev)
{
	device_pm_enable(dev);
	parent_power_state = DEVICE_PM_ACTIVE_STATE;
	return 0;
}

DEVICE_DEFINE(dummy_parent, DUMMY_PARENT_NAME, &dummy_parent_init,
		    dummy_parent_pm_ctrl, NULL, NULL, POST_KERNEL,
		    CONFIG_KERNEL_INIT_PRIORITY_DEFAULT, &funcs);


text:
'use strict';
var common = require('../common'),
    assert = require('assert'),
    repl = require('repl');

// Create a dummy stream that does nothing
const stream = new common.ArrayStream();

var r = repl.start({
  input: stream,
  output: stream,
  useGlobal: false
});

// ensure that the repl context gets its own "console" instance
assert(r.context.console);

// ensure that the repl console instance is not the global one
assert.notStrictEqual(r.context.console, console);


text:
// Copyright 1999-2019 Ed Porras
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// other_tables.h: class definitions for the Running Status
//                 and Stuffing tables
// -----------------------------------

#pragma once

#include <list>
#include <string>
#include "table.h"

namespace sigen {

   class TStream;
   class Section;

   /*! \addtogroup table
    *  @{
    */

   /*! \addtogroup DVB
    *  @{
    */

   /*!
    * \brief Running Status %Table, as per ETSI EN 300 468.
    */
   class RST : public STable
   {
   public:
      enum {
         PID = 0x13                            //!< Packet PID for transmission.
      };

      //! \brief Constructor.
      RST() : STable(TID, 0, MAX_SEC_LEN) {}

      /*!
       * \brief Add a transport stream to table.
       * \param xs_id Unique id of the transport stream.
       * \param on_id Id of the originating network.
       * \param sid Id of the service id.
       * \param ev_id Id of the related event.
       * \param running_status Running status of the event. See sigen::Dvb::RunningStatus_t.
       */
      bool addXportStream(ui16 xs_id, ui16 on_id, ui16 sid, ui16 ev_id,
                          ui8  running_status);

      virtual void buildSections(TStream&) const;

#ifdef ENABLE_DUMP
      void dump(std::ostream&) const;
#endif

   private:
      enum { MAX_SEC_LEN = 1024, TID = 0x71 };

      // the private transport stream class
      struct XportStream : public STable::ListItem {
         enum { BASE_LEN = 9 };

         ui16 id;
         ui16 original_network_id;
         ui16 service_id;
         ui16 event_id;
         ui8 running_status : 3;

         // constructor
         XportStream(ui16 xsid, ui16 onid, ui16 sid, ui16 eid, ui8 rs) :
            id(xsid), original_network_id(onid),
            service_id(sid), event_id(eid), running_status(rs) {}
         XportStream() = delete;
      };

      // the list of transport streams
      std::list<XportStream> xport_stream_list;
   };

   /*!
    * \brief %Stuffing %Table, as per ETSI EN 300 468.
    */
   class Stuffing : public STable
   {
   public:
      /*!
       * \brief Constructor using a std::string.
       * \param stuffing_data Stuffing data bytes.
       * \param section_syntax_indicator `true`: for 1, `false` for 0.
       */
      Stuffing(const std::string& stuffing_data, bool section_syntax_indicator = true);
      /*!
       * \brief Constructor specifying a `ui8` to replicate.
       * \param data_length Length of stuffing data to generate.
       * \param data_byte Data byte to repeat.
       * \param section_syntax_indicator `true`: for 1, `false` for 0.
       */
      Stuffing(ui16 data_length, ui8  data_byte, bool section_syntax_indicator = true)
         : Stuffing(std::string(data_length, data_byte), section_syntax_indicator) {}

      // utility
      virtual void buildSections(TStream&) const;

#ifdef ENABLE_DUMP
      void dump(std::ostream&) const;
#endif

   private:
      std::string data;

      enum { TID = 0x72, MAX_SEC_LEN = 4096, CAPACITY = 4093 };
   };
   //! @}
   //! @}
} // namespace


text:
//
// typica - A client library for Amazon Web Services
// Copyright (C) 2007 Xerox Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package com.xerox.amazonws.sdb;

/**
 * This class is an immutable representation of an item attribute.
 *
 * @author D. Kavanagh
 * @author developer@dotech.com
 */
public class Condition {
	private String name;
	private String value;
	private boolean exists;

	public Condition(String name, String value) {
		this.name = name;
		this.value = value;
		this.exists = false;
	}

	public Condition(String name, boolean exists) {
		this.name = name;
		this.value = null;
		this.exists = exists;
	}

	public String getName() {
		return name;
	}

	public String getValue() {
		return value;
	}

	public boolean isExists() {
		return exists;
	}
}


text:
"""Test for profiling.

This test can be useful for profiling, as most of the execution time
will be spent parsing and rendering instead of managing pytest execution
environment. The test simply ensures that the README and Markdown docs
in this project are formatted. To get and read profiler results:
  - `tox -e profile`
  - `firefox .tox/prof/combined.svg`
"""
from pathlib import Path

from mdformat._cli import run

PROJECT_ROOT = Path(__file__).parent.parent
# Make a few asserts to ensure this actually is the project root
# (a safeguard against refactorings where this file is moved).
assert (PROJECT_ROOT / "docs").exists()
assert (PROJECT_ROOT / "README.md").exists()
assert (PROJECT_ROOT / "src" / "mdformat").exists()

def test_for_profiler():
    docs_path = PROJECT_ROOT / "docs"
    readme_path = PROJECT_ROOT / "README.md"
    assert run([str(docs_path), str(readme_path), "--check"]) == 0


text:
<?php

namespace Drupal\file\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Formatter to render the file URI to its download path.
 *
 * @FieldFormatter(
 *   id = "file_uri",
 *   label = @Translation("File URI"),
 *   field_types = {
 *     "uri",
 *     "file_uri",
 *   }
 * )
 */
class FileUriFormatter extends BaseFieldFileFormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $settings = parent::defaultSettings();

    $settings['file_download_path'] = FALSE;
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form, $form_state);

    $form['file_download_path'] = [
      '#title' => $this->t('Display the file download URI'),
      '#type' => 'checkbox',
      '#default_value' => $this->getSetting('file_download_path'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function viewValue(FieldItemInterface $item) {
    $value = $item->value;
    if ($this->getSetting('file_download_path')) {
      $value = $this->fileUrlGenerator->generateString($value);
    }
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return parent::isApplicable($field_definition) && $field_definition->getName() === 'uri';
  }

}


text:
namespace quipper {

// Based on code in tools/perf/util/header.c, the metadata are of the following
// formats:

typedef u32 num_siblings_type;

class DataReader;
class DataWriter;

struct PerfFileAttr;

class PerfReader {
 public:
  PerfReader();
  ~PerfReader();

  // Copy stored contents to |*perf_data_proto|. Appends a timestamp. Returns
  // true on success.
  bool Serialize(PerfDataProto* perf_data_proto) const;
  // Read in contents from a protobuf. Returns true on success.
  bool Deserialize(const PerfDataProto& perf_data_proto);

  bool ReadFile(const string& filename);
  bool ReadFromVector(const std::vector<char>& data);
  bool ReadFromString(const string& str);
  bool ReadFromPointer(const char* data, size_t size);
  bool ReadFromData(DataReader* data);

  bool WriteFile(const string& filename);
  bool WriteToVector(std::vector<char>* data);
  bool WriteToString(string* str);
  bool WriteToPointer(char* buffer, size_t size);

  // Stores the mapping from filenames to build ids in build_id_events_.
  // Returns true on success.
  // Note: If |filenames_to_build_ids| contains a mapping for a filename for
  // which there is already a build_id_event in build_id_events_, a duplicate
  // build_id_event will be created, and the old build_id_event will NOT be
  // deleted.
  bool InjectBuildIDs(const std::map<string, string>& filenames_to_build_ids);

  // Replaces existing filenames with filenames from |build_ids_to_filenames|
  // by joining on build ids.  If a build id in |build_ids_to_filenames| is not
  // present in this parser, it is ignored.
  bool Localize(const std::map<string, string>& build_ids_to_filenames);

  // Same as Localize, but joins on filenames instead of build ids.
  bool LocalizeUsingFilenames(const std::map<string, string>& filename_map);

  // Stores a list of unique filenames found in MMAP/MMAP2 events into
  // |filenames|.  Any existing data in |filenames| will be lost.
  void GetFilenames(std::vector<string>* filenames) const;
  void GetFilenamesAsSet(std::set<string>* filenames) const;

  // Uses build id events to populate |filenames_to_build_ids|.
  // Any existing data in |filenames_to_build_ids| will be lost.
  // Note:  A filename returned by GetFilenames need not be present in this map,
  // since there may be no build id event corresponding to the MMAP/MMAP2.
  void GetFilenamesToBuildIDs(
      std::map<string, string>* filenames_to_build_ids) const;

  // Sort all events in |proto_| by timestamps if they are available. Otherwise
  // event order is unchanged.
  void MaybeSortEventsByTime();

  // Accessors and mutators.

  // This is a plain accessor for the internal protobuf storage. It is meant for
  // exposing the internals. This is not initialized until Read*() or
  // Deserialize() has been called.
  //
  // Call Serialize() instead of this function to acquire an "official" protobuf
  // with a timestamp.
  const PerfDataProto& proto() const { return *proto_; }

  const RepeatedPtrField<PerfDataProto_PerfFileAttr>& attrs() const {
    return proto_->file_attrs();
  }
  const RepeatedPtrField<PerfDataProto_PerfEventType>& event_types() const {
    return proto_->event_types();
  }

  const RepeatedPtrField<PerfDataProto_PerfEvent>& events() const {
    return proto_->events();
  }
  // WARNING: Modifications to the protobuf events may change the amount of
  // space required to store the corresponding raw event. If that happens, the
  // caller is responsible for correctly updating the size in the event header.
  RepeatedPtrField<PerfDataProto_PerfEvent>* mutable_events() {
    return proto_->mutable_events();
  }

  const RepeatedPtrField<PerfDataProto_PerfBuildID>& build_ids() const {
    return proto_->build_ids();
  }
  RepeatedPtrField<PerfDataProto_PerfBuildID>* mutable_build_ids() {
    return proto_->mutable_build_ids();
  }

  const string& tracing_data() const {
    return proto_->tracing_data().tracing_data();
  }

  const PerfDataProto_StringMetadata& string_metadata() const {
    return proto_->string_metadata();
  }

  uint64_t metadata_mask() const { return proto_->metadata_mask().Get(0); }

 private:
  bool ReadHeader(DataReader* data);
  bool ReadAttrsSection(DataReader* data);
  bool ReadAttr(DataReader* data);
  bool ReadEventAttr(DataReader* data, perf_event_attr* attr);
  bool ReadUniqueIDs(DataReader* data, size_t num_ids, std::vector<u64>* ids);

  bool ReadEventTypesSection(DataReader* data);
  // if event_size == 0, then not in an event.
  bool ReadEventType(DataReader* data, int attr_idx, size_t event_size);

  bool ReadDataSection(DataReader* data);

  // Reads metadata in normal mode.
  bool ReadMetadata(DataReader* data);

  // The following functions read various types of metadata.
  bool ReadTracingMetadata(DataReader* data, size_t size);
  bool ReadBuildIDMetadata(DataReader* data, size_t size);
  // Reads contents of a build ID event or block beyond the header. Useful for
  // reading build IDs in piped mode, where the header must be read first in
  // order to determine that it is a build ID event.
  bool ReadBuildIDMetadataWithoutHeader(DataReader* data,
                                        const perf_event_header& header);

  // Reads a singular string metadata field (with preceding size field) from
  // |data| and writes the string and its Md5sum prefix into |dest|.
  bool ReadSingleStringMetadata(
      DataReader* data,
      size_t max_readable_size,
      PerfDataProto_StringMetadata_StringAndMd5sumPrefix* dest) const;
  // Reads a string metadata with multiple string fields (each with preceding
  // size field) from |data|. Writes each string field and its Md5sum prefix
  // into |dest_array|. Writes the combined string fields (joined into one
  // string into |dest_single|.
  bool ReadRepeatedStringMetadata(
      DataReader* data,
      size_t max_readable_size,
      RepeatedPtrField<PerfDataProto_StringMetadata_StringAndMd5sumPrefix>*
          dest_array,
      PerfDataProto_StringMetadata_StringAndMd5sumPrefix* dest_single) const;

  bool ReadUint32Metadata(DataReader* data, u32 type, size_t size);
  bool ReadUint64Metadata(DataReader* data, u32 type, size_t size);
  bool ReadCPUTopologyMetadata(DataReader* data, u32 type, size_t size);
  bool ReadNUMATopologyMetadata(DataReader* data, u32 type, size_t size);
  bool ReadEventDescMetadata(DataReader* data, u32 type, size_t size);

  // Read perf data from piped perf output data.
  bool ReadPipedData(DataReader* data);

  // Returns the size in bytes that would be written by any of the methods that
  // write the entire perf data file (WriteFile, WriteToPointer, etc).
  size_t GetSize() const;

  // Populates |*header| with the proper contents based on the perf data that
  // has been read.
  void GenerateHeader(struct perf_file_header* header) const;

  // Like WriteToPointer, but does not check if the buffer is large enough.
  bool WriteToPointerWithoutCheckingSize(char* buffer, size_t size);

  bool WriteHeader(const struct perf_file_header& header,
                   DataWriter* data) const;
  bool WriteAttrs(const struct perf_file_header& header,
                  DataWriter* data) const;
  bool WriteData(const struct perf_file_header& header, DataWriter* data) const;
  bool WriteMetadata(const struct perf_file_header& header,
                     DataWriter* data) const;

  // For writing the various types of metadata.
  bool WriteBuildIDMetadata(u32 type, DataWriter* data) const;
  bool WriteSingleStringMetadata(
      const PerfDataProto_StringMetadata_StringAndMd5sumPrefix& src,
      DataWriter* data) const;
  bool WriteRepeatedStringMetadata(
      const RepeatedPtrField<
          PerfDataProto_StringMetadata_StringAndMd5sumPrefix>& src_array,
      DataWriter* data) const;
  bool WriteUint32Metadata(u32 type, DataWriter* data) const;
  bool WriteUint64Metadata(u32 type, DataWriter* data) const;
  bool WriteEventDescMetadata(u32 type, DataWriter* data) const;
  bool WriteCPUTopologyMetadata(u32 type, DataWriter* data) const;
  bool WriteNUMATopologyMetadata(u32 type, DataWriter* data) const;

  // For reading event blocks within piped perf data.
  bool ReadAttrEventBlock(DataReader* data, size_t size);

  // Swaps byte order for non-header fields of the data structure pointed to by
  // |event|, if |is_cross_endian| is true. Otherwise leaves the data the same.
  void MaybeSwapEventFields(event_t* event, bool is_cross_endian);

  // Returns the number of types of metadata stored and written to output data.
  size_t GetNumSupportedMetadata() const;

  // For computing the sizes of the various types of metadata.
  size_t GetBuildIDMetadataSize() const;
  size_t GetStringMetadataSize() const;
  size_t GetUint32MetadataSize() const;
  size_t GetUint64MetadataSize() const;
  size_t GetEventDescMetadataSize() const;
  size_t GetCPUTopologyMetadataSize() const;
  size_t GetNUMATopologyMetadataSize() const;

  // Returns true if we should write the number of strings for the string
  // metadata of type |type|.
  bool NeedsNumberOfStringData(u32 type) const;

  // Replaces existing filenames in MMAP/MMAP2 events based on |filename_map|.
  // This method does not change |build_id_events_|.
  bool LocalizeMMapFilenames(const std::map<string, string>& filename_map);

  // Stores a PerfFileAttr in |proto_| and updates |serializer_|.
  void AddPerfFileAttr(const PerfFileAttr& attr);

  bool get_metadata_mask_bit(uint32_t bit) const {
    return metadata_mask() & (1 << bit);
  }
  void set_metadata_mask_bit(uint32_t bit) {
    proto_->set_metadata_mask(0, metadata_mask() | (1 << bit));
  }

  // The file header is either a normal header or a piped header.
  union {
    struct perf_file_header header_;
    struct perf_pipe_file_header piped_header_;
  };

  // Store the perf data as a protobuf.
  Arena arena_;
  PerfDataProto* proto_;

  // Whether the incoming data is from a machine with a different endianness. We
  // got rid of this flag in the past but now we need to store this so it can be
  // passed to |serializer_|.
  bool is_cross_endian_;

  // For serializing individual events.
  PerfSerializer serializer_;

  // When writing to a new perf data file, this is used to hold the generated
  // file header, which may differ from the input file header, if any.
  struct perf_file_header out_header_;

  DISALLOW_COPY_AND_ASSIGN(PerfReader);
};

}  // namespace quipper

#endif  // CHROMIUMOS_WIDE_PROFILING_PERF_READER_H_


text:
package railway

import "code.cloudfoundry.org/cli/api/cloudcontroller/ccv3"

type funcWithWarningsAndError = func() (ccv3.Warnings, error)

func Sequentially(tracks ...funcWithWarningsAndError) (ccv3.Warnings, error) {
	var warnings ccv3.Warnings

	for _, track := range tracks {
		trackWarnings, err := track()
		warnings = append(warnings, trackWarnings...)
		if err != nil {
			return warnings, err
		}
	}

	return warnings, nil
}


text:
import numpy as np
import networkx as nx
import re

class article_to_category():

    """
        Class to map wikipedia articles to a category vector which can then be used as a content vector for content based recommender systems.
        To run this class you need to have run some of the functions in wiki_categories.py to create the graph links and category index.

        Example of the class being run could be:

        -----------
        from pyspark.sql.types import StructType
        import json
        import pickle

        #load and create the files necessary
        category_idx = pickle.load( open("category_index.p", 'rb'))
        high_level_categories = ['Geography', 'Health', 'History', 'Humanities', 'Literature', 'Mathematics', \
               'Nature', 'People', 'Philosophy', 'Reference_works', 'Science', 'Technology']
        ac = article_to_category(high_level_categories, "category_index_graph_link", category_idx)

        #bring in the wikipedia edits, using the json schema if you have it as it is a lot faster!
        with open('wikipedia_full_text_schema.json', 'r') as json_schema_file:
            schema = StructType.fromJson(json.load(json_schema_file))
        wiki_rdd = sqlCtx.read.json('wiki_edits.json.gz', schema = schema)

        article_mapping = ac.run_mapping(wiki_rdd)
        -----------

    """

    def __init__(self, high_level_categories, category_index_graph_link, category_idx):
        """
        Class initializer to Loads the required files

        Args:
            high_level_idx: An array of the high level categories to map to e.g. ['Concepts', 'Life', 'Physical_universe', 'Society']
            category_index_graph_link: Path to the csv of the category links as created from wiki_categories.create_linked_list()
            category_idx: Dictionary of the categories to an index as created from wiki_categories.create_category_idx_dicts()

        """
        #If the format does not have 'Category' in front like our example above we must add that in
        main_topics = ['Category:' +a for a in high_level_categories]
        self.high_level_idx = [category_idx[a] for a in main_topics]

        #Load the Wikipedia category graph from the graph link.  This is assumed to be a csv file
        #File can be created using code from wiki_categories.create_linked_list()
        dg = nx.DiGraph()
        self.category_index_graph = nx.read_adjlist(category_index_graph_link, 'rb', \
                                       create_using=dg ,delimiter=',', nodetype = int)
        self.category_idx = category_idx

    def run_mapping(self, wiki_rdd):
        """
        Maps articles in a wikipedia dump to the high level categories.
        Will only return articles with a findable category mapping, so will skip those articles without categories
        or for whom the mapping could otherwise not be found.

        Args:
            high_level_idx: the full wikipedia text loaded into an RDD (likely through sqlCtx.read.json)

        Returns:
            article_map: mapping of articles to the top level categories
        """

        #Filter out uninteresting articles
        filtered_rdd = wiki_rdd.rdd.filter(
            lambda row:
            row.redirect_target is None  # Save only edits that are not redirects
            and row.article_namespace == 0  # Save only edits on articles, not talk pages
            and row.full_text is not None  # Has text
        )

        #run the category mapping filtering out any articles where the mapping was not found
        article_map = filtered_rdd.map(lambda row: (row.article_title, row.article_id, extract_categories(row.full_text))) \
            .map(lambda (article_title, article_id, cats): self.category_mapping(article_title, article_id, cats)) \
            .filter(lambda row: row != None)
        return article_map

    def category_mapping(self, article_title, article_id, cats):
        parent_lengths_all = []
        #only try to determine the category mapping if the article contains categories
        #there are only a few articles without any categories
        if len(cats)>0:
            for c in cats:
                c = clean_name(c)
                cat_idx = self.category_idx[c]
                #If the category cannot be determined from the category index
                parent_lengths = np.ones(len(self.high_level_idx))*1000000000
                if cat_idx!=[]:
                    parent_lengths = self.getParentArray(cat_idx)
                parent_lengths_all.append(parent_lengths)

            #a shorter length is better so the shortest path will receive a 1 and the longest a 0...the rest will scale in between
            #also if there is at least one array with values (not the 10000000 vector) then the 100000 vectors should be removed first
            #if there are no arrays with values then no array will be returned
            if np.mean(parent_lengths_all, axis=0)[0]<1000000000:
                clean_list = []
                for pl in parent_lengths_all:
                    if pl[0]!=1000000000 and pl[0]!=0.:
                        clean_list.append(pl)
                avg = np.mean(clean_list, axis=0)
                min_val = min(avg)
                max_val = max(avg)
                diff = max_val-min_val
                if diff==0: diff=1
                content_vector = []
                for t in avg:
                    new_val = ((t-min_val)**0*(max_val-t))/diff
                    content_vector.append(new_val)
                return [article_id, content_vector]

    def getParentArray(self, catID):
        """
        From a given category ID, the function will then find the shortest path to the high level index list
        If  a path from the given category to a top level category cannot be found, then the distance will be 1000000000

        Args:
            catID: the originating category ID

        Returns:
            parent_lengths: the distance in the graph between the category ID and top level categories
        """
        parent_lengths = []
        for main_idx in self.high_level_idx:
            dist = 1000000000
            try:
                paths = nx.shortest_path(self.category_index_graph, main_idx, catID)
                dist = len(paths)
            except:
                pass
            parent_lengths.append(dist)
        return parent_lengths

def clean_name(catName):
    """
    Cleans the category name so that it matches the same format as the category list
    #TODO expand this list of cleans or determine encoding difference

    Args:
        catName: original category name as given in the wikipedia dump

    Returns:
        cleanName: the cleaned category name which matches the dbPedia dump
    """
    cleanName = catName.replace(' ', '_')
    cleanName = cleanName.replace('\u2013', '-')
    return cleanName

def extract_categories(text):
    """Extract the Wikipedia categories from the full text of an article.

    Returns a list of strings enumerating the categories for a Wikipedia
    article by parsing the full text of the article. The strings are of the
    form "Category:Foo" and do not contain the opening or closing square
    brackets. If the article contains a sorting hint in the category (for
    example, "[[Category:Foo|Sorting Hint]]") those are removed before
    returning the category.

    This function uses a regular expression: \[\[(Category:[^\[\]|]*)

    This expression requires that the matched text starts with "[[" but does
    not look for a closing "]]" as these can be arbitrarily far away if a
    sorting hint is included.

    Args:
        text (str): The full text of a Wikipedia article in one string.

    Returns:
        list: A list containing strings of the categories a page belongs to.

        The list is empty if the page belongs to no categories.

    """
    # Since Regexes are unreadable, let me explain:
    #
    # "\[\[Category:[^\[\]]*)" consists of several parts:
    #
    #    \[\[ matches "[["
    #
    #    (...) is a capture group meaning roughly "the expression inside this
    #    group is a block that I want to extract"
    #
    #    Category: matches the text "Category:"
    #
    #    [^...] is a negated set which means "do not match any characters in
    #    this set".
    #
    #    \[, \], and | match "[", "]", and "|" in the text respectively
    #
    #    * means "match zero or more of the preceding regex defined items"
    #
    #  So putting it all together, the regex does this:
    #
    #    Finds "[[" followed by "Category:" and then matches any number
    #    (including zero) characters after that that are not the excluded
    #    characters "[", "]", or "|". When it hits an excluded character it
    #    stops and the text matched by the regex inside the (...) part is
    #    returned.
    return re.findall(r'\[\[(Category:[^\[\]|]*)', text)


text:
/*
 *  Require JS Module: menu
 *
 * Code that controls the nav and search buttons that appears on
 * handhelds. Attribution goes to Dan Thomas' original code at:
 * http://danny-t.co.uk/2012/03/02/really-simple-responsive-menu/
 */

// Start RequireJS code

define(["jquery"], function($) {
  var header = document.getElementById("masthead"),
    loadButtons = document.createDocumentFragment(),
    $navMenu = $("#site-navigation-list"),
    $searchBox = $("#searchbox"),
    menuButton = document.createElement("div"),
    searchButton = document.createElement("div"),
    showMenus;

  menuButton.id = "menu";
  menuButton.setAttribute("class", "mobile-menu-btn-class");

  searchButton.id = "search";
  searchButton.setAttribute("class", "search-btn-class");

  loadButtons.appendChild(searchButton);
  loadButtons.appendChild(menuButton);

  header.appendChild(loadButtons);

  showMenus = function(btn,el) {
    $(btn).click(function() {
      if (el.is(":visible") ) {
        el.slideUp({
          complete:function(){
            $(this).css("display","");
          }
        });
      } else {
        el.slideDown();
      }
    });
  };

  showMenus(menuButton, $navMenu);
  showMenus(searchButton, $searchBox);

});


text:
using System;
using System.Collections.Generic;
using System.Text;
using WinCity.Control.LayoutManager;
using System.Drawing;

namespace WinCity.Control.Test
{
    class ListViewTestForm : RForm
    {
        public ListViewTestForm()
        {
            FlowLayout layout = new FlowLayout();
            TopPanel.BindLayoutManager(layout);

            RListView listView = new RListView();
            listView.PreferredSize = this.Size;
            listView.MinimumSize = this.Size;

            Color[] colors = new Color[]
            {
                Color.Green, Color.Yellow, Color.Red, Color.Pink
            };
            for (int i = 0; i < 20; i++)
            {
                RLabel label = new RLabel();
                label.Transparent = false;
                label.Text = i.ToString();
                label.Font = Font;
                label.ForeColor = Color.Black;
                label.BackColor = colors[i % colors.Length];
                listView.AddItem(label);
            }
            listView.ItemSize = new Size(Width, 40);

            TopPanel.AddControl(listView, FlowLayoutEnum.Next);
        }
    }
}


text:
module.exports = angular.module('trafficOps.private.admin.statuses.new', [])
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('trafficOps.private.admin.statuses.new', {
                url: '/new',
                views: {
                    statusesContent: {
                        templateUrl: 'common/modules/form/status/form.status.tpl.html',
                        controller: 'FormNewStatusController',
                        resolve: {
                            status: function() {
                                return {};
                            }
                        }
                    }
                }
            })
        ;
        $urlRouterProvider.otherwise('/');
    });


text:
using System;

namespace MasterDevs.Core
{
    public static class CodeContracts
    {
        public static T RequireNotNull<T>(this T me, string argumentName = "") where T : class
        {
            if (me == null) throw new ArgumentNullException(argumentName);
            return me;
        }

        public static T RequireHasValue<T>(this T? me, string argumentName = "") where T : struct
        {
            if (me == null || !me.HasValue) throw new ArgumentNullException(argumentName);
            return me.Value;
        }

        public static string RequireNotNullOrEmpty(this string me, string argumentName = "")
        {
            if (string.IsNullOrEmpty(me)) throw new ArgumentNullException(argumentName);
            return me;
        }

        public static string RequireNotNullOrWhiteSpace(this string me, string argumentName = "")
        {
            if (string.IsNullOrWhiteSpace(me)) throw new ArgumentNullException(argumentName);
            return me;
        }
    }
}


text:
const JSONAPISerializer = require('jsonapi-serializer').Serializer;

function Environment(data) {
  return new JSONAPISerializer('environments', {
    attributes: ['name', 'apiEndpoint', 'project'],
    project: {
      ref: 'id',
      included: false,
    },
  }).serialize(data);
}

module.exports = Environment;


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">

  <title>Some articles are just so long they deserve a really long title to see if things will break well</title>
  <meta name="description" content="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce bibendum neque eget nunc mattis eu sollicitudin enim tincidunt. Vestibulum lacus tortor, ultri...">

  <link href="https://fonts.googleapis.com/css?family=Cabin:400,700" rel="stylesheet">
  <link rel="stylesheet" href="/assets/css/main.css">
  <link rel="canonical" href="/misc/2016/05/20/super-long-article.html">
  <link rel="alternate" type="application/rss+xml" title="John Doe" href="/feed.xml">

    John Doe

      John Doe

      Photographer

                                Back

                            Discover

                            Project

                            About

                            Contact

Some articles are just so long they deserve a really long title to see if things will break well

<time datetime="2016-05-20T00:00:00+02:00" itemprop="datePublished">May 20, 2016</time>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce bibendum neque eget nunc mattis eu sollicitudin enim tincidunt. Vestibulum lacus tortor, ultricies id dignissim ac, bibendum in velit. Proin convallis mi ac felis pharetra aliquam. Curabitur dignissim accumsan rutrum. In arcu magna, aliquet vel pretium et, molestie et arcu. Mauris lobortis nulla et felis ullamcorper bibendum. Phasellus et hendrerit mauris. Proin eget nibh a massa vestibulum pretium. Suspendisse eu nisl a ante aliquet bibendum quis a nunc. Praesent varius interdum vehicula. Aenean risus libero, placerat at vestibulum eget, ultricies eu enim. Praesent nulla tortor, malesuada adipiscing adipiscing sollicitudin, adipiscing eget est.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce bibendum neque eget nunc mattis eu sollicitudin enim tincidunt. Vestibulum lacus tortor, ultricies id dignissim ac, bibendum in velit. Proin convallis mi ac felis pharetra aliquam. Curabitur dignissim accumsan rutrum. In arcu magna, aliquet vel pretium et, molestie et arcu. Mauris lobortis nulla et felis ullamcorper bibendum. Phasellus et hendrerit mauris. Proin eget nibh a massa vestibulum pretium. Suspendisse eu nisl a ante aliquet bibendum quis a nunc. Praesent varius interdum vehicula. Aenean risus libero, placerat at vestibulum eget, ultricies eu enim. Praesent nulla tortor, malesuada adipiscing adipiscing sollicitudin, adipiscing eget est.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce bibendum neque eget nunc mattis eu sollicitudin enim tincidunt. Vestibulum lacus tortor, ultricies id dignissim ac, bibendum in velit. Proin convallis mi ac felis pharetra aliquam. Curabitur dignissim accumsan rutrum. In arcu magna, aliquet vel pretium et, molestie et arcu. Mauris lobortis nulla et felis ullamcorper bibendum. Phasellus et hendrerit mauris. Proin eget nibh a massa vestibulum pretium. Suspendisse eu nisl a ante aliquet bibendum quis a nunc. Praesent varius interdum vehicula. Aenean risus libero, placerat at vestibulum eget, ultricies eu enim. Praesent nulla tortor, malesuada adipiscing adipiscing sollicitudin, adipiscing eget est.


text:
angular.module('demoApp', [])
  .controller('demoAppCtl', ['$scope', function($scope) {
    $scope.name = "angular-unit-test";

    $scope.demoFunction = function(num) {
        return num * num;
    };
  }])
  .filter('numberCustomFilter', ['$filter', function ($filter) {
     return function (num) {
         if (num != null) {
             if (num >= 0) {
                 return $filter('number')(num);
             }
         }
         return "-";
     }
  }]);


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.sasportal.v1alpha1.model;

/**
 * The channel with score.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the SAS Portal API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class SasPortalChannelWithScore extends com.google.api.client.json.GenericJson {

  /**
   * The frequency range of the channel.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private SasPortalFrequencyRange frequencyRange;

  /**
   * The channel score, normalized to be in [0,100].
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Double score;

  /**
   * The frequency range of the channel.
   * @return value or {@code null} for none
   */
  public SasPortalFrequencyRange getFrequencyRange() {
    return frequencyRange;
  }

  /**
   * The frequency range of the channel.
   * @param frequencyRange frequencyRange or {@code null} for none
   */
  public SasPortalChannelWithScore setFrequencyRange(SasPortalFrequencyRange frequencyRange) {
    this.frequencyRange = frequencyRange;
    return this;
  }

  /**
   * The channel score, normalized to be in [0,100].
   * @return value or {@code null} for none
   */
  public java.lang.Double getScore() {
    return score;
  }

  /**
   * The channel score, normalized to be in [0,100].
   * @param score score or {@code null} for none
   */
  public SasPortalChannelWithScore setScore(java.lang.Double score) {
    this.score = score;
    return this;
  }

  @Override
  public SasPortalChannelWithScore set(String fieldName, Object value) {
    return (SasPortalChannelWithScore) super.set(fieldName, value);
  }

  @Override
  public SasPortalChannelWithScore clone() {
    return (SasPortalChannelWithScore) super.clone();
  }

}


text:
package flags

import (
	"flag"
	"strconv"
)

type uint32Value uint32

// NewUint32Value creates an uint32 instance with the provided value.
func NewUint32Value(v uint32) *uint32Value {
	val := new(uint32Value)
	*val = uint32Value(v)
	return val
}

// Set parses a command line uint32 value.
// Implements "flag.Value" interface.
func (i *uint32Value) Set(s string) error {
	v, err := strconv.ParseUint(s, 0, 32)
	*i = uint32Value(v)
	return err
}

func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) }

// Uint32FromFlag return the uint32 value of a flag with the given name
func Uint32FromFlag(fs *flag.FlagSet, name string) uint32 {
	val := *fs.Lookup(name).Value.(*uint32Value)
	return uint32(val)
}


text:
<?php

namespace Amazon\Pay\Api;

use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * CustomerLink (Amazon Customer <=> Magento Customer) CRUD interface.
 *
 * @api
 */
interface CustomerLinkRepositoryInterface
{
    /**
     * Lists payment tokens that match specified search criteria.
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria The search criteria.
     * @return \Amazon\Pay\Api\Data\CustomerLinkSearchResultsInterface search result interface.
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);

    /**
     * Loads by Customer ID.
     *
     * @param int $customerId The customer ID.
     * @return \Amazon\Pay\Api\Data\CustomerLinkInterface Customer link interface.
     */
    public function get($customerId);

    /**
     * Loads by Entity ID.
     *
     * @param int $entityId The customer link entity ID.
     * @return \Amazon\Pay\Api\Data\CustomerLinkInterface Customer link interface.
     */
    public function getById($entityId);

    /**
     * Delete customer link.
     *
     * @param \Amazon\Pay\Api\Data\CustomerLinkInterface Customer link interface.
     * @return bool
     * @throws CouldNotDeleteException
     */
    public function delete(Data\CustomerLinkInterface $customerLink);

    /**
     * Delete customer link by entity id
     *
     * @param string $entityId
     * @return bool
     * @throws CouldNotDeleteException
     * @throws NoSuchEntityException
     */
    public function deleteById($entityId);

    /**
     * Save customer link
     *
     * @param \Amazon\Pay\Api\Data\CustomerLinkInterface Customer link interface.
     * @return \Amazon\Pay\Api\Data\CustomerLinkInterface
     * @throws CouldNotSaveException
     */
    public function save(Data\CustomerLinkInterface $customerLink);
}


text:
<?php
namespace LolAPI\GameConstants\GameType;

interface GameTypeFactoryInterface
{
    /**
     * Returns policy for unknown GameType
     * @return UnknownGameTypePolicyInterface
     */
    public function getUnknownDataPolicy();

    /**
     * Create and returns GameType from string code
     * @param $stringCode
     * @return GameTypeInterface
     */
    public function createFromStringCode($stringCode);
}