text:
package("sqlite3")

    set_homepage("https://sqlite.org/")
    set_description("The most used database engine in the world")

    set_urls("https://sqlite.org/2018/sqlite-autoconf-$(version)000.tar.gz",
             {version = function (version) return version:gsub("%.", "") end})

    add_versions("3.24.0", "d9d14e88c6fb6d68de9ca0d1f9797477d82fc3aed613558f87ffbdbbc5ceb74a")
    add_versions("3.23.0", "b7711a1800a071674c2bf76898ae8584fc6c9643cfe933cfc1bc54361e3a6e49")

    on_install("windows", function (package)
        os.vrun("nmake DEBUG=%s -f Makefile.msc DYNAMIC_SHELL=1 PLATFORM=%s USE_CRT_DLL=%s", package:debug() and "1" or "0", package:arch(), package:config("vs_runtime") == "MD" and "1" or "0")
        os.cp("*.h", package:installdir("include"))
        os.cp("sqlite3.lib", package:installdir("lib"))
        os.cp("sqlite3.pdb", package:installdir("lib"))
        os.cp("sqlite3.dll", package:installdir("lib"))
    end)

    on_install("macosx", "linux", function (package)
        import("package.tools.autoconf").install(package, {package:debug() and "--enable-debug" or ""})
    end)

    on_test(function (package)
        assert(package:has_cfuncs("sqlite3_open_v2", {includes = "sqlite3.h"}))
    end)


