text:
/*global log: false */

log.write('c4.js');

var html5AppId = '3C4ECBD1-7CC2-4A1B-B90B-6B4AB000A459',
    //ugBaseUrl = 'https://api.usergrid.com/dino/loadgen1',
    //jobsUrl = ugBaseUrl + '/jobs',
    loadgenUrl = 'http://lvh.me:8001';
    jobsUrl = loadgenUrl + '/jobs';

log.write('loadgenUrl: ' + loadgenUrl);

function Job(name, desc, defaultProps) {
  return {
    type        : "job",
    name        : name,
    description : desc,
    defaultProperties: defaultProps
  };
}

function MainController ($scope, $http, $dialog, $q /*, $httpProvider , $compile */ ) {
  var dialogModel = {}, reUrl = new RegExp('https?://[^/]+(/.*)$'),
      httpConfig, initialContext = {},
      token, org, app;

  $scope.sortKey = 'created';
  $scope.sortReverse = false;
  $scope.jobRecords = [];
  $scope.securityContext = {};
  $scope.showDetails = [];

  $scope.loginRegisterDialogOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: false,
    templateUrl: 'views/login-register-dialog.htm',
    controller: 'LoginRegisterDialogController',
    // resolve is used to inject data into the controller for the dialog.
    resolve: {
      dialogModel: function() { return angular.copy(dialogModel); },
      wantIdentity: function() { return true; },
      title: function() { return "unkown"; }}
  };

  $scope.initialContextDialogOpts = {
    backdrop: true,
    keyboard: true,
    backdropClick: false,
    templateUrl: 'views/initial-context-dialog.htm',
    controller: 'InitialContextDialogController',
    // resolve is used to inject data into the controller for the dialog.
    resolve: {
      initialContext: function() { return angular.copy(initialContext); },
      title: function() { return 'Initial Context'; }
    }
  };

  log.write('MainController');
  // check for existing, working token
  org = window.localStorage.getItem(html5AppId + '.org');
  app = window.localStorage.getItem(html5AppId + '.app');
  token = window.localStorage.getItem(html5AppId + '.bearerToken');
  if ( ! token) {
    log.write('C4 no cached OAuth token.');
    $scope.securityContext.checked = true;
  }
  else if ( ! org || !app ) {
    log.write('C4 no cached org and app.');
    $scope.securityContext.checked = true;
  }
  else {
    // verify that the token is valid, not expired
    log.write('C4 org(' + org + ') app(' + app + ') token(' + token + ')');
    // Since the loadgen server is a pass-through, we need to tell
    // it which org/app the token applies to.
    httpConfig = { headers:{ 'Authorization': 'Bearer ' + token,
                             'Accept': 'application/json',
                             'X-AppSvcs': org + ':' + app
                           } };
    $http.get(loadgenUrl + '/users/me', httpConfig)
      .success(function ( response ) {
        // success implies the token is valid
        $scope.securityContext = { access_token : token, user: response.entities[0]};
        log.write('OAuth token: ' + $scope.securityContext.access_token);
        log.write('user uuid: ' + $scope.securityContext.user.uuid);
        $http.defaults.headers.common.Authorization = 'Bearer ' + $scope.securityContext.access_token;
        $http.defaults.headers.common['x-appsvcs'] = org + ':' + app;
        initialRetrieve();
      })
      .error(function(responseBody, code, headers, config) {
        // in case of error, the token is probably stale.
        log.write('OAuth token validation failed');
        log.write('data: ' + JSON.stringify(responseBody, null, 2));
        log.write('status: ' + JSON.stringify(code, null, 2));
        log.write('headers: ' + JSON.stringify(headers, null, 2));
        window.localStorage.removeItem(html5AppId + '.bearerToken');
        $scope.securityContext.checked = true;
      });
  }

  $scope.openRegisterDialog = function() {
    dialogModel = {};
    $scope.loginRegisterDialogOpts.resolve.title = function() { return "Register"; };
    $scope.loginRegisterDialogOpts.resolve.wantIdentity = function() { return true; };
    var d = $dialog.dialog($scope.loginRegisterDialogOpts);
    d.open().then(function(result){
      if(result) {
        register(result);
      }
    });
  };

  $scope.openLoginDialog = function(keepErrorMsg) {
    if ( ! keepErrorMsg && dialogModel.errorMessage) { delete dialogModel.errorMessage; }
    dialogModel.org = org;
    dialogModel.app = app;
    $scope.loginRegisterDialogOpts.resolve.title = function() { return 'Login'; };
    $scope.loginRegisterDialogOpts.resolve.wantIdentity = function() { return false; };
    var d = $dialog.dialog($scope.loginRegisterDialogOpts);
    d.open().then(function(result){
      if(result) {
        login(result, initialRetrieve);
      }
    });
  };

  $scope.toggleJobStatus = function(item, $event) {
    if (item.status == 'running') {
      $scope.stopJob(item, $event);
    }
    else {
      $scope.openInitialContextDialog(item, $event);
    }
  };

  $scope.openInitialContextDialog = function(item, $event) {
    $scope.initialContextDialogOpts.resolve.title = function() {
      return 'Initial Context: ' + item.name;
    };
    var d = $dialog.dialog($scope.initialContextDialogOpts);
    d.open().then(function(result){
      if(result && result.payload) {
        $scope.startJob(item, result.payload);
      }
    });
  };

  $scope.startJob = function (job, payload) {
    //   POST /jobs/{job-id}?action=start
    if ( ! payload) { payload = {}; }
    $http.post(loadgenUrl + '/jobs/' + job.uuid + '?action=start', payload)
      .success(function(data) {
        log.write('start: ' + JSON.stringify(data));
        job.status = 'running';
      })
      .error(function(data, status, headers, config) {
        log.write('start failed...' + JSON.stringify(data));
      });
  };

  $scope.stopJob = function (job, $event) {
    //   POST /jobs/{job-id}?action=stop
    var url = loadgenUrl + '/jobs/' + job.uuid + '?action=stop';
    $http.post(url)
      .success(function(data) {
        log.write('stop: ' + JSON.stringify(data));
        job.status = 'stopped';
      })
      .error(function(data, status, headers, config) {
        log.write('stop failed...' + JSON.stringify(data));
        if (data.message == "that job is not currently running") {
          job.status = 'stopped';
        }
      });
  };

  $scope.getJobCssClass = function (job) {
    if (job.status === 'running') { return 'icon-stop';}
    return 'icon-play';
  };

  $scope.logout = function() {
    log.write('signing out user ' + $scope.securityContext.user.uuid);
    delete $http.defaults.headers.common.Authorization;
    window.localStorage.removeItem(html5AppId + '.bearerToken');
    $scope.jobRecords = [];
    $scope.securityContext = { checked : true }; // checked and not authenticated
  };

  // see http://docs.angularjs.org/api/ng.$http
  // after login:
  // $httpProvider.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;

  function login(creds, success) {
    // curl -X POST -i -H "Content-Type: application/json"
    //     "https://api.usergrid.com/my-org/my-app/token"
    //     -d '{"grant_type":"password","username":"john.doe","password":"testpw"}'

    // success response:
    // {
    //   "access_token": "5wuGd-eeee-yyyy",
    //   "expires_in": 3600,
    //   "user": {
    //     "uuid": "6941ef6d-0dd0-4040-881d-c7abf5f339cc",
    //     "type": "user",
    //     "name": "Firstname Lastname",
    //     "created": 1372287618225,
    //     "modified": 1372287618225,
    //     "username": "Himself",
    //     "email": "person@example.com",
    //     "activated": true,
    //     "picture": "http://www.gravatar.com/avatar/d5e3ed864e42e13c54a427bd230dcf3d"
    //   }
    // }

    // subsequently, use this in http requests:
    // Authorization: Bearer {access_token}
    var loginPayload = { 'grant_type': 'password', username: creds.username, password: creds.password},
        loginHttpConfig = { headers:{ 'Content-Type': 'application/json',
                                      'Accept': 'application/json',
                                      'x-appsvcs': creds.org + ':' + creds.app }};

    // TODO: proxy the app services login from the loadgen server

    $http.post(loadgenUrl + '/token', loginPayload, loginHttpConfig)

      .success(function (response) {
        var token = response.access_token;
        $scope.securityContext = response;
        $scope.securityContext.checked = true;
        log.write('OAuth token: ' + token);
        window.localStorage.setItem(html5AppId + '.bearerToken', token);
        window.localStorage.setItem(html5AppId + '.org', creds.org);
        window.localStorage.setItem(html5AppId + '.app', creds.app);
        $http.defaults.headers.common.Authorization = 'Bearer ' + token;
        // necessary?
        httpConfig = { headers:{ 'Authorization': 'Bearer ' + token, 'Accept': 'application/json'} };
        org = creds.org;
        app = creds.app;
        if (dialogModel.errorMessage) { delete dialogModel.errorMessage; }
        creds.password = null;
        success();
      })
      .error(function(data, status, headers, config) {
        log.write('login failed');
        if (data && data.error_description) {
          dialogModel.errorMessage = data.error_description;
        }
        $scope.securityContext.checked = true;
        dialogModel.username = creds.username;
        dialogModel.org = creds.org;
        dialogModel.app = creds.app;
        // retry the login
        $scope.openLoginDialog(true);
      });
  }

  function register(creds) {
    // curl -X POST -i -H "Content-Type: application/json"
    //     "https://api.usergrid.com/my-org/my-app/users"
    //     -d '{"username":"john.doe","password":"testpw"}'

    // success response:
    // {
    //   "action" : "post",
    //   "application" : "00e1e88a-8610-11e2-8abc-02e81ac5a17b",
    //   "params" : { },
    //   "path" : "/users",
    //   "uri" : "http://api.usergrid.com/dino/todolist/users",
    //   "entities" : [ {
    //     "uuid" : "e23197ea-e02c-11e2-8f94-4548b396870f",
    //     "type" : "user",
    //     "created" : 1372449415262,
    //     "modified" : 1372449415262,
    //     "username" : "Schlotsky",
    //     "activated" : true,
    //     ...

    // subsequently, can login with those credentials.
    var registerPayload = { username: creds.username, password: creds.password, email: creds.email, name: creds.name },
        localHttpConfig = { headers:{ 'Content-Type': 'application/json', 'Accept': 'application/json'} };

    $http.post(loadgenUrl + '/users', registerPayload, localHttpConfig)
      .success(function (response) {
        var user = response.entities[0];
        if (user && user.activated) {
          log.write('successfully created a new user: ' + user.uuid);
          login(creds, initialRetrieve);
        }
      })
      .error(function(data, status, headers, config) {
        log.write('registration failed');
        if (data && data.error_description) {
          dialogModel.errorMessage = data.error_description;
        }
        dialogModel.username = creds.username;
        // retry the registration
        $scope.openRegisterDialog();
      });
  }

  function shortUrl(url) {
    var m = reUrl.exec(url);
    if ( ! m) {return '??';}
    return m[1];
  }

  // function jobGetter(job) {
  //   return function(){
  //     return $http
  //       .get(ugBaseUrl + job.metadata.connections.includes);
  //   };
  // }
  //
  // function requestGetter(seq) {
  //   return function(){
  //     return $http
  //       .get(ugBaseUrl + seq.metadata.connections.references);
  //   };
  // }
  //
  // function requestAppender(seq) {
  //   return function(resp){
  //     log.write('requests: ' + JSON.stringify(resp.data.entities, null, 2));
  //     seq.requests = resp.data.entities;
  //     return true;
  //   };
  // }
  //
  // function jobAmender(job) {
  //   return function(resp) {
  //     var seq, p, i, L;
  //     log.write('sequences: ' + JSON.stringify(resp.data.entities, null, 2));
  //     job.sequences = resp.data.entities;
  //     p = $q.when(true);
  //     for (i=0, L=job.sequences.length; i<L; i++) {
  //       seq = job.sequences[i];
  //       p = p.then(requestGetter(seq))
  //         .then(requestAppender(seq));
  //     }
  //     return p;
  //   };
  // }

  function trackFailure(e) {
    log.write(JSON.stringify(e, null, 2));
  }

  function initialRetrieve() {
    var url = loadgenUrl + '/jobs' + '?limit=100';
    log.write('get items from Loadgen... ' + url);

    //httpConfig = { headers:{ 'Authorization': 'Bearer ' + token, 'Accept': 'application/json'} };

    $http.get(url)
      .success(function(data, statusCode, hdrsGetterFn, more){
        log.write('got ' + data.length + ' jobs');
        $scope.jobRecords = data;
      })
      .error(function(response, code /*, headers, config */) {
        log.write('failed to get items from UG: ' + JSON.stringify(response,null,2) + ' ' + code);
      });
  }

  $scope.addJob = function () {
    // AFAIK, nobody calls this. There is no UI for this.
    var job = new Job($scope.newJobName, $scope.newJobDescrip, {});
    log.write('New job: ' + $scope.newJobName);
    $http.post(jobsUrl, job)
      .success(function(newJob){
        log.write('New job created:' + JSON.stringify(newJob));
        $scope.jobRecords.push( newJob );
        rec.uuid = newJob.uuid;
        $scope.newJobName = '';
        $scope.newJobDescrip = '';
      })
      .error(function(data, status, headers, config) {
        log.write('creation failed...' + JSON.stringify(data));
      });
    $scope.newJobName = '';
  };

  $scope.itemNormalizationFunction = function(item) {
    var val = item[$scope.sortKey];
    if ($scope.sortKey === 'created' || $scope.sortKey === 'conducted') {
      if (isNaN(val)) { return 0;}
      return val;
    }
    return val;
  };

  $scope.setSort = function($event) {
    var oldKey = $scope.sortKey,
        header = $event.currentTarget.innerHTML,
        fakeItem = new Job('this is fake', 'and this', {});
    if (fakeItem.hasOwnProperty(header.toLowerCase())) {
      $scope.sortKey = header.toLowerCase();
    }
    else if (header === 'Desc'){
      $scope.sortKey = 'description';
    }
    else if (header === 'id'){
      $scope.sortKey = 'uuid';
    }

    if (oldKey === $scope.sortKey) {
      $scope.sortReverse = !$scope.sortReverse;
    }
    else {
      $scope.sortReverse = false;
    }
  };

  $scope.deleteItem = function(item) {
    var url = jobsUrl + '/' + item.uuid;
    log.write('delete item: ' + item.uuid);
    log.write('delete url: ' + url);
    $http.delete(url, httpConfig)
      .success(function(content) {
        log.write('deleted:' + JSON.stringify(content));
      })
      .error(function(data, status, headers, config) {
        log.write('Deletion failed...' + JSON.stringify(data));
      });
    $scope.jobRecords.splice($scope.jobRecords.indexOf(item),1);
  };

  $scope.toggleDetails = function(item, $event) {
    var ix = $scope.showDetails.indexOf(item.uuid);
    if (ix === -1) {
      // make the corresponding icon a minus (collapse)
      angular.element($event.target).addClass( 'icon-minus' );
      angular.element($event.target).removeClass( 'icon-plus' );
      $scope.showDetails.push(item.uuid);
    }
    else {
      // swap icon back to plus
      angular.element($event.target).addClass( 'icon-plus' );
      angular.element($event.target).removeClass( 'icon-minus' );
      $scope.showDetails.splice(ix, 1);
    }
  };

  $scope.wantDetails = function(item) {
    return ($scope.showDetails.indexOf(item.uuid) !== -1);
  };

  $scope.updateItemProp = function(value, previousValue, item, propName) {
    var url = jobsUrl + '/' + item.uuid;
    log.write('Item ' + propName + ': ' + item.uuid + ', ' + value);
    item[propName] = value;
    $http.put(url, item)
      .success(function( /* content */ ) {
        log.write('UG updated, ' + propName + ':' + item[propName]);
      })
      .error(function(data, status, headers, config) {
        log.write('Update failed...' + JSON.stringify(data));
      });
  };

  $scope.getTotalRecords = function () {
    return $scope.jobRecords.length;
  };
}

