text:
import { dispatch } from 'd3-dispatch';
import { select } from 'd3-selection';
import { zoom, zoomIdentity } from 'd3-zoom';
import { rebind } from '@d3fc/d3fc-rebind';

const domainsEqual = (a, b) => {
    if (a == null && b == null) {
        return true;
    }
    const aDomain = a.domain();
    const bDomain = b.domain();
    return (
        aDomain.length === bDomain.length &&
        aDomain.every((d, i) => d?.valueOf() === bDomain[i]?.valueOf())
    );
};

const subtract = (a, b) =>
    zoomIdentity.scale(a.k / b.k).translate(a.x - b.x, a.y - b.y);

const symbol = Symbol('d3fc-domain-zoom');

export default () => {
    const dispatcher = dispatch('zoom');

    const zoomer = zoom().on('zoom', function({ transform }) {
        const node = this;
        let updatedTransform = transform;
        let {
            originalXScale,
            previousXScale,
            xScale,
            originalYScale,
            previousYScale,
            yScale,
            previousTransform
        } = node[symbol];
        if (
            !domainsEqual(previousXScale, xScale) ||
            !domainsEqual(previousYScale, yScale)
        ) {
            originalXScale = xScale?.copy();
            originalYScale = yScale?.copy();
            updatedTransform = subtract(transform, previousTransform);
        }
        if (xScale != null) {
            previousXScale = updatedTransform.rescaleX(
                originalXScale.range(xScale.range())
            );
            xScale.domain(previousXScale.domain());
        }
        if (yScale != null) {
            previousYScale = updatedTransform.rescaleY(
                originalYScale.range(yScale.range())
            );
            yScale.domain(previousYScale.domain());
        }
        previousTransform = updatedTransform;
        node[symbol] = {
            originalXScale,
            previousXScale,
            xScale,
            originalYScale,
            previousYScale,
            yScale,
            previousTransform
        };
        if (updatedTransform !== transform) {
            zoomer.transform(select(node), updatedTransform);
        }
        dispatcher.call('zoom');
    });

    const instance = (selection, xScale = null, yScale = null) => {
        if (xScale == null && yScale == null) {
            console.warn(
                `Without an xScale and/or yScale specified, this component won't do anything. Perhaps you forgot to specify them e.g. selection.call(zoom, x, y)?`
            );
        }
        selection
            .each((d, i, nodes) => {
                const existingContext = nodes[i][symbol];
                if (
                    existingContext != null &&
                    existingContext.xScale === xScale &&
                    existingContext.yScale === yScale
                ) {
                    console.warn(
                        `This component should only be called on a selection once. Perhaps you're missing an .enter()?`
                    );
                }
                const xScaleCopy = xScale?.copy();
                const yScaleCopy = yScale?.copy();
                nodes[i][symbol] = {
                    originalXScale: xScaleCopy,
                    previousXScale: xScaleCopy,
                    xScale,
                    originalYScale: yScaleCopy,
                    previousYScale: yScaleCopy,
                    yScale,
                    previousTransform: zoomIdentity
                };
            })
            .call(zoomer);
    };

    rebind(instance, dispatcher, 'on');
    rebind(
        instance,
        zoomer,
        'extent',
        'filter',
        'wheelDelta',
        'touchable',
        'clickDistance',
        'tapDistance',
        'duration',
        'interpolate'
    );

    return instance;
};


text:
package org.uberfire.client.workbench.widgets.dnd;

import java.util.HashMap;
import java.util.Map;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.uberfire.client.workbench.BeanFactory;
import org.uberfire.client.workbench.panels.WorkbenchPanelView;

import com.allen_sauer.gwt.dnd.client.drop.DropController;
import com.google.gwt.user.client.ui.IsWidget;

/**
 * A Manager of drag and drop operations within the Workbench.
 */
@ApplicationScoped
public class WorkbenchDragAndDropManager {

    /** Maps panels to the drop controllers we have registered them with (so we can unregister them later). */
    Map<WorkbenchPanelView, DropController> dropControllerMap = new HashMap<WorkbenchPanelView, DropController>();

    //The context of the drag operation
    private WorkbenchDragContext workbenchContext = null;

    @Inject
    WorkbenchPickupDragController dragController;

    @Inject
    BeanFactory factory;

    public void makeDraggable( IsWidget draggable,
                               IsWidget dragHandle ) {
        this.dragController.makeDraggable( draggable.asWidget(),
                                           dragHandle.asWidget() );
    }

    public void registerDropController( final WorkbenchPanelView owner,
                                        final DropController dropController ) {
        dropControllerMap.put( owner,
                               dropController );
        dragController.registerDropController( dropController );
    }

    public void unregisterDropController( final WorkbenchPanelView view ) {
        final DropController dropController = dropControllerMap.remove( view );
        dragController.unregisterDropController( dropController );
        factory.destroy( dropController );
    }

    public void unregisterDropControllers() {
        for ( Map.Entry<WorkbenchPanelView, DropController> e : this.dropControllerMap.entrySet() ) {
            final DropController dropController = dropControllerMap.get( e.getKey() );
            dragController.unregisterDropController( dropController );
            factory.destroy( dropController );
        }
        this.dropControllerMap.clear();
    }

    public void setWorkbenchContext( final WorkbenchDragContext workbenchContext ) {
        this.workbenchContext = workbenchContext;
    }

    public WorkbenchDragContext getWorkbenchContext() {
        return this.workbenchContext;
    }

}

redpajama_set_name: RedPajamaGithub


text:
require 'action_dispatch/middleware/show_exceptions'

module ActionDispatch
  class ShowExceptions
    private
      def render_exception_with_template(env, exception)
        body = ErrorsController.action(rescue_responses[exception.class.name]).call(env)
        log_error(exception)
        body
      rescue
        render_exception_without_template(env, exception)
      end

      alias_method_chain :render_exception, :template
  end
end


text:
from datetime import datetime

from bson import ObjectId

from src.services.database import temps
from src.services.monolithic import services

class TempLog:
    collection = temps

    def __init__(self, date, temp, id=None):
        self.id = id
        self.date = date
        self.temp = temp

        assert type(date) is datetime
        assert type(temp) is float or int

    def save(self):
        to_save = {
            "temp": self.temp,
            "date": self.date
        }

        if self.id is not None:
            to_save["_id"] = self.id

        return self.collection.save(to_save)

    @classmethod
    def from_dictionary(cls, json):
        date = json["date"]
        if type(date) is not datetime:
            date = datetime.utcfromtimestamp(json["date"])

        temp = json["temp"]

        try:
            id = json["_id"]["$oid"]
        except KeyError:
            id = None
        except TypeError:
            try:
                id = ObjectId(json["_id"])
            except:
                id = None

        return cls(date, temp, id=id)

    def to_dictionary(self):
        return {"date": int(self.date.strftime("%s")),
                "_id": str(self.id),
                "temp": self.temp}

    @classmethod
    def get_all(cls):
        results = cls.collection.find({}, {"date": -1, "temp": 1})
        temp_changes = []
        for result in results:
            temp_changes.append(cls.from_dictionary(result))

        return temp_changes

    @classmethod
    def get_all_dic(cls):
        all_items = cls.get_all()
        result = []
        for item in all_items:
            result.append(item.to_dictionary())
        return result

if services.TempMonitor is not None:
    print("will log temp changes")
    @services.TempMonitor.temp_changed
    def on_temp_change(temp):
        TempLog(datetime.utcnow(), temp).save()


text:
<?php
class Images extends CI_Model {
	// Contructor
	function __contruct() {
		parent::__contruct();
	}

	//  Return all images, desending order by post date
	function all() {
		$this->db->order_by("id", "desc");
		$query = $this->db->get('images');
		return $query->result_array();
	}

	// Return just the 3 newest images
	function newest() {
		$this->db->order_by("id", "desc");
		$this->db->limit(3);
		$query = $this->db->get('images');
		return $query->result_array();
	}
}

$autoload['model'] = array('images');


text:
import { Component, Input } from "@angular/core";

@Component({
  selector: "mdl-fab-menu",
  templateUrl: "fab-menu.component.html",
  styleUrls: ["fab-menu.component.scss"],
})
export class MdlFabMenuComponent {
  @Input()
  alwaysShowTooltips = false;
}


text:
var fs = require('fs');
var util = require('util');
var path = require('path');

// boot code for jasmine
var jasmineRequire = require('../lib/jasmine-core/jasmine.js');
var jasmine = jasmineRequire.core(jasmineRequire);

var consoleFns = require('../lib/console/console.js');
extend(jasmineRequire, consoleFns);
jasmineRequire.console(jasmineRequire, jasmine);

var env = jasmine.getEnv();

var jasmineInterface = {
  describe: function(description, specDefinitions) {
    return env.describe(description, specDefinitions);
  },

  xdescribe: function(description, specDefinitions) {
    return env.xdescribe(description, specDefinitions);
  },

  it: function(desc, func) {
    return env.it(desc, func);
  },

  xit: function(desc, func) {
    return env.xit(desc, func);
  },

  beforeEach: function(beforeEachFunction) {
    return env.beforeEach(beforeEachFunction);
  },

  afterEach: function(afterEachFunction) {
    return env.afterEach(afterEachFunction);
  },

  expect: function(actual) {
    return env.expect(actual);
  },

  spyOn: function(obj, methodName) {
    return env.spyOn(obj, methodName);
  },

  jsApiReporter: new jasmine.JsApiReporter({
    timer: new jasmine.Timer()
  })
};

extend(global, jasmineInterface);

function extend(destination, source) {
  for (var property in source) destination[property] = source[property];
  return destination;
}

jasmine.addCustomEqualityTester = function(tester) {
  env.addCustomEqualityTester(tester);
};

jasmine.addMatchers = function(matchers) {
  return env.addMatchers(matchers);
};

jasmine.clock = function() {
  return env.clock;
};

// Jasmine "runner"
function executeSpecs(specs, done, isVerbose, showColors) {
  global.jasmine = jasmine;

  for (var i = 0; i < specs.length; i++) {
    var filename = specs[i];
    require(filename.replace(/\.\w+$/, ""));
  }

  var env = jasmine.getEnv();
  var consoleReporter = new jasmine.ConsoleReporter({
    print: util.print,
    onComplete: done,
    showColors: showColors,
    timer: new jasmine.Timer()
  });

  env.addReporter(consoleReporter);
  env.execute();
}

function getFiles(dir, matcher) {
  var allFiles = [];

  if (fs.statSync(dir).isFile() && dir.match(matcher)) {
    allFiles.push(dir);
  } else {
    var files = fs.readdirSync(dir);
    for (var i = 0, len = files.length; i < len; ++i) {
      var filename = dir + '/' + files[i];
      if (fs.statSync(filename).isFile() && filename.match(matcher)) {
        allFiles.push(filename);
      } else if (fs.statSync(filename).isDirectory()) {
        var subfiles = getFiles(filename);
        subfiles.forEach(function(result) {
          allFiles.push(result);
        });
      }
    }
  }
  return allFiles;
}

function getSpecFiles(dir) {
  return getFiles(dir, new RegExp("Spec.js$"));
}