text:
#pragma once
#include <aws/macie2/Macie2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/macie2/model/CriterionAdditionalProperties.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Macie2
{
namespace Model
{

  /**
   *
Specifies, as a map, one or more property-based conditions that filter the
   * results of a query for findings.

See Also:
   AWS
   * API Reference

   */
  class AWS_MACIE2_API FindingCriteria
  {
  public:
    FindingCriteria();
    FindingCriteria(Aws::Utils::Json::JsonView jsonValue);
    FindingCriteria& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline const Aws::Map<Aws::String, CriterionAdditionalProperties>& GetCriterion() const{ return m_criterion; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline bool CriterionHasBeenSet() const { return m_criterionHasBeenSet; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline void SetCriterion(const Aws::Map<Aws::String, CriterionAdditionalProperties>& value) { m_criterionHasBeenSet = true; m_criterion = value; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline void SetCriterion(Aws::Map<Aws::String, CriterionAdditionalProperties>&& value) { m_criterionHasBeenSet = true; m_criterion = std::move(value); }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& WithCriterion(const Aws::Map<Aws::String, CriterionAdditionalProperties>& value) { SetCriterion(value); return *this;}

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& WithCriterion(Aws::Map<Aws::String, CriterionAdditionalProperties>&& value) { SetCriterion(std::move(value)); return *this;}

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& AddCriterion(const Aws::String& key, const CriterionAdditionalProperties& value) { m_criterionHasBeenSet = true; m_criterion.emplace(key, value); return *this; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& AddCriterion(Aws::String&& key, const CriterionAdditionalProperties& value) { m_criterionHasBeenSet = true; m_criterion.emplace(std::move(key), value); return *this; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& AddCriterion(const Aws::String& key, CriterionAdditionalProperties&& value) { m_criterionHasBeenSet = true; m_criterion.emplace(key, std::move(value)); return *this; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& AddCriterion(Aws::String&& key, CriterionAdditionalProperties&& value) { m_criterionHasBeenSet = true; m_criterion.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& AddCriterion(const char* key, CriterionAdditionalProperties&& value) { m_criterionHasBeenSet = true; m_criterion.emplace(key, std::move(value)); return *this; }

    /**
     *
A condition that specifies the property, operator, and one or more values to
     * use to filter the results.

     */
    inline FindingCriteria& AddCriterion(const char* key, const CriterionAdditionalProperties& value) { m_criterionHasBeenSet = true; m_criterion.emplace(key, value); return *this; }

  private:

    Aws::Map<Aws::String, CriterionAdditionalProperties> m_criterion;
    bool m_criterionHasBeenSet = false;
  };

} // namespace Model
} // namespace Macie2
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
var width = 1000;
height = 500;

var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g");

var projection = d3.geo.albersUsa()
    .scale(1000)
    .translate([width / 2, height / 2]);

var geoPath = d3.geo.path()
    .projection(projection);

// From data set
var totalLeaving = 260042;
var avgLeavingFactor = 0.02;
var totalCollegePop = 932902;
var avgLeavingPerc = 36.490196078431374;
var avgStayingPerc = 63.509803921568626;

var currentFactor = "leave"; // Default

g.selectAll("path")
    .data(stateshighres.features)
    .enter()
    .append("path")
    .attr("fill", getFill)
    .attr("d", geoPath);

function getFill(d) {
    var name = d.properties.NAME;
    var data = state_data[name];
    var entering = data["entering"].data / totalLeaving - avgLeavingFactor; // 0.02 is "average"
    var enteringFactor = Math.floor(entering * 45 * 255);
    var leaving = (data["leaving"].data.perc - avgLeavingPerc) / 100;
    var leavingFactor = Math.floor(leaving * 5 * 255);
    var staying = (data["in_state"].data.perc - avgLeavingPerc) / 100;
    var stayingFactor = Math.floor(staying * 2 * 255);

    switch (currentFactor) {
        case "leave":
            return "rgb(" + leavingFactor + ", 0, " + (-1 * leavingFactor) + ")";
            break;
        case "enter":
            return "rgb(" + enteringFactor + ", 0, " + (-1 * enteringFactor) + ")";
            break;
        case "stay":
            return "rgb(" + stayingFactor + ", 0, " + (-1 * stayingFactor) + ")";
            break;
        default:
            console.log("Factor case not recognized");
            return "rgb(0,0,0)";
            break;
    }
}

function toggle() {
    var current = document.getElementById("selection").value;
    currentFactor = current;

    var leavenodes = document.getElementsByClassName("leave-desc");
    var enternodes = document.getElementsByClassName("enter-desc");
    var staynodes = document.getElementsByClassName("stay-desc");
    switch (currentFactor) {
        case "leave":
            setvis(leavenodes, enternodes, staynodes);
            break;
        case "enter":
            setvis(enternodes, leavenodes, staynodes);
            break;
        case "stay":
            setvis(staynodes, enternodes, leavenodes);
            break;
        default:
            console.log("Factor case not recognized");
            break;
    }

    recalc();
}
document.getElementById("selection").addEventListener("change", toggle);

function setvis(vis, invis1, invis2) {
    for (var i = 0; i < vis.length; i++) {
        vis[i].style.display = "block";
    }
    for (var j = 0; j < invis1.length; j++) {
        invis1[j].style.display = "none";
    }
    for (var x = 0; x < invis2.length; x++) {
        invis2[x].style.display = "none";
    }
}

function recalc() {
    g.selectAll("path").remove();
    g.selectAll("path")
        .data(stateshighres.features)
        .enter()
        .append("path")
        .attr("fill", getFill)
        .attr("d", geoPath);
}
// Modal
document.getElementById("help").addEventListener("click", function() {
    document.getElementById("modal").style.display = "block";
});
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}


text:
package com.clarkt.pojo;

import org.json.JSONException;
import org.json.JSONObject;

import com.external.activeandroid.Model;
import com.external.activeandroid.annotation.Column;
import com.external.activeandroid.annotation.Table;

@Table(name = "SimpleGoods")
public class SimpleGoods  extends Model {

     @Column(name = "uid")
     private String uid;

     @Column(name = "name")
     private String name;

     @Column(name = "num")
     private int num = 0;

     @Column(name = "price")
     private float price = 0;

     @Column(name = "singlePrice")
     private float singlePrice = 0;

     @Column(name = "img")
     private Img img;

     @Column(name = "like")
     private float like = 0;

     @Column(name = "sell")
     private int sell = 0;

	public void fromJson(JSONObject jsonObject)  throws JSONException {
	     if(null == jsonObject){
	       return;
	     }

	     this.uid = jsonObject.optString("id", "");
	     this.name = jsonObject.optString("name", "");
	     this.price = (float)jsonObject.optDouble("price", 0);
	     this.singlePrice = (float)jsonObject.optDouble("single_price", 0);
	     this.num = jsonObject.optInt("num", 0);
	     this.like = (float)jsonObject.optDouble("like", 0);
    	 this.sell = jsonObject.optInt("sell", 0);
	     Img img = new Img();
	     img.fromJson(jsonObject.optJSONObject("img"));
	     this.img = img;
	     return;
	 }

	 public JSONObject toJson() throws JSONException {
	     JSONObject localItemObject = new JSONObject();
	     localItemObject.put("id", uid);
	     localItemObject.put("name", name);
	     localItemObject.put("price", price);
	     localItemObject.put("single_price", singlePrice);
	     localItemObject.put("num", num);
	     if(null!=img) {
	       localItemObject.put("img", img.toJson());
	     }
	     localItemObject.put("like", like);
	     localItemObject.put("sell", sell);
	     return localItemObject;
	 }

	public Img getImg() {
		return img;
	}

	public void setImg(Img img) {
		this.img = img;
	}

	public float getLike() {
		return like;
	}

	public void setLike(float like) {
		this.like = like;
	}

	public int getSell() {
		return sell;
	}

	public void setSell(int sell) {
		this.sell = sell;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

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

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float d) {
		this.price = d;
	}

	public float getSinglePrice() {
		return singlePrice;
	}

	public void setSinglePrice(float d) {
		this.singlePrice = d;
	}

	@Override
	public String toString() {
		return "SimpleGoods [uid=" + uid + ", name=" + name + ", num=" + num
				+ ", price=" + price + ", single_price=" + singlePrice
				+ ", img=" + img.toString() + ", like=" + like + ", sell=" + sell + "]";
	}

}


text:
"""
This inline script allows conditional TLS Interception based
on a user-defined strategy.

Example:

    > mitmdump -s tls_passthrough.py

    1. curl --proxy http://localhost:8080 https://example.com --insecure
    // works - we'll also see the contents in mitmproxy

    2. curl --proxy http://localhost:8080 https://example.com --insecure
    // still works - we'll also see the contents in mitmproxy

    3. curl --proxy http://localhost:8080 https://example.com
    // fails with a certificate error, which we will also see in mitmproxy

    4. curl --proxy http://localhost:8080 https://example.com
    // works again, but mitmproxy does not intercept and we do *not* see the contents

Authors: Maximilian Hils, Matthew Tuusberg
"""
from __future__ import (absolute_import, print_function, division)
import collections
import random

from enum import Enum

from libmproxy.exceptions import TlsException
from libmproxy.protocol import TlsLayer, RawTCPLayer

class InterceptionResult(Enum):
    success = True
    failure = False
    skipped = None

class _TlsStrategy(object):
    """
    Abstract base class for interception strategies.
    """
    def __init__(self):
        # A server_address -> interception results mapping
        self.history = collections.defaultdict(lambda: collections.deque(maxlen=200))

    def should_intercept(self, server_address):
        """
        Returns:
            True, if we should attempt to intercept the connection.
            False, if we want to employ pass-through instead.
        """
        raise NotImplementedError()

    def record_success(self, server_address):
        self.history[server_address].append(InterceptionResult.success)

    def record_failure(self, server_address):
        self.history[server_address].append(InterceptionResult.failure)

    def record_skipped(self, server_address):
        self.history[server_address].append(InterceptionResult.skipped)

class ConservativeStrategy(_TlsStrategy):
    """
    Conservative Interception Strategy - only intercept if there haven't been any failed attempts
    in the history.
    """

    def should_intercept(self, server_address):
        if InterceptionResult.failure in self.history[server_address]:
            return False
        return True

class ProbabilisticStrategy(_TlsStrategy):
    """
    Fixed probability that we intercept a given connection.
    """
    def __init__(self, p):
        self.p = p
        super(ProbabilisticStrategy, self).__init__()

    def should_intercept(self, server_address):
        return random.uniform(0, 1) < self.p

class TlsFeedback(TlsLayer):
    """
    Monkey-patch _establish_tls_with_client to get feedback if TLS could be established
    successfully on the client connection (which may fail due to cert pinning).
    """

    def _establish_tls_with_client(self):
        server_address = self.server_conn.address
        tls_strategy = self.script_context.tls_strategy

        try:
            super(TlsFeedback, self)._establish_tls_with_client()
        except TlsException as e:
            tls_strategy.record_failure(server_address)
            raise e
        else:
            tls_strategy.record_success(server_address)

# inline script hooks below.

def start(context, argv):
    if len(argv) == 2:
        context.tls_strategy = ProbabilisticStrategy(float(argv[1]))
    else:
        context.tls_strategy = ConservativeStrategy()

def next_layer(context, next_layer):
    """
    This hook does the actual magic - if the next layer is planned to be a TLS layer,
    we check if we want to enter pass-through mode instead.
    """
    if isinstance(next_layer, TlsLayer) and next_layer._client_tls:
        server_address = next_layer.server_conn.address

        if context.tls_strategy.should_intercept(server_address):
            # We try to intercept.
            # Monkey-Patch the layer to get feedback from the TLSLayer if interception worked.
            next_layer.__class__ = TlsFeedback
            next_layer.script_context = context
        else:
            # We don't intercept - reply with a pass-through layer and add a "skipped" entry.
            context.log("TLS passthrough for %s" % repr(next_layer.server_conn.address), "info")
            next_layer_replacement = RawTCPLayer(next_layer.ctx, logging=False)
            next_layer.reply(next_layer_replacement)
            context.tls_strategy.record_skipped(server_address)


text:
import { ChangeDetectorRef, Component, OnInit } from "@angular/core";
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from "@angular/forms";
import { UserShare, WishList } from "../../models/WishList";
import { LatinizePipe } from "ng-pipes";
import { Subject } from "rxjs";
import { WishItem } from "../../models/WishItem";
import { DemoService } from "../../state/wishes/demo/demo.service";
import { WishesListService } from "../../state/wishes/wishes-list.service";
import { UserQuery } from "../../state/app/user.query";
import { UserState } from "../../state/app/user.store";
import {
  WishListTypeLabel,
  WishListTypeLabelOrder,
  WishListTypePicture
} from "../../models/const";
import { ActivatedRoute, Router } from "@angular/router";
import { UntilDestroy, untilDestroyed } from "@ngneat/until-destroy";
import { debounceTime, filter } from "rxjs/operators";
import { merge } from "rxjs";

import { WishesListQuery } from "../../state/wishes/wishes-list.query";
import { WishQuery } from "../../state/wishes/wish.query";
import * as moment from "moment";

@UntilDestroy()
@Component({
  selector: "app-add-update-list",
  templateUrl: "./add-update-list.component.html",
  styleUrls: ["./add-update-list.component.scss"]
})
export class AddUpdateListComponent implements OnInit {
  isLinear = false;
  nameFormGroup: FormGroup;
  secondFormGroup: FormGroup;
  addUsers = new FormControl([]);
  wishList: WishList = {
    title: "",
    name: "",
    picture: "",
    description: "",
    type: null,
    privacy: "PRIVATE",
    date: 0,
    users: [],
    owners: [],
    forceAnonymous: false
  };
  demoList: WishList;
  wishListLabel = WishListTypeLabel;
  wishListTypeLabelOrder = WishListTypeLabelOrder;
  previewAs: "OWNER" | "REGISTRER" | "PUBLIC" = "OWNER";
  demoWhishs: Subject<WishItem[]> = new Subject<WishItem[]>();
  startDate = moment().month(1);
  public sending: boolean;
  public wishListFormGroup: FormGroup;
  public edit: boolean = false;

  constructor(
    private _formBuilder: FormBuilder,
    private latinize: LatinizePipe,
    private demoService: DemoService,
    private wishListService: WishesListService,
    private wishesListQuery: WishesListQuery,
    private wishQuery: WishQuery,
    private user: UserQuery,
    private router: Router,
    private cd: ChangeDetectorRef,
    private route: ActivatedRoute
  ) {}

  get wishListTypePicture(): any[] {
    return !!this.wishList.type
      ? WishListTypePicture.filter(value => value.type === this.wishList.type)
      : WishListTypePicture;
  }

  ngOnInit() {
    this.wishListFormGroup = this._formBuilder.group({
      title: ["", Validators.required],
      type: [null],
      name: ["", [Validators.required, Validators.pattern("[a-z-_]+")]],
      picture: [""],
      description: [""],
      privacy: ["PRIVATE"],
      users: [{ value: [] }],
      date: [""],
      owners: this._formBuilder.control([]),
      forceAnonymous: [false]
    });

    this.wishListFormGroup.setValue(this.wishList);

    if (this.wishesListQuery.hasActive()) {
      this.edit = true;

      this.wishesListQuery
        .selectActive()
        .pipe(untilDestroyed(this))
        .subscribe((wishlist: WishList) => {
          this.wishListFormGroup.patchValue(wishlist);
          this.onChanges(wishlist);
          this.cd.markForCheck();
        });

      this.wishListFormGroup.get("users").setValue(this.wishList.users || []);
    } else {
      this.edit = false;

      const owner = this.getOwner();
      if (owner) {
        const users: any[] = [
          ...this.wishListFormGroup.get("users").value,
          owner
        ];
        this.wishListFormGroup.get("users").setValue(users);
      }

      this.wishListFormGroup.setValue(this.wishList);

      const subscribeTitle = this.wishListFormGroup
        .get("title")
        .valueChanges.pipe(
          untilDestroyed(this)
          /*takeUntil(
            this.wishListFormGroup.get(  "name").
              .pipe(filter(value => value === true))
          ) // if field name was changed, do not compute name*/
        )
        .subscribe(value => {
          if (this.wishListFormGroup.get("name").untouched) {
            this.changeName(value);
          } else {
            subscribeTitle.unsubscribe();
          }
        });
    }

    if (!this.edit) {
      this.user
        .select()
        .pipe(untilDestroyed(this))
        .subscribe((userInfo: UserState) => {
          if (userInfo.user) {
            const owner = {
              email: userInfo.user.email,
              name: userInfo.user.displayName,
              type: "OWNER"
            };
            const users: any[] = [
              ...this.wishListFormGroup.controls.users.value,
              owner
            ];
            this.wishListFormGroup.controls.users.setValue(users);
          }
        });
    }

    this.wishListFormGroup
      .get("users")
      .valueChanges.pipe(untilDestroyed(this))
      .subscribe((changes: UserShare[]) => {
        const wishlist: Partial<WishList> = {};
        wishlist.owners = changes.filter(user => user.type === "OWNER");

        this.wishListFormGroup.patchValue(wishlist);
      });

    merge(
      this.wishListFormGroup.get("privacy").valueChanges,
      this.wishListFormGroup.get("forceAnonymous").valueChanges
    )
      .pipe(untilDestroyed(this))
      .subscribe(value => this.changesdemoWish());

    this.wishListFormGroup.valueChanges
      .pipe(untilDestroyed(this), debounceTime(500))
      .subscribe(value => this.onChanges(value));

    this.changesdemoWish();

    this.route.queryParams
      .pipe(filter(params => !!params.name))
      .subscribe(params => {
        this.wishListFormGroup.get("title").setValue(params.name);
        this.wishListFormGroup
          .get("name")
          .setValue(this.formatUrlName(params.name));
      });
  }

  changeName(name) {
    if (name && this.wishListFormGroup.controls.name.untouched) {
      this.wishListFormGroup.controls.name.setValue(this.formatUrlName(name));
    }
  }

  public onChanges(wishList) {
    this.wishList = wishList;
    this.demoList = { ...this.wishList };
  }

  public onChangePreview($event) {
    this.previewAs = $event.value;
    this.changesdemoWish();
  }

  selectImg(picture: any) {
    this.wishListFormGroup.controls.picture.setValue(picture.picture);
  }

  createorUpdateList() {
    this.sending = true;
    const rawValue: WishList = this.wishListFormGroup.getRawValue();

    if (rawValue.users.length === 0) {
      const owner = this.getOwner();
      rawValue.users = [owner];
    }

    rawValue.owners = rawValue.users.filter(
      userShare => userShare.type === "OWNER"
    );

    this.wishListService.createOrReplace(rawValue).subscribe(newList => {
      this.sending = false;
      this.router.navigate(["/", newList.name]);
    });
  }

  private getOwner() {
    const userState = this.user.getValue();

    if (userState.user) {
      return {
        email: userState.user.email,
        name: userState.user.displayName,
        type: "OWNER"
      };
    }
    return null;
  }

  private formatUrlName(name) {
    return this.latinize.transform(
      name.toLowerCase().trim().replace(/ /g, "_")
    );
  }

  private changesdemoWish() {
    const wishlist = this.wishListFormGroup.getRawValue();
    this.demoService.update(
      this.demoService.getWishForPrivacy(
        wishlist.privacy,
        this.previewAs,
        wishlist.forceAnonymous
      )
    );
  }
}


text:
import wx

# begin wxGlade: extracode
from external import transfer_function_widget
reload(transfer_function_widget)
TransferFunctionWidget = transfer_function_widget.TransferFunctionWidget

from external import transfer_function_widget
reload(transfer_function_widget)
TransferFunctionWidget = transfer_function_widget.TransferFunctionWidget

# end wxGlade

class TFEditorFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: TFEditorFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.view_frame_panel = wx.Panel(self, -1)
        self.sizer_6_staticbox = wx.StaticBox(self.view_frame_panel, -1, "Built-in presets")
        self.sizer_11_staticbox = wx.StaticBox(self.view_frame_panel, -1, "Saving, Loading")
        self.sizer_8_staticbox = wx.StaticBox(self.view_frame_panel, -1, "Edit Transfer Function")
        self.tf_widget = TransferFunctionWidget(self.view_frame_panel, -1)
        self.label_4 = wx.StaticText(self.view_frame_panel, -1, "Selected vertex Scalar:")
        self.cur_scalar_text = wx.TextCtrl(self.view_frame_panel, -1, "")
        self.colour_button = wx.Button(self.view_frame_panel, -1, "Colour:")
        self.cur_col_text = wx.TextCtrl(self.view_frame_panel, -1, "")
        self.label_5 = wx.StaticText(self.view_frame_panel, -1, "Opacity:")
        self.cur_opacity_text = wx.TextCtrl(self.view_frame_panel, -1, "")
        self.delete_button = wx.Button(self.view_frame_panel, -1, "Delete")
        self.auto_range_button = wx.Button(self.view_frame_panel, -1, "Get input range")
        self.label_1 = wx.StaticText(self.view_frame_panel, -1, "Scalar MIN")
        self.scalar_min_text = wx.TextCtrl(self.view_frame_panel, -1, "")
        self.label_2 = wx.StaticText(self.view_frame_panel, -1, "MAX")
        self.scalar_max_text = wx.TextCtrl(self.view_frame_panel, -1, "")
        self.apply_range_button = wx.Button(self.view_frame_panel, -1, "Apply Range")
        self.label_3 = wx.StaticText(self.view_frame_panel, -1, "Preset:")
        self.preset_choice = wx.Choice(self.view_frame_panel, -1, choices=["Dummy"])
        self.load_preset_button = wx.Button(self.view_frame_panel, -1, "Load preset")
        self.file_load_button = wx.Button(self.view_frame_panel, -1, "Load from file")
        self.file_save_button = wx.Button(self.view_frame_panel, -1, "Save to file")

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: TFEditorFrame.__set_properties
        self.SetTitle("frame_2")
        self.cur_scalar_text.SetMinSize((50, -1))
        self.colour_button.SetBackgroundColour(wx.Colour(0, 127, 255))
        self.colour_button.SetToolTipString("Change colour of currently selected transfer function vertex.")
        self.cur_col_text.SetMinSize((75, -1))
        self.cur_opacity_text.SetMinSize((50, -1))
        self.delete_button.SetToolTipString("Delete the currently selected vertex.")
        self.auto_range_button.SetToolTipString("Determine scalar range from input data.  Input data has to be up to date.")
        self.apply_range_button.SetToolTipString("Apply the entered scalar range to the transfer function.")
        self.preset_choice.SetSelection(0)
        self.load_preset_button.SetToolTipString("Load the selected preset.")
        self.file_load_button.SetToolTipString("Load a DVTF file.")
        self.file_save_button.SetToolTipString("Save current transfer function to a DVTF file.")
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: TFEditorFrame.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_3 = wx.BoxSizer(wx.VERTICAL)
        sizer_10 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_11 = wx.StaticBoxSizer(self.sizer_11_staticbox, wx.HORIZONTAL)
        sizer_12 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_6 = wx.StaticBoxSizer(self.sizer_6_staticbox, wx.HORIZONTAL)
        sizer_13 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_8 = wx.StaticBoxSizer(self.sizer_8_staticbox, wx.VERTICAL)
        sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_7 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_4.Add(self.tf_widget, 1, wx.EXPAND, 0)
        sizer_4.Add((0, 200), 0, 0, 0)
        sizer_8.Add(sizer_4, 1, wx.ALL|wx.EXPAND, 7)
        sizer_7.Add(self.label_4, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4)
        sizer_7.Add(self.cur_scalar_text, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 7)
        sizer_7.Add(self.colour_button, 0, wx.RIGHT, 4)
        sizer_7.Add(self.cur_col_text, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 7)
        sizer_7.Add(self.label_5, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4)
        sizer_7.Add(self.cur_opacity_text, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 7)
        sizer_7.Add(self.delete_button, 0, 0, 0)
        sizer_8.Add(sizer_7, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 7)
        sizer_5.Add(self.auto_range_button, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 7)
        sizer_5.Add(self.label_1, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 3)
        sizer_5.Add(self.scalar_min_text, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4)
        sizer_5.Add(self.label_2, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 3)
        sizer_5.Add(self.scalar_max_text, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 7)
        sizer_5.Add(self.apply_range_button, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_8.Add(sizer_5, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 7)
        sizer_3.Add(sizer_8, 1, wx.BOTTOM|wx.EXPAND, 7)
        sizer_3.Add((400, 0), 0, 0, 0)
        sizer_13.Add(self.label_3, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4)
        sizer_13.Add(self.preset_choice, 1, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 7)
        sizer_13.Add(self.load_preset_button, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_6.Add(sizer_13, 1, wx.ALL|wx.EXPAND, 7)
        sizer_10.Add(sizer_6, 1, wx.RIGHT, 7)
        sizer_12.Add(self.file_load_button, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4)
        sizer_12.Add(self.file_save_button, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_11.Add(sizer_12, 1, wx.ALL|wx.EXPAND, 7)
        sizer_10.Add(sizer_11, 0, 0, 7)
        sizer_3.Add(sizer_10, 0, wx.EXPAND, 0)
        sizer_2.Add(sizer_3, 1, wx.ALL|wx.EXPAND, 7)
        self.view_frame_panel.SetSizer(sizer_2)
        sizer_1.Add(self.view_frame_panel, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        # end wxGlade

# end of class TFEditorFrame

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame = TFEditorFrame(None, -1, "")
    app.SetTopWindow(frame)
    frame.Show()
    app.MainLoop()


text:
<idea-plugin>

  <id>com.intellij</id>
  <resource-bundle>bundle</resource-bundle>
  <resource-bundle><error descr="Cannot resolve property bundle">INVALID_VALUE</error></resource-bundle>

  <extensionPoints>
    <extensionPoint name="localInspection"
                    beanClass="com.intellij.codeInspection.LocalInspectionEP"/>
  </extensionPoints>

  <extensions defaultExtensionNs="com.intellij">
    <<warning descr="groupName or groupKey should be specified">localInspection</warning> key="<error descr="Cannot resolve property key">INVALID_VALUE</error>"/>
    <<warning descr="groupName or groupKey should be specified">localInspection</warning> key="foo"/>
    <<warning descr="displayName or key should be specified">localInspection</warning> groupKey="foo"/>
    <<warning descr="groupName or groupKey should be specified">localInspection</warning> key="foo" groupBundle="bundle"/>

    <<warning descr="groupName or groupKey should be specified">localInspection</warning> key="foo" bundle="bundle"/>
    <<warning descr="displayName or key should be specified">localInspection</warning> groupKey="foo" bundle="bundle"/>

    <localInspection key="foo" bundle="bundle" groupName="groupName"/>
    <localInspection groupKey="foo" bundle="bundle" displayName="displayName"/>

  </extensions>
</idea-plugin>


text:
<?php

namespace Magento\Catalog\Ui\DataProvider\Product;

use Magento\Framework\Data\Collection;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\DataProvider\AddFilterToCollectionInterface;

class AddStoreFieldToCollection implements AddFilterToCollectionInterface
{
    /**
     * Store manager
     *
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * Construct
     *
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(StoreManagerInterface $storeManager)
    {
        $this->storeManager = $storeManager;
    }

    /**
     * {@inheritdoc}
     */
    public function addFilter(Collection $collection, $field, $condition = null)
    {
        if (isset($condition['eq']) && $condition['eq']) {
            /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection  */
            $collection->addStoreFilter($this->storeManager->getStore($condition['eq']));
        }
    }
}


text:
type ESLintReport = {
  node: any,
  message: string,
};

type ESLintContext = {
  report: (ESLintReport) => void,
};


text:
pub mod callback;

#[path = "../../src/utils/environment.rs"]
pub mod environment;

pub mod pool;
pub mod wallet;
pub mod anoncreds;

#[macro_use]
#[path = "../../src/utils/test.rs"]
pub mod test;

#[macro_use]
#[path = "../../src/utils/logger.rs"]
pub mod logger;

pub mod timeout;


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <block class="Magento\Sales\Block\Adminhtml\Order\Creditmemo\View\Comments" name="creditmemo_comments">
            <block class="Magento\Sales\Block\Adminhtml\Order\Comments\View" name="order_comments" template="order/comments/view.phtml"/>
        </block>
    </body>
</page>


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Yingdi Yu <yingdi@cs.ucla.edu>
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#include "simple-visitor.hpp"
#include "../der.hpp"
#include <ndn-cpp/encoding/oid.hpp>

using namespace std;

namespace ndn {

namespace der
{

ndnboost::any
SimpleVisitor::visit(DerBool& derBool)
{
  bool result = true;

  if(0 == derBool.getPayload()[0])
    result = false;

  return ndnboost::any(result);
}

ndnboost::any
SimpleVisitor::visit(DerInteger& derInteger)
{
  return ndnboost::any(derInteger.getPayload());
}

ndnboost::any
SimpleVisitor::visit(DerPrintableString& derPStr)
{
  return ndnboost::any(string((const char*)&derPStr.getPayload()[0], derPStr.getPayload().size()));
}

ndnboost::any
SimpleVisitor::visit(DerBitString& derBStr)
{
  return ndnboost::any(derBStr.getPayload());
}

ndnboost::any
SimpleVisitor::visit(DerNull& derNull)
{
  return ndnboost::any();
}

ndnboost::any
SimpleVisitor::visit(DerOctetString& derOStr)
{
  vector<uint8_t> result(derOStr.getPayload());
  return ndnboost::any(result);
}

ndnboost::any
SimpleVisitor::visit(DerOid& derOid)
{
  vector<int> intList;
  int offset = 0;

  vector<uint8_t>& blob = derOid.getPayload();

  int first = blob[offset];

  intList.push_back(first / 40);
  intList.push_back(first % 40);

  offset++;

  while(offset < blob.size()){
    intList.push_back(derOid.decode128(offset));
  }

  return ndnboost::any(OID(intList));
}

ndnboost::any
SimpleVisitor::visit(DerSequence& derSeq)
{
  return ndnboost::any();
}

ndnboost::any
SimpleVisitor::visit(DerGtime& derGtime)
{
  string str((const char*)&derGtime.getPayload()[0], derGtime.getPayload().size());
  return ndnboost::any(DerGtime::fromIsoString(str.substr(0, 8) + "T" + str.substr(8, 6)));
}

} // der

}


text:
package com.hazelcast.internal.serialization.impl;

import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.nio.Bits;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.serialization.SerializationService;

import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;

import static com.hazelcast.nio.Bits.NULL_ARRAY_LENGTH;

@SuppressWarnings("checkstyle:methodcount")
public class ObjectDataOutputStream extends VersionedObjectDataOutput implements ObjectDataOutput, Closeable {

    private final InternalSerializationService serializationService;
    private final DataOutputStream dataOut;
    private final ByteOrder byteOrder;

    public ObjectDataOutputStream(OutputStream outputStream, InternalSerializationService serializationService) {
        this.serializationService = serializationService;
        this.dataOut = new DataOutputStream(outputStream);
        this.byteOrder = serializationService.getByteOrder();
    }

    @Override
    public void write(int b) throws IOException {
        dataOut.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        dataOut.write(b, off, len);
    }

    @Override
    public void writeBoolean(boolean v) throws IOException {
        dataOut.writeBoolean(v);
    }

    @Override
    public void writeByte(int v) throws IOException {
        dataOut.writeByte(v);
    }

    @Override
    public void writeShort(int v) throws IOException {
        if (bigEndian()) {
            dataOut.writeShort(v);
        } else {
            dataOut.writeShort(Short.reverseBytes((short) v));
        }
    }

    @Override
    public void writeChar(int v) throws IOException {
        if (bigEndian()) {
            dataOut.writeChar(v);
        } else {
            dataOut.writeChar(Character.reverseBytes((char) v));
        }
    }

    @Override
    public void writeInt(int v) throws IOException {
        if (bigEndian()) {
            dataOut.writeInt(v);
        } else {
            dataOut.writeInt(Integer.reverseBytes(v));
        }
    }

    @Override
    public void writeLong(long v) throws IOException {
        if (bigEndian()) {
            dataOut.writeLong(v);
        } else {
            dataOut.writeLong(Long.reverseBytes(v));
        }
    }

    @Override
    public void writeFloat(float v) throws IOException {
        if (bigEndian()) {
            dataOut.writeFloat(v);
        } else {
            writeInt(Float.floatToIntBits(v));
        }
    }

    @Override
    public void writeDouble(double v) throws IOException {
        if (bigEndian()) {
            dataOut.writeDouble(v);
        } else {
            writeLong(Double.doubleToLongBits(v));
        }
    }

    @Override
    public void writeBytes(String s) throws IOException {
        dataOut.writeBytes(s);
    }

    @Override
    public void writeChars(String s) throws IOException {
        int len = s.length();
        for (int i = 0; i < len; i++) {
            int v = s.charAt(i);
            writeChar(v);
        }
    }

    @Override
    public void writeByteArray(byte[] bytes) throws IOException {
        int len = (bytes != null) ? bytes.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            write(bytes);
        }
    }

    @Override
    public void writeBooleanArray(boolean[] booleans) throws IOException {
        int len = booleans != null ? booleans.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (boolean c : booleans) {
                writeBoolean(c);
            }
        }

    }

    @Override
    public void writeCharArray(char[] chars) throws IOException {
        int len = chars != null ? chars.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (char c : chars) {
                writeChar(c);
            }
        }
    }

    @Override
    public void writeIntArray(int[] ints) throws IOException {
        int len = ints != null ? ints.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (int i : ints) {
                writeInt(i);
            }
        }
    }

    @Override
    public void writeLongArray(long[] longs) throws IOException {
        int len = longs != null ? longs.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (long l : longs) {
                writeLong(l);
            }
        }
    }

    @Override
    public void writeDoubleArray(double[] doubles) throws IOException {
        int len = doubles != null ? doubles.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (double d : doubles) {
                writeDouble(d);
            }
        }
    }

    @Override
    public void writeFloatArray(float[] floats) throws IOException {
        int len = floats != null ? floats.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (float f : floats) {
                writeFloat(f);
            }
        }
    }

    @Override
    public void writeShortArray(short[] shorts) throws IOException {
        int len = shorts != null ? shorts.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (short s : shorts) {
                writeShort(s);
            }
        }
    }

    @Override
    public void writeUTFArray(String[] strings) throws IOException {
        int len = strings != null ? strings.length : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            for (String s : strings) {
                writeUTF(s);
            }
        }
    }

    @Override
    public void writeUTF(String str) throws IOException {
        int len = str != null ? str.length() : NULL_ARRAY_LENGTH;
        writeInt(len);
        if (len > 0) {
            final byte[] buffer = new byte[3];
            for (int i = 0; i < len; i++) {
                int count = Bits.writeUtf8Char(buffer, 0, str.charAt(i));
                dataOut.write(buffer, 0, count);
            }
        }
    }

    @Override
    public void write(byte[] b) throws IOException {
        dataOut.write(b);
    }

    @Override
    public void writeObject(Object object) throws IOException {
        serializationService.writeObject(this, object);
    }

    @Override
    public void writeData(Data data) throws IOException {
        byte[] payload = data != null ? data.toByteArray() : null;
        writeByteArray(payload);
    }

    @Override
    public byte[] toByteArray() {
        return toByteArray(0);
    }

    @Override
    public byte[] toByteArray(int padding) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void flush() throws IOException {
        dataOut.flush();
    }

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

    @Override
    public ByteOrder getByteOrder() {
        return byteOrder;
    }

    @Override
    public SerializationService getSerializationService() {
        return serializationService;
    }

    private boolean bigEndian() {
        return byteOrder == ByteOrder.BIG_ENDIAN;
    }
}


text:
Sora
====

Sora is a hypothetical synth, which follows the ethics of the AI Now project.


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Debugger](./puppeteer.protocol.debugger.md) > [BreakLocation](./puppeteer.protocol.debugger.breaklocation.md) > [scriptId](./puppeteer.protocol.debugger.breaklocation.scriptid.md)

