text:
const test = require('ava')
const {eventsys, observable} = require('./craft-observable.js')

test('eventsys', t => {
  t.plan(1)
  let notifier = eventsys()

  notifier.on('test', n => {
    t.is(n, 'it works!')
  })

  notifier.emit('test', 'it works!')
})

test('observable:isObservable', t => {
  t.true(observable().isObservable, 'observable.isObservable is not true')
})

test('observable:get', t => {
  t.plan(3)

  let gettest = observable()

  gettest.$get('fruit', () => "there aren't any fruit")

  t.truthy(gettest.fruit, 'proxy based getters are broken')

  t.truthy(gettest.get('fruit'), 'observable.get(key) not working')

  gettest.fruit = 'Pineapple'

  t.not(gettest.fruit, 'Pineapple', 'getter return values are not sticking!, also pineapples :P')
})

test('observable:set', t => {
  t.plan(4)

  let settest = observable()

  settest.$set('name', (key, value, obj) => {
    t.is(key, 'name')
    return 'My name is ' + value
  })

  settest.name = 'Bob'

  t.is(settest.name, 'My name is Bob', 'His name is not Bob, proxy based setters broken')

  settest.set('name', 'Bernie')

  t.is(settest.get('name'), 'My name is Bernie', 'His name is not Bob, .set(key,val) setters broken')
})