var j$require = (function() {
  var exported = {},
      j$req;

  global.getJasmineRequireObj = getJasmineRequireObj;

  j$req = require(__dirname + "/../src/core/requireCore.js");
  extend(j$req, require(__dirname + "/../src/console/requireConsole.js"));

  var srcFiles = getFiles(__dirname + "/../src/core");
  srcFiles.push(__dirname + "/../src/version.js");
  srcFiles.push(__dirname + "/../src/console/ConsoleReporter.js");

  for (var i = 0; i < srcFiles.length; i++) {
    require(srcFiles[i]);
  }
  extend(j$req, exported);

  delete global.getJasmineRequireObj;

  return j$req;

  function getJasmineRequireObj() {
    return exported;
  }
}());

j$ = j$require.core(j$require);
j$require.console(j$require, j$);

// options from command line
var isVerbose = false;
var showColors = true;
var perfSuite = false;

process.argv.forEach(function(arg) {
  switch (arg) {
    case '--color':
      showColors = true;
      break;
    case '--noColor':
      showColors = false;
      break;
    case '--verbose':
      isVerbose = true;
      break;
    case '--perf':
      perfSuite = true;
      break;
  }
});

specs = [];

if (perfSuite) {
  specs = getFiles(__dirname + '/performance', new RegExp("test.js$"));
} else {
  var consoleSpecs = getSpecFiles(__dirname + "/console"),
      coreSpecs = getSpecFiles(__dirname + "/core"),
      specs = consoleSpecs.concat(coreSpecs);
}

executeSpecs(specs, function(passed) {
  if (passed) {
    process.exit(0);
  } else {
    process.exit(1);
  }
}, isVerbose, showColors);


text:
package controller

import (
	"fmt"
	"io"
	"os"

	"github.com/docker/infrakit/pkg/cli"
	"github.com/docker/infrakit/pkg/plugin"
	"github.com/docker/infrakit/pkg/types"
	"github.com/spf13/cobra"
)

// Describe returns the describe command
func Describe(name string, services *cli.Services) *cobra.Command {
	describe := &cobra.Command{
		Use:   "describe",
		Short: "Describe all managed objects",
	}
	describe.Flags().AddFlagSet(services.OutputFlags)

	tags := describe.Flags().StringSlice("tags", []string{}, "Tags to filter")

	describe.RunE = func(cmd *cobra.Command, args []string) error {

		pluginName := plugin.Name(name)

		controller, err := services.Scope.Controller(pluginName.String())
		if err != nil {
			return nil
		}
		cli.MustNotNil(controller, "controller not found", "name", name)

		var q *types.Metadata

		if len(args) == 1 {
			s := (types.Metadata{
				Name: args[0],
			}).AddTagsFromStringSlice(*tags)
			q = &s
		}

		objects, err := controller.Describe(q)
		if err != nil {
			return err
		}

		return services.Output(os.Stdout, objects,
			func(w io.Writer, v interface{}) error {
				fmt.Printf("%-10s  %-15s  %-15s\n", "KIND", "NAME", "ID")
				for _, o := range objects {
					fmt.Printf("%-10s  %-15s  %-15s\n", o.Spec.Kind, o.Spec.Metadata.Name, o.Spec.Metadata.Identity.ID)
				}
				return nil
			})
	}
	return describe
}


text:
package cn.cerc.mis.custom;

import cn.cerc.mis.core.ISystemTable;

public class SystemTableDefault implements ISystemTable {

    @Override
    public String getBookInfo() {
        return "s_book_info";
    }

    @Override
    public String getBookOptions() {
        return "s_book_options";
    }

    @Override
    public String getAppMenus() {
        return "s_app_menus";
    }

    @Override
    public String getCustomMenus() {
        return "s_custom_menus";
    }

    @Override
    public String getUserMenus() {
        return "s_user_menus";
    }

    @Override
    public String getUserInfo() {
        return "s_user_info";
    }

    @Override
    public String getUserOptions() {
        return "s_user_options";
    }

    @Override
    public String getUserRoles() {
        return "s_user_roles";
    }

    @Override
    public String getRoleAccess() {
        return "s_role_access";
    }

    @Override
    public String getDeviceVerify() {
        return "s_device_verify";
    }

    @Override
    public String getSecurityMobile() {
        return "s_security_mobile";
    }

    @Override
    public String getCurrentUser() {
        return "s_current_user";
    }

    @Override
    public String getUserMessages() {
        return "s_user_messages";
    }

    @Override
    public String getUserLogs() {
        return "s_user_logs";
    }

    @Override
    public String getAppLogs() {
        return "s_app_logs";
    }

    @Override
    public String getPageLogs() {
        return "s_page_logs";
    }

    @Override
    public String getOnlineUsers() {
        return "s_online_users";
    }

    @Override
    public String getLangDict() {
        return "s_lang_dict";
    }

    @Override
    public String getLanguage() {
        return "s_dict_language";
    }

    @Override
    public String getManageBook() {
        return "000000";
    }

}


text:
    Programa
    FAQ

          Selecciona las charlas que más te interesen. Cuando comiencen, recibirás una notificación en este dispositivo.

    <template>

            <input type="checkbox" id="list-switch-" class="mdl-switch__input" />

    </template>

Datos de conexión WIFI

              Red: ViveroWireless

              Contraseña: Cein2007

              Ver programa

Y te preguntarás ¿qué es esto de Open Space?

              Sencillo, se trata de una metodología ágil para organizar reuniones que permite conseguir, de un grupo numeroso de personas
              y en un mínimo tiempo, compartir conocimiento y las mejores ideas sobre un tema.

              O lo que es lo mismo, los bikonianos (y todo el que quiera participar) proponemos unos temas concretos que nos interesan
              y que queremos compartir con todo el mundo (sea de Biko o no) y programamos una serie de reuniones donde tratarlos.

              Ver programa

¿Por qué tienes que venir?

              Porque sea cual sea tu especialidad o intereses profesionales, seguro que encuentras una charla que encaje contigo. Tenemos
              para todos los gustos: diseño, marketing, comunicación, programación, estrategia… Además las reuniones serán
              muy participativas para que todos opinemos y los ponentes nos hablarán desde su propia experiencia lo que hará
              que sean muy productivas.

              Ver programa

¿Cómo lo vamos a hacer?

              Empezamos a las 10:00 de la mañana. Cada asistente elige libremente a qué reunión le interesa asistir, sin necesidad de apuntarse
              en ningún sitio, basta con estar en la sala adecuada a la hora indicada. Puedes asistir a una reunión, dos,
              tres… todas las de una misma sala… La única ley que aplicamos es la "Ley de los dos pies": Si en algún momento
              sientes que no estás aprendiendo o no te interesa lo que se habla, usa tus dos pies ¡y cambia de reunión!

              Ver programa


text:
package org.apache.camel.cdi.bean;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

import org.apache.camel.cdi.ContextName;
import org.apache.camel.impl.DefaultCamelContext;

@ApplicationScoped
@Named("first")
@ContextName("first")
public class FirstNamedCamelContextBean extends DefaultCamelContext {
}


text:
var crypto = require('crypto');
var grunt = require('grunt');
var redis = require('redis');
var zlib = require('zlib');
var redisClient;

var i = require('util').inspect;

function storeInPostgres(cacheKey, hash, body) {
  // console.log('Storing in postgres with : ' + config.server.name);
  // console.log('Body is buffer : ' + (Buffer.isBuffer(body) ? true : false));
  // console.log(i(body));

  // db.named('page-cache-update', [
  //   config.server.name, cacheKey, hash.etag, hash.max_age, hash.content_type, hash.content_length, hash.content_encoding,
  //   // '\\x' + body.toString('hex')
  //   // body.toString('utf8')
  //   body
  // ])
  // .on('error', function(e) { console.log('Page cache error : ' + e); })
  // .execute();
}

function storeInRedis(cacheKey, hash, body) {
  redisClient.multi()
    .hmset(cacheKey + '-meta', hash)
    .set(cacheKey + '-content', body)
    .expire(cacheKey + '-meta', hash.max_age)
    .expire(cacheKey + '-content', hash.max_age)
    .exec();
}

/**
 * Make your final call through this, so that versioning and updates to data structures can be made without breaking
 * backwards compatibility.
 */
function storeInCache(req, res, body, cb) {
  var hash = ((typeof res._cache === 'number') ? { max_age: res._cache } : res._cache) || {};
  var cacheKey = req.originalUrl;
  if(!config.server.cache || isNaN(hash.max_age) || (res.statusCode !== 200 && res.statusCode !== 304)) {
    cb(hash, body);
    return;
  }

  hash.content_type = res.get('Content-Type');
  hash.content_length = res.get('Content-Length');
  hash.etag = res.get('ETag');

  if(config.server.gzip_cache) {
    zlib.gzip(body, function(err, zipped) {
      var len = Buffer.isBuffer(zipped) ? zipped.length : Buffer.byteLength(zipped)
      res.set('Content-Length', len);
      res.set('Content-Encoding', 'gzip');
      hash.content_length = len;
      hash.content_encoding = 'gzip';
      config.server.cache_to == 'postgres' ? storeInPostgres(cacheKey, hash, zipped) : storeInRedis(cacheKey, hash, zipped);
      cb(hash, zipped);
    });
  }
  else {
    config.server.cache_to == 'postgres' ? storeInPostgres(cacheKey, hash, body) : storeInRedis(cacheKey, hash, body);
    cb(hash, body);
  }
};

// Use our own ETag
var etag = function etag(body) {
  return crypto.createHash('md5').update(body).digest('hex');
}

var send = function send(body){
  var req = this.req;
  var head = 'HEAD' == req.method;
  var len;

  // settings
  var app = this.app;

  // allow status / body
  if (2 == arguments.length) {
    // res.send(body, status) backwards compat
    if ('number' != typeof body && 'number' == typeof arguments[1]) {
      this.statusCode = arguments[1];
    } else {
      this.statusCode = body;
      body = arguments[1];
    }
  }

  switch (typeof body) {
    // response status
    case 'number':
      this.get('Content-Type') || this.type('txt');
      this.statusCode = body;
      body = http.STATUS_CODES[body];
      break;
    // string defaulting to html
    case 'string':
      if (!this.get('Content-Type')) {
        this.charset = this.charset || 'utf-8';
        this.type('html');
      }
      break;
    case 'boolean':
    case 'object':
      if (null == body) {
        body = '';
      } else if (Buffer.isBuffer(body)) {
        this.get('Content-Type') || this.type('bin');
      } else {
        return this.json(body);
      }
      break;
  }

  // populate Content-Length
  if (undefined !== body && !this.get('Content-Length')) {
    this.set('Content-Length', len = Buffer.isBuffer(body)
      ? body.length
      : Buffer.byteLength(body));
  }

  // ETag support
  // TODO: W/ support
  if (app.settings.etag && len > 1024 && 'GET' == req.method) {
    if (!this.get('ETag')) {
      this.set('ETag', etag(body));
    }
  }

  // freshness
  if (req.fresh) this.statusCode = 304;

  storeInCache(req, this, body, function(hash, body) {
    if(hash.content_encoding) this.set('Content-Encoding', hash.content_encoding);
    if(hash.etag) this.set('ETag', hash.etag);
    if(hash.max_age) this.set('Max-Age', hash.max_age);

    // strip irrelevant headers and remove the body here after caching
    // so that we don't prime a half empty cache if the first client
    // came back with a matching etag
    if (204 == this.statusCode || 304 == this.statusCode) {
      this.removeHeader('Content-Type');
      this.removeHeader('Content-Length');
      this.removeHeader('Transfer-Encoding');
      body = '';
    }

    this.end(head ? null : body);
  }.bind(this));

  // respond
  return this;
};

