text:
<bill session="110" type="h" number="3143" updated="2009-01-08T23:23:47-05:00">
	<status><introduced date="1185249600" datetime="2007-07-24"/></status>

	<introduced date="1185249600" datetime="2007-07-24"/>
	<titles>
		<title type="short" as="introduced">Methamphetamine Kingpin Elimination Act of 2007</title>
		<title type="official" as="introduced">To eliminate methamphetamine kingpins.</title>
	</titles>
	<sponsor id="412217"/>
	<cosponsors>
		<cosponsor id="400034" joined="2007-08-01"/>
		<cosponsor id="400177" joined="2007-09-10"/>
		<cosponsor id="400313" joined="2007-08-03"/>
		<cosponsor id="400055" joined="2007-08-01"/>
		<cosponsor id="400147" joined="2007-08-01"/>
		<cosponsor id="400287" joined="2007-08-04"/>
		<cosponsor id="400088" joined="2007-09-10"/>
	</cosponsors>
	<actions>
		<action date="1185249600" datetime="2007-07-24"><text>Referred to the Committee on the Judiciary, and in addition to the Committee on Energy and Commerce, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text></action>
		<action date="1185249600" datetime="2007-07-24"><text>Referred to House Judiciary</text></action>
		<action date="1185249600" datetime="2007-07-24"><text>Referred to House Energy and Commerce</text></action>
		<action date="1185249600" datetime="2007-07-24"><committee name="House Energy and Commerce"/><text>Referred to the Subcommittee on Health.</text></action>
		<action date="1186718400" datetime="2007-08-10"><committee name="House Judiciary"/><text>Referred to the Subcommittee on Crime, Terrorism, and Homeland Security.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	7/24/2007--Introduced.<br/>Methamphetamine Kingpin Elimination Act of 2007 - Amends the Controlled Substances Act to expand the threshold criteria for designating an individual as a principal administrator, organizer, or leader of a continuing criminal enterprise involving methamphetamine. Amends the Controlled Substances Import and Export Act to increase the mandatory minimum prison terms for trafficking in methamphetamine. Requires the Attorney General to establish methamphetamine task forces, consisting of federal, state, and local law enforcement authorities, to coordinate efforts to combat methamphetamine trafficking.
	</summary>
</bill>

redpajama_set_name: RedPajamaGithub


text:
import * as React from "react";
import {shallow, ShallowWrapper} from "enzyme";
import {expect} from "chai";

import {ErrorAlerts, ErrorAlertsProps, ErrorAlertsState} from "../../src/component/ErrorAlerts";
import Alerts from "../../src/component/Alerts";

describe("ErrorAlerts", () => {
    describe("className", () => {
        it("should have set a component className", () => {
            let props: ErrorAlertsProps = {
                messages: "error message"
            };

            let wrapper: ShallowWrapper<ErrorAlertsProps, ErrorAlertsState> = shallow(<ErrorAlerts {...props} />);
            expect(wrapper.find(Alerts).find({
                className: "errors",
                alertStyle: "danger",
                messages: props.messages
            })).to.have.length(1);
        });

        it("should have set a custom className if one is provided via props.className", () => {
            let props: ErrorAlertsProps = {
                messages: "error message",
                className: "custom-classname"
            };

            let wrapper: ShallowWrapper<ErrorAlertsProps, ErrorAlertsState> = shallow(<ErrorAlerts {...props} />);
            expect(wrapper.find(Alerts).find({
                className: "errors " + props.className,
                alertStyle: "danger",
                messages: props.messages
            })).to.have.length(1);
        });
    });

    describe("messages without button", () => {
        it("should display the error messages with the default icon", () => {
            let props: ErrorAlertsProps = {
                messages: ["error message 1", "error message 2"]
            };

            let wrapper: ShallowWrapper<ErrorAlertsProps, ErrorAlertsState> = shallow(<ErrorAlerts {...props} />);
            expect(wrapper.find(Alerts).find({
                className: "errors",
                alertStyle: "danger",
                messageIcon: "exclamation-circle",
                messages: props.messages
            })).to.have.length(1);
        });

        it("should display the error messages with a custom icon if one is provided via propsmessageIcon.", () => {
            let props: ErrorAlertsProps = {
                messages: ["error message 1", "error message 2"],
                messageIcon: "arrow-circle-o-right"
            };

            let wrapper: ShallowWrapper<ErrorAlertsProps, ErrorAlertsState> = shallow(<ErrorAlerts {...props} />);
            expect(wrapper.find(Alerts).find({
                className: "errors",
                alertStyle: "danger",
                messageIcon: props.messageIcon,
                messages: props.messages
            })).to.have.length(1);
        });
    });

    describe("messages with button", () => {
        it("should display a the default button", () => {
            let props: ErrorAlertsProps = {
                messages: ["error message 1", "error message 2"],
                onConfirm: () => {
                }
            };

            let wrapper: ShallowWrapper<ErrorAlertsProps, ErrorAlertsState> = shallow(<ErrorAlerts {...props} />);
            expect(wrapper.find(Alerts).find({
                className: "errors",
                alertStyle: "danger",
                messageIcon: "exclamation-circle",
                messages: props.messages,
                onConfirm: props.onConfirm
            })).to.have.length(1);
        });

        it("should display a custom icon for the button if one is provided via props.btnConfirmIcon", () => {
            let props: ErrorAlertsProps = {
                messages: ["error message 1", "error message 2"],
                btnConfirmIcon: "home",
                onConfirm: () => {
                }
            };

            let wrapper: ShallowWrapper<ErrorAlertsProps, ErrorAlertsState> = shallow(<ErrorAlerts {...props} />);
            expect(wrapper.find(Alerts).find({
                className: "errors",
                alertStyle: "danger",
                messageIcon: "exclamation-circle",
                messages: props.messages,
                btnConfirmIcon: props.btnConfirmIcon,
                onConfirm: props.onConfirm
            })).to.have.length(1);
        });

        it("should display a custom label for the button if one is provided via props.btnConfirmLabel", () => {
            let props: ErrorAlertsProps = {
                messages: ["error message 1", "error message 2"],
                btnConfirmLabel: "I Understand",
                onConfirm: () => {
                }
            };

            let wrapper: ShallowWrapper<ErrorAlertsProps, ErrorAlertsState> = shallow(<ErrorAlerts {...props} />);
            expect(wrapper.find(Alerts).find({
                className: "errors",
                alertStyle: "danger",
                messageIcon: "exclamation-circle",
                messages: props.messages,
                btnConfirmLabel: props.btnConfirmLabel,
                onConfirm: props.onConfirm
            })).to.have.length(1);
        });
    });
});


text:
package org.laboys.better.spring.core.annotation.jackson;

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonFormat;

import java.lang.annotation.*;

/**
 * Json日期时间格式化输出
 */
@Documented
@JacksonAnnotationsInside
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
public @interface StandardDateTimeFormatter {}


text:
<button type="button" class="navbar-toggle pull-left">
	Toggle navigation

</button>

				<?php echo Session::get("user_name") ?>

				<?php if(Session::get("owner_flg")) : ?>

<a href="<?php echo Uri::base(false) ?>admin/index">管理者画面

				<?php endif; ?>

<a href="<?php echo Uri::base(false) ?>team/select">チーム選択画面に戻る

<a href="<?php echo Uri::base(false) ?>user/logout">ログアウト


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe "Process.times" do
  it "returns current cpu times" do

    t = Process::times
    t.class.should == Struct::Tms

    # stall for 1 second, but do work instead of sleeping because process
    # times won't increase
    start = Time.now
    1 while (Time.now - start) < 1.1

    # ensure times is at least one second larger
    t2 = Process::times
    diff = (t2.utime + t2.stime) - (t.utime + t.stime)
    (diff > 1).should == true
  end
end


text:
using System;
using NServiceBus;
using NServiceBus.Installation.Environments;