test('observable:nested', t => {
  t.plan(3)

  let base = observable({ nest1: { nest2: {} } })

  t.true(base.nest1.isObservable)
  t.true(base.nest1.nest2.isObservable)

  base.nest1.nest2.nest3 = {}

  t.true(base.nest1.nest2.nest3.isObservable)
})


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('realtime', '0021_auto_20160919_1754'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='ash',
            options={'verbose_name_plural': 'Ashes'},
        ),
        migrations.AlterModelOptions(
            name='volcano',
            options={'verbose_name_plural': 'Volcanoes'},
        ),
        migrations.AddField(
            model_name='ash',
            name='eruption_height',
            field=models.IntegerField(default=0, verbose_name=b'Eruption height in meter'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='ash',
            name='task_id',
            field=models.CharField(default=b'', help_text=b'Task id for processing', max_length=255, verbose_name=b'Celery task id', blank=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='ash',
            name='task_status',
            field=models.CharField(default=b'None', help_text=b'Task status for processing', max_length=30, verbose_name=b'Celery task status', blank=True),
            preserve_default=True,
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
import io
import random
import sys

try:
	import cPickle as pickle
except:
	import pickle

from passage.preprocessing import Tokenizer
from passage.layers import Embedding, GatedRecurrent, Dense
from passage.models import RNN
from passage.utils import save, load

random.seed(0)

testfile, modelfile, tokenizerfile = sys.argv[1:]

test_text = []
with io.open(testfile, 'r', encoding='utf8') as fin:
    for text in fin:
        test_text.append(text.strip())

tokenizer = pickle.load(open(tokenizerfile, 'rb'))
model = load(modelfile)
results = model.predict(tokenizer.transform(test_text))

for r in results:
    print (int(r>=0.5))


text:
'use strict';

import React = require('react');

export default class Footer extends React.Component<any, any> {
  render() {
    return (

Toimitus- ja peruutusehdot

Liput tapahtumaan toimitetaan viivytyksettä asiakkaan antamaan sähköpostiosoitteeseen PDF-A muodossa maksutapahtuman vahvistamisen jälkeen.
          Mikäli toimituksessa on ongelmia, tarkistathan ensin roskapostilaatikon. Muussa tapauksessa ole yhteydessä sähköpostitse liput@teekkarispeksi.fi.
          Lipuilla ei ole peruutusoikeutta.
          Teekkarispeksi ry varaa oikeuden muutoksiin.

Yhteystiedot

Teekkarispeksi ry, y-tunnus: 1888541-7

          liput@teekkarispeksi.fi

          PL69

          02151 Espoo

Tietosuojaseloste

Lippukaupan tietosuojaseloste on saatavilla osoitteesta rekisterit.teekkarispeksi.fi/lippukauppa

Maksupalvelutarjoaja

Maksunvälityspalvelun toteuttajana ja maksupalveluntarjoajana toimii Paytrail Oyj (2122839-7)
        yhteistyössä suomalaisten pankkien ja luottolaitosten kanssa. Paytrail Oyj näkyy maksun saajana
        tiliotteella tai korttilaskulla ja välittää maksun kauppiaalle. Paytrail Oyj:llä on maksulaitoksen
        toimilupa. Reklamaatiotapauksissa pyydämme ottamaan ensisijaisesti yhteyttä tuotteen toimittajaan.

Paytrail Oyj, y-tunnus: 2122839-7

        Innova 2

        Lutakonaukio 7

        40100 Jyväskylä

        https://www.paytrail.com/kuluttaja/maksupalveluehdot

    );
  }
}


text:
package com.martinkl.warc.mapred;

import java.io.EOFException;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import com.martinkl.warc.WARCFileReader;
import com.martinkl.warc.WARCRecord;
import com.martinkl.warc.WARCWritable;

/**
 * Hadoop InputFormat for mapred jobs ('old' API) that want to process data in WARC files.
 *
 * Usage:
 *
 * ```java
 * JobConf job = new JobConf(getConf());
 * job.setInputFormat(WARCInputFormat.class);
 * ```
 *
 * Mappers should use a key of {@link org.apache.hadoop.io.LongWritable} (which is
 * 1 for the first record in a file, 2 for the second record, etc.) and a value of
 * {@link WARCWritable}.
 */
public class WARCInputFormat extends FileInputFormat<LongWritable, WARCWritable> {

    /**
     * Opens a WARC file (possibly compressed) for reading, and returns a RecordReader for accessing it.
     */
    @Override
    public RecordReader<LongWritable, WARCWritable> getRecordReader(InputSplit split, JobConf job, Reporter reporter)
            throws IOException {
        reporter.setStatus(split.toString());
        return new WARCReader(job, (FileSplit) split);
    }

    /**
     * Always returns false, as WARC files cannot be split.
     */
    @Override
    protected boolean isSplitable(FileSystem fs, Path filename) {
        return false;
    }

    private static class WARCReader implements RecordReader<LongWritable, WARCWritable> {
        private final WARCFileReader reader;

        public WARCReader(JobConf job, FileSplit split) throws IOException {
            reader = new WARCFileReader(job, ((FileSplit) split).getPath());
        }

        @Override
        public LongWritable createKey() {
            return new LongWritable();
        }

        @Override
        public WARCWritable createValue() {
            return new WARCWritable();
        }

        @Override
        public boolean next(LongWritable key, WARCWritable value) throws IOException {
            try {
                WARCRecord record = reader.read();
                key.set(reader.getRecordsRead());
                value.setRecord(record);
                return true;
            } catch (EOFException eof) {
                return false;
            }
        }

        @Override
        public long getPos() throws IOException {
            return reader.getBytesRead();
        }

        @Override
        public float getProgress() throws IOException {
            return reader.getProgress();
        }

        @Override
        public void close() throws IOException {
            reader.close();
        }
    }
}


text:
package com.intellij.psi.impl.light;

import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.IncorrectOperationException;
import consulo.annotation.access.RequiredReadAction;
import org.jetbrains.annotations.NonNls;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class LightField extends LightElement implements PsiField {
  private final PsiField myField;
  private final PsiClass myContainingClass;

  public LightField(@Nonnull final PsiManager manager, @Nonnull final PsiField field, @Nonnull final PsiClass containingClass) {
    super(manager, JavaLanguage.INSTANCE);
    myField = field;
    myContainingClass = containingClass;
  }

  @Override
  public void setInitializer(@Nullable final PsiExpression initializer) throws IncorrectOperationException {
    throw new IncorrectOperationException("Not supported");
  }

  @Nonnull
  @Override
  public SearchScope getUseScope() {
    return myField.getUseScope();
  }

  @Override
  public String getName() {
    return myField.getName();
  }

  @Nonnull
  @Override
  public PsiIdentifier getNameIdentifier() {
    return myField.getNameIdentifier();
  }

  @Override
  public PsiDocComment getDocComment() {
    return myField.getDocComment();
  }

  @Override
  public boolean isDeprecated() {
    return myField.isDeprecated();
  }

  @Override
  public PsiClass getContainingClass() {
    return myContainingClass;
  }

  @Nonnull
  @Override
  public PsiType getType() {
    return myField.getType();
  }

  @Override
  public PsiTypeElement getTypeElement() {
    return myField.getTypeElement();
  }

  @Override
  public PsiExpression getInitializer() {
    return myField.getInitializer();
  }

  @Override
  public boolean hasInitializer() {
    return myField.hasInitializer();
  }

  @Override
  public void normalizeDeclaration() throws IncorrectOperationException {
    throw new IncorrectOperationException("Not supported");
  }

  @Override
  public Object computeConstantValue() {
    return myField.computeConstantValue();
  }

  @Override
  public PsiElement setName(@NonNls @Nonnull final String name) throws IncorrectOperationException {
    throw new IncorrectOperationException("Not supported");
  }

  @Override
  public PsiModifierList getModifierList() {
    return myField.getModifierList();
  }

  @Override
  public boolean hasModifierProperty(@NonNls @Nonnull final String name) {
    return myField.hasModifierProperty(name);
  }

  @RequiredReadAction
  @Override
  public String getText() {
    return myField.getText();
  }

  @Override
  public PsiElement copy() {
    return new LightField(myManager, (PsiField)myField.copy(), myContainingClass);
  }

  @RequiredReadAction
  @Nonnull
  @Override
  public TextRange getTextRange() {
    return myField.getTextRange();
  }

  @Override
  public boolean isValid() {
    return myContainingClass.isValid();
  }

  @Override
  public String toString() {
    return "PsiField:" + getName();
  }
}


text:
__author__ = 'Jambunathan'

# The below constant specifies the decimal points allowed in the prices.
PRICE_PRECISION = 3

def pick_max_weight(items, min_value):

  '''
    This function picks a large enough maximum weight
    for the given min_value and items.
  '''

  # return 5000

  # pick the item with poor "value per unit weight ratio"
  # use (min_value/value) * weight * 2 for the min "value per unit weight" item.
  # the knapsack algo cannot do worse than non greedy case

  values_per_unit_weight = [float("inf") for x in items]

  for idx, (_, value, weight) in enumerate(items):
    if value <= min_value:
      values_per_unit_weight[idx] = float(value)/float(weight)

  # none of the weights are less than or equal to the expected weight
  if all([x == float("inf") for x in values_per_unit_weight]):
    return -1

  min_idx = values_per_unit_weight.index(min(values_per_unit_weight))

  max_weight = (float(min_value)/float(items[min_idx][1])) * items[min_idx][2] * 2
  return max_weight

def calculate_cost(items, max_weight, min_value):

  '''
    This method implements a variation of unbounded knapsack algorithm.
    There is infinite supply of items to be placed on the knapsack.
    Also, the weights are floats rather than non-negative integers.
    So we multiply the weights and the max_weight by 1000. (Maximum precision of 3 decimal places is allowed.)
    The weight of knapsack (max_weight) is optional,
    but a "minimum value expected" should be specified otherwise for returning the value.

  '''

  if not max_weight:
    exit_on_min_value = True
    max_weight = pick_max_weight(items, min_value)
    if max_weight == -1:
      return {"error": 'All the item values are more than the expected value: {}'.format(min_value),
              "total_cost": ''}
  else:
    exit_on_min_value = False

  max_weight = int(max_weight * (10**PRICE_PRECISION))
  weights = [int(item[2] * (10**PRICE_PRECISION)) for item in items]
  values = [item[1] for item in items]
  item_names = [item[0] for item in items]

  if all([w > max_weight for w in weights]):
    return {"error": 'All the item weights are more than the expected weight: {}'.format(float(max_weight)/float(10**PRICE_PRECISION)),
            "total_cost": ''}

  # An array, main_arr created to find the optimal value for each of the weight upto max_weight
  # Another array choice_arr is created to note the choice made at each step to remember the items chosen.

  main_arr = [0 for x in range(max_weight+1)]
  choice_arr = [-1 for x in range(max_weight+1)]

  for i, _ in enumerate(main_arr):
    found_min_value = False

    for j in range(len(values)):
      # the current item must weigh less than the current max weight
      if weights[j] <= i:
        if (values[j] + main_arr[i - weights[j]]) > main_arr[i]:
          main_arr[i] = values[j] + main_arr[i - weights[j]]
          # Have chosen the jth item for the current max weight or capacity
          choice_arr[i] = j

      if exit_on_min_value and main_arr[i] >= min_value:
        found_min_value = True
        break

    if found_min_value:
      break

  item_counts = [0 for _ in item_names]
  current_choice = choice_arr[i]

  current_weight = i
  while current_weight > 0 and current_choice != -1:
    item_counts[current_choice] = item_counts[current_choice] + 1
    current_weight = current_weight - weights[current_choice]
    current_choice = choice_arr[current_weight]

  return_data = {}

  servers_data = []
  for idx, item in enumerate(item_names):
    if item_counts[idx] > 0:
      servers_data.append((item, item_counts[idx]))

  return_data['total_cost'] = float(i)/float(10**PRICE_PRECISION)
  return_data['servers'] = sorted(servers_data, key=lambda x: x[1], reverse=True)

  # if the requested minimum value cannot be achieved with the required cost, throw error
  if main_arr[i] < min_value:
    return_data['error'] = 'A cost of {0} can only yield the value: {1} | expected: {2}'.format(return_data['total_cost'],
                                                                                main_arr[i],
                                                                                min_value)

  return return_data

def get_costs(instances, hours, cpus, price):

  '''
    This method calculates the total cost for different server requirements.
    Input:
      instances (dict):
        Input the per hour cost for each server type by region
        { "region_name":
          { "server_type_1": "per hour cost"
            ...
          }

        }
      hours (int):
        Exact Number of hours the servers are needed
      cpus (int or None) [optional]:
        The Minimum number of cpus needed.
      price (float or None) [optional]:
        The maximum price that can be spent for this allocation

      Either cpus or price should definitely be specified

  '''

  server_cpus = {
                 "large": 1,
                 "xlarge": 2,
                 "2xlarge": 4,
                 "4xlarge": 8,
                 "8xlarge": 16,
                 "10xlarge": 32
               }

  result = []

  if cpus is None and price is None:
    raise Exception('Either cpus or price needs to be specified')

  for region_name, region_data in instances.iteritems():
    items = []
    for server_name, server_price in region_data.iteritems():

      # create tuple of (item_name, item_value, item_weight)
      # once a server is selected, it is selected for the whole duration, so the per hour price is multiplied by hours
      # If we run algo per hour, we need to divide the price by hours which will result in
      # incorrect calculation for some cases

      items.append((server_name, server_cpus[server_name], server_price * hours))

    return_data = calculate_cost(items, price, cpus)
    return_data['region'] = region_name
    result.append(return_data)

  result = sorted(result, key=lambda x: x['total_cost'])

  return result


text:
package org.javacs;

public class CompletionData {
    public String className, memberName;
    public String[] erasedParameterTypes;
    public int plusOverloads;
}


text: export * from 'rxjs-compat/operator/debounce';


text:
package com.datastax.driver.spark.rdd

/** Represents a logical conjunction of CQL predicates.
  * Each predicate can have placeholders denoted by '?' which get substituted by values from the `values` array.
  * The number of placeholders must match the size of the `values` array. */
case class CqlWhereClause(predicates: Seq[String], values: Seq[Any]) {

  /** Returns a conjunction of this clause and the given predicate. */
  def and(other: CqlWhereClause) =
    CqlWhereClause(predicates ++ other.predicates, values ++ other.values)

}

object CqlWhereClause {

  /** Empty CQL WHERE clause selects all rows */
  val empty = new CqlWhereClause(Nil, Nil)
}


text:
<?php
namespace Apitude\Core\Entities;

use Doctrine\ORM\Proxy\Proxy;
use Doctrine\ORM\Mapping as ORM;

/**
 * Class AbstractEntity
 * @package Apitude\Core\Entities
 * @ORM\MappedSuperclass
 */
abstract class AbstractEntity
{
    /**
     * Get Entity class
     * @return string
     */
    public function getEntityClass()
    {
        return $this instanceof Proxy ? get_parent_class($this) : self::class;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zero.mapper.master.MerchantMapper">

    <resultMap type="zero.model.Merchant" id="BaseResultMap">
        <result column="merchant_appkey" property="appKey"/>
        <result column="merchant_appsecret" property="appSecret"/>
        <result column="source" property="source"/>
        <result column="channel" property="channel"/>
    </resultMap>

    <select id="getMerchantInfo" resultMap="BaseResultMap">
		select merchant_appkey,merchant_appsecret,source,channel
		from vc_merchant
    </select>

    <update id="update" parameterType="zero.model.Merchant">
        UPDATE vc_merchant
        <set>
            merchant_appkey = #{appKey}
        </set>
        WHERE id = #{id}
    </update>

</mapper>


text:
import sqlite from 'sqlite3';

module.exports = {
    initialiseDb : function() {
        var db = new sqlite.Database('UUUYou.db');

        db.serialize(function () {

            db.run("CREATE TABLE IF NOT EXISTS EventInfo (\
                title TEXT,\
                description TEXT,\
                cost TEXT,\
                timeStart TEXT,\
                timeStop TEXT,\
                venue TEXT,\
                venueAddress TEXT,\
                eventImage TEXT,\
                bookings TEXT,\
                category TEXT,\
                weblink TEXT,\
                age TEXT,\
                meetingPoint TEXT,\
                requirements TEXT,\
                showType TEXT,\
                schedule TEXT,\
                PRIMARY KEY (title, timeStart, venue)\
            )");

            db.run("CREATE TABLE IF NOT EXISTS Venues (\
                venueID TEXT PRIMARY KEY,\
                venueType TEXT,\
                address TEXT,\
                latitude REAL,\
                longitude REAL\
            )");

            db.run("CREATE TABLE IF NOT EXISTS Parks (\
                parkID TEXT PRIMARY KEY,\
                name TEXT\
            )");

            db.run("CREATE TABLE IF NOT EXISTS Items (\
                itemID TEXT PRIMARY KEY,\
                type TEXT,\
                label TEXT,\
                latitude REAL,\
                longitude REAL,\
                park TEXT,\
                FOREIGN KEY(type) REFERENCES ItemTypes(itemTypeID),\
                FOREIGN KEY(park) REFERENCES Parks(parkID)\
            )");

            db.run("CREATE TABLE IF NOT EXISTS ItemTypes (\
                itemTypeID TEXT PRIMARY KEY,\
                description TEXT,\
                quantity INTEGER,\
                use INTEGER DEFAULT 0\
            )");

            db.run("CREATE TABLE IF NOT EXISTS Reviews (\
                reviewID INTEGER PRIMARY KEY,\
                item TEXT,\
                positive INTEGER,\
                FOREIGN KEY(item) REFERENCES Items(itemID)\
            )")

            console.log("Created DB tables");
        });
    }
}


text:
package org.araymond.joal.core.ttorrent.client.utils;

import org.araymond.joal.core.torrent.torrent.InfoHash;
import org.araymond.joal.core.ttorrent.client.DelayQueue;
import org.junit.jupiter.api.Test;

import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.assertj.core.api.Assertions.assertThat;

public class DelayQueueTest {

    public static DelayQueue.InfoHashAble createInfoHashAble(final String str) {
        return () -> new InfoHash(str.getBytes());
    }

    @Test
    public void shouldSort() {
        final DelayQueue<DelayQueue.InfoHashAble> queue = new DelayQueue<>();
        queue.addOrReplace(createInfoHashAble("two"), 20, ChronoUnit.SECONDS);
        queue.addOrReplace(createInfoHashAble("one"), 10, ChronoUnit.MILLIS);
        queue.addOrReplace(createInfoHashAble("four"), 1801, ChronoUnit.SECONDS);
        queue.addOrReplace(createInfoHashAble("three"), 30, ChronoUnit.MINUTES);

        final List<String> announcers = queue.drainAll().stream().map(i -> i.getInfoHash().value()).collect(Collectors.toList());;
        assertThat(announcers).containsExactly("one", "two", "three", "four");
        assertThat(queue.drainAll()).isEmpty();
    }

    @Test
    public void shouldNotBeAvailableBeforeIntervalTimeout() {
        final DelayQueue<DelayQueue.InfoHashAble> queue = new DelayQueue<>();

        queue.addOrReplace(createInfoHashAble("one"), -2, ChronoUnit.MILLIS);
        queue.addOrReplace(createInfoHashAble("two"), -1, ChronoUnit.MILLIS);
        queue.addOrReplace(createInfoHashAble("three"), 30, ChronoUnit.MINUTES);
        queue.addOrReplace(createInfoHashAble("four"), 1801, ChronoUnit.SECONDS);

        final List<String> announcers = queue.getAvailables().stream().map(i -> i.getInfoHash().value()).collect(Collectors.toList());
        assertThat(announcers).hasSize(2);
        assertThat(announcers).containsExactly("one", "two");
    }

    @Test
    public void shouldBeAbleToRemoveOneElement() {

        final DelayQueue<DelayQueue.InfoHashAble> queue = new DelayQueue<>();

        queue.addOrReplace(createInfoHashAble("one"), 20, ChronoUnit.MILLIS);
        queue.addOrReplace(createInfoHashAble("two"), 50, ChronoUnit.SECONDS);
        queue.addOrReplace(createInfoHashAble("three"), 30, ChronoUnit.MINUTES);

        queue.remove(createInfoHashAble("two"));

        final List<String> announcers = queue.drainAll().stream().map(i -> i.getInfoHash().value()).collect(Collectors.toList());
        assertThat(announcers)
                .hasSize(2)
                .containsExactly("one", "three");
    }

    @Test
    public void shouldBeThreadSafe() throws InterruptedException {
        final int announcerCount = 100;
        final DelayQueue<DelayQueue.InfoHashAble> queue = new DelayQueue<>();
        IntStream.range(0, announcerCount).forEach(i -> queue.addOrReplace(createInfoHashAble(String.valueOf(i)), -50, ChronoUnit.MILLIS));

        final List<Callable<List<DelayQueue.InfoHashAble>>> callables = IntStream.range(0, 5)
                .mapToObj(i -> (Callable<List<DelayQueue.InfoHashAble>>) queue::getAvailables)
                .collect(Collectors.toList());
        final ExecutorService executor = Executors.newFixedThreadPool(7);
        final List<Future<List<DelayQueue.InfoHashAble>>> futures = executor.invokeAll(callables);
        final List<DelayQueue.InfoHashAble> results = futures.stream()
                .map(f -> {
                    try {
                        return f.get();
                    } catch (final Exception e) {
                        throw new IllegalStateException(e);
                    }
                })
                .flatMap(List::stream)
                .collect(Collectors.toList());

        assertThat(results).hasSize(announcerCount);
    }

}


text:
/****************************************************************************
 * arch/arm/src/rda5981/rda5981x_adc.c
 *
 *   Copyright (C) 2017 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name tinyara nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
/****************************************************************************
 * Included Files
 ****************************************************************************/
#include <tinyara/config.h>

#include <sys/types.h>
#include <assert.h>
#include <debug.h>
#include <errno.h>

#include <tinyara/irq.h>
#include <tinyara/wqueue.h>
#include <tinyara/analog/adc.h>
#include <tinyara/analog/ioctl.h>

#include "up_arch.h"
#include "rda5981x_adc.h"
#include "chip/rda5981x_pinconfig.h"

//
#ifdef CONFIG_RDA5981_ADC

#define RDA_ADC_RANGE               (0x03FFU)

static int adc_inited_cnt = 0;

/****************************************************************************
 * Private Types
 ****************************************************************************/

/* This structure describes the state of one ADC block */
struct rda_dev_s {
	FAR const struct adc_callback_s *cb;

	struct adc_dev_s *dev;	/* A reference to the outer (parent) */
	uint8_t nchannels;	/* Number of channels */
	uint8_t cchannels;	/* Number of configured channels */
	uint8_t current;	/* Current ADC channel being converted */

	//struct work_s work;	/* Supports the IRQ handling */
	//uint8_t chanlist[RDA5981X_ADC_MAX_CHANNELS];
};

typedef enum {
	ADC0_0 = 0,
	ADC0_1,
	ADC0_2
} ADCName;

/****************************************************************************
 * Private Functions
 ****************************************************************************/
/****************************************************************************
 * Name: adc_conversion
 *
 * Description:
 *   This function executes on the worker thread.  It is scheduled by
 *   adc_interrupt whenever any enabled end-of-conversion event occurs.
 *   All interrupts are disabled when this function runs.
 *   adc_conversion will re-enable the interrupt when it completes
 *   processing the pending interrupt.
 *
 * Input Parameters
 *   arg - The ADC private data structure cast to (void *)
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/
static void adc_conversion(void *arg)
{
#if 0
	uint16_t sample;
	struct rda_dev_s *priv = (struct rda_dev_s *)arg;

	/* Read the ADC sample and pass it to the upper-half */
	sample = getreg32(S5J_ADC_DAT) & ADC_DAT_ADCDAT_MASK;

	if (priv->cb != NULL) {
		DEBUGASSERT(priv->cb->au_receive != NULL);
		priv->cb->au_receive(priv->dev,
							 priv->chanlist[priv->current], sample);
	}

	/* Set the next channel to be sampled */
	priv->current++;

	if (priv->current >= priv->nchannels) {
		priv->current = 0;
	}

	/* Change to the next channel */
	modifyreg32(S5J_ADC_CON2, ADC_CON2_ACHSEL_MASK,
				priv->chanlist[priv->current]);

	/* Exit, start a new conversion */
	modifyreg32(S5J_ADC_CON1, 0, ADC_CON1_STCEN_ENABLE);
#endif
}

/****************************************************************************
 * Name: adc_interrupt
 *
 * Description:
 *   Common ADC interrupt handler.
 *
 * Input Parameters:
 *
 * Returned Value:
 *
 ****************************************************************************/
static int adc_interrupt(int irq, FAR void *context, void *arg)
{
#if 0

	int ret;
	FAR struct rda_dev_s *priv = (FAR struct rda_dev_s *)arg;

	if (getreg32(S5J_ADC_INT_STATUS) & ADC_INT_STATUS_PENDING) {
		/* Clear interrupt pending */
		putreg32(ADC_INT_STATUS_PENDING, S5J_ADC_INT_STATUS);

		/*
		 * Check if interrupt work is already queued. If it is already
		 * busy, then we already have interrupt processing in the
		 * pipeline and we need to do nothing more.
		 */
		if (work_available(&priv->work)) {
			ret = work_queue(LPWORK, &priv->work, adc_conversion,
							 priv, 0);
			if (ret != 0) {
				lldbg("ERROR: failed to queue work: %d\n", ret);
			}
		}
	}
#endif
	return 0;
}

/****************************************************************************
 * Name: adc_startconv
 *
 * Description:
 *   Start (or stop) the ADC conversion process
 *
 * Input Parameters:
 *   priv   - A reference to the ADC block status
 *   enable - True: Start conversion
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/
static void adc_startconv(FAR struct rda_dev_s *priv, bool enable)
{
#if 0

	if (enable) {
		modifyreg32(S5J_ADC_CON1, 0, ADC_CON1_STCEN_ENABLE);
	} else {
		modifyreg32(S5J_ADC_CON1, ADC_CON1_STCEN_ENABLE, 0);
	}
#endif
}

/****************************************************************************
 * Name: adc_set_ch
 *
 * Description
 *   Sets the ADC channel
 *
 * Input Parameters:
 *   dev - pointer to device structure used by the drvier
 *   ch  - ADC channel number + 1 (0 is reserved for all configured channels.)
 *
 * Returned Value:
 *   int - errno
 *
 ****************************************************************************/
static int adc_set_ch(FAR struct adc_dev_s *dev, uint8_t ch)
{
#if 0

	int i;
	FAR struct rda_dev_s *priv = (FAR struct rda_dev_s *)dev->ad_priv;

	if (ch == 0) {
		/*
		 * 0 is reserved for special purpose which samples
		 * all channels
		 */
		priv->current = 0;
		priv->nchannels = priv->cchannels;
	} else {
		/* REVISIT: changing channel is not supported for now */

		for (i = 0; i < priv->cchannels &&
			 priv->chanlist[i] != ch - 1; i++);

		if (i >= priv->cchannels) {
			return -ENODEV;
		}

		priv->current   = i;
		priv->nchannels = 1;
	}

	modifyreg32(S5J_ADC_CON2, ADC_CON2_ACHSEL_MASK,
				priv->chanlist[priv->current]);
#endif
	return 0;
}

/****************************************************************************
 * Name: adc_bind
 *
 * Description:
 *   Bind the upper-half driver callbacks to the lower-half implementation.
 *   This must be called early in order to receive ADC event notifications.
 *
 ****************************************************************************/
static int adc_bind(FAR struct adc_dev_s *dev,
					FAR const struct adc_callback_s *callback)
{
#if 0

	FAR struct rda_dev_s *priv = (FAR struct rda_dev_s *)dev->ad_priv;

	DEBUGASSERT(priv != NULL);
	priv->cb = callback;
#endif
	return 0;
}

/****************************************************************************
 * Name: adc_reset
 *
 * Description:
 *   Reset the ADC device.  Called early to initialize the hardware. This
 *   is called, before adc_setup() and on error conditions.
 *
 * Input Parameters:
 *
 * Returned Value:
 *
 ****************************************************************************/
static void adc_reset(FAR struct adc_dev_s *dev)
{
#if 0

	irqstate_t flags;

	flags = irqsave();

	/* Reset ADC */
	putreg32(ADC_CON1_SOFTRESET_RESET, S5J_ADC_CON1);

	/* Release ADC from reset state */
	putreg32(ADC_CON1_SOFTRESET_NONRESET, S5J_ADC_CON1);

	/* Configuration of the channel conversions */
	adc_set_ch(dev, 0);

	irqrestore(flags);
#endif
}

/****************************************************************************
 * Name: adc_setup
 *
 * Description:
 *   Configure the ADC. This method is called the first time that the ADC
 *   device is opened.  This will occur when the port is first opened.
 *   This setup includes configuring and attaching ADC interrupts.
 *   Interrupts are all disabled upon return.
 *
 * Input Parameters:
 *
 * Returned Value:
 ****************************************************************************/
static int adc_setup(FAR struct adc_dev_s *dev)
{
#if 0

	int ret;
	FAR struct rda_dev_s *priv = (FAR struct rda_dev_s *)dev->ad_priv;

	/* Attach the ADC interrupt */
	ret = irq_attach(IRQ_ADC, adc_interrupt, priv);
	if (ret < 0) {
		lldbg("irq_attach failed: %d\n", ret);
		return ret;
	}

	/* Make sure that the ADC device is in the powered up, reset state */
	adc_reset(dev);

	/*
	 * Enable the ADC interrupt, but it will not be generated until we
	 * request to start the conversion.
	 */
	lldbg("Enable the ADC interrupt: irq=%d\n", IRQ_ADC);
	up_enable_irq(IRQ_ADC);
#endif
	return 0;
}

/****************************************************************************
 * Name: adc_shutdown
 *
 * Description:
 *   Disable the ADC.  This method is called when the ADC device is closed.
 *   This method reverses the operation the setup method.
 *
 * Input Parameters:
 *
 * Returned Value:
 *
 ****************************************************************************/
static void adc_shutdown(FAR struct adc_dev_s *dev)
{
#if 0

	/* Disable interrupt */
	putreg32(ADC_INT_DISABLE, S5J_ADC_INT);

	/* Disable ADC interrupts and detach the ADC interrupt handler */
	up_disable_irq(IRQ_ADC);
	irq_detach(IRQ_ADC);

	/* Reset ADC */
	putreg32(ADC_CON1_SOFTRESET_RESET, S5J_ADC_CON1);
#endif
}

/****************************************************************************
 * Name: adc_rxint
 *
 * Description:
 *   Call to enable or disable RX interrupts.
 *
 * Input Parameters:
 *
 * Returned Value:
 *
 ****************************************************************************/
static void adc_rxint(FAR struct adc_dev_s *dev, bool enable)
{
#if 0
	/* Enable or Disable ADC interrupt */
	putreg32(enable ? ADC_INT_ENABLE : ADC_INT_DISABLE, S5J_ADC_INT);
#endif
}

/****************************************************************************
 * Name: adc_ioctl
 *
 * Description:
 *   All ioctl calls will be routed through this method.
 *
 * Input Parameters:
 *   dev - pointer to device structure used by the driver
 *   cmd - command
 *   arg - arguments passed with command
 *
 * Returned Value:
 *
 ****************************************************************************/
static int adc_ioctl(FAR struct adc_dev_s *dev, int cmd, unsigned long arg)
{
#if 0

	FAR struct rda_dev_s *priv = (FAR struct rda_dev_s *)dev->ad_priv;
	int ret = OK;

	switch (cmd) {
	case ANIOC_TRIGGER:
		adc_startconv(priv, true);
		break;

	default:
		ret = -ENOTTY;
		break;
	}
#endif
	return 0;
}

/****************************************************************************
 * Private Data
 ****************************************************************************/
static const struct adc_ops_s g_adcops = {
	.ao_bind	= adc_bind,
	.ao_reset	= adc_reset,
	.ao_setup	= adc_setup,
	.ao_shutdown	= adc_shutdown,
	.ao_rxint	= adc_rxint,
	.ao_ioctl	= adc_ioctl,
};

static struct rda_dev_s g_adcpriv = {
	.cb		= NULL,
	.current	= 0,
};

static struct adc_dev_s g_adcdev;

/****************************************************************************
 * Public Functions
 ****************************************************************************/
void analogin_init(void)
{
	//use Port B pin6
	unsigned char gp = 6U;  //PortB 6pin

	/* Init ADC */
	if (0 == adc_inited_cnt) {
		rda_ccfg_adc_init();
	}
	adc_inited_cnt++;

	rda_ccfg_gp(gp, 0x00U);
	rda_ccfg_adc_gp(gp, 0x00U);

	rda_configgpio(GPIO_RDA_ADC);
}

uint16_t analogin_read_u16(void)
{
	printf("analogin_read_u16\n");
	uint16_t value = rda_ccfg_adc_read((unsigned char)ADC0_0);
	return (value); // 10 bit
}

float analogin_read(void)
{
	printf("analogin_read\n");
	uint16_t value = rda_ccfg_adc_read((unsigned char)ADC0_0);
	return (float)value * (1.0f / (float)RDA_ADC_RANGE);
}

void analogin_free(void)
{
	unsigned char gp = 6U;
	adc_inited_cnt--;
	if (0 == adc_inited_cnt) {
		rda_ccfg_adc_free();
	}
#if 0	// because we only use ADC0_0
	if (ADC0_2 == obj->adc) {
		return;
	}
	if (ADC0_1 == obj->adc) {
		if (0U == adc1_gp) {
			return;
		}
		gp = adc1_gp;
	}
#endif
	rda_ccfg_adc_gp(gp, 0x01U);
	rda_ccfg_gp(gp, 0x01U);
}

/****************************************************************************
 * Name: rda5981x_adc_initialize
 *
 * Description:
 *   Initialize the ADC. As the pins of each ADC channel are exported through
 *   configurable GPIO and it is board-specific, information on available
 *   ADC channels should be passed to s5j_adc_initialize().
 *
 * Input Parameters:
 *
 * Returned Value:
 *   Valid ADC device structure reference on succcess; a NULL on failure
 *
 ****************************************************************************/
struct adc_dev_s *rda5981x_adc_initialize(void)
{
	FAR struct rda_dev_s *priv = &g_adcpriv;

	/* Initialize the public ADC device data structure */
	g_adcdev.ad_ops  = &g_adcops;
	g_adcdev.ad_priv = priv;

	/* Initialize the private ADC device data structure */
	priv->cb         = NULL;
	priv->dev        = &g_adcdev;
	//priv->cchannels  = cchannels;
#if 0
	if (cchannels > RDA5981X_ADC_MAX_CHANNELS) {
		lldbg("RDA5981 has maximum %d ADC channels.\n",
			  RDA5981X_ADC_MAX_CHANNELS);
		return NULL;
	}

	memcpy(priv->chanlist, chanlist, cchannels);
#endif

	analogin_init();

	return &g_adcdev;
}
#endif /* CONFIG_RDA5981_ADC */


text:
namespace JoinRpg.Dal.Impl.Migrations;

using System.Data.Entity.Migrations;

public partial class ProjectAnnounce : DbMigration
{
    public override void Up() => AddColumn("dbo.ProjectDetails", "ProjectAnnounce_Contents", c => c.String());

    public override void Down() => DropColumn("dbo.ProjectDetails", "ProjectAnnounce_Contents");
}


text:
package ol.event;

import ol.MapEvent;
import ol.source.Tile;

/**
 * A listener for tile loading errors.
 *
 * @author sbaumhekel
 */
public interface TileLoadErrorListener {

    /**
     * Fired if tile loading results in an error.
     *
     * @param evt
     *            {@link MapEvent}
     */
    void onTileLoadError(Tile.Event evt);

}


text:
Introduction
============

lthread is a multicore/multithread coroutine library written in C. It uses [Sam Rushing's](https://github.com/samrushing) _swap function to swap lthreads. What's special about lthread is that it allows you to make *blocking calls* and *expensive* computations, blocking IO inside a coroutine, providing you with the advantages of coroutines and pthreads. See the http server example below.

lthreads are created in userspace and don't require kernel intervention, they are light weight and ideal for socket programming. Each lthread have separate stack, and  the stack is madvise(2)-ed to save space, allowing you to create thousands(tested with a million lthreads) of coroutines and maintain a low memory footprint. The scheduler is hidden from the user and is created automagically in each pthread, allowing the user to take advantage of cpu cores and distribute the load by creating several pthreads, each running it's own lthread scheduler and handling its own share of coroutines. Locks are necessary when accessing global variables from lthreads running in different pthreads, and lthreads must not block on pthread condition variables as this will block the whole lthread scheduler in the pthread.

.. image:: images/lthread_scheduler.png

To run an lthread scheduler in each pthread, launch a pthread and create lthreads using lthread_create() followed by lthread_run() in each pthread.

**Scheduler**

The scheduler is build around epoll/kqueue and uses an rbtree to track which lthreads needs to run next.

If you need to execute an expensive computation or make a blocking call inside an lthread, you can surround the block of code with `lthread_compute_begin()` and `lthread_compute_end()`, which moves the lthread into an lthread_compute_scheduler that runs in its own pthread to avoid blocking other lthreads. lthread_compute_schedulers are created when needed and they die after 60 seconds of inactivity. `lthread_compute_begin()` tries to pick an already created and free lthread_compute_scheduler before it creates a new one.

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

Currently, lthread is supported on FreeBSD, OS X, and Linux (x86 & 64bit arch).

To build and install, simply:

.. code-block:: Shell

    cmake .
    sudo make install

::

Linking
-------

`#include <lthread.h>`

Pass `-llthread` to gcc to use lthread in your program.

C++11 Bindings
--------------

Docs and instructions to download/install can be found `here <http://lthread-cpp.readthedocs.org/en/latest/intro.html>`_.

License
-------

Copyright (C) 2012, Hasan Alayli <halayli@gmail.com>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.


text:
package org.springframework.context.annotation;

import junit.framework.TestCase;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.config.SimpleMapScope;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Mark Fisher
 * @author Juergen Hoeller
 */
public class ComponentScanParserScopedProxyTests extends TestCase {

	public void testDefaultScopedProxy() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"org/springframework/context/annotation/scopedProxyDefaultTests.xml");
		context.getBeanFactory().registerScope("myScope", new SimpleMapScope());
		ScopedProxyTestBean bean = (ScopedProxyTestBean) context.getBean("scopedProxyTestBean");
		// should not be a proxy
		assertFalse(AopUtils.isAopProxy(bean));
	}

	public void testNoScopedProxy() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"org/springframework/context/annotation/scopedProxyNoTests.xml");
		context.getBeanFactory().registerScope("myScope", new SimpleMapScope());
		ScopedProxyTestBean bean = (ScopedProxyTestBean) context.getBean("scopedProxyTestBean");
		// should not be a proxy
		assertFalse(AopUtils.isAopProxy(bean));
	}

	public void testInterfacesScopedProxy() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"org/springframework/context/annotation/scopedProxyInterfacesTests.xml");
		context.getBeanFactory().registerScope("myScope", new SimpleMapScope());
		// should cast to the interface
		FooService bean = (FooService) context.getBean("scopedProxyTestBean");
		// should be dynamic proxy
		assertTrue(AopUtils.isJdkDynamicProxy(bean));
	}

	public void testTargetClassScopedProxy() {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"org/springframework/context/annotation/scopedProxyTargetClassTests.xml");
		context.getBeanFactory().registerScope("myScope", new SimpleMapScope());
		ScopedProxyTestBean bean = (ScopedProxyTestBean) context.getBean("scopedProxyTestBean");
		// should be a class-based proxy
		assertTrue(AopUtils.isCglibProxy(bean));
	}

	public void testInvalidConfigScopedProxy() {
		try {
			new ClassPathXmlApplicationContext(
					"org/springframework/context/annotation/scopedProxyInvalidConfigTests.xml");
			fail("should have thrown Exception; scope-resolver and scoped-proxy both provided");
		}
		catch (FatalBeanException e) {
			// expected
		}
	}

}