## Protocol.Debugger.BreakLocation.scriptId property

Script identifier as reported in the `Debugger.scriptParsed`<!-- -->.

<b>Signature:</b>

```typescript
scriptId: Runtime.ScriptId;
```


text:
<?php

declare(strict_types=1);

namespace GrumPHP\Task;

use GrumPHP\Exception\RuntimeException;
use GrumPHP\Runner\TaskResult;
use GrumPHP\Runner\TaskResultInterface;
use GrumPHP\Task\Context\ContextInterface;
use GrumPHP\Task\Context\GitPreCommitContext;
use GrumPHP\Task\Context\RunContext;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @property \GrumPHP\Linter\Json\JsonLinter $linter
 */
class JsonLint extends AbstractLinterTask
{
    public function getName(): string
    {
        return 'jsonlint';
    }

    public function getConfigurableOptions(): OptionsResolver
    {
        $resolver = parent::getConfigurableOptions();
        $resolver->setDefaults([
            'detect_key_conflicts' => false,
        ]);

        $resolver->addAllowedTypes('detect_key_conflicts', ['bool']);

        return $resolver;
    }

    /**
     * {@inheritdoc}
     */
    public function canRunInContext(ContextInterface $context): bool
    {
        return $context instanceof GitPreCommitContext || $context instanceof RunContext;
    }

