text:
---
title: Sharing the image
---

import SnackInline from '~/components/plugins/SnackInline';
import Video from '~/components/plugins/Video'

Similar to expo-image-picker, the functionality that we need to share is available in an Expo library — this one is called [expo-sharing](../versions/latest/sdk/sharing.md).

## Installing expo-sharing

You can install expo-sharing in the same way as you installed expo-image-picker:

- Run `expo install expo-sharing` in your project directory.

## Using expo-sharing to share an image

<SnackInline label="Sharing" templateId="tutorial/sharing-simple" dependencies={['expo-image-picker', 'expo-sharing']}>

```js
import React from 'react';
import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
/* @info As always, we must import it to use it */ import * as Sharing from 'expo-sharing'; /* @end */

export default function App() {
  const [selectedImage, setSelectedImage] = React.useState(null);

  let openImagePickerAsync = async () => {
    /* most contents of this function were hidden here to keep the example brief */

    setSelectedImage({ localUri: pickerResult.uri });
  };

  /* @info Share the selected image if sharing is available on the user's device */
  let openShareDialogAsync = async () => {
    if (!(await Sharing.isAvailableAsync())) {
      alert(`Uh oh, sharing isn't available on your platform`);
      return;
    }

    await Sharing.shareAsync(selectedImage.localUri);
  }; /* @end */

  if (selectedImage !== null) {
    return (
      <View style={styles.container}>
        <Image source={{ uri: selectedImage.localUri }} style={styles.thumbnail} />
        /* @info Add a button to call the new share function */
        <TouchableOpacity onPress={openShareDialogAsync} style={styles.button}>
          <Text style={styles.buttonText}>Share this photo</Text>
        </TouchableOpacity>
        /* @end */
      </View>
    );
  }

  return (
    <View style={styles.container}>
      {/* Our logo, instructions, and picker button are hidden here to keep the example brief */}
    </View>
  );
}
```

</SnackInline>

## Running the app on Android and iOS

<Video file={"tutorial/sharing-native.mp4"} />

🥰 Everything is working great! The operating system share dialog opens up and is ready to share our selected image.

## Running the app on the web

<Video file={"tutorial/sharing-web-unavailable.mp4"} />

😱 Uh oh. When we hit "Share this photo" we see that our `alert` warns us that sharing is not available. This is happening because the desktop Chrome browser does not currently provide a way for users to share content.

Want to learn more about why we can't use expo-sharing in Chrome?

Sharing didn't work here because the desktop Chrome browser doesn't yet implement the [Web Share API](https://web.dev/web-share/). _"But wait,"_ you say, _"aren't we using expo-sharing, not the Web Share API?"_ You can think of the Expo SDK libraries as translators for different platforms. They speak the language of Expo and turn it into the language of iOS, Android, and web. It isn't always possible to translate from Expo's language to the platform that you're working with. In other words, if the platform doesn't implement a feature, Expo can't tell it to invoke that feature. In some cases Expo can attempt to [polyfill](<https://en.wikipedia.org/wiki/Polyfill_(programming)>) the feature for you, but this isn't always possible. Invoking your operating system's built-in share dialog to share content with other applications needs to be implemented by the platform itself — Chrome in this case.

## Working with what we have available

In the next section we are going to look at how we can handle this and another important platform difference. [Continue to "Handling platform differences"](../tutorial/platform-differences.md).


text:
//
//  DataIOViewController.m
//  splitViewSample
//
//  Created by Victor on 16/5/17.
//  Copyright © 2016年 NilCode. All rights reserved.
//

#import "DataIOViewController.h"
#import "PListViewController.h"
#import "CoreDataViewController.h"

@interface DataIOViewController ()

@end

@implementation DataIOViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];

    [self addView];
}

- (void)addView{

    UIButton *PList=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [PList setTitle:@"PList" forState:UIControlStateNormal];
    [PList addTarget:self action:@selector(ShowPList:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *CoreData=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [CoreData setTitle:@"CoreData" forState:UIControlStateNormal];
    [CoreData addTarget:self action:@selector(ShowCoreData:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:PList];
    [self.view addSubview:CoreData];

    //add Constraint
    PList.translatesAutoresizingMaskIntoConstraints=NO;
    NSLayoutConstraint *btnReadTop=[NSLayoutConstraint constraintWithItem:PList attribute:NSLayoutAttributeTopMargin relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTopMargin multiplier:1.0 constant:20];
    NSLayoutConstraint *btnReadLeading=[NSLayoutConstraint constraintWithItem:PList attribute:NSLayoutAttributeLeadingMargin relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeadingMargin multiplier:1.0 constant:0];

    CoreData.translatesAutoresizingMaskIntoConstraints=NO;
    NSLayoutConstraint *CoreDataTop=[NSLayoutConstraint constraintWithItem:CoreData attribute:NSLayoutAttributeTopMargin relatedBy:NSLayoutRelationEqual toItem:PList attribute:NSLayoutAttributeTopMargin multiplier:1.0 constant:0];
    NSLayoutConstraint *CoreDataLeft=[NSLayoutConstraint constraintWithItem:CoreData attribute:NSLayoutAttributeLeftMargin relatedBy:NSLayoutRelationEqual toItem:PList attribute:NSLayoutAttributeRightMargin multiplier:1.0 constant:40];

    [NSLayoutConstraint activateConstraints:@[btnReadTop,btnReadLeading,CoreDataTop,CoreDataLeft]];
}

-(IBAction)ShowPList:(id)sender{
    PListViewController *plist=[[PListViewController alloc]init];
    [self.navigationController pushViewController:plist  animated:YES];
}

-(IBAction)ShowCoreData:(id)sender{
    CoreDataViewController *cd=[[CoreDataViewController alloc]init];
    [self.navigationController pushViewController:cd  animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class com.puppycrawl.tools.checkstyle.checks.naming.AbstractAccessControlNameCheck (checkstyle 5.6 API)</title>
<meta name="date" content="2012-09-18">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.puppycrawl.tools.checkstyle.checks.naming.AbstractAccessControlNameCheck

Packages that use AbstractAccessControlNameCheck

Package
Description

com.puppycrawl.tools.checkstyle.checks.naming

Contains the Naming conventions checks
 that are bundled with the main distribution.

Uses of AbstractAccessControlNameCheck in com.puppycrawl.tools.checkstyle.checks.naming

Subclasses of AbstractAccessControlNameCheck in com.puppycrawl.tools.checkstyle.checks.naming

Modifier and Type
Class and Description

class
ConstantNameCheck

 Checks that constant names conform to a format specified
 by the format property.

class
MemberNameCheck

 Checks that instance variable names conform to a format specified
 by the format property.

class
MethodNameCheck

 Checks that method names conform to a format specified
 by the format property.

class
StaticVariableNameCheck

 Checks that static, non-final variable names conform to a format specified
 by the format property.

class
TypeNameCheck

 Checks that type names conform to a format specified
 by the format property.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001-2012. All Rights Reserved.


text:
This is a todomvc demo.

The frontend is implemented with ember and stored in the `frontend` directory.

There are two recommended ways to run the app:

* Using the ember hot reloading proxy: `cargo run server --features proxy`
    - The server will be available at `localhost:4200`
* Building into a single binary (with optimizations): `cargo run server --release`
    - The server will be available at `localhost:7878`

## Dependencies

You must have ember-cli installed to build cargonauts in either proxy or release
mode.

You also must have a redis instance running on your machine (this app persists
to redis, a sort of bad idea but w/e, its a demo). The app is configured to
assume the redis instance is running on port `6379`, if this is not the case
you need to change the `REDIS_HOST` key in the Cargo.toml for this app.


text:
class CreateComentarios < ActiveRecord::Migration
  def change
    create_table :comentarios do |t|
      t.string :comentario, limit: 140
      t.integer :likes
      t.integer :usuario_id

      t.timestamps
    end
  end
end


text:
extern crate iron_valid;
extern crate params;

use iron_valid::{Rule, validate};
use params::{Map, Value};
use std::collections::BTreeMap;

#[test]
fn test_boolean_valid_boolean_true() {
    let mut params = Map::new();
    params.assign("boolean", Value::Boolean(true)).ok();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_ok());
    assert_eq!(result.unwrap().find(&["boolean"]).unwrap(),
               &Value::Boolean(true));
}

#[test]
fn test_boolean_valid_boolean_false() {
    let mut params = Map::new();
    params.assign("boolean", Value::Boolean(false)).ok();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_ok());
    assert_eq!(result.unwrap().find(&["boolean"]).unwrap(),
               &Value::Boolean(false));
}

#[test]
fn test_boolean_valid_string() {
    let mut params = Map::new();
    params.assign("boolean", Value::String("true".to_owned())).ok();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_ok());
    assert_eq!(result.unwrap().find(&["boolean"]).unwrap(),
               &Value::Boolean(true));
}

#[test]
fn test_boolean_invalid_string() {
    let mut params = Map::new();
    params.assign("boolean", Value::String("nope".to_owned())).ok();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_err());
    assert_eq!(*result.unwrap_err().get("boolean").unwrap(),
               vec!["The boolean field must be a boolean.".to_owned()]);
}

#[test]
fn test_boolean_valid_numeric() {
    let mut params = Map::new();
    params.assign("boolean", Value::U64(1)).ok();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_ok());
    assert_eq!(result.unwrap().find(&["boolean"]).unwrap(),
               &Value::Boolean(true));
}

#[test]
fn test_boolean_invalid_numeric() {
    let mut params = Map::new();
    params.assign("boolean", Value::U64(42)).ok();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_err());
    assert_eq!(*result.unwrap_err().get("boolean").unwrap(),
               vec!["The boolean field must be a boolean.".to_owned()]);
}

#[test]
fn test_boolean_valid_blank() {
    let params = Map::new();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_ok());
    assert_eq!(result.unwrap().find(&["boolean"]), None);
}

#[test]
fn test_boolean_invalid_null() {
    let mut params = Map::new();
    params.assign("boolean", Value::Null).ok();

    let mut rules = BTreeMap::new();
    rules.insert("boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_err());
    assert_eq!(*result.unwrap_err().get("boolean").unwrap(),
               vec!["The boolean field must be a boolean.".to_owned()]);
}

#[test]
fn test_boolean_valid_boolean_nested() {
    let mut test = Map::new();
    test.assign("boolean", Value::Boolean(true)).ok();
    let mut params = Map::new();
    params.assign("test", Value::Map(test)).ok();

    let mut rules = BTreeMap::new();
    rules.insert("test.boolean", vec![Rule::Boolean]);

    let result = validate(&rules, params);

    assert!(result.is_ok());
    assert_eq!(result.unwrap().find(&["test", "boolean"]).unwrap(),
               &Value::Boolean(true));
}


text:
<?xml version="1.0" encoding="utf-8"?>
<CREOLE-DIRECTORY>
	<JAR>lib/commons-cli-1.1.jar</JAR>
	<JAR>lib/commons-codec-1.3.jar</JAR>
	<JAR>lib/commons-collections-3.2.1.jar</JAR>
	<JAR>lib/commons-httpclient-3.1.jar</JAR>
	<JAR>lib/kim-api-3.0-RC5.jar</JAR>
	<JAR>lib/kim-util-3.0-RC5.jar</JAR>
	<JAR>lib/slf4j-api-1.5.11.jar</JAR>
	<JAR>lib/slf4j-log4j12-1.5.11.jar</JAR>
	<JAR>lib/trove4j-2.0.2.jar</JAR>
	<JAR>lib/owlim-lite-5.4.jar</JAR>
	<JAR>lib/openrdf-sesame-2.7.9-onejar.jar</JAR>
	<JAR>Gazetteer_LKB.jar</JAR>
	<CREOLE>

		<!--
    The large knowledge base gazetteer allows loading huge collections of
    identifiers and labels and using them for gazetteer lookup.
	-->
		<RESOURCE>
			<NAME>Large KB Gazetteer</NAME>
			<CLASS>com.ontotext.kim.gate.KimGazetteer</CLASS>
			<comment>KIM KB based alias-lookup commponent</comment>
			<helpURL>http://nmwiki.ontotext.com/lkb_gazetteer</helpURL>
			<PARAMETER NAME="document" RUNTIME="true"
        COMMENT="The document to be processed">gate.Document</PARAMETER>
			<PARAMETER NAME="annotationSetName" RUNTIME="true"
        COMMENT="The annotation set to be used for the generated annotations"
        OPTIONAL="true">java.lang.String</PARAMETER>

			<!-- Setting limit of the number of the created annotations
	           will reduce the memory consumption of GATE on large documents.
		 Note that GATE documents consume gigabytes of memory if there are tens of thousands
		 of annotations in the document. All PRs that create large number of
		 annotations like the gazetteers and tokenizers may cause an Out Of Memory error
		 on large texts. Setting that options limits the amount of memory that the gazetteer will use. -->
			<PARAMETER NAME="annotationLimit" RUNTIME="true"
        COMMENT="
		The maximum number of the generated annotations. NULL or 0 for no limit.
		See the comments in the creole.xml for more information."
		OPTIONAL="true">java.lang.Integer</PARAMETER>

			<PARAMETER NAME="dictionaryPath" RUNTIME="false"
        COMMENT="Path where the gazetteer dictionary is stored." DEFAULT="dictionary"
		OPTIONAL="false">java.net.URL</PARAMETER>

			<PARAMETER NAME="forceCaseSensitive" RUNTIME="false"
        COMMENT="Whether the gazeteer should return case-sensitive matches regardless of the loaded dictionary."
		OPTIONAL="true">java.lang.Boolean</PARAMETER>

		</RESOURCE>

		<RESOURCE>
			<CLASS>com.ontotext.kim.gate.SesameEnrichment</CLASS>
		</RESOURCE>

	</CREOLE>

</CREOLE-DIRECTORY>


text:
import Ember from 'ember';
import moduleForAcceptance from '../helpers/module-for-acceptance';
import { test } from 'qunit';

let appStore, rex, toby, sam, andy;

moduleForAcceptance('Acceptance | Custom handlers', {
  beforeEach() {
    appStore = this.application.__container__.lookup('service:store');
    rex  = server.create('pet', { name: 'Rex',  alive: true  });
    toby = server.create('pet', { name: 'Toby', alive: false });
    sam  = server.create('pet', { name: 'Sam',  alive: false });
    andy = server.create('pet', { name: 'Andy', alive: true  });
  }
});

test("You can customize the response by passing a handler function that returns the desired body", function(assert) {
  var done = assert.async();
  appStore.findAll('pet').then(function(pets) {
    assert.deepEqual(pets.mapBy('name'), ['Rex', 'Andy']);
  }).finally(done);
});

test("You can customize the response code of a custom handler passing the code as 3rd argument", function(assert) {
  var done = assert.async();
  var request = Ember.$.ajax({
    url: '/pets/' + rex.id,
    method: 'delete'
  });

  request.then(function(response, statusText, jqXHR) {
    assert.equal(jqXHR.status, 200, 'The status code is 200 instead od 204');
    done();
  });
});

test("You can can programatically returns a tailored response by returning a Mirage.Response", function(assert) {
  var done = assert.async();
  var request = Ember.$.ajax({
    url: '/pets',
    method: 'post',
    data: JSON.stringify({ pet: { alive: true } })
  });

  request.then(function() { /* noop */ }, function(response) {
    assert.equal(response.status, 422, 'The status code is 422');
    assert.equal(response.responseText, '{"errors":{"name":["can\'t be blank"]}}', 'The response body is correct');
    assert.equal(response.getResponseHeader('some'), 'header', 'The response contains the custom header');
    done();
  });
});

test("returning a non-blank response from a custom handler whose default status is 204 changes the status to 200", function(assert) {
  var done = assert.async();
  var request = Ember.$.ajax({
    url: '/pets/' + rex.id,
    method: 'put',
    data: JSON.stringify({ pet: { id: rex.id, name: 'The Rex', alive: true } })
  });

  request.then(function(response, statusText, jqXHR) {
    assert.equal(jqXHR.status, 200, 'The status code is 200 instead of 204');
    assert.deepEqual(response, { id: '1', name: "The Rex", alive: true }, 'The response is correct');
    done();
  });
});


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.ibm.mobilefirstplatform.clientsdk.android.core">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <application android:allowBackup="true"
                 android:label="@string/app_name">

    </application>

</manifest>


text:
"""
Fuzzy finding using fuzzywuzzy/Levenshtein distance
"""

from fuzzywuzzy import fuzz

def is_fuzzy_match(a, b, score_cutoff=90):
    """
    Checks if two (unicode) strings are a fuzzy match
    :param a: unicode string
    :param b: unicode string
    :param score_cutoff: integer percentage that consitutes a match
    :return: true or false
    """
    return fuzz.ratio(a, b) > score_cutoff


text:
from json import loads

from tenable_io.api.base import BaseApi
from tenable_io.api.base import BaseRequest
from tenable_io.api.models import AccessGroup, AccessGroupList, AssetRule, AssetRuleFilter, AssetRulePrincipal, Filters

class AccessGroupsApi(BaseApi):

    def list(self, f=None, ft='and', w=None, wf=None, limit=None, offset=0, sort=None):
        """Return the access groups without associated rules.

        :param f: A list of :class:`tenable_io.api.models.AssetFilter` instances.
        :param ft: The action to apply if multiple 'f' parameters are provided. Supported values are **and** and **or**.
        :param w: The search value to be applied across wildcard fields specified with the 'wf' parameter.
        :param wf: The list of fields where the search values specified in the 'w' parameter are applied.
        :param limit: The maximum number of records to be retrieved.
        :param offset: The offset from request.
        :param sort: A list of fields on which the results are sorted.
        :raise TenableIOApiException:  When API error is encountered.
        :return: An instance of :class:`tenable_io.api.models.AccessGroupList`.
        """
        fgen = (i.field + ':' + i.operator + ':' + i.value for i in f) if f is not None else None
        response = self._client.get('access-groups',
                                    params={'f': '&'.join(fgen) if fgen is not None else None,
                                            'ft': ft, 'w': w, 'wf': ','.join(wf) if wf is not None else None,
                                            'limit': limit, 'offset': offset,
                                            'sort': ','.join(sort) if sort is not None else None})
        return AccessGroupList.from_json(response.text)

    def create(self, access_group_request):
        """Create a new access group.

        :param Access_group_request: An instance of :class:`AccessGroupRequest`.
        :raise TenableIOApiException:  When API error is encountered.
        :return: An instance of :class:`tenable_io.api.models.AccessGroup` without the rules information.
        """
        response = self._client.post('access-groups', access_group_request)
        return AccessGroup.from_json(response.text)

    def details(self, id):
        """Returns details for a specific access group

        :param id: The id of the access group
        :raise TenableIOApiException:  When API error is encountered.
        :return: An instance of :class:`tenable_io.api.models.AccessGroup`.
        """
        response = self._client.get('access-groups/%(id)s', path_params={'id': id})
        return AccessGroup.from_json(response.text)

    def delete(self, id):
        """Delete an access group.

        :param id: The id of the access group to delete.
        :raise TenableIOApiException:  When API error is encountered.
        :return: True if successful.
        """
        self._client.delete('access-groups/%(id)s', path_params={'id': id})
        return True

    def edit(self, id, access_group_request):
        """Modifies an access group. This method overwrites the existing data.

        :param id: The id of the access group to be edited.
        :param access_group_request: An instance of :class:`AccessGroupRequest`.
        :raise TenableIOApiException:  When API error is encountered.
        :return: An instance of :class:`tenable_io.api.models.AccessGroup`.
        """
        response = self._client.put('access-groups/%(id)s', payload=access_group_request, path_params={'id': id})
        return AccessGroup.from_json(response.text)

    def filters(self):
        """List available filters for access groups.

        :raise TenableIOApiException:  When API error is encountered.
        :return: An instance of :class:`tenable_io.api.models.Filters`.
        """
        response = self._client.get('access-groups/filters')
        return Filters.from_json(response.text)

    def rule_filters(self):
        """List available filters for asset rules.

        :raise TenableIOApiException:  When API error is encountered.
        :return: An instance of :class:`tenable_io.api.models.Filters`.
        """
        response = self._client.get('access-groups/rules/filters')
        return AssetRuleFilter.from_list(loads(response.text).get('rules', {}))

class AccessGroupRequest(BaseRequest):

    def __init__(
            self,
            name=None,
            all_assets=False,
            all_users=False,
            rules=None,
            principals=None
    ):
        """Request for AccessGroupsApi.create and AccessGroupsApi.edit.

        :param name: The name of the access group. Must be unique within the container, a maximum of 255 characters, and
            alphanumeric, but can include limited special characters (underscore, dash, parenthesis, brackets, colon).
            You can add a maximum of 5,000 access groups to an individual container.
        :type name: string
        :param all_assets: Specifies whether the access group is the All Assets group or a user-defined group. A create
            request with this parameter set to 'true' will fail.
            Set to 'true' to edit membership in the All Assets access group. In which case, any rules
            are ignored, but existing principals are overwritten based on the all_users and principals parameters.
            Set to 'false' to edit a user-defined access group. The existing rules are overwritten with the new rules,
            and existing principals are overwritten based on the all_users and principals parameters.
        :type all_assets: boolean
        :param all_users: Specifies whether assets in the access group can be viewed by all or only some users.
            Default is 'False'. If 'true', all users in your organization have Can View access to the
            assets defined in the rules parameter and any principal parameters is ignored.
            If 'false', only specified users have Can View access to the assets defined in the rules parameter.
            You define which users or user groups have access in the principals parameter of the request.
        :type all_users: boolean
        :param rules: An array of asset rules. Tenable.io uses these rules to assign assets to the access group.
            You can only add rules to access groups if the all_assets parameter is set to 'false'.
        :type rules: list
        :param principals: A list of principals. Each representing a user or user group assigned to the access group.
            Data in this array is handled based on the all_users parameter. If all_users is 'true',
            any principal data is ignored and you can omit this parameter.
            If all_users is 'false', the principal data is added to the access group.
        :type principals: list
        """
        for r in rules:
            assert isinstance(r, AssetRule)

        self.name = name
        self.all_assets = all_assets
        self.all_users = all_users
        self.rules = rules
        self.principals = principals

    def as_payload(self, filter_=None):
        payload = super(AccessGroupRequest, self).as_payload(True)
        rule_list = []
        for r in self.rules:
            rule_list.append(r.as_payload())
        payload.__setitem__('rules', rule_list)
        if not self.all_users and self.principals:
            principal_list = []
            for p in self.principals:
                assert isinstance(p, AssetRulePrincipal)
                principal_list.append(p.as_payload())
            payload.__setitem__('principals', principal_list)
        return payload


text:
<?php

namespace Intaro\SymfonyTestingTools;

if (WebTestCase::isTestsDebug()) {
    class PHPUnitPrinter extends \PHPUnit_TextUI_ResultPrinter
    {
    }
} else {
    class PHPUnitPrinter extends \PHPUnit_Util_Log_TAP
    {
        /**
         * An error occurred.
         *
         * @param \PHPUnit_Framework_Test $test
         * @param \Exception              $e
         * @param float                   $time
         */
        public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time)
        {
            $this->writeNotOk($test, 'Error');

            $message = explode("\n", \PHPUnit_Framework_TestFailure::exceptionToString($e));

            $diagnostic = array(
                'message'  => $message[0],
                'severity' => 'fail'
            );

            $yaml = new \Symfony\Component\Yaml\Dumper;

            $this->write(
                sprintf(
                    "  ---\n%s  ...\n",
                    $yaml->dump($diagnostic, 2, 2)
                )
            );
        }
    }
}


text:
var http = require('http')
var fs   = require('fs')
var url  = require('url');
var mime = require('mime');

function urlToPath(urlStr) {
  var path = url.parse(urlStr).pathname;
  return '.' + decodeURIComponent(path);
}

var methods = {};

methods.GET = function(path, respond) {
  console.log("GET " + path);
  fs.stat(path, function(error, stats) {
    if (error && error.code == 'ENOENT') {
      respond(404, 'File not found');
    } else if (error) {
      respond(500, 'Internal server error: ' + error.toString());
    } else if (stats.isDirectory()) {
      fs.readdir(path, function(error, files) {
        if (error) {
          respond(500, 'Internal server error: ' + error.toString());
        } else {
          respond(200, files.join('\n'));
        }
      });
    } else {
      respond(200, fs.createReadStream(path), mime.lookup(path));
    }
  })
};

var server = http.createServer(function(request, response) {

  function respond(code, body, type) {
    if (!type) type = 'text/plain';
    response.writeHead(code, {'Content-Type': type});
    if (body && body.pipe) {
      body.pipe(response);
    } else {
      response.end(body);
    }
  }

  if (request.method in methods) {
    methods[request.method](urlToPath(request.url), respond, request);
  } else {
    respond(405, 'Method ' + request.method + ' not allowed');
  }

});

server.listen(8000);


text:
<?php

namespace Omnipay\Stripe\Message;

/**
 * Stripe Capture Request
 */
class CaptureRequest extends AbstractRequest
{
    public function getData()
    {
        $this->validate('transactionReference');

        $data = array();

        if ($amount = $this->getAmountInteger()) {
            $data['amount'] = $amount;
        }

        return $data;
    }

    public function getEndpoint()
    {
        return $this->endpoint.'/charges/'.$this->getTransactionReference().'/capture';
    }
}


text:
function A() {

}

A.prototype = {
    doStuff: function() {

    }
};

function B() {}
B.prototype = Object.create(A.prototype);
B.prototype.doStuff = undefined;

var b = new B();
b.doStuff();


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>class DropboxApi::Metadata::FileRequest - RDoc Documentation</title>

<link href="../../css/fonts.css" rel="stylesheet">
<link href="../../css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Parent

DropboxApi::Metadata::Base

    class DropboxApi::Metadata::FileRequest

Example of a serialized {FileRequest} object:

"`json {

"id": "oaCAVmEyrqYnkZX9955Y",
"url": "https://www.dropbox.com/request/oaCAVmEyrqYnkZX9955Y",
"title": "Homework submission",
"created": "2015-10-05T17:00:00Z",
"is_open": true,
"file_count": 3,
"destination": "/File Requests/Homework",
"deadline": {
    "deadline": "2020-10-12T17:00:00Z",
    "allow_late_uploads": {
        ".tag": "seven_days"
    }
}

} "`