function LoginRegisterDialogController ($scope, dialog, dialogModel, title, wantIdentity) {
  $scope.dialogModel = dialogModel;
  $scope.title = title;
  $scope.wantIdentity = wantIdentity;
  $scope.cancel = function(){
    dialog.close();
  };
  $scope.login = function(result){
    dialog.close(result);
  };
}

function InitialContextDialogController ($scope, dialog, initialContext, title) {
  $scope.initialContext = initialContext;
  $scope.title = title;
  $scope.cancel = function(){
    dialog.close();
  };
  $scope.submit = function(result){
    if ( ! result ) {result = {payload:{}};}
    dialog.close(result);
  };
}

function JobEditorController ($scope, dialog, dialogModel, job) {
  $scope.dialogModel = dialogModel;
  $scope.job = job;
  $scope.cancel = function(){
    dialog.close();
  };
  $scope.save = function(modJob){
    dialog.close(modJob);
  };
}

function CollapseDemoController($scope) {
  $scope.isCollapsed = true;
  $scope.getButtonSymbol = function() {
    return ($scope.isCollapsed) ? '<' : '>';
  };
}


text:
FROM debian:buster

LABEL maintainer=<@WebSciDL>

WORKDIR /src

RUN apt update && apt-get install -y \
      dumb-init \
      git \
      make \
      python-pygments \
      texlive-full \
    && rm -rf /var/lib/apt/lists/*

COPY . /src

CMD ["make"]

redpajama_set_name: RedPajamaGithub


text:
"""Build wiki page with a list of all samples.

The information for the wiki page is built from data found in all the README
files in the samples. The format of the README file is:

   Description is everything up to the first blank line.

   api: plus  (Used to look up the long name in discovery).
   keywords: appengine (such as appengine, oauth2, cmdline)

   The rest of the file is ignored when it comes to building the index.
"""
from __future__ import print_function

import httplib2
import itertools
import json
import os
import re

BASE_HG_URI = "http://code.google.com/p/google-api-python-client/source/" "browse/#hg"

http = httplib2.Http(".cache")
r, c = http.request("https://www.googleapis.com/discovery/v1/apis")
if r.status != 200:
    raise ValueError("Received non-200 response when retrieving Discovery.")

# Dictionary mapping api names to their discovery description.
DIRECTORY = {}
for item in json.loads(c)["items"]:
    if item["preferred"]:
        DIRECTORY[item["name"]] = item

# A list of valid keywords. Should not be taken as complete, add to
# this list as needed.
KEYWORDS = {
    "appengine": "Google App Engine",
    "oauth2": "OAuth 2.0",
    "cmdline": "Command-line",
    "django": "Django",
    "threading": "Threading",
    "pagination": "Pagination",
    "media": "Media Upload and Download",
}

def get_lines(name, lines):
    """Return lines that begin with name.

  Lines are expected to look like:

     name: space separated values

  Args:
    name: string, parameter name.
    lines: iterable of string, lines in the file.

  Returns:
    List of values in the lines that match.
  """
    retval = []
    matches = itertools.ifilter(lambda x: x.startswith(name + ":"), lines)
    for line in matches:
        retval.extend(line[len(name) + 1 :].split())
    return retval

def wiki_escape(s):
    """Detect WikiSyntax (i.e. InterCaps, a.k.a. CamelCase) and escape it."""
    ret = []
    for word in s.split():
        if re.match(r"[A-Z]+[a-z]+[A-Z]", word):
            word = "!%s" % word
        ret.append(word)
    return " ".join(ret)

def context_from_sample(api, keywords, dirname, desc, uri):
    """Return info for expanding a sample into a template.

  Args:
    api: string, name of api.
    keywords: list of string, list of keywords for the given api.
    dirname: string, directory name of the sample.
    desc: string, long description of the sample.
    uri: string, uri of the sample code if provided in the README.

  Returns:
    A dictionary of values useful for template expansion.
  """
    if uri is None:
        uri = BASE_HG_URI + dirname.replace("/", "%2F")
    else:
        uri = "".join(uri)
    if api is None:
        return None
    else:
        entry = DIRECTORY[api]
        context = {
            "api": api,
            "version": entry["version"],
            "api_name": wiki_escape(entry.get("title", entry.get("description"))),
            "api_desc": wiki_escape(entry["description"]),
            "api_icon": entry["icons"]["x32"],
            "keywords": keywords,
            "dir": dirname,
            "uri": uri,
            "desc": wiki_escape(desc),
        }
        return context

def keyword_context_from_sample(keywords, dirname, desc, uri):
    """Return info for expanding a sample into a template.

  Sample may not be about a specific api.

  Args:
    keywords: list of string, list of keywords for the given api.
    dirname: string, directory name of the sample.
    desc: string, long description of the sample.
    uri: string, uri of the sample code if provided in the README.

  Returns:
    A dictionary of values useful for template expansion.
  """
    if uri is None:
        uri = BASE_HG_URI + dirname.replace("/", "%2F")
    else:
        uri = "".join(uri)
    context = {
        "keywords": keywords,
        "dir": dirname,
        "uri": uri,
        "desc": wiki_escape(desc),
    }
    return context

def scan_readme_files(dirname):
    """Scans all subdirs of dirname for README files.

  Args:
    dirname: string, name of directory to walk.

  Returns:
    (samples, keyword_set): list of information about all samples, the union
      of all keywords found.
  """
    samples = []
    keyword_set = set()

    for root, dirs, files in os.walk(dirname):
        if "README" in files:
            filename = os.path.join(root, "README")
            with open(filename, "r") as f:
                content = f.read()
                lines = content.splitlines()
                desc = " ".join(itertools.takewhile(lambda x: x, lines))
                api = get_lines("api", lines)
                keywords = get_lines("keywords", lines)
                uri = get_lines("uri", lines)
                if not uri:
                    uri = None

                for k in keywords:
                    if k not in KEYWORDS:
                        raise ValueError(
                            "%s is not a valid keyword in file %s" % (k, filename)
                        )
                keyword_set.update(keywords)
                if not api:
                    api = [None]
                samples.append((api[0], keywords, root[1:], desc, uri))

    samples.sort()

    return samples, keyword_set

def main():
    # Get all the information we need out of the README files in the samples.
    samples, keyword_set = scan_readme_files("./samples")

    # Now build a wiki page with all that information. Accumulate all the
    # information as string to be concatenated when were done.
    page = ['<wiki:toc max_depth="3" />\n= Samples By API =\n']

    # All the samples, grouped by API.
    current_api = None
    for api, keywords, dirname, desc, uri in samples:
        context = context_from_sample(api, keywords, dirname, desc, uri)
        if context is None:
            continue
        if current_api != api:
            page.append(
                """
=== %(api_icon)s %(api_name)s ===

%(api_desc)s

Documentation for the %(api_name)s in [https://google-api-client-libraries.appspot.com/documentation/%(api)s/%(version)s/python/latest/ PyDoc]

"""
                % context
            )
            current_api = api

        page.append("|| [%(uri)s %(dir)s] || %(desc)s ||\n" % context)

    # Now group the samples by keywords.
    for keyword, keyword_name in KEYWORDS.iteritems():
        if keyword not in keyword_set:
            continue
        page.append("\n= %s Samples =\n\n" % keyword_name)
        page.append("
\n")
        for _, keywords, dirname, desc, uri in samples:
            context = keyword_context_from_sample(keywords, dirname, desc, uri)
            if keyword not in keywords:
                continue
            page.append(
                """

  [%(uri)s %(dir)s]
   %(desc)s

"""
                % context
            )
        page.append("
\n")

    print("".join(page))

if __name__ == "__main__":
    main()


text:
/* @flow */
import styled from '@emotion/styled';
import React from 'react';
import Button from '../../../../../../library/Button';
import Popover from '../../../../../../library/Popover';
import { pxToEm } from '../../../../../../library/styles';
import { ThemeProvider } from '../../../../../../library/themes';
import DemoContent from '../../common/DemoContent';
import type { StyledComponent } from '@emotion/styled-base/src/utils';

