text:
using System.Collections.Generic;
using OpenSage.Content;
using OpenSage.Data.Ini;

namespace OpenSage.Gui.ControlBar
{
    public sealed class CommandSet : BaseAsset
    {
        internal static CommandSet Parse(IniParser parser)
        {
            return parser.ParseNamedBlock(
                (x, name) => x.SetNameAndInstanceId("CommandSet", name),
                FieldParseTable,
                new IniArbitraryFieldParserProvider<CommandSet>(
                    (x, name) => x.Buttons[int.Parse(name)] = parser.ParseCommandButtonReference()));
        }

        private static readonly IniParseTable<CommandSet> FieldParseTable = new IniParseTable<CommandSet>
        {
            { "InitialVisible", (parser, x) => x.InitialVisible = parser.ParseInteger() },
        };

        // These are laid out like this:
        // -------------------------------
        // | 01 | 03 | 05 | 07 | 09 | 11 |
        // -------------------------------
        // | 02 | 04 | 06 | 08 | 10 | 12 |
        // -------------------------------
        public Dictionary<int, LazyAssetReference<CommandButton>> Buttons { get; } = new Dictionary<int, LazyAssetReference<CommandButton>>();

        [AddedIn(SageGame.Bfme2)]
        public int InitialVisible { get; private set; }
    }
}


text:
"""
A script to pull licenses/notices/source code for Java dependencies.
It generates a CSV file with [dependency_name, url_to_license, license_type, source_included]
"""

import argparse
import csv
import json
import logging
import os
import shutil
import threading
import traceback
import yaml

from bs4 import BeautifulSoup
from datetime import datetime
from multiprocessing.pool import ThreadPool
from queue import Queue
from tenacity import retry
from tenacity import stop_after_attempt
from tenacity import wait_exponential
from urllib.request import urlopen, URLError, HTTPError

SOURCE_CODE_REQUIRED_LICENSES = ['lgpl', 'glp', 'cddl', 'mpl']
RETRY_NUM = 3
THREADS = 16

@retry(reraise=True,
       wait=wait_exponential(multiplier=2),
       stop=stop_after_attempt(RETRY_NUM))
def pull_from_url(file_name, url, dep, no_list):
    if url == 'skip':
        return
    try:
        url_read = urlopen(url)
        with open(file_name, 'wb') as temp_write:
            shutil.copyfileobj(url_read, temp_write)
        logging.debug(
            'Successfully pulled {file_name} from {url} for {dep}'.format(
                url=url, file_name=file_name, dep=dep))
    except URLError as e:
        traceback.print_exc()
        if pull_from_url.retry.statistics["attempt_number"] < RETRY_NUM:
            logging.error('Invalid url for {dep}: {url}. Retrying...'.format(
                url=url, dep=dep))
            raise
        else:
            logging.error(
                'Invalid url for {dep}: {url} after {n} retries.'.format(
                    url=url, dep=dep, n=RETRY_NUM))
            with thread_lock:
                no_list.append(dep)
            return
    except HTTPError as e:
        traceback.print_exc()
        if pull_from_url.retry.statistics["attempt_number"] < RETRY_NUM:
            logging.info(
                'Received {code} from {url} for {dep}. Retrying...'.format(
                    code=e.code, url=url, dep=dep))
            raise
        else:
            logging.error(
                'Received {code} from {url} for {dep} after {n} retries.'.
                format(code=e.code, url=url, dep=dep, n=RETRY_NUM))
            with thread_lock:
                no_list.append(dep)
            return
    except Exception as e:
        traceback.print_exc()
        if pull_from_url.retry.statistics["attempt_number"] < RETRY_NUM:
            logging.error(
                'Error occurred when pull {file_name} from {url} for {dep}. Retrying...'
                .format(url=url, file_name=file_name, dep=dep))
            raise
        else:
            logging.error(
                'Error occurred when pull {file_name} from {url} for {dep} after {n} retries.'
                .format(url=url, file_name=file_name, dep=dep, n=RETRY_NUM))
            with thread_lock:
                no_list.append(dep)
            return

def pull_source_code(base_url, dir_name, dep):
    # base_url example: https://repo1.maven.org/maven2/org/mortbay/jetty/jsp-2.1/6.1.14/
    soup = BeautifulSoup(urlopen(base_url).read(), "html.parser")
    for href in (a["href"] for a in soup.select("a[href]")):
        if href.endswith(
                '.jar') and not 'javadoc' in href:  # download jar file only
            file_name = dir_name + '/' + href
            url = base_url + '/' + href
            pull_from_url(file_name, url, dep, incorrect_source_url)

@retry(reraise=True, stop=stop_after_attempt(3))
def write_to_csv(csv_list):
    csv_columns = [
        'dependency_name', 'url_to_license', 'license_type', 'source_included'
    ]
    csv_file = "{license_dir}/beam_java_dependency_list.csv".format(
        license_dir=license_dir)
    try:
        with open(csv_file, 'w') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            writer.writeheader()
            for data in csv_list:
                writer.writerow(data)
    except:
        traceback.print_exc()
        raise

def execute(dep):
    '''
    An example of dep.
    {
        "moduleName": "antlr:antlr",
        "moduleUrl": "http://www.antlr.org/",
        "moduleVersion": "2.7.7",
        "moduleLicense": "BSD License",
        "moduleLicenseUrl": "http://www.antlr.org/license.html"
    }
    '''

    name = dep['moduleName'].split(':')[1].lower()
    version = dep['moduleVersion']
    name_version = name + '-' + version
    dir_name = '{license_dir}/{name_version}.jar'.format(
        license_dir=license_dir, name_version=name_version)

    # if auto pulled, directory is existing at {license_dir}
    if not os.path.isdir(dir_name):
        # skip self dependencies
        if dep['moduleName'].startswith('beam'):
            logging.debug('Skippig', name_version)
        os.mkdir(dir_name)
        # pull license
        try:
            license_url = dep_config[name][version]['license']
        except:
            try:
                license_url = dep['moduleLicenseUrl']
            except:
                # url cannot be found, add to no_licenses and skip to pull.
                with thread_lock:
                    no_licenses.append(name_version)
                license_url = 'skip'
        pull_from_url(dir_name + '/LICENSE', license_url, name_version,
                      no_licenses)
        # pull notice
        try:
            notice_url = dep_config[name][version]['notice']
            pull_from_url(dir_name + '/NOTICE', notice_url, name_version)
        except:
            pass
    else:
        try:
            license_url = dep['moduleLicenseUrl']
        except:
            license_url = ''
        logging.debug(
            'License/notice for {name_version} were pulled automatically.'.
            format(name_version=name_version))

    # get license_type to decide if pull source code.
    try:
        license_type = dep['moduleLicense']
    except:
        try:
            license_type = dep_config[name][version]['type']
        except:
            license_type = 'no_license_type'
            with thread_lock:
                no_license_type.append(name_version)

    # pull source code if license_type is one of SOURCE_CODE_REQUIRED_LICENSES.
    if any(x in license_type.lower() for x in SOURCE_CODE_REQUIRED_LICENSES):
        try:
            base_url = dep_config[name][version]['source']
        except:
            module = dep['moduleName'].split(':')[0].replace('.', '/')
            base_url = maven_url_temp.format(module=module + '/' + name,
                                             version=version)
        pull_source_code(base_url, dir_name, name_version)
        source_included = True
    else:
        source_included = False

    csv_dict = {
        'dependency_name': name_version,
        'url_to_license': license_url,
        'license_type': license_type,
        'source_included': source_included
    }
    with thread_lock:
        csv_list.append(csv_dict)

if __name__ == "__main__":
    start = datetime.now()
    parser = argparse.ArgumentParser()
    parser.add_argument('--license_dir', required=True)
    parser.add_argument('--dep_url_yaml', required=True)

    args = parser.parse_args()
    license_dir = args.license_dir
    dep_url_yaml = args.dep_url_yaml

    logging.getLogger().setLevel(logging.INFO)

    # index.json is generated by Gradle plugin.
    with open('{license_dir}/index.json'.format(license_dir=license_dir)) as f:
        dependencies = json.load(f)

    with open(dep_url_yaml) as file:
        dep_config = yaml.full_load(file)

    maven_url_temp = 'https://repo1.maven.org/maven2/{module}/{version}'

    csv_list = []
    no_licenses = []
    no_license_type = []
    incorrect_source_url = []

    logging.info(
        'Pulling license for {num_deps} dependencies using {num_threads} threads.'
        .format(num_deps=len(dependencies['dependencies']),
                num_threads=THREADS))
    thread_lock = threading.Lock()
    pool = ThreadPool(THREADS)
    pool.map(execute, dependencies['dependencies'])

    write_to_csv(csv_list)

    error_msg = []
    run_status = 'succeed'
    if no_licenses:
        logging.error(no_licenses)
        how_to = '**************************************** ' \
                 'Licenses were not able to be pulled ' \
                 'automatically for some dependencies. Please search source ' \
                 'code of the dependencies on the internet and add "license" ' \
                 'and "notice" (if available) field to {yaml_file} for each ' \
                 'missing license. Dependency List: [{dep_list}]'.format(
            dep_list=','.join(sorted(no_licenses)), yaml_file=dep_url_yaml)
        error_msg.append(how_to)
        run_status = 'failed'

    if no_license_type:
        how_to = '**************************************** ' \
                 'License type of some dependencies were not ' \
                 'identified. The license type is used to decide whether the ' \
                 'source code of the dependency should be pulled or not. ' \
                 'Please add "type" field to {yaml_file} for each dependency. ' \
                 'Dependency List: [{dep_list}]'.format(
            dep_list=','.join(sorted(no_license_type)), yaml_file=dep_url_yaml)
        error_msg.append(how_to)
        run_status = 'failed'

    if incorrect_source_url:
        how_to = '**************************************** ' \
                 'Urls to maven repo for some dependencies ' \
                 'were not able to be generated automatically. Please add ' \
                 '"source" field to {yaml_file} for each dependency. ' \
                 'Dependency List: [{dep_list}]'.format(
            dep_list=','.join(sorted(incorrect_source_url)),
            yaml_file=dep_url_yaml)
        error_msg.append(how_to)
        run_status = 'failed'

    end = datetime.now()
    logging.info(
        'pull_licenses_java.py {status}. It took {sec} seconds with {threads} threads.'
        .format(status=run_status,
                sec=(end - start).total_seconds(),
                threads=THREADS))

    if error_msg:
        raise RuntimeError('{n} error(s) occurred.'.format(n=len(error_msg)),
                           error_msg)