Validate

Generated by RDoc 6.0.1.

Based on Darkfish by Michael Granger.


text:
<title>
Is Castro's Cuba a socialist society?
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

WHAT DO SOCIALISTS SAY?

Is Castro's Cuba a socialist society?

By Bridget Broderick | May 24, 2002 | Page 7

THE BUSH White House wasn't long in responding to former President Jimmy Carter's controversial visit to Cuba. Three days after Carter returned, George W. Bush spoke out on Cuban Independence Day, spewing the same rabid anti-Castro rhetoric that the U.S. has used since the 1959 revolution that toppled the U.S.-backed dictator Fulgencio Batista.

No wonder. The Bush administration is packed with veteran Cuba haters--even a few exile fanatics like Otto Reich. These goons were furious about Carter's visit and his call for the U.S. to lift its economic blockade.

Carter couched his appeal in terms of helping ordinary Cubans, who have suffered enormously because of the embargo. But a section of Corporate America is beginning to adopt this position--and not because they're worried about Cuban living standards. Companies like DuPont and Monsanto want access to the Cuban market--and are tired of giving an advantage to Canadian and European competitors because of Washington's hatred of Castro.

The embargo should be lifted. The U.S. government shouldn't be able to impose misery on ordinary Cubans in order to promote U.S. interests in its "backyard."