/**
 * This hooks res.end. If the controller sets "res.cache = seconds" the response is cached in Redis for that many seconds.
 * Cache entries are keyed by URL, and the content is always gzipped.
 */

function cache(lifetime) {
  var url = this.req.originalUrl;
  // if(config.server.cache_to == 'postgres') {
  //   db.named('page-cache-pending', [
  //     config.server.name, url
  //   ]).execute();
  // }
  this._cache = lifetime;
  this.send = send;
}

//
function caching(req, res, next) {
  res.cache = cache;
  next();
};

/**
 * Reads the connection details from config/redis-cache.yml and connects to the server
 */
exports.init = function init(app) {
  if (!app) { throw 'api-builder\'s cache.init(app) needs the express app as a parameter' }
  try { var options = grunt.file.readYAML('config/redis-cache.yml')[process.env.NODE_ENV]; }
  catch (e) { throw 'Please define a config/redis-cache.yml'; }
  if (isNaN(parseInt(options.db))) { throw 'Please set a db: x value in config/redis-cache.yml'; }
  redisClient = redis.createClient(options.port, options.host, { auth_pass: options.password });
  redisClient.select(options.db);
  redisClient.on('error', function (err) {
    console.log('Redis client error : ' + err);
  });

  app.use(caching);
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AppBarMain from '../components/AppBarMain';
import Paper from 'material-ui/Paper';
import StarRating from '../components/starRating';
import RaisedButton from 'material-ui/RaisedButton';
import {indigo,white} from './apecConnectTheme';
import Logo from '../common/assets/APEC-CONNECT-LOGO.svg';
import ToPayItem from '../components/toPayItem';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import actions from 'state/actions';
import Immutable from 'immutable';

/***

This is the basic elements for a main view in the app.

***/

const paperStyle = {
  padding: 10,
  textAlign: 'center',
  height: '100%',
  minHeight: '40vh',
  position: 'relative'
};

const headerDivStyle = {
  position: 'relative',
  width: '30%',
};

const payStyle = {
  width: '50%',
};

const businessNameStyle ={
  fontSize: 48,
};

const userDetailsStyle = {
  fontSize: 20,
};

const logoStyle ={
  width: '100%',
  maxHeight: '150px',
};

{/** User information that will be pulled from the database **/}
const CompanyName = 'David\'s Hat Co.';
const userName = 'DHat72';
const userStarRating = 1;

@withRouter
@connect((state) => {
  return {
    dispatch: state.dispatch,
    ui: state.ui,
    participant: state.participant,
    messages: state.messages,
  };
})
export default class PayScreen extends React.Component {

  constructor(props) {
    super(props);
  };

  componentDidMount() {
    let { dispatch } = this.props;

    setTimeout(function () {
      dispatch(actions.getParticipantMessages());
    });
  }

  componentWillReceiveProps() {
    clearTimeout(this.inboxRefreshTimeout);
    this.refreshInbox();
  }

  refreshInbox = () => {
    let { dispatch } = this.props;
    this.inboxRefreshTimeout = setTimeout(function() {
      dispatch(actions.getParticipantMessages());
    }, 5 * 1000);
  }

  generateInboxItems = () => {
    /**Create a list of messages WHERE
     *  # Buyer === participant
     *  # Invoice part exists
     *  => If paid === true, disable PAY button
    **/
    const items = Immutable.List(this.props.messages.messages).filter ((m, index) => {
      return m.invoice && (m.sender.identifier != this.props.participant.identifier);
    }).map ((m,index) => {
      return <ToPayItem key={index} message={m} keyID={index}/>;
    });

    if (items.size > 0) {
      return items;
    } else {
      return
 Nothing to pay!
;
    }

  }

  render() {
    return (

        {/** AppBarMain contains the app bar and menu drawer **/}
        <AppBarMain title={'Pay'}/>
        {/** Paper containing the logo **/}
        <Paper
          zDepth={1}
          style={paperStyle}
        >

          <Paper
            zDepth={1}
            style={paperStyle}
          >
            {/** container for to pay elements **/}
            {this.generateInboxItems()}
          </Paper>

        </Paper>

    );
  }
}


text:
package com.taskadapter.redmineapi;

import java.util.List;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import com.taskadapter.redmineapi.bean.Group;
import com.taskadapter.redmineapi.bean.Role;
import com.taskadapter.redmineapi.bean.User;
import com.taskadapter.redmineapi.internal.DirectObjectsSearcher;
import com.taskadapter.redmineapi.internal.Transport;

/**
 * Works with Users and Groups.
 *
Obtain it via RedmineManager:
 *

 RedmineManager redmineManager = RedmineManagerFactory.createWithUserAuth(redmineURI, login, password);
 UserManager userManager = redmineManager.getUserManager();
 *

 * Note that some operations with users require Redmine Admin privileges.
 *
 *
Sample usage:
 *

     users = mgr.getUserManager().getUsers();
 *

 *
 * @see RedmineManager#getUserManager()
 */
public class UserManager {
    private final Transport transport;

    UserManager(Transport transport) {
        this.transport = transport;
    }

    /**
     * @return the current user logged into Redmine
     */
    public User getCurrentUser() throws RedmineException {
        return transport.getCurrentUser();
    }

    public User createUser(User user) throws RedmineException {
        return transport.addObject(user);
    }

    /**
     * @param userId user identifier (numeric ID)
     * @throws RedmineAuthenticationException invalid or no API access key is used with the server, which
     *                                 requires authorization. Check the constructor arguments.
     * @throws NotFoundException       if the user with the given id is not found
     */
    public void deleteUser(Integer userId) throws RedmineException {
        transport.deleteObject(User.class, Integer.toString(userId));
    }

    /**
     * Adds the given user to the given group.
     *

     * Note: "add to group" operation used to be safe (idempotent) for Redmine 2.6.x, but FAILS for Redmine 3.0.0 when
     * executed twice on the same user. I submitted a bug: http://www.redmine.org/issues/19363
     *
     * @param user  - The user being added.
     * @param group - The new group of the user.
     * @throws RedmineException
     * @since Redmine 2.1
     */
    public void addUserToGroup(User user, Group group) throws RedmineException {
        transport.addUserToGroup(user.getId(), group.getId());
    }

    /**
     * Load list of users from the server.
     *
This operation requires "Redmine Administrator" permission.
     *
     * @return list of User objects
     * @throws RedmineAuthenticationException invalid or no API access key is used with the server, which
     *                                 requires authorization. Check the constructor arguments.
     * @throws NotFoundException
     * @throws RedmineException
     */
    public List<User> getUsers() throws RedmineException {
        return transport.getObjectsList(User.class, new BasicNameValuePair(
                "include", "memberships,groups"));
    }

    /**
     *
This method does NOT handle paging for you. You need to provide "offset" and "limit" parameters
     * if you want to control paging.
     *
Sample usage:

     final Map<String, String> params = new HashMap<String, String>();
     params.put("name", name);
     final List<User> users = userManager.getUsers(params);

     *
     * @param parameters http parameters: key/value pairs to append to the rest api request
     * @return empty list if no objects found using provided parameters
     * @throws RedmineAuthenticationException invalid or no API access key is used with the server, which
     *                                 requires authorization. Check the constructor arguments.
     * @throws RedmineException
     */
    public List<User> getUsers(Map<String, String> parameters) throws RedmineException {
        return DirectObjectsSearcher.getObjectsListNoPaging(transport, parameters, User.class);
    }

    /**
     * This does NOT require Admin privileges by default Redmine installation (tested with Redmine 2.0.3).
     */
    public User getUserById(Integer userId) throws RedmineException {
        return transport.getObject(User.class, userId, new BasicNameValuePair(
                "include", "memberships,groups"));
    }

    /**
     * Load list of groups on the server.
     *
This operation requires "Redmine Administrator" permission.
     *
     * @return list of User objects
     * @throws RedmineAuthenticationException invalid or no API access key is used with the server, which
     *                                 requires authorization. Check the constructor arguments.
     * @throws NotFoundException
     * @throws RedmineException
     */
    public List<Group> getGroups() throws RedmineException {
        return transport.getObjectsList(Group.class);
    }

    /**
     * Returns the group based on its id.
     *

     * This operation requires "Redmine Administrators" permission.
     *
     * @param id id of the group
     * @return the group
     * @throws RedmineException
     */
    public Group getGroupById(int id) throws RedmineException {
        return transport.getObject(Group.class, id);
    }

    /**
     * Returns the group based on its name.
     *

     * This operation requires "Redmine Administrators" permission.
     *
     * @param name
     *            the name of the group
     * @return the group
     * @throws RedmineException
     */
    public Group getGroupByName(String name) throws RedmineException {
        return transport.getObject(Group.class, name);
    }

    /**
     * Creates a new group.
     *
This operation requires "Redmine Administrator" permission.
     * @return created group.
     * @throws RedmineException
     */
    public Group createGroup(Group base) throws RedmineException {
        return transport.addObject(base);
    }

    /**
     * Deletes a group.
     *
This operation requires "Redmine Administrator" permission.
     */
    public void deleteGroup(Group base) throws RedmineException {
        transport.deleteObject(Group.class, base.getId().toString());
    }

    public List<Role> getRoles() throws RedmineException {
        return transport.getObjectsList(Role.class);
    }

    public Role getRoleById(int id) throws RedmineException {
        return transport.getObject(Role.class, id);
    }

    public void update(User obj) throws RedmineException {
        transport.updateObject(obj);
    }

    public void update(Group group) throws RedmineException {
        transport.updateObject(group);
    }
}


text:
//
//  DCNavigationMenu.h
//  Pods
//
//  Created by Youwei Teng on 9/19/15.
//
//

#ifndef DCNavigationMenu_h
#define DCNavigationMenu_h

#import "DCNavigationMenuView.h"
#import "DCNavigationMenuCollectionView.h"
#import "DCNavigationMenuDefaultCollectionViewCell.h"

#endif /* DCNavigationMenu_h */


text:
var Q = require('q');
var path = require('path');

//parse('./')
// => {hash: {'name': {file}, ...}, list: [{file}, ...]}
// where {file} is:
//    {name(), path(), source(), raw(), update(value), rename(name),
//     show(), hide(), hidden()}
var parseDir = require('./parse');//depends on readDirRec

//compile('./', [filter(dir), filter(dir), filter(dir), ...])
// => [{file}, {file}, {file}]
module.exports = compile;
function compile(input, filters) {
    return parseDir(input).then(function (dir) {
        var hash = dir.hash;
        var list = dir.list;
        return Q.all(serialMap(filters, filterProcessor(dir))).then(function () {
            return dir.list.filter(notHiden);
        });
    });
}

//serialMap([...], =>map(input))
// => [...]
function serialMap(input, map) {
    var output = [];
    function next(i) {
        if (i === input.length) return output;
        return map(input[i]).then(function (res) {
            output.push(res);
            return next(i + 1);
        });
    }
    return next(0);
}

//filterProcessor('./')
//-> processFilter(filter)
//   => filter(dir)
function filterProcessor(dir) {
    return function processFilter(filter) {
        return Q.resolve(filter(dir));
    };
}

//notHidden({file})
//-> true/false
function notHiden(file) {
    return !file.hidden();
}


text:
@class VWBSTreeNode;

typedef NSComparisonResult (^VWComparator)(id obj1, id obj2);

@interface VWBSTree : NSObject

- (instancetype)initWithObject:(id)item compareSelector:(SEL)compareSelector;

- (BOOL)isEmpty;
@end


text:
layout: lab
num: lab04
ready: true
desc: "if/else, nested for loop and if/else logic, ASCII art, tdd"
submit_cs: https://submit.cs.ucsb.edu/form/project/533
---

Please visit:

<https://foo.cs.ucsb.edu/16wiki/index.php/W15:Labs:lab04#Intro>

This content will eventually be relocated to here.

Please the page <{{page.submit_cs}}>, or the Unix shell commmand listed at that
link (e.g. `~submit/submit -p nnn file1 file2 ... filen`) to
submit your assignment rather than the command listed in the instructions.


text:
package com.hazelcast.map.impl.mapstore;

import com.hazelcast.config.Config;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.internal.util.AbstractClockTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.concurrent.TimeUnit;

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

@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class EntryLoaderCustomClockTest extends AbstractClockTest {

    private HazelcastInstance instance;
    private IMap<String, String> map;
    private TestEntryStore<String, String> testEntryStore = new TestEntryStore<>();

    @Before
    public void setup() {
        setClockOffset(100000);
        instance = startNode();
        map = instance.getMap(randomMapName());
    }

    @After
    public void teardown() {
        instance.getLifecycleService().terminate();
        resetClock();
    }

    @Test
    public void testEntryLoader() {
        testEntryStore.putExternally("key", "val", System.currentTimeMillis() + 2000);
        assertEquals("val", map.get("key"));
        sleepAtLeastSeconds(2);
        assertNull(map.get("key"));
    }

    @Test
    public void testEntryStore() {
        map.put("key", "val", 1, TimeUnit.DAYS);
        long expectedExpirationTime = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1);
        testEntryStore.assertRecordStored("key", "val", expectedExpirationTime, 5000);
    }

    @Override
    protected Config getConfig() {
        Config config = smallInstanceConfig();
        MapStoreConfig mapStoreConfig = new MapStoreConfig();
        mapStoreConfig.setImplementation(testEntryStore).setEnabled(true);
        config.getMapConfig("default").setMapStoreConfig(mapStoreConfig);
        return config;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Core Plot (Mac OS): Source/CPTAxisLabel.h Source File</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="customdoxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>

Core Plot (Mac OS)

Cocoa plotting framework for Mac OS X and iOS

Main Page

Animation & Constants

Classes

Files

File List

File Members

Source/CPTAxisLabel.h

Go to the documentation of this file.

00001 #import "CPTDefinitions.h"
00002 #import <Foundation/Foundation.h>
00003
00004 @class CPTLayer;
00005 @class CPTTextStyle;
00006
00007 @interface CPTAxisLabel : NSObject<NSCoding> {
00008     @private
00009     CPTLayer *contentLayer;
00010     CGFloat offset;
00011     CGFloat rotation;
00012     CPTAlignment alignment;
00013     NSDecimal tickLocation;
00014 }
00015
00016 @property (nonatomic, readwrite, retain) CPTLayer *contentLayer;
00017 @property (nonatomic, readwrite, assign) CGFloat offset;
00018 @property (nonatomic, readwrite, assign) CGFloat rotation;
00019 @property (nonatomic, readwrite, assign) CPTAlignment alignment;
00020 @property (nonatomic, readwrite) NSDecimal tickLocation;
00021
00024 -(id)initWithText:(NSString *)newText textStyle:(CPTTextStyle *)style;
00025 -(id)initWithContentLayer:(CPTLayer *)layer;
00027
00030 -(void)positionRelativeToViewPoint:(CGPoint)point forCoordinate:(CPTCoordinate)coordinate inDirection:(CPTSign)direction;
00031 -(void)positionBetweenViewPoint:(CGPoint)firstPoint andViewPoint:(CGPoint)secondPoint forCoordinate:(CPTCoordinate)coordinate inDirection:(CPTSign)direction;
00033
00034 @end

CPTAxisLabel.h

Generated by


text:
var createCompounder = require('./_createCompounder');

/**
 * Converts `string`, as space separated words, to upper case.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category String
 * @param {string} [string=''] The string to convert.
 * @returns {string} Returns the upper cased string.
 * @example
 *
 * _.upperCase('--foo-bar');
 * // => 'FOO BAR'
 *
 * _.upperCase('fooBar');
 * // => 'FOO BAR'
 *
 * _.upperCase('__foo_bar__');
 * // => 'FOO BAR'
 */
var upperCase = createCompounder(function (result, word, index) {
    return result + (index ? ' ' : '') + word.toUpperCase();
});

module.exports = upperCase;


text:
//
//  IndoorMapController.h
//  ifinitySDK
//
//  Created by GetIfinity on 20.03.2015.
//  Copyright (c) 2015 GetIfinity. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#import "IFMFloorplan.h"
#import "IFMVenue.h"
#import "IFDataManager.h"
#import "IFCalibrationCompassContainerView.h"
#import "IFCalibrationCompassView.h"

@class IFIndoorMapController;

/**
 *  Map controler delegate
 */
@protocol IFIndoorMapControllerDelegate <NSObject>

@optional
/**
 *  Called on area enter
 *
 *  @param indoorMapController map controller
 *  @param area                area
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didEnterArea:(IFMArea *)area;

/**
 *  Called on area exit
 *
 *  @param indoorMapController map controller
 *  @param area                area
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didExitArea:(IFMArea *)area;

/**
 *  Called when framework detects strongest beacon assigned for venue and floor.
 *
 *  @param indoorMapController map controller
 *  @param floor               closest floor base on beacon signal
 *  @param venue               closest venue base on beacon signal
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didEnterFloor:(IFMFloorplan *)floor venue:(IFMVenue *)venue;

/**
 *  Called when framework detects strongest beacon assigned for floor.
 *
 *  @param indoorMapController map controller
 *  @param floor               closest floor base on beacon signal
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didEnterFloor:(IFMFloorplan *)floor __attribute__((deprecated));

/**
 *  Distance value change to closest node in path
 *
 *  @param indoorMapController map controller
 *  @param distance            updated distance value
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didChangeTargetNodeDistance:(double)distance;

/**
 *  Total distance value change to navigation target
 *
 *  @param indoorMapController map controller
 *  @param distance            updated total distance value
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didChangeTargetTotalDistance:(double)distance;

/**
 *  Change of heading to navigation target
 *
 *  @param indoorMapController map controller
 *  @param heading             new heading value
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didChangeTargetHeading:(double)heading;

/**
 *  Change of heading
 *
 *  @param indoorMapController map controller
 *  @param heading             new heading value
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didChangeHeading:(double)heading;

/**
 *  Called when floor plan was successful added to map
 *
 *  @param indoorMapController map controller
 *  @param floor               floor plan model object
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didAddFloorPlanInMap:(IFMFloorplan *)floor;

/**
 *  All route nodes in target.
 *
 *  @param indoorMapController map controller
 *  @param nodes               route nodes
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController nodesInRoute:(NSArray *)nodes;

/**
 *  Called when map drag action ends.
 *
 *  @param indoorMapController map controller
 *  @param gestureRecognizer   drag gesture
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didDragMap:(UIGestureRecognizer*)gestureRecognizer;

/**
 *  We lost the connection with all of the beacons inside the floor
 *
 *  @param indoorMapController    map controller
 *  @param floorplan Floorplan with no active beacons
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didLostAllBeaconsForFloorplan:(IFMFloorplan *)floorplan;

/**
 *  We lost the connection with all of the beacons inside the venue
 *
 *  @param indoorMapController    map controller
 *  @param venue IFMVenue with no active beacons
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didLostAllBeaconsForVenue:(IFMVenue *)venue;

/**
 *  Helper method to extend current map with new annotations.
 *  If annotation is not supported by IFINdoorMapController this method is called. This allows to provide own AnnotationView.
 *
 *  @param indoorMapController
 *  @param mapView
 *  @param annotation
 *
 *  @return
 */
- (MKAnnotationView *)indoorMapController:(IFIndoorMapController *)indoorMapController mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation> )annotation __attribute__((deprecated));

/**
 *  Called when starts the compass calibration
 *
 *  @param indoorMapController    map controller
 *  @param calibrationCompassView    view calibration
 */
- (void)indoorMapController:(IFIndoorMapController *)indoorMapController didStartCalibrationWithCalibrationCompassView:(IFCalibrationCompassView *)calibrationCompassView;

/**
 *  Custom view calibration, inherits features that allow calibration of the compass
 *
 *  @param indoorMapController    map controller
 *  @param viewForCalibrationCompassContainer IFCalibrationCompassContainerView - container view calibration
 *
 *  return
 */
- (IFCalibrationCompassView *)indoorMapController:(IFIndoorMapController *)indoorMapController viewForCalibrationCompassContainer:(IFCalibrationCompassContainerView *)calibrationCompassContainer;

/**
 *  Called when the compass calibration has been completed
 *
 *  @param indoorMapController    map controller
 *  @param success
 */
- (void)indoorMapControllerCompleteCalibrationCompass:(IFIndoorMapController *)indoorMapController success:(BOOL)success;

@end

@interface IFIndoorMapController : NSObject <CLLocationManagerDelegate, MKMapViewDelegate>

@property (nonatomic, weak) IBOutlet id<IFIndoorMapControllerDelegate> delegate;
/**
 *  Current floorplan
 */
@property (nonatomic, strong) IFMFloorplan *currentFloorplan;
/**
 *  Image for beacon map annotation. Set if you want to change default image.
 */
@property (nonatomic, strong) UIImage *annotationIconBeacon;
/**
 *  Content is in area icon image. Set if you want to change default image.
 */
@property (nonatomic, strong) UIImage *annotationIconInfoContent;
/**
 *  Image for current user annotation.
 */
@property (nonatomic, strong) UIImage *annotationIconYou;
/**
 *  Display beacons on the map
 */
@property (nonatomic, assign) BOOL shouldAddBeaconsToMap;
/**
 *  Display areas on the map
 */
@property (nonatomic, assign) BOOL shouldAddAreasToMap;
/**
 *  Is target navigation in progress
 */
@property (nonatomic, assign, getter=isTargetNavigationEnabled) BOOL targetNavigationEnabled;
/**
 *  Is warrning next node
 */
@property (nonatomic, strong) NSString *nextNodeWarrning;
/**
 *  Is heading enabled
 */
@property (nonatomic, assign, readonly, getter=isHeading) BOOL heading;
/**
 *  Current user location calclutated with indoor navigation module.
 */
@property (nonatomic, assign, readonly) CLLocationCoordinate2D userCoordinate;
/**
 *  Current user target location calclutated with indoor navigation module. Only is target navigation.
 */
@property (nonatomic, assign, readonly) CLLocationCoordinate2D userTargetCoordinate;
/**
 *  Turn off icon of the current location during navigation
 */
@property (nonatomic, assign) BOOL hideTruePositionWhenNavigating;

/**
 *  Initialize map view with location manager and set self as manager delegate.
 *
 *  @param mapView        map view
 *  @param viewController view controller with map
 *  @param floorplan      floorplan data model
 *  @param manager location manager
 */
- (void)setupWithMapView:(MKMapView *)mapView viewController:(UIViewController *)viewController floorplan:(IFMFloorplan *)floorplan locationManager:(CLLocationManager *)manager;

/**
 *  Start indoor navigation
 */
- (void)start;

/**
 *  Stop indoor navigation
 */
- (void)stop;

/**
 *  Calculate and start navigation to area
 *
 *  @param targetArea target area
 */
- (void)startNavigationToArea:(IFMArea *)targetArea __attribute__((deprecated));
/**
 *  Calculate and start navigation to area
 *
 *  @param targetArea target area
 *  @param type target of routes
 */
- (void)startNavigationToArea:(IFMArea *)targetArea withType:(IFRouteType)type;
/**
 *  End navigation to area
 */
- (void)stopNavigationToArea;
/**
 *  Current area base on position from indoor navigation
 *
 *  @return area model object
 */
- (IFMArea *)currentArea;
/**
 *  Target area in navigation
 *
 *  @return nil if no navigation, area model if navigation in progress
 */
- (IFMArea *)navigateArea __attribute__((deprecated));
/**
 *  Enable map rotation based on heading
 *
 *  @param heading enable/disable heading
 */
- (void)setFollowHeading:(BOOL)heading;

#pragma mark - CLLocationManagerDelegate methods

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status;
- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager;
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)heading;
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