redpajama_set_name: RedPajamaGithub


text:
A dockerized setup of MapaNica.net community websites and tools. It uses traefik
for a reverse proxy, it includes automated certificate generation with
Let's Encrypt.

### Installation

Install Docker and Docker Compose on your system.

### Run the setup

Run the following command inside the `reverseproxy` and the `sites` directory:

```bash
docker-compose up -d
```


text:
package filodb.coordinator

import akka.actor.ActorSystem
import akka.cluster.Cluster
import com.typesafe.config.{Config, ConfigFactory}
import scala.concurrent.ExecutionContext

import filodb.core.FutureUtils
import filodb.core.reprojector._
import filodb.core.store.{ColumnStore, MetaStore}

object GlobalConfig {
  // Loads the overall configuration in a specific order:
  //  - System properties
  //  - Config file in location specified by filodb.config.file
  //  - filodb-defaults.conf (resource / in jar)
  //  - cluster-reference.conf
  //  - all other reference.conf's
  val systemConfig: Config = {
    val customConfig = sys.props.get("filodb.config.file").orElse(sys.props.get("config.file"))
                                .map { path => ConfigFactory.parseFile(new java.io.File(path)) }
                                .getOrElse(ConfigFactory.empty)
    // Don't ask me why, but ConfigFactory.parseResources() does NOT work in Spark 1.4.1 executors
    // and only the below works.
    val defaultsFromUrl = ConfigFactory.parseURL(getClass.getResource("/filodb-defaults.conf"))
    val clusterFromUrl = ConfigFactory.parseURL(getClass.getResource("/cluster-reference.conf"))
    ConfigFactory.defaultOverrides.withFallback(customConfig)
                 .withFallback(defaultsFromUrl)
                 .withFallback(clusterFromUrl)
                 .withFallback(ConfigFactory.defaultReference)
                 .resolve()
  }
}

/**
 * A trait to make setup of the [[NodeCoordinatorActor]] stack a bit easier.
 * Mixed in for tests as well as the main FiloDB app and anywhere else the stack needs to be spun up.
 */
trait CoordinatorSetup {
  def system: ActorSystem

  // The global Filo configuration object.  Should be systemConfig.getConfig("filodb")
  def config: Config

  // NOTE: should only be called once.  It's up to the classes inheriting this to protect themselves.
  // This is automatically done by FiloSetup, for example.
  def kamonInit(): Unit = {
    kamon.Kamon.start()
    val traceLogger = system.actorOf(KamonTraceLogger.props(config))
    kamon.Kamon.tracer.subscribe(traceLogger)
    KamonLogger.start(system, config.getConfig("metrics-logger"))
  }

  lazy val systemConfig: Config = GlobalConfig.systemConfig

  lazy val threadPool = FutureUtils.getBoundedTPE(config.getInt("core-futures-queue-length"),
                                                  "filodb.core",
                                                  config.getInt("core-futures-pool-size"),
                                                  config.getInt("core-futures-max-pool-size"))

  implicit lazy val ec: ExecutionContext = ExecutionContext.fromExecutorService(threadPool)

  // A separate ExecutionContext can optionally be used for reads, to control read task queue length
  // separately perhaps.  I have found this is not really necessary.  This was originally created to
  // help decongest heavy write workloads, but a better design has been the throttling of reprojection
  // by limiting number of segments flushed at once (see the use of foldLeftSequentially in Reprojector).
  lazy val readEc = ec

  // These should be implemented as lazy val's, though tests might want to reset them
  val columnStore: ColumnStore
  val metaStore: MetaStore
  lazy val reprojector = new DefaultReprojector(config, columnStore)

  // TODO: consider having a root actor supervising everything
  lazy val coordinatorActor =
    system.actorOf(NodeCoordinatorActor.props(metaStore, reprojector, columnStore, config),
                   "coordinator")

  lazy val cluster = Cluster(system)

  def shutdown(): Unit = {
    system.shutdown()
    columnStore.shutdown()
    metaStore.shutdown()
    // Important: shut down executioncontext as well
    threadPool.shutdown()
    kamon.Kamon.shutdown()
  }
}

/**
 * This is an optional method for Spark and other FiloDB apps to reuse the same config loading
 * mechanism provided by FiloDB, instead of using the default Typesafe config loading.  To use this
 * pass -Dkamon.config-provider=filodb.coordinator.KamonConfigProvider
 */
class KamonConfigProvider extends kamon.ConfigProvider {
  def config: Config = GlobalConfig.systemConfig
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Tomek Polański</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#FFF176">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="manifest" href="manifest.json">

  <app-root>

