text:
package prefuse.action.animate;

import prefuse.action.Action;

/**
 * Animator that toggles rendering quality to allow for smooth animations but
 * high quality rendering of still images. At the beginning of an animation,
 * high quality rendering (if enabled) is disabled, and at the end the original
 * setting is restored.
 *
 * @author jeffrey heer
 */
public class QualityControlAnimator extends Action {

    /**
     * @see prefuse.action.Action#run(double)
     */
    public void run(double frac) {
        if ( m_vis == null ) return;
        if ( frac == 0.0 || frac == 1.0 ) {
            boolean quality = frac >= 1.0;
            for ( int i=0; i<m_vis.getDisplayCount(); ++i ) {
                m_vis.getDisplay(i).setHighQuality(quality);
            }
            qualityValue(quality);
        }
    }

    /**
     * Callback procedure that subclasses can override to execute
     * custom quality control measures.
     * @param quality true if high quality is desired, false otherwise
     */
    protected void qualityValue(boolean quality) {
        // do nothing
    }

} // end of class QualityControlAnimator


text:
@interface LOGeofenceObserver()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;

@end

@implementation LOGeofenceObserver

-(instancetype)initWithObserver:(id)observer selector:(SEL)selector{
    self = [super initWithObserver:observer selector:selector];
    if (self) {
        _locationManager = [CLLocationManager new];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = kCLDistanceFilterNone;

        self.entries = [NSMutableDictionary new];
    }
    return self;
}

-(void)dealloc{
    if (_locationManager) {
        _locationManager.delegate = nil;
    }
}

-(void)willAddEntries{
    [self stopObserve];
}

-(void)didAddEntries{
    if (self.enabled) {
        [self startObserve];
    }
}

-(void)willRemoveEntries{
    [self stopObserve];
}

-(void)didRemoveEntries:(BOOL)entryIsNothing{
    if (!entryIsNothing && self.enabled) {
        [self startObserve];
    }
}

-(BOOL)isMineEntry:(NSDictionary *)entry{
    return [entry objectForKey:kKeyLatitude] != 0
    && [entry objectForKey:kKeyLongitude] != 0
    && [entry objectForKey:kKeyRange] != 0;
}

//private

-(void)startObserve{
    if (self.entries.count > 0) {
        float iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];

        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_locationManager requestAlwaysAuthorization];
        }

        for (NSDictionary* entry in self.entries.allValues) {
            double latitude = ((NSNumber*)[entry objectForKey:kKeyLatitude]).doubleValue;
            double longitude = ((NSNumber*)[entry objectForKey:kKeyLongitude]).doubleValue;
            long range = ((NSNumber*)[entry objectForKey:kKeyRange]).longValue;

            //最大半径に丸める
            if (range > _locationManager.maximumRegionMonitoringDistance) {
                range = _locationManager.maximumRegionMonitoringDistance;
            }

            CLLocationCoordinate2D center = CLLocationCoordinate2DMake(latitude, longitude);

            if (iOSVersion >= 7.0) {
                CLCircularRegion* region = [[CLCircularRegion alloc] initWithCenter:center radius:range identifier:entry[kKeyEntryId]];
                [_locationManager startMonitoringForRegion:region];
            }else{
                CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:center radius:range identifier:entry[kKeyEntryId]];

                if (iOSVersion >= 5.0) {
                    [_locationManager startMonitoringForRegion:region];
                }else{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                    [_locationManager startMonitoringForRegion:region desiredAccuracy:kCLLocationAccuracyBest];
#pragma clang diagnostic pop
                }
            }
        }
    }
}

-(void)stopObserve{
    for (CLRegion* region in _locationManager.monitoredRegions) {
        if ([region isKindOfClass:[CLCircularRegion class]]) {
            [_locationManager stopMonitoringForRegion:region];
        }
    }
}

