text:
<?php

use yii\db\Migration;

class m170519_085758_expansion_of_logic extends Migration
{
    public function safeUp()
    {
        $tables = Yii::$app->db->schema->getTableNames();
        $dbType = $this->db->driverName;
        $tableOptions_mysql  = "CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB";
        $tableOptions_mssql  = "";
        $tableOptions_pgsql  = "";
        $tableOptions_sqlite = "";

        /**
         * Основные корректировки структуры базы данных
         * @var [type]
         */

        if (!in_array('contragent', $tables))  {
            if ($dbType == "mysql") {
                // Переименование таблицы clients в contragent
                $this->renameTable ('clients', 'contragent');

                // Добавление необходимых полей для расширения таблицы contragent
                $this->addColumn ('contragent', 'contragentType', $this->string(50));
                $this->addColumn ('contragent', 'parentContragent', $this->string(50));
                $this->addColumn ('contragent', 'address', $this->string(50));
                $this->addColumn ('contragent', 'photo', $this->string(50));
                $this->addColumn ('contragent', 'longitude', 'DOUBLE NOT NULL');
                $this->addColumn ('contragent', 'latitude', 'DOUBLE NOT NULL');
                // Добавление необходимых полей для расширения таблицы orders
                $this->addColumn ('orders', 'customerUuid', $this->string(50));
                $this->addColumn ('orders', 'perpetratorUuid', $this->string(50));
                // Добавление необходимых полей для расширения таблицы operationTool
                $this->addColumn ('operationtool', 'quantity', $this->integer(10));
                // Добавление необходимых полей для таблиц orders, task, taskstage и operation
                $this->addColumn ('orders', 'comment', $this->string(100));
                $this->addColumn ('operation', 'comment', $this->string(100));
            }
        }

        if (!in_array('brigade', $tables))  {
            if ($dbType == "mysql") {
                $this->createTable('{{%brigade}}', [
                  '_id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT',
                  0 => 'PRIMARY KEY (`_id`)',
                  'uuid' => 'VARCHAR(50) NOT NULL',
                  'title' => 'VARCHAR(100) NOT NULL',
                  'contragentUuid' => 'VARCHAR(50) NOT NULL',
                  'createdAt' => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ',
                  'changedAt' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                ], $tableOptions_mysql);
            }
        }

        if (!in_array('contragentuser', $tables))  {
            if ($dbType == "mysql") {
                $this->createTable('{{%contragentuser}}', [
                  '_id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT',
                  0 => 'PRIMARY KEY (`_id`)',
                  'uuid' => 'VARCHAR(50) NOT NULL',
                  'contragentUuid' => 'VARCHAR(50) NOT NULL',
                  'userUuid' => 'VARCHAR(50) NOT NULL',
                  'createdAt' => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ',
                  'changedAt' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                ], $tableOptions_mysql);
            }
        }

        if (!in_array('brigadeuser', $tables))  {
            if ($dbType == "mysql") {
                $this->createTable('{{%brigadeuser}}', [
                  '_id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT',
                  0 => 'PRIMARY KEY (`_id`)',
                  'uuid' => 'VARCHAR(50) NOT NULL',
                  'brigadeUuid' => 'VARCHAR(50) NOT NULL',
                  'userUuid' => 'VARCHAR(50) NOT NULL',
                  'createdAt' => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ',
                  'changedAt' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                ], $tableOptions_mysql);
            }
        }

        if (!in_array('defecttype', $tables))  {
            if ($dbType == "mysql") {
                $this->createTable('{{%defecttype}}', [
                  '_id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT',
                  0 => 'PRIMARY KEY (`_id`)',
                  'uuid' => 'VARCHAR(50) NOT NULL',
                  'title' => 'VARCHAR(100) NOT NULL',
                  'equipmentTypeUuid' => 'VARCHAR(50) NOT NULL',
                  'createdAt' => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ',
                  'changedAt' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                ], $tableOptions_mysql);
            }
        }

        if (!in_array('defect', $tables))  {
            if ($dbType == "mysql") {
                $this->createTable('{{%defect}}', [
                  '_id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT',
                  0 => 'PRIMARY KEY (`_id`)',
                  'uuid' => 'VARCHAR(50) NOT NULL',
                  'userUuid' => 'VARCHAR(50) NOT NULL',
                  'date' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                  'equipmentUuid' => 'VARCHAR(50) NOT NULL',
                  'defectTypeUuid' => 'VARCHAR(50) NOT NULL',
                  'process' => 'BOOLEAN DEFAULT NULL',
                  'comment' => 'VARCHAR(100) NOT NULL',
                  'taskUuid' => 'VARCHAR(50) NOT NULL',
                  'createdAt' => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ',
                  'changedAt' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                ], $tableOptions_mysql);
            }
        }

        if (!in_array('tasktemplaterepairpart', $tables))  {
            if ($dbType == "mysql") {
                $this->createTable('{{%tasktemplaterepairpart}}', [
                  '_id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT',
                  0 => 'PRIMARY KEY (`_id`)',
                  'uuid' => 'VARCHAR(50) NOT NULL',
                  'taskTemplateUuid' => 'VARCHAR(50) NOT NULL',
                  'repairPartUuid' => 'VARCHAR(50) NOT NULL',
                  'measureTypeUuid' => 'VARCHAR(50) NOT NULL',
                  'quantity' => 'INT(10) NOT NULL',
                  'createdAt' => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ',
                  'changedAt' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                ], $tableOptions_mysql);
            }
        }

        if (!in_array('taskrepairpart', $tables))  {
            if ($dbType == "mysql") {
                $this->createTable('{{%taskrepairpart}}', [
                  '_id' => 'INT(10) UNSIGNED NOT NULL AUTO_INCREMENT',
                  0 => 'PRIMARY KEY (`_id`)',
                  'uuid' => 'VARCHAR(50) NOT NULL',
                  'taskUuid' => 'VARCHAR(50) NOT NULL',
                  'repairPartUuid' => 'VARCHAR(50) NOT NULL',
                  'measureTypeUuid' => 'VARCHAR(50) NOT NULL',
                  'quantity' => 'INT(10) NOT NULL',
                  'createdAt' => 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ',
                  'changedAt' => 'TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\'',
                ], $tableOptions_mysql);
            }
        }

        /**
         * Унификация БД
         */

        // tasktemplate
        $this->renameColumn('tasktemplate', 'normativ', 'normative');
        // alerttype
        $this->alterColumn('alerttype', 'icon', 'VARCHAR(60)');
        // criticaltype
        $this->alterColumn('criticaltype', 'title', 'VARCHAR(100) NOT NULL');
        $this->alterColumn('criticaltype', 'icon', 'VARCHAR(60)');
        // documentation
        $this->alterColumn('documentation', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('documentation', 'equipmentUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('documentation', 'documentationTypeUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('documentation', 'path', 'VARCHAR(60)');
        $this->alterColumn('documentation', 'required', 'INT(10)');
        // documentationtype
        $this->alterColumn('documentationtype', 'icon', 'VARCHAR(60)');
        //  // equipment
        $this->alterColumn('equipment', 'image', 'VARCHAR(60)');
        $this->alterColumn('equipment', 'parentEquipment', 'VARCHAR(50)');
        // equipmentmodel
        $this->alterColumn('equipmentmodel', 'image', 'VARCHAR(60)');
        //  equipmentstatus
        $this->alterColumn('equipmentstatus', 'icon', 'VARCHAR(60)');
        // equipmenttype
        $this->alterColumn('equipmenttype', 'icon', 'VARCHAR(60)');
        // measuredvalue
        $this->alterColumn('measuredvalue', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('measuredvalue', 'equipmentUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('measuredvalue', 'equipmentUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('measuredvalue', 'value', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('measuredvalue', 'measureTypeUuid', 'VARCHAR(50) NOT NULL');
        // measuretype
        $this->alterColumn('measuretype', 'icon', 'VARCHAR(60)');
        // objects
        $this->alterColumn('objects', 'photo', 'VARCHAR(60)');
        // objecttype
        $this->alterColumn('objecttype', 'icon', 'VARCHAR(60)');
        // operation
        $this->alterColumn('operation', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operation', 'taskStageUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operation', 'operationVerdictUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operation', 'operationStatusUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operation', 'operationTemplateUuid', 'VARCHAR(50) NOT NULL');
        // operationstatus
        $this->alterColumn('operationstatus', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operationstatus', 'title', 'VARCHAR(100) NOT NULL');
        $this->alterColumn('operationstatus', 'icon', 'VARCHAR(60)');
        // operationtemplate
        $this->alterColumn('operationtemplate', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operationtemplate', 'title', 'VARCHAR(100) NOT NULL');
        $this->alterColumn('operationtemplate', 'image', 'VARCHAR(60)');
        $this->alterColumn('operationtemplate', 'equipmentModelUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operationtemplate', 'operationTypeUuid', 'VARCHAR(50) NOT NULL');
        // operationtool
        $this->alterColumn('operationtool', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operationtool', 'operationTemplateUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operationtool', 'toolsUuid', 'VARCHAR(50) NOT NULL');
        // operationtype
        $this->alterColumn('operationtype', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operationtype', 'title', 'VARCHAR(100) NOT NULL');
        $this->alterColumn('operationtype', 'icon', 'VARCHAR(60)');
        // operationverdict
        $this->alterColumn('operationverdict', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('operationverdict', 'title', 'VARCHAR(100) NOT NULL');
        $this->alterColumn('operationverdict', 'icon', 'VARCHAR(60)');
        // orderlevel
        $this->alterColumn('orderlevel', 'icon', 'VARCHAR(60)');
        // orders
        $this->alterColumn('orders', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('orders', 'authorUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('orders', 'userUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('orders', 'orderStatusUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('orders', 'orderVerdictUuid', 'VARCHAR(50) NOT NULL');
        // orderstatus
        $this->alterColumn('orderstatus', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('orderstatus', 'icon', 'VARCHAR(60)');
        // orderverdict
        $this->alterColumn('orderverdict', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('orderverdict', 'icon', 'VARCHAR(60)');
        // repairpart
        $this->alterColumn('repairpart', 'equipmentModelUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('repairpart', 'repairPartTypeUuid', 'VARCHAR(50) NOT NULL');
        // repairparttype
        $this->alterColumn('repairparttype', 'parentRepairTypeUuid', 'VARCHAR(50) NOT NULL');
        // stagerepairpart
        $this->alterColumn('stagerepairpart', 'repairPartUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('stagerepairpart', 'stagePatternUuid', 'VARCHAR(50) NOT NULL');
        // task
        $this->alterColumn('task', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('task', 'orderUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('task', 'equipmentUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('task', 'taskVerdictUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('task', 'taskStatusUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('task', 'taskTemplateUuid', 'VARCHAR(50) NOT NULL');
        // taskstage
        $this->alterColumn('taskstage', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstage', 'taskUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstage', 'equipmentUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstage', 'taskStageStatusUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstage', 'taskStageVerdictUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstage', 'taskStageTemplateUuid', 'VARCHAR(50) NOT NULL');
        // taskstagelist
        $this->alterColumn('taskstagelist', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstagelist', 'taskTemplateUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstagelist', 'taskStageTemplateUuid', 'VARCHAR(50) NOT NULL');
        // taskstageoperationlist
        $this->alterColumn('taskstageoperationlist', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstageoperationlist', 'taskStageTemplateUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstageoperationlist', 'operationTemplateUuid', 'VARCHAR(50) NOT NULL');
        // taskstagestatus
        $this->alterColumn('taskstagestatus', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstagestatus', 'icon', 'VARCHAR(60)');
        // taskstagetemplate
        $this->alterColumn('taskstagetemplate', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstagetemplate', 'image', 'VARCHAR(60)');
        $this->alterColumn('taskstagetemplate', 'taskStageTypeUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstagetemplate', 'equipmentModelUuid', 'VARCHAR(50) NOT NULL');
        // taskstagetype
        $this->alterColumn('taskstagetype', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstagetype', 'icon', 'VARCHAR(60)');
        // taskstageverdict
        $this->alterColumn('taskstageverdict', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstageverdict', 'taskStageTypeUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstageverdict', 'icon', 'VARCHAR(60)');
        // taskstatus
        $this->alterColumn('taskstatus', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskstatus', 'icon', 'VARCHAR(60)');
        // tasktemplate
        $this->alterColumn('tasktemplate', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('tasktemplate', 'equipmentModelUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('tasktemplate', 'taskTypeUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('tasktemplate', 'image', 'VARCHAR(60)');
        // tasktype
        $this->alterColumn('tasktype', 'uuid', 'VARCHAR(50) NOT NULL');
        // taskverdict
        $this->alterColumn('taskverdict', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskverdict', 'taskTypeUuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('taskverdict', 'icon', 'VARCHAR(60)');
        // tool
        $this->alterColumn('tool', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('tool', 'toolTypeUuid', 'VARCHAR(50) NOT NULL');
        // tooltype
        $this->alterColumn('tooltype', 'uuid', 'VARCHAR(50) NOT NULL');
        $this->alterColumn('tooltype', 'parentUuid', 'VARCHAR(50) NOT NULL');

    }

    public function saveDown()
    {
        /**
         * Обратные корректировки структуры базы данных
         * @var [type]
         */

        $this->renameColumn('tasktemplate','normative','normativ');
        $this->dropTable('brigade');
        $this->dropTable('contragentuser');
        $this->dropTable('brigadeuser');
        $this->dropTable('defecttype');
        $this->dropTable('defect');
        $this->dropTable('tasktemplaterepairpart');
        $this->dropTable('taskrepairpart');

        $this->dropColumn('contragent', 'contragentType');
        $this->dropColumn('contragent', 'parentContragent');
        $this->dropColumn('contragent', 'address');
        $this->dropColumn('contragent', 'photo');
        $this->dropColumn('contragent', 'longitude');
        $this->dropColumn('contragent', 'latitude');
        $this->dropColumn('orders', 'customerUuid');
        $this->dropColumn('orders', 'perpetratorUuid');
        $this->dropColumn('operationtool', 'quantity');
        $this->dropColumn('orders', 'comment');
        $this->dropColumn('operation', 'comment');

        $this->renameTable('contragent', 'clients');
    }
}


text:
$moduleName = 'Lability';
$repoRoot = (Resolve-Path "$PSScriptRoot\..\..\..\..").Path;
Import-Module (Join-Path -Path $RepoRoot -ChildPath "$moduleName.psm1") -Force;

Describe 'Unit\Src\Public\Remove-LabVM' {

    InModuleScope -ModuleName $moduleName {

        ## Guard mocks
        Mock Restore-Lab -MockWith { }
        Mock Remove-LabVirtualMachine -MockWith { }

        It 'Removes existing virtual machine' {
            $testVMName = 'TestVM';
            Mock Resolve-LabVMImage -MockWith { 'TestVMImageId'; }

            Remove-LabVM -Name $testVMName -Confirm:$false;

            Assert-MockCalled Remove-LabVirtualMachine -ParameterFilter { $Name -eq $testVMName } -Scope It;
        }

    } #end InModuleScope

} #end describe

redpajama_set_name: RedPajamaGithub


text:
// Schemas:
// *Party:
// {
//  name: String,
//  description: String,
//  genre: String,
//  id: int (auto increments),
//  nowPlaying:song,
//  songs: [song],
//  guests: [Int(clientId)]
// }
//
// *song:
// {
//  title: String,
//  username: String,
//  atwork: String,
//  votes: Int
// }
//
// *client
// {
//   ws_id: int,
//   partyId: int,
//   songsVotedFor: [song]
// }
//

module.exports = function(app, wss){
  var http = require('http');
  var fs = require('fs');
  var _ = require('lodash');
  var Levenshtein = require('levenshtein');

  var ws_connections = []; // Array of ws_connections
  var clients = [];        // Array of client data
  var parties = [];        // Array of parties

  app.get("/", function(req, res){
    fs.readFile(__dirname + '/../public/index.html',function (err, data){
      if(err){
        console.log('Error loading index.html: ' + err);
      }
      res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
      res.write(data);
      res.end();
    });
  });

  // Get list of parties
  app.get('/parties', function(req, res){
    console.log('GET "/"');
    var openParties = [];
    var party, _i, _len;

    for (_i = 0, _len = parties.length; _i < _len; _i++) {
      party = parties[_i];
      if(party){
        openParties.push(party);
      }
    }
    res.send({parties:openParties});
  });

  // Host a party
  app.post('/host', function(req, res){
    console.log('POST "/host"');
    party = req.body;
    party.id = parties.length;
    party.songs = [];
    party.clients = [];
    party.nowPlaying = undefined;

    parties.push(party);
    res.send({partyId:party.id});
  });

  // Get details for a party
  app.get('/party/:id', function(req, res){
    console.log('GET "/party/:id"');
    var partyId = parseInt(req.params.id);
    res.send(getParty(partyId));
  });

  // Post to this route if you've added a song
  app.post('/party/:id/addSongs', function(req, res){
    console.log('POST "/party/:id/addSongs"');
    var song, _i, _len;

    var songs = req.body.songs;
    var partyId = parseInt(req.params.id);
    var party = getParty(partyId);

    for (_i = 0, _len = songs.length; _i < _len; _i++) {
      song = songs[_i];
      song.votes = parseInt(song.votes);
      party.songs.push(song);
    }
    party.songs.sort(compareSongs);

    if(party.nowPlaying === undefined){
      playNextSong(party);
    }

    updateClients(party);
    res.send({status:'success'});
  });

  app.post('/party/:id/handleVote', function(req, res){
    console.log('POST "/party/:id/handleVote');
    var partyId = parseInt(req.params.id);
    var party = getParty(partyId);
    var body = req.body;

    var song, _i, _len;
    for (_i = 0, _len = party.songs.length; _i < _len; _i++) {
      song = party.songs[_i];
      if(body.songId === song.id){
        // console.log('votes: ' + song.votes);
        song.votes += parseInt(body.voteChange);
        party.songs.sort(compareSongs);
        updateClients(party);
        res.send({status:'success'});
      }
      else{
        res.send({status:'failure', msg:'Couldn\'t find song in party...'});
      }
    }
  });

  app.post('/party/:id/skipSong', function(req,res){
    console.log('POST "/party/:id/skipSong');
    var partyId = parseInt(req.params.id);
    var party = getParty(partyId);
    playNextSong(party);
    updateClients(party);
    res.send({status:'success'});
  });

  app.post('/findParty', function(req, res) {
    var body = req.body;
    console.dir(body);
    console.dir(parties);
    var matchedParties = _.filter(parties, function(party) {
      party.d = (new Levenshtein('test', party.name)).distance;
      return party.d < 8;
    });
    matchedParties.sort(function(a, b) { return a.d < b.d; });
    console.dir(matchedParties);
    res.send({parties: matchedParties});
  });

  /************************** Helper functions... ********************/
  function getParty(partyId){
    console.dir('Looking for party with id: ' + partyId);
    var party, _i, _len;
    for (_i = 0, _len = parties.length; _i < _len; _i++) {
      party = parties[_i];
      if(party !== undefined && party.id === partyId){
        return party;
      }
    }
  }
  // Compare two songs to swee which has more votes
  function compareSongs(a,b){
    return (a.votes >= b.votes) ? -1 : 1;
  }
  // Update current song and upcomign songs
  function playNextSong(party){
    party.nowPlaying = party.songs.shift();
  }

  /************************** End of Helpers... ********************/
  /************************** WS Shit... ********************/
  wss.on('connection', function(ws) {
    var client = {
      ws: ws,
      partyId: -1,
      songsVotedFor: []
    };
    var inParty = false; // Are they in a party and need to be taken out of...
    var id = clients.push(client) - 1;
    var pong = true;
    client.id = id;
    console.log("client connection: " + id);
    // Timeout to ack so that ws doesnt close
    setTimeout(function(){
      if(!(ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING)){
        ws.send(JSON.stringify({id:id}));
      }
    }, 1000);

    var interval = setInterval(function(){
      if(!pong){
        if(interval){
          clearInterval(interval);
        }
        if(!(ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING)){
          ws.close();
        }
      }
      else{
        ws.send(JSON.stringify({ping:true}));
        pong = false;
      }
    }, 7500);

    ws.on('message', function(msg) {
      msg = JSON.parse(msg);
      // console.dir(msg);
      if(msg.pong !== void 0){
        pong = true;
      }
      if(msg.joined !== void 0){
        // console.dir(parties);
        clients[id].partyId = msg.joined;
        parties[msg.joined].clients.push(id);
        inParty = true;
      }
    });
    ws.on('close', function() {
      if(interval){
        clearInterval(interval);
      }
      // Take client out of party...
      if(inParty){
        var index = parties[clients[id].partyId].clients.indexOf(id);
        if (index > -1) {
            parties[clients[id].partyId].clients.splice(index, 1);
            // console.dir(parties);
            if(parties[clients[id].partyId].clients.length === 0){
              parties[clients[id].partyId] = undefined;
            }
        }
      }
      clients[id] = undefined;
      console.log('client disconnected: ' + id);
    });
  });

  function updateClients(party){
    // console.dir(party);
    var client, _i, _len;
    for (_i = 0, _len = party.clients.length; _i < _len; _i++) {
      client = clients[party.clients[_i]];
      client.ws.send(JSON.stringify({party:party}));
    }
  }
  /************************** WS Shit ends ********************/
}


text:
<!DOCTYPE html>

{% load browserid %}
{% load staticfiles %}

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width">

		<title>{% block title %}Home{% endblock %} - MoonBizGame</title>
		<link rel="stylesheet" href="{% static 'css/main.css' %}">

		{% block extrahead %}
		{% endblock %}

	{% browserid_info %}

MoonBizGame

	        {% if user.is_authenticated %}
	          {% browserid_logout text='Logout' %}
	        {% else %}
	          {% browserid_login text='Login' %}
	        {% endif %}

	    Home Credits

		{% block content %}
		{% endblock %}

© 2013 Begg Digital. Released under BSD license, source code on
		    	GitHub. A
		    	Begg Digital site.

		{% browserid_js %}


text: Provides few extra tools that are missing in Android Studio/Eclipse Android IDEs.


text:
Network input
-------------

.. automodule:: mlbase.layers.rawinput

.. currentmodule:: mlbase.layers

.. autoclass:: RawInput
   :members:


text:
<?php

defined('PHPFOX') or exit('NO DICE!');

?>
{if !PHPFOX_IS_AJAX_PAGE}
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN"
"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">

		<title>{title}</title>
		{header}

		{plugin call='theme_template_body__start'}
		{if Phpfox::getParam('core.site_is_offline') && Phpfox::getUserParam('core.can_view_site_offline')}

				{phrase var='core.the_site_is_currently_in_offline_mode'}

		{/if}

				{if Phpfox::getParam('core.site_is_offline') && !Phpfox::getUserParam('core.can_view_site_offline')}
				{else}
				Home
				{if Phpfox::isUser()}

0

{phrase var='mobile.notifications'}

				{/if}
				{/if}
				{param var='core.site_title'}

			{if Phpfox::getParam('core.site_is_offline') && !Phpfox::getUserParam('core.can_view_site_offline')}
			{else}
			{if Phpfox::isUser()}

							<form method="post" id='header_search_form' action="{url link='search'}">
								<input type="text" name="q" value="{phrase var='core.mobile_search'}" id="header_sub_menu_search_input" autocomplete="off" class="js_temp_friend_search_input" />

								{phrase var='core.search'}
							</form>

			{/if}
			{/if}

				{/if}
						{if isset($aFilterMenus) && is_array($aFilterMenus) && count($aFilterMenus)}
						Menu

							{foreach from=$aFilterMenus name=filtermenu item=aFilterMenu}
								{if !isset($aFilterMenu.name)}

								{else}

{$aFilterMenu.name}

								{/if}
							{/foreach}

						{/if}

					{breadcrumb}
					{if isset($aBreadCrumbTitle) && count($aBreadCrumbTitle)}

{$aBreadCrumbTitle[0]|clean}

					{/if}

						{search}

							{error}
							{if Phpfox::isUser()
							|| (!Phpfox::isUser() && Phpfox::getLib('module')->getFullControllerName() == 'user.register')
							|| (!Phpfox::isUser() && Phpfox::getLib('module')->getFullControllerName() == 'user.login')
							|| (!Phpfox::isUser() && Phpfox::getLib('module')->getFullControllerName() == 'user.password/request')
							}
							{if defined('PHPFOX_IS_USER_PROFILE')}
							{module name='profile.mobile'}
							{/if}
							{block location='2'}
							{content}
							{block location='4'}
							{else}
							{module name='user.login-block'}
							{/if}

				{if !PHPFOX_IS_AJAX_PAGE}

{phrase var='mobile.full_site'}

·

{$sLocaleName}

					{if Phpfox::isUser()}

·

{phrase var='mobile.logout'}

					{/if}

{/if}


text:
"""
Forward Simulation of Gradiometry Data for Magnetic Vector Models
=================================================================

Here we use the module *SimPEG.potential_fields.magnetics* to predict magnetic
gradiometry data for magnetic vector models. The simulation is performed on a
Tree mesh. For this tutorial, we focus on the following:

    - How to define the survey when we want to measured multiple field components
    - How to predict magnetic data in the case of remanence
    - How to include surface topography
    - How to construct tree meshes based on topography and survey geometry
    - The units of the physical property model and resulting data

"""

#########################################################################
# Import Modules
# --------------
#

import numpy as np
from scipy.interpolate import LinearNDInterpolator
import matplotlib as mpl
import matplotlib.pyplot as plt

from discretize import TreeMesh
from discretize.utils import mkvc, refine_tree_xyz
from SimPEG.utils import plot2Ddata, model_builder, surface2ind_topo, mat_utils
from SimPEG import maps
from SimPEG.potential_fields import magnetics

# sphinx_gallery_thumbnail_number = 2

#############################################
# Topography
# ----------
#
# Here we define surface topography as an (N, 3) numpy array. Topography could
# also be loaded from a file.
#

[x_topo, y_topo] = np.meshgrid(np.linspace(-200, 200, 41), np.linspace(-200, 200, 41))
z_topo = -15 * np.exp(-(x_topo ** 2 + y_topo ** 2) / 80 ** 2)
x_topo, y_topo, z_topo = mkvc(x_topo), mkvc(y_topo), mkvc(z_topo)
xyz_topo = np.c_[x_topo, y_topo, z_topo]

#############################################
# Defining the Survey
# -------------------
#
# Here, we define survey that will be used for the simulation. Magnetic
# surveys are simple to create. The user only needs an (N, 3) array to define
# the xyz locations of the observation locations, the list of field components
# which are to be modeled and the properties of the Earth's field.
#

# Define the observation locations as an (N, 3) numpy array or load them.
x = np.linspace(-80.0, 80.0, 17)
y = np.linspace(-80.0, 80.0, 17)
x, y = np.meshgrid(x, y)
x, y = mkvc(x.T), mkvc(y.T)
fun_interp = LinearNDInterpolator(np.c_[x_topo, y_topo], z_topo)
z = fun_interp(np.c_[x, y]) + 10  # Flight height 10 m above surface.
receiver_locations = np.c_[x, y, z]

# Define the component(s) of the field we want to simulate as strings within
# a list. Here we measure the x, y and z derivatives of the Bz anomaly at
# each observation location.
components = ["bxz", "byz", "bzz"]

# Use the observation locations and components to define the receivers. To
# simulate data, the receivers must be defined as a list.
receiver_list = magnetics.receivers.Point(receiver_locations, components=components)

receiver_list = [receiver_list]

# Define the inducing field H0 = (intensity [nT], inclination [deg], declination [deg])
field_inclination = 60
field_declination = 30
field_strength = 50000
inducing_field = (field_strength, field_inclination, field_declination)

source_field = magnetics.sources.SourceField(
    receiver_list=receiver_list, parameters=inducing_field
)

# Define the survey
survey = magnetics.survey.Survey(source_field)

##########################################################
# Defining an OcTree Mesh
# -----------------------
#
# Here, we create the OcTree mesh that will be used to predict magnetic
# gradiometry data for the forward simuulation.
#

dx = 5  # minimum cell width (base mesh cell width) in x
dy = 5  # minimum cell width (base mesh cell width) in y
dz = 5  # minimum cell width (base mesh cell width) in z

x_length = 240.0  # domain width in x
y_length = 240.0  # domain width in y
z_length = 120.0  # domain width in y

# Compute number of base mesh cells required in x and y
nbcx = 2 ** int(np.round(np.log(x_length / dx) / np.log(2.0)))
nbcy = 2 ** int(np.round(np.log(y_length / dy) / np.log(2.0)))
nbcz = 2 ** int(np.round(np.log(z_length / dz) / np.log(2.0)))

# Define the base mesh
hx = [(dx, nbcx)]
hy = [(dy, nbcy)]
hz = [(dz, nbcz)]
mesh = TreeMesh([hx, hy, hz], x0="CCN")

# Refine based on surface topography
mesh = refine_tree_xyz(
    mesh, xyz_topo, octree_levels=[2, 2], method="surface", finalize=False
)

# Refine box base on region of interest
xp, yp, zp = np.meshgrid([-100.0, 100.0], [-100.0, 100.0], [-80.0, 0.0])
xyz = np.c_[mkvc(xp), mkvc(yp), mkvc(zp)]

mesh = refine_tree_xyz(mesh, xyz, octree_levels=[2, 2], method="box", finalize=False)

mesh.finalize()

##########################################################
# Create Magnetic Vector Intensity Model (MVI)
# --------------------------------------------
#
# Magnetic vector models are defined by three-component effective
# susceptibilities. To create a magnetic vector
# model, we must
#
#     1) Define the magnetic susceptibility for each cell. Then multiply by the
#     unit vector direction of the inducing field. (induced contribution)
#     2) Define the remanent magnetization vector for each cell and normalize
#     by the magnitude of the Earth's field (remanent contribution)
#     3) Sum the induced and remanent contributions
#     4) Define as a vector np.r_[chi_1, chi_2, chi_3]
#
#

# Define susceptibility values for each unit in SI
background_susceptibility = 0.0001
sphere_susceptibility = 0.01

# Find cells active in the forward modeling (cells below surface)
ind_active = surface2ind_topo(mesh, xyz_topo)

# Define mapping from model to active cells
nC = int(ind_active.sum())
model_map = maps.IdentityMap(nP=3 * nC)  # model has 3 parameters for each cell

# Define susceptibility for each cell
susceptibility_model = background_susceptibility * np.ones(ind_active.sum())
ind_sphere = model_builder.getIndicesSphere(np.r_[0.0, 0.0, -45.0], 15.0, mesh.gridCC)
ind_sphere = ind_sphere[ind_active]
susceptibility_model[ind_sphere] = sphere_susceptibility

# Compute the unit direction of the inducing field in Cartesian coordinates
field_direction = mat_utils.dip_azimuth2cartesian(field_inclination, field_declination)

# Multiply susceptibility model to obtain the x, y, z components of the
# effective susceptibility contribution from induced magnetization.
susceptibility_model = np.outer(susceptibility_model, field_direction)

# Define the effective susceptibility contribution for remanent magnetization to have a
# magnitude of 0.006 SI, with inclination -45 and declination 90
remanence_inclination = -45.0
remanence_declination = 90.0
remanence_susceptibility = 0.01

remanence_model = np.zeros(np.shape(susceptibility_model))
effective_susceptibility_sphere = (
    remanence_susceptibility
    * mat_utils.dip_azimuth2cartesian(remanence_inclination, remanence_declination)
)
remanence_model[ind_sphere, :] = effective_susceptibility_sphere

# Define effective susceptibility model as a vector np.r_[chi_x, chi_y, chi_z]
plotting_model = susceptibility_model + remanence_model
model = mkvc(plotting_model)

# Plot Effective Susceptibility Model
fig = plt.figure(figsize=(9, 4))

plotting_map = maps.InjectActiveCells(mesh, ind_active, np.nan)
plotting_model = np.sqrt(np.sum(plotting_model, axis=1) ** 2)
ax1 = fig.add_axes([0.1, 0.12, 0.73, 0.78])
mesh.plot_slice(
    plotting_map * plotting_model,
    normal="Y",
    ax=ax1,
    ind=int(mesh.h[1].size / 2),
    grid=True,
    clim=(np.min(plotting_model), np.max(plotting_model)),
)
ax1.set_title("MVI Model at y = 0 m")
ax1.set_xlabel("x (m)")
ax1.set_ylabel("z (m)")

ax2 = fig.add_axes([0.85, 0.12, 0.05, 0.78])
norm = mpl.colors.Normalize(vmin=np.min(plotting_model), vmax=np.max(plotting_model))
cbar = mpl.colorbar.ColorbarBase(ax2, norm=norm, orientation="vertical")
cbar.set_label(
    "Effective Susceptibility Amplitude (SI)", rotation=270, labelpad=15, size=12
)

###################################################################
# Simulation: Gradiometry Data for an MVI Model
# ---------------------------------------------
#
# Here we predict magnetic gradiometry data for an effective susceptibility model
# in the case of remanent magnetization.
#

# Define the forward simulation. By setting the 'store_sensitivities' keyword
# argument to "forward_only", we simulate the data without storing the sensitivities
simulation = magnetics.simulation.Simulation3DIntegral(
    survey=survey,
    mesh=mesh,
    chiMap=model_map,
    ind_active=ind_active,
    model_type="vector",
    store_sensitivities="forward_only",
)

# Compute predicted data for some model
dpred = simulation.dpred(model)
n_data = len(dpred)

# Plot
fig = plt.figure(figsize=(13, 4))
v_max = np.max(np.abs(dpred))

ax1 = fig.add_axes([0.1, 0.15, 0.25, 0.78])
plot2Ddata(
    receiver_list[0].locations,
    dpred[0:n_data:3],
    ax=ax1,
    ncontour=30,
    clim=(-v_max, v_max),
    contourOpts={"cmap": "bwr"},
)
ax1.set_title("$dBz/dx$")
ax1.set_xlabel("x (m)")
ax1.set_ylabel("y (m)")

ax2 = fig.add_axes([0.36, 0.15, 0.25, 0.78])
cplot2 = plot2Ddata(
    receiver_list[0].locations,
    dpred[1:n_data:3],
    ax=ax2,
    ncontour=30,
    clim=(-v_max, v_max),
    contourOpts={"cmap": "bwr"},
)
cplot2[0].set_clim((-v_max, v_max))
ax2.set_title("$dBz/dy$")
ax2.set_xlabel("x (m)")
ax2.set_yticks([])

ax3 = fig.add_axes([0.62, 0.15, 0.25, 0.78])
cplot3 = plot2Ddata(
    receiver_list[0].locations,
    dpred[2:n_data:3],
    ax=ax3,
    ncontour=30,
    clim=(-v_max, v_max),
    contourOpts={"cmap": "bwr"},
)
cplot3[0].set_clim((-v_max, v_max))
ax3.set_title("$dBz/dz$")
ax3.set_xlabel("x (m)")
ax3.set_yticks([])

ax4 = fig.add_axes([0.88, 0.15, 0.02, 0.79])
norm = mpl.colors.Normalize(vmin=-v_max, vmax=v_max)
cbar = mpl.colorbar.ColorbarBase(
    ax4, norm=norm, orientation="vertical", cmap=mpl.cm.bwr
)
cbar.set_label("$nT/m$", rotation=270, labelpad=15, size=12)

plt.show()


text:
    客服{%this.cid%} - {%this.name%}

...


text:
package net.maizegenetics.phenotype;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.maizegenetics.taxa.TaxaList;
import net.maizegenetics.taxa.TaxaListBuilder;
import net.maizegenetics.taxa.TaxaListUtils;
import net.maizegenetics.taxa.Taxon;

public class FilterPhenotype extends Phenotype {
	private Phenotype basePhenotype;
	private boolean myIsTaxaFilter = false;
	private boolean myIsAttributeFilter = false;
	private int[] myTaxaRedirect = null;
	private int[] myAttributeRedirect = null;
	Map<ATTRIBUTE_TYPE, int[]> myAttributeTypeRedirect = null;
	private String myTableTitle = "Filtered phenotype";

	private FilterPhenotype(Phenotype basePheno, ArrayList<PhenotypeAttribute> retainedAttributes, TaxaList taxaToRetain) {
		basePhenotype = basePheno;

		if (taxaToRetain != null) {
			myIsTaxaFilter = true;
			TaxaList commonTaxa = TaxaListUtils.getCommonTaxa(basePhenotype.taxa(), taxaToRetain);
			int ntaxa = commonTaxa.size();
			myTaxaRedirect = new int[ntaxa];
			int tcount = 0;
			for (Taxon taxon : commonTaxa) {
				myTaxaRedirect[tcount++] = basePhenotype.taxa().indexOf(taxon);
			}
		}

		if (retainedAttributes != null) {
			myIsAttributeFilter = true;
			int nAttr = retainedAttributes.size();
			myAttributeRedirect = new int[nAttr];
			int acount = 0;
			for (PhenotypeAttribute attr : retainedAttributes) {
				myAttributeRedirect[acount++] = basePhenotype.getAttributeList().indexOf(attr);
			}
		}
	}

	public static Phenotype getInstance(Phenotype basePheno, ArrayList<PhenotypeAttribute> retainedAttributes, TaxaList taxaToRetain) {
		return new FilterPhenotype(basePheno, retainedAttributes, taxaToRetain);
	}

	public static Phenotype getInstance(Phenotype basePheno, ArrayList<PhenotypeAttribute> retainedAttributes) {
		return new FilterPhenotype(basePheno, retainedAttributes, null);
	}

	public static Phenotype getInstance(Phenotype basePheno, TaxaList retainedTaxa) {
		return new FilterPhenotype(basePheno, null, retainedTaxa);
	}

	public static Phenotype getInstanceRemoveTaxa(Phenotype basePheno, TaxaList taxaToRemove) {
		ArrayList<Taxon> keepList = new ArrayList<Taxon>(basePheno.taxa());
		keepList.removeAll(taxaToRemove);
		TaxaListBuilder taxaBuilder = new TaxaListBuilder();
		taxaBuilder.addAll(keepList);
		return new FilterPhenotype(basePheno, null, taxaBuilder.build());
	}

	//methods to override ------------------------------------
	@Override
	public Object getValue(int obs, int attrnum) {
		if (myIsTaxaFilter && myIsAttributeFilter) {
			return basePhenotype.getValue(myTaxaRedirect[obs], myAttributeRedirect[attrnum]);
		} else if (myIsAttributeFilter) {
			return basePhenotype.getValue(obs, myAttributeRedirect[attrnum]);
		} else {
			return basePhenotype.getValue(myTaxaRedirect[obs], attrnum);
		}
	}

	@Override
	public PhenotypeAttribute getAttribute(int attrnum) {
		if (myIsAttributeFilter) {
			return basePhenotype.getAttribute(myAttributeRedirect[attrnum]);
		} else return super.getAttribute(attrnum);
	}

	@Override
	public PhenotypeAttribute getAttributeOfType(ATTRIBUTE_TYPE type, int attrnum) {
		if (myIsAttributeFilter) {
			return basePhenotype.getAttribute(myAttributeTypeRedirect.get(type)[attrnum]);
		} else {
			return basePhenotype.getAttributeOfType(type, attrnum);
		}
	}

	@Override
	public List<PhenotypeAttribute> getAttributeListOfType(ATTRIBUTE_TYPE type) {
		if (myIsAttributeFilter) {
			ArrayList<PhenotypeAttribute> attrList = new ArrayList<PhenotypeAttribute>();
			for (int attrnum : myAttributeTypeRedirect.get(type)) attrList.add(super.getAttribute(attrnum));
			return attrList;
		} else {
			return basePhenotype.getAttributeListOfType(type);
		}

	}

	@Override
	public TaxaList taxa() {
		if (myIsTaxaFilter) {
			TaxaListBuilder taxaBuilder = new TaxaListBuilder();
			for (int t : myTaxaRedirect) taxaBuilder.add(basePhenotype.taxa().get(t));
			return taxaBuilder.build();
		} else {
			return basePhenotype.taxa();
		}
	}

	@Override
	public int getNumberOfAttributes() {
		if (myIsAttributeFilter) {
			return myAttributeRedirect.length;
		} else {
			return basePhenotype.getNumberOfAttributes();
		}
	}

	@Override
	public int getNumberOfAttributesOfType(ATTRIBUTE_TYPE type) {
		if (myIsAttributeFilter) {
			return myAttributeTypeRedirect.get(type).length;
		} else return basePhenotype.getNumberOfAttributesOfType(type);
	}

	@Override
	public int getNumberOfObservations() {
		if (myIsTaxaFilter) {
			return myTaxaRedirect.length;
		} else return basePhenotype.getNumberOfObservations();
	}

	@Override
	public Object[] getTableColumnNames() {
		if (myIsAttributeFilter) {
			int nAttr = myAttributeRedirect.length;
			Object[] names = new Object[nAttr];
			for (int a = 0; a < nAttr; a++) {
				names[a] = basePhenotype.getAttribute(a).getName();
			}
			return names;
		} else return basePhenotype.getTableColumnNames();
	}

	@Override
	public Object[][] getTableData() {
		int nrows = myTaxaRedirect.length;
		int ncols = myAttributeRedirect.length + 1;
		Object[][] resultTable = new Object[nrows][ncols];
		for (int r = 0; r < nrows; r++) {
			for (int c = 0; c < ncols; c++) {
				resultTable[r][c] = getValueAt(r,c);
			}
		}
		return resultTable;
	}

	@Override
	public String getTableTitle() {
		return myTableTitle;
	}

	@Override
	public int getColumnCount() {
		if (myIsAttributeFilter) return myAttributeRedirect.length + 1;
		else return basePhenotype.getColumnCount();
	}

	@Override
	public int getRowCount() {
		 if (myIsTaxaFilter) return myTaxaRedirect.length;
		 else return basePhenotype.getRowCount();
	}

	@Override
	public Object[] getRow(int row) {
		int ncols = getColumnCount();
		Object[] rowData = new Object[ncols];
		for (int i = 0; i < ncols; i++) rowData[i] = getValueAt(row, i);
		return super.getRow(row);
	}

	@Override
	public Object[][] getTableData(int start, int end) {
		int nrows = end - start + 1;
		int ncols = myAttributeRedirect.length + 1;
		Object[][] resultTable = new Object[nrows][ncols];
		for (int r = 0; r < nrows ; r++) {
			for (int c = 0; c < ncols; c++) {
				resultTable[r][c] = getValueAt(r + start,c);
			}
		}
		return resultTable;
	}

	@Override
	public Object getValueAt(int row, int col) {
		if (myIsTaxaFilter && myIsAttributeFilter) {
			if (col == 0) return basePhenotype.taxa().get(myTaxaRedirect[row]);
			return basePhenotype.getValue(myTaxaRedirect[row], myAttributeRedirect[col - 1]);
		} else if (myIsAttributeFilter) {
			if (col == 0) return basePhenotype.taxa().get(row);
			return basePhenotype.getValue(row, myAttributeRedirect[col - 1]);
		} else {
			if (col == 0) return basePhenotype.taxa().get(myTaxaRedirect[row]);
			return basePhenotype.getValue(myTaxaRedirect[row], col - 1);
		}
	}

}


text:
/**
 *
 */
package liquibase.ext.teradata.sqlgenerator;

import java.util.Iterator;

import liquibase.Scope;
import liquibase.database.Database;
import liquibase.datatype.DataTypeFactory;
import liquibase.datatype.LiquibaseDataType;
import liquibase.datatype.core.DateTimeType;
import liquibase.datatype.core.DateType;
import liquibase.datatype.core.TimeType;
import liquibase.ext.teradata.database.TeradataDatabase;
import liquibase.logging.LogFactory;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.core.CreateTableGenerator;
import liquibase.statement.AutoIncrementConstraint;
import liquibase.statement.ForeignKeyConstraint;
import liquibase.statement.UniqueConstraint;
import liquibase.statement.core.CreateTableStatement;
import liquibase.util.StringUtil;

/**
 * To handle Teradata specific syntax for default values
 *
 */
public class CreateTableGeneratorTeradata extends CreateTableGenerator {

	@Override
	public int getPriority() {
		return PRIORITY_DATABASE;
	}

	@Override
	public boolean supports(CreateTableStatement statement, Database database) {
		return database instanceof TeradataDatabase;
	}

	/**
	 * Modified to handle Teradata syntax for default values
	 *
	 * @see liquibase.sqlgenerator.core.CreateTableGenerator#generateSql(liquibase.statement.core.CreateTableStatement, liquibase.database.Database,
	 *      liquibase.sqlgenerator.SqlGeneratorChain)
	 */
	@Override
	public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
		StringBuilder buffer = new StringBuilder();
		buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()))
				.append(" ");
		buffer.append("(");
		Iterator<String> columnIterator = statement.getColumns().iterator();

		boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1;

		boolean isPrimaryKeyAutoIncrement = false;

		while (columnIterator.hasNext()) {
			String column = columnIterator.next();
			boolean isAutoIncrement = false;
			for (AutoIncrementConstraint constraint : statement.getAutoIncrementConstraints()) {
				if (constraint.getColumnName().equalsIgnoreCase(column)) {
					isAutoIncrement = true;
					break;
				}
			}

			buffer.append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column));
			buffer.append(" ").append(statement.getColumnTypes().get(column).toDatabaseDataType(database));

			if (statement.getDefaultValue(column) != null) {
				Object defaultValue = statement.getDefaultValue(column);
				buffer.append(" DEFAULT ");
				LiquibaseDataType defaultValueType = DataTypeFactory.getInstance().fromObject(defaultValue, database);
				buffer.append((defaultValueType instanceof DateTimeType ? " TIMESTAMP "
						: (defaultValueType instanceof DateType ? " DATE " : (defaultValueType instanceof TimeType ? " TIME " : ""))));

				buffer.append(defaultValueType.objectToSql(defaultValue, database));
			}

			if (isAutoIncrement && (database.getAutoIncrementClause(null, null, null, true) != null) && (!database.getAutoIncrementClause(null, null, null, true).equals(""))) {
				if (database.supportsAutoIncrement()) {
					buffer.append(" ").append(database.getAutoIncrementClause(null, null, null, true)).append(" ");
				} else {
					Scope.getCurrentScope().getLog(getClass()).warning(database.getShortName() + " does not support autoincrement columns as request for "
							+ (database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())));
				}
			}

			if (statement.getNotNullColumns().containsKey(column)) {
				buffer.append(" NOT NULL");
			}

			if (columnIterator.hasNext()) {
				buffer.append(", ");
			}
		}

		buffer.append(",");

		if (!(isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement)) {

			if (statement.getPrimaryKeyConstraint() != null && !statement.getPrimaryKeyConstraint().getColumns().isEmpty()) {
				if (database.supportsPrimaryKeyNames()) {
					String pkName = StringUtil.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
					if (pkName == null) {
						pkName = database.generatePrimaryKeyName(statement.getTableName());
					}
					if (pkName != null) {
						buffer.append(" CONSTRAINT ");
						buffer.append(database.escapeConstraintName(pkName));
					}
				}
				buffer.append(" PRIMARY KEY (");
				buffer.append(database.escapeColumnNameList(StringUtil.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
				buffer.append(")");

				buffer.append(",");
			}
		}

		for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
			buffer.append(" CONSTRAINT ");
			buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
			String referencesString = fkConstraint.getReferences();
			if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) {
				referencesString = database.getDefaultSchemaName() + "." + referencesString;
			}
			buffer.append(" FOREIGN KEY (").append(
					database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn()))
					.append(") REFERENCES ").append(referencesString);

			if (fkConstraint.isDeleteCascade()) {
				buffer.append(" ON DELETE CASCADE");
			}

			if (fkConstraint.isInitiallyDeferred()) {
				buffer.append(" INITIALLY DEFERRED");
			}
			if (fkConstraint.isDeferrable()) {
				buffer.append(" DEFERRABLE");
			}
			buffer.append(",");
		}

		for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
			if (uniqueConstraint.getConstraintName() != null) {
				buffer.append(" CONSTRAINT ");
				buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
			}
			buffer.append(" UNIQUE (");
			buffer.append(database.escapeColumnNameList(StringUtil.join(uniqueConstraint.getColumns(), ", ")));
			buffer.append(")");
			buffer.append(",");
		}

		String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";

		return new Sql[] { new UnparsedSql(sql) };
	}
}


text:
@interface MemetroOrgViewController ()

@end

@implementation MemetroOrgViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.asesoramiento.text = NSLocalizedString(@"Advice", @"");
    self.asesoramiento.superview.userInteractionEnabled = YES;
    [self.asesoramiento.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushasesoramiento)]];
    self.memetroles.text = NSLocalizedString(@"Memetrols", @"");
    self.memetroles.superview.userInteractionEnabled = YES;
    [self.memetroles.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushmemetroles)]];
    self.sintomas.text = NSLocalizedString(@"Symptoms", @"");
    self.sintomas.superview.userInteractionEnabled = YES;
    [self.sintomas.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushsintomas)]];
    self.asociarse.text = NSLocalizedString(@"Become associated", @"");
    self.asociarse.superview.userInteractionEnabled = YES;
    [self.asociarse.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushasociarse)]];
    self.contacto.text = NSLocalizedString(@"Contact", @"");
    self.contacto.superview.userInteractionEnabled =YES;
    [self.contacto.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushcontacto)]];
    self.trastorno.text = NSLocalizedString(@"Memetro disorder", @"");
    self.trastorno.superview.userInteractionEnabled = YES;
    [self.trastorno.superview addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushtrastorno)]];
}

-(void) pushasesoramiento{
    WebViewController *w = [[WebViewController alloc] init];
    w.url = [NSURL URLWithString:@"http://www.memetro.net/asesoramiento-legal/"];
    [self.navigationController pushViewController:w animated:YES];
}

-(void) pushmemetroles{
    WebViewController *w = [[WebViewController alloc] init];
    w.url = [NSURL URLWithString:@"http://www.memetro.net/memetroles/"];
    [self.navigationController pushViewController:w animated:YES];

}
-(void) pushsintomas{
    WebViewController *w = [[WebViewController alloc] init];
    w.url = [NSURL URLWithString:@"http://www.memetro.net/vivir-con-el-trastono/"];
    [self.navigationController pushViewController:w animated:YES];

}
-(void) pushasociarse{
    WebViewController *w = [[WebViewController alloc] init];
    w.url = [NSURL URLWithString:@"http://www.memetro.net/asociarse/"];
    [self.navigationController pushViewController:w animated:YES];

}
-(void) pushcontacto{
    WebViewController *w = [[WebViewController alloc] init];
    w.url = [NSURL URLWithString:@"http://www.memetro.net/contacto/"];
    [self.navigationController pushViewController:w animated:YES];

}
-(void) pushtrastorno{
    WebViewController *w = [[WebViewController alloc] init];
    w.url = [NSURL URLWithString:@"http://www.memetro.net/trastorno-memetro/"];
    [self.navigationController pushViewController:w animated:YES];

}

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

@end


text:
module PoroValidator
  module Validators
    class FloatValidator < NumericValidator
      def validate(attribute, value, options)
        return if value.nil?

        if is_numeric?(value.to_s, FLOAT_MATCHER)
          return
        end

        message = options[:message] || :float
        errors.add(attribute, message)
      end
    end
  end
end


text:
<?php

namespace Multiservices\InventarioBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Multiservices\InventarioBundle\Entity\Articulos;
use Multiservices\InventarioBundle\Form\ArticulosType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

/**
 * Articulos controller.
 *
 * @Route("/articulos")
 */
class ArticulosController extends Controller
{

    /**
     * Lists all Articulos entities.
     *
     * @Route("/", name="articulos")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MultiservicesInventarioBundle:Articulos')->findAll();
         foreach ($entities as $articulo)
                {
                   $equiposmac = $em->getRepository('MultiservicesInventarioBundle:ArticulosDetalle')->findByCodarticulo($articulo->getId());
            if (!$equiposmac)
            {
                $articulo->registrados=0;
                $articulo->libres=0;
                $articulo->ocupados=0;
                $articulo->danados=0;
            }else
                {
                $articulo->libres=0;
                 $articulo->ocupados=0;
                 $articulo->danados=0;
                $articulo->registrados=count($equiposmac);
                 foreach($equiposmac as $equipo)
                 {
                     if ($equipo->getEstatus()=="LIBRE")
                     {
                         $articulo->libres++;
                     }
                     if ($equipo->getEstatus()=="OCUPADO")
                     {
                         $articulo->ocupados++;
                     }
                     if ($equipo->getAntiguedad()=="DAÑADO")
                     {
                         $articulo->danados++;
                     }
                 }

                }
              }
        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Articulos entity.
     *
     * @Route("/", name="articulos_create")
     * @Method("POST")
     * @Template("MultiservicesInventarioBundle:Articulos:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Articulos();

        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity->setBorrado(0);
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('articulos_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Articulos entity.
     *
     * @param Articulos $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Articulos $entity)
    {
        $form = $this->createForm(ArticulosType::class, $entity, array(
            'action' => $this->generateUrl('articulos_create'),
            'method' => 'POST',
        ));

        $form->add('submit', SubmitType::class, array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Articulos entity.
     *
     * @Route("/new", name="articulos_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Articulos();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Articulos entity.
     *
     * @Route("/{id}", name="articulos_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MultiservicesInventarioBundle:Articulos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Articulos entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Finds and displays a Articulos entity.
     *
     * @Route("/{id}/ajaxgrid", name="articulos_showajaxgrid")
     * @Method("GET")
     *
     */
    public function ajaxgridAction($id)
    {
       $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MultiservicesInventarioBundle:Articulos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Articulos entity.');
        }

        $html = $this->renderView('MultiservicesInventarioBundle:Articulos:ajaxgrid.json.twig', array('entity'=> $entity));

        $response = new Response($html,Response::HTTP_OK,array('Content-Type'=>'application/json'));

        return $response;
    }

    /**
     * Displays a form to edit an existing Articulos entity.
     *
     * @Route("/{id}/edit", name="articulos_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MultiservicesInventarioBundle:Articulos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Articulos entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Articulos entity.
    *
    * @param Articulos $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Articulos $entity)
    {
        $form = $this->createForm(ArticulosType::class, $entity, array(
            'action' => $this->generateUrl('articulos_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', SubmitType::class, array('label' => 'Actualizar'));

        return $form;
    }
    /**
     * Edits an existing Articulos entity.
     *
     * @Route("/{id}", name="articulos_update")
     * @Method("PUT")
     * @Template("MultiservicesInventarioBundle:Articulos:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MultiservicesInventarioBundle:Articulos')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Articulos entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('articulos_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Articulos entity.
     *
     * @Route("/{id}", name="articulos_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MultiservicesInventarioBundle:Articulos')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Articulos entity.');
            }

            try{
            $em->remove($entity);
            $em->flush();
            }catch(\Exception $e){
                return new Response("Hay componentes relacionados con este registro, no se puede eliminar");
            }

        }

        return $this->redirect($this->generateUrl('articulos'));
    }

    /**
     * Creates a form to delete a Articulos entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('articulos_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', SubmitType::class, array('label' => 'Eliminar'))
            ->getForm()
        ;
    }

}


text:
package memmetrics

import (
	"fmt"
	"time"

	"github.com/HdrHistogram/hdrhistogram-go"
	"github.com/vulcand/oxy/v2/internal/holsterv4/clock"
)

// HDRHistogram is a tiny wrapper around github.com/HdrHistogram/hdrhistogram-go that provides convenience functions for measuring http latencies.
type HDRHistogram struct {
	// lowest trackable value
	low int64
	// highest trackable value
	high int64
	// significant figures
	sigfigs int

	h *hdrhistogram.Histogram
}

// NewHDRHistogram creates a new HDRHistogram.
func NewHDRHistogram(low, high int64, sigfigs int) (h *HDRHistogram, err error) {
	defer func() {
		if msg := recover(); msg != nil {
			err = fmt.Errorf("%s", msg)
		}
	}()
	return &HDRHistogram{
		low:     low,
		high:    high,
		sigfigs: sigfigs,
		h:       hdrhistogram.New(low, high, sigfigs),
	}, nil
}

// Export exports a HDRHistogram.
func (h *HDRHistogram) Export() *HDRHistogram {
	var hist *hdrhistogram.Histogram
	if h.h != nil {
		snapshot := h.h.Export()
		hist = hdrhistogram.Import(snapshot)
	}
	return &HDRHistogram{low: h.low, high: h.high, sigfigs: h.sigfigs, h: hist}
}

// LatencyAtQuantile sets latency at quantile with microsecond precision.
func (h *HDRHistogram) LatencyAtQuantile(q float64) time.Duration {
	return time.Duration(h.ValueAtQuantile(q)) * clock.Microsecond
}

// RecordLatencies Records latencies with microsecond precision.
func (h *HDRHistogram) RecordLatencies(d time.Duration, n int64) error {
	return h.RecordValues(int64(d/clock.Microsecond), n)
}

// Reset resets a HDRHistogram.
func (h *HDRHistogram) Reset() {
	h.h.Reset()
}

// ValueAtQuantile sets value at quantile.
func (h *HDRHistogram) ValueAtQuantile(q float64) int64 {
	return h.h.ValueAtQuantile(q)
}

// RecordValues sets record values.
func (h *HDRHistogram) RecordValues(v, n int64) error {
	return h.h.RecordValues(v, n)
}

// Merge merges a HDRHistogram.
func (h *HDRHistogram) Merge(other *HDRHistogram) error {
	if other == nil {
		return fmt.Errorf("other is nil")
	}
	h.h.Merge(other.h)
	return nil
}

type rhOption func(r *RollingHDRHistogram) error

// RollingHDRHistogram holds multiple histograms and rotates every period.
// It provides resulting histogram as a result of a call of 'Merged' function.
type RollingHDRHistogram struct {
	idx         int
	lastRoll    clock.Time
	period      time.Duration
	bucketCount int
	low         int64
	high        int64
	sigfigs     int
	buckets     []*HDRHistogram
}

// NewRollingHDRHistogram created a new RollingHDRHistogram.
func NewRollingHDRHistogram(low, high int64, sigfigs int, period time.Duration, bucketCount int, options ...rhOption) (*RollingHDRHistogram, error) {
	rh := &RollingHDRHistogram{
		bucketCount: bucketCount,
		period:      period,
		low:         low,
		high:        high,
		sigfigs:     sigfigs,
	}

	for _, o := range options {
		if err := o(rh); err != nil {
			return nil, err
		}
	}

	buckets := make([]*HDRHistogram, rh.bucketCount)
	for i := range buckets {
		h, err := NewHDRHistogram(low, high, sigfigs)
		if err != nil {
			return nil, err
		}
		buckets[i] = h
	}
	rh.buckets = buckets
	return rh, nil
}

// Export exports a RollingHDRHistogram.
func (r *RollingHDRHistogram) Export() *RollingHDRHistogram {
	export := &RollingHDRHistogram{}
	export.idx = r.idx
	export.lastRoll = r.lastRoll
	export.period = r.period
	export.bucketCount = r.bucketCount
	export.low = r.low
	export.high = r.high
	export.sigfigs = r.sigfigs

	exportBuckets := make([]*HDRHistogram, len(r.buckets))
	for i, hist := range r.buckets {
		exportBuckets[i] = hist.Export()
	}
	export.buckets = exportBuckets

	return export
}

// Append appends a RollingHDRHistogram.
func (r *RollingHDRHistogram) Append(o *RollingHDRHistogram) error {
	if r.bucketCount != o.bucketCount || r.period != o.period || r.low != o.low || r.high != o.high || r.sigfigs != o.sigfigs {
		return fmt.Errorf("can't merge")
	}

	for i := range r.buckets {
		if err := r.buckets[i].Merge(o.buckets[i]); err != nil {
			return err
		}
	}
	return nil
}

// Reset resets a RollingHDRHistogram.
func (r *RollingHDRHistogram) Reset() {
	r.idx = 0
	r.lastRoll = clock.Now().UTC()
	for _, b := range r.buckets {
		b.Reset()
	}
}

func (r *RollingHDRHistogram) rotate() {
	r.idx = (r.idx + 1) % len(r.buckets)
	r.buckets[r.idx].Reset()
}

// Merged gets merged histogram.
func (r *RollingHDRHistogram) Merged() (*HDRHistogram, error) {
	m, err := NewHDRHistogram(r.low, r.high, r.sigfigs)
	if err != nil {
		return m, err
	}
	for _, h := range r.buckets {
		if errMerge := m.Merge(h); errMerge != nil {
			return nil, errMerge
		}
	}
	return m, nil
}

func (r *RollingHDRHistogram) getHist() *HDRHistogram {
	if clock.Now().UTC().Sub(r.lastRoll) >= r.period {
		r.rotate()
		r.lastRoll = clock.Now().UTC()
	}
	return r.buckets[r.idx]
}

// RecordLatencies sets records latencies.
func (r *RollingHDRHistogram) RecordLatencies(v time.Duration, n int64) error {
	return r.getHist().RecordLatencies(v, n)
}

// RecordValues sets record values.
func (r *RollingHDRHistogram) RecordValues(v, n int64) error {
	return r.getHist().RecordValues(v, n)
}


text:
@implementation GameRepository

static GameRepository* singleton;
@synthesize gameSet = _gameSet;

- (void) commonInitSettings
{
    singleton = self;
}

- (instancetype) init
{
    if (singleton) return singleton;

    self = [super init];

    _gameSet = [[NSMutableSet alloc] init];

    [self commonInitSettings];

    return self;
}

- (instancetype) initWithCoder:(NSCoder *)decoder
{
    self = [super init];

    _gameSet = [decoder decodeObjectForKey:gameSetKey];

    [self commonInitSettings];

    return self;
}

- (void) encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:_gameSet forKey:gameSetKey];
}

+ (GameRepository *)sharedRepository
{
    if (!singleton) {
        singleton = [[self alloc] init];
    }

    return singleton;
}

- (void)addGame:(Game *)game
{
    if (!game) return;

    if (![_gameSet containsObject:game]){
        [_gameSet addObject:game];
    }
}

- (void)removeGame:(Game *)game
{
    if (!game) return;

    if ([_gameSet containsObject:game]){
        [_gameSet removeObject:game];
    }
}

- (NSDictionary<NSString *,Game *> *) gameSetAsDictionary
{
    NSMutableDictionary<NSString*, Game*> *dict;

    dict = [[NSMutableDictionary alloc]init];

    for (Game* game in _gameSet) {
        [dict setValue:game forKey:game.name];
    }

    return dict;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools" >

	<TextView
	    android:id="@+id/textView_editOrder_itemName"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="item Name"/>

	<TextView
	    android:id="@+id/textView_editOrder_itemPrice"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="item price"/>

	<NumberPicker
	    android:id="@+id/numberPicker_editOrder"
	    tools:targetApi="11"
	    android:layout_width="match_parent"
	    android:layout_height="match_parent"/>
</LinearLayout>


text:
package com.intellij.ui.content;

import com.intellij.openapi.project.Project;
import com.intellij.ui.content.impl.ContentImpl;
import com.intellij.ui.content.impl.DesktopContentManagerImpl;
import consulo.ui.Component;
import consulo.wm.impl.UnifiedContentImpl;
import jakarta.inject.Singleton;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

@Singleton
public class ContentFactoryImpl implements ContentFactory {
  @Nonnull
  @Override
  public ContentManager createContentManager(@Nonnull ContentUI contentUI, boolean canCloseContents, @Nonnull Project project) {
    return new DesktopContentManagerImpl(contentUI, canCloseContents, project);
  }

  @Nonnull
  @Override
  public ContentManager createContentManager(boolean canCloseContents, @Nonnull Project project) {
    return createContentManager(new TabbedPaneContentUI(), canCloseContents, project);
  }

  @Nonnull
  @Override
  public Content createUIContent(@Nullable Component component, String displayName, boolean isLockable) {
    return new UnifiedContentImpl(component, displayName, isLockable);
  }

  // TODO [VISTALL] AWT & Swing dependency
  // region AWT & Swing dependency
  @Nonnull
  @Override
  public ContentImpl createContent(javax.swing.JComponent component, String displayName, boolean isLockable) {
    return new ContentImpl(component, displayName, isLockable);
  }
  // endregion
}


text:
package gfxdperf.ycsb.gf;

import com.gemstone.gemfire.cache.GemFireCache;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.distributed.DistributedSystem;

import gfxdperf.PerfTestException;
import gfxdperf.ycsb.core.ByteIterator;
import gfxdperf.ycsb.core.ByteArrayByteIterator;
import gfxdperf.ycsb.core.DB;
import gfxdperf.ycsb.core.DBException;
import gfxdperf.ycsb.core.workloads.CoreWorkloadPrms;
import gfxdperf.ycsb.core.workloads.CoreWorkloadStats;

import hydra.CacheHelper;
import hydra.ConfigPrms;
import hydra.DistributedSystemHelper;
import hydra.Log;
import hydra.RegionHelper;

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

/**
 * Client for measuring YCSB performance with GemFire.
 * <p>
 * This class expects a schema <key> <field1> <field2> <field3> ...
 * All attributes are of type VARCHAR. All accesses are through the primary key.
 */
public class GFDB extends DB {

  public static final boolean logOps = GFPrms.logOps();

  /** Prefix for each column in the table */
  public static String COLUMN_PREFIX = "field";

  /** Primary key column in the table */
  public static final String PRIMARY_KEY = "YCSB_KEY";

  private GemFireCache cache;
  private DistributedSystem distributedSystem;
  private CoreWorkloadStats statistics;

  @Override
  public void init() throws DBException {
    this.distributedSystem = DistributedSystemHelper.getDistributedSystem();
    this.cache = CacheHelper.createCache(ConfigPrms.getCacheConfig());
    this.statistics = CoreWorkloadStats.getInstance();
  }

  @Override
  public void cleanup() throws DBException {
    if (this.statistics != null) {
      this.statistics.close();
      this.statistics = null;
    }
    if (this.distributedSystem != null) {
      this.distributedSystem.disconnect();
      this.distributedSystem = null;
    }
  }

//------------------------------------------------------------------------------
// DB

  @Override
  public int read(String table, String key, Set<String> fields,
      HashMap<String, ByteIterator> result) {
    if (logOps) {
      Log.getLogWriter().info("Reading key=" + key);
    }
    long start = this.statistics.startRead();
    Region<String, Map<String, byte[]>> r = getRegion(table);
    Map<String, byte[]> val = r.get(key);
    if (val == null) {
      String s = "No results reading key=" + key + " from " + table;
      throw new PerfTestException(s);
    } else {
      if (fields == null) {
        for (String k : val.keySet()) {
          result.put(k, new ByteArrayByteIterator(val.get(k)));
        }
      } else {
        for (String field : fields) {
          result.put(field, new ByteArrayByteIterator(val.get(field)));
        }
      }
    }
    this.statistics.endRead(start, 1);
    if (logOps) {
      Log.getLogWriter().info("Read key=" + key);
    }
    return 0;
  }

  @Override
  public int update(String table, String key, HashMap<String, ByteIterator> values) {
    if (logOps) {
      Log.getLogWriter().info("Updating key=" + key);
    }
    long start = this.statistics.startUpdate();
    getRegion(table).put(key, convertToBytearrayMap(values));
    this.statistics.endUpdate(start, 1);
    if (logOps) {
      Log.getLogWriter().info("Updated key=" + key);
    }
    return 0;
  }

  @Override
  public int insert(String table, String key, HashMap<String, ByteIterator> values) {
    if (logOps) {
      Log.getLogWriter().info("Inserting key=" + key);
    }
    long start = this.statistics.startInsert();
    getRegion(table).create(key, convertToBytearrayMap(values));
    this.statistics.endInsert(start, 1);
    if (logOps) {
      Log.getLogWriter().info("Inserted key=" + key);
    }
    return 0;
  }

  @Override
  public int delete(String table, String key) {
    if (logOps) {
      Log.getLogWriter().info("Deleting key=" + key);
    }
    long start = this.statistics.startDelete();
    Object o = getRegion(table).destroy(key);
    if (o == null) {
      String s = "Failed deleting key=" + key + " from " + table;
      throw new PerfTestException(s);
    }
    this.statistics.endDelete(start, 1);
    if (logOps) {
      Log.getLogWriter().info("Deleted key=" + key);
    }
    return 0;
  }

  private Map<String, byte[]> convertToBytearrayMap(Map<String,ByteIterator> values) {
    Map<String, byte[]> retVal = new HashMap<String, byte[]>();
    for (String key : values.keySet()) {
      retVal.put(key, values.get(key).toArray());
    }
    return retVal;
  }

  private Region<String, Map<String, byte[]>> getRegion(String table) {
    Region<String, Map<String, byte[]>> r = this.cache.getRegion(table);
    if (r == null) {
      r = RegionHelper.createRegion(CoreWorkloadPrms.getTableName(),
                                    ConfigPrms.getRegionConfig());
    }
    return r;
  }
}


text:
package au.gov.ga.geodesy.port.adapter.geodesyml;

import java.io.Writer;

import javax.xml.bind.JAXBElement;

import java.io.Reader;

public interface GeodesyMLMarshaller {
    void marshal(Object x, Writer writer) throws MarshallingException;

    // TODO: remove
    void marshal(JAXBElement<?> doc, Writer writer) throws MarshallingException;

    // TODO: unmarshal to plain DTO instead, why not?
    <T> JAXBElement<T> unmarshal(Reader reader, Class<T> type) throws MarshallingException;

}


text:
<?php

namespace TestBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="TestBundle\Repository\UserRepository")
 */
class User
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="user_name", type="string", length=255, unique=true)
     */
    private $userName;

    /**
     * @var string
     *
     * @ORM\Column(name="user_phone", type="string", length=15, nullable=true)
     */
    private $userPhone;

    /**
     * @var string
     *
     * @ORM\Column(name="user_email", type="string", length=255, nullable=true)
     */
    private $userEmail;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set userName
     *
     * @param string $userName
     *
     * @return User
     */
    public function setUserName($userName)
    {
        $this->userName = $userName;

        return $this;
    }

    /**
     * Get userName
     *
     * @return string
     */
    public function getUserName()
    {
        return $this->userName;
    }

    /**
     * Set userPhone
     *
     * @param string $userPhone
     *
     * @return User
     */
    public function setUserPhone($userPhone)
    {
        $this->userPhone = $userPhone;

        return $this;
    }

    /**
     * Get userPhone
     *
     * @return string
     */
    public function getUserPhone()
    {
        return $this->userPhone;
    }

    /**
     * Set userEmail
     *
     * @param string $userEmail
     *
     * @return User
     */
    public function setUserEmail($userEmail)
    {
        $this->userEmail = $userEmail;

        return $this;
    }

    /**
     * Get userEmail
     *
     * @return string
     */
    public function getUserEmail()
    {
        return $this->userEmail;
    }
}


text:
<link rel="import" href="../polymer/polymer.html">

<polymer-element name="core-range" attributes="value min max step ratio">

</polymer-element>


text:
require 'spec_helper'

# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator.  If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails.  There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec.  Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.

describe TimelineEventsController, :type => :controller  do

  # This should return the minimal set of attributes required to create a valid
  # TimelineEvent. As you add validations to TimelineEvent, be sure to
  # update the return value of this method accordingly.
  def valid_attributes
    {}
  end
  before { sign_in FactoryGirl.create(:admin) }

  describe "GET index" do
    it "assigns all timeline_events as @timeline_events" do
      timeline_event = TimelineEvent.create! valid_attributes
      get :index
      assigns(:timeline_events).should include(timeline_event)
    end
  end

  describe "GET show" do
    it "assigns the requested timeline_event as @timeline_event" do
      timeline_event = TimelineEvent.create! valid_attributes
      get :show, :id => timeline_event.id
      assigns(:timeline_event).should eq(timeline_event)
    end
  end

  describe "GET new" do
    it "assigns a new timeline_event as @timeline_event" do
      get :new
      assigns(:timeline_event).should be_a_new(TimelineEvent)
    end
  end

  describe "GET edit" do
    it "assigns the requested timeline_event as @timeline_event" do
      timeline_event = TimelineEvent.create! valid_attributes
      get :edit, :id => timeline_event.id
      assigns(:timeline_event).should eq(timeline_event)
    end
  end

  describe "DELETE destroy" do
    it "destroys the requested timeline_event" do
      timeline_event = TimelineEvent.create! valid_attributes
      expect {
        delete :destroy, :id => timeline_event.id
      }.to change(TimelineEvent, :count).by(-1)
    end

    it "redirects to the timeline_events list" do
      timeline_event = TimelineEvent.create! valid_attributes
      delete :destroy, :id => timeline_event.id
      response.should redirect_to(timeline_events_url)
    end
  end

end


text:
package com.vaadin.tests.themes.valo;

import java.io.IOException;
import java.util.List;

import org.junit.Test;
import org.openqa.selenium.remote.DesiredCapabilities;

import com.vaadin.testbench.elements.ButtonElement;
import com.vaadin.tests.tb3.MultiBrowserTest;

public class GridDisabledTest extends MultiBrowserTest {

    @Override
    public List<DesiredCapabilities> getBrowsersToTest() {
        // Grids current DOM/CSS structure doesn't allow
        // opacity to work properly in IE8.
        return getBrowsersExcludingIE8();
    }

    @Test
    public void disabledGrid() throws IOException {
        openTestURL();

        $(ButtonElement.class).caption("Disable").first().click();

        compareScreen("disabled");
    }
}


text:
<?php
/**
 * HTTP API: WP_HTTP_Response class
 *
 * @package WordPress
 * @subpackage HTTP
 * @since 4.4.0
 */

/**
 * Core class used to prepare HTTP responses.
 *
 * @since 4.4.0
 */
class WP_HTTP_Response {

	/**
	 * Response data.
	 *
	 * @since 4.4.0
	 * @var mixed
	 */
	public $data;

	/**
	 * Response headers.
	 *
	 * @since 4.4.0
	 * @var array
	 */
	public $headers;

	/**
	 * Response status.
	 *
	 * @since 4.4.0
	 * @var int
	 */
	public $status;

	/**
	 * Constructor.
	 *
	 * @since 4.4.0
	 *
	 * @param mixed $data    Response data. Default null.
	 * @param int   $status  Optional. HTTP status code. Default 200.
	 * @param array $headers Optional. HTTP header map. Default empty array.
	 */
	public function __construct( $data = null, $status = 200, $headers = array() ) {
		$this->set_data( $data );
		$this->set_status( $status );
		$this->set_headers( $headers );
	}

	/**
	 * Retrieves headers associated with the response.
	 *
	 * @since 4.4.0
	 *
	 * @return array Map of header name to header value.
	 */
	public function get_headers() {
		return $this->headers;
	}

	/**
	 * Sets all header values.
	 *
	 * @since 4.4.0
	 *
	 * @param array $headers Map of header name to header value.
	 */
	public function set_headers( $headers ) {
		$this->headers = $headers;
	}

	/**
	 * Sets a single HTTP header.
	 *
	 * @since 4.4.0
	 *
	 * @param string $key     Header name.
	 * @param string $value   Header value.
	 * @param bool   $replace Optional. Whether to replace an existing header of the same name.
	 *                        Default true.
	 */
	public function header( $key, $value, $replace = true ) {
		if ( $replace || ! isset( $this->headers[ $key ] ) ) {
			$this->headers[ $key ] = $value;
		} else {
			$this->headers[ $key ] .= ', ' . $value;
		}
	}

	/**
	 * Retrieves the HTTP return code for the response.
	 *
	 * @since 4.4.0
	 *
	 * @return int The 3-digit HTTP status code.
	 */
	public function get_status() {
		return $this->status;
	}

	/**
	 * Sets the 3-digit HTTP status code.
	 *
	 * @since 4.4.0
	 *
	 * @param int $code HTTP status.
	 */
	public function set_status( $code ) {
		$this->status = absint( $code );
	}

	/**
	 * Retrieves the response data.
	 *
	 * @since 4.4.0
	 *
	 * @return mixed Response data.
	 */
	public function get_data() {
		return $this->data;
	}

	/**
	 * Sets the response data.
	 *
	 * @since 4.4.0
	 *
	 * @param mixed $data Response data.
	 */
	public function set_data( $data ) {
		$this->data = $data;
	}

	/**
	 * Retrieves the response data for JSON serialization.
	 *
	 * It is expected that in most implementations, this will return the same as get_data(),
	 * however this may be different if you want to do custom JSON data handling.
	 *
	 * @since 4.4.0
	 *
	 * @return mixed Any JSON-serializable value.
	 */
	public function jsonSerialize() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
		return $this->get_data();
	}
}


text:
package utils

// MergeStringMaps creates a new variable map that merges its arguments,
// from first to last.
func MergeStringMaps(ms ...map[string]interface{}) map[string]interface{} {
	result := map[string]interface{}{}
	for _, m := range ms {
		for k, v := range m {
			result[k] = v
		}
	}
	return result
}


text:
import psutil

g = 2**30 + 0.0
meminfo = psutil.virtual_memory()
diskinfo = psutil.disk_usage('/')
print("Cpu count = {}".format(psutil.cpu_count()))
print("RAM: total {}g, free {}g".format(meminfo.total / g, meminfo.free / g))
print("HDD: total {}g, free {}g".format(diskinfo.total / g, diskinfo.free / g))


text:
namespace Microsoft.Azure.Management.MySQL.FlexibleServers
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for ServerParametersOperations.
    /// </summary>
    public static partial class ServerParametersOperationsExtensions
    {
            /// <summary>
            /// Update a list of configurations in a given server.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='serverName'>
            /// The name of the server.
            /// </param>
            /// <param name='value'>
            /// The parameters for updating a list of server configuration.
            /// </param>
            public static ConfigurationListResult BatchUpdate(this IServerParametersOperations operations, string resourceGroupName, string serverName, ConfigurationListResult value)
            {
                return operations.BatchUpdateAsync(resourceGroupName, serverName, value).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Update a list of configurations in a given server.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='serverName'>
            /// The name of the server.
            /// </param>
            /// <param name='value'>
            /// The parameters for updating a list of server configuration.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ConfigurationListResult> BatchUpdateAsync(this IServerParametersOperations operations, string resourceGroupName, string serverName, ConfigurationListResult value, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.BatchUpdateWithHttpMessagesAsync(resourceGroupName, serverName, value, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Update a list of configurations in a given server.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='serverName'>
            /// The name of the server.
            /// </param>
            /// <param name='value'>
            /// The parameters for updating a list of server configuration.
            /// </param>
            public static ConfigurationListResult BeginBatchUpdate(this IServerParametersOperations operations, string resourceGroupName, string serverName, ConfigurationListResult value)
            {
                return operations.BeginBatchUpdateAsync(resourceGroupName, serverName, value).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Update a list of configurations in a given server.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='serverName'>
            /// The name of the server.
            /// </param>
            /// <param name='value'>
            /// The parameters for updating a list of server configuration.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ConfigurationListResult> BeginBatchUpdateAsync(this IServerParametersOperations operations, string resourceGroupName, string serverName, ConfigurationListResult value, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.BeginBatchUpdateWithHttpMessagesAsync(resourceGroupName, serverName, value, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
import {
  REQUEST_SHOW_SHARED_MESSAGE,
  RECEIVE_SHOW_SHARED_MESSAGE,
} from './types';

const defaultState = {
  isLoading: true,
  content: {},
};

const sharedMessagesReducer = (state = defaultState, action) => {
  switch (action.type) {
    case REQUEST_SHOW_SHARED_MESSAGE:
      return {
        ...state,
        isLoading: true,
      };
    case RECEIVE_SHOW_SHARED_MESSAGE:
      const data = action.response.data;

      return {
        ...state,
        isLoading: false,
        content: data,
      };
    default:
      return state;
  }
};

export default sharedMessagesReducer;