    Hi...
  </app-root>


text:
Instant ICSP/FTDI headers that fit over your Atmega*8 on the breadboard.

I got tired of always using jumpers to break out the ICSP pins for programming and the TX/RX pins for debugging. It took up precious space on my breadboard and made the whole thing messier.

So I made a little breakout board that conveniently fits right over my Atmega*8 (168, 328) chips. When I'm done programming, I can remove it and all that's left is the main circuit with none of the extra crap.

The initial prototype just broke out the ICSP header block, the new version has headers for an FTDI cable, a power indicator LED and a reset button.

[More info](https://hackaday.io/project/8093-atmega8-breadboard-backpack)

![Backpack and chip](http://i.imgur.com/fN1hqkb.jpg)
![Backpack on breadboard](http://i.imgur.com/KIbh1eD.jpg)


text:
<?php

namespace HitzMedia\Currency\Contracts;

interface StoreContract
{
    /**
     * Fetch currencies.
     *
     * @return mixed
     */
    public function fetchCurrencies();

    /**
     * Get currency by code.
     *
     * @param  string $code
     *
     * @return mixed
     */
    public function getCurrency($code);

    /**
     * Add new currency.
     *
     * @param  array $data
     *
     * @throws \HitzMedia\Currency\Exceptions\InvalidParameterException
     * @return \HitzMedia\Currency\Models\Currency
     */
    public function addCurrency(array $data);

    /**
     * Update currency by code.
     *
     * @param  string $code
     * @param  array  $data
     *
     * @throws \HitzMedia\Currency\Exceptions\InvalidParameterException
     * @return \HitzMedia\Currency\Models\Currency
     */
    public function updateCurrency($code, array $data);

    /**
     * Remove currency from store.
     *
     * @param  string $code
     *
     * @return void
     */
    public function removeCurrency($code);
}


text:
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook]
  has_many :user_movies
  has_many :movies, :through => :user_movies

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email
      user.password = Devise.friendly_token[0,20]
    end
  end

  def add_movie(movie)
    if !self.movies.include?(movie)
      self.movies << movie
    end
  end

  def remove_movie(movie)
    self.movies.delete(movie)
  end
end


text:
package com.jensen.boardgames.othello.model.player;

import com.jensen.boardgames.game.model.ai.AI;
import com.jensen.boardgames.game.model.player.Player;
import com.jensen.boardgames.othello.model.OthelloState;
import com.jensen.boardgames.othello.model.board.DiskColor;
import com.jensen.boardgames.othello.model.board.OthelloMove;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

/**
 * A class representing a othello/reversi player.
 */
public class OthelloPlayer implements Player<OthelloState, OthelloMove> {

    private String name;
    private AI<OthelloState, OthelloMove> ai;
    private DiskColor color;

    /**
     * Creates a othello player which has a name and a color.
     *
     * @param name  The name of this player.
     * @param color The color representing this player.
     */
    public OthelloPlayer(String name, DiskColor color) {
        this.name = name;
        this.color = color;
    }

    /**
     * Gets the color representing this player.
     *
     * @return The color of this player.
     */
    public DiskColor getColor() {
        return color;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public AI<OthelloState, OthelloMove> getAI() {
        return ai;
    }

    @Override
    public void setComputerControlled(String difficulty) {
        switch (difficulty) {
            case "EASY":
                throw new NotImplementedException();
                //break;
            case "NORMAL":
                throw new NotImplementedException();
                //break;
            case "HARD":
                throw new NotImplementedException();
                //break;
            default:
                throw new IllegalArgumentException("Unsupported difficulty");
        }
    }

    @Override
    public boolean isComputerControlled() {
        return ai != null;
    }

    @Override
    public String toString() {
        throw new NotImplementedException();
    }

    @Override
    public OthelloPlayer clone() {
        throw new NotImplementedException();
    }

    @Override
    public boolean equals(Object obj) {
        throw new NotImplementedException();
    }
}


text:
package net.simonvt.cathode.common.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import net.simonvt.cathode.common.R;

public class AppBarRelativeLayout extends RelativeLayout {

  private static final int SCRIM_ANIMATION_DURATION = 600;

  static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator();

  private int contentTopViewId;

  private CollapsingTextHelper textHelper;

  private Toolbar toolbar;
  private View dummyView;

  private View contentView;

  private WindowInsetsCompat lastInsets;
  private int insetsTop;

  private int offset;

  private int expandedMarginStart;
  private int expandedMarginTop;
  private int expandedMarginBottom;
  private int expandedMarginEnd;

  private Drawable contentScrim;
  private Drawable statusBarScrim;

  private Rect dummyBounds = new Rect();

  private Rect collapsedBounds = new Rect();

  private Rect expandedBounds = new Rect();

  private boolean scrimsVisible;

  private ValueAnimator scrimAnimator;
  private int scrimAlpha;

  public AppBarRelativeLayout(Context context) {
    this(context, null);
  }

  public AppBarRelativeLayout(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public AppBarRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    setWillNotDraw(false);

    textHelper = new CollapsingTextHelper(this);
    textHelper.setExpandedTextGravity(Gravity.LEFT | Gravity.BOTTOM);
    textHelper.setTextSizeInterpolator(new DecelerateInterpolator());

    TypedArray a =
        context.obtainStyledAttributes(attrs, R.styleable.AppBarRelativeLayout, defStyleAttr,
            R.style.AppBarRelativeLayout);

    contentTopViewId =
        a.getResourceId(R.styleable.AppBarRelativeLayout_contentTopViewId, R.id.appBarContent);

    expandedMarginStart = expandedMarginTop = expandedMarginEnd = expandedMarginBottom =
        a.getDimensionPixelSize(R.styleable.AppBarRelativeLayout_expandedTitleMargin, 0);

    if (a.hasValue(R.styleable.AppBarRelativeLayout_expandedTitleMarginStart)) {
      expandedMarginStart =
          a.getDimensionPixelSize(R.styleable.AppBarRelativeLayout_expandedTitleMarginStart, 0);
    }
    if (a.hasValue(R.styleable.AppBarRelativeLayout_expandedTitleMarginEnd)) {
      expandedMarginEnd =
          a.getDimensionPixelSize(R.styleable.AppBarRelativeLayout_expandedTitleMarginEnd, 0);
    }

    if (a.hasValue(R.styleable.AppBarRelativeLayout_expandedTitleMarginTop)) {
      expandedMarginTop =
          a.getDimensionPixelSize(R.styleable.AppBarRelativeLayout_expandedTitleMarginTop, 0);
    }

    if (a.hasValue(R.styleable.AppBarRelativeLayout_expandedTitleMarginBottom)) {
      expandedMarginBottom =
          a.getDimensionPixelSize(R.styleable.AppBarRelativeLayout_expandedTitleMarginBottom, 0);
    }

    final int collapsedTextAppearance =
        a.getResourceId(R.styleable.AppBarRelativeLayout_collapsedTitleTextAppearance,
            R.style.TextAppearance_AppCompat_Widget_ActionBar_Title);
    textHelper.setCollapsedTextAppearance(collapsedTextAppearance);

    final int expandedTextAppearance =
        a.getResourceId(R.styleable.AppBarRelativeLayout_expandedTitleTextAppearance,
            R.style.TextAppearance_AppCompat_Title);
    textHelper.setExpandedTextAppearance(expandedTextAppearance);

    contentScrim = a.getDrawable(R.styleable.AppBarRelativeLayout_contentScrim);
    if (contentScrim != null) {
      contentScrim.setCallback(this);
    }
    statusBarScrim = a.getDrawable(R.styleable.AppBarRelativeLayout_statusBarScrim);
    if (statusBarScrim != null) {
      statusBarScrim.setCallback(this);
    }

    a.recycle();

    ViewCompat.setOnApplyWindowInsetsListener(this,
        new androidx.core.view.OnApplyWindowInsetsListener() {
          @Override
          public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
            lastInsets = insets;
            insetsTop = lastInsets.getSystemWindowInsetTop();
            return insets.consumeSystemWindowInsets();
          }
        });
  }

  public void setTitle(CharSequence title) {
    textHelper.setText(title);
  }

  @Override protected void onFinishInflate() {
    super.onFinishInflate();
    toolbar = findViewById(R.id.toolbar);
    contentView = findViewById(contentTopViewId);
  }

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

    ObservableScrollView parent = (ObservableScrollView) getParent();
    parent.addListener(scrollListener);
  }

  private ObservableScrollView.ScrollListener
      scrollListener = new ObservableScrollView.ScrollListener() {
    @Override public void onScrollChanged(int l, int t) {
      if (t == offset) {
        return;
      }

      int offsetBy = t - offset;
      offset = t;

      final int childCount = getChildCount();
      for (int i = 0; i < childCount; i++) {
        final View child = getChildAt(i);
        LayoutParams params = (LayoutParams) child.getLayoutParams();
        final int scrollMode = params.scrollMode;
        switch (scrollMode) {
          case LayoutParams.SCROLL_MODE_PIN:
            child.setTranslationY(t);
            break;

          case LayoutParams.SCROLL_MODE_PARALLEX:
            final float parallexMultiplier = params.parallexMultiplier;
            child.setTranslationY(t * parallexMultiplier);
            break;

          default:
            child.setTranslationY(0);
            break;
        }
      }

      updateScrimBounds();

      collapsedBounds.offset(0, offsetBy);
      expandedBounds.offset(0, offsetBy);
      textHelper.setCollapsedBounds(collapsedBounds);
      textHelper.setExpandedBounds(expandedBounds);
      textHelper.offsetBounds(0, offsetBy);

      final int toolbarBottom = toolbar.getBottom();
      final int contentTop = contentView.getTop();

      final int expanded = contentTop - toolbarBottom;

      final float fraction = 1.0f * offset / expanded;

      textHelper.setExpansionFraction(fraction);

      final int toolbarHeight = toolbar.getHeight();
      if (contentTop - offset < toolbarBottom + toolbarHeight) {
        showScrims();
      } else {
        hideScrims();
      }

      invalidate();
    }
  };

  private void updateScrimBounds() {
    final int scrimTop = insetsTop + offset;
    int scrimHeight = contentView.getTop() - scrimTop;
    scrimHeight = Math.max(scrimHeight, toolbar.getHeight());
    final int scrimBottom = scrimTop + scrimHeight;

    contentScrim.setBounds(0, scrimTop, getWidth(), scrimBottom);
  }

  private void showScrims() {
    if (!scrimsVisible) {
      if (ViewCompat.isLaidOut(this) && !isInEditMode()) {
        animateScrim(255);
      } else {
        setScrimAlpha(255);
      }

      scrimsVisible = true;
    }
  }

  private void hideScrims() {
    if (scrimsVisible) {
      if (ViewCompat.isLaidOut(this) && !isInEditMode()) {
        animateScrim(0);
      } else {
        setScrimAlpha(0);
      }
      scrimsVisible = false;
    }
  }

  private void animateScrim(int targetAlpha) {
    if (scrimAnimator == null) {
      scrimAnimator = new ValueAnimator();
      scrimAnimator.setDuration(SCRIM_ANIMATION_DURATION);
      scrimAnimator.setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR);
      scrimAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override public void onAnimationUpdate(ValueAnimator animator) {
          setScrimAlpha((Integer) animator.getAnimatedValue());
        }
      });
    } else if (scrimAnimator.isRunning()) {
      scrimAnimator.cancel();
    }

    scrimAnimator.setIntValues(scrimAlpha, targetAlpha);
    scrimAnimator.start();
  }

  private void setScrimAlpha(int alpha) {
    if (alpha != scrimAlpha) {
      final Drawable contentScrim = this.contentScrim;
      if (contentScrim != null && toolbar != null) {
        ViewCompat.postInvalidateOnAnimation(toolbar);
      }
      scrimAlpha = alpha;
      ViewCompat.postInvalidateOnAnimation(AppBarRelativeLayout.this);
    }
  }

  @Override public void draw(Canvas canvas) {
    super.draw(canvas);

    textHelper.draw(canvas);

    if (statusBarScrim != null && scrimAlpha > 0) {
      final int topInset = lastInsets != null ? lastInsets.getSystemWindowInsetTop() : 0;
      if (topInset > 0) {
        statusBarScrim.setBounds(0, offset, getWidth(), topInset + offset);
        statusBarScrim.mutate().setAlpha(scrimAlpha);
        statusBarScrim.draw(canvas);
      }
    }
  }

  @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
    if (child == toolbar) {
      contentScrim.mutate().setAlpha(scrimAlpha);
      contentScrim.draw(canvas);
    } else if (child.getId() == R.id.backdrop) {
      final int save = canvas.save();
      canvas.clipRect(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
      boolean result = super.drawChild(canvas, child, drawingTime);
      canvas.restoreToCount(save);
      return result;
    }

    return super.drawChild(canvas, child, drawingTime);
  }

  @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);

    if (toolbar.getTop() < insetsTop) {
      toolbar.offsetTopAndBottom(insetsTop - toolbar.getTop());
    }

    // TODO: Is the design lib way better?
    dummyView.getDrawingRect(dummyBounds);
    offsetDescendantRectToMyCoords(dummyView, dummyBounds);

    updateScrimBounds();

    collapsedBounds.left = dummyBounds.left;
    collapsedBounds.top = dummyBounds.top;
    collapsedBounds.right = dummyBounds.right;
    collapsedBounds.bottom = dummyBounds.bottom;
    collapsedBounds.offset(0, offset);
    textHelper.setCollapsedBounds(collapsedBounds);

    expandedBounds.left = left + expandedMarginStart;
    expandedBounds.top = dummyBounds.bottom + expandedMarginTop;
    expandedBounds.right = (right - left) - expandedMarginEnd;
    expandedBounds.bottom = contentView.getTop() - expandedMarginBottom;
    expandedBounds.offset(0, offset);
    textHelper.setExpandedBounds(expandedBounds);

    textHelper.recalculate();
  }

  @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (dummyView == null) {
      dummyView = new View(getContext());
      toolbar.addView(dummyView, FrameLayout.LayoutParams.MATCH_PARENT,
          FrameLayout.LayoutParams.MATCH_PARENT);
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }

  @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
    return p instanceof LayoutParams;
  }

  @Override protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(super.generateDefaultLayoutParams());
  }

  @Override public LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new LayoutParams(getContext(), attrs);
  }

  @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
    return new LayoutParams(p);
  }

  public static class LayoutParams extends RelativeLayout.LayoutParams {

    public static final int SCROLL_MODE_NONE = 0;

    public static final int SCROLL_MODE_PIN = 1;

    public static final int SCROLL_MODE_PARALLEX = 2;

    private static final float DEFAULT_PARALLAX_MULTIPLIER = 0.0f;

    int scrollMode = SCROLL_MODE_NONE;

    float parallexMultiplier = DEFAULT_PARALLAX_MULTIPLIER;

    public LayoutParams(Context c, AttributeSet attrs) {
      super(c, attrs);

      TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.AppBar_LayoutParams);
      scrollMode = a.getInt(R.styleable.AppBar_LayoutParams_layout_scrollMode, SCROLL_MODE_NONE);
      setParallaxMultiplier(a.getFloat(R.styleable.AppBar_LayoutParams_layout_parallexMultiplier,
          DEFAULT_PARALLAX_MULTIPLIER));
      a.recycle();
    }

    public LayoutParams(int width, int height) {
      super(width, height);
    }

    public LayoutParams(ViewGroup.LayoutParams p) {
      super(p);
    }

    public LayoutParams(MarginLayoutParams source) {
      super(source);
    }

    public LayoutParams(FrameLayout.LayoutParams source) {
      super(source);
    }

    public void setScrollMode(int scrollMode) {
      this.scrollMode = scrollMode;
    }

    public int getScrollMode() {
      return scrollMode;
    }

    public void setParallaxMultiplier(float multiplier) {
      parallexMultiplier = multiplier;
    }

    public float getParallaxMultiplier() {
      return parallexMultiplier;
    }
  }
}