But for many people who consider themselves radicals, Cuba is more than a victim of U.S. imperialism that should be defended against Washington. They believe that Cuba is socialist in some way--an alternative to capitalism that may be imperfect and embattled because of the U.S. siege, but an improvement nevertheless.

The revolution in 1959 rightly inspired people around the world because it was a blow against the long U.S. tradition of bullying and intervening in Latin America. But Castro and his allies didn't build a socialist society.

Though supported by most Cubans, the revolution didn't involve the masses of Cuban workers and the poor in their own liberation. The vast majority looked on as Castro and Ché Guevara led a small guerrilla army to victory against Batista's corrupt regime.

The new government promoted literacy and health campaigns, and enacted land and housing reforms. But Castro said nothing about the new government being socialist for two years.

Only after the U.S. government made it clear that it wasn't about to accept any reforms in Cuba did the new government discover its "socialism"--not so coincidentally after it made an economic and political alliance with the former USSR.

Castro adopted the USSR's model for state-run industry and social services. The new system was called "socialist," but bore all the markings of capitalism--with a small minority at the top (in this case, state officials) making all the real decisions. Workers had no power over the direction or priorities of this state capitalist system. "Socialism" was imposed on Cuban workers--not created by them.

Many of Cuba's defenders insist that scarcity and tight government control are inevitable because of the U.S. embargo--and that the Castro government at least spends more for Cuba's social needs than the U.S. Both arguments are partly true. But they overlook important realities.

Many of the basic reforms won after the revolution have been undermined by the U.S. embargo--especially since Castro's adaptation to the free market during the 1990s "special period" following the fall of the ex-USSR. But the policies of the "special period" are only an extension of the top-down system that has existed all along, in which an elite has enjoyed special privileges and powers.

And while the Cuban government spends much more on health care and education for its citizens than the U.S. does, this could be said of many countries that aren't socialist--France, Germany and Canada among them.

Clearly, we don't side with Bush and the other anti-Castro fanatics. But socialists don't have to settle for Castro's fake "socialism" either.

A socialist society is about giving workers a say over the priorities of society--not leaving them in the hands of state bureaucrats.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
package com.xyp260466.dubbo.annotation;
import java.lang.annotation.*;