    /**
     * {@inheritdoc}
     */
    public function run(ContextInterface $context): TaskResultInterface
    {
        $files = $context->getFiles()->name('*.json');
        if (0 === \count($files)) {
            return TaskResult::createSkipped($this, $context);
        }

        $config = $this->getConfiguration();
        $this->linter->setDetectKeyConflicts($config['detect_key_conflicts']);

        try {
            $lintErrors = $this->lint($files);
        } catch (RuntimeException $e) {
            return TaskResult::createFailed($this, $context, $e->getMessage());
        }

        if ($lintErrors->count()) {
            return TaskResult::createFailed($this, $context, (string) $lintErrors);
        }

        return TaskResult::createPassed($this, $context);
    }
}


text:
'use strict';

describe("Song overview specs:", function () {
    var $compile,
        scope,
        template;

    beforeEach(module('thumbnailModule'));

    beforeEach(inject(function (_$compile_, _$rootScope_, $templateCache) {
        $compile = _$compile_;
        scope = _$rootScope_.$new();
        template = $templateCache;
    }));

    describe("When the directive is loaded,", function () {
        it("then should replace the element with the appropriate content", function () {
            scope.overview = {
                id: 1,
                singers: "singer",
                poet: "poet",
                englishTranslation: "englishTranslation",
                audioId: "audioId",
                videoId: "videoId",
                englishTransliteration: "englishTransliteration",
                noun: "noun",
                words: "words"
            };
            var songOverviewDirective = '<song-overview id="{{overview.id}}" singers="overview.singers" poet="overview.poet" english-translation="{{overview.englishTranslation}}" audio-Url="{{overview.audioId}}" video-Url="{{overview.videoId}}" english-transliteration="{{overview.englishTransliteration}}" noun="{{overview.noun}}" words="overview.words"></song-overview>';
            template.put('/user/js/common/templates/songs/songOverview.html', '{{id}} {{singers}} {{poet}} {{englishTranslation}} {{audioUrl}} {{videoUrl}} {{englishTransliteration}} {{noun}} {{words}}');

            var element = $compile(songOverviewDirective)(scope);
            scope.$apply();

            expect(element.html()).toBe('1 singer poet englishTranslation audioId videoId englishTransliteration noun words');
        });
    });
});


text:
package com.madhusudhan.java7.coin.trycatch;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class AutoCloseableTryCatch {

  private static final String JAVA_7_BLOCK_BUSTER = "Java 7 Block Buster";

  private static final String FILENAME = "files/movies.txt";

  private static final String WRITTEN = "The " + AutoCloseableTryCatch.FILENAME + " written.";

  FileOutputStream fos = null;

  DataOutputStream dos = null;

  public void oldTry() {
    try {
      fos = new FileOutputStream(AutoCloseableTryCatch.FILENAME);
      dos = new DataOutputStream(fos);
      dos.writeUTF(AutoCloseableTryCatch.JAVA_7_BLOCK_BUSTER);
      System.out.println(AutoCloseableTryCatch.WRITTEN);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        fos.close();
        dos.close();
      } catch (IOException e) {
        // log the exception
      }
    }
  }

  public void newTry() {

    try (FileOutputStream fos = new FileOutputStream(AutoCloseableTryCatch.FILENAME);
        DataOutputStream dos = new DataOutputStream(fos)) {
      dos.writeUTF(AutoCloseableTryCatch.JAVA_7_BLOCK_BUSTER);
      System.out.println(AutoCloseableTryCatch.WRITTEN);
    } catch (IOException e) {
      // log the exception
    }
  }

  public static void main(String[] args) {
    AutoCloseableTryCatch actc = new AutoCloseableTryCatch();
    actc.oldTry();
    actc.newTry();
  }
}