text:
// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License

#ifndef CHAUDIERE_SYSTEMSTATS_H
#define CHAUDIERE_SYSTEMSTATS_H

#include <string>

namespace chaudiere
{

/**
 * SystemStats retrieves various stats from the underlying OS
 */
class SystemStats
{
public:
   /**
    * Default constructor
    */
   SystemStats();

   /**
    * Destructor
    */
   ~SystemStats();

   /**
    * Retrieves the time that the system has been running in seconds
    * @param uptimeSeconds the variable to be populated
    * @return boolean indicating whether the uptime could be retrieved
    */
   static bool uptimeSeconds(long long& uptimeSeconds);

   /**
    * Retrieves the system load averages for the past 1, 5, and 15 minute intervals
    * @param oneMinute the variable to populate with 1 minute load average
    * @param fiveMinute the variable to populate with 5 minute load average
    * @param fifteenMinute the variable to populate with 15 minute load average
    * @return boolean indicating whether the system load averages could be retrieved
    */
   static bool getLoadAverages(double& oneMinute,
                               double& fiveMinute,
                               double& fifteenMinute);

   /**
    * Retrieves the number of processes running on the system
    * @param numberProcesses the variable to populate
    * @return boolean indicating whether the number of processes could be retrieved
    */
   static bool getNumberProcesses(int& numberProcesses);

private:
   // disallow copies
   SystemStats(const SystemStats& copy);
   SystemStats& operator=(const SystemStats& copy);

};

}

#endif


text:
import md5Hex from 'md5-hex';

export default function gravatarUrl(identifier, options) {
	if (!identifier) {
		throw new Error('Please specify an identifier, such as an email address');
	}

	if (identifier.includes('@')) {
		identifier = identifier.toLowerCase().trim();
	}

	const baseUrl = new URL('https://gravatar.com/avatar/');
	baseUrl.pathname += md5Hex(identifier);
	baseUrl.search = new URLSearchParams(options);

	return baseUrl.toString();
}


text:
class AddControlTypeToSample < ActiveRecord::Migration
  def change
    add_column :sample, :control_type, :string
  end
end


text:
<?php namespace Borla\Chikka;

use Borla\Chikka\Models\Config;
use Borla\Chikka\Models\Message;

use Borla\Chikka\Adapters\Config\ConfigInterface;
use Borla\Chikka\Adapters\Config\ConfigTrait;
use Borla\Chikka\Support\Loader;
use Borla\Chikka\Support\Utilities;

use Borla\Chikka\Exceptions\InvalidConfig;

/**
 * Chikka API
 */

class Chikka implements ConfigInterface {

  use ConfigTrait;

  /**
   * Configuration
   */
  protected $config;

  /**
   * Constructor
   * @param array|Config Array or Config
   */
  function __construct($config) {
    // If config is already a Config
    if ($config instanceof Config) {
      // Set it directly
      $this->setConfig($config);
    }
    elseif (is_array($config)) {
      // Load as config
      $this->setConfig(new Config($config));
    }
    else {
      // Throw error
      throw new InvalidConfig('Configuration must be an array or an instance of \Borla\Chikka\Models\Config');
    }
  }

  /**
   * Send SMS
   * @param string|Mobile $mobile Mobile number can be string or an instance of \Borla\Chikka\Models\Mobile
   * @param string|Message $message Message can be string or an instance of \Borla\Chikka\Models\Message
   */
  public function send($mobile, $message, $messageId = null) {
    // Create message
    $message = $this->createMessage([
      'id'      => $messageId,
      'mobile'  => $mobile,
      'message' => $message,
    ]);
    // Return sender response
    return Loader::sender($this->config)->send($message);
  }

  /**
   * Receive
   */
  public function receive(array $post) {
    // Return receiver
    return Loader::receiver($this->config, $post);
  }

  /**
   * Reply
   */
  public function reply($requestId, $mobile, $message, $cost = 0, $messageId = null, $adjustCost = true) {
    // Create message
    $message = $this->createMessage([
      'id'        => $messageId,
      'mobile'    => $mobile,
      'message'   => $message,
      'request_id'=> $requestId,
      'cost'      => $cost,
    ]);
    // Return sender response
    return Loader::sender($this->config)->reply($message, $adjustCost);
  }

  /**
   * Reply to a message
   */
  public function replyTo(Message $message, $messageOrContent, $cost = 0, $messageId = null, $adjustCost = true) {
    // Return
    return $this->reply($message->id, $message->mobile, $messageOrContent, $cost, $messageId, $adjustCost);
  }

  /**
   * Create message
   */
  protected function createMessage($message) {
    // If instance of message
    if ($message instanceof Message) {
      // Return immediately
      return $message;
    }
    // If array
    elseif (is_array($message)) {
      // If there's message instance in message
      if (isset($message['message']) && $message['message'] instanceof Message) {
        // Get message and set attributes
        return $message['message']->setAttributes(Utilities::arrayExcept(['message'], $message));
      }
    }
    // Return
    return Loader::message($message);
  }

}


text:
'use strict';

require('../support/test-helper');

var fs = require('fs');
var assert = require('../support/assert');
var TestClient = require('../support/test-client');
var serverOptions = require('../../lib/server-options');
const mapnik = require('@carto/mapnik');
var IMAGE_TOLERANCE_PER_MIL = 5;

var CARTOCSS_LABELS = [
    '#layer {',
    '  polygon-fill: #374C70;',
    '  polygon-opacity: 0.9;',
    '  line-width: 1;',
    '  line-color: #FFF;',
    '  line-opacity: 0.5;',
    '}',
    '#layer::labels {',
    '  text-name: [name];',
    '  text-face-name: \'DejaVu Sans Book\';',
    '  text-size: 20;',
    '  text-fill: #FFFFFF;',
    '  text-label-position-tolerance: 0;',
    '  text-halo-radius: 1;',
    '  text-halo-fill: #6F808D;',
    '  text-dy: -10;',
    '  text-allow-overlap: true;',
    '  text-placement: point;',
    '  text-placement-type: dummy;',
    '}'
].join('\n');

function createMapConfig (bufferSize, cartocss) {
    cartocss = cartocss || CARTOCSS_LABELS;

    return {
        version: '1.6.0',
        buffersize: bufferSize,
        layers: [{
            type: 'cartodb',
            options: {
                sql: [
                    'select',
                    '   *',
                    'from',
                    '   populated_places_simple_reduced'
                ].join('\n'),
                cartocss: cartocss,
                cartocss_version: '2.3.0',
                interactivity: 'cartodb_id'
            }
        }]
    };
}

describe('buffer size per format', function () {
    let testClient;

    var testCases = [
        {
            desc: 'should get png tile using buffer-size 0',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-0.png',
            mapConfig: createMapConfig({ png: 0, 'grid.json': 0 }),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get png tile using buffer-size 128',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.png',
            mapConfig: createMapConfig({ png: 128, 'grid.json': 128 }),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get mvt tile using buffer-size 0',
            coords: { z: 7, x: 64, y: 48 },
            format: 'mvt',
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-0.mvt',
            mapConfig: createMapConfig({ mvt: 0 }),
            assert: function (tile, callback) {
                var tileJSON = tile.toJSON();
                var features = tileJSON[0].features;
                assert.strictEqual(features.length, 1);
                callback();
            }
        },
        {
            desc: 'should get mvt tile using buffer-size 128',
            coords: { z: 7, x: 64, y: 48 },
            format: 'mvt',
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.mvt',
            mapConfig: createMapConfig({ mvt: 128 }),
            assert: function (tile, callback) {
                var tileJSON = tile.toJSON();
                var features = tileJSON[0].features;
                assert.strictEqual(features.length, 9);
                callback();
            }
        },
        {
            desc: 'should get grid.json tile using buffer-size 0 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'grid.json',
            layers: [0],
            fixturePath: './test/fixtures/buffer-size/tile-grid.json.7.64.48-buffer-size-0.grid.json',
            mapConfig: createMapConfig({ 'grid.json': 0 }),
            assert: function (tile, callback) {
                assert.utfgridEqualsFile(tile, this.fixturePath, 2, callback);
            }
        },
        {
            desc: 'should get grid.json tile using buffer-size 128 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'grid.json',
            layers: [0],
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.grid.json',
            mapConfig: createMapConfig({ 'grid.json': 128 }),
            assert: function (tile, callback) {
                assert.utfgridEqualsFile(tile, this.fixturePath, 2, callback);
            }
        }
    ];

    afterEach(function (done) {
        if (testClient) {
            return testClient.drain(done);
        }
        return done();
    });

    const originalUsePostGIS = serverOptions.renderer.mvt.usePostGIS;
    after(function () {
        serverOptions.renderer.mvt.usePostGIS = originalUsePostGIS;
    });

    var testFn = (test) => {
        it(test.desc, function (done) {
            testClient = new TestClient(test.mapConfig, 1234);
            var coords = test.coords;
            var options = {
                format: test.format,
                layers: test.layers
            };
            testClient.getTile(coords.z, coords.x, coords.y, options, function (err, res, tile) {
                assert.ifError(err);
                // To generate images use:
                // tile.save(test.fixturePath);
                test.assert(tile, done);
            });
        });
    };

    testCases.filter(test => test.format !== 'mvt').forEach(function (test) {
        testFn(test);
    });

    describe('using mapnik mvt renderer', function () {
        before(function () {
            serverOptions.renderer.mvt.usePostGIS = false;
        });
        testCases.filter(test => test.format === 'mvt').forEach(function (test) {
            testFn(test);
        });
    });

    describe('using postgis mvt renderer', function () {
        before(function () {
            serverOptions.renderer.mvt.usePostGIS = true;
        });
        testCases.filter(test => test.format === 'mvt').forEach(function (test) {
            testFn(test);
        });
    });
});