/**
 * Created by xyp on 16-5-9.
 *
 * 用于指定DUBBO服务类
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Provider {
    String value() default "";
}


text:
require 'spec_helper'

describe JS::Node::Literal, '.construct' do
  let(:class_under_test) do
    Class.new(described_class) do
      include Concord.new(:input)
    end
  end

  let(:input)  { mock('Input')    }
  let(:object) { class_under_test }

  subject { object.construct(input) }

  it { should eql(class_under_test.new(input)) }
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using Newtonsoft.Json.Linq;

namespace csUSDomainPlugin.Effects.ViewModels
{
    public class EffectsOutputParameterViewModel : EffectsInputParameterViewModel
    {
        public object Value
        {
            get
            {
                switch ((int) _data["ParameterType"])
                {
                    case 6:
                        return (string)_data["Data"]["ChemicalName"];
                        break;
                    default:
                        return _data["Data"]["Value"].ToString();
                }
            }
        }
    }
}


text:
var beforeload = (new Date()).getTime();

function getPageLoadTime(){

        var afterload = (new Date()).getTime();

        seconds = (afterload-beforeload) / 1000;

        $('#load_time').text('Tiempo de carga de la página ::  ' + seconds + ' sec(s).');

}

window.onload = getPageLoadTime;


text:
'''Qeez statistics utils module
'''

import importlib
import inspect
import logging
import sys
from zlib import crc32

from redis import StrictRedis

from qeez_stats.config import CFG

LOG = logging.getLogger(__name__)

COLL_ID_FMT = '_coll:%s'
PACKETS_ID_FMT = '_packets:%s'
PACKET_EXPIRE = 1800
PACKET_SEP = ':'
REDIS_CONNS = {}

DEF_RST = '1:0'

if sys.version_info > (3,):
    def to_bytes(str_buf):  # pragma: PY2to3
        '''Converts UTF-8 string to bytes in Py3
        '''
        return bytes(str_buf, encoding='utf-8')

    def to_str(byte_buf):  # pragma: PY2to3
        '''Converts bytes to UTF-8 string in Py3
        '''
        return str(byte_buf, encoding='utf-8')
else:
    def to_bytes(str_buf):  # pragma: PY2to3
        '''Converts UTF-8 string to bytes in Py2
        '''
        return bytes(str_buf)

    def to_str(byte_buf):  # pragma: PY2to3
        '''Converts bytes to UTF-8 string in Py2
        '''
        return str(byte_buf)

def calc_checksum(data):
    '''Calculates CRC32 checksum

    NOTE: Generates the same value across all Python versions and platforms.
    '''
    return '%08x' % (crc32(data) & 0xffffffff)

def get_redis(redis_cfg):
    '''Returns redis client instance for a given config
    '''
    return StrictRedis(
        unix_socket_path=redis_cfg['SOCKET'], db=redis_cfg['DB'])

def get_queue_redis():
    '''Instantiates and returns queue redis client
    '''
    if 'queue_redis' not in REDIS_CONNS:
        REDIS_CONNS['queue_redis'] = get_redis(CFG['QUEUE_REDIS'])
    return REDIS_CONNS['queue_redis']

def get_save_redis():
    '''Instantiates and returns save redis client
    '''
    if 'save_redis' not in REDIS_CONNS:
        REDIS_CONNS['save_redis'] = get_redis(CFG['SAVE_REDIS'])
    return REDIS_CONNS['save_redis']

def get_stat_redis():
    '''Instantiates and returns stat redis client
    '''
    if 'stat_redis' not in REDIS_CONNS:
        REDIS_CONNS['stat_redis'] = get_redis(CFG['STAT_REDIS'])
    return REDIS_CONNS['stat_redis']

def packet_split(key, val, rst=DEF_RST):
    '''Tests if packet parts are OK, returns splitted parts or None
    packet = ('grp_id:loc_id:cmp_id:rnd_id:cat_id:stp_id:gmr_id:tm_id',
        'ans_val:ans_tim:pts', '[int:int:...]')
    '''

    LOG.debug(
        'key / val / rst: %s (%s) / %s (%s) / %s (%s)',
        repr(key), repr(type(key)),
        repr(val), repr(type(val)),
        repr(rst), repr(type(rst)))

    key_parts = key.split(PACKET_SEP)
    if len(key_parts) != 8:
        LOG.warning('Bad key: %s', repr(key))
        return None
    if not all([part.isdigit() for part in key_parts]):
        LOG.warning('Bad key parts: %s', repr(key_parts))
        return None

    val_parts = val.split(PACKET_SEP)
    if len(val_parts) != 3:
        LOG.warning('Bad val: %s', repr(val))
        return None

    rst_parts = rst.split(PACKET_SEP)
    if not all([part.lstrip('-').isdigit() for part in rst_parts]):
        LOG.warning('Bad rst parts: %s', repr(rst_parts))
        return None

    return (key_parts, val_parts, rst_parts)

def decode_raw_packet(raw_packet):
    '''Decodes one raw packet
    '''
    if not raw_packet:
        return None
    raw_packet_len = len(raw_packet)
    if raw_packet_len == 2:
        key, val = raw_packet
        rst = DEF_RST
    elif raw_packet_len == 3:
        key, val, rst = raw_packet
    else:
        return None
    if isinstance(key, bytes):
        key = to_str(key)
    if isinstance(val, bytes):
        val = to_str(val)
    if isinstance(rst, bytes):
        rst = to_str(rst)
    parts = packet_split(key, val, rst)
    if parts is None:
        return None
    key_parts, val_parts, rst_parts = tuple(parts)

    return (
        tuple(int(part) for part in key_parts),
        (
            [int(ans) for ans in val_parts[0].split(',') if ans.isdigit()],
            float(val_parts[1]),
            int(val_parts[2]),
        ),
        tuple(int(part) for part in rst_parts),
    )

def decode_raw_packets(raw_packets):
    '''Decodes multiple raw packets at once
    '''
    return [
        decode_raw_packet(raw_packet) for raw_packet in raw_packets]

def save_packets_to_stat(qeez_token, res_dc, redis_conn=None):
    '''Saves packets
    '''
    if redis_conn is None:
        redis_conn = get_redis(CFG['STAT_REDIS'])
    key = PACKETS_ID_FMT % qeez_token

    # NOTE: strip rst parts
    _data = {}
    for _key, _val in res_dc.items():
        if isinstance(_val, tuple) and len(_val) == 2:
            _data[_key] = _val[0]
        else:
            _data[_key] = _val

    res = redis_conn.hmset(key, _data)
    redis_conn.expire(key, PACKET_EXPIRE)
    return res

def retrieve_packets(qeez_token, redis_conn=None):
    '''Retrieves packets
    '''
    if redis_conn is None:
        redis_conn = get_redis(CFG['STAT_REDIS'])
    return redis_conn.hgetall(PACKETS_ID_FMT % qeez_token)

def update_set(stat, stat_token, redis_conn=None):
    '''Updates stats' collector set
    '''
    if redis_conn is None:
        redis_conn = get_redis(CFG['STAT_REDIS'])
    return redis_conn.sadd(COLL_ID_FMT % stat, stat_token)

def retrieve_set(stat, redis_conn=None):
    '''Retrieves stats' collector set
    '''
    if redis_conn is None:
        redis_conn = get_redis(CFG['STAT_REDIS'])
    return redis_conn.smembers(COLL_ID_FMT % stat)

def get_method_by_path(method_path):
    '''Returns save method object by path
    '''
    method_mod, method_name = method_path.rsplit('.', 1)
    try:
        importlib.import_module(method_mod)
    except ImportError as exc:
        LOG.error(repr(exc))
        return None
    try:
        mod = sys.modules[method_mod]
        method = eval(method_name, mod.__dict__)
        if inspect.isfunction(method):
            return method
    except (KeyError, NameError) as exc:
        LOG.error(repr(exc))
    return None


text:
<!DOCTYPE HTML>
<html>
<head>
	<meta charset="UTF-8">
	<title></title>
	<style type="text/css">
		body, html, iframe, #ckfinder {
			margin: 0;
			padding: 0;
			border: 0;
			width: 100%;
			height: 100%;
			overflow: hidden;
		}
	</style>
	<script type="text/javascript" src="ckfinder.js"></script>
</head>
<body>
	<div id="ckfinder">
		<script type="text/javascript">
			(function(win){
				var get = CKFinder.tools.getUrlParam, tmp;

				var ckfinder = new CKFinder();
				ckfinder.width = ckfinder.height = '100%';
				ckfinder.selectActionFunction = onSelectAction;
				if ( tmp = get( 'type' ) ){
					ckfinder.resourceType = tmp;
				}
				ckfinder.create();

				function onSelectAction(fileUrl, data, allFiles){
					var arrUrl = [];
					for(var i=0,c=allFiles.length;i<c;i++){
						arrUrl.push(allFiles[i].url);
					}
					if(win.callback){
						callback('!'+arrUrl.join(' '));
					}
				}
			})(window);
		</script>
	</div>
</body>
</html>


text:
require 'spec_helper_acceptance'

describe 'kafka::mirror' do
  it 'works with no errors' do
    pp = <<-EOS
      class { 'zookeeper': } ->
      class { 'kafka::mirror':
        consumer_config => {
          'group.id'          => 'kafka-mirror',
          'zookeeper.connect' => 'localhost:2181',
        },
        producer_config => {
          'bootstrap.servers' => 'localhost:9092',
        },
      }
    EOS

    apply_manifest(pp, catch_failures: true)
    apply_manifest(pp, catch_changes: true)
  end

  describe 'kafka::mirror::install' do
    context 'with default parameters' do
      it 'works with no errors' do
        pp = <<-EOS
          class { 'zookeeper': } ->
          class { 'kafka::mirror':
            consumer_config => {
              'group.id'          => 'kafka-mirror',
              'zookeeper.connect' => 'localhost:2181',
            },
            producer_config => {
              'bootstrap.servers' => 'localhost:9092',
            },
          }
        EOS

        apply_manifest(pp, catch_failures: true)
      end

      describe group('kafka') do
        it { is_expected.to exist }
      end

      describe user('kafka') do
        it { is_expected.to exist }
        it { is_expected.to belong_to_group 'kafka' }
        it { is_expected.to have_login_shell '/bin/bash' }
      end

      describe file('/var/tmp/kafka') do
        it { is_expected.to be_directory }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end

      describe file('/opt/kafka-2.11-0.11.0.1') do
        it { is_expected.to be_directory }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end

      describe file('/opt/kafka') do
        it { is_expected.to be_linked_to('/opt/kafka-2.11-0.11.0.1') }
      end

      describe file('/opt/kafka/config') do
        it { is_expected.to be_directory }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end

      describe file('/var/log/kafka') do
        it { is_expected.to be_directory }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end
    end
  end

  describe 'kafka::mirror::config' do
    context 'with default parameters' do
      it 'works with no errors' do
        pp = <<-EOS
          class { 'zookeeper': } ->
          class { 'kafka::mirror':
            consumer_config => {
              'group.id'          => 'kafka-mirror',
              'zookeeper.connect' => 'localhost:2181',
            },
            producer_config => {
              'bootstrap.servers' => 'localhost:9092',
            },
          }
        EOS

        apply_manifest(pp, catch_failures: true)
      end

      describe file('/opt/kafka/config/consumer-1.properties') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end

      describe file('/opt/kafka/config/producer.properties') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end
    end

    context 'with custom config_dir' do
      it 'works with no errors' do
        pp = <<-EOS
          class { 'zookeeper': } ->
          class { 'kafka::mirror':
            consumer_config => {
              'group.id'          => 'kafka-mirror',
              'zookeeper.connect' => 'localhost:2181',
            },
            producer_config => {
              'bootstrap.servers' => 'localhost:9092',
            },
            config_dir => '/opt/kafka/custom_config'
          }
        EOS

        apply_manifest(pp, catch_failures: true)
      end

      describe file('/opt/kafka/custom_config/consumer-1.properties') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end

      describe file('/opt/kafka/custom_config/producer.properties') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end
    end

    context 'with specific version' do
      it 'works with no errors' do
        pp = <<-EOS
          class { 'zookeeper': } ->
          class { 'kafka::mirror':
            version         => '0.11.0.1',
            consumer_config => {
              'group.id'          => 'kafka-mirror',
              'zookeeper.connect' => 'localhost:2181',
            },
            producer_config => {
              'bootstrap.servers' => 'localhost:9092',
            },
          }
        EOS

        apply_manifest(pp, catch_failures: true)
      end

      describe file('/opt/kafka/config/consumer-1.properties') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end

      describe file('/opt/kafka/config/producer.properties') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'kafka' }
        it { is_expected.to be_grouped_into 'kafka' }
      end
    end
  end

  describe 'kafka::mirror::service' do
    context 'with default parameters' do
      it 'works with no errors' do
        pp = <<-EOS
          class { 'zookeeper': } ->
          class { 'kafka::mirror':
            consumer_config => {
              'group.id'          => 'kafka-mirror',
              'zookeeper.connect' => 'localhost:2181',
            },
            producer_config => {
              'bootstrap.servers' => 'localhost:9092',
            },
          }
        EOS

        apply_manifest(pp, catch_failures: true)
      end

      describe file('/etc/init.d/kafka-mirror'), if: (fact('operatingsystemmajrelease') =~ %r{(5|6)} && fact('osfamily') == 'RedHat') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'root' }
        it { is_expected.to be_grouped_into 'root' }
        it { is_expected.to contain 'export KAFKA_JMX_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false' }
        it { is_expected.to contain 'export KAFKA_LOG4J_OPTS="-Dlog4j.configuration=file:$base_dir/../config/log4j.properties"' }
      end

      describe file('/usr/lib/systemd/system/kafka-mirror.service'), if: (fact('operatingsystemmajrelease') == '7' && fact('osfamily') == 'RedHat') do
        it { is_expected.to be_file }
        it { is_expected.to be_owned_by 'root' }
        it { is_expected.to be_grouped_into 'root' }
        it { is_expected.to contain 'export KAFKA_JMX_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false' }
        it { is_expected.to contain 'export KAFKA_LOG4J_OPTS="-Dlog4j.configuration=file:$base_dir/../config/log4j.properties"' }
      end

      describe service('kafka-mirror') do
        it { is_expected.to be_running }
        it { is_expected.to be_enabled }
      end
    end
  end
end


text:
using Microsoft.Practices.Unity;
using PlayingWithUnity.Implementation;
using PlayingWithUnity.Interface;

namespace PlayingWithUnity
{
  public static class Bootstrapper
  {
    public static IUnityContainer Container { get; private set; }

    public static void Initialize()
    {
      Container = BuildUnityContainer();
    }

    private static IUnityContainer BuildUnityContainer()
    {
      // Configure
      var container = new UnityContainer();
      container.RegisterType(typeof(IDataFetcher), typeof(SuperCoolDataFetcher));
      container.RegisterType(typeof(ITransformer), typeof(SuperCoolTransformer));

      return container;
    }
  }
}


text:
using HeroVsRobot.DTO;
using HeroVsRobot.Enums;
using HeroVsRobot.Models;
using HeroVsRobot.Services;
using Microsoft.AspNet.Identity;
using System;
using System.Web.UI;

namespace HeroVsRobot
{
  public partial class _Default : Page
  {
    private string _userId;

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Context.User.Identity.IsAuthenticated)
      {
        showPanels(false);
      }
      else
      {
        _userId = User.Identity.GetUserId();
        if (!Page.IsPostBack)
        {
          updateStatistics(HeroFactory.GetHero(_userId));
        }
        showPanels(true);
        var item = Request.QueryString["action"];

        if (item == null) return;

        switch (item)
        {
          case "large":
          {
            fight(RobotDifficulty.Difficult);
            return;
          }
          case "medium":
          {
            fight(RobotDifficulty.Moderate);
            return;
          }
          case "small":
          {
            fight(RobotDifficulty.Easy);
            return;
          }
          case "lab":
          {
            lab();
            return;
          }
          case "port":
          {
            break;
          }
          case "armory":
          {
            armory();
            return;
          }
          case "medic":
          {
            medic();
            return;
          }
          case "command":
          {
            commandCenter();
            return;
          }
          default:
          {
            return;
          }
        }
      }
    }

    #region Helper Methods

    private void showPanels(bool show)
    {
      playerPanel.Visible = show;
      surfacePanel.Visible = show;
      visitorPanel.Visible = !show;
      introPanel.Visible = !show;
    }

    private void updateStatistics(Hero hero)
    {
      heroLiteral.Text = hero.Name;
      healthLiteral.Text = hero.Health.ToString();
      winsLiteral.Text = hero.Wins.ToString();
      lossesLiteral.Text = hero.Losses.ToString();
      movesLiteral.Text = hero.MovesRemaining.ToString();
      trainingLiteral.Text = hero.TrainingLevel.ToString();
      goldLiteral.Text = hero.Credits.ToString();
      WeaponLiteral.Text = hero.WeaponBonus.ToString();
      armorLiteral.Text = hero.ArmorBonus.ToString();
    }

    private static string formatErrorMessage(string message)
    {
      return string.Format("
{0}
", message);
    }

    #endregion

    #region Calls Into Domain Layer

    private void train()
    {
      try
      {
        var result = TrainingService.Train(_userId);
        resultLabel.Text = result.Message;
        updateStatistics(result.Hero);
      }
      catch (Exception exception)
      {
        resultLabel.Text = formatErrorMessage(exception.Message);
      }
    }

    private void armory()
    {
      try
      {
        var result = WeaponService.UpgradeWeapon(_userId);
        resultLabel.Text = result.Message;
        updateStatistics(result.Hero);
      }
      catch (Exception exception)
      {
        resultLabel.Text = formatErrorMessage(exception.Message);
      }
    }

    private void medic()
    {
      try
      {
        var result = MedicBayService.VisitMedicBay(_userId);
        resultLabel.Text = result.Message;
        updateStatistics(result.Hero);
      }
      catch (Exception exception)
      {
        resultLabel.Text = formatErrorMessage(exception.Message);
      }
    }

    private void lab()
    {
      try
      {
        var result = ArmorService.PurchaseArmor(_userId);
        resultLabel.Text = result.Message;
        updateStatistics(result.Hero);
      }
      catch (Exception exception)
      {
        resultLabel.Text = formatErrorMessage(exception.Message);
      }
    }

    private void commandCenter()
    {
      Response.Redirect("CommandCenter.aspx");
    }

    private void fight(RobotDifficulty difficulty)
    {
      try
      {
        var battleResult = BattleService.PerformBattle(_userId, difficulty);
        var str = formatBattleResult(battleResult);
        resultLabel.Text = str;
        BattleService.RecordBattle(_userId, str);
        updateStatistics(battleResult.Hero);
      }
      catch (Exception exception)
      {
        resultLabel.Text = formatErrorMessage(exception.Message);
      }
    }

    #endregion

    #region Button_Click Event Handlers

    protected void TrainButton_Click(object sender, EventArgs e)
    {
      train();
    }

    protected void UpgradeArmor_Click(object sender, EventArgs e)
    {
      lab();
    }

    protected void UpgradeWeapon_Click(object sender, EventArgs e)
    {
      armory();
    }

    protected void MedicBayButton_Click(object sender, EventArgs e)
    {
      medic();
    }

    protected void CommandCenterButton_Click(object sender, EventArgs e)
    {
      commandCenter();
    }

    protected void NormalRobotButton_Click(object sender, EventArgs e)
    {
      fight(RobotDifficulty.Moderate);
    }

    protected void DifficultRobotButton_Click(object sender, EventArgs e)
    {
      fight(RobotDifficulty.Difficult);
    }

    protected void EasyRobotButton_Click(object sender, EventArgs e)
    {
      fight(RobotDifficulty.Easy);
    }

    #endregion

    #region Battle Related Helper Methods

    private static string formatBattleResult(BattleResult battleResult)
    {
      string result;

      var robotName = battleResult.Robot.Name;
      var heroName = battleResult.Hero.Name;

      var progressMessage = "
Battle Progress:
";
      foreach (var battleRound in battleResult.BattleRounds)
      {
        if (battleRound.HeroHealth <= 20)
        {
          progressMessage += (battleRound.HeroHealth <= 0
            ? string.Format("

Round {0} ...
",
                battleRound.RoundNumber)
            : string.Format("

Round {0} ...
",
                battleRound.RoundNumber));
        }
        else
        {
          progressMessage += string.Format("

Round {0} ...
",
            battleRound.RoundNumber);
        }

        var robotHealth = (battleRound.RobotHealth > 0 ? battleRound.RobotHealth : 0);
        var heroHealth = (battleRound.HeroHealth > 0 ? battleRound.HeroHealth : 0);

        var heroDamageInflicted = battleRound.HeroDamageInflicted;

        progressMessage += string.Format("
{0} inflicted {1} damage on {2} reducing {2}'s health to {3}.
",
          robotName,
          heroDamageInflicted,
          robotName,
          robotHealth);

        var robotDamageInflicted = battleRound.RobotDamageInflicted;

        progressMessage += string.Format("
{0} inflicted {1} damage on {2} reducing {2}'s health to {3}.
",
          heroName,
          robotDamageInflicted,
          heroName,
          heroHealth);
        progressMessage += "
";
      }

      if (battleResult.Hero.Health > 0)
      {
        result = string.Format("
Awesome! {0} defeats {1}!
",
          heroName,
          robotName);

        result += string.Format("
Earned {0} credits!
",
          battleResult.CreditsEarned);

        if (battleResult.BonusMovesAwarded > 0)
        {
          result += string.Format("
w00t! You earned {0} bonus moves!
",
            battleResult.BonusMovesAwarded);
        }
        if (battleResult.Hero.Health <= 20)
        {
          result += string.Format("
Be careful! Your hero only has {0} health left!
",
            battleResult.Hero.Health);
        }
      }
      else
      {
        result = (battleResult.Robot.Health > 0
          ? string.Format("
Oh no! {0} defeats {1}!
",
            robotName,
            heroName)
          : string.Format("
Oh no! Both {0} and {1} were knocked out.",
            heroName,
            robotName));
      }
      return result + progressMessage;
    }

    #endregion

  }
}


text:
using System.Net.Http;
using System.Threading.Tasks;
using LightMock;
using Xunit;

namespace Bandwidth.Net.Test.Api
{
  public class NumberInfoTests
  {
    [Fact]
    public async void TestGet()
    {
      var response = new HttpResponseMessage
      {
        Content = Helpers.GetJsonContent("NumberInfo")
      };
      var context = new MockContext<IHttp>();
      context.Arrange(
        m =>
          m.SendAsync(The<HttpRequestMessage>.Is(r => IsValidGetRequest(r)), HttpCompletionOption.ResponseContentRead,
            null)).Returns(Task.FromResult(response));
      var api = Helpers.GetClient(context).NumberInfo;
      var numberInfo = await api.GetAsync("1234567890");
      Assert.Equal("Name", numberInfo.Name);
      Assert.Equal("number", numberInfo.Number);
    }

    public static bool IsValidGetRequest(HttpRequestMessage request)
    {
      return request.Method == HttpMethod.Get && request.RequestUri.PathAndQuery == "/v1/phoneNumbers/numberInfo/1234567890";
    }
  }
}


text:
using System;

namespace Experience.Models {
    public class Activity {
        public string Id { get; set; }
        public Definition Definition { get; set; }
        public string ObjectType => ObjectTypes.Activity;
    }
}


text:
<?php
	$ajax_num = $_POST['num'];

	require 'sweetlocalhost.class.php';
	$obj = new SweetLH();
	$obj->dispNews($ajax_num);
?>


text:
package com.wenguang.chat.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.wenguang.chat.R;
import com.wenguang.chat.utils.common.SortModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * 作者:陈攀
 * 邮件:616707902@qq.com
 * 创建时间:2016/12/3.
 * 描述:
 */