text:
using SignalR.Dynamic.API.Common;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SignalR.Dynamic.API.Interfaces
{
    public interface IPublisherMetadataProvider
    {
        IEnumerable<Metadata> GetMetadata();
    }
}


text:
self.$config = {
  landing: true,
  tocVisibleDepth: 2,
  repo: 'service-mocker/service-mocker',
  'edit-link': 'https://github.com/service-mocker/service-mocker/blob/master/docs',
  nav: [{
    title: 'Getting Started',
    path: '/home',
  }, {
    title: 'API Reference',
    path: '/api',
  }, {
    title: 'Caveats',
    path: '/caveats',
  }],
  plugins: [
    landingScriptsPlugin([
      'https://unpkg.com/webfontloader@latest',
      'assets/twitter-widget.js',
      'assets/stroke.js',
    ]),
    footerPlugin(),
  ],
};

function landingScriptsPlugin(scripts) {
  var caches = {};

  return function loadScripts(context) {
    context.router.afterEach(function (to) {
      if (to.meta && to.meta.name === 'landing') {
        scripts.forEach(function (url) {
          if (caches[url]) {
            caches[url].parentElement.removeChild(caches[url]);
          }

          var el = caches[url] = document.createElement('script');
          el.src = url; el.async = false;
          document.body.appendChild(el);
        });
      }
    });
  };
}