function createBufferSizeTemplate (name, buffersize, placeholders, cartocss) {
    cartocss = cartocss || CARTOCSS_LABELS;

    return {
        version: '0.0.1',
        name: name,
        placeholders: placeholders || {
            buffersize: {
                type: 'number',
                default: 0
            }
        },
        layergroup: createMapConfig(buffersize)
    };
}

describe('buffer size per format for named maps', function () {
    var testCases = [
        {
            desc: 'should get png tile using buffer-size 0 (default value in template)',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-0.png',
            template: createBufferSizeTemplate('named-default-buffer-size', { png: '<%= buffersize %>' }),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get png tile using buffer-size 128 (placehoder value)',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            placeholders: { buffersize: 128 },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.png',
            template: createBufferSizeTemplate('named-custom-buffer-size', { png: '<%= buffersize %>' }),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get png tile using buffer-size 0 (default value in template by format)',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            placeholders: { buffersize_png: 0 },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-0.png',
            template: createBufferSizeTemplate('named-default-buffer-size-by-format', {
                png: '<%= buffersize_png %>'
            }, {
                buffersize_png: {
                    type: 'number',
                    default: '0'
                }
            }),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get png tile using buffer-size 128 (placehoder value in template by format)',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            placeholders: { buffersize_png: 128 },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.png',
            template: createBufferSizeTemplate('named-custom-buffer-size-by-format', {
                png: '<%= buffersize_png %>'
            }, {
                buffersize_png: {
                    type: 'number',
                    default: '0'
                }
            }),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get grid.json tile using buffer-size 0 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'grid.json',
            layers: [0],
            placeholders: { buffersize_gridjson: 0 },
            fixturePath: './test/fixtures/buffer-size/tile-grid.json.7.64.48-buffer-size-0.grid.json',
            template: createBufferSizeTemplate('named-default-buffer-size-by-format-gridjson', {
                'grid.json': '<%= buffersize_gridjson %>'
            }, {
                buffersize_gridjson: {
                    type: 'number',
                    default: '0'
                }
            }),
            assert: function (tile, callback) {
                assert.utfgridEqualsFile(tile, this.fixturePath, 2, callback);
            }
        },
        {
            desc: 'should get grid.json tile using buffer-size 128 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'grid.json',
            layers: [0],
            placeholders: { buffersize_gridjson: 128 },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.grid.json',
            template: createBufferSizeTemplate('named-custom-buffer-size-by-format-gridjson', {
                'grid.json': '<%= buffersize_gridjson %>'
            }, {
                buffersize_gridjson: {
                    type: 'number',
                    default: '0'
                }
            }),
            assert: function (tile, callback) {
                assert.utfgridEqualsFile(tile, this.fixturePath, 2, callback);
            }
        }
    ];

    afterEach(function (done) {
        if (this.testClient) {
            return this.testClient.drain(done);
        }
        return done();
    });

    testCases.forEach(function (test) {
        it(test.desc, function (done) {
            this.testClient = new TestClient(test.template, 1234);
            var coords = test.coords;
            var options = {
                format: test.format,
                placeholders: test.placeholders,
                layers: test.layers
            };
            this.testClient.getTile(coords.z, coords.x, coords.y, options, function (err, res, tile) {
                assert.ifError(err);
                // To generate images use:
                // tile.save('./test/fixtures/buffer-size/tile-7.64.48-buffer-size-0-test.png');
                test.assert(tile, done);
            });
        });
    });
});

describe('buffer size per format for named maps w/o placeholders', function () {
    let testClient;

    var testCases = [
        {
            desc: 'should get png tile using buffer-size 0 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            placeholders: {
                buffersize: {
                    png: 0
                }
            },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-0.png',
            template: createBufferSizeTemplate('named-no-buffer-size-png-0', {}, {}),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get png tile using buffer-size 128 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            placeholders: {
                buffersize: {
                    png: 128
                }
            },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.png',
            template: createBufferSizeTemplate('named-no-buffer-size-png-128', {}, {}),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        },
        {
            desc: 'should get mvt tile using buffer-size 0 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'mvt',
            placeholders: {
                buffersize: {
                    mvt: 0
                }
            },
            fixturePath: './test/fixtures/buffer-size/tile-mvt-7.64.48-buffer-size-0.mvt',
            template: createBufferSizeTemplate('named-no-buffer-size-mvt', {}, {}),
            assert: function (tile, callback) {
                var tileJSON = tile.toJSON();
                var features = tileJSON[0].features;

                var dataFixture = fs.readFileSync(this.fixturePath);
                var vtile = new mapnik.VectorTile(this.coords.z, this.coords.x, this.coords.y);
                vtile.setDataSync(dataFixture);
                var vtileJSON = vtile.toJSON();
                var vtileFeatures = vtileJSON[0].features;

                assert.strictEqual(features.length, vtileFeatures.length);
                callback();
            }
        },
        {
            desc: 'should get mvt tile using buffer-size 128 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'mvt',
            placeholders: {
                buffersize: {
                    mvt: 128
                }
            },
            fixturePath: './test/fixtures/buffer-size/tile-mvt-7.64.48-buffer-size-128.mvt',
            template: createBufferSizeTemplate('named-no-buffer-size-mvt-128', {}, {}),
            assert: function (tile, callback) {
                var tileJSON = tile.toJSON();
                var features = tileJSON[0].features;

                var dataFixture = fs.readFileSync(this.fixturePath);
                var vtile = new mapnik.VectorTile(this.coords.z, this.coords.x, this.coords.y);
                vtile.setDataSync(dataFixture);
                var vtileJSON = vtile.toJSON();
                var vtileFeatures = vtileJSON[0].features;

                assert.strictEqual(features.length, vtileFeatures.length);
                callback();
            }
        },
        {
            desc: 'should get grid.json tile using buffer-size 0 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'grid.json',
            layers: [0],
            placeholders: {
                buffersize: {
                    'grid.json': 0
                }
            },
            fixturePath: './test/fixtures/buffer-size/tile-grid.json.7.64.48-buffer-size-0.grid.json',
            template: createBufferSizeTemplate('named-no-buffer-size-grid-json-0', {}, {}),
            assert: function (tile, callback) {
                assert.utfgridEqualsFile(tile, this.fixturePath, 2, callback);
            }
        },
        {
            desc: 'should get grid.json tile using buffer-size 128 overriden by template params',
            coords: { z: 7, x: 64, y: 48 },
            format: 'grid.json',
            layers: [0],
            placeholders: {
                buffersize: {
                    'grid.json': 128
                }
            },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-128.grid.json',
            template: createBufferSizeTemplate('named-no-buffer-size-grid-json-128', {}, {}),
            assert: function (tile, callback) {
                assert.utfgridEqualsFile(tile, this.fixturePath, 2, callback);
            }
        },
        {
            desc: 'should get png tile using buffer-size 0' +
                  ' overriden by template params with no buffersize in mapconfig',
            coords: { z: 7, x: 64, y: 48 },
            format: 'png',
            placeholders: {
                buffersize: {
                    png: 0
                }
            },
            fixturePath: './test/fixtures/buffer-size/tile-7.64.48-buffer-size-0.png',
            template: createBufferSizeTemplate('named-no-buffer-size-mapconfig-png-0', undefined, {}),
            assert: function (tile, callback) {
                assert.imageIsSimilarToFile(tile, this.fixturePath, IMAGE_TOLERANCE_PER_MIL, callback);
            }
        }

    ];

    afterEach(function (done) {
        if (testClient) {
            return testClient.drain(done);
        }
        return done();
    });

    const originalUsePostGIS = serverOptions.renderer.mvt.usePostGIS;
    after(function () {
        serverOptions.renderer.mvt.usePostGIS = originalUsePostGIS;
    });

    var testFn = (test) => {
        it(test.desc, function (done) {
            test.template.name += '_1';
            testClient = new TestClient(test.template, 1234);
            var coords = test.coords;
            var options = {
                format: test.format,
                placeholders: test.placeholders,
                layers: test.layers
            };
            testClient.getTile(coords.z, coords.x, coords.y, options, function (err, res, tile) {
                assert.ifError(err);
                // To generate images use:
                // tile.save(test.fixturePath);
                // require('fs').writeFileSync(test.fixturePath, JSON.stringify(tile));
                // require('fs').writeFileSync(test.fixturePath, tile.getDataSync());
                test.assert(tile, done);
            });
        });
    };

    testCases.filter(test => test.format !== 'mvt').forEach(function (test) {
        testFn(test);
    });

    describe('using mapnik mvt renderer', function () {
        before(function () {
            serverOptions.renderer.mvt.usePostGIS = false;
        });
        testCases.filter(test => test.format === 'mvt').forEach(function (test) {
            testFn(test);
        });
    });

    describe('using postgis mvt renderer', function () {
        before(function () {
            serverOptions.renderer.mvt.usePostGIS = true;
        });
        testCases.filter(test => test.format === 'mvt').forEach(function (test) {
            testFn(test);
        });
    });
});


text:
package com.homerenting.domain;

import org.codehaus.jackson.annotate.JsonBackReference;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlElement;
import java.io.Serializable;
import java.util.Set;