public class ReContactAdapter extends BaseAdapter implements SectionIndexer {
    private List<SortModel> mList;
    private List<SortModel> mSelectedList;
    private Context mContext;
    LayoutInflater mInflater;
    // 用来控制CheckBox的选中状况
    private static HashMap<Integer,Boolean> isSelected;

    public ReContactAdapter(Context mContext, List<SortModel> list) {
        this.mContext = mContext;
        mSelectedList = new ArrayList<SortModel>();
        isSelected = new HashMap<Integer, Boolean>();
        if (list == null) {
            this.mList = new ArrayList<SortModel>();
        } else {
            this.mList = list;
        }
    }
    // 初始化isSelected的数据
    private void initDate(){
        for(int i=0; i<mList.size();i++) {
            getIsSelected().put(i,false);
        }
    }
    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     *
     * @param list
     */
    public void updateListView(List<SortModel> list) {
        if (list == null) {
            this.mList = new ArrayList<SortModel>();
        } else {
            this.mList = list;
        }
        initDate();
        notifyDataSetChanged();
    }

    public int getCount() {
        return this.mList.size();
    }

    public Object getItem(int position) {
        return mList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup arg2) {
        ViewHolder viewHolder = null;
        final SortModel mContent = mList.get(position);
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.item_recontact, null);
            viewHolder.tvTitle = (TextView) view.findViewById(R.id.item_name);
            viewHolder.cbChecked = (CheckBox) view.findViewById(R.id.cbChecked);
            viewHolder.tvNumber = (TextView) view.findViewById(R.id.item_phone);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.tvTitle.setText(this.mList.get(position).name);
        viewHolder.tvNumber.setText(this.mList.get(position).number);
       // viewHolder.cbChecked.setChecked(isSelected(mContent));
        // 根据isSelected来设置checkbox的选中状况
        viewHolder.cbChecked.setChecked(getIsSelected().get(position));
        return view;

    }

    public static class ViewHolder {
        public TextView tvTitle;
        public TextView tvNumber;
        public CheckBox cbChecked;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return mList.get(position).sortLetters.charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = mList.get(i).sortLetters;
            char firstChar = sortStr.toUpperCase(Locale.CHINESE).charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    private boolean isSelected(SortModel model) {
        return mSelectedList.contains(model);
        //return true;
    }

//    public void toggleChecked(int position) {
//        if (isSelected(mList.get(position))) {
//            removeSelected(position);
//        } else {
//            setSelected(position);
//        }
//
//    }

//    private void setSelected(int position) {
//        if (!mSelectedList.contains(mList.get(position))) {
//            mSelectedList.add(mList.get(position));
//        }
//    }
//
//    private void removeSelected(int position) {
//        if (mSelectedList.contains(mList.get(position))) {
//            mSelectedList.remove(mList.get(position));
//        }
//    }

    public  List<SortModel> getSelectedList() {
        mSelectedList.clear();
        for (int i=0;i<mList.size();i++){
            if (getIsSelected().get(i)){
                mSelectedList.add(mList.get(i));
            }
        }
        return mSelectedList;
    }

    public void selectAll(){
      //  mSelectedList.clear();
        if (mList!=null){
            for (int i=0;i<mList.size();i++){
                getIsSelected().put(i, true);
                notifyDataSetChanged();
            }
        }
    }
    public void ReselectAll(){
        //  mSelectedList.clear();
        if (mList!=null){
            for (int i=0;i<mList.size();i++){
                getIsSelected().put(i, false);
                notifyDataSetChanged();
            }
        }
    }
    public static HashMap<Integer,Boolean> getIsSelected() {
        return isSelected;
    }

    public static void setIsSelected(HashMap<Integer,Boolean> isSelected) {
        ReContactAdapter.isSelected = isSelected;
    }
}


