text:
package com.nikoblag.android.potato.preferences;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.preference.Preference;
import android.util.AttributeSet;
import android.widget.Toast;
import com.nikoblag.android.potato.util.Const;
import com.nikoblag.android.potato.util.Util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

public class DownloadCrosswordsPreference extends Preference {

    private ProgressDialog progressDialog;
    private DownloadTask downloadTask;

    public DownloadCrosswordsPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onClick() {
        super.onClick();

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setTitle("In progress...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(0);
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                downloadTask.cancel(true);
            }
        });

        downloadTask = new DownloadTask(getContext());
        downloadTask.execute();
    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager.WakeLock wl = Util.newWakeLock(context);
            wl.acquire();

            Properties props = new Properties();

            try {
                props.load(Util.downloadAndOpenFile(context, Const.POTATO_METAFILE_URL, ".meta"));
            } catch (Exception e) {
                wl.release();
                return e.getMessage();
            }

            int max = Integer.parseInt(props.getProperty("max_id"));

            try {
                for (int i = 1; i <= max; i++) {
                    String filename = i + ".jcw";
                    InputStream input = null;
                    OutputStream output = null;
                    HttpURLConnection connection = null;
                    try {
                        URL url = new URL(Const.POTATO_DROPBOX_URL + filename);
                        connection = (HttpURLConnection) url.openConnection();
                        connection.connect();

                        // expect HTTP 200 OK, so we don't mistakenly save error report
                        // instead of the file
                        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                            return "Server returned HTTP " + connection.getResponseCode()
                                    + " " + connection.getResponseMessage();

                        int fileLength = connection.getContentLength();

                        // download the file
                        input = connection.getInputStream();
                        output = context.openFileOutput(filename, Context.MODE_PRIVATE);

                        byte data[] = new byte[4096];
                        long total = 0;
                        int count;
                        while ((count = input.read(data)) != -1) {
                            // allow canceling with back button
                            if (isCancelled())
                                return null;

                            total += count;

                            // publishing the progress....
                            if (fileLength > 0)
                                publishProgress((int) ((total * 100 / fileLength) * ((float) i / max)), i, max);
                            else
                                publishProgress(i * 100 / max, i, max);

                            output.write(data, 0, count);
                        }
                    } catch (Exception e) {
                        return e.toString();
                    } finally {
                        try {
                            if (output != null)
                                output.close();
                            if (input != null)
                                input.close();
                        }
                        catch (IOException ignored) { }

                        if (connection != null)
                            connection.disconnect();
                    }
                }
            } finally {
                wl.release();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            progressDialog.setIndeterminate(false);
            progressDialog.setMax(progress[2]);
            progressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            progressDialog.dismiss();

            if (result != null)
                Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, "Download complete", Toast.LENGTH_SHORT).show();

            notifyChanged();
        }

        @Override
        protected void onCancelled() {
            notifyChanged();
        }
    }
}


text:
> Syntax highlight JavaScript strings for output in terminals.

See our website [@babel/highlight](https://babeljs.io/docs/en/babel-highlight) for more information.

## Install

Using npm:

```sh
npm install --save-dev @babel/highlight
```

or using yarn:

```sh
yarn add @babel/highlight --dev
```

redpajama_set_name: RedPajamaGithub


text:
const Logger = require('./logger');

const Preferences = {};
const PREFIX = 'KEY';
const SEP = '|';

const keyName = (short) => `${PREFIX}${SEP}${short}`

const removePreference = (key) => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.remove(key, () => {
      resolve(true);
    });
  });
};

const setPreferences = (pairs) => {
  return new Promise((resolve, reject) => {
    const preferences = {};
    pairs.forEach(item => {
      const key = keyName(item.short);
      preferences[key] = item;
    });
    chrome.storage.sync.set(preferences, () => {
      resolve(true);
    });
  });
};

const getPreference = (key, defaultValue) => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get({key: defaultValue}, (item) => {
      resolve(item[key]);
    })
  });
};

const getAllPreferences = () => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get(null /* gets everything */, (item) => {
      const prefixed = Object.keys(item);
      const items = prefixed.map(key => item[key]);
      resolve(items);
    });
  });
};

const matchPreference = (fragment, property) => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.get(null /* gets everything */, (item) => {
      // all keys
      const prefixed = Object.keys(item);
      const itemProps = prefixed.filter(key => item[key][property]);
      const filtered = itemProps.filter(key => key.indexOf(fragment) >= 0);
      const items = filtered.map(key => item[key]);
      resolve(items);
    });
  });
};

const clear = () => {
  return new Promise((resolve, reject) => {
    chrome.storage.sync.clear(() => {
      resolve(true);
    });
  });
};

Preferences.addMultiple = (...pairs) => {
  return setPreferences(...pairs);
};

Preferences.add = (short, full) => {
  const pairs = [
    {short: short, full: full}
  ];
  return Preferences.addMultiple(pairs);
};

Preferences.remove = (short) => {
  return removePreference(keyName(short));
};

Preferences.match = (fragment) => {
  return matchPreference(fragment, 'short');
};

Preferences.get = (short, defaultValue) => {
  return getPreference(keyName(short), defaultValue);
}

Preferences.all = () => {
  return getAllPreferences();
};

Preferences.clear = () => clear();

module.exports = Preferences;


text:
from __future__ import division, print_function, unicode_literals

# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#

testinfo = "s, t 1.1, s, t 2.1, s, t 3.1, s, q"
tags = "schedule_interval, position"

import cocos
from cocos.director import director
from cocos.sprite import Sprite
import pyglet
import random
from math import sin, cos

class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super( TestLayer, self ).__init__()

        self.sprite = Sprite('grossini.png')
        self.add( self.sprite  )

        w,h = director.get_window_size()
        self.coords_from_corner = [(0, 0), (0, h), (w, h), (w, 0)]
        self.corner = 0
        self.schedule_interval( self.change_sprite_pos, 1 )
        self.change_sprite_pos(0.0)
        self.schedule(lambda x:0)

    def change_sprite_pos(self, dt):
        self.sprite.position = self.coords_from_corner[self.corner]
        self.corner = (self.corner + 1) % len(self.coords_from_corner)

description = """
Grossini sprite will change position each second, showing at the screen corners
"""

def main():
    print(description)
    director.init()
    test_layer = TestLayer ()
    main_scene = cocos.scene.Scene (test_layer)
    director.run (main_scene)

if __name__ == '__main__':
    main()


text:
using namespace Glyph3;
//--------------------------------------------------------------------------------
ShaderResourceViewDX11::ShaderResourceViewDX11( ShaderResourceViewComPtr pView )
{
	m_pShaderResourceView = pView;
}
//--------------------------------------------------------------------------------
ShaderResourceViewDX11::~ShaderResourceViewDX11()
{
}
//--------------------------------------------------------------------------------
ID3D11ShaderResourceView* ShaderResourceViewDX11::GetSRV()
{
	return( m_pShaderResourceView.Get() );
}
//--------------------------------------------------------------------------------


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * \class document::MapFieldValue
 * \ingroup fieldvalue
 *
 * \brief A fieldvalue containing fieldvalue <-> weight mappings.
 */
#pragma once

#include "fieldvalue.h"
#include <vespa/vespalib/util/polymorphicarray.h>
#include <vespa/vespalib/stllike/hash_map.h>

#define VESPA_DLL_LOCAL  __attribute__ ((visibility("hidden")))

namespace document {

namespace mapfieldvalue {
    class HashMap;
}
class MapFieldValue final : public FieldValue
{
public:
    using IArray=vespalib::IArrayT<FieldValue>;
    using HashMapUP = std::unique_ptr<mapfieldvalue::HashMap>;
private:
    const MapDataType *_type;
    size_t             _count;
    IArray::UP         _keys;
    IArray::UP         _values;
    std::vector<bool>  _present;
    mutable HashMapUP  _lookupMap;

    virtual bool addValue(const FieldValue& fv);
    virtual bool containsValue(const FieldValue& fv) const { return contains(fv); }
    virtual bool removeValue(const FieldValue& fv) { return erase(fv); }
    bool checkAndRemove(const FieldValue& key, fieldvalue::ModificationStatus status,
                        bool wasModified, std::vector<const FieldValue*>& keysToRemove) const;
    fieldvalue::ModificationStatus onIterateNested(PathRange nested, fieldvalue::IteratorHandler & handler) const override;
    // Utility method to avoid constant explicit casting
    const MapDataType& getMapType() const { return *_type; }

    void verifyKey(const FieldValue & key) const __attribute__((noinline));
    void verifyValue(const FieldValue & value) const __attribute__((noinline));
    size_t nextPresent(size_t index) const {
        for (; index < _present.size() && !_present[index]; ++index);
        return index;
    }
    VESPA_DLL_LOCAL HashMapUP buildLookupMap() const __attribute__((noinline));
    VESPA_DLL_LOCAL void ensureLookupMap() const;
    VESPA_DLL_LOCAL ssize_t findIndex(const FieldValue& fv) const;
public:
    typedef std::unique_ptr<MapFieldValue> UP;
    class iterator {
        typedef std::pair<FieldValue *, FieldValue *> pair;
    public:
        iterator(MapFieldValue & map, size_t index) : _map(&map), _index(index) { }
        bool operator == (const iterator & rhs) const { return _map == rhs._map && _index == rhs._index; }
        bool operator != (const iterator & rhs) const { return _map != rhs._map || _index != rhs._index; }
        iterator& operator++() { _index = _map->nextPresent(_index+1); return *this; }
        const pair & operator * () const { setCurr(); return _current; }
        const pair * operator -> () const { setCurr(); return &_current; }
        size_t offset() const { return _index; }
    private:
        void setCurr() const {
             _current.first  = &(*_map->_keys)[_index];
             _current.second = &(*_map->_values)[_index];
        }
        MapFieldValue *_map;
        size_t         _index;
        mutable pair   _current;
    };
    class const_iterator {
    public:
        typedef std::pair<const FieldValue *, const FieldValue *> pair;
        const_iterator(const MapFieldValue & map, size_t index) : _map(&map), _index(index) { }
        bool operator == (const const_iterator & rhs) const { return _map == rhs._map && _index == rhs._index; }
        bool operator != (const const_iterator & rhs) const { return _map != rhs._map || _index != rhs._index; }
        const_iterator& operator++() {  _index = _map->nextPresent(_index+1); return *this; }
        const pair & operator * () const { setCurr(); return _current; }
        const pair * operator -> () const { setCurr(); return &_current; }
    private:
        void setCurr() const {
             _current.first  = &(*_map->_keys)[_index];
             _current.second = &(*_map->_values)[_index];
        }
        const MapFieldValue *_map;
        size_t               _index;
        mutable pair         _current;
    };