@Entity
@Table(name = "PARISH")
@NamedQueries({
        @NamedQuery(name = "Parish.FIND_ALL", query = "SELECT p FROM Parish p")
})
public class Parish implements Serializable{

    /** Default value included to remove warning. Remove or modify at will. **/
    private static final long serialVersionUID = 1L;

    public static final String FIND_ALL = "Parish.FIND_ALL";

    @Id
    @GeneratedValue
    @Column(name = "PARISH_ID", unique = true, nullable = false)
    private Long parishId;

    @NotNull
    @Size(min = 1, max = 25)
    @Pattern(regexp = "[A-Za-z ]*", message = "must contain only letters and spaces")
    @Column(name = "PARISH_NAME", unique = false, nullable = false)
    private String parishName;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="REGION_ID_FK", referencedColumnName = "REGION_ID", unique= false, nullable=true, insertable=true, updatable=true)
    @JsonBackReference
    private Region region;
    	/* ==========================GETTERS/SETTERS======================= */

    public Long getParishId() {
      return parishId;
   }

    @XmlElement
    public void setParishId(Long id) {
      this.parishId = parishId;
   }

    public String getParishName() {
      return parishName;
   }

    @XmlElement
    public void setParishName(String parishName) {
      this.parishName = parishName;
   }

    public Region getRegion() {
        return region;
    }

    @XmlElement
    public void setRegion(Region region) {
        this.region = region;
    }

    	/* ==========================BUILDER======================= */

    public static Builder getBuilder() {
        return new Builder();
    }
    public static class Builder {

        private Parish parish;

        public Builder() {
            parish = new Parish();
        }

        public Builder withName(String parishName) {
            parish.parishName = parishName;
            return this;
        }

        public Builder withRegion(Region region) {
            parish.region = region;
            return this;
        }
        public Parish build() {
            return parish;
        }
    }
}


text:
package ru.asemenov.List;

/**
 * Interface SimpleContainer решение задачи части 005.
 * @author asemenov
 * @version 1
 * @param <E> generic.
 */
public interface SimpleContainer<E> extends Iterable<E> {
    /**
     * Add.
     * @param e value.
     */
    void add(E e);

    /**
     * Get value index.
     * @param index E value.
     * @return E value.
     */
    E get(int index);
}


text:
layout: post/index
title: "Garbage Collector no Delphi - Parte II"
date: 2011-03-12
comments: true
categories:
- dev
tags:
- delphi
- generics
lang: pt
---

Olá pessoal, continuando o post anterior de **Garbage Collector**, agora vou explorar o uso para objetos que herdam a classe **TObject**.

Em uma thread na lista de discução **lista-delphi** o membro **Caique** vez uma colocação perfeita do **Garbage Collector** no **Delphi** e como tinha prometido na thread vou compartilhar com vocês a explicação dele. Segue o link da **thread**.

> O **Delphi** "não" tem **Garbage Collector**. Entende-se por **Garbage Collector** uma forma de destruir qualquer objeto fora de contexto como ocorre em plataformas gerenciadas. O que esta demonstrando no seu exemplo é o uso de interfaces e estas sim por definição destroem o objeto a qual estão associadas quando saem do contexto.

Primeiro desenvolvi uma classe que será responsável por coletar os objetos que não estão mais sendo utilizados.

{% codeblock TSafeGuard.pas lang:delphi line_number:true highlight:true %}
unit GarbageCollector;

interface

uses
  SysUtils;

type
  ISafeGuard = type IUnknown;

type
  TSafeGuard = class(TInterfacedObject, ISafeGuard)
  private
    { Private declarations }
    FObj: TObject;

  public
    { Public declarations }
    constructor Create(obj: TObject);
    destructor Destroy(); override;

  end;

function Guard(out SafeGuard : ISafeGuard) : TObject;

implementation

{ TSafeGuard }

constructor TSafeGuard.Create(obj: TObject);
begin
  self.FObj := obj;
end;

destructor TSafeGuard.Destroy();
begin
  if (Assigned(self.FObj)) then
  begin
    try
      FreeAndNil(self.FObj);
    except
      on e : EInvalidPointer do
        { Objeto ja liberado da memoria. }
    end;
  end;

  inherited Destroy();
end;

function Guard(out SafeGuard: ISafeGuard): TObject;
begin
  Result := TObject.Create();
  SafeGuard := TSafeGuard.Create(Result);
end;

end.
{% endcodeblock %}

Depois criei um **Class Helper** para a classe **TObject** do **Delphi** com isto garantimos que todos os objetos que herdam a classe **TObject** serão coletados pelo nosso **Garbage Collector**. Note que estou utilizando **Generics** para a nossa função **New()** já realizar o cast no objeto sem agente precisar se preocupar com isto.

{% codeblock THelperObject.pas lang:delphi line_number:true highlight:true %}
unit HelperObject;

interface

uses
  SysUtils, Generics.Collections, GarbageCollector;

type
  THelperObject = class helper for TObject
  public
    { Public declarations }
    class function New<T>(out SafeGuard: ISafeGuard): T; static;

  end;

implementation

{ THelperObject }

class function THelperObject.New<T>(out SafeGuard: ISafeGuard): T;
begin
  Result := T(Guard(SafeGuard));
end;

end.
{% endcodeblock %}

Agora a forma de utilização.

{% codeblock lang:delphi line_number:true highlight:true %}
var
  SafeGuard: ISafeGuard;
  label1: TLabel;

begin
  label1 := TLabel.New<TLabel>(SafeGuard);
end;
{% endcodeblock %}

Para garantir que a memória está sendo liberada, utilize a mesma propriedade do post anterior **[Garbage Collector no Delphi - Parte I][post-i]**, neste post está explicado detalhadamento como deve ser utilizada.

{% codeblock lang:delphi line_number:true highlight:true %}
ReportMemoryLeaksOnShutdown := True;
{% endcodeblock %}

Este foi mais um exemplo em **Delphi XE**. Espero que tenham gostado e que seja útil de alguma forma a vocês.

[post-i]: /garbage-collector-no-delphi-parte-i/


text:
import unittest
import csv
import random

from amaasutils.random_utils import random_string
from amaascore.csv_upload import Uploader

class PartyUploaderTest(unittest.TestCase):

    def setUp(self):
        self.longMessage = True  # Print complete error message on failure
        self.asset_manager_id = self.client_id = 1
        self.party_ids = [random_string(8), random_string(8)]
        self.csvfile = 'PartyUploaderTest.csv'
        with open(self.csvfile, 'r+', newline='') as readfile:
            reader = csv.reader(readfile)
            for row in reader:
                header = row
                break
        with open(self.csvfile, 'w+', newline='') as writefile:
            writer = csv.writer(writefile)
            writer.writerow(header)
            writer.writerow(['Party', self.party_ids[0], 'Active', 'SGD', 'description',
                             '12345', 'Singapore', 'SGD', '123', '6789', 'true', '1', 'true', '2', 'false'])
            writer.writerow(['Party', self.party_ids[1], 'Active', 'SGD', 'description',
                             '12345', 'Singapore', 'SGD', '123', '6789', 'true', '1', 'true', '2', 'false'])

    def tearDown(self):
        pass

    def test_PartyUploadDownload(self):
        Uploader().upload(csvpath=self.csvfile, asset_manager_id=self.asset_manager_id)
        Uploader().download(csvpath=self.csvfile, asset_manager_id=self.asset_manager_id, data_id_type='party_id', data_id_list=self.party_ids)

if __name__ == '__main__':
    unittest.main()


text:
class CreatePlans < ActiveRecord::Migration
  def change
    create_table :plans do |t|
      t.string :name
      t.text :description
      t.integer :goal_id
      t.integer :user_id

      t.timestamps null: false
    end
  end
end


text:
<?php

declare(strict_types=1);

use A1comms\GaeSupportLaravel\Integration\ErrorReporting\Report as ErrorBootstrap;
use Google\Cloud\Storage\StorageClient;
use OpenCensus\Trace\Exporter\StackdriverExporter;
use OpenCensus\Trace\Tracer;

require __DIR__.'/helpers.php';

// Load in the Laravel / Lumen support helpers, for the "env()" function,
// as we may be loading before them, resulting in undefined function errors
// in the Trace initialisation.
$helpers = [
    __DIR__.'/../../../laravel/framework/src/Illuminate/Support/helpers.php',
    __DIR__.'/../../../illuminate/support/helpers.php',
    __DIR__.'/../../../laravel/framework/src/Illuminate/Collections/helpers.php',
    __DIR__.'/../../../illuminate/collections/helpers.php',
];
foreach ($helpers as $helper) {
    if (is_file($helper)) {
        require $helper;
    }
}