#pragma mark - MKMapViewDelegate methods

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay> )overlay;
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated;
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation> )annotation;

@end


text:
from zmq.eventloop.zmqstream import ZMQStream as ZmqStream
from zmq.sugar import Socket as ZmqSocket
from zmq.sugar import constants as zmq_constants

from pysigslot import Signal

from pycloudia.streams.zmq_impl.messages import Message
from pycloudia.streams.zmq_impl.strategies import *

__all__ = [
    'RouterStream',
    'DealerStream',
    'SinkStream',
    'PushStream',
    'PullStream',
    'BlowStream',
    'SubStream',
    'PubStream',
]

class BaseStream(object):
    """
    :type zmq_message_factory: C{Callable}
    :type zmq_socket_factory: C{Callable}
    :type zmq_stream_factory: C{Callable}
    :type zmq_socket_type: C{int}
    :type zmq_stream_start_strategy: L{pycloudia.streams.zmq_impl.interfaces.IStartStreamStrategy}
    :type zmq_stream_read_strategy: L{pycloudia.streams.zmq_impl.interfaces.IReadStreamMessageStrategy}
    :type zmq_stream_send_strategy: L{pycloudia.streams.zmq_impl.interfaces.ISendStreamMessageStrategy}
    """
    zmq_message_factory = Message
    zmq_socket_factory = ZmqSocket
    zmq_stream_factory = ZmqStream
    zmq_socket_type = NotImplemented
    zmq_stream_start_strategy = NotImplemented
    zmq_stream_read_strategy = NotImplemented
    zmq_stream_send_strategy = NotImplemented

    @classmethod
    def create_instance(cls, zmq_context, zmq_io_loop, *args, **kwargs):
        return cls(zmq_context, zmq_io_loop, *args, **kwargs)

    def __init__(self, zmq_context, zmq_io_loop):
        self.zmq_stream = self._create_zmq_stream(zmq_context, zmq_io_loop)
        self.on_read = Signal()

    def _create_zmq_stream(self, zmq_context, zmq_io_loop):
        zmq_socket = self.zmq_socket_factory(zmq_context, self.zmq_socket_type)
        zmq_stream = self.zmq_stream_factory(zmq_socket, zmq_io_loop)
        return zmq_stream

    def start(self, host, port):
        self.zmq_stream.on_recv(self._read_message)
        self.zmq_stream_start_strategy.start_tcp(self, host, port)

    def start_on_random_port(self, host, min_port=49152, max_port=65536, max_tries=100):
        self.zmq_stream.on_recv(self._read_message)
        return self.zmq_stream_start_strategy.start_tcp_on_random_port(
            self.zmq_stream, host, min_port, max_port, max_tries
        )

    def _read_message(self, message_list):
        self.zmq_stream_read_strategy.read_message(self, message_list)

    def send_message(self, message):
        self.zmq_stream_send_strategy.send_message(self, message)

    def encode_message_string(self, message_string):
        return self.zmq_message_factory(message_string)

    def close(self):
        self.zmq_stream.close()
        self.zmq_stream = None
        self.on_read.disconnect_all()

    def call_feature(self, name, *args, **kwargs):
        method = self.get_feature(name)
        return method(*args, **kwargs)

    def get_feature(self, name):
        name = self._ensure_has_feature(name)
        return getattr(self.zmq_stream.socket, name)

    def set_feature(self, name, value):
        name = self._ensure_has_feature(name)
        return setattr(self.zmq_stream.socket, name, value)

    def _ensure_has_feature(self, name):
        """
        :type name: C{str}
        :rtype: C{str}
        :raise: C{AttributeError}
        """
        if not hasattr(self.zmq_stream.socket, name):
            raise AttributeError('"{0}" object has no attribute "{1}"'.format(type(self), name))
        return name