-(void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region{

}

-(void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error{

}

//LocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
    if ([region isKindOfClass:[CLCircularRegion class]]) {
        NSDictionary* entry = [self.entries objectForKey:region.identifier];
        if ([entry[kKeyTransitionEnter] boolValue]) {
            LOObserveResult* result = [[LOObserveResult alloc] initWithEntry:entry action:REGION_ENTER];
            [self postResult:result];
        }
    }
}

-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region{
    if ([region isKindOfClass:[CLCircularRegion class]]) {
        NSDictionary* entry = [self.entries objectForKey:region.identifier];
        if ([entry[kKeyTransitionExit] boolValue]) {
            LOObserveResult* result = [[LOObserveResult alloc] initWithEntry:entry action:REGION_EXIT];
            [self postResult:result];
        }
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
/*
 * Displays the "Review request changed" box on the review request page.
 *
 * This handles any rendering needed for special contents in the box,
 * such as the diff complexity icons and the file attachment thumbnails.
 */
RB.ChangeBoxView = RB.CollapsableBoxView.extend({
    initialize: function(options) {
        this.reviewRequest = options.reviewRequest;
        this.reviewRequestEditorView = options.reviewRequestEditorView;
    },

    render: function() {
        var $text = this.$('.changedesc-text');

        _super(this).render.call(this);

        this.reviewRequestEditorView.formatText($text);

        _.each(this.$('.diff-index tr'), function(rowEl) {
            var $row = $(rowEl),
                iconView = new RB.DiffComplexityIconView({
                    numInserts: $row.data('insert-count'),
                    numDeletes: $row.data('delete-count'),
                    numReplaces: $row.data('replace-count'),
                    totalLines: $row.data('total-line-count')
                });

            $row.find('.diff-file-icon')
                .empty()
                .append(iconView.$el);
            iconView.render();
        });

        _.each(this.$('.file-container'), function(thumbnailEl) {
            var $thumbnail = $(thumbnailEl),
                $caption = $thumbnail.find('.file-caption .edit'),
                model = this.reviewRequest.draft.createFileAttachment({
                    id: $thumbnail.data('file-id')
                });

            if (!$caption.hasClass('empty-caption')) {
                model.set('caption', $caption.text());
            }

            this.reviewRequestEditorView.buildFileAttachmentThumbnail(
                model, null,
                {
                    $el: $thumbnail,
                    canEdit: false
                });
        }, this);

        return this;
    }
});


text:
const fs = require('fs');
const util = require('util');
const Client = require('kubernetes-client').Client;
const config = require('kubernetes-client').config;
const client = new Client({ config: config.getInCluster() });
const JSONStream = require('json-stream');
const jsonStream = new JSONStream();
const configFilePath = "./proxyConfig.js"
const namespace = fs.readFileSync('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'utf8').toString();

function getNodes(endpoints) {
  return endpoints.subsets ? endpoints.subsets[0].addresses.map(e => ({ host: e.ip, port: 8125, adminport: 8126 })) : [];
}

function changeConfig(endpoints) {
  currentConfig = fs.readFileSync(configFilePath);
  eval("currentConfig = " + currentConfig);
  currentConfig.nodes = getNodes(endpoints);
  fs.writeFileSync(configFilePath, util.inspect(currentConfig));
}

async function main() {
  await client.loadSpec();
  const stream = client.apis.v1.ns(namespace).endpoints.getStream({ qs: { watch: true, fieldSelector: 'metadata.name=statsd-daemon' } });
  stream.pipe(jsonStream);
  jsonStream.on('data', obj => {
    if (!obj) {
      return;
    }
    console.log('Received update:', JSON.stringify(obj));
    changeConfig(obj.object);
  });
}

try {
  main();
} catch (error) {
  console.error(error);
  process.exit(1);
}


text:
layout: default
---

    {% capture rules %}
      {% include rules.md %}
    {% endcapture %}
    {{ rules | unindent | markdownify }}


text:
Determines whether a sequence contains the specified UcsTableRecord.

## Syntax

**C#**

``` C#
public override bool Contains(UcsTableRecord element)
```

**VB**

``` VB
Public Overrides Function Contains (element As UcsTableRecord) As Boolean
```

### Parameters

element

Type: UcsTableRecord
The UcsTableRecord to locate in the sequence.

### Return Value
Type: bool
true if the source sequence contains the specified element; otherwise, false.
Back to Top

## See Also

#### Reference
UcsContainer Class
Linq2Acad Namespace


text:
<?php
$this->breadcrumbs=array(
	'Map Sections'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'List MapSection', 'url'=>array('index')),
	array('label'=>'Create MapSection', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$.fn.yiiGridView.update('map-section-grid', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

Manage Map Sections

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?= CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'map-section-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'id',
		'createdAt',
		array(            // display 'author.username' using an expression
			'name' => 'createdBy',
			'value' => '$data->getCreateUserName()',
		),
		'changedAt',
		array(            // display 'author.username' using an expression
			'name' => 'changedBy',
			'value' => '$data->getChangeUserName()',
		),
		'leftSectionId',
		'rightSectionId',
		'worldId',
		array(
			'class'=>'CButtonColumn',
			'template' => '{update} {delete}',
		),
	),
)); ?>


text:
"""Code to help with HTTP requests, responses, and events from GitHub's developer API.

This code has been constructed to perform no I/O of its own. This allows you to
use any HTTP library you prefer while not having to implement common details
when working with GitHub's API (e.g. validating webhook events or specifying the
API version you want your request to work against).
"""
import datetime
from email.message import Message
import hmac
import http
import json
import re
from typing import Any, Dict, Mapping, Optional, Tuple, Type, Union
import urllib.parse

import uritemplate
from uritemplate import variable

from . import (
    BadRequest,
    BadRequestUnknownError,
    GitHubBroken,
    HTTPException,
    InvalidField,
    RateLimitExceeded,
    RedirectionException,
    ValidationError,
    ValidationFailure,
)

def _parse_content_type(content_type: Optional[str]) -> Tuple[Optional[str], str]:
    """Tease out the content-type and character encoding.

    A default character encoding of UTF-8 is used, so the content-type
    must be used to determine if any decoding is necessary to begin
    with.
    """
    if not content_type:
        return None, "utf-8"
    else:
        m = Message()
        m["content-type"] = content_type
        type_ = m.get_content_type()
        encoding = m.get_param("charset") or "utf-8"
        return type_, str(encoding)

def _decode_body(
    content_type: Optional[str], body: bytes, *, strict: bool = False
) -> Any:
    """Decode an HTTP body based on the specified content type.

    If 'strict' is true, then raise ValueError if the content type
    is not recognized. Otherwise simply returned the body as a decoded
    string.
    """
    type_, encoding = _parse_content_type(content_type)
    if not len(body) or not content_type:
        return None
    decoded_body = body.decode(encoding)
    if type_ == "application/json":
        return json.loads(decoded_body)
    elif type_ == "application/x-www-form-urlencoded":
        return json.loads(urllib.parse.parse_qs(decoded_body)["payload"][0])
    elif strict:
        raise ValueError(f"unrecognized content type: {type_!r}")
    return decoded_body

def validate_event(payload: bytes, *, signature: str, secret: str) -> None:
    """Validate the signature of a webhook event."""
    # https://docs.github.com/en/developers/webhooks-and-events/securing-your-webhooks#validating-payloads-from-github
    sha256_signature_prefix = "sha256="
    sha1_signature_prefix = "sha1="
    if signature.startswith(sha256_signature_prefix):
        hmac_sig = hmac.new(
            secret.encode("UTF-8"), msg=payload, digestmod="sha256"
        ).hexdigest()
        calculated_sig = sha256_signature_prefix + hmac_sig
    elif signature.startswith(sha1_signature_prefix):
        hmac_sig = hmac.new(
            secret.encode("UTF-8"), msg=payload, digestmod="sha1"
        ).hexdigest()
        calculated_sig = sha1_signature_prefix + hmac_sig
    else:
        raise ValidationFailure(
            f"signature does not start with {repr(sha256_signature_prefix)} or {repr(sha1_signature_prefix)}"
        )
    if not hmac.compare_digest(signature, calculated_sig):
        raise ValidationFailure("payload's signature does not align with the secret")

class Event:

    """Details of a GitHub webhook event."""

    def __init__(self, data: Any, *, event: str, delivery_id: str) -> None:
        # https://docs.github.com/en/free-pro-team@latest/developers/webhooks-and-events/webhook-events-and-payloads
        # https://docs.github.com/en/free-pro-team@latest/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers
        self.data = data
        # Event is not an enum as GitHub provides the string. This allows them
        # to add new events without having to mirror them here. There's also no
        # direct worry of a user typing in the wrong event name and thus no need
        # for an enum's typing protection.
        self.event = event
        self.delivery_id = delivery_id

    @classmethod
    def from_http(
        cls, headers: Mapping[str, str], body: bytes, *, secret: Optional[str] = None
    ) -> "Event":
        """Construct an event from HTTP headers and JSON body data.

        The mapping providing the headers is expected to support lowercase keys.

        Since this method assumes the body of the HTTP request is JSON, a check
        is performed for a content-type of "application/json" (GitHub does
        support other content-types). If the content-type does not match,
        BadRequest is raised.

        If the appropriate headers are provided for event validation, then it
        will be performed unconditionally. Any failure in validation
        (including not providing a secret) will lead to ValidationFailure being
        raised.
        """
        signature = headers.get("x-hub-signature-256", headers.get("x-hub-signature"))
        if signature is not None:
            if secret is None:
                raise ValidationFailure("secret not provided")
            validate_event(body, signature=signature, secret=secret)
        elif secret is not None:
            raise ValidationFailure("signature is missing")

        try:
            data = _decode_body(headers["content-type"], body, strict=True)
        except (KeyError, ValueError) as exc:
            raise BadRequest(
                http.HTTPStatus(415),
                "expected a content-type of "
                "'application/json' or "
                "'application/x-www-form-urlencoded'",
            ) from exc
        return cls(
            data,
            event=headers["x-github-event"],
            delivery_id=headers["x-github-delivery"],
        )

def accept_format(
    *, version: str = "v3", media: Optional[str] = None, json: bool = True
) -> str:
    """Construct the specification of the format that a request should return.

    The version argument defaults to v3 of the GitHub API and is applicable to
    all requests. The media argument along with 'json' specifies what format
    the request should return, e.g. requesting the rendered HTML of a comment.
    Do note that not all of GitHub's API supports alternative formats.

    The default arguments of this function will always return the latest stable
    version of the GitHub API in the default format that this library is
    designed to support.
    """
    # https://docs.github.com/en/free-pro-team@latest/rest/overview/media-types
    # https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#current-version
    accept = f"application/vnd.github.{version}"
    if media is not None:
        accept += f".{media}"
    if json:
        accept += "+json"
    return accept

def create_headers(
    requester: str,
    *,
    accept: str = accept_format(),
    oauth_token: Optional[str] = None,
    jwt: Optional[str] = None,
) -> Dict[str, str]:
    """Create a dict representing GitHub-specific header fields.

    The user agent is set according to who the requester is. GitHub asks it be
    either a username or project name.

    The 'accept' argument corresponds to the 'accept' field and defaults to the
    default result of accept_format(). You should only need to change this value
    if you are using a different version of the API -- e.g. one that is under
    development -- or if you are looking for a different format return type,
    e.g. wanting the rendered HTML of a Markdown file.

    The 'oauth_token' allows making an authenticated request using a personal access
    token. This can be important if you need the expanded rate limit provided
    by an authenticated request.

    The 'jwt' allows authenticating as a GitHub App by passing in the
    bearer token.

    You can only supply only one of oauth_token or jwt, not both.

    For consistency, all keys in the returned dict will be lowercased.
    """
    # user-agent: https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#user-agent-required
    # accept: https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#current-version
    #         https://docs.github.com/en/free-pro-team@latest/rest/overview/media-types
    # authorization: https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#authentication
    # authenticating as a GitHub App: https://docs.github.com/en/free-pro-team@latest/developers/apps/authenticating-with-github-apps#authenticating-as-a-github-app

    if oauth_token is not None and jwt is not None:
        raise ValueError("Cannot pass both oauth_token and jwt.")
    headers = {"user-agent": requester, "accept": accept}
    if oauth_token is not None:
        headers["authorization"] = f"token {oauth_token}"
    elif jwt is not None:
        headers["authorization"] = f"bearer {jwt}"
    return headers

class RateLimit:

    """The rate limit imposed upon the requester.

    The 'limit' attribute specifies the rate of requests per hour the client is
    limited to.

    The 'remaining' attribute specifies how many requests remain within the
    current rate limit that the client can make.

    The reset_datetime attribute is a datetime object representing when
    effectively 'left' resets to 'rate'. The datetime object is timezone-aware
    and set to UTC.

    The boolean value of an instance whether another request can be made. This
    is determined based on whether there are any remaining requests or if the
    reset datetime has passed.
    """

    # https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#rate-limiting

    def __init__(self, *, limit: int, remaining: int, reset_epoch: float) -> None:
        """Instantiate a RateLimit object.

        The reset_epoch argument should be in seconds since the UTC epoch.
        """
        # Instance attribute names stem from the name GitHub uses in their
        # API documentation.
        self.limit = limit
        self.remaining = remaining
        # Name specifies the type to remind users that the epoch is not stored
        # as an int as the GitHub API returns.
        self.reset_datetime = datetime.datetime.fromtimestamp(
            reset_epoch, datetime.timezone.utc
        )

    def __bool__(self) -> bool:
        """True if requests are remaining or the reset datetime has passed."""
        if self.remaining > 0:
            return True
        else:
            now = datetime.datetime.now(datetime.timezone.utc)
            return now > self.reset_datetime

    def __str__(self) -> str:
        """Provide all details in a reasonable format."""
        return f"< {self.remaining:,}/{self.limit:,} until {self.reset_datetime} >"

    @classmethod
    def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]:
        """Gather rate limit information from HTTP headers.

        The mapping providing the headers is expected to support lowercase
        keys.  Returns ``None`` if ratelimit info is not found in the headers.
        """
        try:
            limit = int(headers["x-ratelimit-limit"])
            remaining = int(headers["x-ratelimit-remaining"])
            reset_epoch = float(headers["x-ratelimit-reset"])
        except KeyError:
            return None
        else:
            return cls(limit=limit, remaining=remaining, reset_epoch=reset_epoch)

_link_re = re.compile(
    r"\<(?P<uri>[^>]+)\>;\s*" r'(?P<param_type>\w+)="(?P<param_value>\w+)"(,\s*)?'
)

def _next_link(link: Optional[str]) -> Optional[str]:
    # https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#pagination
    # https://tools.ietf.org/html/rfc5988
    if link is None:
        return None
    for match in _link_re.finditer(link):
        if match.group("param_type") == "rel":
            if match.group("param_value") == "next":
                return match.group("uri")
    else:
        return None

def decipher_response(
    status_code: int, headers: Mapping[str, str], body: bytes
) -> Tuple[Any, Optional[RateLimit], Optional[str]]:
    """Decipher an HTTP response for a GitHub API request.

    The mapping providing the headers is expected to support lowercase keys.

    The parameters of this function correspond to the three main parts
    of an HTTP response: the status code, headers, and body. Assuming
    no errors which lead to an exception being raised, a 3-item tuple
    is returned. The first item is the decoded body (typically a JSON
    object, but possibly None or a string depending on the content
    type of the body). The second item is an instance of RateLimit
    based on what the response specified.

    The last item of the tuple is the URL where to request the next
    part of results. If there are no more results then None is
    returned. Do be aware that the URL can be a URI template and so
    may need to be expanded.

    If the status code is anything other than 200, 201, or 204, then
    an HTTPException is raised.
    """
    data = _decode_body(headers.get("content-type"), body)
    if status_code in {200, 201, 202, 204}:
        return data, RateLimit.from_http(headers), _next_link(headers.get("link"))
    else:
        try:
            message = data["message"]
        except (TypeError, KeyError):
            message = None
        exc_type: Type[HTTPException]
        if status_code >= 500:
            exc_type = GitHubBroken
        elif status_code >= 400:
            exc_type = BadRequest
            if status_code == 403:
                rate_limit = RateLimit.from_http(headers)
                if rate_limit and not rate_limit.remaining:
                    raise RateLimitExceeded(rate_limit, message)
            elif status_code == 422:
                try:
                    errors = data.get("errors", None)
                except AttributeError:
                    # Not JSON so don't know why the request failed.
                    raise BadRequestUnknownError(data)
                exc_type = InvalidField
                if errors:
                    if any(
                        e["code"]
                        in ["missing", "missing_field", "invalid", "already_exists"]
                        for e in errors
                    ):
                        error_context = ", ".join(repr(e.get("field")) for e in errors)
                        message = f"{message} for {error_context}"
                    else:
                        exc_type = ValidationError
                        error_context = ", ".join(
                            repr(e.get("message")) for e in errors
                        )
                        message = f"{message}: {error_context}"
                else:
                    message = data["message"]
                raise exc_type(errors, message)
        elif status_code >= 300:
            exc_type = RedirectionException
        else:
            exc_type = HTTPException
        status_code_enum = http.HTTPStatus(status_code)
        args: Union[Tuple[http.HTTPStatus, str], Tuple[http.HTTPStatus]]
        if message:
            args = status_code_enum, message
        else:
            args = (status_code_enum,)
        raise exc_type(*args)

DOMAIN = "https://api.github.com"

def format_url(
    url: str, url_vars: Optional[variable.VariableValueDict], *, base_url: str = DOMAIN
) -> str:
    """Construct a URL for the GitHub API.

    The URL may be absolute or relative. In the latter case the appropriate
    domain will be added. This is to help when copying the relative URL directly
    from the GitHub developer documentation.

    The dict provided in url_vars is used in URI template formatting.
    """

    url = urllib.parse.urljoin(base_url, url)  # Works even if 'url' is fully-qualified.
    expanded_url: str = uritemplate.expand(url, var_dict=url_vars)
    return expanded_url


text:
m = Map("samba", translate("Network Shares"))

s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true

s:tab("general",  translate("General Settings"))
s:tab("template", translate("Edit Template"))

s:taboption("general", Value, "name", translate("Hostname"))
s:taboption("general", Value, "description", translate("Description"))
s:taboption("general", Value, "workgroup", translate("Workgroup"))
h = s:taboption("general", Flag, "homes", translate("Share home-directories"),
        translate("Allow system users to reach their home directories via " ..
                "network shares"))
h.rmempty = false

tmpl = s:taboption("template", Value, "_tmpl",
	translate("Edit the template that is used for generating the samba configuration."),
	translate("This is the content of the file '/etc/samba/smb.conf.template' from which your samba configuration will be generated. " ..
		"Values enclosed by pipe symbols ('|') should not be changed. They get their values from the 'General Settings' tab."))

tmpl.template = "cbi/tvalue"
tmpl.rows = 20

function tmpl.cfgvalue(self, section)
	return nixio.fs.readfile("/etc/samba/smb.conf.template")
end

function tmpl.write(self, section, value)
	value = value:gsub("\r\n?", "\n")
	nixio.fs.writefile("//etc/samba/smb.conf.template", value)
end

s = m:section(TypedSection, "sambashare", translate("Shared Directories")
  , translate("Please add directories to share. Each directory refers to a folder on a mounted device."))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"

s:option(Value, "name", translate("Name"))
pth = s:option(Value, "path", translate("Path"))
if nixio.fs.access("/etc/config/fstab") then
        pth.titleref = luci.dispatcher.build_url("admin", "system", "fstab")
end

s:option(Value, "users", translate("Allowed users")).rmempty = true

ro = s:option(Flag, "read_only", translate("Read-only"))
ro.rmempty = false
ro.enabled = "yes"
ro.disabled = "no"

br = s:option(Flag, "browseable", translate("Browseable"))
br.rmempty = false
br.default = "yes"
br.enabled = "yes"
br.disabled = "no"

go = s:option(Flag, "guest_ok", translate("Allow guests"))
go.rmempty = false
go.enabled = "yes"
go.disabled = "no"

cm = s:option(Value, "create_mask", translate("Create mask"),
        translate("Mask for new files"))
cm.rmempty = true
cm.size = 4

dm = s:option(Value, "dir_mask", translate("Directory mask"),
        translate("Mask for new directories"))
dm.rmempty = true
dm.size = 4

return m


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace CheetahTesting
{
    public class Then<T> : IContextExecutor<T>, IThen<T>
    {
        private readonly List<Func<IContextExecutor<T>, Task>> _actions;

        internal Then(T context, List<Func<IContextExecutor<T>, Task>> actions)
        {
            Context = context;
            _actions = actions;
        }

        public Then<T> AndAsync(Func<IThen<T>, Task> action)
        {
            _actions.Add(action);
            return this;
        }

        public Then<T> And(Action<IThen<T>> action)
        {
            _actions.Add(action.ToAsync());
            return this;
        }

        public T Context { get; }

        public async Task ExecuteAsync()
        {
            foreach (var action in _actions)
                await action(this);

            if (Context is IDisposable)
                (Context as IDisposable).Dispose();
        }
    }
}


text:
require 'pedant/rspec/node_util'

describe 'license', :license do
  include Pedant::RSpec::NodeUtil

  let (:request_url) { "#{platform.server}/license" }

  let (:node_count) { 0 }

  # TODO this should be in pedant config and rendered from attribute
  MAX_NODE_COUNT = 25
  let (:response_body) {
    {
      "limit_exceeded" => (node_count > MAX_NODE_COUNT ) ? true : false,
      "node_license" => MAX_NODE_COUNT,
      "node_count" => node_count,
      "upgrade_url" => /^https\:\/\.*/
    }}

  context "GET /license" do
    context "with no nodes" do

      it "returns 200 and correct body for superuser" do
        get(request_url, superuser).should look_like(
          :body_exact => response_body,
          :status => 200
          )
      end

      it "returns 200 and correct body for admin user" do
        get(request_url, platform.admin_user).should look_like(
          :body_exact => response_body,
          :status => 200
          )
      end

      it "returns 200 and correct body for normal user" do
        get(request_url, platform.non_admin_user).should look_like(
          :body_exact => response_body,
          :status => 200
          )
      end

      it "returns 401 for invalid user", :authentication do
        get(request_url, invalid_user).should look_like(
          :status => 401
          )
      end

      it "returns 401 for client", :authentication do
        get(request_url, platform.non_admin_client).should look_like(
          :status => 401
          )
      end

    end # with no nodes

    context "with nodes" do
      let(:nodes) do
        (1..node_count).map{|i| new_node(unique_name("pedant_node_list_test_#{i}"))}
      end

      before :each do
        nodes.each do |n|
          add_node(platform.admin_user, n)
        end
      end

      after :each do
        nodes.each do |n|
          delete_node(platform.admin_user, n['name']).should look_like ({:response_code => 200})
        end
      end

      context "with one node" do
        let(:node_count) { 1 }

        it "should return correct body for license status" do
          get(request_url, superuser).should look_like(
            :body_exact => response_body,
            :status => 200
            )
        end
      end # with one node

      context "with #{MAX_NODE_COUNT} nodes (license not exceeded)" do
        let(:node_count) { MAX_NODE_COUNT }

        it "should return correct body for license status" do
          get(request_url, superuser).should look_like(
            :body_exact => response_body,
            :status => 200
            )
        end
      end

      context "with  #{MAX_NODE_COUNT + 1} (license exceeded)" do
        let(:node_count) { MAX_NODE_COUNT + 1}
        it "should return correct body for license status" do
          get(request_url, superuser).should look_like(
            :body_exact => response_body,
            :status => 200
            )
        end
      end # with thirty nodes
    end # with nodes
  end # GET /license

end # license


text:
<?php
    header("Link: </resources/dummy.css>;rel=preload", false);
    header("Link: </resources/square.png>;rel=preload;as=image;media=(min-width: 1px)", false);
?>
<!DOCTYPE html>
<html>
<body>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<link rel="preload" href="/resources/dummy.js" as="script">
<script>
    var t = async_test('Makes sure that Link headers preload resources');
</script>
<script src="/resources/slow-script.pl?delay=200"></script>
<script>
    window.addEventListener("load", t.step_func(function() {
      var nonMediaHeader = performance.getEntriesByName(
        "http://127.0.0.1:8000/resources/dummy.css")[0];
      var mediaHeader = performance.getEntriesByName(
        "http://127.0.0.1:8000/resources/square.png")[0];
      var markup = performance.getEntriesByName(
        "http://127.0.0.1:8000/resources/dummy.js")[0];
      var normalResource = performance.getEntriesByName(
        "http://127.0.0.1:8000/resources/testharness.js")[0];
      // The non-media header can be processed at commit time.
      // The media header needs to tokenize the first chunk of html, and the
      // markup still needs to be tokenized.
      // Note: the link preloads can be preloaded before the normal resource
      // because they don't need to wait for the document element to be
      // available (ApplicationCache initialization time).
      assert_greater_than(markup.startTime, nonMediaHeader.startTime);
      assert_greater_than(mediaHeader.startTime, nonMediaHeader.startTime);
      assert_greater_than(normalResource.startTime, mediaHeader.startTime);
      assert_greater_than(normalResource.startTime, markup.startTime);
      t.done();
    }));
</script>
</body>
</html>


text:
<?php
/**
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class Version68 extends Doctrine_Migration_Base
{
    public function up()
    {
        $this->addColumn('registrars', 'name', 'string', '200', array(
             'notnull' => '1',
             ));
    }

    public function down()
    {
        $this->removeColumn('registrars', 'name');
    }
}


text:
package slapi_test

import (
	"log"

	softlayer_account "github.com/sudorandom/softlayer-go-gen/methods/softlayer_account"
	gentypes "github.com/sudorandom/softlayer-go-gen/types"
	slapi "github.com/sudorandom/softlayer-go/slapi"
)

var (
	username = "INSERT_USERNAME"
	apiKey   = "INSERT_API_KEY"
)

// ExampleBasicAPICall demonstrates using a type provided by softlayer-go-gen
func ExampleClient_Call_basicAPICall() {
	client := slapi.Client{
		Endpoint: "https://api.softlayer.com/rest/v3.1/",
		Auth:     slapi.BasicAuth{Username: username, APIKey: apiKey},
	}

	req := softlayer_account.GetObject()
	req.Mask = `mask[id,companyName]`

	// Make API call with basic account type
	basicAccount := &gentypes.SoftLayer_Account{}
	err := client.Call(req, basicAccount)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Basic:")
	log.Println(basicAccount.Id)
	log.Println(basicAccount.CompanyName)
}

// ExampleCustomAPICall demonstrates using a user-defined type
func ExampleClient_Call_customAPICall() {
	client := slapi.Client{
		Endpoint: "https://api.softlayer.com/rest/v3.1/",
		Auth:     slapi.BasicAuth{Username: username, APIKey: apiKey},
	}

	req := softlayer_account.GetObject()
	req.Mask = `mask[id,virtualGuests,companyName]`

	// Make API call with a custom type, myCustomAccount
	type myCustomAccount struct {
		ID          int64  `json:"id"`
		CompanyName string `json:"companyName"`

		VirtualGuests []*gentypes.SoftLayer_Virtual_Guest `json:"virtualGuests"`
	}

	customAccount := &myCustomAccount{}
	err := client.Call(req, customAccount)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Custom Extended:")
	log.Println(customAccount.ID)
	log.Println(customAccount.CompanyName)
	log.Println(customAccount.VirtualGuests)
}


text:
package org.jenkinsci.plugins.github_integration.junit;

import antlr.ANTLRException;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.coravy.hudson.plugins.github.GithubProjectProperty;
import com.github.kostyasha.github.integration.branch.GitHubBranchTrigger;
import com.github.kostyasha.github.integration.branch.events.GitHubBranchEvent;
import com.github.kostyasha.github.integration.branch.events.impl.GitHubBranchCreatedEvent;
import hudson.util.Secret;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.jenkinsci.plugins.github.GitHubPlugin;
import org.jenkinsci.plugins.github.config.GitHubPluginConfig;
import org.jenkinsci.plugins.github.config.GitHubServerConfig;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRTrigger;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRTriggerMode;
import org.jenkinsci.plugins.github.pullrequest.events.GitHubPREvent;
import org.jenkinsci.plugins.github.pullrequest.events.impl.GitHubPRCommitEvent;
import org.jenkinsci.plugins.github.pullrequest.events.impl.GitHubPROpenEvent;
import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.JenkinsRule;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import static com.jayway.awaitility.Awaitility.await;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.commons.io.FileUtils.writeStringToFile;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.jenkinsci.plugins.github.config.GitHubServerConfig.loginToGithub;
import static org.jenkinsci.plugins.github_integration.awaitility.GHBranchAppeared.ghBranchAppeared;
import static org.jenkinsci.plugins.github_integration.awaitility.GHFromServerConfigAppeared.ghAppeared;
import static org.jenkinsci.plugins.github_integration.awaitility.GHRepoAppeared.ghRepoAppeared;
import static org.jenkinsci.plugins.github_integration.awaitility.GHRepoDeleted.ghRepoDeleted;

/**
 * @author Kanstantsin Shautsou
 */
public class GHRule implements TestRule {
    private static final Logger LOG = LoggerFactory.getLogger(GHRule.class);
    public static final String BRANCH1 = "branch-1";
    public static final String BRANCH2 = "branch-2";

    public static final String GH_TOKEN = System.getProperty("GH_TOKEN", System.getenv("GH_TOKEN"));

    private GHRepository ghRepo;
    private GitHub gitHub;
    private Git git;

    @CheckForNull
    private GitHubServerConfig gitHubServerConfig;

    @Nonnull
    private static JenkinsRule jRule;

    @Nonnull
    private static TemporaryFolder temporaryFolder;
    private File gitRootDir;

    public GHRule(JenkinsRule jRule, TemporaryFolder temporaryFolder) {
        this.jRule = jRule;
        this.temporaryFolder = temporaryFolder;
    }

    /**
     * github connection from configured github-plugin from global configuration.
     */
    public GitHub getGitHub() {
        return gitHub;
    }

    /**
     * GitHub repository that was created in {@link #before}.
     */
    public GHRepository getGhRepo() {
        return ghRepo;
    }

    @Override
    public Statement apply(final Statement base, final Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                before(description);
                try {
                    base.evaluate();
                } finally {
                    after();
                }
            }
        };
    }

    private void after() {
        try {
            ghRepo.delete();
        } catch (IOException e) {
            LOG.error("Can't delete {}", ghRepo.getFullName(), e);
        }
    }

    public void before(Description description) throws IOException, GitAPIException, URISyntaxException, InterruptedException {
        String repoName = description.getClassName() + "-" + description.getMethodName();
        assertThat("Specify GH_TOKEN variable", GH_TOKEN, notNullValue());

        //reuse github client for GitHub preparation
        gitHubServerConfig = prepareGitHubPlugin();
        //FIXME no idea why github-plugin doesn't find configuration without delay, try delay
        await().timeout(20, SECONDS)
                .until(ghAppeared(gitHubServerConfig));

        gitHub = loginToGithub().apply(gitHubServerConfig);

        assertThat("Specify right GH_TOKEN variable!", gitHub, notNullValue());
        LOG.debug(gitHub.getRateLimit().toString());

        ghRepo = gitHub.getMyself().getRepository(repoName);
        if (ghRepo != null) {
            LOG.info("Deleting {}", ghRepo.getHtmlUrl());
            ghRepo.delete();
            await().pollInterval(3, SECONDS)
                    .timeout(120, SECONDS)
                    .until(ghRepoDeleted(gitHub, ghRepo.getFullName()));
        }

        ghRepo = gitHub.createRepository(repoName, "", "", true);
        LOG.info("Created {}", ghRepo.getHtmlUrl());

        await().pollInterval(2, SECONDS)
                .timeout(120, SECONDS)
                .until(ghRepoAppeared(gitHub, ghRepo.getFullName()));

        // prepare git
        gitRootDir = temporaryFolder.newFolder();

        git = Git.init().setDirectory(gitRootDir).call();

        writeStringToFile(new File(gitRootDir, "README.md"), "Test repo");
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage("Initial commit").call();

        final RefSpec refSpec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");

        final StoredConfig storedConfig = git.getRepository().getConfig();
        final RemoteConfig origin = new RemoteConfig(storedConfig, "origin");
        origin.addURI(new URIish(ghRepo.gitHttpTransportUrl()));
        origin.addPushRefSpec(refSpec);
        origin.update(storedConfig);
        storedConfig.save();

        commitFileToBranch(BRANCH1, BRANCH1 + ".file", "content", "commit for " + BRANCH1);

        commitFileToBranch(BRANCH2, BRANCH2 + ".file", "content", "commit for " + BRANCH2);

        git.checkout().setName("master").call();

        pushAll();
    }

    public void pushAll() throws GitAPIException {
        git.push()
                .setPushAll()
                .setProgressMonitor(new TextProgressMonitor())
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GH_TOKEN, ""))
                .call();
    }

    /**
     * Prepare global GitHub plugin configuration.
     * Nothing specific to job.
     */
    public static GitHubServerConfig prepareGitHubPlugin() {
        // prepare global jRule settings
        final StringCredentialsImpl cred = new StringCredentialsImpl(
                CredentialsScope.GLOBAL,
                null,
                "description",
                Secret.fromString(GH_TOKEN)
        );

        SystemCredentialsProvider.getInstance().getCredentials().add(cred);

        final GitHubPluginConfig gitHubPluginConfig = GitHubPlugin.configuration();

        final List<GitHubServerConfig> gitHubServerConfigs = new ArrayList<>();
        final GitHubServerConfig gitHubServerConfig = new GitHubServerConfig(cred.getId());
        gitHubServerConfig.setManageHooks(false);
        gitHubServerConfig.setClientCacheSize(0);
        gitHubServerConfigs.add(gitHubServerConfig);

        gitHubPluginConfig.setConfigs(gitHubServerConfigs);

        return gitHubServerConfig;
    }

    public static GitHubPRTrigger getPreconfiguredPRTrigger() throws ANTLRException {
        final ArrayList<GitHubPREvent> gitHubPREvents = new ArrayList<>();
        gitHubPREvents.add(new GitHubPROpenEvent());
        gitHubPREvents.add(new GitHubPRCommitEvent());

        final GitHubPRTrigger gitHubPRTrigger = new GitHubPRTrigger("", GitHubPRTriggerMode.CRON, gitHubPREvents);
        gitHubPRTrigger.setPreStatus(true);

        return gitHubPRTrigger;
    }

    public static GitHubBranchTrigger getDefaultBranchTrigger() throws ANTLRException {
        final ArrayList<GitHubBranchEvent> githubEvents = new ArrayList<>();
        githubEvents.add(new GitHubBranchCreatedEvent());

        final GitHubBranchTrigger githubTrigger = new GitHubBranchTrigger("", GitHubPRTriggerMode.CRON, githubEvents);
        githubTrigger.setPreStatus(true);

        return githubTrigger;
    }

    public static GithubProjectProperty getPreconfiguredProperty(GHRepository ghRepo) {
        return new GithubProjectProperty(ghRepo.getHtmlUrl().toString());
    }

    public void commitFileToBranch(String branch, String fileName, String content, String commitMessage)
            throws IOException, GitAPIException {
        final String beforeBranch = git.getRepository().getBranch();
        final List<Ref> refList = git.branchList().call();
        boolean exist = false;
        for (Ref ref : refList) {
            if (ref.getName().endsWith(branch)) {
                exist = true;
                break;
            }
        }
        if (!exist) {
            git.branchCreate().setName(branch).call();
        }

        git.checkout().setName(branch).call();

        writeStringToFile(new File(gitRootDir, fileName), content);
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage(commitMessage).call();
        git.push()
                .setPushAll()
                .setProgressMonitor(new TextProgressMonitor())
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GH_TOKEN, ""))
                .call();
        git.checkout().setName(beforeBranch).call();

        await().pollInterval(3, SECONDS)
                .timeout(120, SECONDS)
                .until(ghBranchAppeared(getGhRepo(), branch));
    }