const Root: StyledComponent<{ [key: string]: any }> = styled('div')({
  paddingBottom: pxToEm(130)
});

const DemoLayout = (props: Object) => <Root {...props} />;

export default {
  id: 'rtl',
  title: 'Bidirectionality',
  description: `Popovers support right-to-left (RTL) languages. The placement of
the content as well as the content itself will be reversed when the
\`direction\` theme variable is set to \`rtl\`.`,
  scope: { Button, DemoContent, DemoLayout, Popover, ThemeProvider },
  source: `
    <DemoLayout dir="rtl">
      <ThemeProvider theme={{ direction: 'rtl' }}>
        <Popover content={<DemoContent />} isOpen placement="bottom-start">
          <Button>Open Popover</Button>
        </Popover>
      </ThemeProvider>
    </DemoLayout>`
};


text:
package com.sksamuel.elastic4s.requests.cat

import com.fasterxml.jackson.annotation.JsonProperty

case class CatAliasResponse(alias: String, index: String, filter: String, routing: Routing)
case class Routing(index: String, search: String)

case class CatSegmentsResponse(
  index: String,
  shard: String,
  prirep: String,
  ip: String,
  segment: String,
  generation: String,
  @JsonProperty("docs.count") docsCount: Long,
  @JsonProperty("docs.deleted") docsDeleted: Long,
  size: Long,
  @JsonProperty("size.memory") sizeMemory: Long,
  committed: Boolean,
  searchable: Boolean,
  version: String,
  compound: Boolean
)

case class CatShardsResponse(index: String,
                             shard: String,
                             prirep: String,
                             state: String,
                             docs: Long,
                             store: Long,
                             ip: String,
                             node: String)

case class CatMasterResponse(id: String, host: String, ip: String, node: String)

case class CatIndicesResponse(health: String,
                              status: String,
                              index: String,
                              uuid: String,
                              pri: Int,
                              rep: Int,
                              @JsonProperty("docs.count") count: Long,
                              @JsonProperty("docs.deleted") deleted: Long,
                              @JsonProperty("store.size") storeSize: Long,
                              @JsonProperty("pri.store.size") priStoreSize: Long)

case class CatAllocationResponse(shards: Int,
                                 @JsonProperty("disk.indices") diskIndices: Long,
                                 @JsonProperty("disk.used") diskUsed: Long,
                                 @JsonProperty("disk.avail") diskAvailable: Long,
                                 @JsonProperty("disk.total") diskTotal: Long,
                                 @JsonProperty("disk.percent") diskPercent: Double,
                                 host: String,
                                 ip: String,
                                 node: String)

case class CatCountResponse(epoch: Long, timestamp: String, count: Long)

case class CatPluginResponse(name: String, component: String, version: String)

case class CatNodesResponse(id: String,
                            ip: String,
                            pid: String,
                            cpu: Double,
                            uptime: String,
                            @JsonProperty("heap.percent") heapPercent: Double,
                            @JsonProperty("ram.percent") ramPercent: Double,
                            port: Int,
                            load_1m: Double,
                            load_5m: Double,
                            load_15m: Double,
                            @JsonProperty("node.role") nodeRole: String,
                            master: String,
                            name: String)

case class CatHealthResponse(epoch: Long,
                             timestamp: String,
                             cluster: String,
                             status: String,
                             @JsonProperty("node.total") nodeTotal: Long,
                             @JsonProperty("node.data") nodeData: Long,
                             shards: Int,
                             pri: Int,
                             relo: Int,
                             init: Int,
                             unassign: Int,
                             @JsonProperty("pending_tasks") pendingTasks: Int,
                             @JsonProperty("max_task_wait_time") maxTaskWaitTime: String,
                             @JsonProperty("active_shards_percent") activeShardsPercent: String)

case class CatThreadPoolResponse(id: String,
                                 name: String,
                                 active: Int,
                                 rejected: Int,
                                 completed: Long,
                                 `type`: String,
                                 size: Int,
                                 queue: Int,
                                 @JsonProperty("queue_size") queueSize: Int,
                                 largest: Int,
                                 min: Int,
                                 max: Int,
                                 @JsonProperty("keep_alive") keepAlive: String,
                                 node_id: String,
                                 pid: Int,
                                 host: String,
                                 ip: String,
                                 port: String)


text:
package com.stephentuso.welcome;

import android.support.test.runner.AndroidJUnit4;
import android.support.v4.app.Fragment;
import android.view.View;

import org.junit.Test;
import org.junit.runner.RunWith;

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

/**
 * Created by stephentuso on 10/23/16.
 */
@RunWith(AndroidJUnit4.class)
public class ViewWrapperAndroidTest extends ActivityTest {

    WelcomeConfiguration.Builder builder;
    WelcomeViewWrapper viewWrapper;
    View view;