class RouterStream(BaseStream):
    zmq_socket_type = zmq_constants.ROUTER
    zmq_stream_start_strategy = BindStartStrategy()
    zmq_stream_read_strategy = SignedReadMessageStrategy()
    zmq_stream_send_strategy = RouterSendMessageStrategy()

class DealerStream(BaseStream):
    zmq_socket_type = zmq_constants.DEALER
    zmq_stream_start_strategy = ConnectStartStrategy()
    zmq_stream_read_strategy = DealerReadMessageStrategy()
    zmq_stream_send_strategy = DealerSendMessageStrategy()

    def __init__(self, zmq_context, zmq_io_loop, identity):
        assert identity is not None
        super(DealerStream, self).__init__(zmq_context, zmq_io_loop)
        self.zmq_stream.socket.identity = identity

    @property
    def identity(self):
        return self.zmq_stream.socket.identity

class SinkStream(BaseStream):
    zmq_socket_type = zmq_constants.PULL
    zmq_stream_start_strategy = BindStartStrategy()
    zmq_stream_read_strategy = SignedReadMessageStrategy()
    zmq_stream_send_strategy = RejectSendMessageStrategy()

class PushStream(BaseStream):
    zmq_socket_type = zmq_constants.PUSH
    zmq_stream_start_strategy = ConnectStartStrategy()
    zmq_stream_read_strategy = RejectReadMessageStrategy()
    zmq_stream_send_strategy = SignedSendMessageStrategy()

    def __init__(self, zmq_context, zmq_io_loop, identity):
        assert identity is not None
        super(PushStream, self).__init__(zmq_context, zmq_io_loop)
        self.identity = identity

class PullStream(BaseStream):
    zmq_socket_type = zmq_constants.PULL
    zmq_stream_start_strategy = ConnectStartStrategy()
    zmq_stream_read_strategy = SimpleReadMessageStrategy()
    zmq_stream_send_strategy = RejectSendMessageStrategy()

class BlowStream(BaseStream):
    zmq_socket_type = zmq_constants.PUSH
    zmq_stream_start_strategy = BindStartStrategy()
    zmq_stream_read_strategy = RejectReadMessageStrategy()
    zmq_stream_send_strategy = SimpleSendMessageStrategy()

class SubStream(BaseStream):
    zmq_socket_type = zmq_constants.SUB
    zmq_stream_start_strategy = ConnectStartStrategy()
    zmq_stream_read_strategy = SimpleReadMessageStrategy()
    zmq_stream_send_strategy = RejectSendMessageStrategy()

class PubStream(BaseStream):
    zmq_socket_type = zmq_constants.PUB
    zmq_stream_start_strategy = BindStartStrategy()
    zmq_stream_read_strategy = RejectReadMessageStrategy()
    zmq_stream_send_strategy = SimpleSendMessageStrategy()


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
          "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd" [
  <!ENTITY debian "<productname>Debian</productname>">
]>
<book id="legalnotice.001">
<bookinfo>
<title>Unit Test: legalnotice.001</title>
<releaseinfo role="CVS">$Id: legalnotice.001.xml 4056 2004-11-23 13:28:50Z nwalsh $</releaseinfo>
<author><firstname>Adam</firstname><surname>Di Carlo</surname>
        <affiliation><address><email>adam@onshored.com</email></address></affiliation>
</author>
<edition>draft</edition>
<legalnotice>
      <para>
        A copy of the GNU GPL is available as
        <filename>/usr/share/common-licenses/GPL</filename> on a
        &debian; system.  A copy of the GNU General Public License is
        available.  It is available. It is available. It is
        available. It is available. It is available. It is
        available. It is available. It is available. It is available.
      </para>
      <para>
        We're testing how <sgmltag
        class="element">productname</sgmltag> looks inside of <sgmltag
        class="element">legalnotice</sgmltag>.
      </para>
    </legalnotice>
</bookinfo>
</book>


text:
/******************************************************************
 * Generated by Hottentot CC Generator
 * Date: 02-05-2016 05:11:23
 * Name: calculator_service_server.cc
 * Description:
 *   This file contains definitions of sample stub.
 ******************************************************************/

#include <iostream>

#include <org/labcrypto/hottentot/runtime/configuration.h>
#include <org/labcrypto/hottentot/runtime/logger.h>
#include <org/labcrypto/hottentot/runtime/utils.h>
#include <org/labcrypto/hottentot/runtime/service/service_runtime.h>

#include "calculator_service_impl.h"

int
main(int argc, char **argv) {
  try {
    ::org::labcrypto::hottentot::runtime::Logger::Init();
    ::org::labcrypto::hottentot::runtime::service::ServiceRuntime::Init(argc, argv);
    if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << ::org::labcrypto::hottentot::runtime::Utils::GetCurrentUTCTimeString() << "]: " <<
          "Starting server ..." << std::endl;
    }
    ::ir::ntnaeem::hottentot::examples::calc::CalculatorServiceImpl *service =
        new ::ir::ntnaeem::hottentot::examples::calc::CalculatorServiceImpl;
    ::org::labcrypto::hottentot::runtime::service::ServiceRuntime::Register("0.0.0.0", 2000, service);
    ::org::labcrypto::hottentot::runtime::service::ServiceRuntime::Start();
    if (::org::labcrypto::hottentot::runtime::Configuration::Verbose()) {
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << ::org::labcrypto::hottentot::runtime::Utils::GetCurrentUTCTimeString() << "]: " <<
          "Service runtime is shutdown." << std::endl;
      ::org::labcrypto::hottentot::runtime::Logger::GetOut() <<
        "[" << ::org::labcrypto::hottentot::runtime::Utils::GetCurrentUTCTimeString() << "]: " <<
          "About to disable logging system ..." << std::endl;
    }
    ::org::labcrypto::hottentot::runtime::service::ServiceRuntime::Shutdown();
    ::org::labcrypto::hottentot::runtime::Logger::Shutdown();
  } catch (...) {
    std::cout <<
        "[" << ::org::labcrypto::hottentot::runtime::Utils::GetCurrentUTCTimeString() << "]: " <<
          "Error." << std::endl;
    return 1;
  }
  return 0;
}