//    because org.jenkinsci.plugins.github.internal.GitHubLoginFunction$OkHttpConnector is private
//    public static void flushCache(GitHub gitHub) {
//        try {
//            OkHttpConnector okHttpConnector = (OkHttpConnector) gitHub.getConnector();
//            Field field = okHttpConnector.getClass().getField("urlFactory");
//            field.setAccessible(true);
//            OkUrlFactory urlFactory = (OkUrlFactory) field.get(okHttpConnector);
//            urlFactory.client().getCache().flush();
//        } catch (Exception ex) {
//            Throwables.propagate(ex);
//        }
//        LOG.debug("Flushed GitHub connector cache");
//    }
}


text:
using UnityEngine;
using System.Collections;

public class ProjectileLauncher : MonoBehaviour {

	public Rigidbody2D rocket;				// Prefab of the rocket.
	public float speed = 20f;				// The speed the rocket will fire at.

	private PlayerController playerCtrl;		// Reference to the PlayerControl script.
	private Animator anim;					// Reference to the Animator component.

	void Awake()
	{
		// Setting up the references.
		if(anim!=null)
			anim = transform.root.gameObject.GetComponent<Animator>();
		playerCtrl = transform.root.GetComponent<PlayerController>();
	}

	void Update ()
	{
		// If the fire button is pressed...
		if(Input.GetButtonDown("Fire1"))
		{
			// ... set the animator Shoot trigger parameter and play the audioclip.
			if(anim!=null)
				anim.SetTrigger("Shoot");
			if(audio!=null)
				audio.Play();

			//Rigidbody2D bulletInstance = Instantiate(rocket, transform.position,
			//                                         Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
			//bulletInstance.velocity = new Vector2(speed, 0);
			//bulletInstance.velocity = transform.right*speed;

			// If the player is facing right...
			if(playerCtrl.isFacingRight)
			{
				// ... instantiate the rocket facing right and set it's velocity to the right.
				Rigidbody2D bulletInstance = Instantiate(rocket, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
				bulletInstance.velocity = new Vector2(speed, 0);
			}
			else
			{
				// Otherwise instantiate the rocket facing left and set it's velocity to the left.
				Rigidbody2D bulletInstance = Instantiate(rocket, transform.position, Quaternion.Euler(new Vector3(0,0,180f))) as Rigidbody2D;
				bulletInstance.velocity = new Vector2(-speed, 0);
			}
		}
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors
{
    using DotNetNuke.Services.Installer.Packages;
    using Newtonsoft.Json;

    [JsonObject]
    public class ExtensionLanguagePackageDetailDto : CoreLanguagePackageDetailDto
    {
        public ExtensionLanguagePackageDetailDto()
        {
        }

        public ExtensionLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package)
        {
        }

        [JsonProperty("dependentPackageId")]
        public int DependentPackageId { get; set; }
    }
}


text:
<?php

namespace common\widgets;

use common\models\User;
use Yii;

class Widget extends \yii\bootstrap\Widget {

	/**
	 * @var User
	 */
	public $user;

	/**
	 * @param      $controller
	 * @param null $action
	 * @param null $params
	 *
	 * @return string
	 */
	public static function isActive($controller, $action = null, $params = null, $text = 'active') {
		$string = '';
		if (!is_array($controller)) {
			$controller = [$controller];
		}
		if (!is_array($action) && $action != null) {
			$action = [$action];
		}
		if (!is_array($params) && $params != null) {
			$params = [$params];
		}
		if (in_array(Yii::$app->controller->id, $controller)) {
			if ($action == null || ($action != null && in_array(Yii::$app->controller->action->id, $action))) {
				if ($params == null || in_array($params, array_chunk(Yii::$app->controller->actionParams, 1, true))) {
					$string = $text;
				}
			}
		}
		return $string;
	}

	/**
	 * {@inheritDoc}
	 */
	public function init() {
		parent::init();
		$this->user = Yii::$app->user->getIdentity();
	}
}


text:
class User extends React.Component {
  render () {
    return (
      User {this.props.index}
    )
  }
}

User.propTypes = {
  index: React.PropTypes.number.isRequired
}

class Fixture extends React.Component {
  render () {
    return (

<User index={1} />

<User index={2} />

    )
  }
}

const it = createTest(<Fixture />)

describe('#contain', () => {
  describe('(node)', () => {
    it('passes when the actual matches the expected', (wrapper) => {
      expect(wrapper).to.contain(<User index={1} />)
      expect(wrapper).to.contain(<User index={2} />)
    }, { render: false })

    it('passes negated when the actual does not match the expected', (wrapper) => {
      expect(wrapper).to.not.contain(<User index={3} />)
    }, { render: false })

    it('fails when the actual does not match the expected', (wrapper) => {
      expect(() => {
        expect(wrapper).to.contain(<User index={3} />)
      }).to.throw('to contain <User index={3} />')

      expect(() => {
        expect(wrapper).to.not.contain(<User index={2} />)
      }).to.throw('not to contain <User index={2} />')
    }, { render: false })

    it('fails when the actual is undefined', () => {
      expect(() => {
        expect(undefined).to.contain(<User index={1} />)
      }).to.throw()
    })
  })
})


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// QuickBook Example

// Copyright (c) 2014 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//[buffer_end_flat
//` Shows how the end_flat strategy can be used as a EndStrategy to create flat ends

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/geometries.hpp>
/*<-*/ #include "../examples_utils/create_svg_buffer.hpp" /*->*/

int main()
{
    typedef boost::geometry::model::d2::point_xy<double> point;
    typedef boost::geometry::model::linestring<point> linestring;
    typedef boost::geometry::model::polygon<point> polygon;

    // Declare the flat-end strategy
    boost::geometry::strategy::buffer::end_flat end_strategy;

    // Declare other strategies
    boost::geometry::strategy::buffer::distance_symmetric<double> distance_strategy(1.0);
    boost::geometry::strategy::buffer::side_straight side_strategy;
    boost::geometry::strategy::buffer::join_round join_strategy;
    boost::geometry::strategy::buffer::point_circle point_strategy;

    // Declare/fill a multi linestring
    boost::geometry::model::multi_linestring<linestring> ml;
    boost::geometry::read_wkt("MULTILINESTRING((3 5,5 10,7 5),(7 7,11 10,15 7,19 10))", ml);

    // Create the buffered geometry with flat ends
    boost::geometry::model::multi_polygon<polygon> result;
    boost::geometry::buffer(ml, result,
                distance_strategy, side_strategy,
                join_strategy, end_strategy, point_strategy);
    /*<-*/ create_svg_buffer("buffer_end_flat.svg", ml, result); /*->*/

    return 0;
}

//]


text:
import wx

class MenuEventFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Menus', size=(300, 200))
        menuBar = wx.MenuBar()
        menu1 = wx.Menu()
        menuItem = menu1.Append(-1, "&Open")
        menuBar.Append(menu1, "&File")
        self.SetMenuBar(menuBar)
        self.Bind(wx.EVT_MENU, self.OnCloseMe, menuItem)
    def OnCloseMe(self, event):
        self.Close(True)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = MenuEventFrame(parent=None, id=-1)
    frame.Show()
    app.MainLoop()


text:
package io.jenetics.jpx;

import static java.util.Objects.requireNonNull;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Franz Wilhelmstötter
 * @version 3.0
 * @since 3.0
 */
final class NonCloseableInputStream extends InputStream {

	private final InputStream _input;

	NonCloseableInputStream(final InputStream input) {
		_input = requireNonNull(input);
	}

	@Override
	public int read() throws IOException {
		return _input.read();
	}

	@Override
	public int read(byte[] b) throws IOException {
		return _input.read(b);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		return _input.read(b, off, len);
	}

	@Override
	public byte[] readAllBytes() throws IOException {
		return _input.readAllBytes();
	}

	@Override
	public byte[] readNBytes(int len) throws IOException {
		return _input.readNBytes(len);
	}

	@Override
	public int readNBytes(byte[] b, int off, int len) throws IOException {
		return _input.readNBytes(b, off, len);
	}

	@Override
	public long skip(long n) throws IOException {
		return _input.skip(n);
	}

	@Override
	public void skipNBytes(long n) throws IOException {
		_input.skipNBytes(n);
	}

	@Override
	public int available() throws IOException {
		return _input.available();
	}

	@Override
	public void close() {
	}

	@Override
	public void mark(int readlimit) {
		_input.mark(readlimit);
	}

	@Override
	public void reset() throws IOException {
		_input.reset();
	}

	@Override
	public boolean markSupported() {
		return _input.markSupported();
	}

	@Override
	public long transferTo(OutputStream out) throws IOException {
		return _input.transferTo(out);
	}

}


text:
require "spec_helper"

describe Facter::Util::Fact do
  before {
    Facter.clear
  }

  describe "java_patch_level" do
    context "if java is installed" do
      context 'returns java patch version extracted from java_version fact' do
        before :each do
          Facter.fact(:java_version).stubs(:value).returns('1.7.0_71')
        end
        it do
          Facter.fact(:java_patch_level).value.should == "71"
        end
      end
    end

    context "if java is installed" do
      context 'returns java patch version extracted from java_version fact' do
        before :each do
          Facter.fact(:java_version).stubs(:value).returns(nil)
        end
        it do
          Facter.fact(:java_patch_level).value.should be_nil
        end
      end
    end
  end
end


text:
/**
 * @fileoverview The junk-drawer of type definitions for files that do not pass type checking yet.
 * Shame! Shame! Shame! Avoid adding to this.
 */

declare module '#builtins/amp-layout/build-dom' {
  import {BuildDom} from '#compiler/types';
  export const buildDom: BuildDom;
}

declare module 'extensions/amp-fit-text/0.1/build-dom' {
  import {BuildDom} from '#compiler/types';
  export const buildDom: BuildDom;
}

declare module '#core/dom' {
  export const copyChildren: (from: Node, to: Node) => void;
  export const removeChildren: (node: Node) => void;
  export const isServerRendered: (node: Node) => boolean;
}

declare module '#core/dom/query' {
  export const realChildNodes: (node: Node) => Element[];
}

declare module '#core/dom/layout' {
  export const applyFillContent: (
    node: Node,
    replacedContent?: boolean
  ) => void;
}

declare module '#core/static-layout' {
  export const applyStaticLayout: (node: Node) => void;
}

declare module '#core/dom/css-selectors' {
  export const escapeCssSelectorIdent: (ident: string) => string;
}


text: amp -k team member rm user | grep -q "user"


text:
package org.jeecgframework.core.common.dao.jdbc;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.poi.ss.formula.functions.T;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Repository;

/**
 *
 * @author  张代浩
 *
 */
@Repository("jdbcDao")
public class JdbcDao extends SimpleJdbcTemplate{

	/**
	 * 数据库类型
	 */
	public static final String DATABSE_TYPE_MYSQL ="mysql";
	public static final String DATABSE_TYPE_POSTGRE ="postgresql";
	public static final String DATABSE_TYPE_ORACLE ="oracle";
	public static final String DATABSE_TYPE_SQLSERVER ="sqlserver";
	/**
	 * 分页SQL
	 */
	public static final String MYSQL_SQL = "select * from ( {0}) sel_tab00 limit {1},{2}";         //mysql
	public static final String POSTGRE_SQL = "select * from ( {0}) sel_tab00 limit {2} offset {1}";//postgresql
	public static final String ORACLE_SQL = "select * from (select row_.*,rownum rownum_ from ({0}) row_ where rownum <= {1}) where rownum_>{2}"; //oracle
	public static final String SQLSERVER_SQL = "select * from ( select row_number() over(order by tempColumn) tempRowNumber, * from (select top {1} tempColumn = 0, {0}) t ) tt where tempRowNumber > {2}"; //sqlserver

	@Autowired
	public JdbcDao(DataSource dataSource) {
		super(dataSource);
	}

	/**
	 * 根据sql语句,返回对象集合
	 * @param sql语句(参数用冒号加参数名,例如select * from tb where id=:id)
	 * @param clazz类型
	 * @param parameters参数集合(key为参数名,value为参数值)
	 * @return bean对象集合
	 */
	public List find(String sql,Class clazz,Map parameters){
		return super.find(sql,clazz,parameters);
	}

	/**
	 * 根据sql语句,返回对象
	 * @param sql语句(参数用冒号加参数名,例如select * from tb where id=:id)
	 * @param clazz类型
	 * @param parameters参数集合(key为参数名,value为参数值)
	 * @return bean对象
	 */
	public Object findForObject(String sql,Class clazz,Map parameters){
		return super.findForObject(sql, clazz, parameters);
	}

	/**
	 * 根据sql语句,返回数值型返回结果
	 * @param sql语句(参数用冒号加参数名,例如select count(*) from tb where id=:id)
	 * @param parameters参数集合(key为参数名,value为参数值)
	 * @return bean对象
	 */
	public long findForLong(String sql,Map parameters){
		return super.findForLong(sql, parameters);
	}

	/**
	 * 根据sql语句,返回Map对象,对于某些项目来说,没有准备Bean对象,则可以使用Map代替Key为字段名,value为值
	 * @param sql语句(参数用冒号加参数名,例如select count(*) from tb where id=:id)
	 * @param parameters参数集合(key为参数名,value为参数值)
	 * @return bean对象
	 */
	public Map findForMap(String sql,Map parameters){
		return super.findForMap(sql, parameters);
	}

	/**
	 * 根据sql语句,返回Map对象集合
	 * @see findForMap
	 * @param sql语句(参数用冒号加参数名,例如select count(*) from tb where id=:id)
	 * @param parameters参数集合(key为参数名,value为参数值)
	 * @return bean对象
	 */
	public List<Map<String,Object>> findForListMap(String sql,Map parameters){
		return super.findForListMap(sql, parameters);
	}

	/**
	 * 执行insert,update,delete等操作

	 * 例如insert into users (name,login_name,password) values(:name,:loginName,:password)

	 * 参数用冒号,参数为bean的属性名
	 * @param sql
	 * @param bean
	 */
	public int executeForObject(String sql,Object bean){
		return super.executeForObject(sql, bean);
	}

	/**
	 * 执行insert,update,delete等操作

	 * 例如insert into users (name,login_name,password) values(:name,:login_name,:password)

	 * 参数用冒号,参数为Map的key名
	 * @param sql
	 * @param parameters
	 */
	public int executeForMap(String sql,Map parameters){
		return super.executeForMap(sql, parameters);
	}
	/*
	 * 批量处理操作
	 * 例如:update t_actor set first_name = :firstName, last_name = :lastName where id = :id
	 * 参数用冒号
	 */
	public int[] batchUpdate(final String sql,List<Object[]> batch ){
        return super.batchUpdate(sql,batch);
	}

	/**
	 * 使用指定的检索标准检索数据并分页返回数据
	 */
	public List<Map<String, Object>> findForJdbc(String sql, int page, int rows) {
		//封装分页SQL
		sql = jeecgCreatePageSql(sql,page,rows);
		return this.jdbcTemplate.queryForList(sql);
	}

	public List<Map<String, Object>> findForJdbc(String sql, Object... objs) {
		return this.jdbcTemplate.queryForList(sql,objs);
	}

	/**
	 * 使用指定的检索标准检索数据并分页返回数据
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public List<T> findObjForJdbc(String sql, int page, int rows,Class<T> clazz) {
		List<T> rsList = new ArrayList<T>();
		//封装分页SQL
		sql = jeecgCreatePageSql(sql,page,rows);
		List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);

		T po = null;
		for(Map<String,Object> m:mapList){
			try {
				po = clazz.newInstance();
				MyBeanUtils.copyMap2Bean_Nobig(po, m);
				rsList.add(po);
			}  catch (Exception e) {
				e.printStackTrace();
			}
		}
		return rsList;
	}

	/**
	 * 使用指定的检索标准检索数据并分页返回数据-采用预处理方式
	 *
	 * @param criteria
	 * @param firstResult
	 * @param maxResults
	 * @return
	 * @throws DataAccessException
	 */
	public  List<Map<String, Object>>  findForJdbcParam(String  sql,  int page, int rows,Object... objs){
		//封装分页SQL
		sql = jeecgCreatePageSql(sql,page,rows);
		return jdbcTemplate.queryForList(sql,objs);
	}

	public Map<String, Object> findOneForJdbc(String sql, Object... objs) {
		try{
			return this.jdbcTemplate.queryForMap(sql, objs);
		}catch (EmptyResultDataAccessException e) {
		    return null;
		}
	}

	/**
	 * 使用指定的检索标准检索数据并分页返回数据For JDBC
	 */
	public Long getCountForJdbc(String  sql) {
		return  jdbcTemplate.queryForLong(sql);
	}
	/**
	 * 使用指定的检索标准检索数据并分页返回数据For JDBC-采用预处理方式
	 *
	 */
	public Long getCountForJdbcParam(String  sql,Object... objs) {
		return  jdbcTemplate.queryForLong(sql, objs);
	}

	public Integer executeSql2(String sql,List<Object> param) {
		return this.jdbcTemplate.update(sql,param);
	}

	public Integer executeSql(String sql, Object... param) {
		return this.jdbcTemplate.update(sql,param);
	}

	public Integer countByJdbc(String sql, Object... param) {
		return this.jdbcTemplate.queryForInt(sql, param);
	}

	/**
	 * 按照数据库类型,封装SQL
	 */
	public static String jeecgCreatePageSql(String sql, int page, int rows){
		int beginNum = (page - 1) * rows;
		String[] sqlParam = new String[3];
		sqlParam[0] = sql;
		sqlParam[1] = beginNum+"";
		sqlParam[2] = rows+"";
		if(ResourceUtil.getJdbcUrl().indexOf(DATABSE_TYPE_MYSQL)!=-1){
			sql = MessageFormat.format(MYSQL_SQL, sqlParam);
		}else if(ResourceUtil.getJdbcUrl().indexOf(DATABSE_TYPE_POSTGRE)!=-1){
			sql = MessageFormat.format(POSTGRE_SQL, sqlParam);
		}else {
			int beginIndex = (page-1)*rows;
			int endIndex = beginIndex+rows;
			sqlParam[2] = Integer.toString(beginIndex);
			sqlParam[1] = Integer.toString(endIndex);
			if(ResourceUtil.getJdbcUrl().indexOf(DATABSE_TYPE_ORACLE)!=-1) {
				sql = MessageFormat.format(ORACLE_SQL, sqlParam);
			} else if(ResourceUtil.getJdbcUrl().indexOf(DATABSE_TYPE_SQLSERVER)!=-1) {
				sqlParam[0] = sql.substring(getAfterSelectInsertPoint(sql));
				sql = MessageFormat.format(SQLSERVER_SQL, sqlParam);
			}
		}
		return sql;
	}
	private static int getAfterSelectInsertPoint(String sql) {
	    int selectIndex = sql.toLowerCase().indexOf("select");
	    int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
	    return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
    }
}


text:
<?php

namespace Tms\Bundle\RestBundle\Formatter;

/**
 * DoctrineMongoDbCollectionHypermediaFormatter is the doctrine mongoDB collection formatter.
 *
 * @author Thomas Prelot <thomas.prelot@tessi.fr>
 */
class DoctrineMongoDbCollectionHypermediaFormatter extends AbstractDoctrineCollectionHypermediaFormatter
{
    /**
     * {@inheritdoc }
     */
    protected function addSortToQueryBuilder()
    {
        $this->queryBuilder->sort($this->sort);
    }

    /**
     * {@inheritdoc }
     */
    protected function addPaginationToQueryBuilder()
    {
        $this->queryBuilder->skip($this->computeOffsetWithPage());
        $this->queryBuilder->limit($this->limit);
    }

    /**
     * {@inheritdoc }
     */
    protected function addCriteriaToQueryBuilder()
    {
        if (!$this->criteria) {
            return;
        }

        $class = new \ReflectionClass($this->queryBuilder);

        if ($class->hasMethod('match')) {
            foreach ($this->criteria as $criterionName => $criterionValue) {
                $this->queryBuilder->match($criterionName, $criterionValue);
            }
        } else {
            foreach ($this->criteria as $criterionName => $criterionValue) {
                $this->queryBuilder->field($criterionName)->equals($criterionValue);
            }
        }
    }

    /**
     * {@inheritdoc }
     */
    protected function prepareCountQueryBuilder()
    {
        return $this->queryBuilder;
    }

    /**
     * {@inheritdoc }
     */
    protected function countObjects()
    {
        return $this->prepareCountQueryBuilder()->getQuery()->execute()->count();
    }
}


text:
#include "postgres.h"

#include "miscadmin.h"
#include "storage/lwlock.h"
#include "storage/spin.h"

#ifdef HAVE_SPINLOCKS

/*
 * Report number of semaphores needed to support spinlocks.
 */
int
SpinlockSemas(void)
{
	return 0;
}
#else							/* !HAVE_SPINLOCKS */

/*
 * No TAS, so spinlocks are implemented as PGSemaphores.
 */

/*
 * Report number of semaphores needed to support spinlocks.
 */
int
SpinlockSemas(void)
{
	/*
	 * It would be cleaner to distribute this logic into the affected modules,
	 * similar to the way shmem space estimation is handled.
	 *
	 * plus one for each LWLock and one for each buffer header,plus
	 * NUM_ATOMICS_SEMAPHORES for atomic api(without sufficient spinlock
	 * and/or atomics support)
	 */
	return NumLWLocks() + NBuffers + 10 + NUM_ATOMICS_SEMAPHORES;
}

/*
 * s_lock.h hardware-spinlock emulation
 */

void
s_init_lock_sema(volatile slock_t *lock)
{
	PGSemaphoreCreate((PGSemaphore) lock);
}

void
s_unlock_sema(volatile slock_t *lock)
{
	PGSemaphoreUnlock((PGSemaphore) lock);
}

bool
s_lock_free_sema(volatile slock_t *lock)
{
	/* We don't currently use S_LOCK_FREE anyway */
	elog(ERROR, "spin.c does not support S_LOCK_FREE()");
	return false;
}

int
tas_sema(volatile slock_t *lock)
{
	/* Note that TAS macros return 0 if *success* */
	return !PGSemaphoreTryLock((PGSemaphore) lock);
}

#endif   /* !HAVE_SPINLOCKS */


text:
set -u
set -e

# make directories to work from
mkdir -p certs/{server,client,ca,tmp}

# Create your very own Root Certificate Authority
openssl genrsa \
  -out certs/ca/my-root-ca.key.pem \
  2048

# Self-sign your Root Certificate Authority
# Since this is private, the details can be as bogus as you like
openssl req \
  -x509 \
  -new \
  -sha256 \
  -nodes \
  -key certs/ca/my-root-ca.key.pem \
  -days 3652 \
  -out certs/ca/my-root-ca.crt.pem \
  -subj "/C=US/ST=Utah/L=Provo/O=ACME Signing Authority Inc/CN=example.com"

# NOTE
# -nodes means "no-des" which means "no passphrase"
# -days 3652 means that this example will break about 10 years from now


text:
from mock import Mock, patch
import unittest

from pumphouse.tasks.quota import base

class TestBaseQuota(unittest.TestCase):
    def setUp(self):
        self.tenant_id = Mock(name="tenant_id")
        self.cloud = Mock(name="cloud")
        self.tenant_info = {
            "id": self.tenant_id
        }
        self.quota_info = {
            "a": "1",
            "b": "2"
        }

    def assertRetrieveQuota(self, mock_called, info):
        mock_called.assert_called_once_with(self.tenant_id)
        self.assertEquals(info, mock_called.return_value._info)

    def assertEnsureQuota(self, mock_called, id, info):
        mock_called.assert_called_once_with(
            id,
            a="1",
            b="2"
        )
        self.assertEqual(info, mock_called.return_value._info)

class TestRetrieveTenantQuota(TestBaseQuota):
    @patch.object(base.RetrieveTenantQuota, "client")
    def test_execute(self, mock_client):
        retrieve_tenant_quota = base.RetrieveTenantQuota(self.cloud)
        self.assertRetrieveQuota(mock_client.quotas.get,
                                 retrieve_tenant_quota.execute(self.tenant_id))

class TestRetrieveDefaultQuota(TestBaseQuota):
    @patch.object(base.RetrieveDefaultQuota, "client")
    def test_execute(self, mock_client):
        retrieve_default_quota = base.RetrieveDefaultQuota(self.cloud)
        self.assertRetrieveQuota(
            mock_client.quotas.defaults,
            retrieve_default_quota.execute(self.tenant_id)
        )

class TestEnsureTenantQuota(TestBaseQuota):
    @patch.object(base.EnsureTenantQuota, "client")
    def test_execute(self, mock_client):
        ensure_tenant_quota = base.EnsureTenantQuota(self.cloud)
        self.assertEnsureQuota(mock_client.quotas.update,
                               self.tenant_id,
                               ensure_tenant_quota.execute(self.quota_info,
                                                           self.tenant_info))

class TestEnsureDefaultQuota(TestBaseQuota):
    @patch.object(base.EnsureDefaultQuota, "client")
    def test_execute(self, mock_client):
        ensure_default_quota = base.EnsureDefaultQuota(self.cloud)
        self.assertEnsureQuota(mock_client.quota_classes.update,
                               "default",
                               ensure_default_quota.execute(self.quota_info))


text:
namespace TeamElderberryProject.Interfaces
{
    public interface IIncome
    {
    }
}


text:
New service for {{provider.name}}

{{service.name}}

  Service ID: {{service.uid || '«new»'}}

  Provider: {{provider.name}} ({{template.human_name}})

        <ag-ui-spinner size="22" color="white" style="vertical-align: top;" ng-if="statusMessage.isInfo" style="margin-right: 10px;"></ag-ui-spinner>
        {{statusMessage.text}}

          {{additionalInfo}}

    <form class="ag__form" ng-if="!hasBeenDeleted">

        Name:
        <input ng-model="service.name" type="text" class="form-control" id="ServiceNameInput">

        URL path:
        {{provider.baseUrl}}{{service.path}}
        <input ng-model="service.path" type="text" class="form-control" id="ServicePathInput" placeholder="car">

        Service method:

          <select ng-change="setAction(actionName)" ng-model="actionName" ng-options="action as method for (action, method) in actionToMethod"></select>

      <ag-headers headers="service.headers" for-resource="{{true}}"></ag-headers>

    </form>

  <button ng-disabled="isLoading" class="btn btn-danger pull-left" ng-click="remove()" ng-if="!hasBeenDeleted && !isNew()">Remove service</button>
  <button ng-disabled="isLoading" class="btn btn-primary" ng-click="save()" ng-if="!hasBeenDeleted && isNew()">Create service</button>
  <button ng-disabled="isLoading" class="btn btn-primary" ng-click="save()" ng-if="!hasBeenDeleted && !isNew()">Update service</button>
  <button ng-disabled="isLoading" class="btn btn-default" ng-click="cancel()">Close</button>


text:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

namespace WebApplication2
{
	/// <summary>
	/// Called by ProcRes.  Used for planning.
	/// </summary>
	public partial class frmProcRReq : System.Web.UI.Page
	{
		private static string strURL =
			System.Configuration.ConfigurationSettings.AppSettings["local_url"];
		private static string strDB =
			System.Configuration.ConfigurationSettings.AppSettings["local_db"];
		protected System.Web.UI.WebControls.Label Label2;

		public SqlConnection epsDbConn=new SqlConnection(strDB);

		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
            if (!IsPostBack)
            {
                if (Session["MgrName"] == null)
                {
                    lblOrg.Text = Session["OrgName"].ToString();
                }
                else
                {
                    lblOrg.Text = Session["MgrName"].ToString();
                }
                lblService.Text = "Service: " + Session["ServiceName"].ToString();
                lblLoc.Text = "Location: " + Session["LocName"].ToString();

                btnAddNew.Text = "Identify Procurement Need";
                btnAddExisting.Text = "Add from Existing Service Contracts";

                DataGrid1.Columns[0].Visible = false;//Id
                DataGrid1.Columns[1].Visible = true;//ItemName
                if (Session["ResTypesType"].ToString() == "0")//goods
                {
                    lblGS.Text = "Type of Good:  " + Session["ResourceName"].ToString();
                    btnAddExisting.Text = "Add from Existing Goods";
                    DataGrid1.Columns[2].Visible = true;//txtQty
                    DataGrid1.Columns[2].HeaderText = "Qty (" + Session["QtyMeasure"].ToString() + ")";
                }
                else
                {
                    lblGS.Text = "Type of Service:  " + Session["ResourceName"].ToString();
                    btnAddExisting.Text = "Add from Existing Services";
                    DataGrid1.Columns[2].Visible = false;
                }

                DataGrid1.Columns[3].Visible = false;//textbox Price
                DataGrid1.Columns[4].Visible = false;//Cost (Computed)
                DataGrid1.Columns[5].Visible = false;//Qty
                DataGrid1.Columns[6].Visible = false;//Price
                DataGrid1.Columns[7].Visible = false;//Inventory - Owner Organization
                DataGrid1.Columns[8].Visible = true;//Inventory - Location
                DataGrid1.Columns[9].Visible = true;//Inventory - SubLocation
                if (Session["CallerOpt"] == "EM")
                {
                    DataGrid1.Columns[10].Visible = true;//cbxBackup
                }
                else
                {
                    DataGrid1.Columns[10].Visible = false;//cbxBackup
                }
                DataGrid1.Columns[11].Visible = true;//BudgetsId List
                if (Session["PAY"] == null)
                {
                    DataGrid1.Columns[12].Visible = false;
                }
                else if (Session["PAY"].ToString() == "0")
                {
                    DataGrid1.Columns[0].Visible = false;
                }
                DataGrid1.Columns[13].Visible = true;//btnDelete
                DataGrid1.Columns[14].Visible = false;//BackupFlag
                DataGrid1.Columns[15].Visible = false;//BudgetsId

                if (Session["InventoryId"] != null)
                {
                    AddProcRReq();
                    Session["InventoryId"] = null;
                }
                if (Session["ContractIdSel"] != null)
                {
                    AddProcRReq();
                    Session["ContractIdSel"] = null;
                }
                if (Session["PRS"].ToString() == "1")
                {
                    lblDel.Text = "Deliverable: " + Session["EventName"].ToString();
                    lblTask.Text = Session["PJNameS"].ToString() + ": "
                        + Session["ProjName"].ToString()
                        + " (Procedure: " + Session["ProcName"].ToString() + ")";
                }
                else
                {
                    lblDel.Text = "Procedure: " + Session["ProcName"].ToString();
                }
                loadData();
            }
		}
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand);

		}
		#endregion