text:
package discordbot.db.version;

import discordbot.db.IDbVersion;

/**
 * more work on economy + introduction of betting
 * more indexes on tags
 */
public class db_28_to_29 implements IDbVersion {
    @Override
    public int getFromVersion() {
        return 28;
    }

    @Override
    public int getToVersion() {
        return 29;
    }

    @Override
    public String[] getExecutes() {
        return new String[]{
                "CREATE INDEX tags_tag_name_guild_id_index ON tags (tag_name, guild_id)",
                "CREATE INDEX guild_name ON tags (tag_name)",
                "CREATE TABLE bets ( " +
                        " id INT PRIMARY KEY AUTO_INCREMENT, " +
                        " title VARCHAR(128), " +
                        " owner_id INT NOT NULL, " +
                        " guild_id INT NOT NULL, " +
                        " created_on DATETIME NOT NULL, " +
                        " started_on DATETIME, " +
                        " ends_at DATETIME, " +
                        " price INT )",
                "CREATE TABLE bet_options ( " +
                        " id INT NOT NULL AUTO_INCREMENT, " +
                        " bet_id INT NOT NULL, " +
                        " description VARCHAR(128), " +
                        " CONSTRAINT bet_options_id_bet_id_pk PRIMARY KEY (id, bet_id) )",
                "ALTER TABLE bets ADD bet_status INT DEFAULT 0 NOT NULL",
                "CREATE TABLE todo_list ( " +
                        "id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, " +
                        "user_id INT NOT NULL, " +
                        "guild_id INT NOT NULL, " +
                        "list_name VARCHAR(191) NOT NULL, " +
                        "visibility INT " +
                        ")",
                "CREATE INDEX todo_list_guild_id_index ON todo_list (guild_id)",
                "CREATE INDEX todo_list_user_id_index ON todo_list (user_id)",
                "CREATE INDEX todo_list_guild_id_user_id_index ON todo_list (guild_id, user_id)",
                "CREATE TABLE todo_item( " +
                        "id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, " +
                        "list_id INT(11) NOT NULL, " +
                        "description VARCHAR(191), " +
                        "checked INT(11), " +
                        "priority INT(11)) "

        };
    }
}


text:
declare module KubernetesAPI {
    var pollingOnly: string[];
    class CollectionImpl implements Collection {
        private _options;
        private _kind;
        private _namespace;
        private _path;
        private _apiVersion;
        private handlers;
        private list;
        constructor(_options: K8SOptions);
        options: K8SOptions;
        private _restUrl;
        private _wsUrl;
        getKey(): string;
        wsURL: string;
        restURL: string;
        namespace: string;
        kind: string;
        connected: boolean;
        connect(): void;
        destroy(): void;
        private addLabelFilter(cb, labelSelector);
        get(cb: (data: any[]) => void, labelSelector?: LabelMap): void;
        private getPrefix();
        private restUrlFor(item, useName?);
        watch(cb: (data: any[]) => void, labelSelector?: LabelMap): (data: any[]) => void;
        unwatch(cb: (data: any[]) => void): void;
        put(item: any, cb: (data: any) => void, error?: (err: any) => void): void;
        delete(item: any, cb: (data: any) => void, error?: (err: any) => void): void;
    }
    var K8SClientFactory: K8SClientFactory;
    function get(options: K8SOptions): void;
    function del(options: any): void;
    function put(options: any): void;
    function watch(options: K8SOptions): {
        client: Collection;
        handle: (data: any[]) => void;
        disconnect: () => void;
    };
}