text:
package nl.minvenj.nfi.storm.kafka.fail;

import nl.minvenj.nfi.storm.kafka.util.KafkaMessageId;

/**
 * {@link FailHandler} implementation making tuple failure reliable: messages are always replayed, calls to
 * {@link #fail(KafkaMessageId, byte[])} will cause an error.
 *
 * @author Netherlands Forensics Institute
 */
public class ReliableFailHandler extends AbstractFailHandler {
    /**
     * Configuration identifier for the reliable failure policy ({@code "reliable"}).
     */
    public static final String IDENTIFIER = "reliable";

    @Override
    public boolean shouldReplay(final KafkaMessageId id) {
        // always replay the message, never call fail
        return true;
    }

    /**
     * {@inheritDoc}
     *
     * @throws IllegalStateException always; tuples should always replayed using reliable policy.
     */
    @Override
    public void fail(final KafkaMessageId id, final byte[] message) {
        throw new IllegalStateException("reliable failure policy unexpectedly made to deal with message failure");
    }

    @Override
    public String getIdentifier() {
        return IDENTIFIER;
    }
}


text:
Paged UIScrollView with an embedded UIPageControl.

<img src="https://github.com/romaonthego/REPagedScrollView/raw/master/Screenshot.png" alt="REPagedScrollView Screenshot" width="320" height="480" />

## Requirements
* Xcode 4.5 or higher
* Apple LLVM compiler
* iOS 5.0 or higher
* ARC

## Demo

Build and run the `REPagedScrollViewExample` project in Xcode to see `REPagedScrollView` in action.

## Installation

### CocoaPods

The recommended approach for installating `REPagedScrollView` is via the [CocoaPods](http://cocoapods.org/) package manager, as it provides flexible dependency management and dead simple installation.
For best results, it is recommended that you install via CocoaPods >= **0.15.2** using Git >= **1.8.0** installed via Homebrew.

Install CocoaPods if not already available:

``` bash
$ [sudo] gem install cocoapods
$ pod setup
```

Change to the directory of your Xcode project:

``` bash
$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
```

Edit your Podfile and add REPagedScrollView:

``` bash
platform :ios, '5.0'
pod 'REPagedScrollView', '~> 1.0'
```

Install into your Xcode project:

``` bash
$ pod install
```

Open your project in Xcode from the .xcworkspace file (not the usual project file)

``` bash
$ open MyProject.xcworkspace
```

Please note that if your installation fails, it may be because you are installing with a version of Git lower than CocoaPods is expecting. Please ensure that you are running Git >= **1.8.0** by executing `git --version`. You can get a full picture of the installation details by executing `pod install --verbose`.

### Manual Install

All you need to do is drop `REPagedScrollView` files into your project, and add `#include "REPagedScrollView.h"` to the top of classes that will use it.

## Example Usage

``` objective-c
REPagedScrollView *scrollView = [[REPagedScrollView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:scrollView];

UIView *page1 = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, self.view.frame.size.height - 40)];
page1.backgroundColor = [UIColor lightGrayColor];
[scrollView addPage:page1];

UIView *page2 = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, self.view.frame.size.height - 40)];
page2.backgroundColor = [UIColor blueColor];
[scrollView addPage:page2];
```

## Contact

Roman Efimov

- https://github.com/romaonthego
- https://twitter.com/romaonthego
- romefimov@gmail.com

## License

REPagedScrollView is available under the MIT license.

Copyright © 2013 Roman Efimov.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
namespace milkcat {

class WritableFile {
 public:
  // Open a file for write. On success, return an instance of WritableFile.
  // On failed, set status != Status::OK()
  static WritableFile *New(const char *path, Status *status);
  ~WritableFile();

  // Writes a line to file
  void WriteLine(const char *line, Status *status);

  // Writes data to file
  void Write(const void *data, int size, Status *status);

  // Write an type T to file
  template<typename T>
  void WriteValue(const T &data, Status *status) {
    Write(&data, sizeof(data), status);
  }

 private:
  FILE *fd_;
  std::string file_path_;

  WritableFile();
};

}  // namespace milkcat

#endif  // SRC_UTILS_WRITABLE_FILE_H_


text:
'use strict';

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

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _express = require('express');

var _express2 = _interopRequireDefault(_express);

var _cors = require('cors');

var _cors2 = _interopRequireDefault(_cors);

var _bodyParser = require('body-parser');

var _bodyParser2 = _interopRequireDefault(_bodyParser);

var _socket = require('socket.io');

var _socket2 = _interopRequireDefault(_socket);

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

function getApp() {
    var app = (0, _express2.default)();
    app.use(_bodyParser2.default.json());
    app.use((0, _cors2.default)());

    var server = _http2.default.Server(app);
    var io = (0, _socket2.default)(server);
    return { app: app, server: server, io: io };
}


text:
#include "bytecode/bytecode.h"
#include "bytecode/opcodes.h"
#include "select/propset.h"
#include "select/propget.h"
#include "utils/utils.h"

#include "select/properties/properties.h"
#include "select/properties/helpers.h"

css_error css__cascade_border_left_color(uint32_t opv, css_style *style,
		css_select_state *state)
{
	return css__cascade_bg_border_color(opv, style, state,
			set_border_left_color);
}

css_error css__set_border_left_color_from_hint(const css_hint *hint,
		css_computed_style *style)
{
	return set_border_left_color(style, hint->status, hint->data.color);
}

css_error css__initial_border_left_color(css_select_state *state)
{
	return set_border_left_color(state->computed,
			CSS_BORDER_COLOR_CURRENT_COLOR, 0);
}

css_error css__compose_border_left_color(const css_computed_style *parent,
		const css_computed_style *child,
		css_computed_style *result)
{
	css_color color;
	uint8_t type = get_border_left_color(child, &color);

	if (type == CSS_BORDER_COLOR_INHERIT) {
		type = get_border_left_color(parent, &color);
	}

	return set_border_left_color(result, type, color);
}


text:
/*
 * builtin-diff.c
 *
 * Builtin diff command: Analyze two perf.data input files, look up and read
 * DSOs and symbol information, sort them and produce a diff.
 */
#include "builtin.h"

#include "util/debug.h"
#include "util/event.h"
#include "util/hist.h"
#include "util/session.h"
#include "util/sort.h"
#include "util/symbol.h"
#include "util/util.h"

#include <stdlib.h>

static char const *input_old = "perf.data.old",
		  *input_new = "perf.data";
static char	  diff__default_sort_order[] = "dso,symbol";
static bool  force;
static bool show_displacement;

static int hists__add_entry(struct hists *self,
			    struct addr_location *al, u64 period)
{
	if (__hists__add_entry(self, al, NULL, period) != NULL)
		return 0;
	return -ENOMEM;
}

static int diff__process_sample_event(union perf_event *event,
				      struct perf_sample *sample,
				      struct perf_evsel *evsel __used,
				      struct perf_session *session)
{
	struct addr_location al;

	if (perf_event__preprocess_sample(event, session, &al, sample, NULL) < 0) {
		pr_warning("problem processing %d event, skipping it.\n",
			   event->header.type);
		return -1;
	}

	if (al.filtered || al.sym == NULL)
		return 0;

	if (hists__add_entry(&session->hists, &al, sample->period)) {
		pr_warning("problem incrementing symbol period, skipping event\n");
		return -1;
	}

	session->hists.stats.total_period += sample->period;
	return 0;
}

static struct perf_event_ops event_ops = {
	.sample	= diff__process_sample_event,
	.mmap	= perf_event__process_mmap,
	.comm	= perf_event__process_comm,
	.exit	= perf_event__process_task,
	.fork	= perf_event__process_task,
	.lost	= perf_event__process_lost,
	.ordered_samples = true,
	.ordering_requires_timestamps = true,
};

static void perf_session__insert_hist_entry_by_name(struct rb_root *root,
						    struct hist_entry *he)
{
	struct rb_node **p = &root->rb_node;
	struct rb_node *parent = NULL;
	struct hist_entry *iter;

	while (*p != NULL) {
		parent = *p;
		iter = rb_entry(parent, struct hist_entry, rb_node);
		if (hist_entry__cmp(he, iter) < 0)
			p = &(*p)->rb_left;
		else
			p = &(*p)->rb_right;
	}

	rb_link_node(&he->rb_node, parent, p);
	rb_insert_color(&he->rb_node, root);
}

static void hists__resort_entries(struct hists *self)
{
	unsigned long position = 1;
	struct rb_root tmp = RB_ROOT;
	struct rb_node *next = rb_first(&self->entries);

	while (next != NULL) {
		struct hist_entry *n = rb_entry(next, struct hist_entry, rb_node);

		next = rb_next(&n->rb_node);
		rb_erase(&n->rb_node, &self->entries);
		n->position = position++;
		perf_session__insert_hist_entry_by_name(&tmp, n);
	}

	self->entries = tmp;
}

static void hists__set_positions(struct hists *self)
{
	hists__output_resort(self);
	hists__resort_entries(self);
}

static struct hist_entry *hists__find_entry(struct hists *self,
					    struct hist_entry *he)
{
	struct rb_node *n = self->entries.rb_node;

	while (n) {
		struct hist_entry *iter = rb_entry(n, struct hist_entry, rb_node);
		int64_t cmp = hist_entry__cmp(he, iter);

		if (cmp < 0)
			n = n->rb_left;
		else if (cmp > 0)
			n = n->rb_right;
		else
			return iter;
	}

	return NULL;
}

static void hists__match(struct hists *older, struct hists *newer)
{
	struct rb_node *nd;

	for (nd = rb_first(&newer->entries); nd; nd = rb_next(nd)) {
		struct hist_entry *pos = rb_entry(nd, struct hist_entry, rb_node);
		pos->pair = hists__find_entry(older, pos);
	}
}

static int __cmd_diff(void)
{
	int ret, i;
	struct perf_session *session[2];

	session[0] = perf_session__new(input_old, O_RDONLY, force, false, &event_ops);
	session[1] = perf_session__new(input_new, O_RDONLY, force, false, &event_ops);
	if (session[0] == NULL || session[1] == NULL)
		return -ENOMEM;

	for (i = 0; i < 2; ++i) {
		ret = perf_session__process_events(session[i], &event_ops);
		if (ret)
			goto out_delete;
	}

	hists__output_resort(&session[1]->hists);
	if (show_displacement)
		hists__set_positions(&session[0]->hists);

	hists__match(&session[0]->hists, &session[1]->hists);
	hists__fprintf(&session[1]->hists, &session[0]->hists,
		       show_displacement, true, 0, 0, stdout);
out_delete:
	for (i = 0; i < 2; ++i)
		perf_session__delete(session[i]);
	return ret;
}

static const char * const diff_usage[] = {
	"perf diff [<options>] [old_file] [new_file]",
	NULL,
};

static const struct option options[] = {
	OPT_INCR('v', "verbose", &verbose,
		    "be more verbose (show symbol address, etc)"),
	OPT_BOOLEAN('M', "displacement", &show_displacement,
		    "Show position displacement relative to baseline"),
	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
		    "dump raw trace in ASCII"),
	OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
	OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
		    "load module symbols - WARNING: use only with -k and LIVE kernel"),
	OPT_STRING('d', "dsos", &symbol_conf.dso_list_str, "dso[,dso...]",
		   "only consider symbols in these dsos"),
	OPT_STRING('C', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
		   "only consider symbols in these comms"),
	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
		   "only consider these symbols"),
	OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
		   "sort by key(s): pid, comm, dso, symbol, parent"),
	OPT_STRING('t', "field-separator", &symbol_conf.field_sep, "separator",
		   "separator for columns, no spaces will be added between "
		   "columns '.' is reserved."),
	OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
		    "Look for files with symbols relative to this directory"),
	OPT_END()
};