function footerPlugin() {
  var footer = [
    '',
    'Service Mocker Team ©2017.',
    'Proudly published with docute.',
    '',
  ].join('');

  return function appendFooter(context) {
    context.registerComponent('content:end', {
      template: footer,
    });
  };
}


text:
SamplePresentation
==================

UIPresentationControllerの実装サンプルです。

解説記事はこちら

[[iOS 8] UIPresentationController でカスタムのモーダル表示を実装する](http://dev.classmethod.jp/references/ios-8-uipresentationcontroller/)


text:
package com.matthewmitchell.nubitsj.core;

import javax.annotation.*;
import java.util.List;
import java.util.Set;

/**
 * Convenience implementation of {@link PeerEventListener}.
 */
public class AbstractPeerEventListener implements PeerEventListener {
    @Override
    public void onPeersDiscovered(Set<PeerAddress> peerAddresses) {
    }

    @Override
    public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) {
    }

    @Override
    public synchronized void onDownloadingHashes(Peer peer, boolean isDownloading) {
    }

    @Override
    public void onChainDownloadStarted(Peer peer, int blocksLeft) {
    }

    @Override
    public void onPeerConnected(Peer peer, int peerCount) {
    }

    @Override
    public void onPeerDisconnected(Peer peer, int peerCount) {
    }

    @Override
    public Message onPreMessageReceived(Peer peer, Message m) {
        // Just pass the message right through for further processing.
        return m;
    }

    @Override
    public void onTransaction(Peer peer, Transaction t) {
    }

    @Override
    public List<Message> getData(Peer peer, GetDataMessage m) {
        return null;
    }
}


text:
package com.mrprona.brawlassistant.base.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.mrprona.brawlassistant.BeanContainer;
import com.mrprona.brawlassistant.hero.api.HeroStats;
import com.mrprona.brawlassistant.hero.dao.AbilityDao;
import com.mrprona.brawlassistant.hero.dao.HeroDao;
import com.mrprona.brawlassistant.hero.dao.HeroStatsDao;
import com.mrprona.brawlassistant.item.dao.ItemDao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: ABadretdinov
 * Date: 29.08.13
 * Time: 11:07
 */
