text:
package top.spoofer.hbrdd

import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp
import org.apache.spark.{ SparkContext, SparkConf }
import top.spoofer.hbrdd.config.HbRddConfig

object HbMain {
  private val master = "localhost"
  private val port = "7077"
  private val appName = "hbase-rdd_spark"
  private val data = "hdfs://localhost:9000/test/hbase/testhb"

  private def testRdd2Hbase() = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName(appName)

    //    val sparkConf = new SparkConf().setAppName(appName)

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("cf1" -> Map("testqualifier" -> col1), "cf2" -> Map("testqualifier2" -> col2))
      k -> content //(rowID, Map[family, Map[qualifier, value]])
    }).put2Hbase("test_hbrdd")

    sc.stop()
  }

  private def testRdd2HbaseTs() = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf()
      .setMaster(s"spark://$master:$port").set("executor-memory", "2g")
      .setAppName(appName).setJars(List("/home/spoofer/coding/hbrdd/out/artifacts/hbrdd_jar/hbrdd.jar"))

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("cf1" -> Map("testqualifier" -> (123L, col1)))
      k -> content //(rowID, Map[family, Map[qualifier, value]])
    }).put2Hbase("test_hbrdd")

    sc.stop()
  }

  private def testSingleFamilyRdd2Hbase() = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf()
      .setMaster(s"spark://$master:$port").set("executor-memory", "2g")
      .setAppName(appName).setJars(List("/home/spoofer/coding/hbrdd/out/artifacts/hbrdd_jar/hbrdd.jar"))

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("testqualifier" -> col1)
      k -> content //(rowID, Map[family, Map[qualifier, value]])
    }).put2Hbase("test_hbrdd", "cf1")

    sc.stop()
  }

  private def testSingleFamilyRdd2HbaseTs() = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf()
      .setMaster(s"spark://$master:$port").set("executor-memory", "2g")
      .setAppName(appName).setJars(List("/home/spoofer/coding/hbrdd/out/artifacts/hbrdd_jar/hbrdd.jar"))

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("testqualifier" -> (123L, col1))
      k -> content //(rowID, Map[family, Map[qualifier, value]])
    }).put2Hbase("test_hbrdd", "cf1")

    sc.stop()
  }

  private def testReadHbase() = {
    import org.apache.hadoop.hbase.filter.{ FilterList, SingleColumnValueFilter }
    implicit val hbConfig = HbRddConfig()
    val savePath = "hdfs://localhost:9000/test/spark/hbase/calculation_result"

    val sparkConf = new SparkConf()
      .setMaster(s"spark://$master:$port").set("executor-memory", "2g")
      .setAppName(appName).setJars(List("/home/spoofer/coding/hbrdd/out/artifacts/hbrdd_jar/hbrdd.jar"))
    val sc = new SparkContext(sparkConf)

    val filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL)
    val filter1 = new SingleColumnValueFilter("cf1".getBytes, "testqualifier".getBytes, CompareOp.EQUAL, "'S0My9O0dN".getBytes)

    filterList.addFilter(filter1)
    val qualifiers = Set("testqualifier")
    val tableStructure = Map[String, Set[String]]("cf1" -> qualifiers)
    val families = Set[String]("cf1")
    val rdd = sc.readHbase[String]("test_hbrdd", families, filterList)

    println(rdd.count())
    rdd.saveAsTextFile(savePath)

    sc.stop()
  }

  private def testdeleteHbase() = {
    implicit val hbConfig = HbRddConfig()
    val savePath = "hdfs://localhost:9000/test/spark/hbase/calculation_result"

    val sparkConf = new SparkConf()
      .setMaster(s"spark://$master:$port").set("executor-memory", "2g")
      .setAppName(appName).setJars(List("/home/spoofer/coding/hbrdd/out/artifacts/hbrdd_jar/hbrdd.jar"))
    val sc = new SparkContext(sparkConf)

    val ret = sc.parallelize(List("!7ls>'L%yz", "!AIvygne\\9"), 3).deleteHbase("test_hbrdd")

    /* 删除cf2的testqualifier2的内容,  可以指定多个family的多个qualifier */
    //    val ret = sc.parallelize(List("\"'K.\"B\"@bE", "\")l8I=_$@W"), 3).deleteHbase("test_hbrdd", Map("cf1" -> Set("testqualifier")))
    /* 删除cf2的testqualifier2的内容, 可以指定cf2中多个qualifier */
    //    val ret = sc.parallelize(List("!t@B+b3`5?"), 3).deleteHbase("test_hbrdd", "cf2", Set("testqualifier2"))
    /* 删除cf1, 不管cf1中有多少个qualifier */
    //    val ret = sc.parallelize(List("!]emBlu0Gd", "!c+LpGh-UN"), 3).deleteHbase("test_hbrdd", Set("cf1"))

    println(ret.getClass)
    sc.stop()
  }

  private def testdeleteHbase1() = {
    implicit val hbConfig = HbRddConfig()
    val savePath = "hdfs://localhost:9000/test/spark/hbase/calculation_result"

    val sparkConf = new SparkConf()
      .setMaster(s"spark://$master:$port").set("executor-memory", "1g")
      .setAppName(appName).setJars(List("/home/spoofer/coding/hbrdd/out/artifacts/hbrdd_jar/hbrdd.jar"))
    val sc = new SparkContext(sparkConf)

    val qualifier = Set("testqualifier")

    //    val rdd = sc.parallelize(List("!Hv[|[-K*o", "!IOJ]'M%o5"), 3).map({ rowId =>
    ////      val content = Map("cf1" -> Set("testqualifier"))
    //      rowId  -> Set("testqualifier")
    //    })
    //
    //    rdd.deleteHbase("test_hbrdd", "cf1")
    //    rdd.saveAsTextFile(savePath)

    val ret = sc.textFile(data).map({ line =>
      val Array(rowId, col1, col2, _) = line split "\t"
      val content = Map("cf1" -> Set("testqualifier"))
      rowId -> content //(rowID, Map[family, Set[qualifier]])
    }).deleteHbase("test_hbrdd")

    println(ret.getClass)
    sc.stop()
  }

  private def testSimpleHbaseBluk(): Unit = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName(appName)

    //    val sparkConf = new SparkConf().setAppName(appName)

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("testqualifier" -> col1)
      k -> content //(rowID, Map[qualifier, value])
    }).saveToHbaseByBulk("test_hbrdd", "cf1")

    sc.stop()
  }

  private def testSimpleHbaseBlukTs() = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName(appName)

    //    val sparkConf = new SparkConf().setAppName(appName)

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("testqualifier" -> (System.currentTimeMillis(), col1))
      k -> content //(rowID, Map[qualifier, value])
    }).saveToHbaseByBulk("test_hbrdd", "cf1")

    sc.stop()
  }

  private def testHbaseBluk() = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName(appName)

    //    val sparkConf = new SparkConf().setAppName(appName)

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("cf1" -> Map("testqualifier" -> col1))
      k -> content //(rowID, Map[qualifier, value])
    }).saveToHbaseByBulk("test_hbrdd")

    sc.stop()
  }

  private def testHbaseBlukTs() = {
    implicit val hbConfig = HbRddConfig()

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName(appName)

    //    val sparkConf = new SparkConf().setAppName(appName)

    val sc = new SparkContext(sparkConf)
    val ret = sc.textFile(data).map({ line =>
      val Array(k, col1, col2, _) = line split "\t"
      val content = Map("cf1" -> Map("testqualifier" -> (System.currentTimeMillis(), col1)))
      k -> content //(rowID, Map[qualifier, value])
    }).saveToHbaseByBulk("test_hbrdd")

    sc.stop()
  }

  def main(args: Array[String]) {
    System.setProperty("HADOOP_USER_NAME", "spoofer")
    //    this.testHbaseBlukTs()
    //    this.testHbaseBluk()
    //    this.testRdd2Hbase()
    //    this.testSimpleHbaseBluk()
    //    this.testSimpleHbaseBlukTs()
    this.testReadHbase()
    //    this.testSingleFamilyRdd2Hbase()
    //    this.testdeleteHbase()
    //    this.testdeleteHbase1()
  }
}


text:
ActionMailer::Base.delivery_method = Settings.mail.delivery_method.to_sym

ActionMailer::Base.default_url_options[:host] = Settings.application.hostname

redpajama_set_name: RedPajamaGithub


text:
package androidx.wear.watchface.complications.rendering.utils;

import android.graphics.Rect;
import android.support.wearable.complications.ComplicationData;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;

/**
 * Common superclass for layout helpers. Layout helpers are used to calculate bounds for each
 * element depending on width, height of the complication and complication data.
 *
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY)
public class LayoutHelper {

    private final Rect mBounds = new Rect();
    private ComplicationData mComplicationData;

    /** Returns the complication bounds assuming it's positioned at (0,0). */
    public void getBounds(@NonNull Rect outRect) {
        outRect.set(mBounds);
    }

    /**
     * @param width The width to apply to the layout's bounds
     */
    public void setWidth(int width) {
        mBounds.right = width;
    }

    /**
     * @param height The height to apply to the layout's bounds
     */
    public void setHeight(int height) {
        mBounds.bottom = height;
    }

    /**
     * @param data The {@link ComplicationData} to associate with this {@link LayoutHelper}
     */
    public void setComplicationData(@Nullable ComplicationData data) {
        mComplicationData = data;
    }

    /** Updates layout helper with given parameters. */
    public void update(int width, int height, @Nullable ComplicationData data) {
        setWidth(width);
        setHeight(height);
        setComplicationData(data);
    }

    /**
     * @return The {@link ComplicationData} associated with this {@link LayoutHelper}
     */
    @Nullable
    public ComplicationData getComplicationData() {
        return mComplicationData;
    }

    /**
     * @param outRect {@link Rect} that receives the computed bounds for the icon
     */
    public void getIconBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @param outRect {@link Rect} that receives the computed bounds for the small image
     */
    public void getSmallImageBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @param outRect {@link Rect} that receives the computed bounds for the large image
     */
    public void getLargeImageBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @param outRect {@link Rect} that receives the computed bounds for the ranged value
     */
    public void getRangedValueBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @param outRect {@link Rect} that receives the computed bounds for the short title text
     */
    public void getShortTextBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @return The {@link Layout.Alignment} to use with short text
     */
    @NonNull
    public Layout.Alignment getShortTextAlignment() {
        return Alignment.ALIGN_CENTER;
    }

    /**
     * @return Gravity to use with short text
     */
    public int getShortTextGravity() {
        return Gravity.CENTER;
    }

    /**
     * @param outRect {@link Rect} that receives the computed bounds for the short title text
     */
    public void getShortTitleBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @return The {@link Layout.Alignment} to use with short title text
     */
    @NonNull
    public Layout.Alignment getShortTitleAlignment() {
        return Alignment.ALIGN_CENTER;
    }

    /**
     * @return Gravity to use with short title text
     */
    public int getShortTitleGravity() {
        return Gravity.CENTER;
    }

    /**
     * @param outRect {@link Rect}  that receives the computed bounds for the long text
     */
    public void getLongTextBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @return The {@link Layout.Alignment} to use with long text
     */
    @NonNull
    public Layout.Alignment getLongTextAlignment() {
        return Alignment.ALIGN_CENTER;
    }

    /**
     * @return Gravity to use with long title text
     */
    public int getLongTextGravity() {
        return Gravity.CENTER;
    }

    /**
     * @param outRect {@link Rect}  that receives the computed bounds for the long title text
     */
    public void getLongTitleBounds(@NonNull Rect outRect) {
        outRect.setEmpty();
    }

    /**
     * @return The {@link Layout.Alignment} to use with long title text
     */
    @NonNull
    public Layout.Alignment getLongTitleAlignment() {
        return Alignment.ALIGN_CENTER;
    }

    /**
     * @return The gravity to use with Long Title Text
     */
    public int getLongTitleGravity() {
        return Gravity.CENTER;
    }

    /**
     * @return Whether or not the complication has an icon.
     */
    public boolean hasIcon() {
        return mComplicationData.getIcon() != null;
    }

    /**
     * @return Whether or not the complication has a small image.
     */
    public boolean hasSmallImage() {
        return mComplicationData.getSmallImage() != null;
    }

    /**
     * @return Whether or not the complication has a long title.
     */
    public boolean hasLongTitle() {
        return mComplicationData.getLongTitle() != null;
    }

    /**
     * @return Whether or not the complication has a short title.
     */
    public boolean hasShortTitle() {
        return mComplicationData.getShortTitle() != null;
    }

    /**
     * @return Whether or not the complication has a short text.
     */
    public boolean hasShortText() {
        return mComplicationData.getShortText() != null;
    }
}