if (is_gae() && (PHP_SAPI !== 'cli')) {
    // Set up exception logging properly...
    ErrorBootstrap::init();

    // Properly set REMOTE_ADDR from a trustworthy source (hopefully).
    if (!empty($_SERVER['HTTP_X_APPENGINE_USER_IP'])) {
        $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_APPENGINE_USER_IP'];
    } elseif (is_cloud_run()) {
        $forwards               = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $_SERVER['REMOTE_ADDR'] = trim(array_pop($forwards));
    }
    if (!empty($_SERVER['HTTP_X_APPENGINE_HTTPS'])) {
        // Turn HTTPS on for Laravel
        $_SERVER['HTTPS'] = $_SERVER['HTTP_X_APPENGINE_HTTPS'];
    }

    $storage = new StorageClient();
    $storage->registerStreamWrapper();

    if (!defined('GAE_TRACE_STOP')) {
        $options = [
            'sampler' => (
                new A1comms\GaeSupportLaravel\Trace\Sampler\HttpHeaderSampler()
            ),
            'propagator' => (
                new OpenCensus\Trace\Propagator\HttpHeaderPropagator(
                    new A1comms\GaeSupportLaravel\Trace\Propagator\CloudTraceFormatter()
                )
            ),
        ];

        if (is_gae_flex()) {
            Tracer::start(new StackdriverExporter(['async' => true]), $options);
        } else {
            // TODO: Async on Standard Environment too!
            Tracer::start(new StackdriverExporter(), $options);
        }
    }

    $loaderInterface = 'App\\Trace\\LowLevelLoader';
    if (!class_exists($loaderInterface)) {
        // TODO: Different default arrays for Laravel vs Lumen?
        $loaderInterface = A1comms\GaeSupportLaravel\Trace\LowLevelLoader::class;
    }
    $traceProviders = $loaderInterface::getList();

    foreach ($traceProviders as $p) {
        $p::load();
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Facebook;

namespace wcfCheckinPlaces
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public object getPositionWebUser(string FacebookAccessToken)
        {
            var facebookClient = new FacebookClient(FacebookAccessToken);
            var me = facebookClient.Get("me") as JsonObject;
            var uid = me["id"];
            return uid;
        }

        public string getBarFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "bar");
        }
        public string getShoppingFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "Shopping");
        }
        public string getCoffeeFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "coffee");
        }

        public string getFunFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "fun");
        }
        public string getRestaurentFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "restaurent");
        }
        public string getArtsFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "arts");
        }
        public string getNightlifeFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "Nightlife");
        }
        public string getFoodyFacebook(string access_token, string latitude, string longitude)
        {
            return getDataFacebook(access_token, latitude, longitude, "food");
        }
        public string getImagesFromID(string fbid)
        {
            WebClient wc = new WebClient();
            string u2 = @"https://graph.facebook.com/" + fbid + "/picture?type=square";
            string access = wc.DownloadString(u2);
            return access;

        }
        public string getDataFacebook(string access_token, string latitude, string longitude, string type)
        {
            WebClient wc = new WebClient();
            string u2 = @"https://graph.facebook.com/search?q=" + type + "&type=place&center=" + latitude + "," + longitude + "&topic_filter=all&access_token=" + access_token;
            string access = wc.DownloadString(u2);
            return access;
        }
        /// <summary>
        /// hàm lấy danh sách
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="AppSecret"></param>
        /// <returns></returns>
        public string getAllAlbumsImages(string AppID, string AppSecret)
        {

            Dictionary<string, object> searchParams = new Dictionary<string, object>();
            searchParams.Add("q", "coffee");
            searchParams.Add("center", "37.76,-122.427");
            searchParams.Add("type", "place");
            searchParams.Add("distance", "1000");

            FacebookClient fbClient = new FacebookClient("1387174581298632|VF96nLPKg9EOglF3nSjamJCAFXU");
            var searchedPlaces = fbClient.Get("albums", searchParams);

            return "";
        }
        /// <summary>
        /// hàm lấy danh sách tất cả các photo images của fb
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="albumID"></param>
        /// <returns></returns>
        public string getAllPhotoImages(string access_token, string albumID)
        {

            Dictionary<string, object> searchParams = new Dictionary<string, object>();
            searchParams.Add("fields", "album,from,height,images,link,id,name");

            FacebookClient fbClient = new FacebookClient(access_token);
            var searchedPlaces = fbClient.Get(albumID, searchParams);

            return searchedPlaces.ToString();
        }
        /// <summary>
        /// hàm lấy danh sách các albums id của fb
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="locationID">id địa điểm</param>
        /// <returns></returns>
        public string getAllAlbums(string access_token, string locationID)
        {

            //   Dictionary<string, object> searchParams = new Dictionary<string, object>();
            //   searchParams.Add("albums", "album,from,height,images,link,id,name");

            FacebookClient fbClient = new FacebookClient(access_token);
            var searchedPlaces = fbClient.Get(locationID + "/" + "albums");

            return searchedPlaces.ToString();
        }
        public string GetAccessTokenFromCode(string AppID, string AppSecret)
        {
            var fb = new FacebookClient();
            dynamic result = fb.Get("oauth/access_token", new
            {
                client_id = AppID,
                client_secret = AppSecret,
                grant_type = "client_credentials"
            });
            fb.AccessToken = result.access_token;

            return fb.AccessToken;

            //WebClient wc = new WebClient();
            //string u2 = @"https://graph.facebook.com/search?q=coffee&type=place&center=37.76,122.427&topic_filter=all&access_token=EAATtoMAo5cgBAO1tGfjQZCppIqvREU7KZCwneqxAurhESHR0rcM3nm8d5CA7ANhU2Hj65SYu9xvTrAMZAtV530pe0Q0ZARZBld78xO5UZCDMbMf4tQVIftfeFuGAP5n3du5UEtxqOBy9626pU4LIKNyUP5Xxa7DiWmbenle0mkhAZDZD";
            //string access = wc.DownloadString(u2);

            //return access;

        }

        public string getFoodFacebook(string access_token, string latitude, string longitude)
        {
            throw new NotImplementedException();
        }
        // neo4j
        public void createLocation(Location location, Datum datum)
        {

            neo4jNodeManagement manager = new neo4jNodeManagement();
            // insert node ...
            manager.createLocation(location, datum);
        }

        public void getObject(RootObject root)
        {

        }

        public void deleteLocation(string fid)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.deleteLocation(fid);
        }

        public void deleteLocation()
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.deleteLocation();

        }

        public void createCategoryList(CategoryList C)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.createCategoryList(C);

        }

        public void deleteCategoryList(string id)
        {
            //lam giong nhung phan o tren -> goi lai ham trong manager , bo dong throw di
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.deleteCategoryList(id);
            // throw new NotImplementedException();
        }

        public void createDatum(Datum D)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.createDatum(D);
            //throw new NotImplementedException();
        }

        public void deleteDatum(string id)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.deleteDatum(id);
            //throw new NotImplementedException();
        }

        public void createRelationLocationCategoryList(string location_fid, string categorylist_id)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.createRelationLocationCategoryList(location_fid, categorylist_id);
            //throw new NotImplementedException();
        }

        public void createRelationCategoryListLocation(string categorylist_id, string location_fid)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.createRelationCategoryListLocation(categorylist_id, location_fid);
            //throw new NotImplementedException();
        }

        public void createRelationDatumCategoryList(string Did, string Cid)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.createRelationDatumCategoryList(Did, Cid);
            //throw new NotImplementedException();
        }

        public void createRelationDatumCategoryList()
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.createRelationDatumCategoryList();
            //throw new NotImplementedException();
        }

        public void createRelationDatumLocation()
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.createRelationDatumLocation();
            //throw new NotImplementedException();
        }

        public void addPropertyNode(string name_object, string fid, Dictionary<string, int> dict)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.addPropertyNode(name_object, fid, dict);
            //throw new NotImplementedException();
        }

        public void removePropertyNode(string name_object, string fid, List<string> parameters)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
            manager.removePropertyNode(name_object, fid, parameters);
            //throw new NotImplementedException();
        }

        //public void selectLocationHaveTheSameCategoryList(string name)
        //{
        //    neo4jNodeManagement manager = new neo4jNodeManagement();
        //    manager.selectLocationHaveTheSameCategoryList(name);
        //}
        public List<Location> selectLocationHaveTheSameCategoryList(string nameOfCategoryList)
        {
            neo4jNodeManagement manager = new neo4jNodeManagement();
           return  manager.selectLocationHaveTheSameCategoryList(nameOfCategoryList);
        }

    }

}


text:
<!DOCTYPE html>

  <title>context.py</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="dycco.css">

context.py

                ¶

A MutableMapping subclass for use as a request-local context object.

                ¶

Imports

from __future__ import unicode_literals

from collections import MutableMapping

                ¶

Mapping Class

                ¶

An attribute access dictionary, of a kind.

This utility class is used to cooperatively construct the ApplicationContext (and subsequent RequestContext)
from the contributions of multiple extensions. The concept of "promotion to a class" is needed in order to enable
the use of descriptor protocol attributes; without promotion the protocol would not be utilized.

class Context(MutableMapping):

                ¶

M-Morty! We're, belch, gonna have to go in deep, Morty!  Elbow deep!

Create a new subclass of Context which incorporates instance attributes and new descriptors.

This promotes an instance and its instance attributes up to being a class with class attributes, then
returns an instance of that class.

	def _promote(self, name, instantiate=True):

		metaclass = type(self.__class__)
		contents = self.__dict__.copy()
		cls = metaclass(str(name), (self.__class__, ), contents)

		if instantiate:
			return cls()

		return cls

                ¶

Construct a new Context instance.

All keyword arguments are applied to the instance as attributes through direct assignment to __dict__.

	def __init__(self, **kw):
		self.__dict__.update(kw)
		super(Context, self).__init__()

                ¶

Get a list of the public data attributes.

	def __len__(self):
		return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])

                ¶