public class Helper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "brawlstars.db";
    public static final int DATABASE_VERSION = 4;
    private Context mContext;

    /*public static final String CREATE_ITEMS_FROM="create table if not exists "+
            " items_from ( _id integer PRIMARY KEY AUTOINCREMENT, item_id integer not null, need_id integer not null);";*/

    public Helper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        List<CreateTableDao> allDaos = BeanContainer.getInstance().getAllDaos();
        for (CreateTableDao dao : allDaos) {
            dao.onCreate(db);
        }
        db.execSQL("create table if not exists updated_version(version integer not null);");
        db.execSQL("insert into updated_version (version) values(0);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < DATABASE_VERSION) {
            reinitHeroesAndItems(db);
        }
     /*   List<CreateTableDao> allDaos = BeanContainer.getInstance().getAllDaos();
        for (CreateTableDao dao : allDaos) {
            dao.onUpgrade(db, oldVersion, newVersion);
        }*/
        onCreate(db);
    }

    private void reinitHeroesAndItems(SQLiteDatabase db) {
        db.execSQL("drop table " + ItemDao.TABLE_NAME);
        db.execSQL("drop table " + ItemDao.ITEMS_FROM_MAPPER_TABLE_NAME);
        db.execSQL("drop table " + HeroDao.TABLE_NAME);
        db.execSQL("drop table " + HeroStatsDao.TABLE_NAME);
        db.execSQL("drop table " + AbilityDao.TABLE_NAME);
        db.execSQL("update updated_version set version=0;");
    }

    public Map<Long, Integer> getAllStatsHero() {
        Map<Long, Integer> statsList = new HashMap<>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + HeroStatsDao.TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                HeroStats heroStats = new HeroStats();
                heroStats.setId(cursor.getInt(0));
                heroStats.setPrimaryStat(cursor.getInt(20));
                // Adding contact to list
                statsList.put(heroStats.getId(), heroStats.getPrimaryStat());
            } while (cursor.moveToNext());
        }
        // return contact list
        return statsList;
    }
}


text:
"""Utilities for dealing with ML predict API."""

import json

from googlecloudsdk.core import exceptions as core_exceptions
from googlecloudsdk.core.credentials import http

class InstancesEncodeError(core_exceptions.Error):
  """Indicates that error occurs while decoding the instances in http body."""
  pass

class HttpRequestFailError(core_exceptions.Error):
  """Indicates that the http request fails in some way."""
  pass

def Predict(model_or_version_ref, instances):
  """Performs online prediction on the input data file.

  Args:
      model_or_version_ref: a Resource representing either a model or a version.
      instances: a list of JSON or UTF-8 encoded instances to perform
          prediction on.

  Returns:
      A json object that contains predictions.

  Raises:
      HttpRequestFailError: if error happens with http request, or parsing
          the http response.
  """
  url = model_or_version_ref.SelfLink() + ':predict'
  # Construct the body for the predict request.
  headers = {'Content-Type': 'application/json'}
  try:
    body = json.dumps({'instances': instances}, sort_keys=True)
  except UnicodeDecodeError:
    raise InstancesEncodeError('Instances cannot be JSON encoded, probably '
                               'because the input is not utf-8 encoded.')

  # Workaround since current gcloud sdk cannot handle the httpbody properly.
  # TODO(b/31403673): use M1V1beta1.ProjectsService.Predict once b/31403673
  # is fixed.
  response, response_body = http.Http().request(
      uri=url, method='POST', body=body, headers=headers)
  if response.get('status') != '200':
    raise HttpRequestFailError('HTTP request failed. Response: ' +
                               response_body)
  try:
    return json.loads(response_body)
  except ValueError:
    raise HttpRequestFailError('No JSON object could be decoded from the '
                               'HTTP response body: ' + response_body)


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <mach/hardware.h>
#include <mach/board.h>
#include <mach/adi.h>
#include <asm/gpio.h>

#define SPRD_FLASH_ON		1
#define SPRD_FLASH_OFF		0

int sprd_flash_on(void)
{
	printk("sprd_flash_on vivalto \n");
	gpio_request(GPIO_CAM_FLASH_EN,"cam_flash_en");
	gpio_direction_output(GPIO_CAM_FLASH_EN, SPRD_FLASH_ON);
	gpio_free(GPIO_CAM_FLASH_EN);
	return 0;
}

int sprd_flash_high_light(void)
{
	printk("sprd_flash_high_light vivalto \n");
	gpio_request(GPIO_CAM_FLASH_EN,"cam_flash_en");
	gpio_direction_output(GPIO_CAM_FLASH_EN, SPRD_FLASH_ON);
	gpio_free(GPIO_CAM_FLASH_EN);
	return 0;
}

int sprd_flash_close(void)
{
	printk("sprd_flash_close vivalto \n");
	gpio_request(GPIO_CAM_FLASH_EN,"cam_flash_en");
	gpio_direction_output(GPIO_CAM_FLASH_EN, SPRD_FLASH_OFF);
	gpio_free(GPIO_CAM_FLASH_EN);
	return 0;
}


text:
package request

import (
	"io"
	"os"
	"fmt"
	"log"
	"errors"
	"strings"
	"net/url"
	"net/http"
	"net/http/httputil"
	"crypto/tls"
	"encoding/json"
	"github.com/classmethod/aurl/profiles"
	"github.com/classmethod/aurl/tokens"
)

type AurlExecution struct {
	Name string
	Version string

	Profile profiles.Profile
	Method *string
	Headers *http.Header
	Data *string
	Insecure *bool
	PrintBody *bool
	PrintHeaders *bool

	TargetUrl *string
}

func (execution *AurlExecution) Execute() error {
	log.Printf("Profile = %v", execution.Profile)

	if tokenResponseString, err := tokens.LoadTokenResponseString(execution.Profile.Name); err == nil {
		log.Printf("Stored token response was found: >>>\n%v\n<<<", *tokenResponseString)
		if tokenResponse, err := tokens.New(tokenResponseString); err == nil {
			log.Printf("Stored access token: %v", tokenResponse.AccessToken)
			if tokenResponse.IsExpired() == false {
				response, err := execution.doRequest(tokenResponse, execution.Profile)
				if err == nil {
					log.Printf("Stored access token was valid")
					execution.doPrint(response)
					return nil
				} else {
					log.Printf("Stored access token was invalid: %v", err.Error())
				}
			} else {
				log.Printf("Stored access token was expired")
			}
			if tokenResponse.RefreshToken != "" {
				log.Printf("Stored refresh token: %v", tokenResponse.RefreshToken)
				if tokenResponseString, err = execution.refresh(tokenResponse); err == nil {
					if tokenResponseString != nil {
						log.Printf("Refreshed token response: >>>\n%v\n<<<", *tokenResponseString)
					}
					if tokenResponse, err := tokens.New(tokenResponseString); err == nil {
						if response, err := execution.doRequest(tokenResponse, execution.Profile); err == nil {
							log.Printf("Refreshed access token was valid")
							execution.doPrint(response)
							tokens.SaveTokenResponseString(execution.Profile.Name, tokenResponseString)
							return nil
						} else {
							log.Printf("Refreshed access token was invalid: %v", err.Error())
						}
					} else {
						log.Printf("Failed to parse refreshed token response: %v", err.Error())
					}
				} else {
					log.Printf("Stored refresh token was invalid: %v", err.Error())
				}
			} else {
				log.Printf("Stored refresh token was not found")
			}
		} else {
			log.Printf("Failed to parse stored token response: %v", err.Error())
		}
	} else {
		log.Printf("Stored access token was not found: %v", err.Error())
	}

	if tokenResponseString, err := execution.grant(); err == nil {
		if tokenResponseString != nil {
			log.Printf("Issued token response: >>>\n%v\n<<<", *tokenResponseString)
		}
		if tokenResponse, err := tokens.New(tokenResponseString); err == nil {
			log.Printf("Issued access token: %v", tokenResponse.AccessToken)
			if response, err := execution.doRequest(tokenResponse, execution.Profile); err == nil {
				log.Printf("Issued access token was valid")
				execution.doPrint(response)
				tokens.SaveTokenResponseString(execution.Profile.Name, tokenResponseString)
				return nil
			} else {
				log.Printf("Granted access token was invalid: %v", err.Error())
				execution.doPrint(response)
				return err
			}
		} else {
			log.Printf("Failed to parse granted token response: %v", err.Error())
			return err
		}
	} else {
		log.Printf("Grant failed: %v", err.Error())
		return err
	}
}

func (request *AurlExecution) refresh(tokenResponse tokens.TokenResponse) (*string, error) {
	return refreshGrant(request, tokenResponse.RefreshToken)
}

func (request *AurlExecution) grant() (*string, error) {
	switch request.Profile.GrantType {
	case "authorization_code":	return authCodeGrant(request)
	case "implicit":			return implicitGrant(request)
	case "password":			return resourceOwnerPasswordCredentialsGrant(request)
	case "client_credentials":	return clientCredentialsGrant(request)
	default:					return nil, errors.New("Unknown grant type: " + request.Profile.GrantType)
	}
}

func (request *AurlExecution) doRequest(tokenResponse tokens.TokenResponse, profile profiles.Profile) (*http.Response, error) {
	body := strings.NewReader(*request.Data)
	req, err := http.NewRequest(*request.Method, *request.TargetUrl, body)
	if err != nil {
		return nil, err
	}

	req.Header = *request.Headers
	if req.Header.Get("User-Agent") == "" {
		req.Header.Set("User-Agent", fmt.Sprintf("%s-%s", request.Name, request.Version))
	}
	if req.Header.Get("Content-Type") == "" {
		req.Header.Set("Content-Type", profile.DefaultContentType)
	}
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", tokenResponse.AccessToken))

	if dumpReq, err := httputil.DumpRequestOut(req, true); err == nil {
		log.Printf("Dominant request >>>\n%s\n<<<", string(dumpReq))
	} else {
		log.Printf("Dominant request dump failed: ", err)
	}

	client := &http.Client{
		CheckRedirect: func(redirectRequest *http.Request, via []*http.Request) error {
			log.Printf("Redirect to %s", redirectRequest.URL.String())
			log.Printf("Rriginal request Host = %s", req.URL.String())
			redirectRequest.Header = *request.Headers
			if redirectRequest.Header.Get("User-Agent") == "" {
				redirectRequest.Header.Set("User-Agent", fmt.Sprintf("%s-%s", request.Name, request.Version))
			}
			if matchServer(redirectRequest.URL, req.URL) {
				log.Printf("Propagate authorization header")
				redirectRequest.Header.Set("Authorization", fmt.Sprintf("Bearer %s", tokenResponse.AccessToken))
				return nil
			} else {
				return errors.New("Redirect to non-same origin resource server")
			}
		},
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: *request.Insecure,
			},
		},
	}
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("Dominant request failed")
		return resp, err
	}
	defer resp.Body.Close()

	if dumpResp, err := httputil.DumpResponse(resp, true); err == nil {
		log.Printf("Dominant response >>>\n%s\n<<<", string(dumpResp))
	} else {
		log.Printf("Dominant response dump failed: ", err)
	}

	if resp.StatusCode == 401 {
		return resp, errors.New("401 Unauthorized")
	} else {
		return resp, err
	}
}

func (request *AurlExecution) doPrint(response *http.Response) {
	if response == nil {
		return
	}
	if *request.PrintHeaders {
		log.Println("Printing headers")
		headers, err := json.Marshal(response.Header)
		if err == nil {
			fmt.Println(string(headers))
		} else {
			log.Println("Header marshaling failed: ", err)
			log.Println("Continue...")
			fmt.Println("{}")
		}
	} else {
		log.Println("No printing headers")
	}

	if *request.PrintBody {
		log.Println("Printing body")
		_, err := io.Copy(os.Stdout, response.Body)
		if err != nil {
			log.Println("Error on read: %v", err)
		}
	} else {
		log.Println("No printing body")
	}
}