    MapFieldValue(const DataType &mapType);
    virtual ~MapFieldValue();

    MapFieldValue(const MapFieldValue & rhs);
    MapFieldValue & operator = (const MapFieldValue & rhs);
    void swap(MapFieldValue & rhs);

    void accept(FieldValueVisitor &visitor) override { visitor.visit(*this); }
    void accept(ConstFieldValueVisitor &visitor) const override { visitor.visit(*this); }

    /**
     * These methods for insertion will check for uniqueness.
     **/
    bool put(FieldValue::UP key, FieldValue::UP value);
    bool put(const FieldValue& key, const FieldValue& value);
    bool insertVerify(const FieldValue& key, const FieldValue& value);
    bool insert(FieldValue::UP key, FieldValue::UP value);

    /**
     * This will just append the values to the set, assuming that the
     * new entry is not a duplicate.
     **/
    void push_back(FieldValue::UP key, FieldValue::UP value);
    void push_back(const FieldValue & key, const FieldValue & value);

    FieldValue::UP get(const FieldValue& key) const;
    bool erase(const FieldValue& key);
    bool contains(const FieldValue& key) const;

    // CollectionFieldValue methods kept for compatability's sake
    virtual bool isEmpty() const { return _count == 0; }
    virtual size_t size() const { return _count; }
    virtual void clear();
    void reserve(size_t sz);
    void resize(size_t sz);

    fieldvalue::ModificationStatus iterateNestedImpl(PathRange nested, fieldvalue::IteratorHandler & handler,
                                                     const FieldValue& complexFieldValue) const;

    // FieldValue implementation
    FieldValue& assign(const FieldValue&) override;
    MapFieldValue* clone() const override { return new MapFieldValue(*this); }
    int compare(const FieldValue&) const override;
    void print(std::ostream& out, bool verbose, const std::string& indent) const override;
    const DataType *getDataType() const override;
    void printXml(XmlOutputStream& out) const override;

    const_iterator begin() const { return const_iterator(*this, nextPresent(0)); }
    iterator begin() { return iterator(*this, nextPresent(0)); }

    const_iterator end() const { return const_iterator(*this, _present.size()); }
    iterator end() { return iterator(*this, _present.size()); }

    const_iterator find(const FieldValue& fv) const;
    iterator find(const FieldValue& fv);

    bool has_no_erased_keys() const {
        return (_keys->size() == _count) && (_values->size() == _count);
    }

    /**
     * Returns the key-value pair at the given position in the underlying arrays.
     *
     * Note: Should only be used when has_no_erased_keys() returns true.
     * Otherwise you might access elements that are conceptually removed.
     */
    const_iterator::pair operator[](size_t idx) const {
        return const_iterator::pair(&(*_keys)[idx], &(*_values)[idx]);
    }

    FieldValue::UP createValue() const;
};

}  // namespace document


text:
define(
({
// local representation of all CSS3 named colors, companion to dojo.colors.  To be used where descriptive information
// is required for each color, such as a palette widget, and not for specifying color programatically.
	//Note: due to the SVG 1.0 spec additions, some of these are alternate spellings for the same color (e.g. gray / grey).
	//TODO: should we be using unique rgb values as keys instead and avoid these duplicates, or rely on the caller to do the reverse mapping?
	aliceblue: "alice blue",
	antiquewhite: "antique white",
	aqua: "aqua",
	aquamarine: "aquamarine",
	azure: "azuriu",
	beige: "bej",
	bisque: "bisque",
	black: "negru",
	blanchedalmond: "blanched almond",
	blue: "albastru",
	blueviolet: "albastru-violet",
	brown: "brun",
	burlywood: "burlywood",
	cadetblue: "albastru cadet",
	chartreuse: "chartreuse",
	chocolate: "ciocolată",
	coral: "coral",
	cornflowerblue: "cornflower blue",
	cornsilk: "cornsilk",
	crimson: "stacojiu",
	cyan: "cyan",
	darkblue: "albastru închis",
	darkcyan: "cyan închis",
	darkgoldenrod: "goldenrod închis",
	darkgray: "gri închis",
	darkgreen: "verde închis",
	darkgrey: "gri închis", // same as darkgray
	darkkhaki: "kaki închis",
	darkmagenta: "magenta închis",
	darkolivegreen: "verde măslină închis",
	darkorange: "portocaliu închis",
	darkorchid: "orchid închis",
	darkred: "roşu închis",
	darksalmon: "somon închis",
	darkseagreen: "verde marin închis",
	darkslateblue: "albastru ardezie închis",
	darkslategray: "gri ardezie închis",
	darkslategrey: "gri ardezie închis", // same as darkslategray
	darkturquoise: "turcoaz închis",
	darkviolet: "violet închis",
	deeppink: "roz profund",
	deepskyblue: "albastru cer profund",
	dimgray: "dim gray",
	dimgrey: "dim gray", // same as dimgray
	dodgerblue: "dodger blue",
	firebrick: "cărămiziu aprins",
	floralwhite: "floral white",
	forestgreen: "forest green",
	fuchsia: "fuchsia",
	gainsboro: "gainsboro",
	ghostwhite: "ghost white",
	gold: "auriu",
	goldenrod: "goldenrod",
	gray: "gri",
	green: "verde",
	greenyellow: "verde-gălbui",
	grey: "gri", // same as gray
	honeydew: "honeydew",
	hotpink: "roz aprins",
	indianred: "roşu indian",
	indigo: "indigo",
	ivory: "ivoriu",
	khaki: "kaki",
	lavender: "lavandă",
	lavenderblush: "lavender blush",
	lawngreen: "lawn green",
	lemonchiffon: "lemon chiffon",
	lightblue: "albastru deschis",
	lightcoral: "coral deschis",
	lightcyan: "cyan deschis",
	lightgoldenrodyellow: "goldenrod gălbui deschis",
	lightgray: "gri deschis",
	lightgreen: "verde dschis",
	lightgrey: "gri deschis", // same as lightgray
	lightpink: "roz deschis",
	lightsalmon: "somon deschis",
	lightseagreen: "verde marin deschis",
	lightskyblue: "albastru cer deschis",
	lightslategray: "gri ardezie deschis",
	lightslategrey: "gri ardezie deschis", // same as lightslategray
	lightsteelblue: "albastru metalic deschis",
	lightyellow: "galben deschis",
	lime: "lime",
	limegreen: "verde lime",
	linen: "linen",
	magenta: "magenta",
	maroon: "maro",
	mediumaquamarine: "aquamarin mediu",
	mediumblue: "albastru mediu",
	mediumorchid: "orchid mediu",
	mediumpurple: "purpuriu mediu",
	mediumseagreen: "verde marin mediu",
	mediumslateblue: "albastru ardezie mediu",
	mediumspringgreen: "verde primăvară mediu",
	mediumturquoise: "turcoaz mediu",
	mediumvioletred: "roşu-violet mediu",
	midnightblue: "midnight blue",
	mintcream: "mint cream",
	mistyrose: "misty rose",
	moccasin: "moccasin",
	navajowhite: "navajo white",
	navy: "navy",
	oldlace: "old lace",
	olive: "oliv",
	olivedrab: "oliv şters",
	orange: "portocaliu",
	orangered: "roşu portocaliu",
	orchid: "orchid",
	palegoldenrod: "goldenrod pal",
	palegreen: "verde pal",
	paleturquoise: "turcoaz pal",
	palevioletred: "roşu-violet pal",
	papayawhip: "papaya whip",
	peachpuff: "peach puff",
	peru: "peru",
	pink: "roz",
	plum: "plum",
	powderblue: "powder blue",
	purple: "purpuriu",
	red: "roşu",
	rosybrown: "rosy brown",
	royalblue: "albastru regal",
	saddlebrown: "saddle brown",
	salmon: "somon",
	sandybrown: "sandy brown",
	seagreen: "verde marin",
	seashell: "seashell",
	sienna: "sienna",
	silver: "argintiu",
	skyblue: "albastru cer",
	slateblue: "albastru ardezie",
	slategray: "gri ardezie",
	slategrey: "gri ardezie", // same as slategray
	snow: "zăpadă",
	springgreen: "verde primăvară",
	steelblue: "albastru metalic",
	tan: "tan",
	teal: "teal",
	thistle: "thistle",
	tomato: "tomato",
	transparent: "transparent",
	turquoise: "turcoaz",
	violet: "violet",
	wheat: "wheat",
	white: "alb",
	whitesmoke: "white smoke",
	yellow: "galben",
	yellowgreen: "verde gălbui"
})
);


text:
package betterwithmods.module.hardcore.needs.hunger;

import betterwithmods.util.InvUtils;
import com.google.common.collect.Maps;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import squeek.applecore.api.food.FoodValues;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Created by primetoxinz on 6/20/17.
 */
public class FoodHelper {
    private static final HashMap<ItemStack, FoodValues> FOOD_VALUES = Maps.newHashMap();

    public static HashMap<ItemStack, FoodValues> getFoodValues() {
        return FOOD_VALUES;
    }