    @Override
    public void initActivity() {
        super.initActivity();
        builder =  new WelcomeConfiguration.Builder(activity)
                .animateButtons(false)
                .page(new FragmentWelcomePage() {
                    @Override
                    protected Fragment fragment() {
                        return null;
                    }
                })
                .page(new FragmentWelcomePage() {
                    @Override
                    protected Fragment fragment() {
                        return null;
                    }
                })
                .page(new FragmentWelcomePage() {
                    @Override
                    protected Fragment fragment() {
                        return null;
                    }
                });
        view = new View(activity);
        viewWrapper = new WelcomeViewWrapper(view) {
            @Override
            public void onPageSelected(int pageIndex, int firstPageIndex, int lastPageIndex) {

            }
        };
        viewWrapper.setup(builder.build());
    }

    private void assertVisible() {
        assertVisible(view);
    }

    private void assertVisible(View view) {
        assertEquals(View.VISIBLE, view.getVisibility());
    }

    private void assertInvisible() {
        assertInvisible(view);
    }

    private void assertInvisible(View view) {
        assertEquals(View.INVISIBLE, view.getVisibility());
    }

    @Test
    public void testGetView() {
        assertSame(view, viewWrapper.getView());
    }

    @Test
    public void testVisibility() {
        viewWrapper.setVisibility(false);
        assertInvisible();
        assertFalse(view.isEnabled());
        viewWrapper.setVisibility(true);
        assertVisible();
        assertTrue(view.isEnabled());
    }

    @Test
    public void testDoneButton() {
        DoneButton doneButton = new DoneButton(view);
        doneButton.setup(builder.build());
        doneButton.onPageSelected(2, 0, 4);
        assertInvisible();
        doneButton.onPageSelected(3, 0, 3);
        assertVisible();
        doneButton.onPageSelected(4, 0, 3);
        assertVisible();

        doneButton.setup(builder.useCustomDoneButton(true).build());
        doneButton.onPageSelected(2, 0, 2);
        assertInvisible();
        doneButton.onPageSelected(3, 0, 2);
        assertInvisible();

    }

    @Test
    public void testNextButton() {
        NextButton nextButton = new NextButton(view);
        nextButton.setup(builder.build());
        nextButton.onPageSelected(1, 0, 4);
        assertVisible();
        nextButton.onPageSelected(0, 0, 4);
        assertVisible();
        nextButton.onPageSelected(3, 0, 3);
        assertInvisible();
        nextButton.onPageSelected(5, 0, 3);
        assertInvisible();

        nextButton.setup(builder.showNextButton(false).build());
        nextButton.onPageSelected(1, 0, 4);
        assertInvisible();
        nextButton.onPageSelected(0, 0, 4);
        assertInvisible();
        nextButton.onPageSelected(3, 0, 3);
        assertInvisible();
        nextButton.onPageSelected(5, 0, 3);
        assertInvisible();
    }

    @Test
    public void testSkipButton() {
        SkipButton skipButton = new SkipButton(view);
        skipButton.setup(builder.build());
        skipButton.onPageSelected(1, 0, 4);
        assertVisible();
        skipButton.onPageSelected(0, 0, 4);
        assertVisible();
        skipButton.onPageSelected(3, 0, 3);
        assertInvisible();
        skipButton.onPageSelected(5, 0, 3);
        assertInvisible();

        skipButton.setup(builder.showPrevButton(true).build());
        skipButton.onPageSelected(0, 0, 4);
        assertVisible();
        skipButton.onPageSelected(2, 0, 4);
        assertInvisible();

        skipButton.setup(builder.showPrevButton(false).canSkip(false).build());
        skipButton.onPageSelected(1, 0, 4);
        assertInvisible();
        skipButton.onPageSelected(0, 0, 4);
        assertInvisible();
        skipButton.onPageSelected(3, 0, 3);
        assertInvisible();
        skipButton.onPageSelected(5, 0, 3);
        assertInvisible();
    }

    @Test
    public void testPrevButton() {
        PreviousButton prevButton = new PreviousButton(view);
        prevButton.setup(builder.build());
        prevButton.onPageSelected(0, 0, 3);
        assertInvisible();
        prevButton.onPageSelected(2, 0, 4);
        assertInvisible();

        prevButton.setup(builder.showPrevButton(true).build());
        prevButton.onPageSelected(0, 0, 4);
        assertInvisible();
        prevButton.onPageSelected(1, 0, 3);
        assertVisible();
        prevButton.onPageSelected(4, 0, 3);
        assertVisible();
    }

}


text:
select id from tbl_enterprise_structure where pId=? order by sort;
update tbl_enterprise_structure set lid=?,rid=? where id=?;
update tbl_enterprise_structure d
left join (
    select node.id,count(distinct s.id) cnt from tbl_enterprise_structure node
    left join tbl_enterprise_structure desendant on desendant.lid between node.lid and node.rid
    left join tbl_enterprise_staff s on s.department_id=desendant.id
    group by node.id
) x on x.id=d.id
set d.staff_count=x.cnt;


text:
namespace net {

TEST(VerifyNameMatchTest, Simple) {
  // TODO(mattm): Use valid Names.
  const uint8_t hello[] = {'h', 'e', 'l', 'l', 'o'};
  const uint8_t aello[] = {'a', 'e', 'l', 'l', 'o'};
  const uint8_t hello1[] = {'h', 'e', 'l', 'l', 'o', '1'};
  EXPECT_TRUE(VerifyNameMatch(der::Input(hello), der::Input(hello)));
  EXPECT_FALSE(VerifyNameMatch(der::Input(aello), der::Input(hello)));
  EXPECT_FALSE(VerifyNameMatch(der::Input(hello), der::Input(hello1)));
  EXPECT_FALSE(VerifyNameMatch(der::Input(hello1), der::Input(hello)));
}

}  // namespace net


text:
require 'spec_helper'

describe CloudFormer::EFS::FileSystem do
  it "should generate correct json" do
    fs = CloudFormer::EFS::FileSystem.new('file_system') do
      file_system_tags :list do
        entry do
          key 'Name'
          value 'TestFileSystem'
        end
      end
    end

    expect(fs.dump_json).to eq({
      "Type" => "AWS::EFS::FileSystem",
      "Properties" => {
        "FileSystemTags" => [
          {
            "Key" => "Name",
            "Value" => "TestFileSystem",
          },
        ]
      }
    })
  end
end


text:
module Inquery
  module Exceptions
    class Base < StandardError; end
    class UnknownCallSignature < Base; end
    class InvalidRelation < Base; end
  end
end


text:
/*global window*/
(function (module) {
	module.exports = function ($) {
		return function (whom) {
			if (whom === undefined) {
				whom = 'developer';
			}
			return 'Welcome, ' + whom + '!';
		};
	};
}((typeof window === 'undefined') ? module : window.thorny_path('./thorny-spec-demo/common/welcome')));


text:
package org.teavm.classlib.java.text;

public class TParsePosition {

    private int currentPosition, errorIndex = -1;

    public TParsePosition(int index) {
        currentPosition = index;
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof TParsePosition)) {
            return false;
        }
        TParsePosition pos = (TParsePosition) object;
        return currentPosition == pos.currentPosition && errorIndex == pos.errorIndex;
    }

    public int getErrorIndex() {
        return errorIndex;
    }

    public int getIndex() {
        return currentPosition;
    }

    @Override
    public int hashCode() {
        return currentPosition + errorIndex;
    }

    public void setErrorIndex(int index) {
        errorIndex = index;
    }

    public void setIndex(int index) {
        currentPosition = index;
    }

    @Override
    public String toString() {
        return getClass().getName() + "[index=" + currentPosition + ", errorIndex=" + errorIndex + "]";
    }
}


text:
import json

import pytest
from M2Crypto import BIO
from M2Crypto import SMIME
from M2Crypto import X509
from path import Path

from passbook.models import Barcode, BarcodeFormat, CurrencyField, Pass, StoreCard

cwd = Path(__file__).parent

wwdr_certificate = cwd / 'certificates' / 'wwdr_certificate.pem'
certificate = cwd / 'certificates' / 'certificate.pem'
key = cwd / 'certificates' / 'private.key'
password_file = cwd / 'certificates' / 'password.txt'

def create_shell_pass(barcodeFormat=BarcodeFormat.CODE128):
    cardInfo = StoreCard()
    cardInfo.addPrimaryField('name', u'Jähn Doe', 'Name')
    stdBarcode = Barcode('test barcode', barcodeFormat, 'alternate text')
    passfile = Pass(cardInfo, organizationName='Org Name', passTypeIdentifier='Pass Type ID', teamIdentifier='Team Identifier')
    passfile.barcode = stdBarcode
    passfile.serialNumber = '1234567'
    passfile.description = 'A Sample Pass'
    return passfile

def test_basic_pass():
    passfile = create_shell_pass()
    assert passfile.formatVersion == 1
    assert passfile.barcode.format == BarcodeFormat.CODE128
    assert len(passfile._files) == 0

    passfile_json = passfile.json_dict()
    assert passfile_json is not None
    assert passfile_json['suppressStripShine'] == False
    assert passfile_json['formatVersion'] == 1
    assert passfile_json['passTypeIdentifier'] == 'Pass Type ID'
    assert passfile_json['serialNumber'] == '1234567'
    assert passfile_json['teamIdentifier'] == 'Team Identifier'
    assert passfile_json['organizationName'] == 'Org Name'
    assert passfile_json['description'] == 'A Sample Pass'

def test_manifest_creation():
    passfile = create_shell_pass()
    manifest_json = passfile._createManifest(passfile._createPassJson())
    manifest = json.loads(manifest_json)
    assert 'pass.json' in manifest