text:
source functions-gbp

set -x

trap prepare_logs ERR

run_gbp_rally
exit_code=$?

# Prepare the log files for Jenkins to upload
prepare_logs

exit $exit_code


text:
namespace FootballPredictions.Models
{
    public class Prediction
    {
        public int Id { get; set; }

        public Game Game { get; set; }

        public GameResult Result { get; set; }

        // TODO: prediction should have user
    }
}


text:
package net.nothinginteresting.vaadin.event.bus;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target({ METHOD })
@Retention(RUNTIME)
public @interface ViewHandler
{
	String value() default "";
}


text:
<applicationConfig xmlns="http://www.edmunds.com/etm/1.0">
    <application>
        <groupId>${project.groupId}</groupId>
        <artifactId>${project.artifactId}</artifactId>
        <version>${project.version}</version>
    </application>
    <urlRules>
        <urlRule>/test-app/**</urlRule>
        <urlRule>/[make]/[model]/[year]/**</urlRule>
    </urlRules>
    <httpMonitor>
        <url>/test-app/</url>
        <content>ETM client library</content>
    </httpMonitor>
</applicationConfig>


text:
all: local test alpine linux

test:
	docker run --rm -ti -v $(CURDIR):/usr/local/src/github.com/qnib/qcollect/ --workdir /usr/local/src/github.com/qnib/qcollect qnib/golang ./test.sh

local:
	./build.sh

alpine:
	docker run --rm -ti -v $(CURDIR):/usr/local/src/github.com/qnib/qcollect/ --workdir /usr/local/src/github.com/qnib/qcollect qnib/alpn-go-dev ./build.sh

linux:
	docker run --rm -ti -v $(CURDIR):/usr/local/src/github.com/qnib/qcollect --workdir /usr/local/src/github.com/qnib/qcollect qnib/golang ./build.sh


text:
//
//  DonwloadData.m
//  Spotify2Music
//
//  Created by Christian Mazzeo on 21/7/15.
//  Copyright (c) 2015 Onsitesoft. All rights reserved.
//

#import "CMDownloadFile.h"
typedef void (^NH3_ResponseDataBLock)(NSError *error,NSData *data);
@interface CMDownloadFile(){
    NSTimer*                timeoutTimer;
    BOOL                    requestAsynchronous;
    NSTimeInterval          timeout;
    NH3_ResponseDataBLock  responseBLock;
    NSString *              fullPathString;
}
@end

@implementation CMDownloadFile
- (id)initWithServerPath:(NSString *)serverPath  fileName:(NSString *)fileName  requestAsynchronous:(BOOL)asynchronous  timeOut:(NSTimeInterval)timeOut completionHandler:(void (^)(NSError *error,NSData *data))completionHandler{
    self = [super init];
    if (self){
        responseBLock = completionHandler;

        requestAsynchronous = asynchronous;
        timeout = timeOut;
        fullPathString = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@/%@",serverPath,fileName]];
    }
    return self;
}
- (void)main{

    [self startWebService];
}
- (void)callTimeOut{

    [timeoutTimer invalidate];
    NSError * tempError = [[NSError alloc] initWithDomain:@"" code:-1001 userInfo:nil] ;
    responseBLock(tempError,nil);
}

- (void)startWebService{
#ifdef DEBUG
    NSLog(@"Downloding File: %@",fullPathString);
#endif
  /*   timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:timeout target:self  selector:@selector(callTimeOut) userInfo:nil repeats:NO];
    NSURL *url = [NSURL URLWithString:fullPathString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
*/
}
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes{

}
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes{

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    /*

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
    NSDictionary *dict = httpResponse.allHeaderFields;
    NSString *lengthString = [dict valueForKey:@"Content-Length"];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber *length = [formatter numberFromString:lengthString];
    self.totalBytes = length.unsignedIntegerValue;

    self.imageData = [[NSMutableData alloc] initWithCapacity:self.totalBytes];
     */
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
   /* [self.imageData appendData:data];
    self.receivedBytes += data.length;
    */

    // Actual progress is self.receivedBytes / self.totalBytes
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // responseBLock(error,tempData);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
     //responseBLock(error,nil);
}
@end


text:
<?php

require_once '../../bootstrap.php';

use Pop\Archive\Archive;

try {
    // Create a new TAR archive and add some files to it
    // (Make sure the '../tmp' folder is writable)
    $archive = new Archive('../tmp/test.tar');
    $archive->addFiles('../assets');

    // Display the new archive file size
    echo $archive->getBasename() . ': file size => ' . $archive->getSize() . '
 ' . PHP_EOL;

    // Compress the archive (Gzip by default)
    $archive->compress('bz');

    // Display the newly compressed archive file size
    echo $archive->getBasename() . ': compressed file size => ' . $archive->getSize() . '
 ' . PHP_EOL;
    echo 'Done.';
} catch (\Exception $e) {
    echo $e->getMessage() . PHP_EOL . PHP_EOL;
}


text:
Town::Town(std::string name, SDL_Renderer *renderer, SDL_Window *window)
  : EntityContainer(name, renderer, window)
{
  mGroupMap["buildings"] = new EntityGroup(renderer, window);
  mGroupMap["units"] = new EntityGroup(renderer, window);
  mGroupMap["constructions"] = new EntityGroup(renderer, window);
  mRegion = nullptr;
}

Town::~Town()
{
  TerminalText::printTerminal("INFO: Town::~Town: Deleting Town.");
}

void Town::addEntity(Entity * ent)
{
  if ( dynamic_cast<Unit*>(ent) )
    {
      dynamic_cast<Unit*>(ent)->setTown(this);
      mGroupMap["units"]->addEntity( ent );
    }
  else if ( dynamic_cast<Building*>(ent) )
    {
      dynamic_cast<Building*>(ent)->setTown(this);
      mGroupMap["buildings"]->addEntity( ent );
    }
  else if ( dynamic_cast<Construction*>(ent) )
    {
      dynamic_cast<Construction*>(ent)->setTown(this);
      mGroupMap["constructions"]->addEntity( ent );
    }
  else
    TerminalText::printTerminal("WARN: Town::addEntity: Only a Unit, Building or Constreuction can be added to the Town.");
}

void Town::setUnitImage( std::string filename )
{
  mGroupMap["units"]->setImage( filename );
}

void Town::setStockpile(Building * bld)
{
  Entity * ent = getEntity( bld->getName() );
  if ( ent == nullptr )
    {
      //the stockpile is not yet in the lists of entities
      EntityContainer::addEntity( "buildings", bld );
    }
  mStockpile = bld;
}

void Town::update()
{
  //set the stockpile to a building of type=stockpile, if not already the case
  if ( mStockpile->getType() != 1)
    {
      for (auto &itb: mGroupMap["buildings"]->mEntities)
        {
          if ( dynamic_cast<Building*>(itb)->getType() == 1 )
            setStockpile(dynamic_cast<Building*>(itb));
        }
    }
  EntityContainer::update();
}


text:
layout: post
authors: ["Greg Wilson"]
title: "Reopening Instructor Training"
date: 2016-07-25
time: "00:04:00"
category: ["Instructor Training"]
---

For the last ten months,
the Software Carpentry Foundation has worked toward three goals
for its instructor training program:

1.  Make the content more relevant.

2.  Increase the number of people able to deliver instructor training.

3.  Find a format that meets everyone's needs in a sustainable way.

We have made a lot of progress on all three,
and are therefore now able to offer instructor training once again
to people who aren't affiliated with our partner organizations,
but would like to teach Software Carpentry, Data Carpentry, or both
(as the course is shared by both organizations).
If you wish to apply to take part
in one of the two open-enrollment classes we will offer this fall,
please fill in the form at:

<https://amy.software-carpentry.org/workshops/request_training/>

to tell us about yourself,
what excites you about teaching,
and how Software and Data Carpentry can help in your community.
We will notify applicants as spaces become available.
If you have any questions,
please mail
[training@software-carpentry.org](mailto:training@software-carpentry.org).

If you would like to accelerate the process,
check out our [Partnership program]({{site.baseurl}}/scf/join/).
Organizational partners make ongoing commitments to supporting our organization
and are prioritized for instructor training.
If you need help making the case at your organization,
feel free to contact us at
[partnerships@software-carpentry.org](mailto:partnerships@software-carpentry.org):
we'd be happy to help.

Please note that as a condition of taking this training, you must:

*   abide by our code of conduct, which can be found at
    <http://software-carpentry.org/conduct/> and
    <http://datacarpentry.org/code-of-conduct/>,

*   agree to teach at a Software Carpentry or Data Carpentry workshop
    within 12 months of the course,
    and

*   complete three short tasks after the course in order to complete certification.
    The tasks take a total of approximately 8-10 hours,
    and are described at
    <{{site.training_url}}/checkout/>.

For more information on Software and Data Carpentry instructor training,
please see the course material at:

<{{site.training_url}}>

Please also see [this additional post]({{site.baseurl}}/blog/2016/07/more-on-instructor-training.html),
which answers some frequently-asked questions about this training.


text:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _

from categories.base import CategoryBaseAdmin

from storybase_taxonomy.forms import (CategoryAdminForm,
		                      CategoryTranslationAdminForm)
from storybase_taxonomy.models import Category, CategoryTranslation, Tag

class CategoryTranslationInline(admin.StackedInline):
    """Inline for translated fields of a Story"""
    model = CategoryTranslation
    form = CategoryTranslationAdminForm
    prepopulated_fields = {'slug': ('name',)}
    extra = 1

class CategoryAdmin(CategoryBaseAdmin):
    model = Category
    form = CategoryAdminForm
    list_display = ('obj_name',)
    search_fields = ('categorytranslation__name',)
    prepopulated_fields = {}
    inlines = [CategoryTranslationInline]

    def get_actions(self, request):
        """
        Override CategoryBaseAdmin's implementation because we want to
        allow bulk deletion
        """
        actions = super(CategoryBaseAdmin, self).get_actions(request)
        return actions

    def obj_name(self, obj):
        """
        Workaround to show the name in the change list view of the admin

        We need to do this because the name field is on the translation
        class

        """
        return obj.name
    obj_name.short_description = _('Name')

class TagAdmin(admin.ModelAdmin):
    pass

admin.site.register(Category, CategoryAdmin)
admin.site.register(Tag, TagAdmin)