    protected static Optional<FoodValues> getFoodValue(ItemStack stack) {
        return FOOD_VALUES.entrySet().stream().filter(entry -> InvUtils.matches(entry.getKey(), stack)).map(Map.Entry::getValue).findFirst();
    }

    public static void registerFood(ItemStack item, int hunger) {
        registerFood(item, hunger, 0, false);
    }

    public static void registerFood(ItemStack stack, int hunger, float fat, boolean alwaysEdible) {
        registerFood(stack, new FoodValues(hunger, fat), alwaysEdible);
    }

    public static void registerFood(ItemStack stack, FoodValues values, boolean alwaysEdible) {
        if (alwaysEdible) {
            setAlwaysEdible(stack);
        }
        FOOD_VALUES.put(stack, values);
    }

    public static void setAlwaysEdible(ItemStack stack) {
        if (stack.getItem() instanceof ItemFood) {
            ItemFood food = (ItemFood) stack.getItem();
            food.setAlwaysEdible();
        }
    }

}


text:
class DishOption
	include Mongoid::Document
	include Mongoid::Timestamps
	store_in collection: "Options", database: "dishgo"
	field :name, localize: true
	field :type, type: String
	field :max_selections, type: Integer
	field :published, type: Boolean
	field :min_selections, type: Integer
	field :advanced, type: Boolean
	field :position, type: Integer
	field :extra_cost, type: Boolean

	field :draft, type: Hash

	# belongs_to :dish_size, class_name: "Dish", inverse_of: :sizes
	belongs_to :dish, class_name: "Dish", inverse_of: :options, index: true
	belongs_to :draft_dish, class_name: "Dish", inverse_of: :draft_options, index: true

	belongs_to :dish_which_uses_this_as_size_options, class_name: "Dish", inverse_of: :sizes, index: true
	belongs_to :draft_dish_which_uses_this_as_size_options, class_name: "Dish", inverse_of: :draft_sizes, index: true

	belongs_to :restaurant, index: true
	belongs_to :odesk, index: true

	has_many :individual_options, class_name: "IndividualOption", inverse_of: :options
	has_many :draft_individual_options, class_name: "IndividualOption", inverse_of: :draft_options

	index({ _id:1 }, { unique: true, name:"id_index" })

  	default_scope -> { asc(:created_at) }

	# accepts_nested_attributes_for :individual_options, :draft_individual_options

	def load_data_from_json option, request_restaurant

		draft = {}
		#Load or Create the individual options for this option.
		individual_options = option["individual_options"].collect.with_index do |individual_option,index|
			if individual_option_object = IndividualOption.where(:_id => individual_option["id"]).first and individual_option_object
				# Rails.logger.warn "---\nLoading IndividualOption[#{individual_option["name"]}]\n---"
			  	# If someone has tried to load options from another restaurant, something fishy is going on.
				if individual_option_object.restaurant_id.blank?
					individual_option_object.restaurant = request_restaurant
				end

			  if individual_option_object.restaurant_id != request_restaurant.id
        		Rails.logger.warn "Bailing out in options individual_option_object.restaurant_id[#{individual_option_object.restaurant_id}] != request_restaurant.id[#{request_restaurant.id}]\n------------"
			  	# return false
			  end
			else
				individual_option_object = IndividualOption.create
				individual_option_object.published = false
				individual_option_object.restaurant = request_restaurant
			end

			if !individual_option_object.load_data_from_json(individual_option,request_restaurant)
        		Rails.logger.warn "Bailing out in options individual_option_object.restaurant_id[#{individual_option_object.restaurant_id}] != request_restaurant.id[#{request_restaurant.id}]\n------------"
				return false
			end

			next individual_option_object
		end

		draft[:name] = option["name"]
		draft[:type] = option["type"]
		draft[:advanced] = option["advanced"]
		draft[:max_selections] = option["max_selections"]
		draft[:min_selections] = option["min_selections"]
		draft[:extra_cost] = option["extra_cost"]

		self.draft = draft
		self.draft_individual_options = individual_options
		self.save
	end

	def odesk_load_data_from_json option, odesk_request
		# Rails.logger.warn "Dish_Options\n---------"
		draft = {}
		#Load or Create the individual options for this option.
		individual_options = option["individual_options"].collect.with_index do |individual_option,index|
			if individual_option_object = IndividualOption.where(:_id => individual_option["id"]).first and individual_option_object
				# Rails.logger.warn "---\nLoading IndividualOption[#{individual_option["name"]}]\n---"
			  # If someone has tried to load options from another restaurant, something fishy is going on.
			  if individual_option_object.odesk_id != odesk_request.id
			  	return false
			  end
			else
				individual_option_object = IndividualOption.create
				individual_option_object.published = false
				individual_option_object.odesk = odesk_request
			end

			if !individual_option_object.odesk_load_data_from_json(individual_option,odesk_request)
				return false
			end

			next individual_option_object
		end
		draft[:name] = option["name"]
		draft[:type] = option["type"]
		draft[:advanced] = option["advanced"]
		draft[:max_selections] = option["max_selections"]
		draft[:min_selections] = option["min_selections"]
		draft[:extra_cost] = option["extra_cost"]
		self.draft = draft
		self.draft_individual_options = individual_options
		# Rails.logger.warn "End Dish_Options\n---------"
		self.save
	end

	def publish_menu
		self.name_translations = self.draft["name"]
		self.type = self.draft["type"]
		self.advanced = self.draft["advanced"] || false
		self.max_selections = self.draft["max_selections"]
		self.min_selections = self.draft["min_selections"]
		self.extra_cost = self.draft["extra_cost"]
		self.individual_options = self.draft_individual_options
		self.individual_options.each do |individual_option|
			individual_option.publish_menu
		end
		self.save
	end

	def reset_draft_menu
		draft = {}
		draft[:name] = self.name_translations
		draft[:type] = self.type
		draft[:advanced] = self.advanced
		draft[:max_selections] = self.max_selections
		draft[:min_selections] = self.min_selections
		draft[:extra_cost] = self.extra_cost
		self.draft = draft
		self.draft_individual_options = self.individual_options
		self.draft_individual_options.each do |individual_option|
			individual_option.reset_draft_menu
		end
		self.save
	end

	def api_custom_to_hash lang
		option_hash = self.as_document
		option_hash["name"] = self.name_translations[lang]
		option_hash[:id] = self.id
		option_hash["individual_options"] = self.individual_options.collect do |ind_opt|
			ind_opt_hash = ind_opt.api_as_document
			ind_opt_hash[:id] = ind_opt.id
			ind_opt_hash["name"] = ind_opt.name_translations[lang]
			ind_opt_hash["icon"] = ind_opt.icon.serializable_hash({}) if ind_opt.icon
			next ind_opt_hash
		end
		return option_hash
	end

	def custom_to_hash icon_list = []
		option_hash = self.as_document
		option_hash[:id] = self.id
		option_hash["individual_options"] = self.individual_options.collect do |ind_opt|
			ind_opt_hash = ind_opt.as_document
			ind_opt_hash[:id] = ind_opt.id
			if icon_list.include?(ind_opt.id)
				ind_opt_hash["icon"] = ind_opt.icon.serializable_hash({})
			end
			next ind_opt_hash
		end
		return option_hash
	end

	def custom_to_hash_draft
		option_hash = self.as_document
		option_hash[:id] = self.id
		option_hash.merge!(self.draft)
		option_hash["individual_options"] = self.draft_individual_options.collect do |ind_opt|
			ind_opt_hash = ind_opt.as_document
			ind_opt_hash[:id] = ind_opt.id
			ind_opt_hash.merge!(ind_opt.draft)
			ind_opt["size_prices"] = ind_opt.draft_size_prices
			ind_opt_hash["icon"] = ind_opt.draft_icon.serializable_hash({})	if ind_opt.draft_icon
			next ind_opt_hash
		end
		return option_hash
	end

end


text:
#ifndef NDK_DEBUG_H
#define NDK_DEBUG_H

/* TODO : use the Nginx printf function */

#include <ngx_core.h>
#include <ngx_http.h>

/* TODO
- andk_debug variety of debugging formats
- global include file for all debugging - can pass declaration to cflags for the option
*/

#if (NDK_DEBUG)

    #if (NGX_HAVE_VARIADIC_MACROS)

        #define ndk_debug(...)  ndk_debug_helper (__func__,__VA_ARGS__)

        #define ndk_debug_helper(func,...) \
            fprintf(stderr, "%-60s", func); \
            fprintf(stderr, (const char *)__VA_ARGS__); \
            fprintf(stderr,"\n");
            /*fprintf(stderr, " at %s line %d.\n", __FILE__, __LINE__)*/

    #else

        /* NOTE : these includes might not be necessary since they're probably included with the core */

        #include <stdarg.h>
        #include <stdio.h>
        #include <stdarg.h>

        static void ndk_debug (const char * fmt, ...) {
        }

    #endif

    #if NDK_DEBUG > 1

        #define ndk_debug_request()  ndk_debug_request_helper(r, __func__)

        static ngx_inline void
        ndk_debug_request_helper (ngx_http_request_t *r, const char *func)
        {
            ngx_http_posted_request_t       *pr;

            /* TODO : improve the format */

            fprintf (stderr, "%s %.*s %.*s?%.*s c:%d m:%p r:%p ar:%p pr:%p",
                    func,
                    (int) r->method_name.len, r->method_name.data,
                    (int) r->uri.len, r->uri.data,
                    (int) r->args.len, r->args.data,
                    0/*(int) r->main->count*/, r->main,
                    r, r->connection->data, r->parent);

            if (r->posted_requests) {
                fprintf(stderr, " posted:");

                for (pr = r->posted_requests; pr; pr = pr->next) {
                    fprintf (stderr, "%p,", pr);
                }
            }

            fprintf (stderr, "\n");
        }

    #else

        #define ndk_debug_request()

    #endif

    static ngx_inline void
    ndk_debug_print_posted_requests (ngx_http_request_t *r)
    {
        ngx_http_posted_request_t   *pr;

        ndk_request_log_debug_http (r, "ndk debug - http posted requests");

        for (pr = r->main->posted_requests; pr; pr = pr->next) {

            if (!pr->request)
                continue;

            ndk_request_log_debug_http (r, "ndk debug - http posted request:%V", &pr->request->uri);
        }
    }

    #define ndk_debug_http_conf_location(cf)    ndk_debug_http_conf_location_helper (cf, __func__)

    static ngx_inline void
    ndk_debug_http_conf_location_helper (ngx_conf_t *cf, const char *func)
    {
        ngx_http_core_loc_conf_t        *lcf;

        lcf = ngx_http_conf_get_module_loc_conf (cf, ngx_http_core_module);

        ndk_debug_helper (func, "[%s]", lcf->name.data);
    }

    /*
    static void
    ndk_debug_log_chain (ngx_log_t *log, ngx_chain_t *cl)
    {

    }
    */