		private void loadData ()
		{
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "wms_RetrievePSEPRInv";
            cmd.Parameters.Add("@OrgId", SqlDbType.Int);
            cmd.Parameters["@OrgId"].Value = Int32.Parse(Session["OrgId"].ToString());
            cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
            cmd.Parameters["@LocationsId"].Value = Int32.Parse(Session["LocationsId"].ToString());
            cmd.Parameters.Add("@PSEPResID", SqlDbType.Int);
            cmd.Parameters["@PSEPResID"].Value = Int32.Parse(Session["PSEPResID"].ToString());
            if (Session["PRS"].ToString() == "1")
            {
                cmd.Parameters.Add("@ProjectId", SqlDbType.Int);
                cmd.Parameters["@ProjectId"].Value = Int32.Parse(Session["ProjectId"].ToString());
            }

            cmd.Connection = this.epsDbConn;
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds, "ProcS");
            if (ds.Tables["ProcS"].Rows.Count == 0)
            {
                DataGrid1.Visible = false;
                lblContents1.Text = "Note:  There is no resource assigned."
                    + ". Click on 'Add' to assign resources.";
                //lblOrg.Text = "PP" + Session["MgrId"].ToString() + "LL" + Session["LocationsId"].ToString()
                 //   + "PSepResID:" + Session["PSEPResID"].ToString()
                 //   + "PRS:" + Session["PRS"].ToString()  + "Project:" + Session["ProjectId"].ToString();
            }
            Session["ds"] = ds;
            DataGrid1.DataSource = ds;
            DataGrid1.DataBind();
            refreshGrid();

		}
		private void refreshGrid()
		{
			foreach (DataGridItem i in DataGrid1.Items)
			{
                CheckBox cb = (CheckBox)(i.Cells[10].FindControl("cbxBackup"));
                DropDownList dl = (DropDownList) (i.Cells[11].FindControl("lstBudgets"));
                TextBox tQ = (TextBox)(i.Cells[2].FindControl("txtQty"));
                //TextBox tP = (TextBox)(i.Cells[3].FindControl("txtPrice"));

				if (i.Cells[14].Text == "1")
				{
                    cb.Checked = true;
				}

                if (i.Cells[5].Text.StartsWith("&") == false)
                {
                    tQ.Text = i.Cells[5].Text;
                }
                /*if (i.Cells[6].Text.StartsWith("&") == false)
                {
                    tP.Text = i.Cells[6].Text;
                }*/

                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Connection = this.epsDbConn;
                cmd.CommandText = "fms_RetrieveFunds";
                cmd.Parameters.Add("@OrgId", SqlDbType.Int);
                cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
                /*cmd.Parameters.Add("@OrgIdP", SqlDbType.Int);
                cmd.Parameters["@OrgIdP"].Value = Session["OrgIdP"].ToString();
                cmd.Parameters.Add("@LicenseId", SqlDbType.Int);
                cmd.Parameters["@LicenseId"].Value = Session["LicenseId"].ToString();
                cmd.Parameters.Add("@DomainId", SqlDbType.Int);
                cmd.Parameters["@DomainId"].Value = Session["DomainId"].ToString();*/
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds, "Funds");
                dl.DataSource = ds;
                dl.DataMember = "Funds";
                dl.DataTextField = "Name";
                dl.DataValueField = "Id";
                dl.DataBind();

            if (i.Cells[15].Text != "")
            {
                dl.SelectedIndex = dl.Items.IndexOf(dl.Items.FindByValue(i.Cells[15].Text));
            }
			}
		}
		private void updateGrid()
		{
            float r = 1;
            foreach (DataGridItem i in DataGrid1.Items)
            {
                if (r == 0)
                {
                    break;
                }
                CheckBox cb = (CheckBox)(i.Cells[10].FindControl("cbxBackup"));
                DropDownList dl = (DropDownList)(i.Cells[11].FindControl("lstBudgets"));
                TextBox tQ = (TextBox)(i.Cells[2].FindControl("txtQty"));
                //TextBox tP = (TextBox)(i.Cells[3].FindControl("txtPrice"));

                if (Session["ResTypesType"].ToString() == "0" && tQ.Text.Trim() != "")
                {
                    string s = tQ.Text.Trim();
                    bool result = float.TryParse(s, out r);
                    if (r == 0)
                    {
                        lblContents1.Text = "Please enter valid number in the Column titled 'Quantity'.";
                        break;
                    }
                    else
                    {
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "fms_UpdatePSEPResInv";
                    cmd.Connection = this.epsDbConn;
                    cmd.Parameters.Add("@Id", SqlDbType.Int);
                    cmd.Parameters["@Id"].Value = Int32.Parse(i.Cells[0].Text);
                    cmd.Parameters.Add("@BackupFlag", SqlDbType.Int);
                    if (cb.Checked)
                    {
                        cmd.Parameters["@BackupFlag"].Value = 1;
                    }
                    else
                    {
                        cmd.Parameters["@BackupFlag"].Value = 0;
                    }

                    cmd.Parameters.Add("@Budgets", SqlDbType.Int);
                    cmd.Parameters["@Budgets"].Value = Int32.Parse(dl.SelectedItem.Value);
                    cmd.Parameters.Add("@Qty", SqlDbType.Decimal);

                    if (tQ.Text != "")
                    {
                        if (Session["ResTypesType"].ToString() == "0")
                        {
                            cmd.Parameters["@Qty"].Value = decimal.Parse(tQ.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
                        }
                    }
                    /*cmd.Parameters.Add("@Price", SqlDbType.Decimal);
                    if (tP.Text != "")
                    {
                        cmd.Parameters["@Price"].Value = decimal.Parse(tP.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
                    }*/
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                    r = 1;
                    }
                }

                else
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "fms_UpdatePSEPResInv";
                    cmd.Connection = this.epsDbConn;
                    cmd.Parameters.Add("@Id", SqlDbType.Int);
                    cmd.Parameters["@Id"].Value = Int32.Parse(i.Cells[0].Text);
                    cmd.Parameters.Add("@BackupFlag", SqlDbType.Int);
                    if (cb.Checked)
                    {
                        cmd.Parameters["@BackupFlag"].Value = 1;
                    }
                    else
                    {
                        cmd.Parameters["@BackupFlag"].Value = 0;
                    }

                    cmd.Parameters.Add("@BudgetsId", SqlDbType.Int);
                    cmd.Parameters["@BudgetsId"].Value = Int32.Parse(dl.SelectedItem.Value);
                    cmd.Parameters.Add("@Qty", SqlDbType.Decimal);

                    if (tQ.Text != "")
                    {
                        if (Session["ResTypesType"].ToString() == "0")
                        {
                            cmd.Parameters["@Qty"].Value = decimal.Parse(tQ.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
                        }
                    }
                    /*cmd.Parameters.Add("@Price", SqlDbType.Decimal);
                    if (tP.Text != "")
                    {
                        cmd.Parameters["@Price"].Value = decimal.Parse(tP.Text.Trim(), System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands);
                    }*/
                    cmd.Connection.Open();
                    cmd.ExecuteNonQuery();
                    cmd.Connection.Close();
                }
              }
            if (r == 1)
            {
                Exit();
            }
		    }
        /*if (tP.Text.Trim() != "")
                {
                    float r = 0;
                    string s = tP.Text.Trim();
                    bool result = float.TryParse(s, out r);
                    if (r == 0)
                    {
                        lblContents1.Text = "Please enter valid number in the Column titled 'Price'.";
                        break;
                    }
                }*/
           private void AddProcRReq()
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "wms_AddPSEPResInv";
            cmd.Connection = this.epsDbConn;
            cmd.Parameters.Add("@PSEPResId", SqlDbType.Int);
            cmd.Parameters["@PSEPResId"].Value = Session["PSEPResId"].ToString();
            cmd.Parameters.Add("@OrgId", SqlDbType.Int);
            cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
            cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
            cmd.Parameters["@LocationsId"].Value = Session["LocationsId"].ToString();
            if (Session["InventoryId"] != null)
            {
                cmd.Parameters.Add("@InventoryId", SqlDbType.Int);
                cmd.Parameters["@InventoryId"].Value = Session["InventoryId"].ToString();
            }
            if (Session["ContractIdSel"] != null)
            {
                cmd.Parameters.Add("@ContractsId", SqlDbType.Int);
                cmd.Parameters["@ContractsId"].Value = Session["ContractIdSel"].ToString();
            }
            if (Session["PRS"].ToString() == "1")
            {
                cmd.Parameters.Add("@ProjectId", SqlDbType.Int);
                cmd.Parameters["@ProjectId"].Value = Session["ProjectId"].ToString();
            }
            cmd.Parameters.Add("@BudgetsId", SqlDbType.Int);
            cmd.Parameters["@BudgetsId"].Value = 5;

            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
        }
		private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			if (e.CommandName == "Update")
			{
				Session["CPPR"]="frmProcRReq";
				Session["btnAction"]="Update";
				Session["ProcProcureId"]=e.Item.Cells[0].Text;
				Response.Redirect (strURL + "frmUpdProcPReq.aspx?");
			}
			else if (e.CommandName == "Pay")
			{
				Session["CPay"]="frmProcRReq";
				Session["ProcProcuresId"] = e.Item.Cells[0].Text;
				Response.Redirect (strURL + "frmPayments.aspx?");
			}
			else if (e.CommandName == "Delete")
			{
				SqlCommand cmd=new SqlCommand();
				cmd.CommandType=CommandType.StoredProcedure;
                cmd.CommandText = "wms_DeletePSEPResInv";
				cmd.Connection=this.epsDbConn;
				cmd.Parameters.Add ("@Id", SqlDbType.Int);
				cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
				cmd.Connection.Open();
				cmd.ExecuteNonQuery();
				cmd.Connection.Close();
				loadData();
			}
		}

		/*private void btnAdd_Click(object sender, System.EventArgs e)
		{
				Session["CallerUpdProcure"]="frmProcRReq";
				Session["Contractor"] = "Table";
				Session["btnAction"]="Add";
				Session["Id"]="0";
				Response.Redirect (strURL + "frmUpdProcProcure.aspx?");
		}*/
		private void Exit()
		{
			Response.Redirect (strURL + Session["cps"].ToString() + ".aspx?");
		}

		protected void btnOK_Click(object sender, System.EventArgs e)
		{
		    updateGrid();
		}
        private void getInv()
        {
            Session["InventoryId"] = null;
            Session["Update"] = "No";
            Session["CInv"] = "frmProcRReq";
            Response.Redirect(strURL + "frmInventory.aspx?");
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {

        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Session["InventoryId"] = null;
            AddProcRReq();
            loadData();
        }
        protected void btnAddExisting_Click1(object sender, EventArgs e)
        {
            if (Session["ResTypesType"].ToString() == "0")
            {
                getInv();
            }
            else
            {
                Session["CContracts"] = "frmProcRReq";
                Response.Redirect(strURL + "frmContractsS.aspx?");
            }
        }
}

}


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

namespace MiningCore.Crypto.Hashing.Ethash
{
    public class Block
    {
        public ulong Height { get; set; }
        public BigInteger Difficulty { get; set; }
        public byte[] HashNoNonce { get; set; }
        public ulong Nonce { get; set; }
        public byte[] MixDigest { get; set; }
    }
}


text:
using Skybrud.Social.Google.YouTube.Objects.Videos;
using Skybrud.Social.Http;
using Skybrud.Social.Json;

namespace Skybrud.Social.Google.YouTube.Responses {

    public class YouTubeVideoListResponse : YouTubeResponse<YouTubeVideoList> {

        #region Constructors

        private YouTubeVideoListResponse(SocialHttpResponse response) : base(response) { }

        #endregion

        #region Static methods

        public static YouTubeVideoListResponse ParseResponse(SocialHttpResponse response) {

            if (response == null) return null;

            // Parse the raw JSON response
            JsonObject obj = response.GetBodyAsJsonObject();
            if (obj == null) return null;

            // Validate the response
            ValidateResponse(response, obj);

            // Initialize the response object
            return new YouTubeVideoListResponse(response) {
                Body = YouTubeVideoList.Parse(obj)
            };

        }

        #endregion

    }

}