text:
using System;

namespace DragonSpark.Sources
{
	public interface IScopeAware<in T> : IScopeAware, IAssignable<Func<object, T>>, IAssignable<Func<T>> {}
}


text:
package com.spotify.reaper;

import org.apache.cassandra.repair.RepairParallelism;
import org.hibernate.validator.HibernateValidator;
import org.junit.Before;
import org.junit.Test;

import javax.validation.Validation;
import javax.validation.Validator;

import io.dropwizard.db.DataSourceFactory;

import static org.fest.assertions.api.Assertions.assertThat;

public class ReaperApplicationConfigurationTest {

  private final Validator validator = Validation
      .byProvider(HibernateValidator.class)
      .configure()
      .buildValidatorFactory()
      .getValidator();

  private final ReaperApplicationConfiguration config = new ReaperApplicationConfiguration();

  @Before
  public void setUp() {
    //create a valid config
    DataSourceFactory dataSourceFactory = new DataSourceFactory();
    dataSourceFactory.setDriverClass("org.postgresql.Driver");
    dataSourceFactory.setUrl("jdbc:postgresql://db.example.com/db-prod");
    dataSourceFactory.setUser("user");
    config.setDataSourceFactory(dataSourceFactory);
    config.setHangingRepairTimeoutMins(1);
    config.setRepairParallelism(RepairParallelism.DATACENTER_AWARE);
    config.setRepairRunThreadCount(1);
    config.setSegmentCount(1);
    config.setScheduleDaysBetween(7);
    config.setStorageType("foo");
  }

  @Test
  public void testRepairIntensity() {
    config.setRepairIntensity(-0.1);
    assertThat(validator.validate(config)).hasSize(1);

    config.setRepairIntensity(0);
    assertThat(validator.validate(config)).hasSize(1);

    config.setRepairIntensity(1);
    assertThat(validator.validate(config)).hasSize(0);
  }
}


text:
package org.la4j.vector.source;

import java.util.Random;

public class RandomVectorSource implements VectorSource {

    private int length;
    private Random random;

    public RandomVectorSource(int length, Random random) {
        this.length = length;
        this.random = random;
    }

    @Override
    public double get(int i) {
        return random.nextDouble();
    }

    @Override
    public int length() {
        return length;
    }
}


text:
<?php

namespace phpseclib\Crypt;

use phpseclib\Crypt\AES;
use phpseclib\Crypt\Base;
use phpseclib\Crypt\Blowfish;
use phpseclib\Crypt\DES;
use phpseclib\Crypt\RC4;
use phpseclib\Crypt\TripleDES;
use phpseclib\Crypt\Twofish;

/**
 * Pure-PHP Random Number Generator
 *
 * @package Random
 * @author  Jim Wigginton <terrafrost@php.net>
 * @access  public
 */
class Random
{
    /**
     * Generate a random string.
     *
     * Although microoptimizations are generally discouraged as they impair readability this function is ripe with
     * microoptimizations because this function has the potential of being called a huge number of times.
     * eg. for RSA key generation.
     *
     * @param Integer $length
     * @return String
     */
    public static function string($length)
    {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
            // ie. class_alias is a function that was introduced in PHP 5.3
            if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
                return mcrypt_create_iv($length);
            }
            // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
            // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
            // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
            // call php_win32_get_random_bytes():
            //
            // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
            // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
            //
            // php_win32_get_random_bytes() is defined thusly:
            //
            // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
            //
            // we're calling it, all the same, in the off chance that the mcrypt extension is not available
            if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
                return openssl_random_pseudo_bytes($length);
            }
        } else {
            // method 1. the fastest
            if (function_exists('openssl_random_pseudo_bytes')) {
                return openssl_random_pseudo_bytes($length);
            }
            // method 2
            static $fp = true;
            if ($fp === true) {
                // warning's will be output unles the error suppression operator is used. errors such as
                // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
                $fp = @fopen('/dev/urandom', 'rb');
            }
            if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource()
                return fread($fp, $length);
            }
            // method 3. pretty much does the same thing as method 2 per the following url:
            // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
            // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
            // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
            // restrictions or some such
            if (function_exists('mcrypt_create_iv')) {
                return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
            }
        }
        // at this point we have no choice but to use a pure-PHP CSPRNG

        // cascade entropy across multiple PHP instances by fixing the session and collecting all
        // environmental variables, including the previous session data and the current session
        // data.
        //
        // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
        // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
        // PHP isn't low level to be able to use those as sources and on a web server there's not likely
        // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
        // however, a ton of people visiting the website. obviously you don't want to base your seeding
        // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
        // by the user and (2) this isn't just looking at the data sent by the current user - it's based
        // on the data sent by all users. one user requests the page and a hash of their info is saved.
        // another user visits the page and the serialization of their data is utilized along with the
        // server envirnment stuff and a hash of the previous http request data (which itself utilizes
        // a hash of the session data before that). certainly an attacker should be assumed to have
        // full control over his own http requests. he, however, is not going to have control over
        // everyone's http requests.
        static $crypto = false, $v;
        if ($crypto === false) {
            // save old session data
            $old_session_id = session_id();
            $old_use_cookies = ini_get('session.use_cookies');
            $old_session_cache_limiter = session_cache_limiter();
            $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false;
            if ($old_session_id != '') {
                session_write_close();
            }

            session_id(1);
            ini_set('session.use_cookies', 0);
            session_cache_limiter('');
            session_start();

            $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
                serialize($_SERVER) .
                serialize($_POST) .
                serialize($_GET) .
                serialize($_COOKIE) .
                serialize($GLOBALS) .
                serialize($_SESSION) .
                serialize($_OLD_SESSION)
            ));
            if (!isset($_SESSION['count'])) {
                $_SESSION['count'] = 0;
            }
            $_SESSION['count']++;

            session_write_close();

            // restore old session data
            if ($old_session_id != '') {
                session_id($old_session_id);
                session_start();
                ini_set('session.use_cookies', $old_use_cookies);
                session_cache_limiter($old_session_cache_limiter);
            } else {
                if ($_OLD_SESSION !== false) {
                    $_SESSION = $_OLD_SESSION;
                    unset($_OLD_SESSION);
                } else {
                    unset($_SESSION);
                }
            }

            // in SSH2 a shared secret and an exchange hash are generated through the key exchange process.
            // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C.
            // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the
            // original hash and the current hash. we'll be emulating that. for more info see the following URL:
            //
            // http://tools.ietf.org/html/rfc4253#section-7.2
            //
            // see the is_string($crypto) part for an example of how to expand the keys
            $key = pack('H*', sha1($seed . 'A'));
            $iv = pack('H*', sha1($seed . 'C'));

            // ciphers are used as per the nist.gov link below. also, see this link:
            //
            // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
            switch (true) {
                case class_exists('\phpseclib\Crypt\AES'):
                    $crypto = new AES(Base::MODE_CTR);
                    break;
                case class_exists('\phpseclib\Crypt\Twofish'):
                    $crypto = new Twofish(Base::MODE_CTR);
                    break;
                case class_exists('\phpseclib\Crypt\Blowfish'):
                    $crypto = new Blowfish(Base::MODE_CTR);
                    break;
                case class_exists('\phpseclib\Crypt\TripleDES'):
                    $crypto = new TripleDES(Base::MODE_CTR);
                    break;
                case class_exists('\phpseclib\Crypt\DES'):
                    $crypto = new DES(Base::MODE_CTR);
                    break;
                case class_exists('\phpseclib\Crypt\RC4'):
                    $crypto = new RC4();
                    break;
                default:
                    user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
                    return false;
            }

            $crypto->setKey($key);
            $crypto->setIV($iv);
            $crypto->enableContinuousBuffer();
        }

        //return $crypto->encrypt(str_repeat("\0", $length));

        // the following is based off of ANSI X9.31:
        //
        // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
        //
        // OpenSSL uses that same standard for it's random numbers:
        //
        // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c
        // (do a search for "ANS X9.31 A.2.4")
        $result = '';
        while (strlen($result) < $length) {
            $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21
            $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20
            $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20
            $result.= $r;
        }
        return substr($result, 0, $length);
    }
}


text:
package io.stalk.cloud.auth.controller;

import static java.util.Arrays.asList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.approval.Approval;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestAPIController {

    @Autowired private ApprovalStore approvalStore;
    @Autowired private TokenStore tokenStore;

	@RequestMapping("/ping")
	public String ping() {
		return "pong";
	}

    @RequestMapping(value = "/approval/revoke", method = RequestMethod.POST)
    public String revokeApproval(@ModelAttribute Approval approval) {
        approvalStore.revokeApprovals(asList(approval));
        tokenStore
                .findTokensByClientIdAndUserName(approval.getClientId(), approval.getUserId())
                .forEach(tokenStore::removeAccessToken);
        return "redirect:/approvals";
    }

}


text:
// Copyright (c) 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api_ash.h"

#include <memory>

#include "base/files/file_path.h"
#include "base/memory/scoped_refptr.h"
#include "base/values.h"
#include "chrome/browser/ash/policy/core/device_attributes_fake.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/system/fake_statistics_provider.h"
#include "chromeos/system/statistics_provider.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/browser/api_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

namespace {

constexpr char kFakeDirectoryApiId[] = "fake directory API ID";
constexpr char kFakeDeviceSerialNumber[] = "fake device serial number";
constexpr char kFakeAssetId[] = "fake asset ID";
constexpr char kFakeAnnotatedLocation[] = "fake annotated location";

std::string ParamToString(const testing::TestParamInfo<bool>& info) {
  return info.param ? "SignInProfile" : "NonSignInProfile";
}

}  // namespace

// The bool parameter tells if a test instance should use a sign in profile or
// not. This is useful because the extension APIs should return empty string on
// non sign in and non affiliated profiles.
class EnterpriseDeviceAttributesApiAshTest
    : public testing::TestWithParam<bool> {
 protected:
  void SetUp() override {
    // Set up fake device attributes.
    device_attributes_ = std::make_unique<policy::FakeDeviceAttributes>();
    device_attributes_->SetFakeDirectoryApiId(kFakeDirectoryApiId);
    device_attributes_->SetFakeDeviceAssetId(kFakeAssetId);
    device_attributes_->SetFakeDeviceAnotatedLocation(kFakeAnnotatedLocation);

    // Set up fake serial number.
    statistics_provider_.SetMachineStatistic(
        chromeos::system::kSerialNumberKeyForTest, kFakeDeviceSerialNumber);
    chromeos::system::StatisticsProvider::SetTestProvider(
        &statistics_provider_);

    // Set up a testing profile. Needs to return true when passed to
    // crosapi::browser_util::IsSigninProfileOrBelongsToAffiliatedUser.
    TestingProfile::Builder builder;
    if (IsSignInProfile()) {
      builder.SetPath(
          base::FilePath(FILE_PATH_LITERAL(chrome::kInitialProfile)));
    }
    profile_ = builder.Build();
  }

  bool IsSignInProfile() { return GetParam(); }

  content::BrowserTaskEnvironment task_environment_;
  std::unique_ptr<policy::FakeDeviceAttributes> device_attributes_;
  std::unique_ptr<Profile> profile_;

 private:
  chromeos::system::FakeStatisticsProvider statistics_provider_;
};