Iterate all valid (public) attributes/keys.

	def __iter__(self):
		return (i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_')

                ¶

Retrieve an attribute through dictionary access.

	def __getitem__(self, name):
		try:
			return getattr(self, name)
		except AttributeError:
			pass

                ¶

We do this here to avoid Python 3's nested exception support.

		raise KeyError(name)

                ¶

Assign an attribute through dictionary access.

	def __setitem__(self, name, value):
		setattr(self, name, value)

                ¶

Delete an attribute through dictionary access.

	def __delitem__(self, name):
		try:
			return delattr(self, name)
		except AttributeError:
			pass

                ¶

We do this here to avoid Python 3's nested exception support.

		raise KeyError(name)

                ¶

We generally want to exclude "default object attributes" from the context's list of attributes.
 This auto-detects the basic set of them for exclusion from iteration in the above methods.

Context._STANDARD_ATTRS = set(dir(Context()))

      Generated by Dycco.
      Last updated 25 Apr 2016.


text:
#ifndef BOOST_ASIO_IP_HOST_NAME_HPP
#define BOOST_ASIO_IP_HOST_NAME_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>
#include <string>
#include <boost/system/error_code.hpp>

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {
namespace ip {

/// Get the current host name.
BOOST_ASIO_DECL std::string host_name();

/// Get the current host name.
BOOST_ASIO_DECL std::string host_name(boost::system::error_code& ec);

} // namespace ip
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#if defined(BOOST_ASIO_HEADER_ONLY)
# include <boost/asio/ip/impl/host_name.ipp>
#endif // defined(BOOST_ASIO_HEADER_ONLY)

#endif // BOOST_ASIO_IP_HOST_NAME_HPP


text:
package common

import (
	"bytes"
	"errors"
	"fmt"
	"log"
	"os/exec"
	"path/filepath"
	"regexp"
	"runtime"
)

func workstationCheckLicense() error {
	matches, err := filepath.Glob("/etc/vmware/license-*")
	if err != nil {
		return fmt.Errorf("Error looking for VMware license: %s", err)
	}

	if len(matches) == 0 {
		return errors.New("Workstation does not appear to be licensed. Please license it.")
	}

	return nil
}

func workstationFindVdiskManager() (string, error) {
	return exec.LookPath("vmware-vdiskmanager")
}

func workstationFindVMware() (string, error) {
	return exec.LookPath("vmware")
}

func workstationFindVmrun() (string, error) {
	return exec.LookPath("vmrun")
}

func workstationDhcpLeasesPath(device string) string {
	return "/etc/vmware/" + device + "/dhcpd/dhcpd.leases"
}

func workstationToolsIsoPath(flavor string) string {
	return "/usr/lib/vmware/isoimages/" + flavor + ".iso"
}

func workstationVmnetnatConfPath() string {
	return ""
}

func workstationVerifyVersion(version string) error {
	if runtime.GOOS != "linux" {
		return fmt.Errorf("The VMware WS version %s driver is only supported on Linux, and Windows, at the moment. Your OS: %s", version, runtime.GOOS)
	}

	//TODO(pmyjavec) there is a better way to find this, how?
	//the default will suffice for now.
	vmxpath := "/usr/lib/vmware/bin/vmware-vmx"

	var stderr bytes.Buffer
	cmd := exec.Command(vmxpath, "-v")
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return err
	}

	versionRe := regexp.MustCompile(`(?i)VMware Workstation (\d+)\.`)
	matches := versionRe.FindStringSubmatch(stderr.String())
	if matches == nil {
		return fmt.Errorf(
			"Could not find VMware WS version in output: %s", stderr.String())
	}
	log.Printf("Detected VMware WS version: %s", matches[1])

	return compareVersions(matches[1], version, "Workstation")
}


text:
0.16.3
======

Bug Fixes:
----------
* Add more SQL keywords for auto-complete suggestion.
* Messages raised as part of stored procedures are no longer ignored.
* Use postgres flavored syntax highlighting instead of generic ANSI SQL.

0.16.2
======

Bug Fixes:
----------
* Fix a bug where the schema qualifier was ignored by the auto-completion.
  As a result the suggestions for tables vs functions are cleaner. (Thanks: darikg_)
* Remove scientific notation when formatting large numbers. (Thanks: `Daniel Rocco`_)
* Add the FUNCTION keyword to auto-completion.
* Display NULL values as <null> instead of empty strings.
* Fix the completion refresh when ``\connect`` is executed.

0.16.1
======

Bug Fixes:
----------
* Fix unicode issues with hstore.
* Fix a silent error when database is changed using \\c.

0.16.0
======

Features:
---------
* Add \ds special command to show sequences.
* Add Vi mode for keybindings. This can be enabled by adding 'vi = True' in ~/.pgclirc. (Thanks: `Jay Zeng`_)
* Add a -v/--version flag to pgcli.
* Add completion for TEMPLATE keyword and smart-completion for
  'CREATE DATABASE blah WITH TEMPLATE <tab>'. (Thanks: `Daniel Rocco`_)
* Add custom decoders to json/jsonb to emulate the behavior of psql. This
  removes the unicode prefix (eg: u'Éowyn') in the output. (Thanks: `Daniel Rocco`_)
* Add \df special command to show functions. (Thanks: darikg_)
* Make suggestions for special commands smarter. eg: \dn - only suggests schemas. (Thanks: darikg_)
* Print out the version and other meta info about pgcli at startup.

Bug Fixes:
----------
* Fix a rare crash caused by adding new schemas to a database. (Thanks: darikg_)
* Make \dt command honor the explicit schema specified in the arg. (Thanks: darikg_)
* Print BIGSERIAL type as Integer instead of Float.
* Show completions for special commands at the beginning of a statement. (Thanks: `Daniel Rocco`_)
* Allow special commands to work in a multi-statement case where multiple sql
  statements are separated by semi-colon in the same line.

0.15.4
======
* Dummy version to replace accidental PyPI entry deletion.

0.15.3
======
* Override the LESS options completely instead of appending to it.

0.15.2
=======
* Revert back to using psycopg2 as the postgres adapter. psycopg2cffi fails for some tests in Python 3.

0.15.0
=======

Features:
---------
* Add syntax color styles to config.
* Add auto-completion for COPY statements.
* Change Postgres adapter to psycopg2cffi, to make it PyPy compatible.
  Now pgcli can be run by PyPy.

Bug Fixes:
----------
* Treat boolean values as strings instead of ints.
* Make \di, \dv and \dt to be schema aware. (Thanks: darikg_)
* Make column name display unicode compatible.

0.14.0
======

Features:
---------
* Add alias completion support to ON keyword. (Thanks: `Iryna Cherniavska`_)
* Add LIMIT keyword to completion.
* Auto-completion for Postgres schemas. (Thanks: darikg_)
* Better unicode handling for datatypes, dbname and roles.
* Add \timing command to time the sql commands.
  This can be set via config file (~/.pgclirc) using `timing = True`.
* Add different table styles for displaying output.
  This can be changed via config file (~/.pgclirc) using `table_format = fancy_grid`.
* Add confirmation before printing results that have more than 1000 rows.

Bug Fixes:
----------

* Performance improvements to expanded view display (\x).
* Cast bytea files to text while displaying. (Thanks: `Daniel Rocco`_)
* Added a list of reserved words that should be auto-escaped.
* Auto-completion is now case-insensitive.
* Fix the broken completion for multiple sql statements. (Thanks: darikg_)

0.13.0
======

Features:
---------

* Add -d/--dbname option to the commandline.
  eg: pgcli -d database
* Add the username as an argument after the database.
  eg: pgcli dbname user

Bug Fixes:
----------
* Fix the crash when \c fails.
* Fix the error thrown by \d when triggers are present.
* Fix broken behavior on \?. (Thanks: darikg_)

0.12.0
======

Features:
---------

* Upgrade to prompt_toolkit version 0.26 (Thanks: https://github.com/macobo)
  * Adds Ctrl-left/right to move the cursor one word left/right respectively.
  * Internal API changes.
* IPython integration through `ipython-sql`_ (Thanks: https://github.com/darikg)
  * Add an ipython magic extension to embed pgcli inside ipython.
  * Results from a pgcli query are sent back to ipython.
* Multiple sql statments in the same line separated by semi-colon. (Thanks: https://github.com/macobo)

.. _`ipython-sql`: https://github.com/catherinedevlin/ipython-sql

Bug Fixes:
----------

* Fix 'message' attribute not found exception in Python 3. (Thanks: https://github.com/GMLudo)
* Use the database username as the database name instead of defaulting to OS username. (Thanks: https://github.com/fpietka)
* Auto-completion for auto-escaped column/table names.
* Fix i-reverse-search to work in prompt_toolkit version 0.26.

0.11.0
======

Features:
---------

* Add \dn command. (Thanks: https://github.com/CyberDem0n)
* Add \x command. (Thanks: https://github.com/stuartquin)
* Auto-escape special column/table names. (Thanks: https://github.com/qwesda)
* Cancel a command using Ctrl+C. (Thanks: https://github.com/macobo)
* Faster startup by reading all columns and tables in a single query. (Thanks: https://github.com/macobo)
* Improved psql compliance with env vars and password prompting. (Thanks: https://github.com/darikg)

Bug Fixes:
----------
* Fix the broken behavior of \d+. (Thanks: https://github.com/macobo)
* Fix a crash during auto-completion. (Thanks: https://github.com/Erethon)

Improvements:
-------------
* Faster test runs on TravisCI. (Thanks: https://github.com/macobo)
* Integration tests with Postgres!! (Thanks: https://github.com/macobo)

.. _darikg: https://github.com/darikg
.. _`Iryna Cherniavska`: https://github.com/j-bennet
.. _`Daniel Rocco`: https://github.com/drocco007
.. _`Jay Zeng`:  https://github.com/jayzeng


text:
# Da2e SimpleFactory

[![Build Status](https://travis-ci.org/dmitrya2e/simple-factory.svg?branch=master)](https://travis-ci.org/dmitrya2e/simple-factory)

SimpleFactory is a mini-package implementing Simple Factory design pattern and providing its functionality.

## How to use

```php
<?php

use Da2e\SimpleFactory\SimpleFactory;

$factory = new SimpleFactory();
$factory->create(TheObjectYouNeedToCreate::class, ['optional', 'array', 'of', 'constructor', 'args']);
```

The order of the constructor arguments matters!

To automate the process of creating homogeneous objects with the same constructor arguments, you could simply create a wrapper for the SimpleFactory and pass the required arguments to its constructor, as follows:

```php
<?php

use Da2e\SimpleFactory\SimpleFactory;

class MySimpleFactory extends SimpleFactory
{
    private $dependency;

    public function __construct($dependency)
    {
        $this->dependency = $dependency;
    }

    /**
     * {@inheritdoc}
     */
    public function create(string $class, array $constructorArgs = [])
    {
        parent::create($class, array_merge([$this->dependency], $constructorArgs));
    }
}

$factory = new MySimpleFactory('foobar');
$factory->create(TheObjectYouNeedToCreate1::class);
$factory->create(TheObjectYouNeedToCreate2::class);
$factory->create(TheObjectYouNeedToCreate3::class);

```

## Software requirements

- PHP >= 7.0

## How to install

```
composer require da2e/simple-factory "1.*"
```

## License

This bundle is under the [MIT license](LICENSE).


text:
Read the slua sources code, and learn how to use git

Note:

* Not not rebase master **onto** feature branch
* Use pull —rebase