class Program
{
    static void Main()
    {
        // To disable second level retries(SLR), uncomment the following line. SLR is enabled by default.
        //Configure.Features.Disable<NServiceBus.Features.SecondLevelRetries>();

        Configure.Serialization.Json();
        Configure configure = Configure.With();
        configure.Log4Net();
        configure.DefineEndpointName("Samples.FaultTolerance.Server");
        configure.DefaultBuilder();
        configure.InMemorySagaPersister();
        configure.UseInMemoryTimeoutPersister();
        configure.InMemorySubscriptionStorage();
        configure.UseTransport<Msmq>();

        using (IStartableBus startableBus = configure.UnicastBus().CreateBus())
        {
            IBus bus = startableBus
                .Start(() => configure.ForInstallationOn<Windows>().Install());
            bus.SendLocal(new MyMessage());
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}


text:
package  trustrecords;
use strict;

my %config = (hive          => "NTUSER\.DAT",
              hasShortDescr => 1,
              hasDescr      => 0,
              hasRefs       => 0,
              osmask        => 22,
              version       => 20120716);

sub getConfig{return %config}
sub getShortDescr {
	return "Gets user's Office 2010 TrustRecords values";
}
sub getDescr{}
sub getRefs {}
sub getHive {return $config{hive};}
sub getVersion {return $config{version};}

my $VERSION = getVersion();

sub pluginmain {
	my $class = shift;
	my $ntuser = shift;
	::logMsg("Launching  trustrecords v.".$VERSION);
	my $reg = Parse::Win32Registry->new($ntuser);
	my $root_key = $reg->get_root_key;

	::rptMsg("trustrecords v.".$VERSION);
# First, let's find out which version of Office is installed
	my @version;
	my $key_path = "Software\\Microsoft\\Office";
	if (my $key = $root_key->get_subkey($key_path)) {
		my @subkeys = $key->get_list_of_subkeys();
		foreach my $s (@subkeys) {
			my $name = $s->get_name();
			push(@version,$name) if ($name =~ m/^\d/);
		}
	}

	my @v = reverse sort {$a<=>$b} @version;
#	::rptMsg("Office version = ".$v[0]);

# Now that we have the most recent version of Office installed, let's
# start looking at the various subkeys
	my @apps = ("Word","PowerPoint","Excel","Access");
	my $key_path = "Software\\Microsoft\\Office\\".$v[0];

	foreach my $app (@apps) {
		my $app_path = $key_path."\\".$app."\\Security\\Trusted Documents";
		::rptMsg($app);
		if (my $app_key = $root_key->get_subkey($app_path)) {
			my $lastpurge = $app_key->get_value("LastPurgeTime")->get_data();
			::rptMsg("LastPurgeTime = ".gmtime($lastpurge));

			if (my $trust = $app_key->get_subkey("TrustRecords")) {
				my @vals = $trust->get_list_of_values();

				foreach my $v (@vals) {
					my ($t0,$t1) = (unpack("VV",substr($v->get_data(),0,8)));
					my $t = ::getTime($t0,$t1);
					::rptMsg(gmtime($t)." -> ".$v->get_name());
				}
			}
		}
		::rptMsg("");
	}
}
1;


text:
title:  "Lako mai vei Au..."
date:   24/07/2021
---

### Wilika ena Macawa oqo:
Maciu 11:20–30, Maciu 5:5, Vakarua 18:15, Kalatia 5:1, Lako Yani 18:13–22, Kalatia 6:2.

>
Wiligusu

> "Dou lako mai vei au, koi kemudou vakaaduaga sa oca ka colata nai colacola bibi, ia kau na vakacegui kemudou." (Maciu 11:28)

D ou lako mai vei au, koi kemudou vakaaduaga sa oca ka colata nai colacola bibi, ia kau na vakacegui kemudou." Sa dua dina na vosa ni yalayala totoka e solia tiko oqo ki vei keda o Jisu. veikeda e sega ni sotava na bula ni lomaocaoca ena so na gauna, e na vuku beka ni cakacaka se e na vuku ni colacola bibi ni bula e da lako curuma? Ia o Jisu e via kaya tiko ki veikeda, ni o Koya ga e kila vinaka na veika kece eda lako curumatiko, io, o Koya ga ena rawa ni vukei keda—kevaka eda vakatara me vaka-kina.

Ni oti na Nona tukuna ki veikeda meda colata na Nona ivua, sa qai kuria ko Jisu ena Nona kaya, "Ni sa rawarawa na Noqui vua ka mamada na Noqui colacola" (Maciu 11:30). Dua tale na kenai tukutukuni, Vakagalalataka nai vua kei nai colacola ko colata tiko (solia mai vei Au) ka taura na Noqu me nomu, ni sa rawarawa na noqui colacola

Eda na vakila vakacava na vakacegu o koya e tukuna tiko qo o Jisu? Mevaka ni da sa bula tiko ena dua na vuravura a tukuna kina na Kalou vei Atama, ni sa oti nai valavala ca, "e na buno ni matamu ko na kania kina na kemu kakana" (Vakatekivu3:19). Ena vuku ni ka oya, eda sa kila na cava na cakacaka kei na colata nai colacola ka ruirui dredre sara meda colata duadua

_Vulica na lesoni ena macawa oqo me vakarautaki iko ena Siga Tabu, Jiulai 31_


text:
I see you are interested in contributing. That is wonderful. I love
contributions.

I guarantee that there are bugs in this software. And I guarantee that there is
a feature you want that is not in here yet. As such, any and all bugs reports
are gratefully accepted, bugfixes even more so. Helping out with bugs is the
easiest way to contribute.

## The Quick Version

* Have a [GitHub Account][].
* Search the [GitHub Issues][] and see if your issue already present. If so
  add your comments, :thumbsup:, etc.
* Issue not there? Not a problem, open up a [new issue][].
    * **Bug reports** please be as detailed as possible. Include:
        * full ruby engine and version: `ruby -e 'puts RUBY_DESCRIPTION'`
        * operating system and version
        * version of hitimes `ruby -rubygems -e "require 'hitimes'; puts Hitimes::VERSION"`
        * as much detail about the bug as possible so I can replicated it. Feel free
          to link in a [gist][]
    * **New Feature**
        * What the new feature should do.
        * What benefit the new feature brings to the project.
* Fork the [repo][].
* Create a new branch for your issue: `git checkout -b issue/my-issue`
* Lovingly craft your contribution:
    * `rake develop` to get started
    * `rake test` to run tests
* Make sure that `rake test` passes. Its important, I said it twice.
* Add yourself to the contributors section below.
* Submit your [pull request][].

## Building Windows Binaries

This is done using https://github.com/rake-compiler/rake-compiler-dock

1. have VirtualBox installed
2. have Docker Machine installed (https://docs.docker.com/engine/installation/)
3. `gem install rake-compiler-dock`
4. `rake-compiler-dock` (this could take a while)
5. `bundle`
6. `rake cross native gem`

# Contributors

* Jeremy Hinegardner
* Wojciech Piekutowski

[GitHub Account]: https://github.com/signup/free "GitHub Signup"
[GitHub Issues]:  https://github.com/copiousfreetime/hitimes/issues "Hitimes Issues"
[new issue]:      https://github.com/copiousfreetime/hitimes/issues/new "New Hitimes Issue"
[gist]:           https://gist.github.com/ "New Gist"
[repo]:           https://github.com/copiousfreetime/hitimes "hitimes Repo"
[pull request]:   https://help.github.com/articles/using-pull-requests "Using Pull Requests"


text:
See this url: https://rawgit.com/OtagoStudyGroup/studyGroup/gh-pages/lessons/SYSKA_May_2016/20160526_SYSKA_SWC_RStudio.html

Or use the markdown "md" file to view as a webpage.


text:
#ifndef _MATH_H
# error "Never use <bits/inf.h> directly; include <math.h> instead."
#endif

/* If we don't have real infinity, then we're supposed to produce a float
   value that overflows at translation time, which is required to produce
   a diagnostic.  GCC's __builtin_inff produces a quite nice diagnostic
   that tells the user that the target doesn't support infinities.  */

#if __GNUC_PREREQ(3,3)
# define INFINITY	(__builtin_inff())
#else
# define INFINITY	(1e9999f)
#endif


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Iaccessible" do
  it "fails" do
    hwnd = IAccessible.find_window(nil, "MainFormWindow")

    childs = IAccessible.get_accChildCount(hwnd)

    (0..childs).each do |child|
      role_id = IAccessible.get_accRole(hwnd, child)

      name_len = IAccessible.get_accName(hwnd, child, nil, 0) + 1
      name_ptr = FFI::MemoryPointer.new :char, name_len
      IAccessible.get_accName(hwnd, child, name_ptr, name_len)
      name = name_ptr.read_string

      role_name_ptr = FFI::MemoryPointer.new :char, 255
      IAccessible.get_role_text(role_id, role_name_ptr, 255)
      role_name = role_name_ptr.read_string

      accessible = IAccessible.is_accessible(hwnd, child)

      puts "Child #{child} with name #{name} has role id #{role_id} which is #{role_name}. Accessible = #{accessible}"
    end
  end
end


text:
<?php
namespace Bolt\EventListener;

use Bolt\Controller\Zone;
use Silex\Application;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Determine what zone a request is relative to.
 *
 * @author Carson Full <carsonfull@gmail.com>
 */
class ZoneGuesser implements EventSubscriberInterface
{
    /** @var \Silex\Application $app */
    protected $app;

    /**
     * Constructor function.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Kernel request listener callback.
     *
     * @param GetResponseEvent $event
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (Zone::get($request)) {
            return;
        }

        $this->setZone($request);
    }

    /**
     * Sets the request's zone if needed and returns it.
     *
     * @param Request $request
     *
     * @return string
     */
    public function setZone(Request $request)
    {
        if ($zone = Zone::get($request)) {
            return $zone;
        }

        $zone = $this->determineZone($request);
        Zone::set($request, $zone);

        return $zone;
    }

    /**
     * Determine the zone and return it
     *
     * @param Request $request
     *
     * @return string
     */
    protected function determineZone(Request $request)
    {
        if ($request->isXmlHttpRequest() || $this->isPathApplicable($request, Zone::ASYNC)) {
            return Zone::ASYNC;
        } elseif ($this->isPathApplicable($request, Zone::BACKEND)) {
            return Zone::BACKEND;
        } else {
            return Zone::FRONTEND;
        }
    }

    /**
     * Check is a request applies to a zone.
     *
     * @param Request $request
     * @param string  $zone
     *
     * @return boolean
     */
    protected function isPathApplicable(Request $request, $zone)
    {
        $prefix = $this->app["controller.$zone.mount_prefix"];
        return $this->startsWith($request->getPathInfo(), $prefix);
    }

    /**
     * Check if a path string starts with a given prefix.
     *
     * @param string $path
     * @param string $prefix
     *
     * @return boolean
     */
    protected function startsWith($path, $prefix)
    {
        return strpos($path, '/' . ltrim($prefix, '/')) === 0;
    }

    /**
     * Return the events to subscribe to.
     *
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest', 31], // Right after route is matched
        ];
    }
}


text:
package to.cwa.trocado.util;

import com.google.appengine.api.datastore.Category;
import com.googlecode.objectify.Ref;

/**
 * @author krico
 * @since 21/05/16.
 */
public final class ObjectsUtil {
    private ObjectsUtil() {
    }

    public static String toString(Category category) {
        return category == null ? null : category.getCategory();
    }

    public static <T> T get(Ref<T> ref) {
        if (ref == null) return null;
        return ref.get();
    }
}


text:
using System;
using System.Data;
using System.Configuration;
using gov.va.medora.mdo;
using gov.va.medora.mdo.dao.vista;

namespace gov.va.medora.mdws.dto
{
    public class UserOptionTO : AbstractTO
    {
        public string number;
        public string id;
        public string name;
        public string displayName;
        public string key;
        public string reverseKey;
        public string type;
        public bool primaryOption;

        public UserOptionTO() { }

        public UserOptionTO(UserOption mdo)
        {
            this.number = mdo.Number;
            this.id = mdo.Id;
            this.name = mdo.Name;
            this.displayName = mdo.DisplayName;
            this.key = mdo.Key;
            this.reverseKey = mdo.ReverseKey;
            this.type = mdo.Type;
            this.primaryOption = mdo.PrimaryOption;
        }
    }
}


text:
<?php
/**
 * Template to construct and output a post item in a component
 *
 * @since BlogCentral 1.0.0
 *
 * @package BlogCentral
 * @subpackage layout-item-wrapper-begin.php
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?><li <?php echo $blogcentral_extra_li_class . $blogcentral_component_item_style;?>>

	<div class="component-main<?php if ( isset( $blogcentral_meta_wrap_class ) ) { echo $blogcentral_meta_wrap_class; } ?>">
		<?php
		// Output media
		if ( isset( $blogcentral_media ) ) : ?>
			<figure<?php if ( isset( $blogcentral_media_wrap_style ) ) { echo $blogcentral_media_wrap_style;} ?> class="component-media-wrap<?php
				if ( isset( $blogcentral_img_wrap_class ) ) {
					echo $blogcentral_img_wrap_class;
				} ?>">
				<?php echo $blogcentral_media; ?>

		<?php endif;

		// Depending on the layout, this div will be displayed below the media, floated right of media, etc..
		if ( isset( $blogcentral_meta_content ) ) : ?>
			<div<?php if ( isset( $blogcentral_meta_wrap_style ) ) { echo $blogcentral_meta_wrap_style; } ?> class="component-content-wrap">
				<?php if ( isset( $blogcentral_meta_content ) ) { echo $blogcentral_meta_content; }	?>

		<?php endif; ?>


text:
package play.api.routing.sird

import java.net.URI
import java.net.URL

import play.api.mvc.RequestHeader

class RequiredQueryStringParameter(paramName: String) extends QueryStringParameterExtractor[String] {
  def unapply(qs: QueryString): Option[String] = qs.get(paramName).flatMap(_.headOption)
}

class OptionalQueryStringParameter(paramName: String) extends QueryStringParameterExtractor[Option[String]] {
  def unapply(qs: QueryString): Option[Option[String]] = Some(qs.get(paramName).flatMap(_.headOption))
}

class SeqQueryStringParameter(paramName: String) extends QueryStringParameterExtractor[Seq[String]] {
  def unapply(qs: QueryString): Option[Seq[String]] = Some(qs.getOrElse(paramName, Nil))
}

trait QueryStringParameterExtractor[T] {
  import QueryStringParameterExtractor._
  def unapply(qs: QueryString): Option[T]
  def unapply(req: RequestHeader): Option[T] = unapply(req.queryString)
  def unapply(uri: URI): Option[T]           = unapply(parse(uri.getRawQuery))
  def unapply(uri: URL): Option[T]           = unapply(parse(uri.getQuery))
}

object QueryStringParameterExtractor {
  private def parse(query: String): QueryString =
    Option(query).fold(Map.empty[String, Seq[String]]) {
      _.split("&")
        .map {
          _.span(_ != '=') match {
            case (key, v) => key -> v.drop(1) // '=' prefix
          }
        }
        .groupBy(_._1)
        .view
        .mapValues(_.toSeq.map(_._2))
        .toMap
    }

  def required(name: String) = new RequiredQueryStringParameter(name)
  def optional(name: String) = new OptionalQueryStringParameter(name)
  def seq(name: String)      = new SeqQueryStringParameter(name)
}


text:
using Bogus;
using System;

namespace DragonSpark.Application.Compose.Entities.Generation;

public static class Include
{
	public static Include<T, TOther> New<T, TOther>() where TOther : class
		=> new Include<T, TOther>((generator, _) => generator.Generate(), (_, _, _) => {},
		                          scope => scope.Once());

	public static IncludeMany<T, TOther> Many<T, TOther>() where TOther : class
		=> new IncludeMany<T, TOther>((generator, _) => generator.Generate(3), (_, _, _) => {});
}

public readonly struct Include<T, TOther> where TOther : class
{
	readonly Func<Faker<TOther>, T, TOther> _generate;
	readonly Action<Faker, T, TOther>       _post;
	readonly AssignScope<T, TOther>         _scope;

	public Include(Func<Faker<TOther>, T, TOther> generate, Action<Faker, T, TOther> post,
	               AssignScope<T, TOther> scope)
	{
		_generate = generate;
		_post     = post;
		_scope    = scope;
	}

	public Include<T, TOther> Generate(Func<Faker<TOther>, T, TOther> generate)
		=> new Include<T, TOther>(generate, _post, _scope);

	public Include<T, TOther> Configure(Action<Faker, TOther> post)
		=> Configure((generator, _, instance) => post(generator, instance));

	public Include<T, TOther> Configure(Action<Faker, T, TOther> post)
		=> new Include<T, TOther>(_generate, post, _scope);

	public Include<T, TOther> Scoped(AssignScope<T, TOther> scope)
		=> new Include<T, TOther>(_generate, _post, scope);

	internal Payload Complete() => new Payload(_generate, _post, _scope);

	public readonly struct Payload
	{
		public Payload(Func<Faker<TOther>, T, TOther> generate, Action<Faker, T, TOther> configure,
		               AssignScope<T, TOther> scope)

		{
			Generate  = generate;
			Configure = configure;
			Scope     = scope;
		}

		public Func<Faker<TOther>, T, TOther> Generate { get; }

		public Action<Faker, T, TOther> Configure { get; }

		public AssignScope<T, TOther> Scope { get; }

		public Payload With(Action<Faker, T, TOther> configure) => new Payload(Generate, configure, Scope);

		public void Deconstruct(out Func<Faker<TOther>, T, TOther> generate, out Action<Faker, T, TOther> post,
		                        out AssignScope<T, TOther> scope)
		{
			generate = Generate;
			post     = Configure;
			scope    = Scope;
		}
	}
}


text:
/*
 * File:   blshRetriever.h
 * Author: chteflio
 *
 * Created on March 4, 2016, 3:39 PM
 */

#ifndef BLSHRETRIEVER_H
#define	BLSHRETRIEVER_H

namespace mips {

    class BlshRetriever : public LshRetriever {

        inline void processIndexesTopk(const double * query, row_type queryId,
                BlshIndex* index, LshIndex* queryIndex, int activeBlocks,
                ProbeBucket& probeBucket, RetrievalArguments* arg)const {

            row_type numCandidatesToVerify = 0;

#ifdef TIME_IT
            arg->t.start();
#endif
            index->lshBins->getCandidatesWithBlshPruning(queryIndex->cosSketches->sketches, queryId, index->cosSketches->sketches,
                    index->minMatches, arg->candidatesToVerify, numCandidatesToVerify, arg->done, activeBlocks, probeBucket.startPos);

#ifdef TIME_IT
            arg->t.stop();
            arg->scanTime += arg->t.elapsedTime().nanos();
            arg->t.start();
#endif

            verifyCandidatesTopK_lengthTest(query, numCandidatesToVerify, arg);
#ifdef TIME_IT
            arg->t.stop();
            arg->ipTime += arg->t.elapsedTime().nanos();
#endif
        }

        inline void processIndexes(const double * query, row_type queryId,
                BlshIndex* index, LshIndex* queryIndex, int activeBlocks,
                ProbeBucket& probeBucket, RetrievalArguments* arg)const {

            row_type numCandidatesToVerify = 0;

#ifdef TIME_IT
            arg->t.start();
#endif

            index->lshBins->getCandidatesWithBlshPruning(queryIndex->cosSketches->sketches, queryId, index->cosSketches->sketches,
                    index->minMatches, arg->candidatesToVerify, numCandidatesToVerify, arg->done, activeBlocks, probeBucket.startPos);

#ifdef TIME_IT
            arg->t.stop();
            arg->scanTime += arg->t.elapsedTime().nanos();
            arg->t.start();
#endif

            verifyCandidates_noLengthTest(query, numCandidatesToVerify, arg);
#ifdef TIME_IT
            arg->t.stop();
            arg->ipTime += arg->t.elapsedTime().nanos();
#endif
        }

    public:
        BlshRetriever() = default;
        ~BlshRetriever() = default;

        inline virtual void tune(ProbeBucket& probeBucket, const ProbeBucket& prevBucket, std::vector<RetrievalArguments>& retrArg) {

            row_type sampleSize = probeBucket.xValues->size();

            if (sampleSize > 0) {

                // measure length
                // access plain properly
                if (retrArg[0].competitorMethod != NULL) {
                    plain.sampleTimes = *(retrArg[0].competitorMethod);
                } else {
                    plain.tune(probeBucket, prevBucket, retrArg);
                }

                double avgLengthTime = plain.sampleTotalTime / sampleSize;

                // measure LSH
                sampleTimes.resize(sampleSize);
                BlshIndex* index = static_cast<BlshIndex*> (probeBucket.getIndex(BLSH));

                // create lsh signatures for sample queries
                LshIndex queryIndex;
                queryIndex.initializeLists(probeBucket.xValues->size());

                double avgBlockTime = 0;
                double min_t_b = -1;
                int breakpoint = sampleSize - 1;

                for (int i = sampleSize - 1; i >= 0; i--) {
                    int t = probeBucket.xValues->at(i).i;
                    int ind = probeBucket.xValues->at(i).j;

                    const double* query = retrArg[t].queryMatrix->getMatrixRowPtr(ind);

                    double localTheta = probeBucket.bucketScanThreshold / query[-1];
                    int activeBlocks = repetitionsForTheta.findActiveBlocks(localTheta);

                    if (activeBlocks > LSH_SIGNATURES || activeBlocks <= 0) {
                        sampleTimes[i] = plain.sampleTimes[i];

                    } else {
                        if (activeBlocks > index->initializedSketchesForIndex && i < sampleSize - 1) {

                            double expectedTime = avgBlockTime * activeBlocks / (index->initializedSketchesForIndex * (probeBucket.xValues->size() - i));

                            if (expectedTime > avgLengthTime) {
                                min_t_b = localTheta;
                                breakpoint = i;
                                break;
                            }
                        }

                        index->checkAndReallocateAll(retrArg[0].probeMatrix, true, probeBucket.startPos, probeBucket.endPos, activeBlocks,
                                retrArg[0].sums, retrArg[0].countsOfBlockValues, retrArg[0].sketches, true);

                        retrArg[0].tunerTimer.start();
                        queryIndex.checkAndReallocateSingle(retrArg[t].queryMatrix, ind, i, activeBlocks, retrArg[t].sums);

                        LshRetriever::processIndexes(query, i, index, &queryIndex, activeBlocks, probeBucket, &retrArg[0]);
                        retrArg[0].tunerTimer.stop();
                        sampleTimes[i] = retrArg[0].tunerTimer.elapsedTime().nanos();
                        avgBlockTime += sampleTimes[i] / activeBlocks;
                    }
                }

                if (breakpoint == sampleSize - 1) {
                    // compare
                    findCutOffPoint(sampleTimes, plain.sampleTimes, sampleTotalTime, t_b_indx);

                    if (plain.sampleTotalTime < sampleTotalTime) {
                        probeBucket.setAfterTuning(1, 1);
                    } else {
                        double value = (t_b_indx == 0 ? -1 : probeBucket.xValues->at(t_b_indx).result);
                        probeBucket.setAfterTuning(1, value);
                    }

                } else {

                    if (breakpoint == sampleSize - 2) {
                        probeBucket.setAfterTuning(1, 1);
                    } else {
                        probeBucket.setAfterTuning(1, min_t_b);
                    }
                }
            } else {
                probeBucket.setAfterTuning(prevBucket.numLists, prevBucket.t_b);
            }

        }

        inline virtual void run(ProbeBucket& probeBucket, RetrievalArguments* arg) const {

            BlshIndex* index = static_cast<BlshIndex*> (probeBucket.getIndex(BLSH));

            for (auto& queryBatch : arg->queryBatches) {

                if (queryBatch.maxLength() < probeBucket.bucketScanThreshold) {
                    break;
                }

                if (probeBucket.t_b == 1 || (probeBucket.t_b * queryBatch.minLength() > probeBucket.bucketScanThreshold)) {
                    plain.run(queryBatch, probeBucket, arg);

                } else { // do it per query

#ifdef TIME_IT
                    arg->t.start();
#endif

                    if (queryBatch.lshIndex == NULL) {
                        queryBatch.createLshIndex(*(arg->queryMatrix));
                    }

#ifdef TIME_IT
                    arg->t.stop();
                    arg->preprocessTime += arg->t.elapsedTime().nanos();
#endif

                    LshIndex* queryIndex = queryBatch.lshIndex;

                    for (row_type i = queryBatch.startPos; i < queryBatch.endPos; ++i) {

                        const double* query = arg->queryMatrix->getMatrixRowPtr(i);

                        if (query[-1] < probeBucket.bucketScanThreshold)// skip all users from this point on for this bucket
                            break;

                        arg->queryId = arg->queryMatrix->getId(i);
                        if (probeBucket.t_b * query[-1] > probeBucket.bucketScanThreshold) {
                            plain.run(query, probeBucket, arg);
                        } else {

#ifdef TIME_IT
                            arg->t.start();
#endif
                            double localTheta = probeBucket.bucketScanThreshold / query[-1];
                            int activeBlocks = repetitionsForTheta.findActiveBlocks(localTheta);

#ifdef TIME_IT
                            arg->t.stop();
                            arg->boundsTime += arg->t.elapsedTime().nanos();
#endif

                            if (activeBlocks > LSH_SIGNATURES || activeBlocks <= 0) {
                                plain.run(query, probeBucket, arg);
                            } else {

#ifdef TIME_IT
                                arg->t.start();

#endif
//                                 std::cout<<"worst: "<<index->worst<<std::endl;
//                                std::cout<<"About to process my first vector with BLSH"<<std::endl;
//                                std::cout<<"activeBlocks: "<<activeBlocks<<" localTheta: "<<localTheta<<
//                                         " initializedSketchesForIndex: "<<index->initializedSketchesForIndex<<std::endl;
                                if (activeBlocks > index->initializedSketchesForIndex) {
                                    index->lockIndex();
                                    index->checkAndReallocateAll(arg->probeMatrix, true, probeBucket.startPos, probeBucket.endPos, activeBlocks,
                                            arg->sums, arg->countsOfBlockValues, arg->sketches, true); // need for lock here////////////////////////////
                                    index->unlockIndex();
                                }

                                queryIndex->checkAndReallocateSingle(arg->queryMatrix, i, i - queryBatch.startPos, activeBlocks, arg->sums);
#ifdef TIME_IT
                                arg->t.stop();
                                arg->preprocessTime += arg->t.elapsedTime().nanos();
#endif

                                processIndexes(query, i - queryBatch.startPos, index, queryIndex, activeBlocks, probeBucket, arg);
//                                std::cout<<"Done to process my first vector with LSH"<<std::endl;
//                                exit(1);
                            }
                        }
                    }
                }
            }

        }

        inline virtual void tuneTopk(ProbeBucket& probeBucket, const ProbeBucket& prevBucket, std::vector<RetrievalArguments>& retrArg) {

            row_type sampleSize = (probeBucket.xValues != nullptr ? probeBucket.xValues->size() : 0);

            if (sampleSize > 0) {
                plain.sampleTimes.reserve(sampleSize);

                for (row_type i = 0; i < sampleSize; ++i) {
                    int t = probeBucket.xValues->at(i).i;
                    int ind = probeBucket.xValues->at(i).j;

                    plain.sampleTimes.emplace_back(probeBucket.sampleThetas[t][ind].lengthTime);
                    plain.sampleTotalTime += probeBucket.sampleThetas[t][ind].lengthTime;
                }

                double avgLengthTime = plain.sampleTotalTime / sampleSize;

                // measure LSH
                sampleTimes.resize(sampleSize);
                BlshIndex* index = static_cast<BlshIndex*> (probeBucket.getIndex(BLSH));

                if (!index->isInitialized()) {
#if defined(TIME_IT)
                    retrArg[0].t.start();
#endif
                    index->initializeLists(*(retrArg[0].probeMatrix), std::numeric_limits<double>::max(), true, retrArg[0].R, probeBucket.startPos, probeBucket.endPos);

#if defined(TIME_IT)
                    retrArg[0].t.stop();
                    retrArg[0].initializeListsTime += retrArg[0].t.elapsedTime().nanos();
#endif
                }
                // create lsh signatures for sample queries
                LshIndex queryIndex;
                queryIndex.initializeLists(sampleSize);

                double avgBlockTime = 0;
                double min_t_b = -1;
                int breakpoint = sampleSize - 1;

                for (int i = sampleSize - 1; i >= 0; i--) {

                    int t = probeBucket.xValues->at(i).i;
                    int ind = probeBucket.xValues->at(i).j;
                    const double* query = retrArg[t].queryMatrix->getMatrixRowPtr(ind);

                    const std::vector<QueueElement>& prevResults = prevBucket.sampleThetas[t].at(ind).results; //just reading

                    std::copy(prevResults.begin(), prevResults.end(), retrArg[0].heap.begin());
                    std::make_heap(retrArg[0].heap.begin(), retrArg[0].heap.end(), std::greater<QueueElement>());

                    double minScore = retrArg[0].heap.front().data;
                    double localTheta = minScore * (minScore > 0 ? probeBucket.invNormL2.second : probeBucket.invNormL2.first);
                    int activeBlocks = repetitionsForTheta.findActiveBlocks(localTheta);

                    if (activeBlocks > LSH_SIGNATURES || activeBlocks <= 0) {
                        sampleTimes[i] = plain.sampleTimes[i];
                    } else {

                        if (activeBlocks > index->initializedSketchesForIndex && i < sampleSize - 1) {

                            double expectedTime = avgBlockTime * activeBlocks / (index->initializedSketchesForIndex * (sampleSize - i));

                            if (expectedTime > avgLengthTime) {
                                min_t_b = localTheta;
                                breakpoint = i;
                                break;
                            }
                        }
                        index->checkAndReallocateAll(retrArg[0].probeMatrix, true, probeBucket.startPos, probeBucket.endPos, activeBlocks,
                                retrArg[0].sums, retrArg[0].countsOfBlockValues, retrArg[0].sketches, true);

                        retrArg[0].tunerTimer.start();
                        queryIndex.checkAndReallocateSingle(retrArg[t].queryMatrix, ind, i, activeBlocks, retrArg[0].sums);

                        LshRetriever::processIndexesTopk(query, i, index, &queryIndex, activeBlocks, probeBucket, &retrArg[0]);

                        retrArg[0].tunerTimer.stop();
                        sampleTimes[i] = retrArg[0].tunerTimer.elapsedTime().nanos();
                        avgBlockTime += sampleTimes[i] / activeBlocks;
                    }
                }

                if (breakpoint == sampleSize - 1) { // no break at all
                    // compare
                    findCutOffPoint(sampleTimes, plain.sampleTimes, sampleTotalTime, t_b_indx);

                    if (plain.sampleTotalTime < sampleTotalTime) {
                        probeBucket.setAfterTuning(1, 1);
                    } else {
                        double value = (t_b_indx == 0 ? -1 : probeBucket.xValues->at(t_b_indx).result);
                        probeBucket.setAfterTuning(1, value);
                    }

                } else {

                    if (breakpoint == sampleSize - 2) {
                        probeBucket.setAfterTuning(1, 1);
                    } else {
                        probeBucket.setAfterTuning(1, min_t_b);
                    }
                }
            } else {
                probeBucket.setAfterTuning(prevBucket.numLists, prevBucket.t_b);
            }

        }

        inline virtual void runTopK(ProbeBucket& probeBucket, RetrievalArguments* arg) const {

            if (probeBucket.t_b == 1) {
                plain.runTopK(probeBucket, arg);
            } else { // do it per query

                BlshIndex* index = static_cast<BlshIndex*> (probeBucket.getIndex(BLSH));

                if (!index->isInitialized()) {
#ifdef TIME_IT
                    arg->t.start();
#endif
                    index->initializeLists(*(arg->probeMatrix), arg->worstMinScore, true, arg->R, probeBucket.startPos, probeBucket.endPos);

#ifdef TIME_IT
                    arg->t.stop();
                    arg->initializeListsTime += arg->t.elapsedTime().nanos();
#endif
                }
                if (index->minMatches == nullptr) {
                    double worstCaseTheta = arg->worstMinScore;

                    if (worstCaseTheta > 0) {
                        worstCaseTheta *= probeBucket.invNormL2.second;
                        worstCaseTheta = (worstCaseTheta > 1 ? 1 : worstCaseTheta); // it will break in the loop afterwards
                    } else {
                        worstCaseTheta *= probeBucket.invNormL2.first;
                        worstCaseTheta = (worstCaseTheta < -1 ? -1 : worstCaseTheta); // it will have to check everything
                    }
                    arg->worstMinScore = std::numeric_limits<double>::max();
                    index->lockIndex();
                    index->allocateBayesLSHMemory(worstCaseTheta);
                    index->unlockIndex();
                }

                for (auto& queryBatch : arg->queryBatches) {

                    if (queryBatch.isWorkDone())
                        continue;

#ifdef TIME_IT
                    arg->t.start();
#endif

                    if (queryBatch.lshIndex == NULL) {
                        queryBatch.createLshIndex(*(arg->queryMatrix));
                    }

#ifdef TIME_IT
                    arg->t.stop();
                    arg->preprocessTime += arg->t.elapsedTime().nanos();
#endif

                    LshIndex* queryIndex = queryBatch.lshIndex;

                    ///////////////////////
                    row_type user = queryBatch.startPos;
                    int start = queryBatch.startPos * arg->k;
                    int end = queryBatch.endPos * arg->k;
                    for (row_type i = start; i < end; i += arg->k) {
                        if (queryBatch.isQueryInactive(user)) {
                            user++;
                            continue;
                        }

                        const double* query = arg->queryMatrix->getMatrixRowPtr(user);

                        double minScore = arg->topkResults[i].data;
                        double minScoreAppr = minScore;

#ifdef         HYBRID_APPROX
                        //                        minScoreAppr += arg->queryMatrix->epsilonEquivalents[user];
                        //                        arg->currEpsilonAppr = arg->queryMatrix->epsilonEquivalents[user];

                        if (minScoreAppr >= 0) {
                            minScoreAppr *= (1 + arg->epsilon);
                            arg->currEpsilonAppr = (1 + arg->epsilon);
                        } else {
                            //                            minScoreAppr *= (1 - arg->epsilon);
                            arg->currEpsilonAppr = 1; //(1 - arg->epsilon);
                        }

#endif

                        if (probeBucket.normL2.second < minScoreAppr) {// skip this bucket and all other buckets
                            queryBatch.inactivateQuery(user);
                            user++;
#ifdef         HYBRID_APPROX

                            arg->moveTopkToHeap(i);
                            arg->totalErrorAfterResults += approximateHybridError(*arg, probeBucket.normL2.second, probeBucket.invNormL2.second);
#endif

                            continue;
                        }

                        arg->moveTopkToHeap(i);

                        arg->queryId = arg->queryMatrix->getId(user);

                        if (probeBucket.t_b * probeBucket.normL2.second > minScore) {

                            plain.runTopK(query, probeBucket, arg);

                        } else {
#ifdef TIME_IT
                            arg->t.start();
#endif

#if defined(HYBRID_APPROX) && (defined(RELATIVE_APPROX)   || defined(ABS_APPROX))
                            double localTheta = minScoreAppr;
#else
                            double localTheta = minScore;
#endif

                            localTheta = localTheta * (localTheta > 0 ? probeBucket.invNormL2.second : probeBucket.invNormL2.first);
                            int activeBlocks = repetitionsForTheta.findActiveBlocks(localTheta);

#ifdef TIME_IT
                            arg->t.stop();
                            arg->boundsTime += arg->t.elapsedTime().nanos();
#endif
                            if (activeBlocks > LSH_SIGNATURES) {
                                plain.runTopK(query, probeBucket, arg);
                            } else {

#ifdef TIME_IT
                                arg->t.start();
#endif
                                if (activeBlocks > index->initializedSketchesForIndex) {
                                    index->lockIndex();
                                    index->checkAndReallocateAll(arg->probeMatrix, true, probeBucket.startPos, probeBucket.endPos, activeBlocks,
                                            arg->sums, arg->countsOfBlockValues, arg->sketches, true); // need for lock here
                                    index->unlockIndex();
                                }

                                queryIndex->checkAndReallocateSingle(arg->queryMatrix, user, user - queryBatch.startPos, activeBlocks, arg->sums);
#ifdef TIME_IT
                                arg->t.stop();
                                arg->preprocessTime += arg->t.elapsedTime().nanos();
#endif

                                processIndexesTopk(query, user - queryBatch.startPos, index, queryIndex, activeBlocks, probeBucket, arg);

                            }

                        }

                        minScore = arg->heap.front().data;

                        if (arg->worstMinScore > minScore) {
                            arg->worstMinScore = minScore;
                        }

                        arg->writeHeapToTopk(user);
                        user++;

                    }
                }
            }
        }

    };

}

#endif	/* BLSHRETRIEVER_H */


text:
package org.toobsframework.jms.doitref;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.toobsframework.doitref.beans.DoItRefBean;

public class DoItRefMessageReceiver implements IDoItRefMessageReceiver  {

  private static Log log = LogFactory.getLog(DoItRefMessageReceiver.class);

  private JmsDoItRefReceiver jmsReceiver = null;

  public JmsDoItRefReceiver getJmsReceiver() {
    return this.jmsReceiver;
  }

  public void setJmsReceiver(JmsDoItRefReceiver jmsReceiver) {
    this.jmsReceiver = jmsReceiver;
  }

  public DoItRefBean recieve() throws JmsDoItRefException {
    if (log.isDebugEnabled()) {
      log.debug("recieve()");
    }
    return jmsReceiver.recieveMessage();
  }

}


text:
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * OpenAPI spec version: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

import { Link } from './Link';
import { HttpFile } from '../http/http';

export class BranchImpllinks {
    'self'?: Link;
    'actions'?: Link;
    'runs'?: Link;
    'queue'?: Link;
    '_class'?: string;

    static readonly discriminator: string | undefined = undefined;

    static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
        {
            "name": "self",
            "baseName": "self",
            "type": "Link",
            "format": ""
        },
        {
            "name": "actions",
            "baseName": "actions",
            "type": "Link",
            "format": ""
        },
        {
            "name": "runs",
            "baseName": "runs",
            "type": "Link",
            "format": ""
        },
        {
            "name": "queue",
            "baseName": "queue",
            "type": "Link",
            "format": ""
        },
        {
            "name": "_class",
            "baseName": "_class",
            "type": "string",
            "format": ""
        }    ];

    static getAttributeTypeMap() {
        return BranchImpllinks.attributeTypeMap;
    }

    public constructor() {
    }
}


text:
try:
    import queue
except ImportError:
    import Queue    # noqa
import threading

class Producer(object):

    def __init__(self, period_in_seconds, input_queue, input_functor):
        self._period_in_seconds = period_in_seconds
        self._input_queue = input_queue
        self._input_functor = input_functor
        self._event = threading.Event()
        self._thread = threading.Thread(target=self._loop)

    def start(self):
        self._thread.start()

    def stop(self):
        self._event.set()
        self._thread.join()

    def _loop(self):
        while not self._event.wait(self._period_in_seconds):
            self.__put_item_into_the_queue()

    def __put_item_into_the_queue(self):
        try:
            self._input_queue.put(self._input_functor)
        except queue.Full:
            pass

class Consumer(object):

    STOP_SENTINEL = "STOP"

    def __init__(self, output_queue, output_functor):
        self._output_queue = output_queue
        self._output_functor = output_functor
        self._thread = threading.Thread(target=self._loop)
        self.no_data_from_the_queue = True
        self.request_update = False

    def start(self):
        self._thread.start()

    def stop(self):
        self._output_queue.put(self.STOP_SENTINEL)
        self._thread.join()

    def _loop(self):
        for result in iter(self._output_queue.get, self.STOP_SENTINEL):
            self.no_data_from_the_queue = not result
            if result:
                self._output_functor(result)
                self.request_update = True


text:
This section does not exist yet.

To contribute tutorials, simply fork the following repository:

[[https://github.com/ronreiter/interactive-tutorials]]

Then you may add or edit tutorials, and then send me a pull request.

To write a tutorial, simply create a Markdown page under the relevant directory in the `tutorials` directory, and link it in the welcome screen in the relevant section. After adding it, please make sure that it linked correctly by running the Flask web server.

To link to the tutorial that you have created, create a link from the page you would like to link from (usually the `Welcome.md` page) using double brackets.

Each tutorial consists of a brief explanation of the subject, and a short exercise which will test the user. Once the user has finished modifying the code according to the exercise, it should execute to print out the expected output that you will provide.

Every tutorial must have the following structure:

### File name.md

    Tutorial
    --------
    Here you may write text that explains a certain feature.

    Exercise
    --------
    Here you will need to write the purpose of the exercise. Finishing the exercise correctly
    must be accomplished using the new feature that you are explaining.

    Tutorial Code
    -------------
    Write a code block that will appear on the interpreter window. For example, you may
    write an empty function, which the user must complete in order to finish the exercise.

    Expected Output
    ---------------
    Write a code block that will describe the exact output expected from the modified code,
    if it has been modified correctly.

    Solution
    --------
    Write the solution code to the problem.


text:
<?php

namespace Encore\Admin\Layout;

use Illuminate\Contracts\Support\Renderable;

class Column implements Buildable
{
    protected $width = 12;

    protected $contents = [];

    public function __construct($content, $width = 12)
    {
        if ($content instanceof \Closure) {
            call_user_func($content, $this);
        } else {
            $this->append($content);
        }

        $this->width = $width;
    }

    public function append($content)
    {
        $this->contents[] = $content;
    }

    public function build()
    {
        $this->startColumn();

        foreach ($this->contents as $content) {
            if ($content instanceof Renderable) {
                echo $content->render();
            } else {
                echo (string) $content;
            }
        }

        $this->endColumn();
    }

    protected function startColumn()
    {
        echo "
width}\">";
    }

    protected function endColumn()
    {
        echo '
';
    }
}


text:
layout: post
title:  "Manage Jekyll platform build environment with Vagrant, rvm & bundler"
date:   2016-02-15
description: Manage Jekyll platform build environment with Vagrant, rvm & bundler.
categories:
- blog
permalink: manage-jekyll-with-vagrant-rvm-bundler
---

Building static websites with Jekyll and Github Pages is a rather simple and straightforward process. but, when it comes to managing and maintaining the underlying Ruby environment and all its dependencies, things tend to get pretty messy from time to time (read: platform migration to Jekyll 3.0 which will be the subject of this post' continuation). Even more so if you decide to personalize a thing or two, introduce new feature(s) or implement a new, custom theme. The mess just keeps growing.

To get rid of the "pretty messy" part, we need to abstract the platform away from bare metal while making it:

1. Parallel.

    Bootstrap and manage multiple environments on a single machine while keeping them independent and isolated from each other so that i.e. changing between production and development website instances would not compromise one another.

2. Consistent.

    Setup. Modify. Break. Destroy. Repeat. Also track every change using version-controlled data files.

Provisioning on top of Vagrant and/or Docker machine seemed like the most obvious solution at first. After giving it some consideration, deploying an entire OS sandbox per each new branch would be to much overhead.

Coming from Python world, utilizing virtualenv for each new environment and storing all dependencies in a `requirements.txt` file would have been the easiest way to go. Fortunately enough Ruby ecosystem provides us with a similar solution called rvm.

### Provision a dedicated VM

Define additional dependencies inside a custom `bootstrap.sh` script:

{% highlight sh %}
sudo apt-get -y install nodejs git
{% endhighlight %}

Customize `Vagrantfile` to forward HTTP, HTTPS and Jekyll serve-dedicated ports (server is running headless) and use the `bootstrap.sh` during provisioning:

{% highlight ruby %}
Vagrant.configure(2) do |config|
  config.vm.network "forwarded_port", guest: 80, host: 8080
  config.vm.network "forwarded_port", guest: 443, host: 8443
  config.vm.network "forwarded_port", guest: 4000, host: 4000

  config.vm.provision "shell", path: "bootstrap.sh", privileged: false
end
{% endhighlight %}

And `vagrant up && vagrant ssh`..

### Setup rvm and configure gem sets

rvm is, concept-wise, similar to Python virtualenv. Simply put it lets you install, manage and work with multiple, completely independent Ruby environments (both interpreters and sets of gems) on a single host via `PATH` environmental variable manipulation.

Setup rvm (note: do not use `--ruby` option since it will always pull in the latest Ruby version):

{% highlight sh %}
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
curl -sSL https://get.rvm.io | bash -s stable
source /home/vagrant/.rvm/scripts/rvm
{% endhighlight %}

If the required interpreter version is not available as a pre-compiled binary (returned via the `known` option), rvm will build it from source:

{% highlight sh %}
rvm list known
rvm install 2.1.1
{% endhighlight %}

### Setup bundler

Managing gems with bundler introduces the necessary environment consistency. (yet again using Python reference) bundler `Gemfile` is to rvm environment what `requirements.txt` file is to virtualenv - a (version-controlled) list of required gems and their versions.

Add bundler to `global` gem set so that it will be included in ALL (current and future) environments.

{% highlight sh %}
rvm @global do gem install bundler
{% endhighlight %}

(note: gem sets are available on a per-interpreter basis)

### Setup Jekyll

In order to keep the build environment consistent, Github Pages engine dependencies and their versions must be stored in a `Gemfile`. While tracking all the requirements could become a serious effort, to make bootstrapping and maintenance easier, Github provides a single meta-gem - github-pages.

(as it will be version-controlled) create the `Gemfile` inside the project directory and customize it:

{% highlight ruby %}
source 'https://rubygems.org'
gem 'github-pages', '= 43'
{% endhighlight %}

Create a `blog-stable` gem set to store the stable version of the blog environment:

{% highlight sh %}
rvm gemset create blog-stable
rvm use 2.1.1@blog-stable --default
{% endhighlight %}

Install all the requirements:
{% highlight sh %}
rvm @blog-stable do bundle install
{% endhighlight %}

Before executing, any Jekyll-related command needs to be preceded with `rvm @<gemset> do bundle exec <cmd>` prefix.

To test our solution, run:
{% highlight sh %}
rvm @blog-stable do bundle exec jekyll serve
{% endhighlight %}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using NFluent;
using NUnit.Framework;
using Sharpility.Extensions;
using Sharpility.Util;

namespace Sharpility.Tests.Util
{
    [TestFixture]
    public class StringsTests
    {
        [Test, TestCaseSource("LimitedStringTestCases")]
        public string ShouldReturnLimitedString(string value, int length)
        {
            // when
            var result = Strings.LimitedString(value, length);

            // then
            return result;
        }

        private static IEnumerable<ITestCaseData> LimitedStringTestCases()
        {
            yield return new TestCaseData(null, 100)
                .SetName("Should return null on null string limited to 100 characters")
                .Returns(null);

            yield return new TestCaseData("alice has a cat", 5)
                .SetName("Should return string limited to 5 characters")
                .Returns("alice");

            yield return new TestCaseData("alice has a cat", 1000)
                .SetName("Should return same string when characets limit is greater than string length")
                .Returns("alice has a cat");
        }

        [Test, TestCaseSource("StringLengthTestCases")]
        public int ShouldReturnStringLength(string value)
        {
            // when
            var length = Strings.Length(value);

            // then
            return length;
        }

        private static IEnumerable<ITestCaseData> StringLengthTestCases()
        {
            yield return new TestCaseData("test")
                .SetName("Should return string length")
                .Returns(4);

            yield return new TestCaseData(null)
                .SetName("Should return 0 length for null string")
                .Returns(0);
        }

        [Test, TestCaseSource("ToStringTestCases")]
        public string ShouldReturnReturnObjectToString(object obj)
        {
            // when
            var toString = Strings.ToString(obj);

            // then
            return toString;
        }

        private static IEnumerable<ITestCaseData> ToStringTestCases()
        {
            yield return new TestCaseData("test")
                .SetName("Should return string")
                .Returns("test");

            yield return new TestCaseData(null)
                .SetName("Should generate toString of null object")
                .Returns("null");

            yield return new TestCaseData(new List<int?> { 1, 2, null, 3 })
                .SetName("Should generate toString of collection")
                .Returns("[1, 2, null, 3]");

            yield return new TestCaseData(Lists.EmptyList<int>())
                .SetName("Should generate toString of empty collection")
                .Returns("[]");

            yield return new TestCaseData((object) new object[] {"A", "B", 3, 4})
               .SetName("Should generate toString of array")
               .Returns("[A, B, 3, 4]");

            yield return new TestCaseData(Dictionaries.Create("A", 1, "B", 2, "C", 3))
              .SetName("Should generate toString of dictionary")
              .Returns("[(A, 1), (B, 2), (C, 3)]");

            yield return new TestCaseData(Dictionaries.Create(
                "A", Lists.AsList(Lists.AsList(1, 2, 3), Lists.AsList(4, 5, 6)),
                "B", Lists.AsList(Lists.AsList(1), Lists.AsList(2)),
                "C", Lists.AsList(Lists.EmptyList<int>(), null)))
              .SetName("Should generate toString of complex dictionary")
              .Returns("[(A, [[1, 2, 3], [4, 5, 6]]), (B, [[1], [2]]), (C, [[], null])]");

            yield return new TestCaseData(new DateTime(2016, 2, 9, 10, 45, 0, DateTimeKind.Utc))
               .SetName("Should include UTC kind for DateTime")
               .Returns("2016-02-09 10:45:00Z");

            yield return new TestCaseData(new DateTime(2016, 2, 9, 10, 45, 0, DateTimeKind.Unspecified))
               .SetName("Should ignore unspecified kind for DateTime")
               .Returns("2016-02-09 10:45:00");
        }

        [Test]
        [Explicit] // Depends on system settings
        public void ToStringOfDateTimeWithLocalKindShouldIncludeZoneOffset()
        {
            // given
            var dateTime = new DateTime(2016, 2, 9, 10, 50, 0, DateTimeKind.Local);

            // when
            var dateTimeToString = Strings.ToString(dateTime);

            // then
            Check.That(dateTimeToString).Equals("2016-02-09 10:50:00+01:00");
        }

        [Test, TestCaseSource("StringFormatTestCases")]
        public string ShouldFormatStringParameters(string value, object[] parameters)
        {
            // when
            var formatted = Strings.Format(value, parameters);

            // then
            return formatted;
        }

        private static IEnumerable<ITestCaseData> StringFormatTestCases()
        {
            yield return new TestCaseData("test", new object[0])
                .SetName("Should format string without params")
                .Returns("test");

            yield return new TestCaseData("This is '{0}'", new object[] {null})
                .SetName("Should format null params")
                .Returns("This is 'null'");

            yield return new TestCaseData("{0}, {1}, {2}", new object[] { 1, "B", null })
                .SetName("Should format multiple params")
                .Returns("1, B, null");

            yield return new TestCaseData("This is {0}", new object[] {Lists.AsList(1, 2, 3)})
                .SetName("Should format list params")
                .Returns("This is [1, 2, 3]");

            yield return new TestCaseData("This is {0}", new object[] {
                Lists.AsList(Lists.AsList("A", "B"), Lists.AsList("C", "D"), Lists.EmptyList<string>())})
                .SetName("Should format nested list params")
                .Returns("This is [[A, B], [C, D], []]");

            yield return new TestCaseData("This is {0}", new object[] { Dictionaries.Create("A", 1, "B", 2) })
               .SetName("Should format dictionary params")
               .Returns("This is [(A, 1), (B, 2)]");
        }

        [Test, TestCaseSource("EqualsIgnoreCasesTestCases")]
        public bool ShouldExtendStringByEqualsIgnoreCasesMethod(string given, string comparedTo)
        {
            // when
            var result = given.EqualsIgnoreCases(comparedTo);

            // then
            return result;
        }

        [SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse")]
        [SuppressMessage("ReSharper", "RedundantAssignment")]
        private static IEnumerable<ITestCaseData> EqualsIgnoreCasesTestCases()
        {
            var given = "aa";
            var comparedTo = "aa";
            var expected = true;
            yield return new TestCaseData(given, comparedTo)
                .SetName(Strings.Format("'{0}' to '{1}' compared with ignored cases returns {2}", given, comparedTo, expected))
                .Returns(expected);

            given = "AAA";
            comparedTo = "AAA";
            expected = true;
            yield return new TestCaseData(given, comparedTo)
                .SetName(Strings.Format("'{0}' to '{1}' compared with ignored cases returns {2}", given, comparedTo, expected))
                .Returns(expected);

            given = "AAA";
            comparedTo = "aaa";
            expected = true;
            yield return new TestCaseData(given, comparedTo)
                .SetName(Strings.Format("'{0}' to '{1}' compared with ignored cases returns {2}", given, comparedTo, expected))
                .Returns(expected);

            given = "AaAaa";
            comparedTo = "aAAAa";
            expected = true;
            yield return new TestCaseData(given, comparedTo)
                .SetName(Strings.Format("'{0}' to '{1}' compared with ignored cases returns {2}", given, comparedTo, expected))
                .Returns(expected);

            given = "AAB";
            comparedTo = "AA";
            expected = false;
            yield return new TestCaseData(given, comparedTo)
                .SetName(Strings.Format("'{0}' to '{1}' compared with ignored cases returns {2}", given, comparedTo, expected))
                .Returns(expected);
        }

        [Test]
        public void ShouldReturnByteArrayAsString()
        {
            // given
            var bytes = "this is a test".ToBytes();

            // when
            var toString = Strings.ToString(bytes);

            // then
            Check.That(toString).IsEqualTo("this is a test");
        }
    }
}


text:
<decorators defaultdir="/decorators">
	<excludes>
		<pattern>/includes/*</pattern>
		<pattern>/40*.jsp</pattern>
		<pattern>/dwr/*</pattern>
	</excludes>
	<decorator name="default" page="default.jsp">
		<pattern>/*.jsp</pattern>
		<pattern>/*.do</pattern>
	</decorator>
</decorators>


text:
package metrics

import (
	"fmt"
	"strconv"
	"time"

	"github.com/prometheus/client_golang/prometheus"

	"k8s.io/apiserver/pkg/admission"
)

const (
	namespace = "apiserver"
	subsystem = "admission"
)

var (
	// Use buckets ranging from 25 ms to ~2.5 seconds.
	latencyBuckets       = prometheus.ExponentialBuckets(25000, 2.5, 5)
	latencySummaryMaxAge = 5 * time.Hour

	// Metrics provides access to all admission metrics.
	Metrics = newAdmissionMetrics()
)

// ObserverFunc is a func that emits metrics.
type ObserverFunc func(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string)

const (
	stepValidate = "validate"
	stepAdmit    = "admit"
)

// WithControllerMetrics is a decorator for named admission handlers.
func WithControllerMetrics(i admission.Interface, name string) admission.Interface {
	return WithMetrics(i, Metrics.ObserveAdmissionController, name)
}

// WithStepMetrics is a decorator for a whole admission phase, i.e. admit or validation.admission step.
func WithStepMetrics(i admission.Interface) admission.Interface {
	return WithMetrics(i, Metrics.ObserveAdmissionStep)
}

// WithMetrics is a decorator for admission handlers with a generic observer func.
func WithMetrics(i admission.Interface, observer ObserverFunc, extraLabels ...string) admission.Interface {
	return &pluginHandlerWithMetrics{
		Interface:   i,
		observer:    observer,
		extraLabels: extraLabels,
	}
}

// pluginHandlerWithMetrics decorates a admission handler with metrics.
type pluginHandlerWithMetrics struct {
	admission.Interface
	observer    ObserverFunc
	extraLabels []string
}

// Admit performs a mutating admission control check and emit metrics.
func (p pluginHandlerWithMetrics) Admit(a admission.Attributes, o admission.ObjectInterfaces) error {
	mutatingHandler, ok := p.Interface.(admission.MutationInterface)
	if !ok {
		return nil
	}

	start := time.Now()
	err := mutatingHandler.Admit(a, o)
	p.observer(time.Since(start), err != nil, a, stepAdmit, p.extraLabels...)
	return err
}

// Validate performs a non-mutating admission control check and emits metrics.
func (p pluginHandlerWithMetrics) Validate(a admission.Attributes, o admission.ObjectInterfaces) error {
	validatingHandler, ok := p.Interface.(admission.ValidationInterface)
	if !ok {
		return nil
	}

	start := time.Now()
	err := validatingHandler.Validate(a, o)
	p.observer(time.Since(start), err != nil, a, stepValidate, p.extraLabels...)
	return err
}

// AdmissionMetrics instruments admission with prometheus metrics.
type AdmissionMetrics struct {
	step       *metricSet
	controller *metricSet
	webhook    *metricSet
}

// newAdmissionMetrics create a new AdmissionMetrics, configured with default metric names.
func newAdmissionMetrics() *AdmissionMetrics {
	// Admission metrics for a step of the admission flow. The entire admission flow is broken down into a series of steps
	// Each step is identified by a distinct type label value.
	step := newMetricSet("step",
		[]string{"type", "operation", "rejected"},
		"Admission sub-step %s, broken out for each operation and API resource and step type (validate or admit).", true)

	// Built-in admission controller metrics. Each admission controller is identified by name.
	controller := newMetricSet("controller",
		[]string{"name", "type", "operation", "rejected"},
		"Admission controller %s, identified by name and broken out for each operation and API resource and type (validate or admit).", false)

	// Admission webhook metrics. Each webhook is identified by name.
	webhook := newMetricSet("webhook",
		[]string{"name", "type", "operation", "rejected"},
		"Admission webhook %s, identified by name and broken out for each operation and API resource and type (validate or admit).", false)

	step.mustRegister()
	controller.mustRegister()
	webhook.mustRegister()
	return &AdmissionMetrics{step: step, controller: controller, webhook: webhook}
}

func (m *AdmissionMetrics) reset() {
	m.step.reset()
	m.controller.reset()
	m.webhook.reset()
}

// ObserveAdmissionStep records admission related metrics for a admission step, identified by step type.
func (m *AdmissionMetrics) ObserveAdmissionStep(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {
	m.step.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)
}

// ObserveAdmissionController records admission related metrics for a built-in admission controller, identified by it's plugin handler name.
func (m *AdmissionMetrics) ObserveAdmissionController(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {
	m.controller.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)
}

// ObserveWebhook records admission related metrics for a admission webhook.
func (m *AdmissionMetrics) ObserveWebhook(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {
	m.webhook.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)
}

type metricSet struct {
	latencies        *prometheus.HistogramVec
	latenciesSummary *prometheus.SummaryVec
}

func newMetricSet(name string, labels []string, helpTemplate string, hasSummary bool) *metricSet {
	var summary *prometheus.SummaryVec
	if hasSummary {
		summary = prometheus.NewSummaryVec(
			prometheus.SummaryOpts{
				Namespace: namespace,
				Subsystem: subsystem,
				Name:      fmt.Sprintf("%s_admission_duration_seconds_summary", name),
				Help:      fmt.Sprintf(helpTemplate, "latency summary in seconds"),
				MaxAge:    latencySummaryMaxAge,
			},
			labels,
		)
	}

	return &metricSet{
		latencies: prometheus.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: namespace,
				Subsystem: subsystem,
				Name:      fmt.Sprintf("%s_admission_duration_seconds", name),
				Help:      fmt.Sprintf(helpTemplate, "latency histogram in seconds"),
				Buckets:   latencyBuckets,
			},
			labels,
		),

		latenciesSummary: summary,
	}
}

// MustRegister registers all the prometheus metrics in the metricSet.
func (m *metricSet) mustRegister() {
	prometheus.MustRegister(m.latencies)
	if m.latenciesSummary != nil {
		prometheus.MustRegister(m.latenciesSummary)
	}
}

// Reset resets all the prometheus metrics in the metricSet.
func (m *metricSet) reset() {
	m.latencies.Reset()
	if m.latenciesSummary != nil {
		m.latenciesSummary.Reset()
	}
}

// Observe records an observed admission event to all metrics in the metricSet.
func (m *metricSet) observe(elapsed time.Duration, labels ...string) {
	elapsedSeconds := elapsed.Seconds()
	m.latencies.WithLabelValues(labels...).Observe(elapsedSeconds)
	if m.latenciesSummary != nil {
		m.latenciesSummary.WithLabelValues(labels...).Observe(elapsedSeconds)
	}
}


text:
chapter: Commit
layout: slide
tags: ['commit','diagram']
---

<img class="diagram" src="assets/diagrams/commit/structure.png">

{% capture notes %}
* Git folder is a directory "database" of snapshots for every commit
* `.git` folder contains files, directories
* `.git` is the _entire_ repository
* `/objects` contains all commits, blob, trees
{% endcapture %}
{% include hydeslides/core/notes %}


text:
namespace java {namespace util {

bool Arrays::__init_done = __init_static_variables();
bool Arrays::__init_static_variables(){
	Java2CppSystem::getSelf();
	ThreadContext* ctx = ThreadContext::newThreadContext();
	{
		GCNotifier __refobj1(ctx, __FILEW__, __LINE__, L"Arrays", L"__init_static_variables");
	}
	ctx->localGC();
	delete ctx;
	return true;
}
 Arrays::Arrays(ThreadContext* ctx) throw()  : IObject(ctx)
{
}
void Arrays::__construct_impl(ThreadContext* ctx) throw()
{
}
 Arrays::~Arrays() throw()
{
	ThreadContext *ctx = ThreadContext::getCurentContext();
	if(ctx != nullptr){ctx->incGcDenial();}
	__releaseRegerences(false, ctx);
	if(ctx != nullptr){ctx->decGcDenial();}
}
void Arrays::__releaseRegerences(bool prepare, ThreadContext* ctx) throw()
{
	if(!prepare){
		return;
	}
}
bool Arrays::equals(IArrayObjectPrimitive<char>* array1, IArrayObjectPrimitive<char>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<char>*)nullptr || array2 == (IArrayObjectPrimitive<char>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(array1->get(i) != array2->get(i))
		{
			return false;
		}
	}
	return true;
}
bool Arrays::equals(IArrayObjectPrimitive<short>* array1, IArrayObjectPrimitive<short>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<short>*)nullptr || array2 == (IArrayObjectPrimitive<short>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(array1->get(i) != array2->get(i))
		{
			return false;
		}
	}
	return true;
}
bool Arrays::equals(IArrayObjectPrimitive<wchar_t>* array1, IArrayObjectPrimitive<wchar_t>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<wchar_t>*)nullptr || array2 == (IArrayObjectPrimitive<wchar_t>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(array1->get(i) != array2->get(i))
		{
			return false;
		}
	}
	return true;
}
bool Arrays::equals(IArrayObjectPrimitive<int>* array1, IArrayObjectPrimitive<int>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<int>*)nullptr || array2 == (IArrayObjectPrimitive<int>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(array1->get(i) != array2->get(i))
		{
			return false;
		}
	}
	return true;
}
bool Arrays::equals(IArrayObjectPrimitive<long long>* array1, IArrayObjectPrimitive<long long>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<long long>*)nullptr || array2 == (IArrayObjectPrimitive<long long>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(array1->get(i) != array2->get(i))
		{
			return false;
		}
	}
	return true;
}
bool Arrays::equals(IArrayObjectPrimitive<double>* array1, IArrayObjectPrimitive<double>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<double>*)nullptr || array2 == (IArrayObjectPrimitive<double>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(Double::doubleToLongBits(array1->get(i), ctx) != Double::doubleToLongBits(array2->get(i), ctx))
		{
			return false;
		}
	}
	return true;
}
bool Arrays::equals(IArrayObjectPrimitive<bool>* array1, IArrayObjectPrimitive<bool>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<bool>*)nullptr || array2 == (IArrayObjectPrimitive<bool>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(array1->get(i) != array2->get(i))
		{
			return false;
		}
	}
	return true;
}
bool Arrays::equals(IArrayObjectPrimitive<float>* array1, IArrayObjectPrimitive<float>* array2, ThreadContext* ctx) throw()
{
	if(array1 == array2)
	{
		return true;
	}
	if(array1 == (IArrayObjectPrimitive<float>*)nullptr || array2 == (IArrayObjectPrimitive<float>*)nullptr || array1->length != array2->length)
	{
		return false;
	}
	for(int i = 0; i < array1->length; i ++ )
	{
		if(Float::floatToIntBits(array1->get(i), ctx) != Float::floatToIntBits(array2->get(i), ctx))
		{
			return false;
		}
	}
	return true;
}
void Arrays::fill(IArrayObjectPrimitive<int>* groupBounds, int i, ThreadContext* ctx) throw()
{
	for(int j = 0; j < groupBounds->length; j ++ )
	{
		groupBounds->set(i,j, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<char>* array, char value, ThreadContext* ctx) throw()
{
	for(int i = 0; i < array->length; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<char>* array, int start, int end, char value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<short>* array, short value, ThreadContext* ctx) throw()
{
	for(int i = 0; i < array->length; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<short>* array, int start, int end, short value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<wchar_t>* array, wchar_t value, ThreadContext* ctx) throw()
{
	for(int i = 0; i < array->length; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<wchar_t>* array, int start, int end, wchar_t value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<int>* array, int start, int end, int value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<long long>* array, long long value, ThreadContext* ctx) throw()
{
	for(int i = 0; i < array->length; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<long long>* array, int start, int end, long long value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<float>* array, float value, ThreadContext* ctx) throw()
{
	for(int i = 0; i < array->length; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<float>* array, int start, int end, float value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<double>* array, double value, ThreadContext* ctx) throw()
{
	for(int i = 0; i < array->length; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<double>* array, int start, int end, double value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<bool>* array, bool value, ThreadContext* ctx) throw()
{
	for(int i = 0; i < array->length; i ++ )
	{
		array->set(value,i, ctx);
	}
}
void Arrays::fill(IArrayObjectPrimitive<bool>* array, int start, int end, bool value, ThreadContext* ctx) throw()
{
	for(int i = start; i < end; i ++ )
	{
		array->set(value,i, ctx);
	}
}
int Arrays::binarySearch(IArrayObjectPrimitive<wchar_t>* array, wchar_t value, ThreadContext* ctx) throw()
{
	int low = 0;int mid = -1;int high = array->length - 1;
	while(low <= high)
	{
		mid = ((unsigned int)(low + high))>> 1;
		if(value > array->get(mid))
		{
			low = mid + 1;
		}
				else
		{
			if(value == array->get(mid))
			{
				return mid;
			}
						else
			{
				high = mid - 1;
			}
		}
	}
	if(mid < 0)
	{
		return -1;
	}
	return -mid - (value < array->get(mid) ? 1 : 2);
}
int Arrays::binarySearch(IArrayObjectPrimitive<int>* array, int value, ThreadContext* ctx) throw()
{
	int low = 0;int mid = -1;int high = array->length - 1;
	while(low <= high)
	{
		mid = ((unsigned int)(low + high))>> 1;
		if(value > array->get(mid))
		{
			low = mid + 1;
		}
				else
		{
			if(value == array->get(mid))
			{
				return mid;
			}
						else
			{
				high = mid - 1;
			}
		}
	}
	if(mid < 0)
	{
		return -1;
	}
	return -mid - (value < array->get(mid) ? 1 : 2);
}
int Arrays::binarySearch(IArrayObjectPrimitive<long long>* array, long long value, ThreadContext* ctx) throw()
{
	int low = 0;int mid = -1;int high = array->length - 1;
	while(low <= high)
	{
		mid = ((unsigned int)(low + high))>> 1;
		if(value > array->get(mid))
		{
			low = mid + 1;
		}
				else
		{
			if(value == array->get(mid))
			{
				return mid;
			}
						else
			{
				high = mid - 1;
			}
		}
	}
	if(mid < 0)
	{
		return -1;
	}
	return -mid - (value < array->get(mid) ? 1 : 2);
}
int Arrays::binarySearch(IArrayObjectPrimitive<short>* array, short value, ThreadContext* ctx) throw()
{
	int low = 0;int mid = -1;int high = array->length - 1;
	while(low <= high)
	{
		mid = ((unsigned int)(low + high))>> 1;
		if(value > array->get(mid))
		{
			low = mid + 1;
		}
				else
		{
			if(value == array->get(mid))
			{
				return mid;
			}
						else
			{
				high = mid - 1;
			}
		}
	}
	if(mid < 0)
	{
		return -1;
	}
	return -mid - (value < array->get(mid) ? 1 : 2);
}
void Arrays::__cleanUp(ThreadContext* ctx){
}
}}


text:
#pragma once

#include "huffman/huff_dd.hpp"
#include "huffman/huff_ps.hpp"
#include "arrays/span.hpp"

#include "wx_huff_ps.hpp"

struct huff_ps_disp {
  static constexpr bool needs_all_borders = false;

  template <typename AlphabetType, typename ContextType, typename HuffCodes>
  static void calc_huff(AlphabetType const* text,
                        uint64_t const size,
                        uint64_t const levels,
                        HuffCodes const& codes,
                        ContextType& ctx,
                        span<uint64_t const> const level_sizes) {
    huff_ps(text, size, levels, codes, ctx, level_sizes);
  }
};

template <typename AlphabetType, bool is_tree_>
using wx_huff_dd_ps = huff_dd<huff_ps_disp, wx_huff_ps, AlphabetType, is_tree_>;

/******************************************************************************/


text:
layout: doc
permalink: /de/osm-data/
lang: de
title: OSM-Daten
category: osm-data
cover: yes
nosearch: true
---

OpenStreetMap-Daten
==================

OpenStreetMap ist eine umfangreiche geographische Datenbank und dabei offen und kostenlos.
Aber wie kommen Sie an die Daten heran? In diesem Abschnitt werden wir näher darauf eingehen,
wie die OSM-Daten strukturiert sind und wie Sie die Daten für Ihre Zwecke benutzen können.

<!--
We'll cover:

-	OSM Data: An Overview
-	Geographic File Formats and the .osm file
-	Getting Data
-	OSM Data and Databases
-	Manipulating OSM files with Osmosis
-	The OverPass API

-->


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = debounce;
function debounce(func, wait, immediate) {
  var timeout = void 0;
  var args = void 0;
  var context = void 0;
  var timestamp = void 0;
  var result = void 0;

  var later = function later() {
    var last = +new Date() - timestamp;

    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) {
          context = null;
          args = null;
        }
      }
    }
  };

  return function debounced() {
    context = this;
    args = arguments;
    timestamp = +new Date();

    var callNow = immediate && !timeout;
    if (!timeout) {
      timeout = setTimeout(later, wait);
    }

    if (callNow) {
      result = func.apply(context, args);
      context = null;
      args = null;
    }

    return result;
  };
}


text:
namespace dotless.Core.engine
{
    using System.Collections.Generic;
    using System.Linq;
    using exceptions;
    using utils;
    using LessNodes;

    public class ElementBlock : NodeBlock, INearestResolver, IReferenceableNode
    {
        public string Name { get; set; }
        public Selector Selector { get; set; }

        public ElementBlock(string name, string selector)
        {
            Name = name;
            Selector = selector!=null ? Selector.Get(selector) : Selector.Get("");
        }

        public ElementBlock(string name) : this(name, null)
        {
        }

        /// <summary>
        /// Gets the Trees Root Element
        /// </summary>
        /// <returns></returns>
        public ElementBlock GetRoot()
        {
            var els = this;
            while (!els.IsRoot())
                els = (ElementBlock)els.Parent;
            return els;
        }

        /// <summary>
        /// Gets a specific node based upon its Name value
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private INode Get(string key){
            var rules = All()
                .SelectMany(e => e.Children)
                .Where( e => e is IReferenceableNode )
                .Cast<IReferenceableNode>();

            foreach(var rule in rules)
            {
                if (rule.Name == key)
                    return rule;
            }
            return null;
        }
        public T GetAs<T>(string key) { return (T)Get(key); }

        /// <summary>
        /// Gets a specific node based upon its Equality value
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private INode Get(INode key){
            return Children.Where(r => r.Equals(key)).FirstOrDefault();
        }
        public T GetAs<T>(INode key) { return (T)Get(key); }

        /// <summary>
        /// All Elements down the tree from current one
        /// </summary>
        /// <returns></returns>
        public IList<ElementBlock> All()
        {
            var path = new List<ElementBlock>();
            if(!path.Contains(this)) path.Add(this);
            foreach(var element in Elements){
                path.Add(element);
                path.AddRange(element.All());
            }
            return path;
        }

        /// <summary>
        /// Decend through
        /// </summary>
        /// <param name="selector"></param>
        /// <param name="elementBlock"></param>
        /// <returns></returns>
        internal ElementBlock Descend(Selector selector, ElementBlock elementBlock)
        {
            Selector s;
            if (selector is Child)
            {
                s = GetAs<ElementBlock>(elementBlock.Name).Selector;
                if (s is Child || s is Descendant) return GetAs<ElementBlock>(elementBlock.Name);
            }
            else if(selector is Descendant)
                return GetAs<ElementBlock>(elementBlock.Name);
            else
            {
                s = GetAs<ElementBlock>(elementBlock.Name).Selector;
                if (s.GetType() == selector.GetType()) return GetAs<ElementBlock>(elementBlock.Name);
            }
            return null;
        }

        public override string ToString()
        {
            return IsRoot() ? "*" : Name;
        }

        public bool IsTag
        {
            get { return !IsId || !IsClass || !IsUniversal; }
        }
        public bool IsClass
        {
            get { return Name.StartsWith("."); }
        }
        public bool IsId
        {
            get { return Name.StartsWith("#"); }
        }
        public bool IsUniversal
        {
            get { return Name == "*"; }
        }

        /// <summary>
        /// Nearest node to this element (used for nested variable identification).
        /// </summary>
        /// <param name="ident"></param>
        /// <returns></returns>
        public INode Nearest(string ident)
        {
            INode node = null;
            foreach (var el in Path().Where(n => n is ElementBlock).Cast<ElementBlock>())
            {
                node = GetNodesByIdent(ident, el).FirstOrDefault();
                if (node != null) break;
            }
            if (node == null)
                throw new VariableNameException(ident);
            return node;
        }

        public IList<ElementBlock> Nearests(string ident)
        {
            IList<ElementBlock> nodes = null;
            foreach (var el in Path().Where(n => n is ElementBlock).Cast<ElementBlock>())
            {
                nodes = GetNodesByIdent(ident, el).Cast<ElementBlock>().ToList();
            }
            if (nodes == null || nodes.Count == 0) throw new VariableNameException(ident);
            return nodes;
        }
        public T NearestAs<T>(string ident) { return (T)Nearest(ident); }

        private IEnumerable<INode> GetNodesByIdent(string ident, ElementBlock el)
        {
            IEnumerable<IReferenceableNode> ary;
            if (ident.IsVariable())
                ary = el.Variables.Cast<IReferenceableNode>();
            else
                ary = el.Elements.Cast<IReferenceableNode>();

            return ary.Where(i => i.Name == ident).Cast<INode>();
        }
    }
}


text:
import React from 'react';
import { Link } from 'react-router';
import { shallow } from 'enzyme';
import expect from 'expect';

import { DocumentEdit } from '../DocumentEdit';
import Errors from '../../../components/Errors';
import Button from '../../../components/Button';

import { doc } from './fixtures';

const defaultProps = {
  currentDocument: doc,
  errors: [],
  fieldChanged: false,
  updated: false,
  isFetching: false,
  router: {},
  route: {},
  params: { collection_name: "movies", splat: [null, "inception", "md"] }
};

const setup = (props = defaultProps) => {
  const actions = {
    fetchDocument: expect.createSpy(),
    putDocument: expect.createSpy(),
    deleteDocument: expect.createSpy(),
    updateTitle: expect.createSpy(),
    updateBody: expect.createSpy(),
    updatePath: expect.createSpy(),
    clearErrors: expect.createSpy()
  };

  const component = shallow(<DocumentEdit {...actions} {...props} />);

  return {
    component,
    actions,
    saveButton: component.find(Button).first(),
    deleteButton: component.find(Button).last(),
    errors: component.find(Errors),
    props
  };
};

describe('Containers::DocumentEdit', () => {
  it('should render correctly', () => {
    let { component } = setup(Object.assign(
      {}, defaultProps, { isFetching: true }
    ));
    component = setup(Object.assign(
      {}, defaultProps, { currentDocument: {} }
    )).component;
    expect(component.find('h1').node).toExist();
  });

  it('should not render error messages initially', () => {
    const { errors } = setup();
    expect(errors.node).toNotExist();
  });

  it('should render error messages', () => {
    const { errors } = setup(Object.assign({}, defaultProps, {
      errors: ['The title field is required!']
    }));
    expect(errors.node).toExist();
  });

  it('should not call putDocument if a field is not changed.', () => {
    const { saveButton, actions } = setup();
    saveButton.simulate('click');
    expect(actions.putDocument).toNotHaveBeenCalled();
  });

  it('should call putDocument if a field is changed.', () => {
    const { saveButton, actions } = setup(Object.assign({}, defaultProps, {
      fieldChanged: true
    }));
    saveButton.simulate('click');
    expect(actions.putDocument).toHaveBeenCalled();
  });

  it('should call deleteDocument', () => {
    const { deleteButton, actions } = setup();
    deleteButton.simulate('click');
    expect(actions.deleteDocument).toNotHaveBeenCalled(); // TODO pass prompt
  });
});