#else

    #if (NGX_HAVE_VARIADIC_MACROS)

        #define     ndk_debug(...)
        #define     ndk_debug_request()

    #else

        #include <stdarg.h>

        static void ndk_debug (const char * fmt, ...) {
        }

        static void ndk_debug_request() {
        }

    #endif

    #define     ndk_debug_http_conf_location(cf)

#endif

#if (NDK_DEBUG)

    #define     ndk_debug_check_read_event_handler(r)                               \
                                                                                \
                    ndk_debug("r->read_event_handler = %s",                         \
                        r->read_event_handler == ngx_http_block_reading ?           \
                            "ngx_http_block_reading" :                              \
                        r->read_event_handler == ngx_http_test_reading ?            \
                            "ngx_http_test_reading" :                               \
                        r->read_event_handler == ngx_http_request_empty_handler ?   \
                            "ngx_http_request_empty_handler" : "UNKNOWN")

    #define     ndk_debug_check_write_event_handler(r)                              \
                                                                                \
                    ndk_debug ("r->write_event_handler = %s",                       \
                        r->write_event_handler == ngx_http_handler ?                \
                            "ngx_http_handler" :                                    \
                        r->write_event_handler == ngx_http_core_run_phases ?        \
                            "ngx_http_core_run_phases" :                            \
                        r->write_event_handler == ngx_http_request_empty_handler ?  \
                            "ngx_http_request_empty_handler" : "UNKNOWN")

#else

    #define     ndk_debug_check_read_event_handler(r)
    #define     ndk_debug_check_write_event_handler(r)

#endif

#endif /* NDK_DEBUG_H */


text:
<?php

    require_once(dirname(__FILE__) . '/ProPackageIDGenerator.php');
    require_once(dirname(__FILE__) . "/ProConfigBuilder.php");

    class ProPackageBuilder {
        private $licenseData;
        private $proConfigPath;
        private $htaccessPath;

        public function __construct($licenseData, $proConfigPath, $htaccessPath) {
            $this->licenseData = $licenseData;
            $this->proConfigPath = $proConfigPath;
            $this->htaccessPath = $htaccessPath;
        }

        public function buildLicenseZip($archivePath, $salt, $emailAddress) {
            $packageIDGenerator = new ProPackageIDGenerator($salt);
            $proPackageID = $packageIDGenerator->idFromEmail($emailAddress);
            $archive = new ZipArchive();
            $archive->open($archivePath, ZipArchive::CREATE);
            $this->addIndexHtmlToZip($archive);
            $this->addHtaccessToZip($archive);
            $this->addEmptyProfileToZip($archive, $proPackageID);
            $this->addLicenseToZip($archive, $proPackageID);
            $this->addConfigToZip($archive, $proPackageID);
            $archive->close();
        }

        private function renderProConfig($proPackageID) {
            $configBuilder = new ProConfigBuilder($proPackageID);
            return $configBuilder->renderProConfig($this->proConfigPath);
        }

        private function addIndexHtmlToZip($archive) {
            $archive->addFromString("license/index.html", "");
        }

        private function addHtaccessToZip($archive) {
            $archive->addFile($this->htaccessPath, "license/.htaccess");
        }

        private function generateRelativeProfilePath($proPackageID) {
            $configBuilder = new ProConfigBuilder($proPackageID);
            return $configBuilder->generateRelativeProfilePath();
        }

        private function generateRelativeLicensePath($proPackageID) {
            $configBuilder = new ProConfigBuilder($proPackageID);
            return $configBuilder->generateRelativeLicensePath();
        }

        private function addEmptyProfileToZip($archive, $proPackageID) {
            $profileLocalPath = $this->generateRelativeProfilePath($proPackageID);
            $archive->addFromString("license/" . $profileLocalPath, "");
        }

        private function addLicenseToZip($archive, $proPackageID){
            $licenseLocalPath = $this->generateRelativeLicensePath($proPackageID);
            $archive->addFromString("license/" . $licenseLocalPath, $this->licenseData);
        }

        private function addConfigToZip($archive, $proPackageID) {
            $renderedConfig = $this->renderProConfig($proPackageID);
            $archive->addFromString("license/config_pro.php", $renderedConfig);
        }
    }


text:
    position: absolute;
    display: none;
    width: 300px;
    border: 1px solid #fdd;
    padding: 2px;
    background-color: #fee;
    opacity: 0.80;
    font-size: smaller;
    cursor:move;
}

#tooltip #title {
    font-weight: bold;
}

#tooltip #type {
    font-style: italic;
}


text:
/*! HTML5 Boilerplate v4.3.0 | MIT License | http://h5bp.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html,
button,
input,
select,
textarea {
    color: #222;
}

html {
    font-size: 19px;
    line-height: 1.4;
    background: url('img/monument.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

/*
 * Remove text-shadow in selection highlight: h5bp.com/i
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between images, videos, audio and canvas and the bottom of
 * their containers: h5bp.com/i/440
 */

audio,
canvas,
img,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browse Happy prompt
   ========================================================================== */

.browsehappy {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

body {
    text-align: center;
    font-size: 16px;
    /*background-image: url('http://www.dcclubbing.com/wordpress/wp-content/uploads/2012/01/georgetown-m-street.jpg');
    background-size: cover;
    background-position: center;
    background-position: center center;*/
}

.site-header {
    width: 100%;
    height: 220px;
    text-align: center;
    margin: 0 auto;
    font-family: 'Lato', sans-serif;
    color: white;

}

.salsa-title {
    font-size: 6em;
    margin: 10px 0 10px 0;
}

h3 {
    font-size: 1.1em;
    text-align: center;
    margin-left: 1em;
}

.search-place {
    display: inline-block;
    padding: 5px 3px 0 125px;
    margin-right: 95px;
}

input {
    border: 0;
    padding: 7px;
    font-size: 15px;

  }
input[type="submit"] {
    color: white;
    background: red;
}

.places {
    text-align: center;
    font-family: 'Lato', sans-serif;
}

.horizontal-nav {
    list-style: none;
    padding: 0;
}

.places li {
    display: inline-block;
    margin: 50px;
}

.btn {
    text-transform: uppercase;
    color: rgb(0,0,0);
    padding: 10px;
    border-radius: 5px;
    font-weight: bold;
    display: block;
    text-align: center;
    box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.2);
    transition-property: box-shadow;
    transition-duration: 200ms;
}

.places-btn {
    background-color: lightgray;
    text-decoration: none;
}

footer {
    font-family: 'Lato', sans-serif;
    margin-top: 150px;
    color: white;
}

.ftr {
    width: 100%;
    height: 90px;
}

.ftr a {
    margin: 60px;
}

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

/*
 * Hide from both screenreaders and browsers: h5bp.com/u
 */

.hidden {
    display: none !important;
    visibility: hidden;
}

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screenreaders, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/*
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */

.clearfix {
    *zoom: 1;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media all and (max-width: 950px) {
    /* Style adjustments for viewports that meet the condition */

.salsa-title {
    font-size: 4em;
}

h3 {
    font-size: 0.9em;
    float: left;
}

.navigation {
    clear: both;
    width: 100%;
}

.main-nav li {
    display: block;
    margin-right: 20px;
    float: left;

}

.places {
    width: 100%;
    margin: 0;
}

.search-place {
    float: left;
    padding: 5px 3px 0 125px;
    margin-right: 100px;
}

input {
    font-size: 10px;
}

.btn {
    color: black;
    padding: 7px;
    border-radius: 5px;
    font-weight: bold;
    display: inline;
    text-align: center;
    box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.2);
    transition-property: box-shadow;
    transition-duration: 200ms;
}

}

@media print,
       (-o-min-device-pixel-ratio: 5/4),
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid required HTTP connection: h5bp.com/r
   ========================================================================== */