func matchServer(a *url.URL, b *url.URL) bool {
	if a.Scheme != b.Scheme {
		return false
	}
	if a.Host != b.Host {
		return false
	}
	return true
}


text:
require("kaoscript/register");
module.exports = function() {
	var Weekday = require("./.enum.method.wstt.default.ks.j5k8r9.ksb")().Weekday;
	const day = Weekday.__ks_sttc_fromString_0("monday");
	return {
		Weekday
	};
};


text:
package com.zero.pattern.creator.abstractFactory;

import com.zero.pattern.creator.beans.Sender;

public interface Provider {
	Sender produce();
}


text:
<?php

namespace com\blackmoonit\exceptions;
{//begin namespace

/**
 * 404 error occured, pop us back out to the index.php code for what to load
 */
class FourOhFourExit extends \Exception implements IDebuggableException
{
	private $mDebuggableExceptionTrait;
	public $url = '';

	function __construct($aUrl, $aCode=404, $aPreviousException=NULL) {
		parent::__construct("Page Not Found: ".$aUrl, $aCode, $aPreviousException);
		$this->url = $aUrl;
        $this->mDebuggableExceptionTrait = new DebuggableExceptionTrait($this);
	}

	public function getException()
	{ return $this->mDebuggableExceptionTrait->getException(); }

	public function setContextMsg($aMsg) {
		$this->mDebuggableExceptionTrait->setContextMsg($aMsg);
		return $this; //support chaining
	}

	public function getContextMsg() {
		return $this->mDebuggableExceptionTrait->getContextMsg();
	}

	public function getErrorMsg() {
		return $this->mDebuggableExceptionTrait->getErrorMsg();
	}

	public function getDebugMsg()
	{ return $this->mDebuggableExceptionTrait->getDebugMsg(); }

	public function getDebugDisplay($aMsg=null) {
		return $this->mDebuggableExceptionTrait->getDebugDisplay($aMsg);
	}

	public function getDebugCheck() {
		return $this->mDebuggableExceptionTrait->getDebugCheck();
	}

	public function setDebugCheck($aDebugCheck) {
		return $this->mDebuggableExceptionTrait->setDebugCheck($aDebugCheck);
	}

	public function getCssFileUrl() {
		return $this->mDebuggableExceptionTrait->getCssFileUrl();
	}

	public function setCssFileUrl($aCssFileUrl) {
		return $this->mDebuggableExceptionTrait->setCssFileUrl($aCssFileUrl);
	}

	public function getFileRoot() {
		return $this->mDebuggableExceptionTrait->getFileRoot();
	}

	public function setFileRoot($aFileRoot) {
		return $this->mDebuggableExceptionTrait->setFileRoot($aFileRoot);
	}

	public function debugPrint($aMsg=null) {
		return $this->mDebuggableExceptionTrait->debugPrint($aMsg);
	}

}//end class

}//end namespace


text:
package com.github.dannywe.csv.validation

import javax.validation.Validation

import com.github.dannywe.csv.base.StreamValidator

object JavaxValidator extends StreamValidator(Validation.buildDefaultValidatorFactory.getValidator)


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

using xcordion.api;
using xcordion.util;
using xcordion.lang.csharp;

namespace xcordion.lang.csharp
{
    class MarkupWriter
    {
        private DirectoryInfo outputDirectory;

        public MarkupWriter(DirectoryInfo outputDirectory)
        {
            this.outputDirectory = outputDirectory;
        }

        private void Mkdirs(DirectoryInfo dir)
        {
            if (dir.Parent == null || dir.Parent == dir)
            {
                throw new ArgumentException();
            }
            if (!dir.Parent.Exists)
            {
                Mkdirs(dir.Parent);
            }
            dir.Create();
        }

        public string Write(XmlTestDocument testDocument, string outputPath, Type testClass, ICompatibleList<ResourceReference<XmlTestElement>> resourceRefs)
        {
            if (!outputDirectory.Exists) {
                outputDirectory.Create();
            }

            foreach (ResourceReference<XmlTestElement> resourceRef in resourceRefs)
            {
        	    WriteResourceToOutputDirectory(resourceRef, testClass, outputPath);
            }

            FileInfo outputFile = new FileInfo(outputDirectory.FullName + Path.DirectorySeparatorChar + outputPath);
            if (!outputFile.Directory.Exists)
            {
                Mkdirs(outputFile.Directory);
            }

            File.WriteAllText(outputFile.FullName, testDocument.asXml());

            return outputFile.FullName;
        }

        private void WriteResourceToOutputDirectory(ResourceReference<XmlTestElement> resourceRef, Type testClass, String outputPath) {
            string path = resourceRef.getResourcePath();
            Stream resource = new ResourceFinder(testClass).GetResource(path);
            if (resource == null)
            {
                resource = new ResourceFinder(typeof(MarkupWriter)).GetResource(path);
                if (resource == null)
                {
                    StringBuilder sb = new StringBuilder();
                    string[] resourceNames = typeof(MarkupWriter).Assembly.GetManifestResourceNames();
                    sb.AppendLine("resource count: " + resourceNames.Length);
                    foreach (string s in resourceNames) {
                        sb.AppendLine("resource: " + s);
                    }
                    throw new XcordionBug(sb.ToString() + "Cannot find resource: " + path);
                }
            }

            using (resource)
            {
                path = path.Replace('/', Path.DirectorySeparatorChar);
                while (path[0] == Path.DirectorySeparatorChar)
                {
			        path = path.Substring(1);
		        }

                FileInfo outputFile = new FileInfo(outputDirectory.FullName + Path.DirectorySeparatorChar + path);
                if (!outputFile.Directory.Exists)
                {
                    Mkdirs(outputFile.Directory);
                }

                resourceRef.setResourceReferenceUri(FileUtils.relativePath(outputPath, path, false, Path.DirectorySeparatorChar));

                if (outputFile.Exists && outputFile.LastWriteTime < DateTime.Now.AddSeconds(5))
                {
        	        return;
                }

                byte[] bytes = new byte[resource.Length];
                resource.Read(bytes, 0, bytes.Length);
                File.WriteAllBytes(outputFile.FullName, bytes);
            }

        }

    }
}


text:
var DispatchService = function() {
}

DispatchService.prototype.dispatch = function(commit, callback) {
	// body...
};


text:
#ifndef	_MACHINE_PLATFORM_H_
#define	_MACHINE_PLATFORM_H_

#include <machine/smp.h>
#include <machine/pcpu.h>

struct mem_region {
	vm_offset_t	mr_start;
	vm_size_t	mr_size;
};

void	mem_regions(struct mem_region **, int *, struct mem_region **, int *);
vm_offset_t platform_real_maxaddr(void);

u_long	platform_timebase_freq(struct cpuref *);

int	platform_smp_first_cpu(struct cpuref *);
int	platform_smp_next_cpu(struct cpuref *);
int	platform_smp_get_bsp(struct cpuref *);
int	platform_smp_start_cpu(struct pcpu *);
void	platform_smp_ap_init(void);

const char *installed_platform(void);
void platform_probe_and_attach(void);

#endif	/* _MACHINE_PLATFORM_H_ */


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__new_array_struct_twoIntsStruct_34.cpp
Label Definition File: CWE401_Memory_Leak__new_array.label.xml
Template File: sources-sinks-34.tmpl.cpp
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource:  Allocate data using new[]
 * GoodSource: Point data to a stack buffer
 * Sinks:
 *    GoodSink: call delete[] on data
 *    BadSink : no deallocation of data
 * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function)
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