int cmd_diff(int argc, const char **argv, const char *prefix __used)
{
	sort_order = diff__default_sort_order;
	argc = parse_options(argc, argv, options, diff_usage, 0);
	if (argc) {
		if (argc > 2)
			usage_with_options(diff_usage, options);
		if (argc == 2) {
			input_old = argv[0];
			input_new = argv[1];
		} else
			input_new = argv[0];
	} else if (symbol_conf.default_guest_vmlinux_name ||
		   symbol_conf.default_guest_kallsyms) {
		input_old = "perf.data.host";
		input_new = "perf.data.guest";
	}

	symbol_conf.exclude_other = false;
	if (symbol__init() < 0)
		return -1;

	setup_sorting(diff_usage, options);
	setup_pager();

	sort_entry__setup_elide(&sort_dso, symbol_conf.dso_list, "dso", NULL);
	sort_entry__setup_elide(&sort_comm, symbol_conf.comm_list, "comm", NULL);
	sort_entry__setup_elide(&sort_sym, symbol_conf.sym_list, "symbol", NULL);

	return __cmd_diff();
}


text:
using System;
using System.Net;

namespace SteamToolkit.Web
{
    /// <summary>
    /// A response from the web.
    /// </summary>
    public interface IResponse : IDisposable
    {
        /// <summary>
        /// Reads the stream to a string
        /// </summary>
        /// <returns>The stream as a string</returns>
        string ReadStream();

        /// <summary>
        /// Deserializes the stream to an XML serializable type.
        /// </summary>
        /// <typeparam name="TSerializable">A serializable type.</typeparam>
        /// <returns>The deserialized type.</returns>
        TSerializable DeserializeXml<TSerializable>();

        /// <summary>
        /// Deserializes the stream to a JSON serializable type
        /// </summary>
        /// <typeparam name="TSerializable">A serializable type.</typeparam>
        /// <returns>The deserialized type.</returns>
        TSerializable DeserializeJson<TSerializable>();

        /// <summary>
        /// Any cookies created from the response.
        /// </summary>
        CookieCollection Cookies { get; }
    }
}


text:
/************************************************************************************//**
// Copyright (c) 2006-2015 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief The interface for the Tootle library.
****************************************************************************************/
#ifndef _CMP_MESH_H_
#define _CMP_MESH_H_

namespace CMP_MESH {

/// The default vertex cache size
#define DEFAULT_VCACHE_SIZE  16

/// The maximum allowed number of faces in the mesh
#define MAX_FACES            0x7fffffff

/// The maximum allowed number of vertices in the mesh
#define MAX_VERTICES         0x7fffffff

/// The parameter for TootleFastOptimize to create more clusters (lower number generates more clusters).
/// This parameter decides where to put extra breaks to create more clusters (refer to the SIGGRAPH 2007 paper
/// for the full description of the parameter.
#define DEFAULT_ALPHA        0.75f

/// Enumeration for face winding order
enum eFaceWinding {
    CCW = 1,                ///< Face is ordered counter-clockwise
    CW = 2                  ///< Face is ordered clockwise
};

/// Enumeration for the algorithm for vertex optimization
enum eVCacheOptimizer {
    VCACHE_AUTO = 1,           ///< If vertex cache size is less than 7, use TSTRIPS algorithm otherwise TIPSY.
    VCACHE_DIRECT3D = 2,       ///< Use D3DXOptimizeFaces to optimize faces.
    VCACHE_LSTRIPS = 3,        ///< Build a list like triangle strips to optimize faces.
    VCACHE_TIPSY = 4           ///< Use TIPSY (the algorithm from SIGGRAPH 2007) to optimize faces.
};

/// Enumeration for the algorithm for overdraw optimization.
enum eOverdrawOptimizer {
    OVERDRAW_AUTO = 1,          ///< Use either Direct3D or raytracing to reorder clusters (depending on the number of clusters).
    OVERDRAW_DIRECT3D = 2,      ///< Use Direct3D rendering to reorder clusters to optimize overdraw (slow O(N^2)).
    OVERDRAW_RAYTRACE = 3,      ///< Use CPU raytracing to reorder clusters to optimize overdraw (slow O(N^2)).
    OVERDRAW_FAST = 4           ///< Use a fast approximation algorithm (from SIGGRAPH 2007) to reorder clusters.
};

struct MESH_SETTINGS {
    char *       m_pViewpointName;
    unsigned int m_Clustering;
    unsigned int m_CacheSize;
    bool         m_OptimizeVertexMemory;   // true if you want to optimize vertex memory location, false to skip
    bool         m_MeasureOverdraw;        // true if you want to measure overdraw, false to skip
    eFaceWinding     m_FaceeWinding;
    eVCacheOptimizer m_VCacheOptimizer;
};

}

#endif


text:
package com.lambdaworks.test.crypto;

import com.lambdaworks.test.codec.Base16;

public abstract class AbstractCipherTest {
    public byte[] hex(String s) {
        s = s.replaceAll("(^0x|\\s+)", "");
        return Base16.decode(s.toCharArray());
    }
}


text:
<?php

namespace Barryvdh\Debugbar\DataCollector;

use DebugBar\DataCollector\DataCollector;
use DebugBar\DataCollector\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Config;

/**
 * Based on Illuminate\Foundation\Console\RoutesCommand for Taylor Otwell
 * https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Console/RoutesCommand.php
 *
 */
class IlluminateRouteCollector extends DataCollector implements Renderable
{
    /**
     * The router instance.
     *
     * @var \Illuminate\Routing\Router
     */
    protected $router;

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

    /**
     * {@inheritDoc}
     */
    public function collect()
    {
        $route = $this->router->current();
        return $this->getRouteInformation($route);
    }

    /**
     * Get the route information for a given route.
     *
     * @param  \Illuminate\Routing\Route $route
     * @return array
     */
    protected function getRouteInformation($route)
    {
        if (!is_a($route, 'Illuminate\Routing\Route')) {
            return array();
        }
        $uri = head($route->methods()) . ' ' . $route->uri();
		$action = $route->getAction();

        $result = array(
    	   'uri' => $uri ?: '-',
        );

        $result = array_merge($result, $action);

        if (isset($action['controller']) && strpos($action['controller'], '@') !== false) {
			list($controller, $method) = explode('@', $action['controller']);
			if(class_exists($controller) && method_exists($controller, $method)) {
			    $reflector = new \ReflectionMethod($controller, $method);
			}
            unset($result['uses']);
		} elseif (isset($action['uses']) && $action['uses'] instanceof \Closure) {
            $reflector = new \ReflectionFunction($action['uses']);
            $result['uses'] = $this->formatVar($result['uses']);
        }

        if (isset($reflector)) {
            $filename = ltrim(str_replace(base_path(), '', $reflector->getFileName()), '/');
            $result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine();
        }

		if ($before = $this->getBeforeFilters($route)) {
		    $result['before'] = $before;
		}

		if ($after = $this->getAfterFilters($route)) {
		    $result['after'] = $after;
		}

        return $result;
    }

    /**
     * Get before filters
     *
     * @param  \Illuminate\Routing\Route $route
     * @return string
     */
    protected function getBeforeFilters($route)
    {
        $before = array_keys($route->beforeFilters());

        $before = array_unique(array_merge($before, $this->getPatternFilters($route)));

        return implode(', ', $before);
    }

    /*
     * The following is copied/modified from the RoutesCommand from Laravel, by Taylor Otwell
     * https://github.com/laravel/framework/blob/4.1/src/Illuminate/Foundation/Console/RoutesCommand.php
     *
     */

    /**
     * Get all of the pattern filters matching the route.
     *
     * @param  \Illuminate\Routing\Route $route
     * @return array
     */
    protected function getPatternFilters($route)
    {
        $patterns = array();

        foreach ($route->methods() as $method) {
            // For each method supported by the route we will need to gather up the patterned
            // filters for that method. We will then merge these in with the other filters
            // we have already gathered up then return them back out to these consumers.
            $inner = $this->getMethodPatterns($route->uri(), $method);

            $patterns = array_merge($patterns, array_keys($inner));
        }

        return $patterns;
    }

    /**
     * Get the pattern filters for a given URI and method.
     *
     * @param  string $uri
     * @param  string $method
     * @return array
     */
    protected function getMethodPatterns($uri, $method)
    {
        return $this->router->findPatternFilters(Request::create($uri, $method));
    }

    /**
     * Get after filters
     *
     * @param  Route $route
     * @return string
     */
    protected function getAfterFilters($route)
    {
        return implode(', ', array_keys($route->afterFilters()));
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'route';
    }

    /**
     * {@inheritDoc}
     */
    public function getWidgets()
    {
        $widgets = array(
            "route" => array(
                "icon" => "share",
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
                "map" => "route",
                "default" => "{}"
            )
        );
        if (Config::get('debugbar.options.route.label', true)) {
            $widgets['currentroute'] = array(
                "icon" => "share",
                "tooltip" => "Route",
                "map" => "route.uri",
                "default" => ""
            );
        }
        return $widgets;
    }

    /**
     * Display the route information on the console.
     *
     * @param  array $routes
     * @return void
     */
    protected function displayRoutes(array $routes)
    {
        $this->table->setHeaders($this->headers)->setRows($routes);

        $this->table->render($this->getOutput());
    }
}


text:
package io.flow.lint.linters

import io.flow.lint.Linter
import io.apibuilder.spec.v0.models.{Field, Model, Operation, Parameter, Resource, Service}
import scala.util.{Failure, Success, Try}

/**
  *  - validates that any field with a maximum has the maximum set to 100
  *  - validates that any field with a minimum has the minimum set to 0 or 1
  *  - if there is a numeric default and a minimum, validates that
  *    default >= minimum
  *  - every parameter that is an array should have a maximum of 100
  *    (except if it is the expand parameter)
  */