def test_header_fields():
    passfile = create_shell_pass()
    passfile.passInformation.addHeaderField('header', 'VIP Store Card', 'Famous Inc.')
    pass_json = passfile.json_dict()
    assert pass_json['storeCard']['headerFields'][0]['key'] == 'header'
    assert pass_json['storeCard']['headerFields'][0]['value'] == 'VIP Store Card'
    assert pass_json['storeCard']['headerFields'][0]['label'] == 'Famous Inc.'

def test_secondary_fields():
    passfile = create_shell_pass()
    passfile.passInformation.addSecondaryField('secondary', 'VIP Store Card', 'Famous Inc.')
    pass_json = passfile.json_dict()
    assert pass_json['storeCard']['secondaryFields'][0]['key'] == 'secondary'
    assert pass_json['storeCard']['secondaryFields'][0]['value'] == 'VIP Store Card'
    assert pass_json['storeCard']['secondaryFields'][0]['label'] == 'Famous Inc.'

def test_back_fields():
    passfile = create_shell_pass()
    passfile.passInformation.addBackField('back1', 'VIP Store Card', 'Famous Inc.')
    pass_json = passfile.json_dict()
    assert pass_json['storeCard']['backFields'][0]['key'] == 'back1'
    assert pass_json['storeCard']['backFields'][0]['value'] == 'VIP Store Card'
    assert pass_json['storeCard']['backFields'][0]['label'] == 'Famous Inc.'

def test_auxiliary_fields():
    passfile = create_shell_pass()
    passfile.passInformation.addAuxiliaryField('aux1', 'VIP Store Card', 'Famous Inc.')
    pass_json = passfile.json_dict()
    assert pass_json['storeCard']['auxiliaryFields'][0]['key'] == 'aux1'
    assert pass_json['storeCard']['auxiliaryFields'][0]['value'] == 'VIP Store Card'
    assert pass_json['storeCard']['auxiliaryFields'][0]['label'] == 'Famous Inc.'

def test_code128_pass():
    """
    This test is to create a pass with a new code128 format,
    freezes it to json, then reparses it and validates it defaults
    the legacy barcode correctly
    """
    passfile = create_shell_pass()
    jsonData = passfile._createPassJson()
    thawedJson = json.loads(jsonData)
    assert thawedJson['barcode']['format'] == BarcodeFormat.PDF417
    assert thawedJson['barcodes'][0]['format'] == BarcodeFormat.CODE128

def test_pdf_417_pass():
    """
    This test is to create a pass with a barcode that is valid
    in both past and present versions of IOS
    """
    passfile = create_shell_pass(BarcodeFormat.PDF417)
    jsonData = passfile._createPassJson()
    thawedJson = json.loads(jsonData)
    assert thawedJson['barcode']['format'] == BarcodeFormat.PDF417
    assert thawedJson['barcodes'][0]['format'] == BarcodeFormat.PDF417

def test_files():
    passfile = create_shell_pass()
    passfile.addFile('icon.png', open(cwd / 'static/white_square.png', 'rb'))
    assert len(passfile._files) == 1
    assert 'icon.png' in passfile._files

    manifest_json = passfile._createManifest(passfile._createPassJson())
    manifest = json.loads(manifest_json)
    assert '170eed23019542b0a2890a0bf753effea0db181a' == manifest['icon.png']

    passfile.addFile('logo.png', open(cwd / 'static/white_square.png', 'rb'))
    assert len(passfile._files) == 2
    assert 'logo.png' in passfile._files

    manifest_json = passfile._createManifest(passfile._createPassJson())
    manifest = json.loads(manifest_json)
    assert '170eed23019542b0a2890a0bf753effea0db181a' == manifest['logo.png']

def test_signing():
    """
    This test can only run locally if you provide your personal Apple Wallet
    certificates, private key and password. It would not be wise to add
    them to git. Store them in the files indicated below, they are ignored
    by git.
    """
    try:
        with open(password_file) as file_:
            password = file_.read().strip()
    except IOError:
        password = ''

    passfile = create_shell_pass()
    manifest_json = passfile._createManifest(passfile._createPassJson())
    signature = passfile._sign_manifest(
        manifest_json,
        certificate,
        key,
        wwdr_certificate,
        password,
    )

    smime = passfile._get_smime(
        certificate,
        key,
        wwdr_certificate,
        password,
    )

    store = X509.X509_Store()
    try:
        store.load_info(bytes(wwdr_certificate, encoding='utf8'))
    except TypeError:
        store.load_info(str(wwdr_certificate))

    smime.set_x509_store(store)

    data_bio = BIO.MemoryBuffer(bytes(manifest_json, encoding='utf8'))

    # PKCS7_NOVERIFY = do not verify the signers certificate of a signed message.
    assert smime.verify(signature, data_bio, flags=SMIME.PKCS7_NOVERIFY) == bytes(manifest_json, encoding='utf8')

    tampered_manifest = bytes('{"pass.json": "foobar"}', encoding='utf8')
    data_bio = BIO.MemoryBuffer(tampered_manifest)
    # Verification MUST fail!
    with pytest.raises(SMIME.PKCS7_Error):
        smime.verify(signature, data_bio, flags=SMIME.PKCS7_NOVERIFY)

def test_passbook_creation():
    """
    This test can only run locally if you provide your personal Apple Wallet
    certificates, private key and password. It would not be wise to add
    them to git. Store them in the files indicated below, they are ignored
    by git.
    """
    try:
        with open(password_file) as file_:
            password = file_.read().strip()
    except IOError:
        password = ''

    passfile = create_shell_pass()
    passfile.addFile('icon.png', open(cwd / 'static' / 'white_square.png', 'rb'))
    passfile.create(certificate, key, wwdr_certificate, password)

def test_currency_field_has_no_numberstyle():
    balance_field = CurrencyField(
        'balance',
        float(22.00),
        'test label',
        'USD',
    )

    passfile = create_shell_pass()
    passfile.passInformation.headerFields.append(balance_field)

    pass_json = passfile.json_dict()
    assert 'currencyCode' in pass_json['storeCard']['headerFields'][0]
    assert 'numberStyle' not in pass_json['storeCard']['headerFields'][0]


text:
#import <AVFoundation/AVFoundation.h>
#import <Foundation/Foundation.h>

#import "RTCMacros.h"

NS_ASSUME_NONNULL_BEGIN

RTC_EXTERN const int kRTCAudioSessionPreferredNumberOfChannels;
RTC_EXTERN const double kRTCAudioSessionHighPerformanceSampleRate;
RTC_EXTERN const double kRTCAudioSessionLowComplexitySampleRate;
RTC_EXTERN const double kRTCAudioSessionHighPerformanceIOBufferDuration;
RTC_EXTERN const double kRTCAudioSessionLowComplexityIOBufferDuration;

// Struct to hold configuration values.
RTC_OBJC_EXPORT
@interface RTCAudioSessionConfiguration : NSObject

@property(nonatomic, strong) NSString *category;
@property(nonatomic, assign) AVAudioSessionCategoryOptions categoryOptions;
@property(nonatomic, strong) NSString *mode;
@property(nonatomic, assign) double sampleRate;
@property(nonatomic, assign) NSTimeInterval ioBufferDuration;
@property(nonatomic, assign) NSInteger inputNumberOfChannels;
@property(nonatomic, assign) NSInteger outputNumberOfChannels;

/** Initializes configuration to defaults. */
- (instancetype)init NS_DESIGNATED_INITIALIZER;

/** Returns the current configuration of the audio session. */
+ (instancetype)currentConfiguration;
/** Returns the configuration that WebRTC needs. */
+ (instancetype)webRTCConfiguration;
/** Provide a way to override the default configuration. */
+ (void)setWebRTCConfiguration:(RTCAudioSessionConfiguration *)configuration;

@end

NS_ASSUME_NONNULL_END


text:
from .viewport_helpers import compute_view  # noqa
from .type_checking import has_geo_interface, is_pandas_df, records_from_geo_interface  # noqa
from .color_scales import assign_random_colors  # noqa


text:
namespace AvalonDock.TestApp
{
    partial class UserControl1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(16, 40);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(121, 20);
            this.textBox1.TabIndex = 0;
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(16, 94);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(121, 20);
            this.textBox2.TabIndex = 0;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(22, 17);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(52, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "TextBox1";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(22, 78);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(52, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "TextBox2";
            //
            // UserControl1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Name = "UserControl1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
    }
}


text:
using GenderPayGap.Core;
using System;
using System.ComponentModel.DataAnnotations;

namespace GenderPayGap.WebUI.Classes
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
    public class DUNSNumberAttribute : RegularExpressionAttribute
    {
        private const string pattern = @"^[0-9]{9}$";

        public DUNSNumberAttribute() : base(pattern)
        {
            ErrorMessage = Global.CompanyNumberRegexError;
        }
    }
}


text:
local os = _G.os

local shell = require("shellex.shell")
local args = shell.parse(...)
local hostname = args[1]

if hostname then
	os.setComputerLabel(hostname)
else
	hostname = os.getComputerLabel()
	if hostname then
		print(hostname)
	else
		io.stderr:write("Hostname not set\n")
		return 1
	end
end


text:
SparkleFormation.build do
  registry! :bootstrap
  registry! :core_params
  registry! :core_vpc_params
end


text:
/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-07 The eXist Project
 *  http://exist-db.org
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * $Id: ValidationFunctions_DTD_Test.java 6709 2007-10-12 20:58:52Z dizzzz $
 */
package org.exist.validation;

import junit.framework.TestCase;
import junit.textui.TestRunner;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import org.exist.storage.DBBroker;
import org.exist.xmldb.DatabaseInstanceManager;
import org.exist.xquery.XPathException;