@media print {
    * {
        background: transparent !important;
        color: #000 !important; /* Black prints faster: h5bp.com/s */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links for images, or javascript/internal links
     */

    .ir a:after,
    a[href^="javascript:"]:after,
    a[href^="#"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    thead {
        display: table-header-group; /* h5bp.com/t */
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    @page {
        margin: 0.5cm;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class
        name="edu.wustl.catissuecore.domain.ClinicalStudyEvent"
        table="SYN_CAT_CLINICAL_STUDY_EVENT"
        dynamic-update="false"
        dynamic-insert="false"
    >

    <cache usage="read-write" />

        <id
            name="id"
            column="IDENTIFIER"
            type="long"
            length="30"
            unsaved-value="null"
        >
            <generator class="native">
                <param name="sequence">CATISSUE_STUDY_EVENT_SEQ</param>
            </generator>
        </id>

        <many-to-one
            name="clinicalStudy"
            class="edu.wustl.catissuecore.domain.ClinicalStudy"
            cascade="none"

            update="true"
            insert="true"
            column="CLINICAL_STUDY_ID"
        />

        <property
            name="collectionPointLabel"
            type="string"
            update="true"
            insert="true"
            column="COLLECTION_POINT_LABEL"
            length="255"
        />

        <property
            name="studyCalendarEventPoint"
            type="double"
            update="true"
            insert="true"
            column="EVENT_POINT"
            length="10"
        />

        <set
            name="eventEntryCollection"
            table="SYN_CAT_CLIN_STUDY_EVNT_NTRY"
            lazy="true"
            inverse="true"
            cascade="save-update"
            sort="unsorted"
        >

        <cache usage="read-write" />

              <key
                  column="CLINICAL_STUDY_EVENT_ID"
              />

              <one-to-many
                  class="edu.wustl.catissuecore.domain.ClinicalStudyEventEntry"
              />
        </set>

        <!--
            To add non XDoclet property mappings, create a file named
                hibernate-properties-ClinicalStudyEvent.xml
            containing the additional properties and place it in your merge dir.
        -->

    </class>

</hibernate-mapping>


text:
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [3.0.1] - 2020-04-07
### Added
- Added `.codacy.yml` for Codacy analysis
- Added `.mocharc.yml`

### Changed
- Updated `devDependencies` to latest versions
- Migrated to using `nyc` from `istanbul`
- Migrated `husky` pre-push hooks
- Migrated to CircleCI v2 pipelines
- Updated `package.json` to new Node.js and NPM version compatibility


text:
/**
 * @fileoverview Externs for MediaSession based on
 * {@link https://bit.ly/2Id3dGD Editor's Draft, 12 January 2017}
 *
 * @externs
 */

const MediaMetadata = class {
  constructor(options) {
    /** @type {string} */
    this.title;

    /** @type {string} */
    this.artist;

    /** @type {!Object} */
    this.artwork;
  }
};

const MediaSession = class {
  constructor() {
    /** @type {?MediaMetadata} */
    this.metadata;
  }
};

/** @type {MediaSession} */
Navigator.prototype.mediaSession;


text:
<?php

namespace Tests\HtmlSanitizer\Bundle\Extension;

use HtmlSanitizer\Bundle\HtmlSanitizerBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\Kernel;
use Tests\HtmlSanitizer\Bundle\Kernel\KernelTestTrait;

/**
 * @internal
 */
class CustomExtensionAppKernel extends Kernel
{
    use KernelTestTrait;

    public function registerBundles()
    {
        return [new FrameworkBundle(), new HtmlSanitizerBundle()];
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(function (ContainerBuilder $container) {
            $container->loadFromExtension('framework', ['secret' => '$ecret']);

            $container->loadFromExtension('html_sanitizer', [
                'default_sanitizer' => 'default',
                'sanitizers' => [
                    'default' => [
                        'extensions' => ['basic', 'image'],
                        'tags' => ['img' => ['allowed_hosts' => ['trusted.com']]],
                    ],
                    'basic' => [
                        'extensions' => ['basic'],
                    ],
                ],
            ]);

            $definition = new Definition(CustomExtension::class);
            $definition->addTag('html_sanitizer.extension');
            $container->setDefinition('app.custom_extension', $definition);

            $container->setAlias('test.html_sanitizer.builder', 'html_sanitizer.builder')->setPublic(true);
        });
    }
}


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

namespace WyriHaximus\TwigView\Lib\Twig\Node;

use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\ArrayExpression;
use Twig\Node\Node;

/**
 * Class Element.
 */
final class Element extends Node
{
    /**
     * Constructor.
     *
     * @param \Twig\Node\Expression\AbstractExpression $name Name.
     * @param \Twig\Node\Expression\AbstractExpression $data Data.
     * @param \Twig\Node\Expression\AbstractExpression $options Options.
     * @param int $lineno Linenumber.
     * @param string $tag Tag.
     */
    public function __construct(
        AbstractExpression $name,
        ?AbstractExpression $data = null,
        ?AbstractExpression $options = null,
        int $lineno = 0,
        ?string $tag = null
    ) {
        if ($data === null) {
            $data = new ArrayExpression([], $lineno);
        }

        if ($options === null) {
            $options = new ArrayExpression([], $lineno);
        }

        parent::__construct(
            [
                'name' => $name,
                'data' => $data,
                'options' => $options,
            ],
            [],
            $lineno,
            $tag
        );
    }

    /**
     * Compile node.
     *
     * @param \Twig\Compiler $compiler Compiler.
     * @return void
     */
    public function compile(Compiler $compiler)
    {
        $compiler->addDebugInfo($this);

        $compiler->raw('echo $context[\'_view\']->element(');
        $compiler->subcompile($this->getNode('name'));

        $data = $this->getNode('data');
        $compiler->raw(',');
        $compiler->subcompile($data);

        $options = $this->getNode('options');
        $compiler->raw(',');
        $compiler->subcompile($options);

        $compiler->raw(");\n");
    }
}


text:
My open source books and articles
this is also testing purpose


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = getImplicitRole;

var _implicitRoles = require('./implicitRoles');

var _implicitRoles2 = _interopRequireDefault(_implicitRoles);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Returns an element's implicit role given its attributes and type.
 * Some elements only have an implicit role when certain props are defined.
 *
 * @param type - The node's tagName.
 * @param attributes - The collection of attributes on the node.
 * @returns {String} - String representing the node's implicit role or '' if it doesn't exist.
 */
function getImplicitRole(type, attributes) {
  var normalizedType = type.toUpperCase();

  if (_implicitRoles2.default[normalizedType]) {
    return _implicitRoles2.default[normalizedType](attributes);
  }

  return '';
}


text:
<?php

namespace Amp\Parallel\Worker;

use Amp\Parallel\Context\Parallel;
use Amp\Parallel\Context\Thread;

/**
 * Worker factory that includes a custom bootstrap file after initializing the worker.
 */
final class BootstrapWorkerFactory implements WorkerFactory
{
    /** @var string */
    private $bootstrapPath;

    /** @var string */
    private $className;

    /**
     * @param string $bootstrapFilePath Path to custom bootstrap file.
     * @param string $envClassName      Name of class implementing \Amp\Parallel\Worker\Environment to instigate in each
     *     worker. Defaults to \Amp\Parallel\Worker\BasicEnvironment.
     *
     * @throws \Error If the given class name does not exist or does not implement {@see Environment}.
     */
    public function __construct(string $bootstrapFilePath, string $envClassName = BasicEnvironment::class)
    {
        if (!\file_exists($bootstrapFilePath)) {
            throw new \Error(\sprintf("No file found at autoload path given '%s'", $bootstrapFilePath));
        }

        if (!\class_exists($envClassName)) {
            throw new \Error(\sprintf("Invalid environment class name '%s'", $envClassName));
        }

        if (!\is_subclass_of($envClassName, Environment::class)) {
            throw new \Error(\sprintf(
                "The class '%s' does not implement '%s'",
                $envClassName,
                Environment::class
            ));
        }

        $this->bootstrapPath = $bootstrapFilePath;
        $this->className = $envClassName;
    }

    /**
     * {@inheritdoc}
     *
     * The type of worker created depends on the extensions available. If multi-threading is enabled, a WorkerThread
     * will be created. If threads are not available a WorkerProcess will be created.
     */
    public function create(): Worker
    {
        if (Parallel::isSupported()) {
            return new WorkerParallel($this->className, $this->bootstrapPath);
        }

        if (Thread::isSupported()) {
            return new WorkerThread($this->className, $this->bootstrapPath);
        }

        return new WorkerProcess(
            $this->className,
            [],
            \getenv("AMP_PHP_BINARY") ?: (\defined("AMP_PHP_BINARY") ? \AMP_PHP_BINARY : null),
            $this->bootstrapPath
        );
    }
}


text:
package org.keycloak.testsuite.broker;

import org.jboss.arquillian.graphene.page.Page;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testsuite.Assert;
import org.keycloak.testsuite.admin.ApiUtil;
import org.keycloak.testsuite.pages.PasswordPage;
import org.keycloak.testsuite.util.UserBuilder;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage;

/**
 * Tests first-broker-login flow with new authenticators.
 *

 * Especially for re-authentication of user, which is linking to IDP broker, it uses "Password Form" authenticator instead of default IdpUsernamePasswordForm.
 * It tests various variants with OTP( Conditional OTP, Password-or-OTP) .
 *
 * @author Marek Posolda
 */
public class KcOidcFirstBrokerLoginNewAuthTest extends AbstractInitializedBaseBrokerTest {

    @Page
    PasswordPage passwordPage;

    @Override
    protected BrokerConfiguration getBrokerConfiguration() {
        return KcOidcBrokerConfiguration.INSTANCE;
    }

    @Before
    public void disableReviewProfileBeforeTest() {
        updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    }

    /**
     * Tests the firstBrokerLogin flow configured to re-authenticate with PasswordForm authenticator (Not the form with username/password, but password only)
     * OTP is not configured for the user and hence not requested (There is default OTP conditional subflow used)
     */
    @Test
    public void testReAuthenticateWithPasswordAndConditionalOTP_otpNotRequested() {
        configureBrokerFlowToReAuthenticationWithPasswordForm(bc.getIDPAlias(), "first broker login with password form");

        String consumerRealmUserId = createUser("consumer");
        loginWithBrokerAndConfirmLinkAccount();

        // Assert on the page with password form
        Assert.assertTrue(passwordPage.isCurrent("consumer"));

        // Try bad password first
        passwordPage.login("bad-password");
        Assert.assertEquals("Invalid username or password.", passwordPage.getError());

        // Try good password
        passwordPage.login("password");

        assertUserAuthenticatedInConsumer(consumerRealmUserId);
    }

    /**
     * Tests the firstBrokerLogin flow configured to re-authenticate with PasswordForm authenticator.
     * Assert that OTP is required too as it is configured for the user (There is default OTP conditional subflow used)
     */
    @Test
    public void testReAuthenticateWithPasswordAndConditionalOTP_otpRequested() {
        configureBrokerFlowToReAuthenticationWithPasswordForm(bc.getIDPAlias(), "first broker login with password form");

        // Create user and link him with TOTP
        String consumerRealmUserId = createUser("consumer");
        String totpSecret = addTOTPToUser("consumer");

        loginWithBrokerAndConfirmLinkAccount();

        // Login with password
        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.login("password");

        // Assert on TOTP page. Login with TOTP
        loginTotpPage.assertCurrent();
        loginTotpPage.login(totp.generateTOTP(totpSecret));

        assertUserAuthenticatedInConsumer(consumerRealmUserId);
    }

    /**
     * Tests the firstBrokerLogin flow configured to re-authenticate with PasswordForm OR TOTP.
     * TOTP is not configured for the user and hence he MUST authenticate with password
     */
    @Test
    public void testReAuthenticateWithPasswordOrOTP_otpNotConfigured_passwordUsed() {
        configureBrokerFlowToReAuthenticationWithPasswordOrTotp(bc.getIDPAlias(), "first broker login with password or totp");

        String consumerRealmUserId = createUser("consumer");

        loginWithBrokerAndConfirmLinkAccount();

        // Assert that user can't see credentials combobox. Password is the only available credentials.
        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.assertCredentialsComboboxAvailability(false);

        // Login with password
        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.login("password");

        assertUserAuthenticatedInConsumer(consumerRealmUserId);
    }

    /**
     * Tests the firstBrokerLogin flow configured to re-authenticate with PasswordForm OR TOTP.
     * TOTP is configured for the user and hence he can authenticate with OTP. However he selects password
     */
    @Test
    public void testReAuthenticateWithPasswordOrOTP_otpConfigured_passwordUsed() {
        configureBrokerFlowToReAuthenticationWithPasswordOrTotp(bc.getIDPAlias(), "first broker login with password or totp");

        // Create user and link him with TOTP
        String consumerRealmUserId = createUser("consumer");
        addTOTPToUser("consumer");

        loginWithBrokerAndConfirmLinkAccount();

        // Assert that user can see credentials combobox. Password and OTP are available credentials. Password should be selected.
        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.assertCredentialsComboboxAvailability(true);
        Assert.assertNames(passwordPage.getAvailableCredentials(), "Password", "OTP");
        Assert.assertEquals("Password", passwordPage.getSelectedCredential());

        // Login with password
        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.login("password");

        assertUserAuthenticatedInConsumer(consumerRealmUserId);
    }

    /**
     * Tests the firstBrokerLogin flow configured to re-authenticate with PasswordForm OR TOTP.
     * TOTP is configured for the user and he selects it to authenticate. Password is not used.
     */
    @Test
    public void testReAuthenticateWithPasswordOrOTP_otpConfigured_otpUsed() {
        configureBrokerFlowToReAuthenticationWithPasswordOrTotp(bc.getIDPAlias(), "first broker login with password or totp");

        // Create user and link him with TOTP
        String consumerRealmUserId = createUser("consumer");
        String totpSecret = addTOTPToUser("consumer");

        loginWithBrokerAndConfirmLinkAccount();

        // Assert that user can see credentials combobox. Password and OTP are available credentials. Password should be selected.
        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.assertCredentialsComboboxAvailability(true);

        // Select OTP and assert
        passwordPage.selectCredential("OTP");
        loginTotpPage.assertCurrent();
        Assert.assertEquals("OTP", loginTotpPage.getSelectedCredential());

        // Login with OTP now
        loginTotpPage.login(totp.generateTOTP(totpSecret));

        assertUserAuthenticatedInConsumer(consumerRealmUserId);
    }

    /**
     * Tests the firstBrokerLogin flow configured to re-authenticate with PasswordForm authenticator.
     * Do some testing with back button
     */
    @Test
    public void testBackButtonWithOTPEnabled() {
        configureBrokerFlowToReAuthenticationWithPasswordForm(bc.getIDPAlias(), "first broker login with password form");

        // Create user and link him with TOTP
        String consumerRealmUserId = createUser("consumer");
        String totpSecret = addTOTPToUser("consumer");

        loginWithBrokerAndConfirmLinkAccount();

        // Login with password
        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.login("password");

        // Assert on TOTP page. Assert "Back" button available
        loginTotpPage.assertCurrent();
        loginTotpPage.assertBackButtonAvailability(true);

        // Click "Back" 2 times. Should be on "Confirm account" page
        loginTotpPage.clickBackButton();

        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.assertBackButtonAvailability(true);
        passwordPage.clickBackButton();

        // Back button won't be available on "Confirm Link" page. It was the first authenticator
        idpConfirmLinkPage.assertCurrent();
        idpConfirmLinkPage.assertBackButtonAvailability(false);

        // Authenticate
        idpConfirmLinkPage.clickLinkAccount();

        Assert.assertTrue(passwordPage.isCurrent("consumer"));
        passwordPage.login("password");

        loginTotpPage.assertCurrent();
        loginTotpPage.login(totp.generateTOTP(totpSecret));

        assertUserAuthenticatedInConsumer(consumerRealmUserId);
    }

    // Add OTP to the user. Return TOTP secret
    private String addTOTPToUser(String username) {

        RealmResource realm = adminClient.realm(bc.consumerRealmName());
        UserResource user = ApiUtil.findUserByUsernameId(realm, username);

        // Add CONFIGURE_TOTP requiredAction to the user
        UserRepresentation userRep = UserBuilder.edit(user.toRepresentation()).requiredAction(UserModel.RequiredAction.CONFIGURE_TOTP.toString()).build();
        user.update(userRep);

        // Login. TOTP will be required at login time.
        driver.navigate().to(getAccountUrl(bc.consumerRealmName()));
        loginPage.login(username, "password");

        totpPage.assertCurrent();
        String totpSecret = totpPage.getTotpSecret();
        totpPage.configure(totp.generateTOTP(totpSecret));

        // Logout user through admin endpoint
        user.logout();

        return totpSecret;
    }

    // Login with broker and click "Link account"
    private void loginWithBrokerAndConfirmLinkAccount() {
        driver.navigate().to(getAccountUrl(bc.consumerRealmName()));

        logInWithBroker(bc);

        waitForPage(driver, "account already exists", false);
        assertTrue(idpConfirmLinkPage.isCurrent());
        assertEquals("User with email user@localhost.com already exists. How do you want to continue?", idpConfirmLinkPage.getMessage());
        idpConfirmLinkPage.clickLinkAccount();
    }

    private void assertUserAuthenticatedInConsumer(String consumerRealmUserId) {
        waitForPage(driver, "keycloak account management", true);
        accountUpdateProfilePage.assertCurrent();
        assertNumFederatedIdentities(consumerRealmUserId, 1);
    }

    // Configure the variant of firstBrokerLogin flow, which will use PasswordForm instead of IdpUsernamePasswordForm.
    // In other words, the form with password-only instead of username/password.
    private void configureBrokerFlowToReAuthenticationWithPasswordForm(String idpAlias, String newFlowAlias) {
        BrokerRunOnServerUtil.configureBrokerFlowToReAuthenticationWithPasswordForm(testingClient, bc.consumerRealmName(), idpAlias, newFlowAlias);
    }

    // Configure the variant of firstBrokerLogin flow, which will allow to reauthenticate user with password OR totp
    // TOTP will be available just if configured for the user
    private void configureBrokerFlowToReAuthenticationWithPasswordOrTotp(String idpAlias, String newFlowAlias) {
        BrokerRunOnServerUtil.configureBrokerFlowToReAuthenticationWithPasswordOrTotp(testingClient, bc.consumerRealmName(), idpAlias, newFlowAlias);
    }
}


text:
class DartVMInitializer {
 public:
  static void Initialize(Dart_InitializeParams* params,
                         bool enable_timeline_event_handler,
                         bool trace_systrace);
  static void Cleanup();

 private:
  static void LogDartTimelineEvent(const char* label,
                                   int64_t timestamp0,
                                   int64_t timestamp1_or_async_id,
                                   Dart_Timeline_Event_Type type,
                                   intptr_t argument_count,
                                   const char** argument_names,
                                   const char** argument_values);
};

#endif  // FLUTTER_RUNTIME_DART_VM_INITIALIZER_H_


text:
1. Before you start, I strongly recommend reading these:

    * Apps on Facebook.com -> <http://developers.facebook.com/docs/guides/canvas/>
    * Graph API -> <http://developers.facebook.com/docs/reference/api/>
    * Authentication -> <http://developers.facebook.com/docs/authentication/>
    * Heroku: Building a Facebook Application -> <http://devcenter.heroku.com/articles/facebook/>

2. Go to [FB Developers website](http://facebook.com/developers) and create a new FB app. Set its canvas name, canvas url and your site URL. Make sure the canvas type is set to "iframe" (which should be the case by default).

3. Build a new Rails application.

    ``` shell
        rails new <name>
    ```

4. Declare rest-more and its dependencies in the Gemfile. Add these lines:

    ``` ruby
        gem 'rest-more'

        # these gems are used in rest-more
        gem 'json' # you may also use other JSON parsers/generators, i.e. 'yajl-ruby' or 'json_pure'
    ```

    And run:

    ``` shell
        bundle install
    ```

5. In order to configure your Rails application for the Facebook application you created, you must create a `rest-core.yaml` file in your /config directory and fill it with your Facebook configuration. If you plan to run your application in the Facebook canvas, also provide a canvas name.

    Example:

    ``` yaml
        development:
          facebook:
            app_id: 'XXXXXXXXXXXXXX'
            secret: 'YYYYYYYYYYYYYYYYYYYYYYYYYYY'
            callback_host: 'my.dev.host.com'

        production:
          facebook:
            app_id: 'XXXXXXXXXXXXXX'
            secret: 'YYYYYYYYYYYYYYYYYYYYYYYYYYY'
            canvas: 'yourcanvasname'
            callback_host: 'my.production.host.com'
    ```

   If you push to Heroku, your production callback_host should be `yourappname.heroku.com`. You can also access your app directly running `rails server` (or just `rails s`) in your console, but if you do not have an external IP address (e.g. you are behind a NAT), you will need to use a service called a tunnel in order to make your application accessible to the outer world (and Facebook callbacks). You'll find more information on setting up a tunnel here: <http://tunnlr.com/>.

6. Let's create a first controller for your app - ScratchController.

    ``` shell
        rails generate controller Scratch
    ```

7. The next step will be to include rest-more in your controller. You should put this line in:

    ``` ruby
        include RC::Facebook::RailsUtil
    ```

     Now you can make use of the rest-more commands :)

8. To actually use rest-more in a controller action, you will need to first call "rc_facebook_setup", which reads the configuration from the rest-core.yaml and creates a Facebook client.   Let's set this up in a before_filter.

    Add this line after the `include RestGraph::RailsUtil`:

    ``` ruby
        before_filter :filter_setup_facebook
    ```

    And declare filter_setup_facebook as a private function:

    ``` ruby
        private
        def filter_setup_facebook
          rc_facebook_setup(:auto_authorize => true)
        end
    ```

    The `:auto_authorize` argument of `rc_facebook_setup` tells rest-more to redirect users to the app authorization page if the app is not authorized yet.

    Hooray! You can now perform all kinds of Graph API operations using the Facebook client.

9. Let's start with following sample action in the Scratch controller:

    ``` ruby
        def me
          render :text => rc_facebook.get('me').inspect
        end
    ```

10. To run this, go to the /config/routes.rb file to set up the default routing. For now you will just need this line:

    ``` ruby
        match ':controller/:action'
    ```

11. Commit your change in git, and then push to Heroku:

    ``` shell
        git add .
        git commit -m "first test of rest-more using scratch/me"
        git push heroku master
    ```

    After you push your app to Heroku, you can open <http://yourappname.heroku.com/scratch/me> in your browser. If you are not yet logged into Facebook, it will ask you to log in.  If you are logged in your Facebook account, this address should redirect you to the authorization page and ask if you want to let your application access your public information. After you confirm, you should be redirected back to 'scratch/me' action which will show your basic information.

12. To see other information, such as your home feed, is very easy. You can add another sample action to your controller:

    ``` ruby
        def feed
          render :text => rc_facebook.get('me/home').inspect
        end
    ```

    If you will push the changes to Heroku and go to <http://yourappname.heroku.com/scratch/feed>, the page should display a JSON hash with all the data from your Facebook home feed.

13. Now let's try to access your Facebook wall. You need to add a new action to your controller:

    ``` ruby
        def wall
          render :text => rc_facebook.get('me/feed').inspect
        end
    ```

    Note that Facebook's naming is such that your home news feeds is accessed via `me/home` and your profile walls is accessed via `me/feed` ...

    Actually, I need to warn you that this time the action won't work properly. Why? Because users didn't grant you the permission to access their walls! You need to ask them for this special permission and that means you need to add something more to your controller.

    So, we will organize all the permissions we need as a scope and pass them to the `rc_facebook_setup` call. I find it handy to make the scope array and declare what kind of permissions I need just inside this array. If you feel it's a good idea, you can add this line to your private setup function, just before you call `rc_facebook_setup`:

    ``` ruby
        scope = []
        scope << 'read_stream'
    ```

    The only permission you need right now is the 'read_stream' permission. You can find out more about different kinds of user permissions here: <http://developers.facebook.com/docs/authentication/permissions/>

    You also need to add the `auto_authorize_scope` argument to the `rc_facebook_setup`. It will look this way now:

    ``` ruby
        rc_facebook_setup(:auto_authorize => true, :auto_authorize_scope => scope.join(','))
    ```

    As you see, you might as well pass the argument like this `:auto_authorize_scope => 'read_stream'`, but once you have to get a lot of different permissions, it's very useful to put them all in an array, because it's more readable and you can easily delete or comment out any one of them.

    Now save your work and push it to Heroku or just try in your tunneled development environment. /scratch/wall URL should give you the hash with user's wall data now!

    Remember. Anytime you need to get data of a new kind, you need to ask user for a certain permission first and that means you need to declare this permission in your scope array!

14. What else? If you know how to deal with hashes then you will definitely know how to get any kind of data you want using the rest_graph object. Let's say you want to get a last object from a user's wall (last in terms of time, last posted, so the first on the wall and therefore first to Ruby). Let's take a look at the /scratch/feed page. The hash which is printed on this page has 2 keys - data and paging. Let's leave the paging key aside. What's more interesting here comes as a value of 'data'. So the last object in any user's wall will be simply:

    ``` ruby
        rc_facebook.get('me/feed')['data'].first
    ```

    Now let's say you want only to keep the name of the author of this particular object. You can get it by using:

    ``` ruby
        rc_facebook.get('me/feed')['data'].first['from']['name']
    ```

    That's it!

15. More information on customizing rest-more and its functions are to be found here: <https://github.com/godfat/rest-more>


text:
namespace Microsoft.Azure.Management.Sql.Fluent
{
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
    using Microsoft.Azure.Management.Sql.Fluent.Models;

    /// <summary>
    /// An immutable client-side representation of an Azure SQL Database export operation request.
    /// </summary>
    public interface ISqlDatabaseExportRequest  :
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasInner<Models.ExportRequestInner>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IExecutable<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabaseImportExportResponse>,
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasParent<Microsoft.Azure.Management.Sql.Fluent.ISqlDatabase>
    {
    }
}


text:
// Adapted from: https://www.codeproject.com/Articles/18409/Asynchronously-Execute-PowerShell-Scripts-from-C

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.Windows.Threading;

namespace AsyncPowerShellScripter
{
    /// <summary>
    /// Class that assists in asynchronously executing and retrieving the results of a powershell script pipeline.
    /// </summary>
    public class PipelineExecutor
    {
        #region public types, members
        public delegate void DataEndDelegate(PipelineExecutor sender);
        public delegate void DataReadyDelegate(PipelineExecutor sender, ICollection<PSObject> data);
        public delegate void ErrorReadyDelegate(PipelineExecutor sender, ICollection<object> data);
        /// <summary>
        /// Occurs when powershell script completed its execution.
        /// </summary>
        public event DataEndDelegate OnDataEnd;
        /// <summary>
        /// Occurs when there is new data available from the powershell script.
        /// </summary>
        public event DataReadyDelegate OnDataReady;
        /// <summary>
        /// Occurs when there is new errordata available from the powershell script.
        /// </summary>
        public event ErrorReadyDelegate OnErrorReady;
        /// <summary>
        /// Gets the powershell Pipeline associated with this PipelineExecutor
        /// </summary>
        public Pipeline Pipeline
        {
            get
            {
                return pipeline;
            }
        }
        #endregion public types, members

        #region private types, members

        /// <summary>
        /// The object that is used to invoke the events on.
        /// </summary>
        private Dispatcher dispatcher;

        /// <summary>
        /// The powershell script pipeline that will be executed asynchronously.
        /// </summary>
        private Pipeline pipeline;

        /// <summary>
        /// Event set when the user wants to stop script execution.
        /// </summary>
        private ManualResetEvent stopEvent;
        /// <summary>
        /// Local delegate to a private method
        /// </summary>
        private DataEndDelegate synchDataEnd;
        /// <summary>
        /// Local delegate to a private method
        /// </summary>
        private DataReadyDelegate synchDataReady;
        /// <summary>
        /// Local delegate to a private method
        /// </summary>
        private ErrorReadyDelegate synchErrorReady;
        /// <summary>
        /// Array of waithandles, used in the StoppableInvoke() method.
        /// </summary>
        private WaitHandle[] waitHandles;
        #endregion private types, members

        #region public methods
        /// <summary>
        /// Constructor, creates a new PipelineExecutor for the given powershell script.
        /// </summary>
        /// <param name="runSpace">Powershell runspace to use for creating and executing the script.</param>
        /// <param name="dispatcher">The object to synchronize the DataReady and DataEnd events with.
        /// Normally you'd pass the form or component here.</param>
        /// <param name="command">The script to run</param>
        public PipelineExecutor(Runspace runSpace, Dispatcher dispatcher, string command)
        {
            this.dispatcher = dispatcher;

            // initialize delegates
            synchDataReady = new DataReadyDelegate(SynchDataReady);
            synchDataEnd = new DataEndDelegate(SynchDataEnd);
            synchErrorReady = new ErrorReadyDelegate(SynchErrorReady);

            // initialize event members
            stopEvent = new ManualResetEvent(false);
            waitHandles = new WaitHandle[] { null, stopEvent };
            // create a pipeline and feed it the script text
            pipeline = runSpace.CreatePipeline(command);

            // we'll listen for script output data by way of the DataReady event
            pipeline.Output.DataReady += new EventHandler(Output_DataReady);
            pipeline.Error.DataReady += new EventHandler(Error_DataReady);
        }

        /// <summary>
        /// Start executing the script in the background.
        /// </summary>
        public void Start()
        {
            if (pipeline.PipelineStateInfo.State == PipelineState.NotStarted)
            {
                // close the pipeline input. If you forget to do
                // this it won't start processing the script.
                pipeline.Input.Close();
                // invoke the pipeline. This will cause it to process the script in the background.
                pipeline.InvokeAsync();
            }
        }
        /// <summary>
        /// Stop executing the script.
        /// </summary>
        public void Stop()
        {
            // first make sure StoppableInvoke() stops blocking
            stopEvent.Set();
            // then tell the pipeline to stop the script
            pipeline.Stop();
        }
        private void Error_DataReady(object sender, EventArgs e)
        {
            // fetch all available objects
            Collection<object> data = pipeline.Error.NonBlockingRead();

            // if there were any, invoke the ErrorReady event
            if (data.Count > 0)
            {
                StoppableInvoke(synchErrorReady, new object[] { this, data });
            }
        }
        #endregion public methods

        #region private methods

        public bool InvokeRequired
        {
            get { return dispatcher.CheckAccess(); }
        }
        public IAsyncResult BeginInvoke(Delegate method, object[] args)
        {
            return new DispatcherOperationAsync(dispatcher.BeginInvoke(method, args));
        }
        public object EndInvoke(IAsyncResult result)
        {
            result.AsyncWaitHandle.WaitOne();
            if (result is DispatcherOperationAsync)
                return ((DispatcherOperationAsync)result).Result;
            return null;
        }
        public object Invoke(Delegate method, object[] args)
        {
            return InvokeRequired ? EndInvoke(BeginInvoke(method, args)) : method.DynamicInvoke(args);
        }
        /// <summary>
        /// Event handler for the DataReady event of the powershell script pipeline.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Output_DataReady(object sender, EventArgs e)
        {
            // fetch all available objects
            Collection<PSObject> data = pipeline.Output.NonBlockingRead();

            // if there were any, invoke the DataReady event
            if (data.Count > 0)
            {
                StoppableInvoke(synchDataReady, new object[] { this, data });
            }

            if (pipeline.Output.EndOfPipeline)
            {
                // we're done! invoke the DataEnd event
                StoppableInvoke(synchDataEnd, new object[] { this });
            }
        }
        /// <summary>
        /// Special Invoke method that operates similarly to <see cref="ISynchronizeInvoke.Invoke"/> but in addition to that, it can be
        /// aborted by setting the stopEvent. This avoids potential deadlocks that are possible when using the regular
        /// <see cref="ISynchronizeInvoke.Invoke"/> method.
        /// </summary>
        /// <param name="method">A <see cref="System.Delegate"/> to a method that takes parameters of the same number and type that are
        /// contained in <paramref name="args"/></param>
        /// <param name="args">An array of type <see cref="System.Object"/> to pass as arguments to the given method. This can be null if
        /// no arguments are needed </param>
        /// <returns>The <see cref="Object"/> returned by the asynchronous operation</returns>
        private object StoppableInvoke(Delegate method, object[] args)
        {
            IAsyncResult asyncResult = BeginInvoke(method, args);
            waitHandles[0] = asyncResult.AsyncWaitHandle;
            return (WaitHandle.WaitAny(waitHandles) == 0) ? EndInvoke(asyncResult) : null;
        }
        /// <summary>
        /// private DataEnd handling method that will pass the call on to any handlers that are
        /// attached to the OnDataEnd event of this <see cref="PipelineExecutor"/> instance.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private void SynchDataEnd(PipelineExecutor sender)
        {
            DataEndDelegate delegateDataEndCopy = OnDataEnd;
            if (delegateDataEndCopy != null)
            {
                delegateDataEndCopy(sender);
            }
        }
        /// <summary>
        /// private DataReady handling method that will pass the call on to any event handlers that are
        /// attached to the OnDataReady event of this <see cref="PipelineExecutor"/> instance.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private void SynchDataReady(PipelineExecutor sender, ICollection<PSObject> data)
        {
            DataReadyDelegate delegateDataReadyCopy = OnDataReady;
            if (delegateDataReadyCopy != null)
            {
                delegateDataReadyCopy(sender, data);
            }
        }
        /// <summary>
        /// private ErrorReady handling method that will pass the call on to any event handlers that are
        /// attached to the OnErrorReady event of this <see cref="PipelineExecutor"/> instance.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        private void SynchErrorReady(PipelineExecutor sender, ICollection<object> data)
        {
            ErrorReadyDelegate delegateErrorReadyCopy = OnErrorReady;
            if (delegateErrorReadyCopy != null)
            {
                delegateErrorReadyCopy(sender, data);
            }
        }

        #endregion private methods

        #region Internal IAsync Class
        private class DispatcherOperationAsync : IAsyncResult, IDisposable
        {
            private readonly DispatcherOperation _dop;
            private ManualResetEvent _handle = new ManualResetEvent(false);

            #region Implementation of IAsyncResult

            public DispatcherOperationAsync(DispatcherOperation dispatcherOperation)
            {
                _dop = dispatcherOperation;
                _dop.Aborted += DopAborted;
                _dop.Completed += DopCompleted;
            }
            public object AsyncState
            {
                get
                {
                    //Not Implementted
                    return null;
                }
            }
            public WaitHandle AsyncWaitHandle
            {
                get { return _handle; }
            }
            public bool CompletedSynchronously
            {
                get { return false; }
            }
            public bool IsCompleted
            {
                get { return _dop.Status == DispatcherOperationStatus.Completed; }
            }
            public object Result
            {
                get
                {
                    if (!IsCompleted)
                        throw new InvalidAsynchronousStateException("Not Completed");
                    return _dop.Result;
                }
            }
            private void DopAborted(object sender, EventArgs e)
            {
                _handle.Set();
            }
            private void DopCompleted(object sender, EventArgs e)
            {
                _handle.Set();
            }
            #endregion Implementation of IAsyncResult

            #region Implementation of IDisposable

            public void Dispose()
            {
                if (_handle == null) return;
                _handle.Dispose();
                _handle = null;
            }

            #endregion Implementation of IDisposable
        }
        #endregion Internal IAsync Class
    }
}


text:
import json
import logging
import urllib.request

from cogbot import checks
from cogbot.cog_bot import CogBot
from discord.ext import commands
from discord.ext.commands import Context
from discord.ext.commands.errors import *

log = logging.getLogger(__name__)

class MinecraftCommandsConfig:
    DEFAULT_COMMAND_MANIFEST = \
        'https://gist.githubusercontent.com/Arcensoth/0f3f91161352383e65f2259cb4d90230/raw/minecraft_commands.json'
    DEFAULT_COMMAND_PAGE = 'http://minecraft.gamepedia.com/Commands'

    def __init__(self, **options):
        self.command_manifest = options.pop('command_manifest', self.DEFAULT_COMMAND_MANIFEST)
        self.command_page = options.pop('command_page', self.DEFAULT_COMMAND_PAGE)

class MinecraftCommands:
    def __init__(self, bot: CogBot, ext: str):
        self.bot = bot
        options = bot.state.get_extension_state(ext)
        self.config = MinecraftCommandsConfig(**options)
        self.command_messages = {}
        self._reload_commands()

    def _message_lines(self, cmd, data):
        yield '```'

        usage = data.get('usage')

        if usage:
            if not isinstance(usage, list):
                usage = [usage]

            for usage_item in usage:
                yield f'{cmd} {usage_item}'

        else:
            yield cmd

        yield '```'

        see = data.get('see')

        if isinstance(see, str):
            yield f'See: <{see}>'

        elif isinstance(see, list):
            yield 'See:'
            for link in see:
                yield f'    - <{link}>'

        else:
            yield f'See: <{self.config.command_page}#{cmd}>'

    def _reload_commands(self):
        manifest = self.config.command_manifest

        log.info(f'reloading Minecraft commands from: {manifest}')

        response = urllib.request.urlopen(manifest)
        content = response.read().decode('utf8')

        try:
            cmd_data = json.loads(content)
        except Exception as e:
            raise CommandError(f'failed to load command manifest json: {e.args[0]}')

        self.command_messages = {cmd: '\n'.join(self._message_lines(cmd, data)) for cmd, data in cmd_data.items()}

        log.info(f'finished loading {len(cmd_data)} commands')

    async def mcc(self, ctx: Context, command: str):
        if command not in self.command_messages:
            raise CommandNotFound(f'no such Minecraft command "{command}"')
        await self.bot.say(self.command_messages[command])

    async def mccreload(self, ctx: Context):
        try:
            self._reload_commands()
            await self.bot.react_success(ctx)
        except:
            await self.bot.react_failure(ctx)

    @commands.command(pass_context=True, name='mcc')
    async def cmd_mcc(self, ctx: Context, *, command: str):
        await self.mcc(ctx, command)

    @checks.is_manager()
    @commands.command(pass_context=True, name='mccreload', hidden=True)
    async def cmd_mccreload(self, ctx):
        await self.mccreload(ctx)

def setup(bot):
    bot.add_cog(MinecraftCommands(bot, __name__))


text:
//
//  PBBAPopupAnimator.h
//  ZappMerchantLib
//
//  Created by Alexandru Maimescu on 3/3/16.
//  Copyright 2016 IPCO 2012 Limited
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <UIKit/UIKit.h>

/**
 *  Popup animation type
 */
typedef NS_ENUM(NSInteger, PBBAPopupAnimationType) {
    /**
     *  The animation used during presentation
     */
    PBBAPopupAnimationTypePresention,
    /**
     *  The animation used during dismissal
     */
    PBBAPopupAnimationTypeDismissal,
    /**
     *  The animation used during content transition (child view controllers transition)
     */
    PBBAPopupAnimationTypeContentTransition,
    /**
     *  The animation used for scaling down the popup if there is no enough space for it (landscape on small screens)
     */
    PBBAPopupAnimationTypeScaleAspectFit
};

/**
 *  Popup animator
 */
@interface PBBAPopupAnimator : NSObject <UIViewControllerAnimatedTransitioning>

/**
 *  Popup animation type
 */
@property (nonatomic, assign) PBBAPopupAnimationType animationType;

/**
 *  Get an animator instance for given animation type.
 *
 *  @param animationType The animation type.
 *
 *  @return An instance of PBBAPopupAnimator class.
 */
- (instancetype)initWithAnimationType:(PBBAPopupAnimationType)animationType;

@end


text:
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

const client = require('twilio')(accountSid, authToken);

client.lookups.v1
  .phoneNumbers('+16502530000')
  .fetch({ type: 'caller-name' })
  .then(number => console.log(number.carrier.type, number.carrier.name));