namespace CWE401_Memory_Leak__new_array_struct_twoIntsStruct_34
{

typedef union
{
    struct _twoIntsStruct * unionFirst;
    struct _twoIntsStruct * unionSecond;
} unionType;

#ifndef OMITBAD

void bad()
{
    struct _twoIntsStruct * data;
    unionType myUnion;
    data = NULL;
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = new struct _twoIntsStruct[100];
    /* Initialize and make use of data */
    data[0].intOne = 0;
    data[0].intTwo = 0;
    printStructLine((twoIntsStruct *)&data[0]);
    myUnion.unionFirst = data;
    {
        struct _twoIntsStruct * data = myUnion.unionSecond;
        /* POTENTIAL FLAW: No deallocation */
        ; /* empty statement needed for some flow variants */
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
    struct _twoIntsStruct * data;
    unionType myUnion;
    data = NULL;
    /* FIX: Use memory allocated on the stack */
    struct _twoIntsStruct dataGoodBuffer[100];
    data = dataGoodBuffer;
    /* Initialize and make use of data */
    data[0].intOne = 0;
    data[0].intTwo = 0;
    printStructLine((twoIntsStruct *)&data[0]);
    myUnion.unionFirst = data;
    {
        struct _twoIntsStruct * data = myUnion.unionSecond;
        /* POTENTIAL FLAW: No deallocation */
        ; /* empty statement needed for some flow variants */
    }
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
    struct _twoIntsStruct * data;
    unionType myUnion;
    data = NULL;
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = new struct _twoIntsStruct[100];
    /* Initialize and make use of data */
    data[0].intOne = 0;
    data[0].intTwo = 0;
    printStructLine((twoIntsStruct *)&data[0]);
    myUnion.unionFirst = data;
    {
        struct _twoIntsStruct * data = myUnion.unionSecond;
        /* FIX: Deallocate memory */
        delete[] data;
    }
}

void good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN

using namespace CWE401_Memory_Leak__new_array_struct_twoIntsStruct_34; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
from ospurge.resources import base
from ospurge.resources.base import BaseServiceResource
from ospurge.resources import glance

class ListObjectsMixin(BaseServiceResource):
    def list_objects(self):
        for container in self.cloud.list_containers():
            for obj in self.cloud.list_objects(container['name']):
                obj['container_name'] = container['name']
                yield obj

class Objects(base.ServiceResource, glance.ListImagesMixin, ListObjectsMixin):
    ORDER = 73

    def check_prerequisite(self):
        return (self.list_images_by_owner() == [] and
                self.cloud.list_volume_backups() == [])

    def list(self):
        for item in self.list_objects():
            yield item

    def delete(self, resource):
        self.cloud.delete_object(resource['container_name'], resource['name'])

    @staticmethod
    def to_str(resource):
        return "Object '{}' from Container '{}'".format(
            resource['name'], resource['container_name'])

class Containers(base.ServiceResource, ListObjectsMixin):
    ORDER = 75

    def check_prerequisite(self):
        return list(self.list_objects()) == []

    def list(self):
        return self.cloud.list_containers()

    def delete(self, resource):
        self.cloud.delete_container(resource['name'])

    @staticmethod
    def to_str(resource):
        return "Container (name='{}')".format(resource['name'])


text:
/**
 * The entire dc.js library is scoped under the **dc** name space. It does not introduce
 * anything else into the global name space.
 *
 * Most `dc` functions are designed to allow function chaining, meaning they return the current chart
 * instance whenever it is appropriate.  The getter forms of functions do not participate in function
 * chaining because they return values that are not the chart, although some,
 * such as {@link #dc.baseMixin+svg .svg} and {@link #dc.coordinateGridMixin+xAxis .xAxis},
 * return values that are themselves chainable d3 objects.
 * @namespace dc
 * @version <%= conf.pkg.version %>
 * @example
 * // Example chaining
 * chart.width(300)
 *      .height(300)
 *      .filter('sunday');
 */
/*jshint -W079*/
var dc = {
    version: '<%= conf.pkg.version %>',
    constants: {
        CHART_CLASS: 'dc-chart',
        DEBUG_GROUP_CLASS: 'debug',
        STACK_CLASS: 'stack',
        DESELECTED_CLASS: 'deselected',
        SELECTED_CLASS: 'selected',
        NODE_INDEX_NAME: '__index__',
        GROUP_INDEX_NAME: '__group_index__',
        DEFAULT_CHART_GROUP: '__default_chart_group__',
        EVENT_DELAY: 40,
        NEGLIGIBLE_NUMBER: 1e-10
    },
    _renderlet: null
};
/*jshint +W079*/

dc.chartRegistry = (function () {
    // chartGroup:string => charts:array
    var _chartMap = {};

    function initializeChartGroup (group) {
        if (!group) {
            group = dc.constants.DEFAULT_CHART_GROUP;
        }

        if (!_chartMap[group]) {
            _chartMap[group] = [];
        }

        return group;
    }

    return {
        has: function (chart) {
            for (var e in _chartMap) {
                if (_chartMap[e].indexOf(chart) >= 0) {
                    return true;
                }
            }
            return false;
        },

        register: function (chart, group) {
            group = initializeChartGroup(group);
            _chartMap[group].push(chart);
        },

        deregister: function (chart, group) {
            group = initializeChartGroup(group);
            for (var i = 0; i < _chartMap[group].length; i++) {
                if (_chartMap[group][i].anchorName() === chart.anchorName()) {
                    _chartMap[group].splice(i, 1);
                    break;
                }
            }
        },

        clear: function (group) {
            if (group) {
                delete _chartMap[group];
            } else {
                _chartMap = {};
            }
        },

        list: function (group) {
            group = initializeChartGroup(group);
            return _chartMap[group];
        }
    };
})();

dc.registerChart = function (chart, group) {
    dc.chartRegistry.register(chart, group);
};

dc.deregisterChart = function (chart, group) {
    dc.chartRegistry.deregister(chart, group);
};

dc.hasChart = function (chart) {
    return dc.chartRegistry.has(chart);
};

dc.deregisterAllCharts = function (group) {
    dc.chartRegistry.clear(group);
};

/**
 * Clear all filters on all charts within the given chart group. If the chart group is not given then
 * only charts that belong to the default chart group will be reset.
 * @memberof dc
 * @name filterAll
 * @param {String} [group]
 */
dc.filterAll = function (group) {
    var charts = dc.chartRegistry.list(group);
    for (var i = 0; i < charts.length; ++i) {
        charts[i].filterAll();
    }
};

/**
 * Reset zoom level / focus on all charts that belong to the given chart group. If the chart group is
 * not given then only charts that belong to the default chart group will be reset.
 * @memberof dc
 * @name refocusAll
 * @param {String} [group]
 */
dc.refocusAll = function (group) {
    var charts = dc.chartRegistry.list(group);
    for (var i = 0; i < charts.length; ++i) {
        if (charts[i].focus) {
            charts[i].focus();
        }
    }
};

/**
 * Re-render all charts belong to the given chart group. If the chart group is not given then only
 * charts that belong to the default chart group will be re-rendered.
 * @memberof dc
 * @name renderAll
 * @param {String} [group]
 */
dc.renderAll = function (group) {
    var charts = dc.chartRegistry.list(group);
    for (var i = 0; i < charts.length; ++i) {
        charts[i].render();
    }

    if (dc._renderlet !== null) {
        dc._renderlet(group);
    }
};

/**
 * Redraw all charts belong to the given chart group. If the chart group is not given then only charts
 * that belong to the default chart group will be re-drawn. Redraw is different from re-render since
 * when redrawing dc tries to update the graphic incrementally, using transitions, instead of starting
 * from scratch.
 * @memberof dc
 * @name redrawAll
 * @param {String} [group]
 */
dc.redrawAll = function (group) {
    var charts = dc.chartRegistry.list(group);
    for (var i = 0; i < charts.length; ++i) {
        charts[i].redraw();
    }

    if (dc._renderlet !== null) {
        dc._renderlet(group);
    }
};

/**
 * If this boolean is set truthy, all transitions will be disabled, and changes to the charts will happen
 * immediately
 * @memberof dc
 * @name disableTransitions
 * @type {Boolean}
 * @default false
 */
dc.disableTransitions = false;

dc.transition = function (selections, duration, callback, name) {
    if (duration <= 0 || duration === undefined || dc.disableTransitions) {
        return selections;
    }

    var s = selections
        .transition(name)
        .duration(duration);

    if (typeof(callback) === 'function') {
        callback(s);
    }

    return s;
};

/* somewhat silly, but to avoid duplicating logic */
dc.optionalTransition = function (enable, duration, callback, name) {
    if (enable) {
        return function (selection) {
            return dc.transition(selection, duration, callback, name);
        };
    } else {
        return function (selection) {
            return selection;
        };
    }
};

// See http://stackoverflow.com/a/20773846
dc.afterTransition = function (transition, callback) {
    if (transition.empty() || !transition.duration) {
        callback.call(transition);
    } else {
        var n = 0;
        transition
            .each(function () { ++n; })
            .each('end', function () {
                if (!--n) {
                    callback.call(transition);
                }
            });
    }
};

/**
 * @name units
 * @memberof dc
 * @type {{}}
 */
dc.units = {};

/**
 * The default value for {@link #dc.coordinateGridMixin+xUnits .xUnits} for the
 * {@link #dc.coordinateGridMixin Coordinate Grid Chart} and should
 * be used when the x values are a sequence of integers.
 * It is a function that counts the number of integers in the range supplied in its start and end parameters.
 * @name integers
 * @memberof dc.units
 * @see {@link #dc.coordinateGridMixin+xUnits coordinateGridMixin.xUnits}
 * @example
 * chart.xUnits(dc.units.integers) // already the default
 * @param {Number} start
 * @param {Number} end
 * @return {Number}
 */
dc.units.integers = function (start, end) {
    return Math.abs(end - start);
};

/**
 * This argument can be passed to the {@link #dc.coordinateGridMixin+xUnits .xUnits} function of the to
 * specify ordinal units for the x axis. Usually this parameter is used in combination with passing
 * {@link https://github.com/mbostock/d3/wiki/Ordinal-Scales d3.scale.ordinal} to
 * {@link #dc.coordinateGridMixin+x .x}.
 * It just returns the domain passed to it, which for ordinal charts is an array of all values.
 * @name ordinal
 * @memberof dc.units
 * @see {@link https://github.com/mbostock/d3/wiki/Ordinal-Scales d3.scale.ordinal}
 * @see {@link #dc.coordinateGridMixin+xUnits coordinateGridMixin.xUnits}
 * @see {@link #dc.coordinateGridMixin+x coordinateGridMixin.x}
 * @example
 * chart.xUnits(dc.units.ordinal)
 *      .x(d3.scale.ordinal())
 * @param {*} start
 * @param {*} end
 * @param {Array<String>} domain
 * @return {Array<String>}
 */
dc.units.ordinal = function (start, end, domain) {
    return domain;
};

/**
 * @name fp
 * @memberof dc.units
 * @type {{}}
 */
dc.units.fp = {};
/**
 * This function generates an argument for the {@link #dc.coordinateGridMixin Coordinate Grid Chart}
 * {@link #dc.coordinateGridMixin+xUnits .xUnits} function specifying that the x values are floating-point
 * numbers with the given precision.
 * The returned function determines how many values at the given precision will fit into the range
 * supplied in its start and end parameters.
 * @name precision
 * @memberof dc.units.fp
 * @see {@link #dc.coordinateGridMixin+xUnits coordinateGridMixin.xUnits}
 * @example
 * // specify values (and ticks) every 0.1 units
 * chart.xUnits(dc.units.fp.precision(0.1)
 * // there are 500 units between 0.5 and 1 if the precision is 0.001
 * var thousandths = dc.units.fp.precision(0.001);
 * thousandths(0.5, 1.0) // returns 500
 * @param {Number} precision
 * @return {Function} start-end unit function
 */
dc.units.fp.precision = function (precision) {
    var _f = function (s, e) {
        var d = Math.abs((e - s) / _f.resolution);
        if (dc.utils.isNegligible(d - Math.floor(d))) {
            return Math.floor(d);
        } else {
            return Math.ceil(d);
        }
    };
    _f.resolution = precision;
    return _f;
};

dc.round = {};
dc.round.floor = function (n) {
    return Math.floor(n);
};
dc.round.ceil = function (n) {
    return Math.ceil(n);
};
dc.round.round = function (n) {
    return Math.round(n);
};

dc.override = function (obj, functionName, newFunction) {
    var existingFunction = obj[functionName];
    obj['_' + functionName] = existingFunction;
    obj[functionName] = newFunction;
};

dc.renderlet = function (_) {
    if (!arguments.length) {
        return dc._renderlet;
    }
    dc._renderlet = _;
    return dc;
};

dc.instanceOfChart = function (o) {
    return o instanceof Object && o.__dcFlag__ && true;
};


text:
{% extends "wagtailadmin/base.html" %}
{% load wagtailadmin_tags %}
{% load compress i18n %}
{% load gravatar %}

{% block extra_css %}
    {% compress css %}
        <link rel="stylesheet" href="{{ STATIC_URL }}wagtailadmin/scss/layouts/styleguide.scss" type="text/x-scss" />
    {% endcompress %}
{% endblock %}

{% block titletag %}{% trans 'Styleguide' %}{% endblock %}
{% block bodyclass %}styleguide{% endblock %}

{% block content %}
    {% trans "Styleguide" as title_trans %}
    {% include "wagtailadmin/shared/header.html" with title=title_trans %}

Contents

Colour palette

Typography

Listings

Buttons

Dropdown buttons

Header

Forms

Page editor

Tabs

Breadcrumbs

Misc formatters

Icons

Colour palette

color-teal

color-teal-darker

color-teal-dark

color-salmon

color-salmon-light

color-grey-1

color-grey-1-1

color-grey-2

color-grey-3

color-grey-4

color-grey-5

color-red

color-orange

color-green

Typography

This is an h1

This is an h2

This is an h3

This is an h4

This is an h5

This is a paragraph

These are

items in an

unordered list

These are

items in an

ordered list

            This is an example of code

Listings

table listing

                        Heading 1
                        Heading 2
                        Heading 3

TD with title class

                        Regular listing TD
                        Regular listing TD

TD with title class

                        Regular listing TD
                        Regular listing TD

ul listing

List item

List item

List item

Listings used for choosing a list item

                        Heading 1
                        Heading 2
                        Heading 3

TD with title class

                        Regular listing TD
                        Regular listing TD

TD with title class

                        Regular listing TD
                        Regular listing TD

Buttons

            button

            button-secondary

            yes

            no / serious

            bicolor with icon

            button-small

            bicolo button-small

            mixed 1

            mixed 2

button on a div

Buttons must have interaction possible (i.e be an input or button element) to get a suitable hover cursor

            <button>button</button>

            <button class="button-small">small button</button>

            <button class="bicolor icon icon-plus">bicolor with icon</button>

            <input type="submit" class="bicolor icon icon-plus" value="bicolor only supported on button elements" />

            <button class="icon icon-view">button</button>

Dropdown buttons

                        <input type="button" value="drop down" class="button" />

items should not exceed button width

item 2

                        <input type="button" value="drop down" class="button" />

Items in this list do not match button width

item 2

                        <input type="button" value="drop up" class="button" />

item 1

item 2

                        <button value="drop up" class="button icon icon-view">icon dropup</button>

item 1

item 2

                        Link button

items should not exceed button width

item 2

                    <button>button for comparison of height</button>

Header

            {% include "wagtailadmin/shared/header.html" with title=title_trans %}

            {% include "wagtailadmin/shared/header.html" with title=title_trans add_link="wagtailimages_add_image" icon="image" add_text="button" search_url="wagtailimages_index" %}

Forms

            <form>

                    {% for field in example_form %}
                        {% if field.name == 'file' %}
                            {% include "wagtailimages/images/_file_field.html" %}
                        {% elif field.name == 'date' %}
                            {% include "wagtailadmin/shared/field_as_li.html" with input_classes="iconfield icon-date" %}
                        {% else %}
                            {% include "wagtailadmin/shared/field_as_li.html" %}
                        {% endif %}
                    {% endfor %}

<input type="submit" value="{% trans 'Save' %}" />{% trans "Delete image" %}

            </form>

TODO: Date picker

TODO: Time picker

TODO: Datetime picker

TODO: Rich text input

TODO: Page chooser

TODO: Image chooser

TODO: Document chooser

TODO: Snippet chooser

Page editor

Tabs

Tab 1

Tab 2

Tabs are currently only used following headers, where they often appear merged with the bottom of the header:

            {% include "wagtailadmin/shared/header.html" with title=title_trans merged=1 %}

Tab1

Tab2

Tabs can also indicate errors:

            {% include "wagtailadmin/shared/header.html" with title=title_trans merged=1 %}

Tab1

Tab2

Breadcrumbs

Home

Various

Subpages

There is a max length of this many

Misc formatters

Avatar icons

 Gravatar set

 Gravatar not set

Status tags

Primary tag

Secondary tag

Icons

wagtail

wagtail-inverse

cogs

doc-empty-inverse

doc-empty

edit

arrow-up

arrow-down

search

cross

folder-open-1

folder-inverse

mail

arrows-up-down

locked

unlocked

arrow-right

doc-full / file-text-alt

image / picture

doc-full-inverse

folder

plus

tag

folder-open-inverse

cog

tick

user

arrow-left

tick-inverse

plus-inverse

snippet

bold

italic

undo

repeat

list-ol

list-ul

link

radio-full

radio-empty

arrow-up-big

arrow-down-big

group

media

horizontalrule

password

download

order

grip

home

order-down

order-up

bin

spinner
 spinner

pick

redirect

view

collapse-up

collapse-down

help

warning

success

date

time

form

{% endblock %}

{% block extra_js %}

{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.ComponentModel;

namespace ExifLibrary
{
    /// <summary>
    /// Represents the binary view of a TIFF file.
    /// </summary>
    public class TIFFFile : ImageFile
    {
        #region Properties
        /// <summary>
        /// Gets the TIFF header.
        /// </summary>
        public TIFFHeader TIFFHeader { get; private set; }
        /// <summary>
        /// Gets the image file directories.
        /// </summary>
        public List<ImageFileDirectory> IFDs { get; private set; }
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the <see cref="JPEGFile"/> class from the
        /// specified data stream.
        /// </summary>
        /// <param name="stream">A <see cref="Sytem.IO.Stream"/> that contains image data.</param>
        /// <param name="encoding">The encoding to be used for text metadata when the source encoding is unknown.</param>
        protected internal TIFFFile(Stream stream, System.Text.Encoding encoding)
        {
            Format = ImageFileFormat.TIFF;
            IFDs = new List<ImageFileDirectory>();
            Encoding = encoding;

            // Read the entire stream
            byte[] data = Utility.GetStreamBytes(stream);

            // Read the TIFF header
            TIFFHeader = TIFFHeader.FromBytes(data, 0);
            uint nextIFDOffset = TIFFHeader.IFDOffset;
            if (nextIFDOffset == 0)
                throw new NotValidTIFFileException("The first IFD offset is zero.");

            // Read IFDs in order
            while (nextIFDOffset != 0)
            {
                ImageFileDirectory ifd = ImageFileDirectory.FromBytes(data, nextIFDOffset, TIFFHeader.ByteOrder);
                nextIFDOffset = ifd.NextIFDOffset;
                IFDs.Add(ifd);
            }

            // Process IFDs
            // TODO: Add support for multiple frames
            foreach (ImageFileDirectoryEntry field in IFDs[0].Fields)
            {
                Properties.Add(ExifPropertyFactory.Get(field.Tag, field.Type, field.Count, field.Data, BitConverterEx.SystemByteOrder, IFD.Zeroth, Encoding));
            }
        }
        #endregion

        #region Instance Methods
        /// <summary>
        /// Saves the <see cref="ImageFile"/> to the given stream.
        /// </summary>
        /// <param name="stream">The data stream used to save the image.</param>
        public override void Save(Stream stream)
        {
            BitConverterEx conv = BitConverterEx.SystemEndian;

            // Write TIFF header
            uint ifdoffset = 8;
            // Byte order
            stream.Write((BitConverterEx.SystemByteOrder == BitConverterEx.ByteOrder.LittleEndian ? new byte[] { 0x49, 0x49 } : new byte[] { 0x4D, 0x4D }), 0, 2);
            // TIFF ID
            stream.Write(conv.GetBytes((ushort)42), 0, 2);
            // Offset to 0th IFD, will be corrected below
            stream.Write(conv.GetBytes(ifdoffset), 0, 4);

            // Write IFD sections
            for (int i = 0; i < IFDs.Count; i++)
            {
                ImageFileDirectory ifd = IFDs[i];

                // Save the location of IFD offset
                long ifdLocation = stream.Position - 4;

                // Write strips first
                byte[] stripOffsets = new byte[4 * ifd.Strips.Count];
                byte[] stripLengths = new byte[4 * ifd.Strips.Count];
                uint stripOffset = ifdoffset;
                for (int j = 0; j < ifd.Strips.Count; j++)
                {
                    byte[] stripData = ifd.Strips[j].Data;
                    byte[] oBytes = BitConverter.GetBytes(stripOffset);
                    byte[] lBytes = BitConverter.GetBytes((uint)stripData.Length);
                    Array.Copy(oBytes, 0, stripOffsets, 4 * j, 4);
                    Array.Copy(lBytes, 0, stripLengths, 4 * j, 4);
                    stream.Write(stripData, 0, stripData.Length);
                    stripOffset += (uint)stripData.Length;
                }

                // Remove old strip tags
                for (int j = ifd.Fields.Count - 1; j > 0; j--)
                {
                    ushort tag = ifd.Fields[j].Tag;
                    if (tag == 273 || tag == 279)
                        ifd.Fields.RemoveAt(j);
                }
                // Write new strip tags
                ifd.Fields.Add(new ImageFileDirectoryEntry(273, 4, (uint)ifd.Strips.Count, stripOffsets));
                ifd.Fields.Add(new ImageFileDirectoryEntry(279, 4, (uint)ifd.Strips.Count, stripLengths));

                // Write fields after strips
                ifdoffset = stripOffset;

                // Correct IFD offset
                long currentLocation = stream.Position;
                stream.Seek(ifdLocation, SeekOrigin.Begin);
                stream.Write(conv.GetBytes(ifdoffset), 0, 4);
                stream.Seek(currentLocation, SeekOrigin.Begin);

                // Offset to field data
                uint dataOffset = ifdoffset + 2 + (uint)ifd.Fields.Count * 12 + 4;

                // Field count
                stream.Write(conv.GetBytes((ushort)ifd.Fields.Count), 0, 2);

                // Fields
                foreach (ImageFileDirectoryEntry field in ifd.Fields)
                {
                    // Tag
                    stream.Write(conv.GetBytes(field.Tag), 0, 2);
                    // Type
                    stream.Write(conv.GetBytes(field.Type), 0, 2);
                    // Count
                    stream.Write(conv.GetBytes(field.Count), 0, 4);

                    // Field data
                    byte[] data = field.Data;
                    if (data.Length <= 4)
                    {
                        stream.Write(data, 0, data.Length);
                        for (int j = data.Length; j < 4; j++)
                            stream.WriteByte(0);
                    }
                    else
                    {
                        stream.Write(conv.GetBytes(dataOffset), 0, 4);
                        long currentOffset = stream.Position;
                        stream.Seek(dataOffset, SeekOrigin.Begin);
                        stream.Write(data, 0, data.Length);
                        dataOffset += (uint)data.Length;
                        stream.Seek(currentOffset, SeekOrigin.Begin);
                    }
                }

                // Offset to next IFD
                ifdoffset = dataOffset;
                stream.Write(conv.GetBytes(i == IFDs.Count - 1 ? 0 : ifdoffset), 0, 4);
            }
        }

        /// <summary>
        /// Converts the <see cref="ImageFile"/> to a <see cref="System.Drawing.Image"/>.
        /// </summary>
        /// <returns>Returns a <see cref="System.Drawing.Image"/> containing image data.</returns>
        public override Image ToImage()
        {
            MemoryStream stream = new MemoryStream();
            Save(stream);
            return Image.FromStream(stream);
        }
        #endregion
    }
}


text:
package stdtypes

import (
	"io/ioutil"
	"sync"
	"testing"

	"github.com/gogo/protobuf/proto"
)

func TestConcurrentTextMarshal(t *testing.T) {
	// Verify that there are no race conditions when calling
	// TextMarshaler.Marshal on a protobuf message that contains a StdDuration

	std := StdTypes{}
	var wg sync.WaitGroup

	tm := proto.TextMarshaler{}

	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			err := tm.Marshal(ioutil.Discard, &std)
			if err != nil {
				t.Fatal(err)
			}
		}()
	}
	wg.Wait()
}


text:
<?php

use LibCloud\Compute\ComputeFactory;
use Symfony\Component\HttpFoundation\ParameterBag;

require_once(__DIR__ . '/../common.php');

/**
 * Digital Ocean
 */
$provider = ComputeFactory::getProvider('digital_ocean', '');

// get all nodes
$nodes = $provider->listNodes();

// we can get one node by providing nodeId to listNodes() method
$node = $provider->listNodes(123123);

// we can perform next actions with Node
$provider->shutdownNode($node); //
$provider->bootNode($node); //
$provider->rebootNode($node); //
$provider->destroyNode($node);

// clone method not supported by digital ocean api

// create Node we must provide size (size in digitalocean),
// location (region in digitalocean) and image (image in digitalocean)
$sizes = $provider->listSizes(); // list digitalocean sizes
$locations = $provider->listLocations(); // list digitalocean regions
$images = $provider->listImages(); // list digitalocean images
$createdNode = $provider->createNode(
    new ParameterBag(['size' => $sizes[0], 'location' => $locations[0], 'image' => $images[0]])
);

// resize. parameters Node and new size
$provider->resizeNode($createdNode, $sizes[1]);

// update
// digital ocean api has a few more methods to work with Node
$provider->updateNode($node, new ParameterBag(['action' => 'rename', 'name' => 'new-droplet-label']));
$provider->updateNode($node, new ParameterBag(['action' => 'passwordReset']));
$provider->updateNode($node, new ParameterBag(['action' => 'enableBackups']));
$provider->updateNode($node, new ParameterBag(['action' => 'disableBackups']));
$provider->updateNode($node, new ParameterBag(['action' => 'enableIpv6']));
$provider->updateNode($node, new ParameterBag(['action' => 'enablePrivateNetworking']));