import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.modules.XPathQueryService;

/**
 *  Set of Tests for validation:validate($a) and validation:validate($a, $b)
 * regaring validatin using DTD's.
 *
 * @author Dannes Wessels (dizzzz@exist-db.org)
 */
public class ValidationFunctions_DTD_Test extends TestCase {

    private final static Logger logger = Logger.getLogger(ValidationFunctions_DTD_Test.class);

    private static XPathQueryService service;
    private static Collection root = null;
    private static Database database = null;

    public static void main(String[] args) throws XPathException {
        TestRunner.run(ValidationFunctions_XSD_Test.class);
    }

    public ValidationFunctions_DTD_Test(String arg0) {
        super(arg0);
    }

    public void testsetUp() throws Exception {

        System.out.println(this.getName());
        BasicConfigurator.configure();
        logger.info(this.getName());

        Class cl = Class.forName("org.exist.xmldb.DatabaseImpl");
        database = (Database) cl.newInstance();
        database.setProperty("create-database", "true");
        DatabaseManager.registerDatabase(database);
        root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", null);
        service = (XPathQueryService) root.getService( "XQueryService", "1.0" );
    }

    // ===========================================================

    private void clearGrammarCache() {
        logger.info("Clearing grammar cache");
        ResourceSet result = null;
        try {
            result = service.query("validation:clear-grammar-cache()");

        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            fail(e.getMessage());
        }
    }

    // ===========================================================

    public void testValidateUsingSystemCatalog() {

        System.out.println(this.getName());
        logger.info(this.getName());

        ResourceSet result = null;
        String r = null;
        try {
            // DTD for hamlet_valid.xml is registered in system catalog.
            // result should be "document is valid"
            result = service.query(
                "validation:validate( xs:anyURI('"+TestTools.VALIDATION_TMP+"/hamlet_valid.xml') )");
            r = (String) result.getResource(0).getContent();
            assertEquals( "hamlet_valid.xml in systemcatalog", "true", r );

        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            fail(e.getMessage());
        }
    }

    public void testSpecifiedCatalog() {

        System.out.println(this.getName());
        logger.info(this.getName());

        clearGrammarCache();

        ResourceSet result = null;
        String r = null;
        try {
            logger.info("Test1");
            result = service.query(
                "validation:validate( xs:anyURI('"+TestTools.VALIDATION_HOME+"/hamlet_valid.xml') ,"
                +" xs:anyURI('/db/validation/dtd/catalog.xml') )");
            r = (String) result.getResource(0).getContent();
            assertEquals("valid document", "true", r );

            clearGrammarCache();

            logger.info("Test2");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_invalid.xml') ,"
                +" xs:anyURI('/db/validation/dtd/catalog.xml') )");
            r = (String) result.getResource(0).getContent();
            assertEquals( "invalid document", "false", r );

            clearGrammarCache();

            logger.info("Test3");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_valid.xml'), "
                +" xs:anyURI('/db/validation/xsd/catalog.xml') )");
            r = (String) result.getResource(0).getContent();
            assertEquals("wrong catalog", "false", r );

            clearGrammarCache();

            logger.info("Test4");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_invalid.xml'), "
                +" xs:anyURI('/db/validation/xsd/catalog.xml') )");
            r = (String) result.getResource(0).getContent();
            assertEquals("wrong catalog, invalid document", "false", r );

        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            fail(e.getMessage());
        }
    }

    public void testSpecifiedGrammar() {

        System.out.println(this.getName());
        logger.info(this.getName());

        clearGrammarCache();

        ResourceSet result = null;
        String r = null;
        try {
            logger.info("Test1");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_valid.xml'), "
                +" xs:anyURI('/db/validation/dtd/hamlet.dtd') )");
            r = (String) result.getResource(0).getContent();
            assertEquals("valid document", "true", r );

            clearGrammarCache();

            logger.info("Test2");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_invalid.xml'), "
                +" xs:anyURI('/db/validation/dtd/hamlet.dtd') )");
            r = (String) result.getResource(0).getContent();
            assertEquals( "invalid document", "false", r );

            clearGrammarCache();

        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            fail(e.getMessage());
        }
    }

    public void testSearchedGrammar() {

        System.out.println(this.getName());
        logger.info(this.getName());

        clearGrammarCache();

        ResourceSet result = null;
        String r = null;
        try {

            logger.info("Test1");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_valid.xml'), "
                +" xs:anyURI('/db/validation/dtd/') )");
            r = (String) result.getResource(0).getContent();
            assertEquals("valid document", "true", r );

            clearGrammarCache();

            logger.info("Test2");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_valid.xml'), "
                +" xs:anyURI('/db/validation/xsd/') )");
            r = (String) result.getResource(0).getContent();
            assertEquals( "valid document, not found", "false", r );

            clearGrammarCache();

            logger.info("Test3");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_valid.xml'), "
                +" xs:anyURI('/db/') )");
            r = (String) result.getResource(0).getContent();
            assertEquals("valid document", "true", r );

            clearGrammarCache();

            logger.info("Test4");
            result = service.query(
                "validation:validate( xs:anyURI('/db/validation/hamlet_invalid.xml'), "
                +" xs:anyURI('/db/') )");
            r = (String) result.getResource(0).getContent();
            assertEquals( "invalid document", "false", r );

            clearGrammarCache();

        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            fail(e.getMessage());
        }
    }

    public void testtearDown() throws Exception {

        System.out.println(this.getName());
        logger.info(this.getName());

        DatabaseManager.deregisterDatabase(database);
        DatabaseInstanceManager dim =
            (DatabaseInstanceManager) root.getService("DatabaseInstanceManager", "1.0");
        dim.shutdown();

    }

}


text:
<?php

//-----------------------------------------------------------------
// Public class
//-----------------------------------------------------------------

/**
 * A gateway for collecting and modifying single rows in selected database table.
 *
 * @version	0.1.0
 * @author	Emil Johansson <emiljohansson.se@gmail.com>
 */
class RowGateway extends Gateway {

	//----------------------------------------------------------
	// Protected properties
	//----------------------------------------------------------

	/**
	 * Some fields should not be able to be updated, such as the Primary key.
	 * @var array
	 */
	protected $protectedFields = array('id');

	/**
	 * The record based on the database table, matching each field.
	 * @var Record
	 */
	protected $record;

	//----------------------------------------------------------
	// Constructor method
	//----------------------------------------------------------

	/**
	 * Initializes the database object and what table to connect to.
	 *
	 * @param	string	$tableName
	 * @return	void
	 */
	public function __construct($tableName) {
		parent::__construct($tableName);
		$this->record = new Record();
	}

	//----------------------------------------------------------
	// Public methods
	//----------------------------------------------------------

	/**
	 * Returns the record.
	 *
	 * @return	Record
	 */
	public function getRecord() {
		return $this->record;
	}

	/**
	 * Sets the record.
	 *
	 * @param	Record	$aRecord;
	 * @return	void
	 */
	public function setRecord(Record $aRecord) {
		$this->record = $aRecord;
	}

	/**
	 * Sets the records public data based on the values in the param.
	 *
	 * @param	array	$data
	 * @return	Record
	 */
	public function setRecordData($data) {
		foreach ($data as $key => $value) {
			if ($key == $this->primaryKey) {
				if (!isset($this->record->id)) {
					$this->record->$key = $value;
				}
			}
			else {
				$this->record->$key = $value;
			}
		}
		return $this->record;
	}

	/**
	 * Returns an array, containing all fields from the model.
	 *
	 * @return	array
	 */
	public function toArray() {
		return (array)$this->record;
	}

	/**
	 * Removes a row from the database table.
	 *
	 * @return	int	The number of affected rows.
	 * @throws	SQLException
	 */
	public function remove() {
		$query		= "DELETE FROM ".$this->table." WHERE ".$this->primaryKey." = ?";
		$statement	= new Statement($query);
		$statement->add($this->record->id);
		try {
			return $statement->executeUpdate();
		}
		catch (SQLException $e) {
			throw $e;
		}
	}

	/**
	 * Either updates or inserts a new row to the database.
	 *
	 * @return	Response
	 */
	public function save() {
		$recordArr = $this->toArray();
		if (!isset($recordArr[$this->primaryKey])) {
			return $this->insert();
		}
		return $this->update();
	}

	//----------------------------------------------------------
	// Protected methods
	//----------------------------------------------------------

	/**
	 * Inserts a new row to the database table.
	 *
	 * @todo	refactor
	 * @return	Response
	 */
	protected function insert() {
		$arr		= $this->toArray();
		$response	= new Response();
		$query		= "INSERT INTO ".$this->table;
		if (count($arr) < 1) {
			$arr[$this->primaryKey] = "NULL";
		}
		if (count($arr) === 1 && array_key_exists('id', $arr)) {
			$query .= "(".$this->primaryKey.") VALUES (NULL)";
			if ($this->database->query($query)) {
				$pk					= $this->primaryKey;
				$this->record->$pk	= $this->database->insert_id;
			}
			$response->add($this->toArray());
			return $response;
		}

		$query	.= " (";

		foreach ($arr as $key => $value) {
			if (!in_array($key, $this->protectedFields)) {
				$query .= $key.",";
			}
		}

		$query = substr_replace($query, ") ", -1);
		$query .= "VALUES (";

		foreach ($arr as $key => $value) {
			if (!in_array($key, $this->protectedFields)) {
				if ($value === null && $value !== "0") {
					$query .= "NULL,";
				}
				else {
					$query .= "'".$value."',";
				}
			}
		}

		$query = substr_replace($query, ") ", -1);

		try {
			$this->executeStatement($query, "Insert");
		}
		catch (SQLException $e) {
			$response->setStatusToError($e->message());
		}

		$pk					= $this->primaryKey;
		$this->record->$pk	= $this->database->insert_id;
		$response->add($this->toArray());
		return $response;
	}