TEST_P(EnterpriseDeviceAttributesApiAshTest, GetDirectoryDeviceIdFunction) {
  auto function = base::MakeRefCounted<
      EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction>(
      std::move(device_attributes_));

  std::unique_ptr<base::Value> result =
      api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), /*args=*/"[]", profile_.get());
  ASSERT_TRUE(result->is_string());
  EXPECT_EQ(IsSignInProfile() ? kFakeDirectoryApiId : "", result->GetString());
}

TEST_P(EnterpriseDeviceAttributesApiAshTest, GetDeviceSerialNumberFunction) {
  auto function = base::MakeRefCounted<
      EnterpriseDeviceAttributesGetDeviceSerialNumberFunction>();

  std::unique_ptr<base::Value> result =
      api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), /*args=*/"[]", profile_.get());
  ASSERT_TRUE(result->is_string());
  EXPECT_EQ(IsSignInProfile() ? kFakeDeviceSerialNumber : "",
            result->GetString());
}

TEST_P(EnterpriseDeviceAttributesApiAshTest, GetDeviceAssetIdFunction) {
  auto function =
      base::MakeRefCounted<EnterpriseDeviceAttributesGetDeviceAssetIdFunction>(
          std::move(device_attributes_));

  std::unique_ptr<base::Value> result =
      api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), /*args=*/"[]", profile_.get());
  ASSERT_TRUE(result->is_string());
  EXPECT_EQ(IsSignInProfile() ? kFakeAssetId : "", result->GetString());
}

TEST_P(EnterpriseDeviceAttributesApiAshTest,
       GetDeviceAnnotatedLocationFunction) {
  auto function = base::MakeRefCounted<
      EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction>(
      std::move(device_attributes_));

  std::unique_ptr<base::Value> result =
      api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), /*args=*/"[]", profile_.get());
  ASSERT_TRUE(result->is_string());
  EXPECT_EQ(IsSignInProfile() ? kFakeAnnotatedLocation : "",
            result->GetString());
}

INSTANTIATE_TEST_SUITE_P(All,
                         EnterpriseDeviceAttributesApiAshTest,
                         testing::Bool(),
                         &ParamToString);
}  // namespace extensions


text:
package com.orientechnologies.orient.core.db.graph;

import java.util.Collection;
import java.util.IdentityHashMap;

import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.ODatabasePojoAbstract;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.exception.OGraphException;
import com.orientechnologies.orient.core.fetch.OFetchHelper;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.iterator.OGraphVertexIterator;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;

/**
 * GraphDB implementation on top of underlying Document. Graph Element are Object itself. This API will be not more supported in the
 * future in favor of {@link OGraphDatabase} class much lighter and faster than this. Otherwise, you can use the TinkerPop
 * Blueprints entry-point.
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 */
public class ODatabaseGraphTx extends ODatabasePojoAbstract<OGraphElement> {

	public ODatabaseGraphTx(final String iURL) {
		super(new ODatabaseDocumentTx(iURL));
	}

	@Override
	@SuppressWarnings("unchecked")
	public <THISDB extends ODatabase> THISDB open(final String iUserName, final String iUserPassword) {
		underlying.open(iUserName, iUserPassword);

		checkForGraphSchema();

		return (THISDB) this;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <THISDB extends ODatabase> THISDB create() {
		underlying.create();

		checkForGraphSchema();

		return (THISDB) this;
	}

	public OGraphVertex createVertex() {
		return new OGraphVertex(this);
	}

	public OGraphVertex createVertex(final String iClassName) {
		return new OGraphVertex(this, iClassName);
	}

	public OGraphVertex getRoot(final String iName) {
		final ODocument doc = (ODocument) underlying.getDictionary().get(iName);
		if (doc != null)
			return registerPojo(new OGraphVertex(this, doc));
		return null;
	}

	public OGraphVertex getRoot(final String iName, final String iFetchPlan) {
		return registerPojo(new OGraphVertex(this, (ODocument) underlying.getDictionary().get(iName), iFetchPlan));
	}

	public ODatabaseGraphTx setRoot(final String iName, final OGraphVertex iNode) {
		underlying.getDictionary().put(iName, iNode.getDocument());
		return this;
	}

	public ODictionary<OGraphElement> getDictionary() {
		throw new UnsupportedOperationException("getDictionary()");
	}

	@SuppressWarnings("unchecked")
	public OGraphElement newInstance() {
		return new OGraphVertex(this);
	}

	@SuppressWarnings("unchecked")
	public OGraphElement load(final OGraphElement iObject) {
		if (iObject != null)
			iObject.load();
		return iObject;
	}

	@SuppressWarnings("unchecked")
	public OGraphElement load(final OGraphElement iObject, final String iFetchPlan) {
		if (iObject != null)
			iObject.load(iFetchPlan);
		return iObject;
	}

	@SuppressWarnings("unchecked")
	public OGraphElement load(final OGraphElement iObject, final String iFetchPlan, final boolean iIgnoreCache) {
		if (iObject != null)
			iObject.load(iFetchPlan, iIgnoreCache);
		return iObject;
	}

	public void reload(final OGraphElement iObject) {
		if (iObject != null)
			iObject.reload();
	}

	public void reload(final OGraphElement iObject, final String iFetchPlan, final boolean iIgnoreCache) {
		if (iObject != null)
			iObject.reload(iFetchPlan, iIgnoreCache);
	}

	@SuppressWarnings("unchecked")
	public OGraphElement load(final ORID iRecordId) {
		return load(iRecordId, null);
	}

	@SuppressWarnings("unchecked")
	public OGraphElement load(final ORID iRecordId, final String iFetchPlan) {
		return load(iRecordId, iFetchPlan, false);
	}

	@SuppressWarnings("unchecked")
	public OGraphElement load(final ORID iRecordId, final String iFetchPlan, final boolean iIgnoreCache) {
		ODocument doc = loadAsDocument(iRecordId, iFetchPlan, iIgnoreCache);

		if (doc == null)
			return null;

		return newInstance(doc.getClassName()).setDocument(doc);
	}

	public ODocument loadAsDocument(final ORID iRecordId, final String iFetchPlan, final boolean iIgnoreCache) {
		if (iRecordId == null)
			return null;

		// TRY IN LOCAL CACHE
		ODocument doc = getRecordById(iRecordId);
		if (doc == null) {
			// TRY TO LOAD IT
			doc = (ODocument) underlying.load(iRecordId, iFetchPlan, iIgnoreCache);
			if (doc == null)
				// NOT FOUND
				return null;
		}
		OFetchHelper.checkFetchPlanValid(iFetchPlan);
		if (doc.getClassName() == null)
			throw new OGraphException(
					"The document loaded has no class, while it should be a OGraphVertex, OGraphEdge or any subclass of its. Record: " + doc);

		return doc;
	}

	public ODatabaseComplex<OGraphElement> save(final OGraphElement iObject) {
		iObject.getDocument().save();
		return this;
	}

	public ODatabaseComplex<OGraphElement> save(final OGraphElement iObject, final String iClusterName) {
		iObject.getDocument().save(iClusterName);
		return this;
	}

	public ODatabaseComplex<OGraphElement> delete(final OGraphElement iObject) {
		iObject.getDocument().delete();
		unregisterPojo(iObject, iObject.getDocument());
		return this;
	}

	public OGraphVertexIterator browseVertexes() {
		return new OGraphVertexIterator(this, true);
	}

	public OGraphVertexIterator browseVertexes(final boolean iPolymorphic) {
		return new OGraphVertexIterator(this, iPolymorphic);
	}

	@SuppressWarnings("unchecked")
	public OGraphElement newInstance(final String iClassName) {
		if (iClassName.equals(OGraphVertex.class.getSimpleName()))
			return new OGraphVertex(this);
		else if (iClassName.equals(OGraphEdge.class.getSimpleName()))
			return new OGraphEdge(this);

		OClass cls = getMetadata().getSchema().getClass(iClassName);
		if (cls != null) {
			cls = cls.getSuperClass();
			while (cls != null) {
				if (cls.getName().equals(OGraphVertex.class.getSimpleName()))
					return new OGraphVertex(this, iClassName);
				else if (cls.getName().equals(OGraphEdge.class.getSimpleName()))
					return new OGraphEdge(this, iClassName);

				cls = cls.getSuperClass();
			}
		}

		throw new OGraphException("Unrecognized class: " + iClassName);
	}

	public IdentityHashMap<ODocument, OGraphElement> getRecords2Objects() {
		return records2Objects;
	}

	public void removeCachedElements(final Collection<OGraphElement> iElements) {
		for (OGraphElement e : iElements) {
			records2Objects.remove(e.getDocument());
			rid2Records.remove(e.getDocument().getIdentity());
			objects2Records.remove(System.identityHashCode(e));
		}
	}

	private OGraphVertex registerPojo(final OGraphVertex iVertex) {
		registerUserObject(iVertex, iVertex.getDocument());
		return iVertex;
	}

	private void checkForGraphSchema() {
		OClass vertex = underlying.getMetadata().getSchema().getClass(OGraphDatabase.VERTEX_CLASS_NAME);
		OClass edge = underlying.getMetadata().getSchema().getClass(OGraphDatabase.EDGE_CLASS_NAME);

		if (vertex == null) {
			// CREATE THE META MODEL USING THE ORIENT SCHEMA
			vertex = underlying.getMetadata().getSchema()
					.createClass(OGraphDatabase.VERTEX_CLASS_NAME, underlying.addPhysicalCluster(OGraphDatabase.VERTEX_CLASS_NAME));
			edge = underlying.getMetadata().getSchema()
					.createClass(OGraphDatabase.EDGE_CLASS_NAME, underlying.addPhysicalCluster(OGraphDatabase.EDGE_CLASS_NAME));

			edge.createProperty(OGraphDatabase.EDGE_FIELD_IN, OType.LINK, vertex);
			edge.createProperty(OGraphDatabase.EDGE_FIELD_OUT, OType.LINK, vertex);

			vertex.createProperty(OGraphDatabase.VERTEX_FIELD_IN, OType.LINKSET, edge);
			vertex.createProperty(OGraphDatabase.VERTEX_FIELD_OUT, OType.LINKSET, edge);
		} else {
			// @COMPATIBILITY <= 1.0rc4: CHANGE FROM outEdges -> out and inEdges -> in
			if (vertex.existsProperty(OGraphDatabase.VERTEX_FIELD_OUT_EDGES)) {
				OGraphDatabaseMigration.migrate((OGraphDatabase) new OGraphDatabase(getURL()).open("admin", "admin"));
			}
		}
	}

	@Override
	public ODocument pojo2Stream(final OGraphElement iPojo, ODocument record) {
		return record;
	}

	@Override
	public Object stream2pojo(ODocument record, final Object iPojo, String iFetchPlan) {
		((OGraphElement) iPojo).setDocument(record);
		return iPojo;
	}

	@Override
	public void delete() {
		underlying.delete();
	}

	public long countClass(final String iClassName) {
		return underlying.countClass(iClassName);
	}
}