case object MinimumMaximum extends Linter with Helpers {

  val GlobalMax = 100

  val CountryMax = 3
  val CurrencyMax = 3
  val LanguageMax = 2

  override def validate(service: Service): Seq[String] = {
    service.models.flatMap(validateModel) ++ service.resources.flatMap(validateResource(service, _))
  }

  def validateModel(model: Model): Seq[String] = {
    model.fields.flatMap { validateField(model, _) }
  }

  def validateField(model: Model, field: Field): Seq[String] = {
    val minErrors = field.minimum match {
      case None => Nil
      case Some(min) => {
        field.default match {
          case None => Nil
          case Some(default) => {
            Try(
              default.toLong
            ) match {
              case Success(d) => {
                if (d < min) {
                  Seq(error(model, field, s"Default must be >= minimum[$min] and not $default"))
                } else {
                  Nil
                }
              }
              case Failure(_) => {
                // Not a number - nothing to validate
                Nil
              }
            }
          }
        }
      }
    }

    val maxErrors = field.maximum match {
      case None => Nil
      case Some(max) =>  field.name match {
        case c if isCountry(c) =>
          if (max == CountryMax) {
            Nil
          } else {
            Seq(error(model, field, s"Maximum must be $CountryMax and not $max"))
          }

        case c if isCurrency(c) =>
          if (max == CurrencyMax) {
            Nil
          } else {
            Seq(error(model, field, s"Maximum must be $CurrencyMax and not $max"))
          }

        case c if isLanguage(c) =>
          if (max == LanguageMax) {
            Nil
          } else {
            Seq(error(model, field, s"Maximum must be $LanguageMax and not $max"))
          }

        case _ =>
          field.minimum match {
            case Some(min) => {
              if (max >= min) {
                Nil
              } else {
                Seq(error(model, field, s"Maximum, if specified with minimum, must be >= $min and not $max"))
              }
            }
            case None => Nil
          }
      }
    }

    minErrors ++ maxErrors
  }

  def validateResource(service: Service, resource: Resource): Seq[String] = {
    resource.operations.flatMap(validateOperation(service, resource, _))
  }

  def validateOperation(service: Service, resource: Resource, operation: Operation): Seq[String] = {
    operation.parameters.flatMap(validateParameter(service, resource, operation, _))
  }

  def validateParameter(service: Service, resource: Resource, operation: Operation, param: Parameter): Seq[String] = {
    val minErrors = param.minimum match {
      case None => Nil
      case Some(min) => {
        if (min < 0) {
          Seq(error(resource, operation, param, s"Minimum must be >= 0 and not $min"))
        } else {
          Nil
        }
      }
    }

    val maxErrors = param.maximum match {
      case None => {
        if (isArray(param.`type`)) {
          Seq(error(resource, operation, param, s"Missing maximum"))
        } else {
          Nil
        }
      }

      case Some(max) => {
        if (isArray(param.`type`)) {
          val desiredMax = service.enums.find(_.name == baseType(param.`type`)) match {
            case Some(enum) => Some(enum.values.size)
            case None => {
              if (isPrimitiveType(param.`type`)) {
                Some(GlobalMax)
              } else {
                None
              }
            }
          }

          desiredMax match {
            case None => Nil
            case Some(expected) => {
              if (max == expected) {
                Nil
              } else if (param.name == ExpandName) {
                Nil
              } else {
                Seq(error(resource, operation, param, s"Maximum must be $expected and not $max"))
              }
            }
          }
        } else {
          Nil
        }
      }
    }

    minErrors ++ maxErrors
  }

}


text:
package ru.stqa.pft.sandbox;

/**
 * Created by Сергей on 16.07.2017.
 */
public class Equality {

  public static void main (String[] args)
  {
    String s1 = "firefox";
    String s2 = new String(s1);

    System.out.println(s1==s2);  // ссылочное сравнение, когда сравниваются ссылки на объекты
    System.out.println(s1.equals(s2)); // это логическое сравнение, по смыслу
  }

}


text:
- used to make network/ajax requests
- works differently in tests (requests will not be made)
  - this is a great thing, and will push us into a great development environment

**get**

```coffee
file_List: (callback)=>
  url = "/api/v1/file/list"
  @.$http.get url
         .success callback
```

**post**

```coffee
file_Save: (target,data, callback)=>
  url = "/api/v1/file/save/#{target}?pretty"
  @.$http.post(url, data)
         .success (data)->
            callback data
```


text:
namespace courgette {

class EncodedProgram;
class Instruction;

// A Label is a symbolic reference to an address.  Unlike a conventional
// assembly language, we always know the address.  The address will later be
// stored in a table and the Label will be replaced with the index into the
// table.
//
// TODO(sra): Make fields private and add setters and getters.
class Label {
 public:
  static const int kNoIndex = -1;
  Label() : rva_(0), index_(kNoIndex) {}
  explicit Label(RVA rva) : rva_(rva), index_(kNoIndex) {}

  RVA rva_;    // Address refered to by the label.
  int index_;  // Index of address in address table, kNoIndex until assigned.
};

typedef std::map<RVA, Label*> RVAToLabel;

// An AssemblyProgram is the result of disassembling an executable file.
//
// * The disassembler creates labels in the AssemblyProgram and emits
//   'Instructions'.
// * The disassembler then calls DefaultAssignIndexes to assign
//   addresses to positions in the address tables.
// * [Optional step]
// * At this point the AssemblyProgram can be converted into an
//   EncodedProgram and serialized to an output stream.
// * Later, the EncodedProgram can be deserialized and assembled into
//   the original file.
//
// The optional step is to modify the AssemblyProgram.  One form of modification
// is to assign indexes in such a way as to make the EncodedProgram for this
// AssemblyProgram look more like the EncodedProgram for some other
// AssemblyProgram.  The modification process should call UnassignIndexes, do
// its own assignment, and then call AssignRemainingIndexes to ensure all
// indexes are assigned.
//
class AssemblyProgram {
 public:
  AssemblyProgram();
  ~AssemblyProgram();

  void set_image_base(uint64 image_base) { image_base_ = image_base; }

  // Instructions will be assembled in the order they are emitted.

  // Generates an entire base relocation table.
  void EmitMakeRelocsInstruction();

  // Following instruction will be assembled at address 'rva'.
  void EmitOriginInstruction(RVA rva);

  // Generates a single byte of data or machine instruction.
  void EmitByteInstruction(uint8 byte);

  // Generates 4-byte relative reference to address of 'label'.
  void EmitRel32(Label* label);

  // Generates 4-byte absolute reference to address of 'label'.
  void EmitAbs32(Label* label);

  Label* FindOrMakeAbs32Label(RVA rva);
  Label* FindOrMakeRel32Label(RVA rva);

  void DefaultAssignIndexes();
  void UnassignIndexes();
  void AssignRemainingIndexes();

  EncodedProgram* Encode() const;

  // Accessor for instruction list.
  const std::vector<Instruction*>& instructions() const {
    return instructions_;
  }

  // Returns the label if the instruction contains and absolute address,
  // otherwise returns NULL.
  Label* InstructionAbs32Label(const Instruction* instruction) const;

  // Returns the label if the instruction contains and rel32 offset,
  // otherwise returns NULL.
  Label* InstructionRel32Label(const Instruction* instruction) const;

 private:
  void Emit(Instruction* instruction) { instructions_.push_back(instruction); }

  Label* FindLabel(RVA rva, RVAToLabel* labels);

  // Helper methods for the public versions.
  static void UnassignIndexes(RVAToLabel* labels);
  static void DefaultAssignIndexes(RVAToLabel* labels);
  static void AssignRemainingIndexes(RVAToLabel* labels);

  // Sharing instructions that emit a single byte saves a lot of space.
  Instruction* GetByteInstruction(uint8 byte);
  Instruction** byte_instruction_cache_;

  uint64 image_base_;  // Desired or mandated base address of image.

  std::vector<Instruction*> instructions_;  // All the instructions in program.

  // These are lookup maps to find the label associated with a given address.
  // We have separate label spaces for addresses referenced by rel32 labels and
  // abs32 labels.  This is somewhat arbitrary.
  RVAToLabel rel32_labels_;
  RVAToLabel abs32_labels_;

  DISALLOW_COPY_AND_ASSIGN(AssemblyProgram);
};

}  // namespace courgette
#endif  // COURGETTE_ASSEMBLY_PROGRAM_H_


text:
// <copyright file="ApdexValue.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System;

namespace App.Metrics.Apdex
{
    /// <summary>
    ///     The value reported by an Apdex Metric
    /// </summary>
    public sealed class ApdexValue
    {
        public ApdexValue(double score, int satisfied, int tolerating, int frustrating, int sampleSize, bool allowWarmup = true)
        {
            Satisfied = satisfied;
            Tolerating = tolerating;
            Frustrating = frustrating;
            SampleSize = sampleSize;

            // DEVNOTE: Allow some warmup time before calculating apdex scores
            if (allowWarmup && sampleSize <= AppMetricsReservoirSamplingConstants.ApdexRequiredSamplesBeforeCalculating)
            {
                Score = 1;
            }
            else
            {
                Score = double.IsNaN(score) ? 0 : Math.Round(score, 2, MidpointRounding.AwayFromZero);
            }
        }

        public int Frustrating { get; }

        public int SampleSize { get; }

        public int Satisfied { get; }

        public double Score { get; }

        public int Tolerating { get; }
    }
}


text:
bin=`dirname $0`
daemon_pid_file="${bin}/../state/checkin-daemon.pid"

if [ ! -f "${daemon_pid_file}" ]; then
  exit 1
fi
PID=`cat ${daemon_pid_file}`
if [ -z "$PID" ]; then
  exit 1
fi
#echo "Stopping upgrade check-in daemon..."
kill $PID
ret=$?
if [ "$ret" != "0" ]; then
  echo "Error killing process with pid $PID"
  exit 1
fi
#echo "Waiting for shutdown..."
tries=15
while [ "$tries" -gt 0 ]; do
  tries=$(($tries - 1))
  ps -e -o pid,args | grep "^$PID" 2>&1 > /dev/null
  ret=$?
  if [ "$ret" != 0 ]; then
    break
  fi
  sleep 2
done
ps e | grep "^$PID " 2>&1 > /dev/null
ret=$?
if [ "$ret" == 0 ]; then
  echo "Kill signal sent but waiting for upgrade check-in daemon to stop timed out after 30 seconds!."
  exit 1
fi
# upgrade check-in daemon will delete its own pid file.
#echo "upgrade check-in daemon shutdown."


text:
package com.siahmsoft.soundwaper;

public class Constants {