	/**
	 * Updates a row in the database table.
	 *
	 * @return	boolean		Query success
	 */
	protected function update() {
		$arr	= $this->toArray();
		$query	= "UPDATE ".$this->table." SET ";
		foreach ($this->toArray() as $key => $value) {
			if (isset($value) && !in_array($key, $this->protectedFields)) {
				$query .= $key." = '".$value."', ";
			}
		}

		$query = substr($query, 0, count($query)-3);
		$query .= " WHERE ".$this->primaryKey." = ".$arr[$this->primaryKey];

		$this->executeStatement($query, "Update");

		$response	= new Response();
		$response->add($this->toArray());
		return $response;
	}

	//----------------------------------------------------------
	// Private methods
	//----------------------------------------------------------

	/**
	 * Executes a statement.
	 *
	 * @param	string	$query
	 * @param	string	$type	For the error text, I.e. upate or insert
	 * @throws	SQLException
	 */
	private function executeStatement($query, $type = "Query") {
		$statement	= new Statement($query);
		try {
			$statement->executeUpdate();
		}
		catch (SQLException $e) {
			throw $e;
		}
	}
}


text:
package es.deusto.weblab.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

import es.deusto.weblab.client.configuration.ConfigurationRetriever;
import es.deusto.weblab.client.lab.experiments.EntryRegistry;
import es.deusto.weblab.client.lab.experiments.ExperimentBase;
import es.deusto.weblab.client.lab.experiments.ExperimentCreator;
import es.deusto.weblab.client.lab.experiments.ExperimentFactory.IExperimentLoadedCallback;
import es.deusto.weblab.client.lab.experiments.IBoardBaseController;
import es.deusto.weblab.client.lab.experiments.IExperimentCreatorFactory;
import es.deusto.weblab.client.lab.experiments.JSBoardBaseController;
import es.deusto.weblab.client.lab.experiments.exceptions.ExperimentCreatorInstanciationException;
import es.deusto.weblab.client.ui.audio.AudioManager;

public class WebLabClient implements EntryPoint {

	public static String baseLocation;
	private static final String MAIN_SLOT = "weblab_slot";

    public void putWidget(Widget widget){
        while(RootPanel.get(WebLabClient.MAIN_SLOT).getWidgetCount() > 0)
            RootPanel.get(WebLabClient.MAIN_SLOT).remove(0);
        RootPanel.get(WebLabClient.MAIN_SLOT).add(widget);
    }

    public void showError(String message) {
    	putWidget(new Label(message));
    }

	@Override
	public void onModuleLoad() {
        HistoryProperties.reloadHistory();
		JSBoardBaseController.onConfigurationLoaded(new Runnable() {
			@Override
			public void run() {
				JSBoardBaseController.log("Configuration loaded. Starting GWT experiment...");
				JSBoardBaseController.show();

				final IBoardBaseController boardBaseController = new JSBoardBaseController();
				WebLabClient.baseLocation = JSBoardBaseController.getBaseLocation();
				JSBoardBaseController.log("Base location: " +  WebLabClient.baseLocation);

				final ConfigurationRetriever configurationRetriever = JSBoardBaseController.getExperimentConfiguration();
				AudioManager.initialize(configurationRetriever);
				final String clientCodeName = JSBoardBaseController.getClientCodeName();
				final IExperimentCreatorFactory experimentCreatorFactory = getExperimentFactory(clientCodeName);
				if (experimentCreatorFactory == null) {
					showError("client code name " + clientCodeName + " not implemented in GWT");
                    JSBoardBaseController.experimentLoaded();
					return;
				}

				final ExperimentCreator creator;
				try {
					creator = experimentCreatorFactory.createExperimentCreator(configurationRetriever);
				} catch (ExperimentCreatorInstanciationException e1) {
					showError("Could not instantiate experiment: " + e1.getMessage());
					e1.printStackTrace();
                    JSBoardBaseController.experimentLoaded();
					return;
				}

				final IExperimentLoadedCallback callback = new IExperimentLoadedCallback() {

					@Override
					public void onFailure(Throwable e) {
						JSBoardBaseController.log("Client code name " + clientCodeName + " not working: " + e.getMessage());
						showError("client code name " + clientCodeName + " not implemented in GWT");
                        JSBoardBaseController.experimentLoaded();
					}

					@Override
					public void onExperimentLoaded(ExperimentBase experiment) {
						JSBoardBaseController.log("GWT experiment loaded. Registering methods.");
						WebLabClient.this.putWidget(experiment.getWidget());
						JSBoardBaseController.registerExperiment(experiment);
					}
				};

				if (JSBoardBaseController.isMobile()) {
					creator.createMobile(boardBaseController, callback);
				} else {
					creator.createWeb(boardBaseController, callback);
				}
			}
		});
	}

	private IExperimentCreatorFactory getExperimentFactory(final String clientCodeName) {
		IExperimentCreatorFactory currentCreatorFactory = null;
		for(IExperimentCreatorFactory creatorFactory : EntryRegistry.creatorFactories) {
			if (creatorFactory.getCodeName().equals(clientCodeName)) {
				currentCreatorFactory = creatorFactory;
			}
		}
		return currentCreatorFactory;
	}
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>#golang #toolkit</title>

		<meta name="description" content="Slides pour bdxio2015, la boite à outils parfaite pour go">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/moon.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

#golang #toolkit

La boite à outils idéale

					Proposé par Benjamin Chenebault / @TheBenC_

				> From the beginning of the project, Go was designed with tools in mind.
				> Rob Pike, 2013

					Proposé par Benjamin Chenebault / @TheBenC_

Development tools

The basics

go clean

go build

go install

go run

gofmt, Le formatteur

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00000.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

goimport, Le formatteur ++

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00001.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

govet, le linter

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00002.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

gocover, le moteur de couverture

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00003.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

count covermode

golint, le checkstyle pour go

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00004.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

goerrcheck, le checker d'erreurs

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00005.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

Performance tools

Memory profiler

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00006.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

CPU profiler

					Proposé par Benjamin Chenebault / @TheBenC_

Benchmark et optimisations locales

					<video height="500px" autoplay>
					<source src="Kazam_screencast_00007.mp4" type="video/mp4">
					</video>

					Proposé par Benjamin Chenebault / @TheBenC_

Other tools

race detection

go test -race mypkg    // to test the package

go run -race mysrc.go  // to run the source file

go build -race mycmd   // to build the command

go install -race mypkg // to install the package

gocode, le démon d'autocomplétion

go oracle, le démon de navigation

					Proposé par Benjamin Chenebault / @TheBenC_

					blocking profiling, goroutine profiling, garbage collector trace, gcvis, cross compilation, etc

THE END

						- Try github.com/BenC-/generator-go

						- Try vim-go

						- Try GoSublime plugin


text:
/* $Id$ */
/*
 * Copyright (C) 2010 Teluu Inc. (http://www.teluu.com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef __PJLIB_UTIL_CLI_CONSOLE_H__
#define __PJLIB_UTIL_CLI_CONSOLE_H__

/**
 * @file cli_console.h
 * @brief Command Line Interface Console Front End API
 */

#include <pjlib-util/cli_imp.h>

PJ_BEGIN_DECL

/**
 * @ingroup PJLIB_UTIL_CLI_IMP
 * @{
 *
 */

/**
 * This structure contains various options for CLI console front-end.
 * Application must call pj_cli_console_cfg_default() to initialize
 * this structure with its default values.
 */
typedef struct pj_cli_console_cfg
{
    /**
     * Default log verbosity level for the session.
     *
     * Default value: PJ_CLI_CONSOLE_LOG_LEVEL
     */
    int log_level;

    /**
     * Specify text message as a prompt string to user.
     *
     * Default: empty
     */
    pj_str_t prompt_str;

    /**
     * Specify the command to quit the application.
     *
     * Default: empty
     */
    pj_str_t quit_command;

} pj_cli_console_cfg;

/**
 * Initialize pj_cli_console_cfg with its default values.
 *
 * @param param		The structure to be initialized.
 */
PJ_DECL(void) pj_cli_console_cfg_default(pj_cli_console_cfg *param);

/**
 * Create a console front-end for the specified CLI application, and return
 * the only session instance for the console front end. On Windows operating
 * system, this may open a new console window.
 *
 * @param cli		The CLI application instance.
 * @param param		Optional console CLI parameters. If this value is
 * 			NULL, default parameters will be used.
 * @param p_sess	Pointer to receive the session instance for the
 * 			console front end.
 * @param p_fe		Optional pointer to receive the front-end instance
 * 			of the console front-end just created.
 *
 * @return		PJ_SUCCESS on success, or the appropriate error code.
 */
PJ_DECL(pj_status_t) pj_cli_console_create(pj_cli_t *cli,
					   const pj_cli_console_cfg *param,
					   pj_cli_sess **p_sess,
					   pj_cli_front_end **p_fe);

/**
 * Retrieve a cmdline from console stdin and process the input accordingly.
 *
 * @param sess		The CLI session.
 * @param buf		Pointer to receive the buffer.
 * @param maxlen	Maximum length to read.
 *
 * @return		PJ_SUCCESS if an input was read
 */
PJ_DECL(pj_status_t) pj_cli_console_process(pj_cli_sess *sess,
					    char *buf,
					    unsigned maxlen);

/**
 * @}
 */

PJ_END_DECL

#endif /* __PJLIB_UTIL_CLI_CONSOLE_H__ */


text:
// Header for C3PaneAddressBook class

#ifndef __C3PANEADDRESSBOOK__MULBERRY__
#define __C3PANEADDRESSBOOK__MULBERRY__

#include "C3PaneViewPanel.h"

#include "CAddressBookView.h"

// Classes
class C3PaneAddressBook : public C3PaneViewPanel
{
	friend class C3PaneItems;

public:
					C3PaneAddressBook();
	virtual 		~C3PaneAddressBook();