text:
import {pickState} from '../utils'

test('pickState only picks state that downshift cares about', () => {
  const otherStateToSet = {
    isOpen: true,
    foo: 0,
  }
  const result = pickState(otherStateToSet)
  const expected = {isOpen: true}
  const resultKeys = Object.keys(result)
  const expectedKeys = Object.keys(expected)
  resultKeys.sort()
  expectedKeys.sort()
  expect(result).toEqual(expected)
  expect(resultKeys).toEqual(expectedKeys)
})


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=enum.locale_t.html">

Redirecting to enum.locale_t.html...


text:
package imagej.workflowpipes.pipesentity;

import java.io.Serializable;
import java.util.ArrayList;

import org.json.JSONObject;

/**
 * Represents the pipes prop type
 * @author rick
 *
 */
public class Prop implements Serializable {

	private Connector connector;

	public Prop( Connector connector )
	{
		this.connector = connector;
	}

	public static JSONObject getJSON( ArrayList<Prop> props )
	{
		JSONObject jsonObject = new JSONObject();
		for(Prop prop : props )
		{
			// add the prop
			jsonObject.put( prop.getConnector().getConnectorID(), prop.getConnector().getJSON() );
		}

		return jsonObject;
	}

	public Connector getConnector()
	{
		return connector;
	}
}


text:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite1" verbose="1">
    <test name="Vitrinas-MGE" >
        <classes>
            <class name="ru.stqa.pft.gge.tests.VitrinaOpenTestsMGE" />
        </classes>
    </test>
</suite>


text:
import slice from "../core/slice";

/**
 * Inserts the provided element in a copy of an array-like object at the
 * specified index.

 * If the index is greater than the length of the array-like, the element
 * will be appended at the end.

 * Negative indexes are allowed; when a negative index is out of bounds
 * the element will be inserted at the start of the resulting array.
 * @example
 * const arr = [1, 2, 3, 4, 5];
 *
 * _.insert(arr, 3, 99) // => [1, 2, 3, 99, 4, 5]
 * _.insert(arr, -2, 99) // => [1, 2, 3, 99, 4, 5]
 * _.insert(arr, 10, 99) // => [1, 2, 3, 4, 5, 99]
 * _.insert(arr, -10, 99) // => [99, 1, 2, 3, 4, 5]
 *
 * @memberof module:lamb
 * @category Array
 * @see {@link module:lamb.insertAt|insertAt}
 * @see {@link module:lamb.sortedInsert|sortedInsert}
 * @see {@link module:lamb.append|append}, {@link module:lamb.appendTo|appendTo}
 * @since 0.1.0
 * @param {ArrayLike} arrayLike
 * @param {Number} index
 * @param {*} element
 * @returns {Array}
 */
function insert (arrayLike, index, element) {
    var result = slice(arrayLike, 0, arrayLike.length);

    result.splice(index, 0, element);

    return result;
}

export default insert;


text: (crontab -l ; cat /usr/local/lib/node_modules/escapephone/crontab.txt) | sort -u | crontab -


text:
(function () {
  'use strict';

  angular
    .module('registrations')
    .controller('RegistrationsListController', RegistrationsListController);

  RegistrationsListController.$inject = ['RegistrationsService'];

  function RegistrationsListController(RegistrationsService) {
    var vm = this;

    vm.registrations = RegistrationsService.query();
  }
})();


text:
"""
Proxy Backends
------------------

Provides a utility and a decorator class that allow for modifying the behavior
of different backends without altering the class itself or having to extend the
base backend.

.. versionadded:: 0.5.0  Added support for the :class:`.ProxyBackend` class.

"""

from .api import CacheBackend

class ProxyBackend(CacheBackend):
    """A decorator class for altering the functionality of backends.

    Basic usage::

        from yosai_dpcache.cache import make_region
        from yosai_dpcache.cache.proxy import ProxyBackend

        class MyFirstProxy(ProxyBackend):
            def get(self, key):
                # ... custom code goes here ...
                return self.proxied.get(key)

            def set(self, key, value):
                # ... custom code goes here ...
                self.proxied.set(key)

        class MySecondProxy(ProxyBackend):
            def get(self, key):
                # ... custom code goes here ...
                return self.proxied.get(key)

        region = make_region().configure(
            'yosai_dpcache.cache.dbm',
            expiration_time = 3600,
            arguments = {
                "filename":"/path/to/cachefile.dbm"
            },
            wrap = [ MyFirstProxy, MySecondProxy ]
        )

    Classes that extend :class:`.ProxyBackend` can be stacked
    together.  The ``.proxied`` property will always
    point to either the concrete backend instance or
    the next proxy in the chain that a method can be
    delegated towards.

    .. versionadded:: 0.5.0

    """

    def __init__(self, *args, **kwargs):
        self.proxied = None

    def wrap(self, backend):
        ''' Take a backend as an argument and setup the self.proxied property.
        Return an object that be used as a backend by a :class:`.CacheRegion`
        object.
        '''
        assert(
            isinstance(backend, CacheBackend) or
            isinstance(backend, ProxyBackend))
        self.proxied = backend
        return self

    #
    # Delegate any functions that are not already overridden to
    # the proxies backend
    #
    def get(self, key):
        return self.proxied.get(key)

    def set(self, key, value):
        self.proxied.set(key, value)

    def delete(self, key):
        self.proxied.delete(key)

    def get_multi(self, keys):
        return self.proxied.get_multi(keys)

    def set_multi(self, mapping):
        self.proxied.set_multi(mapping)

    def delete_multi(self, keys):
        self.proxied.delete_multi(keys)

    def get_mutex(self, key):
        return self.proxied.get_mutex(key)

    def keys(self, pattern):
        return self.proxied.keys(pattern)


text:
{% assign minutes = content | number_of_words | divided_by: 180 %}
{% if minutes == 0 %}
{% assign minutes = 1 %}
{% endif %}

<span class="reading-time" title="Estimated read time">
  {% assign words = content | number_of_words %}
  {% if words < 360 %}
    1 min
  {% else %}
    {{ words | divided_by:180 }} mins
  {% endif %}
</span>


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

namespace Multiverse.Tools.WorldEditor
{
    public class CopyToClipboardCommandFactory : ICommandFactory
    {
        // bool notCopy = false;
        WorldEditor app;
        List<IWorldObject> copyObjects;

        public CopyToClipboardCommandFactory(WorldEditor worldEditor, List<IWorldObject> copyObjects)
        {
            this.app = worldEditor;
            this.copyObjects = copyObjects;
            foreach (IWorldObject obj in copyObjects)
            {
                if (obj.IsTopLevel)
                {
                    continue;
                }
                return;
            }
        }

        public ICommand CreateCommand()
        {
            ICommand cmd = new CopyToClipboardCommand(app, copyObjects);
            return cmd;

        }
    }
}