text:
import { ACTIONS } from '../utils/constants';

export function setApplicationFilter(data) {
	return {
		type: ACTIONS.SET_APPLICATION_FILTER,
		data
	};
}

export function setApplicationFilters(data) {
	return {
		type: ACTIONS.SET_APPLICATION_FILTERS,
		data
	};
}


text:
/*
 * SELinux support for the XFRM LSM hooks
 *
 * Author : Trent Jaeger, <jaegert@us.ibm.com>
 * Updated : Venkat Yekkirala, <vyekkirala@TrustedCS.com>
 */
#ifndef _SELINUX_XFRM_H_
#define _SELINUX_XFRM_H_

#include <net/flow.h>

int selinux_xfrm_policy_alloc(struct xfrm_sec_ctx **ctxp,
			      struct xfrm_user_sec_ctx *sec_ctx);
int selinux_xfrm_policy_clone(struct xfrm_sec_ctx *old_ctx,
			      struct xfrm_sec_ctx **new_ctxp);
void selinux_xfrm_policy_free(struct xfrm_sec_ctx *ctx);
int selinux_xfrm_policy_delete(struct xfrm_sec_ctx *ctx);
int selinux_xfrm_state_alloc(struct xfrm_state *x,
	struct xfrm_user_sec_ctx *sec_ctx, u32 secid);
void selinux_xfrm_state_free(struct xfrm_state *x);
int selinux_xfrm_state_delete(struct xfrm_state *x);
int selinux_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir);
int selinux_xfrm_state_pol_flow_match(struct xfrm_state *x,
			struct xfrm_policy *xp, const struct flowi *fl);

/*
 * Extract the security blob from the sock (it's actually on the socket)
 */
static inline struct inode_security_struct *get_sock_isec(struct sock *sk)
{
	if (!sk->sk_socket)
		return NULL;

	return SOCK_INODE(sk->sk_socket)->i_security;
}

#ifdef CONFIG_SECURITY_NETWORK_XFRM
extern atomic_t selinux_xfrm_refcount;

static inline int selinux_xfrm_enabled(void)
{
	return (atomic_read(&selinux_xfrm_refcount) > 0);
}

int selinux_xfrm_sock_rcv_skb(u32 sid, struct sk_buff *skb,
			struct common_audit_data *ad);
int selinux_xfrm_postroute_last(u32 isec_sid, struct sk_buff *skb,
			struct common_audit_data *ad, u8 proto);
int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, int ckall);
int selinux_xfrm_skb_sid(struct sk_buff *skb, u32 *sid);

static inline void selinux_xfrm_notify_policyload(void)
{
	atomic_inc(&flow_cache_genid);
}
#else
static inline int selinux_xfrm_enabled(void)
{
	return 0;
}

static inline int selinux_xfrm_sock_rcv_skb(u32 isec_sid, struct sk_buff *skb,
			struct common_audit_data *ad)
{
	return 0;
}

static inline int selinux_xfrm_postroute_last(u32 isec_sid, struct sk_buff *skb,
			struct common_audit_data *ad, u8 proto)
{
	return 0;
}

static inline int selinux_xfrm_decode_session(struct sk_buff *skb, u32 *sid, int ckall)
{
	*sid = SECSID_NULL;
	return 0;
}

static inline void selinux_xfrm_notify_policyload(void)
{
}

static inline int selinux_xfrm_skb_sid(struct sk_buff *skb, u32 *sid)
{
	*sid = SECSID_NULL;
	return 0;
}
#endif

#endif /* _SELINUX_XFRM_H_ */


text:
import irregularPluralsJson = require('./irregular-plurals.json');

declare const irregularPlurals: ReadonlyMap<
	keyof typeof irregularPluralsJson,
	string
>;

export = irregularPlurals;


text:
namespace arc {

namespace {
constexpr char kTestData[] = "TEST_DATA";
constexpr size_t kNumFds = 3;
}  // namespace

TEST(ArcVideoAcceleratorUtil, DuplicateFD_OK) {
  base::ScopedFD fd = CreateTempFileForTesting(kTestData);
  auto fds = DuplicateFD(std::move(fd), kNumFds);

  EXPECT_EQ(fds.size(), kNumFds);
}

TEST(ArcVideoAcceleratorUtil, DuplicateFD_Fail) {
  auto fds = DuplicateFD(base::ScopedFD(), kNumFds);

  EXPECT_EQ(fds.size(), 0u);
}

}  // namespace arc


text:
package it.polito.elite.enocean.protocol.serial.v3.network.packet.commoncommand;

import it.polito.elite.enocean.protocol.serial.v3.network.packet.ESP3Packet;
/**
 * Delete all filter from filter list
 *
 * @author Andrea Biasi <biasiandrea04@gmail.com>
 *
 */

public class CoWrFilterDelAll extends ESP3Packet {
	public CoWrFilterDelAll() {
		super();
		this.packetType = COMMON_COMMAND;
		// Command code
		this.data[0] = 0x0D;
		this.buildPacket();
	}
}


text:
package com.hackgsu.fall2016.android.views;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;
import android.view.View;
import com.hackgsu.fall2016.android.R;

/**
 * Created by Joshua King on 10/17/16.
 */
public class SlideUpBehavior extends FloatingActionButton.Behavior {
	private boolean isDown;

	public SlideUpBehavior (Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	public boolean onStartNestedScroll (final CoordinatorLayout coordinatorLayout,
										final FloatingActionButton child,
										View directTargetChild,
										View target,
										int nestedScrollAxes) {
		return coordinatorLayout.getResources().getBoolean(R.bool.isAdmin);
	}
}


text:
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Heisenslaught.Users
{
    public class HSUserStore : IUserStore<HSUser>, IUserLoginStore<HSUser>, IUserPasswordStore<HSUser>, IUserEmailStore<HSUser>, IUserRoleStore<HSUser>, IUserSecurityStampStore<HSUser>
    {
        private readonly IMongoCollection<HSUser> _userCollection;
        private readonly ILogger _logger;
        private readonly RoleManager<HSRole> _roleManager;

        public HSUserStore(IMongoDatabase database, ILoggerFactory loggerFactory, RoleManager<HSRole> roleManager) : this(database, loggerFactory, roleManager, "users") { }
        public HSUserStore(IMongoDatabase database, ILoggerFactory loggerFactory, RoleManager<HSRole> roleManager, string collectionName)
        {
            _userCollection = database.GetCollection<HSUser>(collectionName);
            _logger = loggerFactory.CreateLogger(GetType().Name);
            _roleManager = roleManager;

            EnsureIndicies();
        }

        public async Task<IdentityResult> CreateAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            cancellationToken.ThrowIfCancellationRequested();
            await _userCollection.InsertOneAsync(user, null, cancellationToken).ConfigureAwait(false);
            return IdentityResult.Success;

        }

        public async Task<IdentityResult> DeleteAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            cancellationToken.ThrowIfCancellationRequested();
            var query = Builders<HSUser>.Filter.Eq(u => u.Id, user.Id);
            await _userCollection.DeleteOneAsync(query, null, cancellationToken).ConfigureAwait(false);
            return IdentityResult.Success;
        }

        public Task<HSUser> FindByIdAsync(string userId, CancellationToken cancellationToken)
        {
            if (userId == null)
            {
                throw new ArgumentNullException(nameof(userId));
            }
            cancellationToken.ThrowIfCancellationRequested();
            var query = Builders<HSUser>.Filter.Eq(u => u.Id, userId);
            return _userCollection.Find(query).FirstOrDefaultAsync(cancellationToken);

        }

        public Task<HSUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
        {
            if (normalizedUserName == null)
            {
                throw new ArgumentNullException(nameof(normalizedUserName));
            }
            cancellationToken.ThrowIfCancellationRequested();
            var query = Builders<HSUser>.Filter.Eq(u => u.BattleTagNormaized, normalizedUserName);
            return _userCollection.Find(query).FirstOrDefaultAsync(cancellationToken);
        }

        public Task<string> GetNormalizedUserNameAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            return Task.FromResult(user.BattleTagNormaized);
        }

        public Task<string> GetUserIdAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            return Task.FromResult(user.Id);
        }

        public Task<string> GetUserNameAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            return Task.FromResult(user.BattleTag);
        }

        public Task SetNormalizedUserNameAsync(HSUser user, string normalizedName, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (normalizedName == null)
            {
                throw new ArgumentNullException(nameof(normalizedName));
            }

            user.SetBattleTagNormaized(normalizedName);

            return Task.FromResult(0);
        }

        public Task SetUserNameAsync(HSUser user, string userName, CancellationToken cancellationToken)
        {
            throw new NotSupportedException("Changing the username is not supported.");
        }

        public async Task<IdentityResult> UpdateAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            var query = Builders<HSUser>.Filter.Eq(u => u.Id, user.Id);
            var replaceResult = await _userCollection.ReplaceOneAsync(query, user, new UpdateOptions { IsUpsert = false }).ConfigureAwait(false);
            return replaceResult.IsModifiedCountAvailable && replaceResult.ModifiedCount == 1
                ? IdentityResult.Success
                : IdentityResult.Failed();
        }

        public void Dispose() { }

        private void EnsureIndicies()
        {

        }

        public Task AddLoginAsync(HSUser user, UserLoginInfo login, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (login == null)
            {
                throw new ArgumentNullException(nameof(login));
            }

            if (user.Logins.Any(x => x.Equals(login)))
            {
                throw new InvalidOperationException("Login already exists.");
            }
            user.AddLogin(new HSUserLogin(login));

            return Task.FromResult(0);

        }

        public Task RemoveLoginAsync(HSUser user, string loginProvider, string providerKey, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (loginProvider == null)
            {
                throw new ArgumentNullException(nameof(loginProvider));
            }

            if (providerKey == null)
            {
                throw new ArgumentNullException(nameof(providerKey));
            }

            var login = new UserLoginInfo(loginProvider, providerKey, string.Empty);
            var loginToRemove = user.Logins.FirstOrDefault(x => x.Equals(login));

            if (loginToRemove != null)
            {
                user.RemoveLogin(loginToRemove);
            }
            return Task.FromResult(0);
        }

        public Task<IList<UserLoginInfo>> GetLoginsAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var logins = user.Logins.Select(login =>
               new UserLoginInfo(login.LoginProvider, login.ProviderKey, null));
            return Task.FromResult<IList<UserLoginInfo>>(logins.ToList());
        }

        public Task<HSUser> FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken)
        {
            if (loginProvider == null)
            {
                throw new ArgumentNullException(nameof(loginProvider));
            }

            if (providerKey == null)
            {
                throw new ArgumentNullException(nameof(providerKey));
            }

            var loginQuery = Builders<HSUser>.Filter.ElemMatch(u => u.Logins,
                Builders<HSUserLogin>.Filter.And(
                    Builders<HSUserLogin>.Filter.Eq(lg => lg.LoginProvider, loginProvider),
                    Builders<HSUserLogin>.Filter.Eq(lg => lg.ProviderKey, providerKey)
                )
            );

            return _userCollection.Find(loginQuery).FirstOrDefaultAsync();
        }

        public Task SetPasswordHashAsync(HSUser user, string passwordHash, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            user.PasswordHash = passwordHash;
            return Task.FromResult(0);
        }

        public Task<string> GetPasswordHashAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            return Task.FromResult(user.PasswordHash);
        }

        public Task<bool> HasPasswordAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            return Task.FromResult(user.PasswordHash != null);
        }

        public Task SetEmailAsync(HSUser user, string email, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (user.PrimaryEmail == null)
            {
                user.PrimaryEmail = new HSEmailAddress();
            }
            user.PrimaryEmail.Value = email ?? throw new ArgumentNullException(nameof(email));

            return Task.FromResult(0);
        }

        public Task<string> GetEmailAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var primaryEmail = user.PrimaryEmail?.Value;
            return Task.FromResult(primaryEmail);
        }

        public Task<bool> GetEmailConfirmedAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var confirmed = user.PrimaryEmail?.IsConfirmed();
            return Task.FromResult((bool)confirmed);
        }

        public Task SetEmailConfirmedAsync(HSUser user, bool confirmed, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if(user.PrimaryEmail != null)
            {
                if (confirmed)
                {
                    user.PrimaryEmail.SetConfirmed();
                }
                else
                {
                    user.PrimaryEmail.SetUnconfirmed();
                }
            }
            return Task.FromResult(0);
        }

        public Task<HSUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken)
        {
            if (normalizedEmail == null)
            {
                throw new ArgumentNullException(nameof(normalizedEmail));
            }

            var query = Builders<HSUser>.Filter.Eq(u => u.PrimaryEmail.ValueNormaized, normalizedEmail);
            return _userCollection.Find(query).FirstOrDefaultAsync(cancellationToken);
        }

        public Task<string> GetNormalizedEmailAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var primaryEmail = user.PrimaryEmail?.ValueNormaized;
            return Task.FromResult(primaryEmail);
        }

        public Task SetNormalizedEmailAsync(HSUser user, string normalizedEmail, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (normalizedEmail != null && user.PrimaryEmail != null)
            {
                user.PrimaryEmail.ValueNormaized = normalizedEmail;
            }
            return Task.FromResult(0);
        }

        public async Task AddToRoleAsync(HSUser user, string roleName, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (roleName == null)
            {
                throw new ArgumentNullException(nameof(roleName));
            }
            var role = await _roleManager.FindByNameAsync(roleName);
            if(role == null)
            {
                throw new KeyNotFoundException("The role '" + roleName + "' does not exisit.");
            }
            user.AddRole(roleName);
        }

        public Task RemoveFromRoleAsync(HSUser user, string roleName, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            if (roleName == null)
            {
                throw new ArgumentNullException(nameof(roleName));
            }
            user.RemoveRole(roleName);
            return Task.FromResult(0);
        }

        public Task<IList<string>> GetRolesAsync(HSUser user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            return Task.FromResult<IList<string>>(user.Roles.ToList<string>());
        }

        public Task<bool> IsInRoleAsync(HSUser user, string roleName, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (roleName == null)
            {
                throw new ArgumentNullException(nameof(roleName));
            }
            return Task.FromResult(user.HasRole(roleName));
        }

        public async Task<IList<HSUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken)
        {
            if (roleName == null)
            {
                throw new ArgumentNullException(nameof(roleName));
            }

            var query = Builders<HSUser>.Filter.AnyEq(u => u.Roles, roleName);
            return await _userCollection.Find(query).ToListAsync(cancellationToken);
        }

        public Task SetSecurityStampAsync(HSUser user, string stamp, CancellationToken cancellationToken)
        {
            user.SetSecurityStamp(stamp);
            return Task.FromResult(0);
        }

        public Task<string> GetSecurityStampAsync(HSUser user, CancellationToken cancellationToken)
        {
            return Task.FromResult(user.SecurityStamp == null ? "" : user.SecurityStamp);
        }
    }
}


text:
using UnityEngine;
using System.Collections;

/// <summary>
/// Gives player all weapons. (Cheating!)
/// </summary>
public class GivePlayerAllWeapons : IActivate {

	public string[] WeaponsToGive;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

	public override void Activate ()
	{
		var player = GameObject.FindGameObjectWithTag("Player");
		var weapons = player.GetComponent<WeaponScript>();
		weapons.PickUpAllWeapons();
	}

}


text:
package org.apache.kafka.trogdor.workload;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.kafka.trogdor.common.JsonUtil;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class TopicsSpecTest {
    @Rule
    final public Timeout globalTimeout = Timeout.millis(120000);

    private final static TopicsSpec FOO;
    private final static PartitionsSpec PARTSA;
    private final static PartitionsSpec PARTSB;

    static {
        FOO = new TopicsSpec();

        PARTSA = new PartitionsSpec(3, (short) 3, null, null);
        FOO.set("topicA[0-2]", PARTSA);

        Map<Integer, List<Integer>> assignmentsB = new HashMap<>();
        assignmentsB.put(0, Arrays.asList(0, 1, 2));
        assignmentsB.put(1, Arrays.asList(2, 3, 4));
        PARTSB = new PartitionsSpec(0, (short) 0, assignmentsB, null);
        FOO.set("topicB", PARTSB);
    }

    @Test
    public void testMaterialize() {
        Map<String, PartitionsSpec> parts = FOO.materialize();
        assertTrue(parts.containsKey("topicA0"));
        assertTrue(parts.containsKey("topicA1"));
        assertTrue(parts.containsKey("topicA2"));
        assertTrue(parts.containsKey("topicB"));
        assertEquals(4, parts.keySet().size());
        assertEquals(PARTSA, parts.get("topicA0"));
        assertEquals(PARTSA, parts.get("topicA1"));
        assertEquals(PARTSA, parts.get("topicA2"));
        assertEquals(PARTSB, parts.get("topicB"));
    }

    @Test
    public void testPartitionNumbers() {
        List<Integer> partsANumbers = PARTSA.partitionNumbers();
        assertEquals(Integer.valueOf(0), partsANumbers.get(0));
        assertEquals(Integer.valueOf(1), partsANumbers.get(1));
        assertEquals(Integer.valueOf(2), partsANumbers.get(2));
        assertEquals(3, partsANumbers.size());

        List<Integer> partsBNumbers = PARTSB.partitionNumbers();
        assertEquals(Integer.valueOf(0), partsBNumbers.get(0));
        assertEquals(Integer.valueOf(1), partsBNumbers.get(1));
        assertEquals(2, partsBNumbers.size());
    }

    @Test
    public void testPartitionsSpec() throws Exception {
        String text = "{\"numPartitions\": 5, \"configs\": {\"foo\": \"bar\"}}";
        PartitionsSpec spec = JsonUtil.JSON_SERDE.readValue(text, PartitionsSpec.class);
        assertEquals(5, spec.numPartitions());
        assertEquals("bar", spec.configs().get("foo"));
        assertEquals(1, spec.configs().size());
    }
}


text:
using Gallio.Common.IO;
using Gallio.Runtime.ProgressMonitoring;
using Gallio.UI.ProgressMonitoring;

namespace Gallio.Icarus.Commands
{
    internal class OpenReportCommand : ICommand
    {
        private readonly IFileSystem fileSystem;

        public string FileName
        {
            get;
            set;
        }

        public OpenReportCommand(IFileSystem fileSystem)
        {
            this.fileSystem = fileSystem;
        }

        public void Execute(IProgressMonitor progressMonitor)
        {
            using (progressMonitor.BeginTask("Opening report", 100))
            {
                if (!string.IsNullOrEmpty(FileName))
                    fileSystem.OpenFile(FileName);
            }
        }
    }
}


text:
<?php
/**
 * The template for displaying Archive pages
 *
 * Used to display archive-type pages if nothing more specific matches a query.
 * For example, puts together date-based pages if no date.php file exists.
 *
 * If you'd like to further customize these archive views, you may create a
 * new template file for each specific one. For example, Ridizain
 * already has tag.php for Tag archives, category.php for Category archives,
 * and author.php for Author archives.
 *
 * @link http://codex.wordpress.org/Template_Hierarchy
 *
 *
 * @package Ridizain
 * @since Ridizain 1.0
 */

get_header(); ?>

			<?php if ( have_posts() ) : ?>

					<?php
						if ( is_day() ) :
							printf( __( 'Daily Archives: %s', 'ridizain' ), get_the_date() );

						elseif ( is_month() ) :
							printf( __( 'Monthly Archives: %s', 'ridizain' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'ridizain' ) ) );

						elseif ( is_year() ) :
							printf( __( 'Yearly Archives: %s', 'ridizain' ), get_the_date( _x( 'Y', 'yearly archives date format', 'ridizain' ) ) );

						else :
							_e( 'Archives', 'ridizain' );

						endif;
					?>

			<?php
					// Start the Loop.
					while ( have_posts() ) : the_post();

						/*
						 * Include the post format-specific template for the content. If you want to
						 * use this in a child theme, then include a file called called content-___.php
						 * (where ___ is the post format) and that will be used instead.
						 */
						get_template_part( 'content', get_post_format() );

					endwhile;
					// Previous/next page navigation.
					ridizain_paging_nav();

				else :
					// If no content, include the "No posts found" template.
					get_template_part( 'content', 'none' );

				endif;
			?>

<?php
get_sidebar( 'content' );
get_sidebar();
get_footer();