	virtual void	Init();

			void	GetOpenItems(cdstrvect& items) const;
			void	CloseOpenItems();
			void	SetOpenItems(const cdstrvect& items);

	virtual void	DoClose();

	virtual bool	TestCloseAll();
	virtual void	DoCloseAll();

	virtual bool	TestCloseOne(unsigned long index);
	virtual void	DoCloseOne(unsigned long index);

	virtual bool	TestCloseOthers(unsigned long index);
	virtual void	DoCloseOthers(unsigned long index);

			void	SetUseSubstitute(bool subs);
			bool	GetUseSubstitute() const
		{ return mUseSubstitute; }
			bool	IsSubstituteLocked(unsigned long index) const;
			bool	IsSubstituteDynamic(unsigned long index) const;

	virtual bool	IsSpecified() const;

	virtual CBaseView*	GetBaseView() const;
	CAddressBookView*	GetAddressBookView()
		{ return &mAddressBookView; }

	virtual cdstring GetTitle() const;
	virtual UINT	GetIconID() const;

protected:
	CAddressBookView	mAddressBookView;
	bool				mDoneInit;
	bool				mUseSubstitute;

	// Generated message map functions
	//{{AFX_MSG()
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

#endif


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Bagliettoa limborioides A. Massal.

### Remarks
null


text:
package live;

import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;

import tools.JSON;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterObjectFactory;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;

/**
 * This class calls the Twitter streaming api
 * @author Han
 *
 */
public class LiveContentGrabber implements Runnable, Stoppable, OutputQueue<JSONObject> {

	private static final Logger logger = LogManager.getLogger("LiveContentGrabber");

	private TwitterStream twitterStream;

	public static long tweetCounter = 0;

	private int missedTweets;

	private Queue<JSONObject> output_queue;

	private List<String> words;

	public LiveContentGrabber(List<String> words) {
		this.output_queue = new ConcurrentLinkedQueue<JSONObject>();
		this.words = words;
	}

	public int getMissedTweets() {
		return missedTweets;
	}

	public Queue<JSONObject> getOutputQueue() {
		return output_queue;
	}

	private void processTweet(Status status) {
    	String line = TwitterObjectFactory.getRawJSON(status);

    	output_queue.offer(JSON.parse(line));

		if(++tweetCounter % 100 == 0) {
			logger.info("Write buffer {}", tweetCounter);
		}
	}

	private void startStreaming(List<String> words) {

		StatusListener listener = new StatusListener(){
	        public void onStatus(Status status) {
	        	processTweet(status);
	        }

	        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
	        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
	        	missedTweets = numberOfLimitedStatuses;
	        }
	        public void onException(Exception ex) {
	            logger.info("TwitterStream {}", ex.getMessage());
	        }
			public void onScrubGeo(long arg0, long arg1) {

			}
			public void onStallWarning(StallWarning arg0) {
				logger.info("TwitterStream stall warning");
			}
	    };

	    twitterStream = new TwitterStreamFactory().getInstance();

	    logger.info("Start streaming with {}", words);

	    FilterQuery query = new FilterQuery();
	    query.track(words.toArray(new String[words.size()]));

	    twitterStream.addListener(listener);
	    twitterStream.filter(query);
	}

	public void stop() {

		if(twitterStream != null)
			twitterStream.shutdown();

		logger.info("Shutting down");
	}

	public void run() {
		logger.trace("Start LiveContentGrabber");

		startStreaming(words);

		logger.trace("End LiveContentGrabber");
	}

}


text:
<!doctype html>
<html>
<head>
  <style>
    body {
      text-align: center;
      padding: 5%;
      font-family: monospace;
      font-size: 13px;
      letter-spacing: 2px;
      color: #555;
    }
  </style>
  <script src="hasAppleColorEmoji.js"></script>
</head>
<body>
  <script type="text/javascript">
    var text
    if(hasAppleColorEmoji()) {
      text = "Yes, you have 🍎🎨😍!"
    } else {
      text = "No, you don't have AppleColorEmoji. 😞"
    }
    document.body.appendChild(document.createTextNode(text))
  </script>
</body>
</html>


text:
go-ukigumo-agent
================

(PROTOTYPE) ukigumo-agent for golang


text:
var assert = require('assert');
var schema = require('../../libs/schema');
var configSchema = require('../../schemas/config');
var goodConfig = require('../data/goodConfig');

describe('schemas/config.js', () => {
    describe('test configuration schema validation', () => {
        it('should validate a working configuration', () => {
            let compiledSchema = schema.compileJsonSchema(configSchema);
            assert.ok(compiledSchema);
            let valid = schema.validateJson(compiledSchema, goodConfig);
            if (!valid) {
                throw new Error(compiledSchema.errors);
            }
            assert.ok(valid);
        });
        it('should fail to validate an empty configuration', () => {
            let compiledSchema = schema.compileJsonSchema(configSchema);
            assert.ok(compiledSchema);
            assert.ok(!schema.validateJson(compiledSchema), {});
        });
        it('should fail to validate config missing aws settings', () => {
            let compiledSchema = schema.compileJsonSchema(configSchema);
            assert.ok(compiledSchema);
            let noAwsConfig = Object.assign({}, goodConfig);
            delete noAwsConfig['aws'];
            assert.ok(!schema.validateJson(compiledSchema, noAwsConfig));
        });
        it('should fail if there are unexpected properties', () => {
            let compiledSchema = schema.compileJsonSchema(configSchema);
            assert.ok(compiledSchema);
            let extraPropConfig = Object.assign({extraConfig: 1234},
                goodConfig);
            assert.ok(!schema.validateJson(compiledSchema, extraPropConfig));
        });
    });
});


text:
module Taskable
  TASK_PATTERN_MD = /^(?<bullet> *[*-] *)\[(?<checked>[ xX])\]/.freeze
  TASK_PATTERN_HTML = /^<li>\[(?<checked>[ xX])\]/.freeze

  # Change the state of a task list item for this Taskable.  Edit the object's
  # description by finding the nth task item and changing its checkbox
  # placeholder to "[x]" if +checked+ is true, or "[ ]" if it's false.
  # Note: task numbering starts with 1
  def update_nth_task(n, checked)
    index = 0
    check_char = checked ? 'x' : ' '

    # Do this instead of using #gsub! so that ActiveRecord detects that a field
    # has changed.
    self.description = self.description.gsub(TASK_PATTERN_MD) do |match|
      index += 1
      case index
      when n then "#{$LAST_MATCH_INFO[:bullet]}[#{check_char}]"
      else match
      end
    end

    save
  end

  # Return true if this object's description has any task list items.
  def tasks?
    description && description.match(TASK_PATTERN_MD)
  end

  # Return a string that describes the current state of this Taskable's task
  # list items, e.g. "20 tasks (12 done, 8 unfinished)"
  def task_status
    return nil unless description

    num_tasks = 0
    num_done = 0

    description.scan(TASK_PATTERN_MD) do
      num_tasks += 1
      num_done += 1 unless $LAST_MATCH_INFO[:checked] == ' '
    end

    "#{num_tasks} tasks (#{num_done} done, #{num_tasks - num_done} unfinished)"
  end
end


text:
sap.ui.define(["sap/ui/core/UIComponent"], function (UIComponent) {
	"use strict";

	var Component = UIComponent.extend("sap.uxap.sample.ObjectPageState.Component", {
		metadata: {
			rootView: "sap.uxap.sample.ObjectPageState.ObjectPageState",
			dependencies: {
				libs: [
					"sap.m"
				]
			},
			config: {
				sample: {
					stretch: true,
					files: [
						"ObjectPageState.view.xml",
						"ObjectPageState.controller.js",
						"HRData.json"
					]
				}
			}
		}
	});
	return Component;
}, true);


text:
__author__ = 'Rafa Haro <rh@athento.com>'

def test_hocr():
    import os
    from hocr_parser.parser import HOCRDocument

    filename = "output.hocr"
    dir_path = os.path.dirname(os.path.abspath(__file__))
    full_path = os.path.join(dir_path, filename)
    document = HOCRDocument(full_path, is_path=True)
    assert document.npages == 1
    page = document.pages[0]
    assert page.parent == document
    assert page.coordinates == (0, 0, 545, 771)
    assert page.id == 'page_1'
    assert page.nareas == 3
    area = page.areas[0]
    assert area.parent == page
    assert area.coordinates == (83, 68, 449, 376)
    assert area.nparagraphs == 2
    assert area.paragraphs[0].lines[0].nwords == 1
    assert area.paragraphs[0].lines[0].ocr_text == area.paragraphs[0].lines[0].words[0].ocr_text == "|"
    assert area.paragraphs[1].nlines == 10

    area2_text = """At the remote terminal.
demodulation reconstructs the video
signal, which is used to modulate the
density ofprint produced by a
printing device. This device is
scanning in a raster scan
synchronised with that at the
transmitting terminal. As a result, a
facsimile copy of the subject
document is produced."""

    area1_line2 = "In facsimilea photocell is caused"
    assert area.paragraphs[1].lines[0].ocr_text == area1_line2

    area = page.areas[1]
    assert area.ocr_text == area2_text