text:
define(
  ["dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/_base/array",
    'dojo/_base/html',
    "dojo/on",
    "dojo/query",
    "dijit/_WidgetsInTemplateMixin",
    "dijit/registry",
    "jimu/BaseWidgetSetting",
    'jimu/dijit/ImageChooser',
    "dojo/text!./Edit.html",
    "jimu/dijit/ServiceURLInput",
    "jimu/SpatialReference/wkidUtils",
    'jimu/utils',
    "../utils"
  ],
  function(
    declare,
    lang,
    array,
    html,
    on,
    query,
    _WidgetsInTemplateMixin,
    registry,
    BaseWidgetSetting,
    ImageChooser,
    template,
    ServiceURLInput,
    SRUtils,
    jimuUtils,
    utils) {
    return declare([BaseWidgetSetting, _WidgetsInTemplateMixin], {
      baseClass: "jimu-basemapgallery-Edit",
      ImageChooser: null,
      templateString: template,
      validUrl: false,
      mapName: null,
      subLayerUrlNum: 0,
      urlInputS: [],
      baseMapSRID: null,
      spatialReference: null,

      postCreate: function() {
        this.inherited(arguments);

        this.imageChooser = new ImageChooser({
          cropImage: true,
          defaultSelfSrc: this.folderUrl + "images/default.jpg",
          showSelfImg: true,
          format: [ImageChooser.GIF, ImageChooser.JPEG, ImageChooser.PNG],
          goldenWidth: 84,
          goldenHeight: 67
        });

        html.addClass(this.imageChooser.domNode, 'img-chooser');
        html.place(this.imageChooser.domNode, this.imageChooserBase, 'replace');

        this.own(on(this.url, 'Change', lang.hitch(this, '_onServiceUrlChange')));
        this.title.proceedValue = false;
        this.own(on(this.title, 'Change', lang.hitch(this, '_onBaseMapTitleChange')));
        this.url.proceedValue = false;
        this.url.setProcessFunction(lang.hitch(this, '_onServiceFetch', this.url),
          lang.hitch(this, '_onServiceFetchError'));
      },

      startup: function() {
        var thumbnailUrl;
        if (this.basemap && this.basemap.title) {
          this.title.set('value', this.basemap.title);
        }
        if (this.basemap && this.basemap.thumbnailUrl) {
          if (this.basemap.thumbnailUrl.indexOf('//') === 0) {
            thumbnailUrl = this.basemap.thumbnailUrl + this.token;
          } else {
            thumbnailUrl = jimuUtils.processUrlInWidgetConfig(this.basemap.thumbnailUrl,
              this.folderUrl);
          }
        } else {
          thumbnailUrl = this.folderUrl + "images/default.jpg";
        }
        this.imageChooser.setDefaultSelfSrc(thumbnailUrl);

        if (this.basemap && this.basemap.layers) {
          if (utils.isNoUrlLayerMap(this.basemap)) {
            html.destroy(this.urlPart);
            html.setStyle(this.secondTable, 'display', 'none');
            html.setStyle(this.settingContentDiv, 'height', '150px');
          } else {
            var numLayer = this.basemap.layers.length;
            if (this.basemap.layers[0] && this.basemap.layers[0].url) {
              this.url.set('value', this.basemap.layers[0].url);
            }
            for (var j = 1; j < numLayer; j++) {
              this.addLayerUrl(this.basemap.layers[j].url);
            }
          }
        }
      },

      _onServiceUrlChange: function() {
        this.popup.disableButton(0);
      },

      _checkTitle: function(title) {
        var validTitle = true;
        for (var i = 0; i < this.basemaps.length; i++) {
          if (this.basemaps[i].title === title) {
            if (this.basemap && this.basemap.title === title) {
              validTitle = true;
            } else {
              validTitle = false;
            }
          }
        }
        return validTitle;
      },

      _onBaseMapTitleChange: function(title) {
        // this._checkRequiredField();
        var validTitle = this._checkTitle(title);
        var errorMessage = null;
        if (!title) {
          this.title.proceedValue = false;
        } else if (validTitle) {
          this.title.proceedValue = true;
        } else {
          this.title.proceedValue = false;
          errorMessage = this.nls.invalidTitle1 + title + this.nls.invalidTitle2;
        }
        this._checkProceed(errorMessage);
      },

      _checkProceed: function(errorMessage) {
        var canProceed = true;
        var urlDijits = [];
        html.setAttr(this.errorMassage, 'innerHTML', '');
        if (this.title.proceedValue) {
          urlDijits = this._getUrlDijits();
          for (var i = 0; i < urlDijits.length; i++) {
            canProceed = canProceed && urlDijits[i].proceedValue;
          }
        } else {
          canProceed = false;
        }
        if (canProceed) {
          this.popup.enableButton(0);
        } else {
          this.popup.disableButton(0);
          if (errorMessage) {
            html.setAttr(this.errorMassage, 'innerHTML', errorMessage);
          }
        }
      },

      _onServiceFetch: function(urlDijit, evt) {
        var result = false;
        var errorMessage = null;
        var url = evt.url.replace(/\/*$/g, '');
        if (this._isStringEndWith(url, '/MapServer') ||
          this._isStringEndWith(url, '/ImageServer')) {
          var curMapSpatialRefObj = this.map.spatialReference;
          var basemapSpatialRefObj = evt.data.spatialReference ||
            evt.data.extent.spatialReference ||
            evt.data.initialExtent.spatialReference ||
            evt.data.fullExtent.spatialReference;
          if (curMapSpatialRefObj &&
            basemapSpatialRefObj &&
            SRUtils.isSameSR(curMapSpatialRefObj.wkid, basemapSpatialRefObj.wkid)) {
            urlDijit.proceedValue = true;
            result = true;
          } else {
            urlDijit.proceedValue = false;
            result = false;
            errorMessage = this.nls.invalidBasemapUrl2;
          }
        } else {
          urlDijit.proceedValue = false;
          result = false;
          errorMessage = this.nls.invalidBasemapUrl1;
        }

        this._checkProceed(errorMessage);
        return result;
      },

      _isStringEndWith: function(s, endS) {
        return (s.lastIndexOf(endS) + endS.length === s.length);
      },

      _onServiceFetchError: function() {},

      onAddLayerUrl: function() {
        this.addLayerUrl();
      },

      addLayerUrl: function(url) {
        /*jshint unused: false*/
        var urlTrDom = html.create('tr', {}, this.body);
        var urlFirstTdDom = html.create('td', {
          'class': 'first'
        }, urlTrDom);
        var urlSecondTdDom = html.create('td', {
          'class': 'second'
        }, urlTrDom);

        var urlThirdTdDom = html.create('td', {
          'class': 'third'
        }, urlTrDom);

        var urlInput = new ServiceURLInput({
          placeHolder: this.nls.urlPH,
          required: true,
          proceedValue: 0,
          style: {
            width: "100%"
          }
        }).placeAt(urlSecondTdDom);
        html.addClass(urlInput.domNode, "url_field_dom");

        if (url) {
          urlInput.set('value', url);
        }

        var deleteSpanDom = html.create('span', {
          'class': 'delete-layer-url-icon'
        }, urlThirdTdDom);

        urlInput.setProcessFunction(lang.hitch(this, '_onServiceFetch', urlInput),
          lang.hitch(this, '_onServiceFetchError'));
        this.own(on(deleteSpanDom, 'click', lang.hitch(this, '_onDeleteClick', urlTrDom)));
        this._checkProceed();
      },

      _onDeleteClick: function(urlTrDom) {
        html.destroy(urlTrDom);
        this._checkProceed();
      },

      _getUrlDijits: function() {
        var urlDijits = [];
        query(".url_field_dom", this.firstTable).forEach(lang.hitch(this, function(urlDom) {
          urlDijits.push(registry.byNode(urlDom));
        }));
        return urlDijits;
      },

      _getEditedBaseMap: function() {
        var basemap = {
          title: jimuUtils.stripHTML(this.title.value),
          thumbnailUrl: utils.getStanderdUrl(this.imageChooser.imageData),
          layers: [],
          spatialReference: (this.basemap && this.basemap.spatialReference) ||
            this.map.spatialReference
        };

        // do not update basmaps if map is bingMap or openstreetMap
        if (utils.isNoUrlLayerMap(this.basemap)) {
          basemap.layers = this.basemap.layers;
        } else {
          array.forEach(this._getUrlDijits(), function(urlDijit) {
            basemap.layers.push({
              url: urlDijit.value
            });
          }, this);
        }

        return basemap;
      },

      _onEditOk: function(settingWidget) {
        if (this.basemap) {
          //this.basemap = this._getEditedBaseMap();
          settingWidget.basemaps[settingWidget._findBaseMapByTitle(this.basemap.title)] =
            this._getEditedBaseMap();
        } else {
          settingWidget.basemaps.push(this._getEditedBaseMap());
        }
        settingWidget.popup.close();

        settingWidget.refreshMapGallary();
      },

      _onEditClose: function(settingWidget) {
        if (settingWidget.popup) {
          settingWidget.popup.close();
        }
        this.destroy();
      }

    });
  });


text:
<?php

namespace Synapse\Cmf\Framework\Engine\Context\Content;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Synapse\Cmf\Framework\Theme\Content\Resolver\ContentResolver;
use Synapse\Cmf\Framework\Engine\Resolver\TemplateResolver;
use Synapse\Cmf\Framework\Engine\Resolver\VariationResolver;
use Synapse\Cmf\Framework\Theme\Content\Entity\Content;
use Synapse\Cmf\Framework\Theme\Content\Model\ContentInterface;
use Synapse\Cmf\Framework\Theme\Theme\Model\ThemeInterface;
use Synapse\Cmf\Framework\Theme\Variation\Entity\VariationContext;

/**
 * Builder class for synapse rendering context.
 */
class RenderingContextBuilder
{
    /**
     * @var TemplateResolver
     */
    protected $templateResolver;

    /**
     * @var ContentResolver
     */
    protected $contentResolver;

    /**
     * @var VariationResolver
     */
    protected $variationResolver;

    /**
     * @var OptionsResolver
     */
    protected $optionsResolver;

    /**
     * @var array
     */
    protected $options;

    /**
     * Construct.
     *
     * @param TemplateResolver  $templateResolver
     * @param ContentResolver   $contentResolver
     * @param VariationResolver $variationResolver
     */
    public function __construct(
        TemplateResolver $templateResolver,
        ContentResolver $contentResolver,
        VariationResolver $variationResolver
    ) {
        $this->templateResolver = $templateResolver;
        $this->contentResolver = $contentResolver;
        $this->variationResolver = $variationResolver;
        $this->options = array();
        $this->optionsResolver = new OptionsResolver();

        $this->optionsResolver->setDefault('templateTypeName', null);
        $this->optionsResolver->setAllowedTypes('templateTypeName', array('string', 'null'));
        $this->optionsResolver->setRequired('content');
        $this->optionsResolver->setAllowedTypes('content', ContentInterface::class);
        $this->optionsResolver->setRequired('theme');
        $this->optionsResolver->setAllowedTypes('theme', ThemeInterface::class);
    }

    /**
     * Create context from defined members.
     *
     * @return RenderingContext
     */
    public function createContext()
    {
        // context options
        $resolvedOptions = $this->optionsResolver->resolve($this->options);
        $resolvedOptions['content'] = $this->contentResolver->resolve(
            $resolvedOptions['content']
        );

        // create variation
        $variation = $this->variationResolver->resolve(
            (new VariationContext())->denormalize($resolvedOptions)
        );

        return new RenderingContext(
            $resolvedOptions['content'],
            $resolvedOptions['theme'],
            $this->templateResolver->resolve(
                $resolvedOptions['theme'],
                $resolvedOptions['content'],
                $variation,
                $resolvedOptions['templateTypeName']
            ),
            $variation
        );
    }

    /**
     * Define context builder content.
     *
     * @param ContentInterface|Content $content
     *
     * @return self
     */
    public function setContent($content)
    {
        $this->options['content'] = $content;

        return $this;
    }

    /**
     * Define context builder theme.
     *
     * @param ThemeInterface $theme
     *
     * @return self
     */
    public function setTheme(ThemeInterface $theme)
    {
        $this->options['theme'] = $theme;

        return $this;
    }

    /**
     * Define context builder template type name.
     *
     * @param string $templateTypeName
     *
     * @return self
     */
    public function setTemplateTypeName($templateTypeName)
    {
        $this->options['templateTypeName'] = $templateTypeName;

        return $this;
    }
}


text:
#include "common.h"
#include "common/imanager.h"

std::vector<IManager*>* IManager::managers = NULL;
std::vector<IManager*>* IManager::pending = NULL;

// add manager to registry
IManager::IManager()
{
	// make managers vector
	if (!pending)
		pending = new std::vector<IManager*>;

	// register
	pending->push_back(this);
}

// initialize a manager if not already handled
int IManager::require(IManager& manager)
{
	// make managers vector
	if (!managers)
		managers = new std::vector<IManager*>;

	// already initialized?
	if (std::find(managers->begin(), managers->end(), &manager) != managers->end())
		return 0;

	// try initialization
	if (manager.initialize())
		return 1;

	// add to pending list
	managers->push_back(&manager);

	// all good!
	return 0;
}

// load all managers
int IManager::initializeAll()
{
	// load manager
	for (std::vector<IManager*>::iterator i = pending->begin(); i != pending->end(); ++i)
		if (IManager::require(**i))
			return -1;

	// release pending list
	delete pending;
	pending = NULL;

	return 0;
}

// shutdown all managers
void IManager::shutdownAll()
{
	for (std::vector<IManager*>::reverse_iterator i = managers->rbegin(); i != managers->rend(); ++i)
		(*i)->shutdown();
}

// save state for all managers
void IManager::saveAll()
{
	for (std::vector<IManager*>::reverse_iterator i = managers->rbegin(); i != managers->rend(); ++i)
		(*i)->save();
}


text:
package wolf;
import java.util.ArrayList;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
/**
 * A symbol table.
 * @author (Kevin Dittmar)
 * @author (William Ezekiel)
 * @author (Joseph Alacqua)
 * @version Apr 3, 2016
 */
public class SymbolTable {
  Map<String, Binding> symbol_table;
  SymbolTable parent_table;
  String table_name;

  /**
   * Create a symbol table
   * @param table_name it the name of the table
   */
  public SymbolTable(String table_name) {
    symbol_table = new LinkedHashMap();
    this.table_name = table_name;
  }

  /**
   * @param parent_table is the parent table of this symbol table
   * @param table_name is the name of this symbol table
   */
  public SymbolTable(SymbolTable parent_table, String table_name) {
    this(table_name);
    this.parent_table = parent_table;
  }

  /**
   * Put an item into the symbol table.
   * @param i an identifier
   * @param b a binding
   * @return the updated symbol table or null if the identifier already exists
   *    in symbol table.
   */
  public SymbolTable put(Identifier i, Binding b) {
    if(!symbol_table.containsKey(i.identifier.getText())) {
      symbol_table.put(i.identifier.getText(),b);
      return this;
    }
    System.err.println("Identifier " + i + " already defined in this context");
    return null;
  }

  public Binding lookup(Identifier i) {
      return symbol_table.get(i.identifier.getText());
  }

  /**
   * @return string representation of a symbol table
   */
  @Override
  public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append(paddedTableString("-----Table " + table_name + "-----"))
        .append("\n")
        .append(paddedTableString("Identifier"))
        .append(paddedTableString("Binding"))
        .append(paddedTableString("Table"))
        .append("\n");
      for(String key: symbol_table.keySet()) {
          Binding b = symbol_table.get(key);
          Identifier id = b.identifier;
          Type type = b.table_value.type;
          SymbolTable sym_table = b.table_value.table;
          sb.append(paddedTableString(id.toString()))
            .append(paddedTableString(type.toString()));
          if (sym_table != null) {
              sb.append(paddedTableString("Table " + sym_table.table_name));
          }
          sb.append("\n");
      }
      return sb.toString();
  }

      /**
     * @param string a string
     * @return a padded string for the string representation
     * of this parse table.
     */
    private String paddedTableString(String string) {
        int left_num_spaces =
            (Math.max(40, string.length()) - string.length()) / 2 + 1;
        int right_num_spaces = left_num_spaces + (string.length() % 2);
        return String.format(
            "%" + left_num_spaces + "s" +   // left spaces
            "%s" +                          // table contents
            "%" + right_num_spaces + "s",   // right spaces
            " ", string, " "
        );
    }

    /**
     * @return the number of arguments expected for the function associated
     * with this table.
     */
    public int getNumberOfArguments() {
        int count = 0;
        for(Binding binding:symbol_table.values()) {
            if(!binding.hasTable()) {
                count++;
            }
        }
        return count;
    }

    /**
     * @return the arg types for the function associated with this table.
     */
    public List<Type> getArgFormat() {
        List<Type> argTypes = new ArrayList();
        for(Binding binding:symbol_table.values()) {
            if(!binding.hasTable()) {
                argTypes.add(binding.table_value.type);
            }
        }
        return argTypes;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `from_raw_buf` fn in crate `core`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, from_raw_buf">

    <title>core::slice::from_raw_buf - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

core::<wbr>slice

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Function core::<wbr>slice::<wbr>from_raw_buf<wbr>Deprecated
            [-] [+]
        [src]

pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: usize) -> &'a [T]

Forms a slice from a pointer and a length.

The pointer given is actually a reference to the base of the slice. This
reference is used to give a concrete lifetime to tie the returned slice to.
Typically this should indicate that the slice is valid for as long as the
pointer itself is valid.

The len argument is the number of elements, not the number of bytes.

This function is unsafe as there is no guarantee that the given pointer is
valid for len elements, nor whether the lifetime provided is a suitable
lifetime for the returned slice.

Example
fn main() {
    use std::slice;

    // manifest a slice out of thin air!
    let ptr = 0x1234 as *const usize;
    let amt = 10;
    unsafe {
        let slice = slice::from_raw_buf(&ptr, amt);
    }
}

use std::slice;

// manifest a slice out of thin air!
let ptr = 0x1234 as *const usize;
let amt = 10;
unsafe {
    let slice = slice::from_raw_buf(&ptr, amt);
}

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Colorpicker</title>

    <link rel="stylesheet" href="colorpicker.css">

Colorpicker


text:
from collections import defaultdict
from traceback import format_exception
import sys
import time

from pyrsistent import v
from twisted.python.reflect import fullyQualifiedName as fully_qualified_name
import attr

@attr.s
class _DelayedMessage:
    """
    A test status message that will be shown at the end of a run.
    """

    width = attr.ib()
    status = attr.ib()
    subject = attr.ib()
    body = attr.ib(default=())

    def lines(self):
        yield "=" * self.width
        yield "\n"
        yield self.status
        yield "\n"
        if self.body:
            yield self.body

class Outputter:

    _last_test_class = None
    _last_test_module = None

    FAILED, PASSED = "FAILED", "PASSED"
    ERROR, FAIL, OK, SKIPPED = "[ERROR]", "[FAIL]", "[OK]", "[SKIPPED]"
    EXPECTED_FAILURE, UNEXPECTED_SUCCESS = "[XFAIL]", "[UNEXPECTED SUCCESS]"

    _COLORS = [
        ("_error", "RED", ERROR),
        ("_fail", "RED", FAIL),
        ("_failed", "RED", FAILED),
        ("_ok", "GREEN", OK),
        ("_passed", "GREEN", PASSED),
        ("_skipped", "BLUE", SKIPPED),
        ("_unexpected_success", "YELLOW", UNEXPECTED_SUCCESS),
        ("_expected_failure", "BLUE", EXPECTED_FAILURE),
    ]

    def __init__(self, colored=True, indent=" " * 2, line_width=120):
        self.indent = indent
        self.line_width = line_width

        if colored:
            from colorama import Fore, Style
            for attribute, color, text in self._COLORS:
                color = getattr(Fore, color)
                message = f"{Style.BRIGHT}{color}{text}{Style.RESET_ALL}"
                setattr(self, attribute, message)
        else:
            for attribute, _, text in self._COLORS:
                setattr(self, attribute, text)

        self._later = {
            status: defaultdict(list) for status in [
                self.SKIPPED,
                self.EXPECTED_FAILURE,
                self.FAIL,
                self.UNEXPECTED_SUCCESS,
                self.ERROR,
            ]
        }

    def _show_later(self, **kwargs):
        message = _DelayedMessage(width=self.line_width, **kwargs)
        self._later[message.status][message.body].append(message)

    def run_started(self):
        pass

    def run_stopped(self, recorder, runtime):
        for status in self._later.values():
            for messages in status.values():
                if not messages:
                    continue
                yield "\n"
                yield from messages[0].lines()
                for message in messages:
                    yield "\n"
                    yield _test_name(message.subject)

        yield "\n"
        yield "-" * self.line_width
        tests = "tests" if recorder.testsRun != 1 else "test"
        yield f"\nRan {recorder.testsRun} {tests} in {runtime:.3f}s\n\n"
        if recorder.wasSuccessful():
            yield self._passed
        else:
            yield self._failed

        if recorder.testsRun:
            yield " ("
            summary = []
            for attribute in (
                "successes",
                "skips",
                "failures",
                "errors",
                "expected_failures",
                "unexpected_successes",
            ):
                subcount = len(getattr(recorder, attribute))
                if subcount:
                    summary.append(f"{attribute}={subcount}")
            yield ", ".join(summary)
            yield ")"

        yield "\n"

    def test_started(self, test):
        cls = test.__class__
        module = cls.__module__

        if self._last_test_module != module:
            self._last_test_module = module
            yield module
            yield "\n"

        if self._last_test_class != cls:
            self._last_test_class = cls
            yield self.indent
            yield cls.__name__
            yield "\n"

    def test_stopped(self, test):
        pass

    def test_errored(self, test, exc_info):
        self._show_later(
            status=self.ERROR,
            body="".join(format_exception(*exc_info)),
            subject=test,
        )
        return self.format_line(test, self._error)

    def test_failed(self, test, exc_info):
        self._show_later(
            status=self.FAIL,
            body="".join(format_exception(*exc_info)),
            subject=test,
        )
        return self.format_line(test, self._fail)

    def test_skipped(self, test, reason):
        self._show_later(status=self.SKIPPED, body=reason, subject=test)
        return self.format_line(test, self._skipped)

    def test_expectedly_failed(self, test, exc_info):
        self._show_later(status=self.EXPECTED_FAILURE, subject=test)
        return self.format_line(test, self._expected_failure)

    def test_unexpectedly_succeeded(self, test):
        self._show_later(status=self.UNEXPECTED_SUCCESS, subject=test)
        return self.format_line(test, self._unexpected_success)

    def test_succeeded(self, test):
        return self.format_line(test, self._ok)

    def format_line(self, test, result):
        before = f"{self.indent}{self.indent}{test._testMethodName} ..."
        return self._pad_center(left=before, right=result) + "\n"

    def _pad_center(self, left, right):
        space = self.line_width - len(left) - len(right)
        return left + " " * space + right

@attr.s
class Counter:
    """
    A counter is a recorder that does not hold references to tests it sees.
    """

    errors = attr.ib(default=0)
    failures = attr.ib(default=0)
    expected_failures = attr.ib(default=0)
    unexpected_successes = attr.ib(default=0)
    successes = attr.ib(default=0)

    shouldStop = False

    @property
    def count(self):
        return sum(attr.astuple(self))

    testsRun = count

    def startTest(self, test):
        pass

    def stopTest(self, test):
        pass

    def addError(self, test, exc_info):
        self.errors += 1

    def addFailure(self, test, exc_info):
        self.failures += 1

    def addExpectedFailure(self, *args, **kwargs):
        self.expected_failures += 1

    def addUnexpectedSuccess(self, test):
        self.unexpected_successes += 1

    def addSuccess(self, test):
        self.successes += 1

@attr.s
class Recorder:

    errors = attr.ib(default=v())
    failures = attr.ib(default=v())
    skips = attr.ib(default=v())
    successes = attr.ib(default=v())
    expected_failures = attr.ib(default=v())
    unexpected_successes = attr.ib(default=v())

    shouldStop = False

    @property
    def testsRun(self):
        return sum(len(tests) for tests in attr.astuple(self))

    def startTestRun(self):
        pass

    def stopTestRun(self):
        pass

    def startTest(self, test):
        pass

    def stopTest(self, test):
        pass

    def addError(self, test, exc_info):
        self.errors = self.errors.append((test, exc_info))

    def addFailure(self, test, exc_info):
        self.failures = self.failures.append((test, exc_info))

    def addExpectedFailure(self, test, exc_info):
        self.expected_failures = self.expected_failures.append(
            (test, exc_info),
        )

    def addSkip(self, test, reason):
        self.skips = self.skips.append(test)

    def addSuccess(self, test):
        self.successes = self.successes.append(test)

    def addUnexpectedSuccess(self, test):
        self.unexpected_successes = self.unexpected_successes.append(test)

    def wasSuccessful(self):
        return not (self.errors or self.failures or self.unexpected_successes)

@attr.s
class ComponentizedReporter:

    outputter = attr.ib(factory=Outputter)
    recorder = attr.ib(factory=Recorder, repr=False)
    stream = attr.ib(default=sys.stdout)
    _time = attr.ib(default=time.time, repr=False)

    shouldStop = False

    @property
    def testsRun(self):
        return self.recorder.testsRun

    def startTestRun(self):
        self._start_time = self._time()
        self.recorder.startTestRun()
        self.stream.writelines(self.outputter.run_started() or "")

    def stopTestRun(self):
        self.recorder.stopTestRun()
        runtime = self._time() - self._start_time
        self.stream.writelines(
            self.outputter.run_stopped(self.recorder, runtime) or "",
        )

    def startTest(self, test):
        self.recorder.startTest(test)
        self.stream.writelines(self.outputter.test_started(test) or "")

    def stopTest(self, test):
        self.recorder.stopTest(test)
        self.stream.writelines(self.outputter.test_stopped(test) or "")

    def addError(self, test, exc_info):
        self.recorder.addError(test, exc_info)
        self.stream.writelines(
            self.outputter.test_errored(test, exc_info) or "",
        )

    def addFailure(self, test, exc_info):
        self.recorder.addFailure(test, exc_info)
        self.stream.writelines(
            self.outputter.test_failed(test, exc_info) or "",
        )

    def addSkip(self, test, reason):
        self.recorder.addSkip(test, reason)
        self.stream.writelines(self.outputter.test_skipped(test, reason) or "")

    def addExpectedFailure(self, test, exc_info):
        self.recorder.addExpectedFailure(test, exc_info)
        self.stream.writelines(
            self.outputter.test_expectedly_failed(test, exc_info) or "",
        )

    def addUnexpectedSuccess(self, test):
        self.recorder.addUnexpectedSuccess(test)
        self.stream.writelines(
            self.outputter.test_unexpectedly_succeeded(test) or "",
        )

    def addSuccess(self, test):
        self.recorder.addSuccess(test)
        self.stream.writelines(self.outputter.test_succeeded(test) or "")

    def wasSuccessful(self):
        return self.recorder.wasSuccessful()

def _test_name(test):
    """
    Retrieve the name of the given test.

    Arguments:

        test (TestCase):

            a test case instance

    """
    return f"{fully_qualified_name(test.__class__)}.{test._testMethodName}"


text:
immutable LabelGeometry <: Gadfly.GeometryElement
    # One of :dynamic, :left, :right, :above, :below, :centered
    position::Symbol

    # If true, hide labels that can't be made to not-overlap during dynamic
    # lael layout.
    hide_overlaps::Bool

    tag::Symbol

    function LabelGeometry(;position=:dynamic, hide_overlaps::Bool=true, tag::Symbol=empty_tag)
        new(position, hide_overlaps, tag)
    end
end

element_aesthetics(::LabelGeometry) = [:x, :y, :label]

default_statistic(::LabelGeometry) = Gadfly.Stat.identity()

const label = LabelGeometry

# A deferred context function for labeling points in a plot. Optimizing label
# placement depends on knowing the absolute size of the containing context.
function deferred_label_context(geom::LabelGeometry,
                                aes::Gadfly.Aesthetics,
                                theme::Gadfly.Theme,
                                drawctx::ParentDrawContext)

    # Label layout is non-trivial problem. Quite a few papers and at least one
    # Phd thesis has been written on the topic. The approach here is pretty
    # simple. A label may be placed anywhere surrounding a point or hidden.
    # Simulated annealing is used to try to minimize a penalty, which is equal
    # to the number of overlapping or out fo bounds labels, plus terms
    # penalizing hidden labels.
    #
    # TODO:
    # Penalize to prefer certain label positions over others.

    parent_transform = drawctx.t
    units = drawctx.units
    parent_box = drawctx.box

    canvas_width, canvas_height = parent_box.width, parent_box.height

    # This should maybe go in theme? Or should we be using Aesthetics.size?
    padding = 2mm

    point_positions = Array(Tuple, 0)
    for (x, y) in zip(aes.x, aes.y)
        x = Compose.absolute_x_position(Compose.x_measure(x), parent_transform, units,
                                        parent_box)
        y = Compose.absolute_y_position(Compose.y_measure(y), parent_transform, units,
                                        parent_box)
        x -= parent_box.x0
        y -= parent_box.y0
        push!(point_positions, (x, y))
    end

    extents = text_extents(theme.point_label_font,
                           theme.point_label_font_size,
                           aes.label...)
    extents = [(width + padding, height + padding)
               for (width, height) in extents]

    positions = Gadfly.Maybe(AbsoluteBoundingBox)[]
    for (i, (text_width, text_height)) in enumerate(extents)
        x, y = point_positions[i]
        push!(positions, AbsoluteBoundingBox(
                x, y, text_width.abs, text_height.abs))
    end

    # TODO: use Aesthetics.size and/or theme.default_point_size
    for (x, y) in point_positions
        push!(positions, AbsoluteBoundingBox(x - 0.5, y - 0.5, 1.0, 1.0))
        push!(extents, (1mm, 1mm))
    end

    n = length(aes.label)

    # Return a box containing every point that the label could possibly overlap.
    function max_extents(i)
        AbsoluteBoundingBox(positions[i].x0 - extents[i][1].abs,
                            positions[i].y0 - extents[i][2].abs,
                            2*extents[i][1].abs,
                            2*extents[i][2].abs)
    end

    # True if two boxes overlap
    function overlaps(a, b)
        if a === nothing || b === nothing
            return false
        end

        a.x0 + a.width  >= b.x0 && a.x0 <= b.x0 + b.width &&
        a.y0 + a.height >= b.y0 && a.y0 <= b.y0 + b.height
    end

    # True if a is fully contained in box.
    function box_contains(a)
        if a === nothing
            return true
        end

        0 < a.x0 && a.x0 + a.width < parent_box.width &&
        0 < a.y0 - a.height && a.y0 < parent_box.height
    end

    # Checking for label overlaps is O(n^2). To mitigate these costs, we build a
    # sparse overlap matrix. This also costs O(n^2), but we only have to do it
    # once, rather than every iteration of annealing.
    possible_overlaps = [Array(Int, 0) for _ in 1:length(positions)]

    # TODO: this whole thing would be much more effecient if we forbid from
    # the start labels that overlap points. We should be able to precompute
    # that, since they're static.

    for j in 1:n
        for i in (j+1):n
            if overlaps(max_extents(i), max_extents(j))
                push!(possible_overlaps[i], j)
                push!(possible_overlaps[j], i)
            end
        end

        for i in (n+1):length(positions)
            # skip the point box corresponding to label
            if i == j + n
                continue
            end

            if overlaps(positions[i], max_extents(j))
                push!(possible_overlaps[i], j)
                push!(possible_overlaps[j], i)
            end
        end
    end

    # This variable holds the value of the objective function we wish to
    # minimize. A label overlap is a penalty of 1. Other penaties (out of bounds
    # labels, hidden labels) or calibrated to that.
    total_penalty = 0

    for i in 1:n
        if !box_contains(positions[i])
            total_penalty += theme.label_out_of_bounds_penalty
        end
    end

    for j in 1:n
        for i in possible_overlaps[j]
            if i > j && overlaps(positions[i], positions[j])
                total_penalty += 1
            end
        end
    end

    label_visibility = fill(true, length(positions))

    num_iterations = n * theme.label_placement_iterations
    for k in 1:num_iterations
        if total_penalty == 0
            break
        end
        j = rand(1:n)

        new_total_penalty = total_penalty

        # Propose flipping the visibility of the label.
        if label_visibility[j] && geom.hide_overlaps && rand() < theme.label_visibility_flip_pr
            pos = nothing
            new_total_penalty += theme.label_hidden_penalty

        # Propose a change to label placement.
        else
            if !label_visibility[j]
                new_total_penalty -= theme.label_hidden_penalty
            end

            r = rand()
            point_x, point_y = point_positions[j]
            xspan = extents[j][1].abs
            yspan = extents[j][2].abs

            if rand() < 0.5
                xpos = Gadfly.lerp(rand(),
                                   (point_x - 7xspan/8),
                                   (point_x - 6xspan/8))
            else
                xpos = Gadfly.lerp(rand(),
                                   (point_x - 2xspan/8),
                                   (point_x - 1xspan/8))
            end

            ypos = Gadfly.lerp(rand(),
                               (point_y - 3yspan/4),
                               (point_y - 1yspan/4))

            # choose a side
            if r < 0.25 # top
                pos = AbsoluteBoundingBox(xpos, point_y - extents[j][2].abs,
                                          extents[j][1].abs, extents[j][2].abs)
            elseif 0.25 <= r < 0.5 # right
                pos = AbsoluteBoundingBox(point_x, ypos,
                                          extents[j][1].abs, extents[j][2].abs)
            elseif 0.5 <= r < 0.75 # bottom
                pos = AbsoluteBoundingBox(xpos, point_y,
                                          extents[j][1].abs, extents[j][2].abs)
            else # left
                pos = AbsoluteBoundingBox(point_x - extents[j][1].abs, ypos,
                                          extents[j][1].abs, extents[j][2].abs)
            end
        end

        if !box_contains(positions[j]) && label_visibility[j]
            new_total_penalty -= theme.label_out_of_bounds_penalty
        end

        if !box_contains(pos)
            new_total_penalty += theme.label_out_of_bounds_penalty
        end

        for i in possible_overlaps[j]
            if overlaps(positions[i], positions[j]) &&
                    label_visibility[i] && label_visibility[j]
                new_total_penalty -= 1
            end

            if overlaps(positions[i], pos) && label_visibility[i]
                new_total_penalty += 1
            end
        end

        improvement = total_penalty - new_total_penalty

        T = 0.1 * (1.0 - (k / (1 + num_iterations)))
        if improvement >= 0 || rand() < exp(improvement / T)
            if pos === nothing
                label_visibility[j] = false
            else
                label_visibility[j] = true
                positions[j] = pos
            end
            total_penalty = new_total_penalty
        end

    end

    return compose!(
        context(),
        text([(positions[i].x0 + extents[i][1].abs/2)*mm for i in 1:n],
             [(positions[i].y0 + extents[i][2].abs/2)*mm for i in 1:n],
             aes.label,
             [hcenter], [vcenter]; tag=geom.tag),
        visible(label_visibility),
        font(theme.point_label_font),
        fontsize(theme.point_label_font_size),
        fill(theme.point_label_color),
        stroke(nothing),
        svgclass("geometry"))
end

const label_layouts = @compat Dict(
    :left     => (hright,  vcenter, -2mm,  0mm),
    :right    => (hleft,   vcenter,  2mm,  0mm),
    :above    => (hcenter, vbottom,  0mm, -2mm),
    :below    => (hcenter, vtop,     0mm,  2mm),
    :centered => (hcenter, vcenter,  0mm,  0mm)
)

function render(geom::LabelGeometry, theme::Gadfly.Theme, aes::Gadfly.Aesthetics)
    Gadfly.assert_aesthetics_defined("Geom.Label", aes, :label, :x, :y)

    if geom.position == :dynamic
        return ctxpromise(drawctx -> deferred_label_context(geom, aes, theme, drawctx))
    else
        if !in(geom.position, [:left, :right, :above, :below, :centered])
            error("""
                The position argument of Geom.label must be one of :dynamic,
                :left, :right, :above, :below, :centered
                """)
        end

        hpos, vpos, xoff, yoff = label_layouts[geom.position]

        return compose!(
            context(),
            text([Compose.x_measure(x) + xoff for x in aes.x],
                 [Compose.y_measure(y) + yoff for y in aes.y],
                 aes.label,
                 [hpos], [vpos]; tag=geom.tag),
            font(theme.point_label_font),
            fontsize(theme.point_label_font_size),
            fill(theme.point_label_color),
            stroke(nothing),
            svgclass("geometry"))
    end
end


text:
A simple game in unity 5 that challenges the player to collect all cubes.

This project follows the [lessons](http://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) in Unity's Roll-A-Ball tutorial. Each commit corresponds to the progress made in each video.

## Prerequisites:

- [Git](https://git-scm.com/downloads)
- [Unity 5](https://unity3d.com/get-unity)

## Quick start

Clone this repository:

```bash
git clone git@github.com:agconti/rollerball.git
```

Check out the first lesson:

```bash
git checkout 096a669
```

Open it in the Unity IDE.

Start the first [video](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) and follow along.

Then check out the next commit as you move on to the next video to progress through the tutorial.

When you're done, check out the finished game [here](https://drive.google.com/file/d/0B4s3lnt98zyGZ1dUYXpDN1FEckEzcktEa3EtUzY2Z19KcnpZ/view?usp=sharing).


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace _2019111701CsMenu
{
    public partial class frmArea : Form
    {
        public frmArea()
        {
            InitializeComponent();
        }

        private void btnCal_Click(object sender, EventArgs e)
        {
            float fRadius = 0;
            double fArea = 0;

          // float.TryParse(txtRadius .Text.ToString () ,out fRadius );
            //
            try
            {
                fRadius = float.Parse(txtRadius.Text.ToString());
                fArea = 3.14 * fRadius * fRadius;
                txtArea.Text = fArea.ToString();
            }
            catch
            {
                MessageBox.Show("wrong input");
                txtRadius.Text = "";
                txtRadius.Focus();
            }

        }
    }
}


text:
require 'spec_helper'
require 'wary/status'

describe Wary::Status::OK do
  it_behaves_like 'a status', :ok
end


text:
layout: post

#event information
title:  "Death By Design"
cover: "/images/1024px-Electronics_factory_in_Shenzhen.jpg"
attribution:
  name: "Electronics factory in Shenzhen"
  author: "Steve Jurvetson"
  license: "CC BY 2.0"
  name_url: "https://commons.wikimedia.org/wiki/File:Electronics_factory_in_Shenzhen.jpg"
  license_url: "https://creativecommons.org/licenses/by/2.0/deed.en"
date:   "2016-11-29 18:30"
endDate:   "2016-11-29 20:45"
creation: "2016-10-18"
start_time: "6:30 pm"
end_time: "8:45 pm"
location:
  name: "Natural History Museum"
  address:
    - "10th St and Constitution Ave"
  city: "Washington"
  state: DC
  zip: 20560
tags: [ 'Natural History Museum' ]
excerpt: >
  Natural History on the Big Screen introduces audiences to some of the latest
  environmental films that address the relationship humans have with the planet.
  The "Stories From a Transforming World" three part series presented with the
  Environmental Film Festival in the Nation's Capital and curated by Joshua
  Bell, Curator of Globalization at the National Museum of Natural History, will
  explore multiple perspectives on the Age of Man - from close to home, to a
  global scale. The film "Death By Design" will be screened November 29.

---

Natural History on the Big Screen introduces audiences to some of the latest
environmental films that address the relationship humans have with the planet.
The "Stories From a Transforming World" three part series presented with the
Environmental Film Festival in the Nation's Capital and curated by Joshua
Bell, Curator of Globalization at the National Museum of Natural History, will
explore multiple perspectives on the Age of Man - from close to home, to a
global scale.

Death by Design, a feature length documentary, explores this question and
uncovers a global story of damaged lives, environmental destruction and devices
that are designed to die.

Consumers love – and live on – their smartphones, tablets and laptops. A cascade
of new devices pours endlessly into the market, promising even better
communication, non-stop entertainment and instant information. The numbers are
staggering. By 2020, four billion people will have a personal computer. Five
billion will own a mobile phone.

But this revolution has a dark side, hidden from most consumers. In an
investigation that spans the globe, filmmaker Sue Williams investigates the
underbelly of the electronics industry and reveals how even the smallest devices
have deadly environmental and health costs. From the intensely secretive
factories in China, to a ravaged New York community and the high tech corridors
of Silicon Valley, the film tells a story of environmental degradation, of
health tragedies, and the fast approaching tipping point between consumerism and
sustainability.

The event is free and open to the public but [advance registration is
required](http://go.si.edu/site/Calendar/392493667). Seating
is limited.


text:
package org.wso2.appserver.configuration.server;

import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * A Java class which models a holder for server level classloading configurations.
 *
 * @since 6.0.0
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class ClassLoaderEnvironments {
    @XmlElement(name = "Environments")
    private Environments environments;

    public Environments getEnvironments() {
        return environments;
    }

    public void setEnvironments(Environments environments) {
        this.environments = environments;
    }

    /**
     * A nested class which models a group of class-loading environments for Application Server.
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Environments {
        @XmlElement(name = "Environment")
        private List<Environment> environments;

        public List<Environment> getEnvironments() {
            return environments;
        }

        public void setEnvironments(List<Environment> environments) {
            this.environments = environments;
        }
    }

    /**
     * A nested class which models a class-loading environment for Application Server.
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Environment {
        @XmlElement(name = "Name")
        private String name;
        @XmlElement(name = "Classpath")
        private String classpath;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getClasspath() {
            return classpath;
        }

        public void setClasspath(String classpath) {
            this.classpath = classpath;
        }
    }
}


text:
from decimal import Decimal
import os, logging, MySQLdb, sys, ConfigParser

#configurazione del modulo logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    filename=os.path.splitext(os.path.join(os.getcwd(),
                                                           os.path.basename(__file__)))[0]+'.log',
                    filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)-8s: %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

#questi sono presi dal file di configurazione in load_config
CFG = None

page_complete = """<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>HmtDB - Statistics</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="../theme/stylesheet.css">
    <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
    <link rel="icon" type="image/png" href="img/favicon-32x32.png" sizes="32x32">

        About HmtDB
        Database Functions
        Statistics
        Citing HmtDB
        What's New
        People
        Contacts

Statistics

World Map

Genomes in HmtDB

                Continent Name
                Individual Type
                Number of Genomes
                Complete Genomes
                Only Coding Region Genomes

"""

page_row ="""

                        %s
                        Normal
                        %d
                        %d
                        %d

                        Patient
                        %d
                        %d
                        %d

"""

page_header2 = """

Variant Sites in HmtDB

                    Continent Name
                    Number of Variant Sites

"""

page_row2 = """

                    %s
                    %d

"""

variants_table = ""

page_footer = """

"""

def get_connection():
    db_config = dict(CFG.items('connessione'))
    try:
        return MySQLdb.connect(compress=True, **db_config)
    except MySQLdb.DatabaseError:
        logging.critical("non si riesce ad effettuare una connessione al db")
        sys.exit(1)

def load_config(cfg_file):
    cfg = ConfigParser.SafeConfigParser()
    cfg.read(cfg_file)
    global CFG
    CFG = cfg
    #per testare
    get_connection()
    #i nomi da usare nei file per i continenti

def write_stats():
    #f = open(fname, 'w')
    #f.write(page_header)
    global genomes_table
    global variants_table
    cur = get_connection().cursor()
    tot_coding_pa = tot_complete_pa = tot_coding = tot_complete = 0
    for continente in ['Africa', 'America', 'Asia', 'Europe', 'Oceania', 'Undefined Continent']:
        cur.execute("SELECT TOTAL FROM STATS WHERE GENOME_TYPE = 'N' AND COMPLETE_GENOME = 'Y' AND CONTINENT_NAME = %s", continente)
        n_complete = cur.fetchone()
        if n_complete:
            n_complete = int(n_complete[0])
        else:
            n_complete = 0
        cur.execute("SELECT TOTAL FROM STATS WHERE GENOME_TYPE = 'N' AND COMPLETE_GENOME = 'N' AND CONTINENT_NAME = %s", continente)
        n_coding = cur.fetchone()
        if n_coding:
            n_coding = int(n_coding[0])
        else:
            n_coding = 0
        cur.execute("SELECT TOTAL FROM STATS WHERE GENOME_TYPE = 'P' AND COMPLETE_GENOME = 'Y' AND CONTINENT_NAME = %s", continente)
        p_complete = cur.fetchone()
        if p_complete:
            p_complete = int(p_complete[0])
        else:
            p_complete = 0
        cur.execute("SELECT TOTAL FROM STATS WHERE GENOME_TYPE = 'P' AND COMPLETE_GENOME = 'N' AND CONTINENT_NAME = %s", continente)
        p_coding = cur.fetchone()
        if p_coding:
            p_coding = int(p_coding[0])
        else:
            p_coding = 0
        tot_coding += n_coding
        tot_complete += n_complete
        tot_coding_pa += p_coding
        tot_complete_pa += p_complete

        if continente != 'Undefined Continent':
            worldDict[continente].append(n_coding + n_complete + p_coding + p_complete)

        genomes_table += page_row % (continente, n_coding+n_complete, n_complete, n_coding, p_coding+p_complete, p_complete, p_coding)

        #f.write( page_row %
        #         (
        #             continente,
        #             n_coding+n_complete, n_complete, n_coding,
        #             p_coding+p_complete, p_complete, p_coding
        #         )
        #         )

    genomes_table += page_row % ('All Continents', tot_coding+tot_complete, tot_complete, tot_coding, tot_coding_pa+tot_complete_pa, tot_complete_pa, tot_coding_pa)

    #f.write(page_row %
    #        ('All continents', tot_coding+tot_complete, tot_complete, tot_coding,
    #         tot_coding_pa+tot_complete_pa, tot_complete_pa, tot_coding_pa
    #         )
    #        )
    #f.write(page_header2)
    query = "SELECT COUNT(NUCLEOTIDE_POSITION) AS VARIANTSITES FROM NT_VARIABILITY WHERE INSERTION_POSITION = 0 AND %s > 0 GROUP BY GENOME_TYPE"
    for continente, var in [('Africa','VAR_AF'), ('America','VAR_AM'), ('Asia','VAR_AS'), ('Europe','VAR_EU'), ('Oceania','VAR_OC'), ('All continents','VAR_TOT')]:
        cur.execute(query % var)

        if continente != 'All continents':
            worldDict[continente].append(int(cur.fetchone()[0]))
            variants_table += page_row2 % (continente, worldDict[continente][2])
        else:
            variants_table += page_row2 % (continente, int(cur.fetchone()[0]))

            #f.write(page_row2 % (continente, cur.fetchone()[0]) )
            #f.write(page_footer)
            #f.close()

def createPage():
    global page_complete
    for i in worldDict:
        page_complete += "['%s', '%s', %d, %d]," % (worldDict[i][0], i, worldDict[i][1], worldDict[i][2])

    page_complete += page_header

    page_complete += genomes_table

    page_complete += page_header2

    page_complete += variants_table

    page_complete += page_footer

    f = open("stats.html", "wb")
    f.write(page_complete)
    f.close()

def run():
    logging.debug("lettura della configurazione")
    cfg_file = [
        #os.path.join(
        #os.path.dirname(os.path.abspath(__file__)),
        #os.path.splitext(os.path.basename(__file__))[0]+'.cfg'
        #),
        os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'common.cfg'
        )
    ]
    load_config(cfg_file)
    write_stats()
    createPage()

if __name__ == '__main__':
    run()


text:
package io.arabesque.utils;

import java.io.DataInput;
import java.io.IOException;
import java.util.Iterator;

public class ReadIntegerIterable implements Iterable<Integer> {
    private DataInput dataInput;
    private int numIntegersToRead;
    private int numIntegersRead;

    public ReadIntegerIterable(DataInput dataInput, int numIntegersToRead) {
        this.dataInput = dataInput;
        this.numIntegersToRead = numIntegersToRead;
        this.numIntegersRead = 0;
    }

    @Override
    public Iterator<Integer> iterator() {
        return new ReadIntegerIterator();
    }

    private class ReadIntegerIterator implements Iterator<Integer> {
        @Override
        public boolean hasNext() {
            return numIntegersRead < numIntegersToRead;
        }

        @Override
        public Integer next() {
            try {
                ++numIntegersRead;
                return dataInput.readInt();
            } catch (IOException e) {
                throw new NoMoreDataException();
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    public class NoMoreDataException extends RuntimeException {
    }
}


text:
class ProductItem < ActiveRecord::Base
  belongs_to :shop
  has_many :user_item_ables
  has_many :users, through: :user_item_ables
end


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spirit V3.0.6 (Boost V1.73.0)</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Spirit X3 3.0.9">
<link rel="up" href="../changelog.html" title="Changelog">
<link rel="prev" href="spirit_3_0_7.html" title="Spirit V3.0.7 (Boost V1.74.0)">
<link rel="next" href="spirit_3_0_5.html" title="Spirit V3.0.5 (Boost V1.72.0)">

Home
Libraries
People
FAQ
More

Spirit V3.0.6 (Boost
      V1.73.0)

            ADL used to find and match unused_type
            streaming operators for every type in boost::spirit::x3
            namespace GH#553 GH#552

            Ceased dependence on Boost.TTI

            Rule placeholders now a non-trivial type because its copy constructor
            checks for a static initialization fiasco GH#571

            Most parsers are now constexpr-constructible GH#570

Copyright © 2001-2018 Joel de Guzman,
      Hartmut Kaiser

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
var __decorate = this.__decorate || function (decorators, target, key, value) {
    var kind = typeof (arguments.length == 2 ? value = target : value);
    for (var i = decorators.length - 1; i >= 0; --i) {
        var decorator = decorators[i];
        switch (kind) {
            case "function": value = decorator(value) || value; break;
            case "number": decorator(target, key, value); break;
            case "undefined": decorator(target, key); break;
            case "object": value = decorator(target, key, value) || value; break;
        }
    }
    return value;
};
var collection_1 = require('angular2/src/facade/collection');
var lang_1 = require('angular2/src/facade/lang');
var modelModule = require('./model');
var FormBuilder = (function () {
    function FormBuilder() {
    }
    FormBuilder.prototype.group = function (controlsConfig, extra) {
        if (extra === void 0) { extra = null; }
        var controls = this._reduceControls(controlsConfig);
        var optionals = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "optionals") : null;
        var validator = lang_1.isPresent(extra) ? collection_1.StringMapWrapper.get(extra, "validator") : null;
        if (lang_1.isPresent(validator)) {
            return new modelModule.ControlGroup(controls, optionals, validator);
        }
        else {
            return new modelModule.ControlGroup(controls, optionals);
        }
    };
    FormBuilder.prototype.control = function (value, validator) {
        if (validator === void 0) { validator = null; }
        if (lang_1.isPresent(validator)) {
            return new modelModule.Control(value, validator);
        }
        else {
            return new modelModule.Control(value);
        }
    };
    FormBuilder.prototype.array = function (controlsConfig, validator) {
        var _this = this;
        if (validator === void 0) { validator = null; }
        var controls = collection_1.ListWrapper.map(controlsConfig, function (c) { return _this._createControl(c); });
        if (lang_1.isPresent(validator)) {
            return new modelModule.ControlArray(controls, validator);
        }
        else {
            return new modelModule.ControlArray(controls);
        }
    };
    FormBuilder.prototype._reduceControls = function (controlsConfig) {
        var _this = this;
        var controls = {};
        collection_1.StringMapWrapper.forEach(controlsConfig, function (controlConfig, controlName) {
            controls[controlName] = _this._createControl(controlConfig);
        });
        return controls;
    };
    FormBuilder.prototype._createControl = function (controlConfig) {
        if (controlConfig instanceof modelModule.Control || controlConfig instanceof modelModule.ControlGroup || controlConfig instanceof modelModule.ControlArray) {
            return controlConfig;
        }
        else if (collection_1.ListWrapper.isList(controlConfig)) {
            var value = collection_1.ListWrapper.get(controlConfig, 0);
            var validator = controlConfig.length > 1 ? controlConfig[1] : null;
            return this.control(value, validator);
        }
        else {
            return this.control(controlConfig);
        }
    };
    return FormBuilder;
})();
exports.FormBuilder = FormBuilder;
Object.defineProperty(FormBuilder.prototype.control, "parameters", { get: function () {
        return [[], [Function]];
    } });
Object.defineProperty(FormBuilder.prototype.array, "parameters", { get: function () {
        return [[collection_1.List], [Function]];
    } });


text:
#ifndef SIMTA_SIMTA_LMDB_H
#define SIMTA_SIMTA_LMDB_H

#include <lmdb.h>
#include <yasl.h>

#define SIMTA_DB_OK 0
#define SIMTA_DB_SYSERROR 1
#define SIMTA_DB_NOTFOUND 2

struct simta_dbh {
    MDB_env *h_env;
};

struct simta_dbc {
    MDB_cursor *c_cursor;
    int         c_init;
    int         c_keyed;
};

char *simta_db_strerror(int);

int simta_db_new(struct simta_dbh **, const char *);
int simta_db_open_rw(struct simta_dbh **, const char *);
int simta_db_open_r(struct simta_dbh **, const char *);

int simta_db_put(struct simta_dbh *, yastr, yastr);
int simta_db_get(struct simta_dbh *, yastr, yastr *);

int  simta_db_cursor_open(struct simta_dbh *, struct simta_dbc **);
int  simta_db_cursor_get(struct simta_dbc *, yastr *, yastr *);
void simta_db_cursor_close(struct simta_dbc *);

void simta_db_close(struct simta_dbh *);

#endif /* SIMTA_SIMTA_LMDB_H */
/* vim: set softtabstop=4 shiftwidth=4 expandtab :*/


text:
package zygo

import (
	"errors"
	"fmt"
	"sort"
	"strings"
)

type Scope struct {
	Map        map[int]Sexp
	IsGlobal   bool
	Name       string
	Parent     *Scope
	IsFunction bool // if true, read-only.
	env        *Glisp
}

func (env *Glisp) NewScope() *Scope {
	return &Scope{
		Map: make(map[int]Sexp),
		env: env,
	}
}

func (env *Glisp) NewNamedScope(name string) *Scope {
	return &Scope{
		Map:  make(map[int]Sexp),
		Name: name,
		env:  env,
	}
}

func (s *Scope) CloneScope() *Scope {
	n := s.env.NewScope()
	for k, v := range s.Map {
		n.Map[k] = v
	}
	return n
}

func (s Scope) IsStackElem() {}

func (stack *Stack) PushScope() {
	s := stack.env.NewScope()
	if stack.Size() > 0 {
		s.Parent = stack.GetTop().(*Scope)
	}
	stack.Push(s)
}

func (stack *Stack) PopScope() error {
	_, err := stack.Pop()
	return err
}

// dynamic scoping lookup. See env.LexicalLookupSymbol() for the lexically
// scoped equivalent.
func (stack *Stack) lookupSymbol(sym SexpSymbol, minFrame int) (Sexp, error, *Scope) {
	if !stack.IsEmpty() {
		for i := 0; i <= stack.tos-minFrame; i++ {
			elem, err := stack.Get(i)
			if err != nil {
				return SexpNull, err, nil
			}
			switch scope := elem.(type) {
			case (*Scope):
				expr, ok := scope.Map[sym.number]
				if ok {
					return expr, nil, scope
				}
			}
		}
	}

	if stack.env != nil && stack.env.debugSymbolNotFound {
		stack.env.ShowStackStackAndScopeStack()
	}
	return SexpNull, fmt.Errorf("symbol `%s` not found", sym.name), nil
}

func (stack *Stack) LookupSymbol(sym SexpSymbol) (Sexp, error, *Scope) {
	return stack.lookupSymbol(sym, 0)
}

// LookupSymbolNonGlobal  - closures use this to only find symbols below the global scope, to avoid copying globals it'll always be-able to ref
func (stack *Stack) LookupSymbolNonGlobal(sym SexpSymbol) (Sexp, error, *Scope) {
	return stack.lookupSymbol(sym, 1)
}

var SymNotFound = errors.New("symbol not found")

// lookup symbols, but don't go beyond a function boundary
func (stack *Stack) LookupSymbolUntilFunction(sym SexpSymbol) (Sexp, error, *Scope) {

	if !stack.IsEmpty() {
	doneSearching:
		for i := 0; i <= stack.tos; i++ {
			elem, err := stack.Get(i)
			if err != nil {
				return SexpNull, err, nil
			}
			switch scope := elem.(type) {
			case (*Scope):
				VPrintf("   ...looking up in scope '%s'\n", scope.Name)
				expr, ok := scope.Map[sym.number]
				if ok {
					return expr, nil, scope
				}
				if scope.IsFunction {
					VPrintf("   ...scope '%s' was a function, halting up search\n",
						scope.Name)
					break doneSearching
				}
			}
		}
	}

	if stack != nil && stack.env != nil && stack.env.debugSymbolNotFound {
		fmt.Printf("debugSymbolNotFound is true, here are scopes:\n")
		stack.env.ShowStackStackAndScopeStack()
	}
	return SexpNull, SymNotFound, nil
}

func (stack *Stack) BindSymbol(sym SexpSymbol, expr Sexp) error {
	if stack.IsEmpty() {
		panic("empty stack!!")
		//return errors.New("no scope available")
	}
	cur, already := stack.elements[stack.tos].(*Scope).Map[sym.number]
	if already {
		Q("BindSymbol already sees symbol %v, currently bound to '%v'", sym.name, cur.SexpString())

		lhsTy := cur.Type()
		rhsTy := expr.Type()
		if lhsTy == nil {
			// for backcompat with closure.zy, just do the binding for now if the LHS isn't typed.
			//return fmt.Errorf("left-hand-side had nil type")
			// TODO: fix this? or require removal of previous symbol binding to avoid type errors?
			stack.elements[stack.tos].(*Scope).Map[sym.number] = expr
			return nil
		}
		if rhsTy == nil {
			return fmt.Errorf("right-hand-side had nil type")
		}

		// both sides have type
		Q("BindSymbol: both sides have type. rhs=%v, lhs=%v", rhsTy.SexpString(), lhsTy.SexpString())

		if lhsTy == rhsTy {
			Q("BindSymbol: YES types match exactly. Good.")
			stack.elements[stack.tos].(*Scope).Map[sym.number] = expr
			return nil
		}

		if rhsTy.UserStructDefn != nil && rhsTy.UserStructDefn != lhsTy.UserStructDefn {
			return fmt.Errorf("cannot assign %v to %v", rhsTy.ShortName(), lhsTy.ShortName())
		}

		if lhsTy.UserStructDefn != nil && lhsTy.UserStructDefn != rhsTy.UserStructDefn {
			return fmt.Errorf("cannot assign %v to %v", rhsTy.ShortName(), lhsTy.ShortName())
		}

		// TODO: problem with this implementation is that it may narrow the possible
		// types assignments to this variable. To fix we'll need to keep around the
		// type of the symbol in the symbol table, separately from the value currently
		// bound to it.
		if lhsTy.TypeCache != nil && rhsTy.TypeCache != nil {
			if rhsTy.TypeCache.AssignableTo(lhsTy.TypeCache) {
				Q("BindSymbol: YES: rhsTy.TypeCache (%v) is AssigntableTo(lhsTy.TypeCache) (%v). Good.", rhsTy.TypeCache, lhsTy.TypeCache)
				stack.elements[stack.tos].(*Scope).Map[sym.number] = expr
				return nil
			}
		}
		Q("BindSymbol: at end, defaulting to deny")
		return fmt.Errorf("cannot assign %v to %v", rhsTy.ShortName(), lhsTy.ShortName())
	} else {
		Q("BindSymbol: new symbol %v", sym.name)
	}
	stack.elements[stack.tos].(*Scope).Map[sym.number] = expr
	return nil
}

func (stack *Stack) DeleteSymbolFromTopOfStackScope(sym SexpSymbol) error {
	if stack.IsEmpty() {
		panic("empty stack!!")
		//return errors.New("no scope available")
	}
	_, present := stack.elements[stack.tos].(*Scope).Map[sym.number]
	if !present {
		return fmt.Errorf("symbol `%s` not found", sym.name)
	}
	delete(stack.elements[stack.tos].(*Scope).Map, sym.number)
	return nil
}

// used to implement (set v 10)
func (scope *Scope) UpdateSymbolInScope(sym SexpSymbol, expr Sexp) error {

	_, found := scope.Map[sym.number]
	if !found {
		return fmt.Errorf("symbol `%s` not found", sym.name)
	}
	scope.Map[sym.number] = expr
	return nil
}

func (scope *Scope) DeleteSymbolInScope(sym SexpSymbol) error {

	_, found := scope.Map[sym.number]
	if !found {
		return fmt.Errorf("symbol `%s` not found", sym.name)
	}
	delete(scope.Map, sym.number)
	return nil
}

type SymtabE struct {
	Key string
	Val string
}

type SymtabSorter []*SymtabE

func (a SymtabSorter) Len() int           { return len(a) }
func (a SymtabSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a SymtabSorter) Less(i, j int) bool { return a[i].Key < a[j].Key }

func (scop Scope) Show(env *Glisp, indent int, label string) (s string, err error) {
	rep := strings.Repeat(" ", indent)
	rep4 := strings.Repeat(" ", indent+4)
	s += fmt.Sprintf("%s %s  %s\n", rep, label, scop.Name)
	if scop.IsGlobal && !env.showGlobalScope {
		s += fmt.Sprintf("%s (global scope - omitting content for brevity)\n", rep4)
		return
	}
	if len(scop.Map) == 0 {
		s += fmt.Sprintf("%s empty-scope: no symbols\n", rep4)
		return
	}
	sortme := []*SymtabE{}
	for symbolNumber, val := range scop.Map {
		symbolName := env.revsymtable[symbolNumber]
		sortme = append(sortme, &SymtabE{Key: symbolName, Val: val.SexpString()})
	}
	sort.Sort(SymtabSorter(sortme))
	for i := range sortme {
		s += fmt.Sprintf("%s %s -> %s\n", rep4,
			sortme[i].Key, sortme[i].Val)
	}
	return
}

type Showable interface {
	Show(env *Glisp, indent int, label string) (string, error)
}


text:
from google.cloud import billing_v1
from google.iam.v1 import iam_policy_pb2  # type: ignore

def sample_set_iam_policy():
    # Create a client
    client = billing_v1.CloudBillingClient()

    # Initialize request argument(s)
    request = iam_policy_pb2.SetIamPolicyRequest(
        resource="resource_value",
    )

    # Make the request
    response = client.set_iam_policy(request=request)

    # Handle the response
    print(response)

# [END cloudbilling_v1_generated_CloudBilling_SetIamPolicy_sync]


text:
package cn.libery.library_multiphotopick.photopick;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;

import cn.libery.library_multiphotopick.R;

public class AllPhotoAdapter extends GridPhotoAdapter {

    public AllPhotoAdapter(Context context, Cursor c, boolean autoRequery, PhotoPickActivity activity) {
        super(context, c, autoRequery, activity);
    }

    @Override
    public int getCount() {
        return super.getCount() + 1;
    }

    @Override
    public Object getItem(int position) {
        if (position > 0) {
            return super.getItem(position - 1);
        } else {
            return super.getItem(position);
        }
    }

    @Override
    public long getItemId(int position) {
        if (position > 0) {
            return super.getItemId(position - 1);
        } else {
            return -1;
        }
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (position > 0) {
            return super.getDropDownView(position - 1, convertView, parent);
        } else {
            return getView(position, convertView, parent);
        }
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (position > 0) {
            return super.getView(position - 1, convertView, parent);
        } else {
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.photopick_gridlist_item_camera2, parent, false);
                convertView.getLayoutParams().height = PhotoPickActivity.width / 3;
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mActivity.camera();
                    }
                });
            }

            return convertView;
        }
    }
}


text:
Accessible Blockly
==================

Google's Blockly is a web-based, visual programming editor that is accessible
to blind users.

The code in this directory renders a version of the Blockly toolbox and
workspace that is fully keyboard-navigable, and compatible with most screen
readers. It is optimized for NVDA on Firefox.

In the future, Accessible Blockly may be modified to suit accessibility needs
other than visual impairments. Note that deaf users are expected to continue
using Blockly over Accessible Blockly.

Using Accessible Blockly in Your Web App
----------------------------------------
The demo at blockly/demos/accessible covers the absolute minimum required to
import Accessible Blockly into your web app. You will need to import the files
in the same order as in the demo: utils.service.js will need to be the first
Angular file imported.

When the DOMContentLoaded event fires, call ng.platform.browser.bootstrap() on
the main component to be loaded. This will usually be blocklyApp.AppComponent,
but if you have another component that wraps it, use that one instead.

Customizing the Sidebar and Audio
---------------------------------
The Accessible Blockly workspace comes with a customizable sidebar.

To customize the sidebar, you will need to declare an ACCESSIBLE_GLOBALS object
in the global scope that looks like this:

    var ACCESSIBLE_GLOBALS = {
      mediaPathPrefix: null,
      customSidebarButtons: []
    };

The value of mediaPathPrefix should be the location of the accessible/media
folder.

The value of 'customSidebarButtons' should be a list of objects, each
representing buttons on the sidebar. Each of these objects should have the
following keys:
  - 'text' (the text to display on the button)
  - 'action' (the function that gets run when the button is clicked)
  - 'id' (optional; the id of the button)

Limitations
-----------
- We do not support having multiple Accessible Blockly apps in a single webpage.
- Accessible Blockly does not support the use of shadow blocks.


text:
package org.dcm4chex.archive.dcm.movescu;

import java.io.Serializable;

/**
 * @author gunter.zeilinger@tiani.com
 * @version $Revision: 2831 $ $Date: 2006-10-03 19:02:46 +0800 (周二, 03 10月 2006) $
 * @since 26.08.2004
 *
 */
public final class MoveOrder implements Serializable {

	private static final long serialVersionUID = 3617856386927702068L;

    private String retrieveAET;

    private String moveDestination;

    private String patientId;

    private String[] studyIuids;

    private String[] seriesIuids;

    private String[] sopIuids;

    private int priority;

    private int failureCount;

    public MoveOrder(String retrieveAET, String moveDestination, int priority,
            String patientId, String[] studyIuids, String[] seriesIuids,
            String[] sopIuids) {
        this.priority = priority;
        this.retrieveAET = retrieveAET;
        this.moveDestination = moveDestination;
        this.patientId = patientId;
        this.studyIuids = studyIuids;
        this.seriesIuids = seriesIuids;
        this.sopIuids = sopIuids;
    }

    public MoveOrder(String retrieveAET, String moveDestination, int priority,
			String patientId, String studyIuid, String seriesIuid,
			String[] sopIuids) {
		this(retrieveAET, moveDestination, priority, patientId,
				studyIuid != null ? new String[] { studyIuid } : null,
				seriesIuid != null ? new String[] { seriesIuid } : null,
				sopIuids);
	}

    public MoveOrder(String retrieveAET, String moveDestination, int priority,
			String patientId, String studyIuid, String seriesIuid) {
		this(retrieveAET, moveDestination, priority, patientId,
				studyIuid, seriesIuid, null);
	}

    public MoveOrder(String retrieveAET, String moveDestination, int priority,
			String patientId, String studyIuid, String[] seriesIuids) {
		this(retrieveAET, moveDestination, priority, patientId,
				studyIuid != null ? new String[] { studyIuid } : null,
				seriesIuids, null);
	}

    public MoveOrder(String retrieveAET, String moveDestination, int priority,
			String patientId, String studyIuid) {
		this(retrieveAET, moveDestination, priority, patientId,
				studyIuid, null, null);
	}

    public MoveOrder(String retrieveAET, String moveDestination, int priority,
			String patientId, String[] studyIuids) {
		this(retrieveAET, moveDestination, priority, patientId, studyIuids, null, null);
	}

    public String toString() {
        StringBuffer sb = new StringBuffer("MoveOrder[");
        if (sopIuids != null) {
            sb.append(sopIuids.length).append(" Instances, dest=");
        } else if (seriesIuids != null) {
            sb.append(seriesIuids.length).append(" Series, dest=");
        } else if (studyIuids != null) {
            sb.append(studyIuids.length).append(" Studies, dest=");
        } else {
            sb.append("1 Patient, dest=");
        }
        sb.append(moveDestination);
        sb.append(", qrscp=").append(retrieveAET);
        sb.append(", priority=").append(priority);
        sb.append(", failureCount=").append(failureCount);
        sb.append("]");
        return sb.toString();
    }

    public final String getQueryRetrieveLevel() {
        return sopIuids != null ? "IMAGE" : seriesIuids != null ? "SERIES"
                : studyIuids != null ? "STUDY" : "PATIENT";
    }

    public final int getPriority() {
        return priority;
    }

    public final void setPriority(int priority) {
        this.priority = priority;
    }

    public final int getFailureCount() {
        return failureCount;
    }

    public final void setFailureCount(int failureCount) {
        this.failureCount = failureCount;
    }

    public final String getMoveDestination() {
        return moveDestination;
    }

    public final void setMoveDestination(String moveDestination) {
        this.moveDestination = moveDestination;
    }

    public final String getPatientId() {
        return patientId;
    }

    public final void setPatientId(String patientId) {
        this.patientId = patientId;
    }

    public final String getRetrieveAET() {
        return retrieveAET;
    }

    public final void setRetrieveAET(String retrieveAET) {
        this.retrieveAET = retrieveAET;
    }

    public final String[] getSeriesIuids() {
        return seriesIuids;
    }

    public final void setSeriesIuids(String[] seriesIuids) {
        this.seriesIuids = seriesIuids;
    }

    public final String[] getSopIuids() {
        return sopIuids;
    }

    public final void setSopIuids(String[] sopIuids) {
        this.sopIuids = sopIuids;
    }

    public final String[] getStudyIuids() {
        return studyIuids;
    }

    public final void setStudyIuids(String[] studyIuids) {
        this.studyIuids = studyIuids;
    }

}