	public class Prefs {
		public static final String DEFAULT_USER 		= "djquano"; //a friend of mine ;P
        public static final String NAME 				= "SoundcloudLiveWallpaperSettings";
        public static final String USER_KEY 			= "sc_user";
        public static final String TIMER_KEY            = "timer";
    	public static final String CLICK_TO_CHANGE_KEY  = "clickToChangeWaveform";
    	public static final String SHOW_TRACK_INFO_KEY  = "showTrackName";
    }
}


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

namespace GridDesktop.Examples.WorkingWithGrid
{
    public partial class ManagingContextMenu : Form
    {
        public ManagingContextMenu()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // ExStart:HideContextMenuItem
            // Get the ContextMenuManager
            ContextMenuManager cmm = this.grdDataEntry.ContextMenuManager;

            // Hide the Copy option in the context menu
            cmm.MenuItemAvailable_Copy = false;

            // Hide the InsertRow option in the context menu
            cmm.MenuItemAvailable_InsertRow = false;

            // Hide the Format Cell dialog box
            cmm.MenuItemAvailable_FormatCells = false;
            // ExEnd:HideContextMenuItem
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // ExStart:AddContextMenuItem
            // Get the active worksheet
            Worksheet sheet = grdDataEntry.GetActiveWorksheet();

            // Set the total columns diaplyed in the grid
            sheet.ColumnsCount = 15;

            // Set the total rows displayed in the grid
            sheet.RowsCount = 15;

            // Define a new menu item and specify its event handler
            MenuItem mi = new MenuItem("newMenuItem", new System.EventHandler(miClicked));

            // Set the label
            mi.Text = "New Item";

            // Add the menu item to the GridDesktop's context menu
            grdDataEntry.ContextMenu.MenuItems.Add(mi);
            // ExEnd:AddContextMenuItem
        }

        // ExStart:EventHandler
        // Event Handler for the new menu item
        private void miClicked(object sender, EventArgs e)
        {
            MenuItem mi = (MenuItem)sender;
            MessageBox.Show("miCliked: " + mi.Text);
        }
        // ExEnd:EventHandler
    }
}


text:
Przykładowa implementacja z [LinqKit](https://github.com/scottksmith95/LINQKit):

    static async Task<Person[]> GetPeople(string filter)
    {
        using (var context = new PeopleContext())
        {
            var filter = new FilterSpecification(filter);

            return await context.People
                .Where(filter.ToExpression())
                .ToArrayAsync();
        }
    }


text:
.agendaEvent {
  animation: blink-animation 1s steps(15, start) infinite;
}
@keyframes blink-animation {
  to {
    	color: red;
  }
}


text:
<?php

namespace Buoy\Common\Service;

use Symfony\Component\Validator\ConstraintViolationList;

Class Response
{
	const FORBIDDEN = 'error.forbidden';
	const NOT_FOUND = 'error.not_found';
	const BAD_REQUEST = 'error.bad_request';
	const INTERNAL_SERVER_ERROR = 'error.internal_server_error';
	const CONFLICT = 'error.conflict';
	const METHOD_NOT_ALLOWED = 'error.method_not_allowed';

	protected $data;

	protected $metadata;

	protected $errors;

	public function __construct()
	{
		$this->data = array();
		$this->metadata = array();
		$this->errors = new ConstraintViolationList();
	}

	public function getData()
	{
		return $this->data;
	}

	public function setData($data)
	{
		$this->data = $data;
	}

	public function getMetaData()
	{
		return $this->metadata;
	}

	public function setMetaData($metadata)
	{
		$this->metadata = $metadata;
	}

	public function metaKeys()
	{
		return array_keys($this->metadata);
	}

	public function addMeta($key, $value)
	{
		$this->metadata[$key] = $value;
 	}

 	public function getMeta($key, $default = null)
 	{
 		if ($this->hasMeta($key)) {
 			return $this->metadata[$key];
 		}

 		return $default;
 	}

 	public function hasMeta($key)
 	{
 		return array_key_exists($key, $this->metadata);
 	}

 	public function removeMeta($key)
 	{
 		unset($this->metadata[$key]);
 	}

 	public function isOk()
 	{
 		if (count($this->errors) === 0) {
 			return true;
 		}

 		return false;
 	}

 	public function getErrors()
 	{
 		return $this->errors;
 	}

 	public function addError($error, $message = '')
 	{
 		if (!$error instanceof Violation) {
 			$error = new Violation($message, array(), null, '', null, null, $error);
 		}

 		$this->errors->add($error);
 	}

 	public function addErrors(ConstraintViolationList $errors)
 	{
 		$this->errors->addAll($errors);
 	}
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import Component from './Component';

ReactDOM.render(
  <Component />,
  document.getElementById('app')
)


text:
<?php

namespace Google\Cloud\Dev\Tests\Unit\DocFx;

use Google\Cloud\Core\Testing\TestHelpers;
use Google\Cloud\Dev\ComponentManager;
use Google\Cloud\Dev\DocFx\Page\OverviewPage;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Yaml\Yaml;

/**
 * @group dev
 */
class CommandTest extends TestCase
{
    private static $fixturesDir;
    private static $tmpDir;

    public function testGenerateDocFxFiles()
    {
        $fixturesFiles = array_diff(scandir(self::$fixturesDir), ['..', '.']);
        $generatedFiles = array_diff(scandir(self::$tmpDir), ['..', '.']);

        $this->assertEquals([], array_diff($fixturesFiles, $generatedFiles));

    }

    /**
     * @depends testGenerateDocFxFiles
     * @dataProvider provideDocFxFiles
     */
    public function testDocFxFiles(string $file)
    {
        $this->assertTrue(
            file_exists(self::$fixturesDir . '/' . $file),
            sprintf('%s does not exist in fixtures (%s)', $file, self::$tmpDir . '/' . $file)
        );

        $left  = self::$fixturesDir . '/' . $file;
        $right = self::$tmpDir . '/' . $file;
        if (file_get_contents($left) !== file_get_contents($right)) {
            if ('1' === getenv('UPDATE_FIXTURES')) {
                file_put_contents(self::$fixturesDir . '/' . $file, file_get_contents($right));
                $this->markTestIncomplete('Updated fixture ' . $file);
            }
            $output = shell_exec(sprintf('git diff --no-index %s %s --color=always', $left, $right));
            $this->assertTrue(false, $output);
        }

        $this->assertTrue(true, 'file contents match');
    }

    /**
     * @depends testDocFxFiles
     */
    public function testDocsMetadataFile()
    {
        $this->assertTrue(
            file_exists(self::$tmpDir . '/docs.metadata'),
            'docs.metadata was not generated in ' . self::$tmpDir
        );

        $left  = self::$fixturesDir . '/docs.metadata';
        $right = self::$tmpDir . '/docs.metadata';
        $rightContents = preg_replace('/seconds: \d+/', 'seconds: *', file_get_contents($right));
        $rightContents = preg_replace('/nanos: \d+/', 'nanos: *', $rightContents);
        if (file_get_contents($left) !== $rightContents) {
            file_put_contents($right, $rightContents);
            $output = shell_exec(sprintf('git diff --no-index %s %s --color=always', $left, $right));
            $this->assertTrue(false, $output);
        }

        $this->assertTrue(true, 'file contents match');
    }

    public function testOverviewPage()
    {
        $overview1 = new OverviewPage("# Not beta\n\n", $beta = false);
        $this->assertEquals("# Not beta\n\n", $overview1->getContents());

        $overview2 = new OverviewPage("No header\n\n", $beta = true);
        $this->assertEquals("No header\n\n", $overview2->getContents());

        $overview3 = new OverviewPage("# No newline", $beta = true);
        $this->assertEquals('# No newline', $overview3->getContents());

        $overview4 = new OverviewPage("# Yes beta\nend.", $beta = true);
        $this->assertStringContainsString('pre-GA', $overview4->getContents());
        $this->assertStringStartsWith("# Yes beta\n", $overview4->getContents());
        $this->assertStringEndsWith("\nend.", $overview4->getContents());
    }

    public function provideDocFxFiles()
    {
        $structureXml = __DIR__ . '/../../fixtures/phpdoc/structure.xml';
        $tmpDir = sys_get_temp_dir() . '/' . rand();
        $cmd = sprintf(
            '%s/google-cloud docfx --component Vision --xml %s --out=%s --metadata-version=1.0.0',
            __DIR__ . '/../../../',
            $structureXml,
            $tmpDir
        );
        passthru($cmd);

        $filesAsArguments = [];
        $generatedFiles = array_diff(scandir($tmpDir), ['..', '.']);
        foreach ($generatedFiles as $file) {
            if ($file === 'docs.metadata') {
                continue;
            }
            $filesAsArguments[] = [$file];
        }

        self::$tmpDir = $tmpDir;
        self::$fixturesDir = realpath(__DIR__ . '/../../fixtures/docfx');

        return $filesAsArguments;
    }
}


text:
"""
    views
    ~~~~~

    Routes & views for this app!
"""

from flask import (
    Blueprint, render_template, jsonify, request, current_app
)
from jinja2 import TemplateNotFound
import voweler
from string import ascii_lowercase
import json

simple_page = Blueprint('simple_page', __name__,
                        template_folder='templates')

def render_score(score):
    return "{0:.0f}%".format(score * 100.)

@simple_page.route('/')
def base():
    # serve the single page app
    return current_app.send_static_file('index.html')

@simple_page.route('/state')
def state():
    """
    Optionally update model via 'update' querystring arg
    Returns (after update):
        weights of model
        current predicted vowel list
    """
    next_letter = request.args.get('update')
    if next_letter:
        current_app.vp.handle_letter(next_letter)

    vocab = [
        (e, current_app.vp.handle_letter(e, update=False))
        for e in ascii_lowercase
    ]
    current_score = voweler.separability.get_perceptron_accuracy(current_app.vp)
    scatter_data = voweler.separability.project_to_1d(
        current_app.vp.to_vec, current_app.vp.w
    )
    return jsonify(
        weights=[round(x, 2) for x in current_app.vp.w],
        vowels=[
            l
            for l in ascii_lowercase
            if current_app.vp.handle_letter(l, update=False) == 1.
        ],
        scatter_data=scatter_data,
        current_score=render_score(current_score)
    )

@simple_page.route('/size')
def set_size():
    size = request.args.get('size')
    perceptron_kwargs = {}
    if size:
        perceptron_kwargs['input_width'] = int(size)
    current_app.vp = voweler.perceptron.VowelPerceptron(**perceptron_kwargs)
    (x_data, y_data, score) = voweler.separability.assess_embedding(
        current_app.vp.to_vec)
    return jsonify(
        reset=True,
        scatter_data=voweler.separability.get_c3_payload(x_data, y_data),
        score=render_score(score)
    )