text:
package com.github.tinyretry.retry.conf;

/**
 * <pre>
 * desc:
 * created: 2012-9-4 ÏÂÎç01:07:24
 * author: xiaofeng.zhouxf
 * todo:
 * history:
 * </pre>
 */
public class DefaultConfiguration implements Configureable { // extends Configration implements Configureable {

    private Configuretion configuretion;

    public void init() {

    }

    // @Override
    // public void init() {
    // if (configuretion != null) {
    // Configration.ZOOKEEPER_CONNECT_STR = configuretion.getString(Constants.ZOOKEEPER_CONNECT_STR);
    // Configration.ZOOKEEPER_CONNECT_TIME_OUT = configuretion.getInt(Constants.ZOOKEEPER_CONNECT_TIME_OUT);
    // Configration.ZOOKEEPER_CONNECT_RETRY_TIMES = configuretion.getInt(Constants.ZOOKEEPER_CONNECT_RETRY_TIMES);
    // Configration.ZOOKEEPER_CONNECT_RETRY_INTERVAL_TIME = configuretion
    // .getInt(Constants.ZOOKEEPER_CONNECT_RETRY_INTERVAL_TIME);
    // Configration.ZOOKEEPER_EXECUTE_CONNECT_TIMEOUT = configuretion.getInt(Constants.ZOOKEEPER_CONNECT_TIME_OUT);
    // Configration.DEFAULT_PARENT = configuretion.getString(Constants.ZOOKEEPER_DEFAULT_PARENT);
    // }
    // }

    public void addConf(String classpathUrl) {
        if (configuretion != null) {
            configuretion.addConf(classpathUrl);
        }
    }

    public void setConfiguretion(Configuretion configuretion) {
        this.configuretion = configuretion;
    }

}


text:
package q

import (
	"fmt"
	"math"
	"sort"

	"golang.org/x/tools/container/intsets"
)

type IntPair [2]int

func ArrayPairSum(array []int, sum int) []IntPair {
	if len(array) < 2 {
		return nil
	}
	sort.Ints(array)

	result := make([]IntPair, 0, 100)
	left, right := 0, len(array) - 1
	currentSum := 0
	for ; left < right; {
		currentSum = array[left] + array[right]
		// fmt.Printf("currentSum = %v, left = %v, right = %v\n", currentSum, array[left], array[right])
		if currentSum == sum {
			result = append(result, IntPair{array[left], array[right]})
			left += 1
			continue
		} else if currentSum < sum {
			left += 1 // search with bigger number
		} else {
			right -= 1 // search with smaller number
		}
	}
	return result
}

func ArrayPairSum2(array []int, sum int) []IntPair {
	if len(array) < 2 {
		return nil
	}

	seen := intsets.Sparse{}
	result := make([]IntPair, 0, 100)
	for _, n := range array {
		target := sum - n
		if !seen.Has(target) {
			fmt.Printf("Insert: target=%d, n=%d, seen=%v\n", target, n, seen.String())
			seen.Insert(n)
		} else {
			fmt.Printf("Has: target=%d, n=%d, seen=%v\n", target, n, seen.String())
			result = append(result, IntPair{
				int(math.Min(float64(n), float64(target))),
				int(math.Max(float64(n), float64(target))),
			})
		}
	}
	return result
}

redpajama_set_name: RedPajamaGithub


text:
ApplicationMainWindow::ApplicationMainWindow(QSharedPointer<IUserCommunicationManager> p_communicationManager,
                                             QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ApplicationMainWindow),
    m_communicationManager(p_communicationManager)
{
    ui->setupUi(this);
}

ApplicationMainWindow::~ApplicationMainWindow()
{
    delete ui;
}


text:
<?php
    $options[] = array( "name" => "Meta",
    					"sicon" => "metatag.png",
						"type" => "heading");

    $options[] = array( "name" => "Meta",
                        "desc" => "Use this settings for meta tags. Uncheck it if you use a SEO plugin.",
                        "id" => SN."meta",
                        "std" => "0",
                        "type" => "checkbox");

    $options[] = array( "name" => "Meta Description",
						"id" => SN."metadescription",
						"std" => "Moments - Premium wordpress theme solution for your blog.",
						"type" => "textarea");

    $options[] = array( "name" => "Meta Keywords",
						"std" => "clean proffesional wordpress theme, flexible wordpress theme,premium wordpress theme ",
						"id" => SN."metakeywords",
                        "type" => "textarea");

?>


text:
using System.IO;

namespace FSA.PhysicalFileSystem
{
	public class PhysicalFile : BaseFile
	{
		public readonly PhysicalFileSystem _fs;

		protected internal PhysicalFile(PhysicalFileSystem fs, string path)
			: base(fs, path)
		{
			_fs = fs;

			FullPath = fs.GetFullPath(path);
		}

		public string FullPath
		{ get; private set; }

		public override bool Exists
		{
			get { return File.Exists(FullPath); }
		}

		public override Stream OpenRead()
		{
			return File.OpenRead(FullPath);
		}

		protected override IDirectory GetDirectory()
		{
			return new PhysicalDirectory(_fs, System.IO.Path.GetDirectoryName(Path));
		}

		protected override void MoveFile(IFile newFile)
		{
			var physicalDestinationPath = _fs.GetFullPath(newFile.Path);

			File.Move(FullPath, physicalDestinationPath);
		}

		protected override void CopyFile(IFile newFile)
		{
			var physicalDestinationPath = _fs.GetFullPath(newFile.Path);

			File.Copy(FullPath, physicalDestinationPath);
		}

		protected override void DeleteFile()
		{
			File.Delete(FullPath);
		}

		protected override Stream GetWriteStream()
		{
			return File.OpenWrite(FullPath);
		}
	}
}


text:
(function() {
    'use strict';

    angular
        .module('app.employee')
        .controller('CertificateDialogController', CertificateDialogController);

    /** @ngInject */
    function CertificateDialogController($mdDialog, selectedMail, $scope, employeeService) {
        $scope.newEmp = selectedMail;

        console.log($scope.newEmp.SpecialInfo);
        $scope.done = function() {
        console.log($scope.newEmp);
        };
        $scope.sendForm = function() {
            console.log(mode);
            console.log(JSON.stringify($scope.newEmp));
            if (mode == 'C') {
                employeeService.postEmp($scope.newEmp).then(function(res) {
                    $scope.closeDialog();
                }, function(err) {
                    console.log(err);
                });

            } else {
                employeeService.putEmpData($scope.newEmp).then(function(res) {
                    $scope.closeDialog();
                }, function(err) {
                    console.log(err);
                });
            }
            $mdDialog.hide();
        };
        var vm = this;
        console.log(selectedMail);
        // Data
        // $scope.form = {
        //     from: 'johndoe@creapond.com'
        // };

        // vm.hiddenCC = true;
        // vm.hiddenBCC = true;

        // If replying
        // if (angular.isDefined(selectedMail)) {
        //     vm.form.to = selectedMail.from.email;
        //     vm.form.subject = 'RE: ' + selectedMail.subject;
        //     vm.form.message = '<blockquote>' + selectedMail.message + '</blockquote>';
        // }

        // Methods
        $scope.closeDialog = closeDialog;
        vm.addNewList = addNewList;

        //////////

        function closeDialog() {
            $mdDialog.hide();
        };

        // Methods
        // $scope.family = [];
        $scope.family = [];

        $scope.employee = {

            "CertificateInfo": {
                "DateRecordCI": new Date,
                "FirstNameCI": "อนัญญา",
                "LastNameCI": "ทองไทย",
                "PositionCI": "Develop",
                "DateStartCI": new Date("2015-09-01"),
                "SalaryCI": 5,
                "DatePrintCI": new Date,
                "BossSign": "ลายเซ็น"

            },

        };

        // $scope.composeDialog = function(ev) {
        //         var newEmp = {
        //             "PersonalInfo": {},
        //             "FamilyInfo": [],
        //             "EducationInfo": [],
        //             "WorkExperienceInfo": [],
        //             "LanguageInfo": [],
        //             "SpecialInfo": [{

        //                 "TypingSI": 'false',
        //                 "ComputerSI": 'false',
        //                 "DrivingSI": 'false'

        //             }],
        //             "OtherInfo": {}
        //         };
        //         $mdDialog.show({
        //             controller: 'CertificateDialogController',
        //             controllerAs: 'vm',
        //             locals: {
        //                 selectedMail: newEmp,
        //                 mode:'C'
        //             },
        //             templateUrl: 'app/main/apps/employee/dialogs/compose/certificate.html',
        //             parent: angular.element($document.body),
        //             targetEvent: ev,
        //             clickOutsideToClose: true
        //         });
        //     }

            $scope.cerDialog = function(ev) {

                $mdDialog.show({
                    controller: 'CertificateDialogController',
                    controllerAs: 'vm',
                    locals: {
                        selectedMail: $scope.selectedEmp,
                        mode:'U'
                    },
                    templateUrl: 'app/main/apps/employee/dialogs/compose/certificate.html',
                    parent: angular.element($document.body),
                    targetEvent: ev,
                    clickOutsideToClose: true
                });
            }

        //////////

        /**
         * Submit stepper form
         *
         * @param ev
         */

        function addNewList() {
            $scope.family.push({
                'nameFm': $scope.family.nameFm,
                'LastNameFm': $scope.family.LastNameFm,
                'age': $scope.family.age,
                'related': $scope.family.related,
                'Occupation': $scope.family.Occupation,
                'tel': $scope.family.tel
            });
            $scope.family.nameFm = '';
            $scope.family.LastNameFm = '';
            $scope.family.age = '';
            $scope.family.related = '';
            $scope.family.Occupation = '';
            $scope.family.tel = '';
        }

    }

})();


text:
<?php
namespace app\commands;

use Yii;
use yii\console\Controller;
use app\components\rbac\GroupRule;
use yii\rbac\DbManager;

class RbacController extends Controller
{

    public function actionInit()
    {
        $auth = new DbManager;
        $auth->init();

        $auth->removeAll();
        $groupRule = new GroupRule();

        $auth->add($groupRule);

        $user = $auth->createRole('user');
        $user->description = 'User';
        $user->ruleName = $groupRule->name;
        $auth->add($user);

        $admin = $auth->createRole('admin');
        $admin->description = 'Admin';
        $admin->ruleName = $groupRule->name;
        $auth->add($admin);

        //permissions
        $viewUsers = $auth->createPermission('viewUsers');
        $viewUsers->description = 'View all users';
        $auth->add($viewUsers);

        $addInFavorite = $auth->createPermission('addInFavorite');
        $addInFavorite->description = 'Add song in favorite';
        $auth->add($addInFavorite);

        //children
        $auth->addChild($user, $addInFavorite);
        $auth->addChild($admin, $viewUsers);
        $auth->addChild($admin, $user);

        //assignments
        //$auth->assign($admin, Yii::$app->user->id);
        //$auth->assign($user, 2);
    }
}


text:
'use strict';

const {
  MAX_TX_PER_BLOCK
} = require('../constants');

const monitor = require('fast-json-patch');

const Actor = require('./actor');
const Block = require('./block');
const Stack = require('./stack');
const State = require('./state');

/**
 * Chain.
 * @property {String} name Current name.
 * @property {Map} indices
 * @property {Storage} storage
 */
class Chain extends Actor {
  /**
   * Holds an immutable chain of events.
   * @param       {Vector} genesis Initial state for the chain of events.
   */
  constructor (origin = {}) {
    super(origin);

    this.name = (origin) ? origin.name : '@fabric/playnet';
    this.settings = Object.assign({
      name: this.name,
      type: 'sha256',
      validator: this.validate.bind(this)
    }, origin);

    // Internal State
    this._state = {
      blocks: {},
      genesis: null,
      consensus: null,
      content: {
        blocks: []
      },
      transactions: {},
      mempool: [],
      ledger: []
    };

    return this;
  }

  static fromObject (data) {
    return new Chain(data);
  }

  get consensus () {
    return this.tip;
  }

  get tip () {
    return this._state.consensus;
  }

  get root () {
    return this.mast.getRoot();
  }

  get blocks () {
    return this._state.ledger;
  }

  get leaves () {
    return this.blocks.map(x => Buffer.from(x, 'hex'));
  }

  get subsidy () {
    return 50;
  }

  get mempool () {
    return this._state.mempool;
  }

  get _tree () {
    const stack = new Stack(this.leaves);
    return stack.asMerkleTree();
  }

  createSignedBlock (proposal = {}) {
    return {
      actor: proposal.actor || Actor.randomBytes(32).toString('hex'),
      changes: proposal.changes,
      mode: proposal.mode || 'NAIVE_SIGHASH_SINGLE',
      object: Buffer.concat(
        Buffer.alloc(32), // pubkey
        Buffer.alloc(32), // parent
        Buffer.alloc(32), // changes
        Buffer.alloc(64), // signature
      ),
      parent: this.id,
      signature: Buffer.alloc(64),
      state: this.state,
      type: 'FabricBlock'
    };
  }

  trust (source) {
    const self = this;

    source.on('message', function TODO (message) {
      self.emit('debug', `Message from trusted source: ${message}`);
    });

    return self;
  }

  async start () {
    const chain = this;

    // Monitor changes
    this.observer = monitor.observe(this._state);

    // before returning, ensure a commit
    await chain.commit();

    return chain;
  }

  async stop () {
    await this.commit();
    return this;
  }

  async attach (application) {
    if (!application.store) {
      this.emit('error', `Application has no "store" property.`);
    } else {
      this.store = application.store;
    }

    return this;
  }

  async open () {
    return this.storage.open();
  }

  async close () {
    return this.storage.close();
  }

  async _load () {
    const chain = this;

    const query = await chain.storage.get('/blocks');
    const response = new State(query);

    this.log('query:', query);
    this.log('response:', response);
    this.log('response id:', response.id);

    return chain;
  }

  async append (block) {
    if (!block) throw new Error('Must provide a block.');
    if (!(block instanceof Block)) {
      block = new Block(block);
    }

    if (this.blocks.length <= 0) {
      this._state.genesis = block.id;
    }

    this._state.blocks[block.id] = block;
    this._state.ledger.push(block.id);
    this._state.consensus = block.id;

    await this.commit();

    this.emit('block', block);

    return this;
  }

  async _listBlocks () {
    return this.blocks;
  }

  async proposeTransaction (transaction) {
    const actor = new Actor(transaction);

    this._state.transactions[actor.id] = actor;
    this._state.mempool.push(actor.id);

    return actor;
  }

  async generateBlock () {
    const proposal = {
      parent: this.consensus,
      transactions: []
    };

    // TODO: _sortFees
    if (this.mempool.length) {
      for (let i = 0; i < MAX_TX_PER_BLOCK; i++) {
        const candidate = this.mempool.shift();
        if (candidate) {
          proposal.transactions.push(candidate);
        }
      }
    }

    const block = new Block(proposal);
    await this.append(block);

    return block;
  }

  async generateBlocks (count = 1) {
    const blocks = [];

    for (let i = 0; i < count; i++) {
      const block = await this.generateBlock();
      blocks.push(block);
    }

    return blocks;
  }

  async commit () {
    let changes = null;

    if (this.observer) {
      changes = monitor.generate(this.observer);
    }

    if (changes) {
      this.emit('changes', {
        type: 'StateChanges',
        data: changes
      });
    }

    const state = new Actor(this._state);
    return state.id;
  }

  async verify (level = 4, depth = 6) {
    this.log(`Verification Level ${level} running from -${depth}...`);
    console.log('root:', this.root);
    return (this['@id'] === this.root);
  }

  validate (chain) {
    let valid = false;
    for (let i = 0; i < chain.height; i++) {
      let block = chain.blocks[i];
    }
    return valid;
  }

  render () {
    console.log('[CHAIN]', '[RENDER]', this);
    return `<Chain id="${this.id}" />`;
  }
}

module.exports = Chain;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SB Admin 2 - Bootstrap Admin Theme</title>

    <link href="<?php echo public_url('admin'); ?>/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="<?php echo public_url('admin'); ?>/vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <link href="<?php echo public_url('admin'); ?>/dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="<?php echo public_url('admin'); ?>/vendor/morrisjs/morris.css" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        Toggle navigation

                    </button>
                    bongdaso123.esy.es

<a href="<?php echo admin_url('admin/logout'); ?>"> Logout

                                <a href="<?php echo admin_url('baiviet'); ?>">Quản lý bài viết

                                <a href="<?php echo admin_url('admin'); ?>">Quản lý tài khoản

                                Quản lý thể loại

                                        <a href="<?php echo admin_url('league'); ?>">Quản lý giải

                                        <a href="<?php echo admin_url('team'); ?>">Quản lý đội

                <?php
                $this->load->view($temp);
                ?>


text:
set +v
kill -s SIGKILL $(pgrep -f "th multi-server.lua")
nohup th multi-server.lua >> logs/server.log 2>&1&


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE fontscolors PUBLIC "-//NetBeans//DTD Editor Fonts and Colors settings 1.1//EN" "http://www.netbeans.org/dtds/EditorFontsColors-1_1.dtd">
<fontscolors>
    <fontcolor bgColor="ffe3f2e1" default="comment" name="RUBYCOMMENT"/>
    <fontcolor default="keyword" name="mod-method">

    </fontcolor>
    <fontcolor bgColor="ffe3f2e1" default="default" name="ruby"/>
    <fontcolor default="whitespace" name="whitespace"/>
    <fontcolor bgColor="ffe3f2e1" default="default" foreColor="black" name="ruby-delimiter">

    </fontcolor>
    <fontcolor default="comment" name="comment"/>
</fontscolors>


text:
package org.elasticsearch.plugin.javascript;

import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.javascript.JavaScriptScriptEngineService;

/**
 *
 */
public class JavaScriptPlugin extends Plugin {

    static {
        // install rhino policy on plugin init
        JavaScriptScriptEngineService.init();
    }

    @Override
    public String name() {
        return "lang-javascript";
    }

    @Override
    public String description() {
        return "JavaScript plugin allowing to add javascript scripting support";
    }

    public void onModule(ScriptModule module) {
        module.addScriptEngine(JavaScriptScriptEngineService.class);
    }
}


text:
<!-- Questo è un test Questo è un test
Questo è un test Questo è un test
Questo è un test Questo è un test
Questo è un test Questo è un test
Questo è un test Questo è un test  -->
{: .inizio}

![elena](images/mara.jpg)
{: .content-image}


text:
"""
This script is used to build and test (verify) reviews that are posted
to ReviewBoard. The script is intended for use by automated "ReviewBots"
that are run on ASF infrastructure (or by anyone that wishes to donate
some compute power). For example, see 'support/jenkins/reviewbot.sh'.

The script performs the following sequence:
* A query grabs review IDs from Reviewboard.
* In reverse order (most recent first), the script determines if the
  review needs verification (if the review has been updated or changed
  since the last run through this script).
* For each review that needs verification:
  * The review is applied (via 'support/apply-reviews.py').
  * Mesos is built and unit tests are run.
  * The result is posted to ReviewBoard.
"""

import argparse
import time
import datetime
import json
import os
import platform
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request

from common import ReviewBoardHandler, ReviewError, REVIEWBOARD_URL

REVIEW_SIZE = 1000000  # 1 MB in bytes.
# This is the mesos repo ID obtained from querying the reviews.apache.org API
MESOS_REPOSITORY_ID = 122

def parse_parameters():
    """Method to parse the arguments for argparse."""
    parser = argparse.ArgumentParser(
        description="Reviews that need verification from the Review Board")
    parser.add_argument("-u", "--user", type=str, required=True,
                        help="Review Board user name")
    parser.add_argument("-p", "--password", type=str, required=True,
                        help="Review Board user password")
    parser.add_argument("-r", "--reviews", type=int, required=False,
                        default=-1, help="The number of reviews to fetch,"
                                         " that will need verification")
    parser.add_argument("--skip-verify", action='store_true', required=False,
                        help="Skip the verification and just write the review"
                             " ids that need verification")
    default_hours_behind = 8
    datetime_before = (datetime.datetime.now() -
                       datetime.timedelta(hours=default_hours_behind))
    datetime_before_string = datetime_before.isoformat()
    default_query = {"status": "pending", "repository": MESOS_REPOSITORY_ID,
                     "last-updated-from": datetime_before_string.split(".")[0]}
    parser.add_argument("-q", "--query", type=str, required=False,
                        help="Query parameters, passed as string in JSON"
                             " format. Example: '%s'" % json.dumps(
                                 default_query),
                        default=json.dumps(default_query))

    subparsers = parser.add_subparsers(title="The script plug-in type")

    file_parser = subparsers.add_parser(
        "file", description="File plug-in just writes to a file all"
                            " the review ids that need verification")
    file_parser.add_argument("-o", "--out-file", type=str, required=True,
                             help="The out file with the reviews IDs that"
                                  " need verification")

    return parser.parse_args()

def shell(command):
    """Run a shell command."""
    print(command)
    return subprocess.check_output(
        command, stderr=subprocess.STDOUT, shell=True)

def apply_review(review_id):
    """Apply a review using the script apply-reviews.py."""
    print("Applying review %s" % review_id)
    shell("python support/apply-reviews.py -n -r %s" % review_id)

def apply_reviews(review_request, reviews, handler):
    """Apply multiple reviews at once."""
    # If there are no reviewers specified throw an error.
    if not review_request["target_people"]:
        raise ReviewError("No reviewers specified. Please find a reviewer by"
                          " asking on JIRA or the mailing list.")

    # If there is a circular dependency throw an error.`
    if review_request["id"] in reviews:
        raise ReviewError("Circular dependency detected for review %s."
                          "Please fix the 'depends_on' field."
                          % review_request["id"])
    else:
        reviews.append(review_request["id"])

    # First recursively apply the dependent reviews.
    for review in review_request["depends_on"]:
        review_url = review["href"]
        print("Dependent review: %s" % review_url)
        apply_reviews(handler.api(review_url)["review_request"],
                      reviews, handler)

    # Now apply this review if not yet submitted.
    if review_request["status"] != "submitted":
        apply_review(review_request["id"])

def post_review(review_request, message, handler):
    """Post a review on the review board."""
    print("Posting review: %s" % message)

    review_url = review_request["links"]["reviews"]["href"]
    data = urllib.parse.urlencode({'body_top': message, 'public': 'true'})
    handler.api(review_url, data)

# @atexit.register
def cleanup():
    """Clean the git repository."""
    try:
        shell("git clean -fd")
        HEAD = shell("git rev-parse HEAD")
        print(HEAD)
        shell("git checkout HEAD -- %s" % HEAD)
    except subprocess.CalledProcessError as err:
        print("Failed command: %s\n\nError: %s" % (err.cmd, err.output))

def verify_review(review_request, handler):
    """Verify a review."""
    print("Verifying review %s" % review_request["id"])
    build_output = "build_" + str(review_request["id"])

    try:
        # Recursively apply the review and its dependents.
        reviews = []
        apply_reviews(review_request, reviews, handler)

        reviews.reverse()  # Reviews are applied in the reverse order.

        if platform.system() == 'Windows':
            command = "support\\windows-build.bat"

            # There is no equivalent to `tee` on Windows.
            subprocess.check_call(
                ['cmd', '/c', '%s 2>&1 > %s' % (command, build_output)])
        else:
            # Launch docker build script.

            # TODO(jojy): Launch 'docker_build.sh' in subprocess so that
            # verifications can be run in parallel for various configurations.
            configuration = ("export "
                             "OS='ubuntu:14.04' "
                             "BUILDTOOL='autotools' "
                             "COMPILER='gcc' "
                             "CONFIGURATION='--verbose "
                             "--disable-libtool-wrappers' "
                             "ENVIRONMENT='GLOG_v=1 MESOS_VERBOSE=1'")

            command = "%s; ./support/docker-build.sh" % configuration

            # `tee` the output so that the console can log the whole build
            # output. `pipefail` ensures that the exit status of the build
            # command ispreserved even after tee'ing.
            subprocess.check_call(['bash', '-c',
                                   'set -o pipefail; %s 2>&1 | tee %s'
                                   % (command, build_output)])

        # Success!
        post_review(
            review_request,
            "Patch looks great!\n\n"
            "Reviews applied: %s\n\n"
            "Passed command: %s" % (reviews, command), handler)
    except subprocess.CalledProcessError as err:
        # If we are here because the docker build command failed, read the
        # output from `build_output` file. For all other command failures read
        # the output from `e.output`.
        if os.path.exists(build_output):
            output = open(build_output).read()
        else:
            output = err.output

        if platform.system() == 'Windows':
            # We didn't output anything during the build (because `tee`
            # doesn't exist), so we print the output to stdout upon error.

            # Pylint raises a no-member error on that line due to a bug
            # fixed in pylint 1.7.
            # TODO(ArmandGrillet): Remove this once pylint updated to >= 1.7.
            # pylint: disable=no-member
            sys.stdout.buffer.write(output)

        # Truncate the output when posting the review as it can be very large.
        if len(output) > REVIEW_SIZE:
            output = "...<truncated>...\n" + output[-REVIEW_SIZE:]

        output += "\nFull log: "
        output += urllib.parse.urljoin(os.environ['BUILD_URL'], 'console')

        post_review(
            review_request,
            "Bad patch!\n\n" \
            "Reviews applied: %s\n\n" \
            "Failed command: %s\n\n" \
            "Error:\n%s" % (reviews, err.cmd, output), handler)
    except ReviewError as err:
        post_review(
            review_request,
            "Bad review!\n\n" \
            "Reviews applied: %s\n\n" \
            "Error:\n%s" % (reviews, err.args[0]), handler)

    # Clean up.
    # cleanup()

def verification_needed_write(review_ids, parameters):
    """Write the IDs of the review requests that need verification."""
    num_reviews = len(review_ids)
    print("%s review requests need verification" % num_reviews)
    # out_file parameter is mandatory to be passed
    try:
        # Using file plug-in
        with open(parameters.out_file, 'w') as f:
            f.write('\n'.join(review_ids))
    except Exception:
        print("Failed opening file '%s' for writing" % parameters.out_file)
        raise

def main():
    """Main function to verify the submitted reviews."""
    parameters = parse_parameters()
    print("\n%s - Running %s" % (time.strftime('%m-%d-%y_%T'),
                                 os.path.abspath(__file__)))
    # The colon from timestamp gets encoded and we don't want it to be encoded.
    # Replacing %3A with colon.
    query_string = urllib.parse.urlencode(
        json.loads(parameters.query)).replace("%3A", ":")
    review_requests_url = "%s/api/review-requests/?%s" % (REVIEWBOARD_URL,
                                                          query_string)
    handler = ReviewBoardHandler(parameters.user, parameters.password)
    num_reviews = 0
    review_ids = []
    review_requests = handler.api(review_requests_url)
    for review_request in reversed(review_requests["review_requests"]):
        if parameters.reviews == -1 or num_reviews < parameters.reviews:
            try:
                needs_verification = handler.needs_verification(review_request)
                if not needs_verification:
                    continue
                # An exception is raised if cyclic dependencies are found
                handler.get_dependent_review_ids(review_request)
            except ReviewError as err:
                message = ("Bad review!\n\n"
                           "Error:\n%s" % (err.args[0]))
                handler.post_review(review_request, message, handler)
                continue
            except Exception as err:
                print("Error occured: %s" % err)
                needs_verification = False
                print("WARNING: Cannot find if review %s needs"
                      " verification" % (review_request["id"]))
            if not needs_verification:
                continue
            review_ids.append(str(review_request["id"]))
            num_reviews += 1
            if not parameters.skip_verify:
                verify_review(review_request, handler)

    verification_needed_write(review_ids, parameters)

if __name__ == '__main__':
    main()


text:
inline void frequire(FILE *f, std::string file = "Unknown file", std::string procedure = "Unknown procedure") {
  if (f == 0) {
    std::cerr << "\n" << procedure << " : File " << file << " cannot be opened!\n" << std::endl;
    exit(1);
  }
}

inline void frequire(std::ifstream &in, std::string file = "Unknown file", std::string procedure = "Unknown procedure") {
  if (!in) {
    std::cerr << "\n" << procedure << " : File " << file << " cannot be opened for reading!\n" << std::endl;
    exit(1);
  }
}

inline void frequire(std::ofstream &out, std::string file = "Unknown file", std::string procedure = "Unknown procedure") {
  if (!out) {
    std::cerr << "\n" << procedure << " : File " << file << " cannot be opened for writing!\n" << std::endl;
    exit(1);
  }
}

inline void require(bool requirement, std::string error = "Requirement failed!", std::string procedure = "Unknown procedure") {
  if (!requirement) {
    std::cerr << "\n" << procedure << " : " << error << "\n" << std::endl;
    exit(1);
  }
}

#if BOOST_FS
#else
inline bool fexists(const std::string& fileName) {
  std::ifstream in(fileName.c_str());
  if (in) {
    in.close();
    return true; // file exists
  }
  return false; // file doesn't exist
}
#endif // BOOST_FS

#endif // REQUIRE_H


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ProfessorTurma;

/**
 * UsuarioTurmaSearch represents the model behind the search form about `app\models\UsuarioTurma`.
 */
class ProfessorTurmaSearch extends ProfessorTurma
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Turma_id', 'Usuarios_id'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ProfessorTurma::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'Turma_id' => $this->Turma_id,
            'Usuarios_id' => $this->Usuarios_id,
        ]);

        return $dataProvider;
    }
}


text:
                Razão Social (*)

                Nome fantasia (*)

                <input type="text" class="form-control" placeholder="O nome de registro da instituição" name="razaoSocial" required style="width: 100%">

                <input type="text" class="form-control" placeholder="O nome popular da instituição." name="nomeFantasia" required style="width: 100%">

                Sigla (*)

                CNPJ (*)

                Inscrição Estadual (*)

                Categoria Admin.

                <input type="text" class="form-control" placeholder="Sigla da instituição." name="sigla" pattern="[a-zA-Z]+" title="Permitido apenas letras." required style="width: 100%">

                <input type="text" class="form-control" placeholder="xx.xxx.xxx/xxxx-xx" name="cnpj" id="cnpj" OnKeyPress="formatar('##.###.###/####-##', this)" maxlength="18" onchange="validar()" required style="width: 100%">

                <input type="text" class="form-control" placeholder="Inscrição Estadual" name="inscEst" required style="width: 100%">

                <select class="form-control" style="width: 100%" name="catAdm">
                    <option value="default">Selecione</option>
                    <option value="clucra">Com fins lucrativos</option>
                    <option value="slucra">Sem fins lucraivos não beneficiente</option>
                    <option value="bene">Beneficiente</option>
                </select>

                Mantenedora (*)

                Representante legal (*)

                <input type="text" class="form-control" style="width: 100%" placeholder="Mantenedora" name="mantenedora" required>

                <input type="text" class="form-control" style="width: 100%" placeholder="Representante legal" name="representanteLegal" required>

                Premissas da faculdade

                <textarea rows="6" style="width: 100%" class="form-control" placeholder="Premissas." name="premissa"></textarea>


text:
using EPiServer.Commerce.Catalog.ContentTypes;
using EPiServer.Framework.DataAnnotations;
using EPiServer.Reference.Commerce.Site.Features.Product.Services;
using EPiServer.Web.Mvc;
using System.Web.Mvc;

namespace EPiServer.Reference.Commerce.Site.Features.Product.Controllers
{
    [TemplateDescriptor(Inherited = true)]
    public class ProductPartialController : PartialContentController<ProductContent>
    {
        private readonly IProductService _productService;

        public ProductPartialController(IProductService productService)
        {
            _productService = productService;
        }

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public override ActionResult Index(ProductContent currentContent)
        {
            return PartialView("_Product", _productService.GetProductTileViewModel(currentContent));
        }
    }
}


text:
package de.congrace.exp4j;
// Edited by Devin Bost, 2014
public abstract class ArrayUtil {
    public static double[] reverse(double[] data) {
        int left = 0;
        int right = data.length - 1;

        while (left < right) {
            // swap the values at the left and right indices
            double temp = data[left];
            data[left] = data[right];
            data[right] = temp;

            // move the left and right index pointers in toward the center
            left++;
            right--;
        }
        return data;
    }
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Changing field 'Channel.db_lock_storage'
        db.alter_column('comms_channel', 'db_lock_storage', self.gf('django.db.models.fields.TextField')())

        # Changing field 'Msg.db_lock_storage'
        db.alter_column('comms_msg', 'db_lock_storage', self.gf('django.db.models.fields.TextField')())

    def backwards(self, orm):

        # Changing field 'Channel.db_lock_storage'
        db.alter_column('comms_channel', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512))

        # Changing field 'Msg.db_lock_storage'
        db.alter_column('comms_msg', 'db_lock_storage', self.gf('django.db.models.fields.CharField')(max_length=512))

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'comms.channel': {
            'Meta': {'object_name': 'Channel'},
            'db_aliases': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'db_desc': ('django.db.models.fields.CharField', [], {'max_length': '80', 'null': 'True', 'blank': 'True'}),
            'db_keep_log': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'db_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'comms.externalchannelconnection': {
            'Meta': {'object_name': 'ExternalChannelConnection'},
            'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}),
            'db_external_config': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_external_key': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'db_external_send_code': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_is_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'comms.msg': {
            'Meta': {'object_name': 'Msg'},
            'db_date_sent': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
            'db_header': ('django.db.models.fields.CharField', [], {'max_length': 128, 'null': 'True', 'blank': 'True'}),
            'db_hide_from_channles': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'hide_from_channels_set'", 'null': 'True', 'to': "orm['comms.Channel']"}),
            'db_hide_from_objects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'hide_from_objects_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_hide_from_players': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'hide_from_players_set'", 'null': 'True', 'to': "orm['players.PlayerDB']"}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_message': ('django.db.models.fields.TextField', [], {}),
            'db_receivers_channels': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'channel_set'", 'null': 'True', 'to': "orm['comms.Channel']"}),
            'db_receivers_objects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'receiver_object_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_receivers_players': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'receiver_player_set'", 'null': 'True', 'to': "orm['players.PlayerDB']"}),
            'db_sender_external': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'db_index': 'True'}),
            'db_sender_objects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'sender_object_set'", 'null': 'True', 'db_index': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_sender_players': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'sender_player_set'", 'null': 'True', 'db_index': 'True', 'to': "orm['players.PlayerDB']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'comms.playerchannelconnection': {
            'Meta': {'object_name': 'PlayerChannelConnection'},
            'db_channel': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['comms.Channel']"}),
            'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'objects.objectdb': {
            'Meta': {'object_name': 'ObjectDB'},
            'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_destination': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'destinations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}),
            'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'players.playerdb': {
            'Meta': {'object_name': 'PlayerDB'},
            'db_cmdset_storage': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_is_connected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True', 'blank': 'True'}),
            'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'})
        }
    }

    complete_apps = ['comms']


text:
# I worked on this challenge [with: Wesley El-Amin].
# I spent [1.5] hours on this challenge.

# Pseudocode
=begin
Take a 16 digit number as input.
Output should be a true or false statement determining whether the credit card
number is valid.
Create a class method for CreditCard that initializes with 16 digits. If the
number that has been input is not 16 digits long, the user will recieve an ArgumentError.
Take the input number, convert it into a string, and split the string into individual
parts. Starting with the second to last string, convert that and every other string
to an integer, then double its value change it to a string.
If the string is longer than one character, break it into single-character parts.
Finally, convert all strings to integers and add them together and divide that sum
by 10.
Set up a conditional: If the quotient of the sum of all integers divided by 10
has no remainder, the statement is true. If there is a remainder, the statement is false.
=end

# Initial Solution

# Don't forget to check on initialization for a card length
# of exactly 16 digits

class CreditCard
  def initialize (number)
    if number.to_s.length == 16
      @number = number.to_s
    else
      raise ArgumentError.new("not a valid number")
    end
  end

  def split_number
    @number_array = @number.split(//)
  end

  def double_every_other
    split_number
    @double_array = @number_array.collect.with_index { |digit, index| index.even? || index == 0 ? digit.to_i * 2 : digit }
    @double_array.map! { |term| term.to_s.split(//)}
    @double_array.flatten!
  end

  def check_card
    double_every_other
    if @double_array.inject(0) { |memo, number| memo + number.to_i } % 10 == 0
      true
    else
      false
    end
  end

end

# Refactored solution

class CreditCard
  # Initializes CreditCard class as a 16 character string using a 16 digit number.
  def initialize (number)
    @number = number.to_s if number.to_s.length == 16
    raise ArgumentError.new("not a valid number") if number.to_s.length != 16
  end

  # Splits the original string into 16 strings, places them in an array, then
  # then converts the first string and every other subsequent string into an
  # integer. Finally this method doubles each integer, converts each integer
  # into a string, and places all of the strings (old and new) into an array.
  def double_every_other
    @number_array = @number.split(//)
    @double_array = @number_array.collect.with_index { |digit, index| index.even? ? digit.to_i * 2 : digit }
    @double_array.map! { |term| term.to_s.split(//)}.flatten!
  end

  # This final method takes all of the strings in the new array, converts them
  # into integers, and adds them up. If the sum of all of those integers is
  # divisible by 10 with no remainder, the method returns true. In any other circumstance,
  # the method returns false.
  def check_card
    double_every_other
    @double_array.inject(0) { |initial, number| initial + number.to_i } % 10 == 0
  end
end

#Reflection

# What was the most difficult part of this challenge for you and your pair?

# The most difficult was going from one method to the next to logically fulfill the requirements. I felt that a few times we got results other than the ones we expected.

# What new methods did you find to help you when you refactored?

# We didn't find any new methods, we used inject, map, and flatten to maneuver and alter the arrays we needed to follow the algorithm

# What concepts or learnings were you able to solidify in this challenge?

# The different ways methods can call each other and the ways the pass on variables. Especially the instance variables, they can really be used anywhere in the class it makes it very convenient.


text:
@( label: String, href: String )

@label


text:
/*
 * This file defines the OS dependent network related functions
 * that MUST be available to olsrd.
 * The implementations of the functions should be found in
 * <OS>/net.c (e.g. linux/net.c)
 */

#ifndef _OLSR_NET_OS_H
#define _OLSR_NET_OS_H

#include "olsr_types.h"
#include "interfaces.h"

/* OS dependent functions */
ssize_t olsr_sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t);

ssize_t olsr_recvfrom(int, void *, size_t, int, struct sockaddr *, socklen_t *);

int olsr_select(int, fd_set *, fd_set *, fd_set *, struct timeval *);

int bind_socket_to_device(int, char *);

int convert_ip_to_mac(union olsr_ip_addr *, struct sockaddr *, char *);

int disable_redirects(const char *, struct interface *, int);

int disable_redirects_global(int);

int deactivate_spoof(const char *, struct interface *, int);

int restore_settings(int);

int enable_ip_forwarding(int);

int gethemusocket(struct sockaddr_in *);

int getsocket(int, char *);

int getsocket6(int, char *);

int get_ipv6_address(char *, struct sockaddr_in6 *, int);

int calculate_if_metric(char *);

int check_wireless_interface(char *);

olsr_bool is_if_link_up(char *);

int join_mcast(struct interface *, int);

#endif

/*
 * Local Variables:
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 */


text:
<?php
/**
 * Maria - Intelligent Extensible Text Bot - 2016/2017
 *
 * @author Rafal Purwin
 * @license MIT - see LICENSE.md
 */

namespace Maria\Controllers\Admin\Translations;

use Arc\Core\Application;
use Arc\Core\Controller;
use Arc\Core\Http;
use Maria\Models\Language;

/**
 * Class Aiml
 * @package Maria\Controllers\Admin\Translations
 */
class Aiml extends Controller {

    /**
     * @var Language
     */
    private $language;

    /**
     * AIML constructor.
     * @param Application $application
     * @param Http $http
     */
    public function __construct(Application $application, Http $http, Language $language) {
        parent::__construct($application, $http);
        $this->language = $language;
    }

    /**
     * Upload single AIML file for language
     */
    public function uploadAIML() {
        $this->http->response()->redirect($this->http->uri()->getPreviousRoute());
        $this->language->load($this->http->request()->getParameter('id'));

        if(!$this->language->getId()) {
            $this->application->flashMessage()->addDanger('Taki język nie istnieje');
            return;
        }

        if($this->language->hasAIML()) {
            $this->deleteAIMLFile();
        }
        $this->addAIMLFile();
    }

    /**
     * Upload new AIML file for current language
     */
    private function addAIMLFile() {
        if($this->http->request()->getFile('aiml')['error'] == 4) {
            return;
        }

        try {
            $file = $this->application->file();
            $file->setFile($this->http->request()->getFile('aiml'));
            if($file->isValid()) {
                $file->upload(strtoupper($this->language->getCode()), 'src/etc/aiml');
                $this->application->flashMessage()->addSuccess('Plik AIML dodany pomyślnie');
                return;
            }
        } catch (\Exception $ex) {
            $this->application->flashMessage()->addDanger($ex->getMessage());
            return;
        }

        $this->application->flashMessage()->addDanger('Plik jest niepoprawny');
        return;
    }

    /**
     * Delete language existing AIML file
     */
    private function deleteAIMLFile() {
        if($this->language->hasTranslations()) {
            $fileName = $this->language->getCode() . '.xml';
            $this->application->file()->delete($fileName, 'src/etc/aiml');
        }
    }

    /**
     * AIML template download action
     */
    public function downloadTemplate() {
        $template = SRC . 'etc' . DS . 'aiml' . DS . 'PL.xml';

        $this->http->response()->setHeader('Content-type', 'octet/stream');
        $this->http->response()->setHeader('Content-disposition', 'attachment; filename=template.xml');
        $this->http->response()->setHeader('Content-Length', filesize($template));
        readfile($template);
    }
}


text:
import hammerhead from '../deps/hammerhead';

const nativeIndexOf = Array.prototype.indexOf;
const nativeForEach = Array.prototype.forEach;
const nativeSome    = Array.prototype.some;
const nativeMap     = Array.prototype.map;
const nativeFilter  = Array.prototype.filter;
const nativeReverse = Array.prototype.reverse;
const nativeReduce  = Array.prototype.reduce;
const nativeSplice  = Array.prototype.splice;

export function toArray (arg) {
    const arr    = [];
    const length = arg.length;

    for (let i = 0; i < length; i++)
        arr.push(arg[i]);

    return arr;
}

export function reverse (arr) {
    return nativeReverse.call(arr);
}

export function isArray (arg) {
    return hammerhead.nativeMethods.objectToString.call(arg) === '[object Array]';
}

export function find (arr, callback) {
    const length = arr.length;

    for (let i = 0; i < length; i++) {
        if (callback(arr[i], i, arr))
            return arr[i];
    }

    return null;
}

export function indexOf (arr, arg) {
    return nativeIndexOf.call(arr, arg);
}

export function forEach (arr, callback) {
    nativeForEach.call(arr, callback);
}

export function some (arr, callback) {
    return nativeSome.call(arr, callback);
}

export function map (arr, callback) {
    return nativeMap.call(arr, callback);
}

export function filter (arr, callback) {
    return nativeFilter.call(arr, callback);
}

export function reduce (arr, callback, initialValue) {
    return nativeReduce.call(arr, callback, initialValue);
}

export function remove (arr, item) {
    const index = indexOf(arr, item);

    if (index > -1)
        nativeSplice.call(arr, index, 1);
}

export function equals (arr1, arr2) {
    if (arr1.length !== arr2.length)
        return false;

    for (let i = 0, l = arr1.length; i < l; i++) {
        if (arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

export function getCommonElement (arr1, arr2) {
    for (let i = 0; i < arr1.length; i++) {
        for (let t = 0; t < arr2.length; t++) {
            if (arr1[i] === arr2[t])
                return arr1[i];
        }
    }

    return null;
}


text:
using NUnit.Framework;

namespace NEventStore.Persistence.Oracle.Tests
{
    /// <summary>
    /// this is needed to allow NUnit test adapter to discover the tests,
    /// if we do not have any class explicitly marked with the TestFixture attribute
    /// all the assembly will be ignored (even if some class inherit from something which is
    /// marked with the attribute in a reference assembly)
    /// </summary>
#if NUNIT
    [TestFixture]
    public class NUnitTestAdapterTestsDiscovery
    {
    }
#endif
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>value::is_primitive</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.JSON">
<link rel="up" href="../boost__json__value.html" title="value">
<link rel="prev" href="is_structured.html" title="value::is_structured">
<link rel="next" href="is_number.html" title="value::is_number">

Home
Libraries
People
FAQ
More

value::is_primitive

          Returns true if this is not an array or object.

          Synopsis

bool
is_primitive() const;

          Description

          This function returns true
          if kind() is neither kind::object
          nor kind::array.

          Complexity

          Constant.

          Exception
          Safety

          No-throw guarantee.

Copyright © 2019, 2020 Vinnie Falco
Copyright © 2020 Krystian Stasiowski

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.dubbo.rpc.protocol.dubbo;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.bytecode.Wrapper;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.protocol.AsyncToSyncInvoker;

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

import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_KEY;
import static org.apache.dubbo.common.constants.RpcConstants.CALLBACK_INSTANCES_LIMIT_KEY;
import static org.apache.dubbo.common.constants.RpcConstants.DEFAULT_CALLBACK_INSTANCES;
import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CALLBACK_SERVICE_PROXY_KEY;
import static org.apache.dubbo.rpc.protocol.dubbo.Constants.IS_CALLBACK_SERVICE;
import static org.apache.dubbo.rpc.protocol.dubbo.Constants.CHANNEL_CALLBACK_KEY;
import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY;

/**
 * callback service helper
 */
class CallbackServiceCodec {
    private static final Logger logger = LoggerFactory.getLogger(CallbackServiceCodec.class);

    private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
    private static final DubboProtocol protocol = DubboProtocol.getDubboProtocol();
    private static final byte CALLBACK_NONE = 0x0;
    private static final byte CALLBACK_CREATE = 0x1;
    private static final byte CALLBACK_DESTROY = 0x2;
    private static final String INV_ATT_CALLBACK_KEY = "sys_callback_arg-";

    private static byte isCallBack(URL url, String methodName, int argIndex) {
        // parameter callback rule: method-name.parameter-index(starting from 0).callback
        byte isCallback = CALLBACK_NONE;
        if (url != null) {
            String callback = url.getParameter(methodName + "." + argIndex + ".callback");
            if (callback != null) {
                if (callback.equalsIgnoreCase("true")) {
                    isCallback = CALLBACK_CREATE;
                } else if (callback.equalsIgnoreCase("false")) {
                    isCallback = CALLBACK_DESTROY;
                }
            }
        }
        return isCallback;
    }

    /**
     * export or unexport callback service on client side
     *
     * @param channel
     * @param url
     * @param clazz
     * @param inst
     * @param export
     * @throws IOException
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private static String exportOrUnexportCallbackService(Channel channel, URL url, Class clazz, Object inst, Boolean export) throws IOException {
        int instid = System.identityHashCode(inst);

        Map<String, String> params = new HashMap<>(3);
        // no need to new client again
        params.put(IS_SERVER_KEY, Boolean.FALSE.toString());
        // mark it's a callback, for troubleshooting
        params.put(IS_CALLBACK_SERVICE, Boolean.TRUE.toString());
        String group = (url == null ? null : url.getParameter(GROUP_KEY));
        if (group != null && group.length() > 0) {
            params.put(GROUP_KEY, group);
        }
        // add method, for verifying against method, automatic fallback (see dubbo protocol)
        params.put(METHODS_KEY, StringUtils.join(Wrapper.getWrapper(clazz).getDeclaredMethodNames(), ","));

        Map<String, String> tmpMap = new HashMap<>(url.getParameters());
        tmpMap.putAll(params);
        tmpMap.remove(VERSION_KEY);// doesn't need to distinguish version for callback
        tmpMap.put(INTERFACE_KEY, clazz.getName());
        URL exportUrl = new URL(DubboProtocol.NAME, channel.getLocalAddress().getAddress().getHostAddress(), channel.getLocalAddress().getPort(), clazz.getName() + "." + instid, tmpMap);

        // no need to generate multiple exporters for different channel in the same JVM, cache key cannot collide.
        String cacheKey = getClientSideCallbackServiceCacheKey(instid);
        String countKey = getClientSideCountKey(clazz.getName());
        if (export) {
            // one channel can have multiple callback instances, no need to re-export for different instance.
            if (!channel.hasAttribute(cacheKey)) {
                if (!isInstancesOverLimit(channel, url, clazz.getName(), instid, false)) {
                    Invoker<?> invoker = PROXY_FACTORY.getInvoker(inst, clazz, exportUrl);
                    // should destroy resource?
                    Exporter<?> exporter = protocol.export(invoker);
                    // this is used for tracing if instid has published service or not.
                    channel.setAttribute(cacheKey, exporter);
                    logger.info("Export a callback service :" + exportUrl + ", on " + channel + ", url is: " + url);
                    increaseInstanceCount(channel, countKey);
                }
            }
        } else {
            if (channel.hasAttribute(cacheKey)) {
                Exporter<?> exporter = (Exporter<?>) channel.getAttribute(cacheKey);
                exporter.unexport();
                channel.removeAttribute(cacheKey);
                decreaseInstanceCount(channel, countKey);
            }
        }
        return String.valueOf(instid);
    }

    /**
     * refer or destroy callback service on server side
     *
     * @param url
     */
    @SuppressWarnings("unchecked")
    private static Object referOrDestroyCallbackService(Channel channel, URL url, Class<?> clazz, Invocation inv, int instid, boolean isRefer) {
        Object proxy = null;
        String invokerCacheKey = getServerSideCallbackInvokerCacheKey(channel, clazz.getName(), instid);
        String proxyCacheKey = getServerSideCallbackServiceCacheKey(channel, clazz.getName(), instid);
        proxy = channel.getAttribute(proxyCacheKey);
        String countkey = getServerSideCountKey(channel, clazz.getName());
        if (isRefer) {
            if (proxy == null) {
                URL referurl = URL.valueOf("callback://" + url.getAddress() + "/" + clazz.getName() + "?" + INTERFACE_KEY + "=" + clazz.getName());
                referurl = referurl.addParametersIfAbsent(url.getParameters()).removeParameter(METHODS_KEY);
                if (!isInstancesOverLimit(channel, referurl, clazz.getName(), instid, true)) {
                    @SuppressWarnings("rawtypes")
                    Invoker<?> invoker = new ChannelWrappedInvoker(clazz, channel, referurl, String.valueOf(instid));
                    proxy = PROXY_FACTORY.getProxy(new AsyncToSyncInvoker<>(invoker));
                    channel.setAttribute(proxyCacheKey, proxy);
                    channel.setAttribute(invokerCacheKey, invoker);
                    increaseInstanceCount(channel, countkey);

                    //convert error fail fast .
                    //ignore concurrent problem.
                    Set<Invoker<?>> callbackInvokers = (Set<Invoker<?>>) channel.getAttribute(CHANNEL_CALLBACK_KEY);
                    if (callbackInvokers == null) {
                        callbackInvokers = new ConcurrentHashSet<Invoker<?>>(1);
                        callbackInvokers.add(invoker);
                        channel.setAttribute(CHANNEL_CALLBACK_KEY, callbackInvokers);
                    }
                    logger.info("method " + inv.getMethodName() + " include a callback service :" + invoker.getUrl() + ", a proxy :" + invoker + " has been created.");
                }
            }
        } else {
            if (proxy != null) {
                Invoker<?> invoker = (Invoker<?>) channel.getAttribute(invokerCacheKey);
                try {
                    Set<Invoker<?>> callbackInvokers = (Set<Invoker<?>>) channel.getAttribute(CHANNEL_CALLBACK_KEY);
                    if (callbackInvokers != null) {
                        callbackInvokers.remove(invoker);
                    }
                    invoker.destroy();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                // cancel refer, directly remove from the map
                channel.removeAttribute(proxyCacheKey);
                channel.removeAttribute(invokerCacheKey);
                decreaseInstanceCount(channel, countkey);
            }
        }
        return proxy;
    }

    private static String getClientSideCallbackServiceCacheKey(int instid) {
        return CALLBACK_SERVICE_KEY + "." + instid;
    }

    private static String getServerSideCallbackServiceCacheKey(Channel channel, String interfaceClass, int instid) {
        return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + "." + instid;
    }

    private static String getServerSideCallbackInvokerCacheKey(Channel channel, String interfaceClass, int instid) {
        return getServerSideCallbackServiceCacheKey(channel, interfaceClass, instid) + "." + "invoker";
    }

    private static String getClientSideCountKey(String interfaceClass) {
        return CALLBACK_SERVICE_KEY + "." + interfaceClass + ".COUNT";
    }

    private static String getServerSideCountKey(Channel channel, String interfaceClass) {
        return CALLBACK_SERVICE_PROXY_KEY + "." + System.identityHashCode(channel) + "." + interfaceClass + ".COUNT";
    }

    private static boolean isInstancesOverLimit(Channel channel, URL url, String interfaceClass, int instid, boolean isServer) {
        Integer count = (Integer) channel.getAttribute(isServer ? getServerSideCountKey(channel, interfaceClass) : getClientSideCountKey(interfaceClass));
        int limit = url.getParameter(CALLBACK_INSTANCES_LIMIT_KEY, DEFAULT_CALLBACK_INSTANCES);
        if (count != null && count >= limit) {
            //client side error
            throw new IllegalStateException("interface " + interfaceClass + " `s callback instances num exceed providers limit :" + limit
                    + " ,current num: " + (count + 1) + ". The new callback service will not work !!! you can cancle the callback service which exported before. channel :" + channel);
        } else {
            return false;
        }
    }

    private static void increaseInstanceCount(Channel channel, String countkey) {
        try {
            //ignore concurrent problem?
            Integer count = (Integer) channel.getAttribute(countkey);
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            channel.setAttribute(countkey, count);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    private static void decreaseInstanceCount(Channel channel, String countkey) {
        try {
            Integer count = (Integer) channel.getAttribute(countkey);
            if (count == null || count <= 0) {
                return;
            } else {
                count--;
            }
            channel.setAttribute(countkey, count);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static Object encodeInvocationArgument(Channel channel, RpcInvocation inv, int paraIndex) throws IOException {
        // get URL directly
        URL url = inv.getInvoker() == null ? null : inv.getInvoker().getUrl();
        byte callbackStatus = isCallBack(url, inv.getMethodName(), paraIndex);
        Object[] args = inv.getArguments();
        Class<?>[] pts = inv.getParameterTypes();
        switch (callbackStatus) {
            case CallbackServiceCodec.CALLBACK_NONE:
                return args[paraIndex];
            case CallbackServiceCodec.CALLBACK_CREATE:
                inv.setAttachment(INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, url, pts[paraIndex], args[paraIndex], true));
                return null;
            case CallbackServiceCodec.CALLBACK_DESTROY:
                inv.setAttachment(INV_ATT_CALLBACK_KEY + paraIndex, exportOrUnexportCallbackService(channel, url, pts[paraIndex], args[paraIndex], false));
                return null;
            default:
                return args[paraIndex];
        }
    }

    public static Object decodeInvocationArgument(Channel channel, RpcInvocation inv, Class<?>[] pts, int paraIndex, Object inObject) throws IOException {
        // if it's a callback, create proxy on client side, callback interface on client side can be invoked through channel
        // need get URL from channel and env when decode
        URL url = null;
        try {
            url = DubboProtocol.getDubboProtocol().getInvoker(channel, inv).getUrl();
        } catch (RemotingException e) {
            if (logger.isInfoEnabled()) {
                logger.info(e.getMessage(), e);
            }
            return inObject;
        }
        byte callbackstatus = isCallBack(url, inv.getMethodName(), paraIndex);
        switch (callbackstatus) {
            case CallbackServiceCodec.CALLBACK_NONE:
                return inObject;
            case CallbackServiceCodec.CALLBACK_CREATE:
                try {
                    return referOrDestroyCallbackService(channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), true);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    throw new IOException(StringUtils.toString(e));
                }
            case CallbackServiceCodec.CALLBACK_DESTROY:
                try {
                    return referOrDestroyCallbackService(channel, url, pts[paraIndex], inv, Integer.parseInt(inv.getAttachment(INV_ATT_CALLBACK_KEY + paraIndex)), false);
                } catch (Exception e) {
                    throw new IOException(StringUtils.toString(e));
                }
            default:
                return inObject;
        }
    }
}


text:
layout: post
title:  "Principios S.O.L.I.D"
date:   2011-03-14 11:00:04
published: true
categories: [conceptos y principios]
tags: [principios, poo]
comments: true
shortinfo: Conoceremos estos principios del desarrollo de software para crear sistemas óptimos.
---

Los principios **S.O.L.I.D** son un conjunto de guías que nos ayudan a _**evitar malos diseños**_ cuando desarrollamos software orientado a objetos. Estos principios fueron reunidos y expuestos por _Robert Martin_, también conocido como "El tío bob" en su libro _"Agile Software Development: Principles, Patterns, and Practices"_.

El buen uso de estos principios nos permite construir software extensible y fácil de mantener,  también nos permiten detectar lo que conocemos como _**code smell**_ de los cuales hablaremos después. El Sr. Martin nos habla también de 3 características importantes que deben ser evitadas en la construcción de nuestro software:

1. **Rigidez :** Al cambiar algo en el sistema, es necesario cambiar otras partes por estar muy acopladas.
2. **Fragilidad :** Al hacer un cambio en el sistema, otras partes que no esperábamos del mismo se rompen.
3. **Inmovilidad :** Dificultad para reutilizar cosas en otro sistema por ser difícil de desenredar del actual.

Si nuestro objetivo es desarrollar buen software no podemos perdernos de su conocimiento que junto con los patrones de diseño nos van a hacer la vida más fácil.

Estos principios son:

* **S**ingle Responsability Principle
* **O**pen / Close Principle
* **L**iskov Substitution Principle
* **I**nterface Segregation Principle
* **D**ependency Inversion Principle

Veamos rápidamente la definición de cada uno. En las próximas entradas los veremos con más detalle.

#### [Single Responsability Principle [Principio de Responsabilidad Simple]]({% post_url 2011-04-29-SOLID-principio-de-responsabilidad-simple %})
Una clase debe tener una sola razón para cambiar.

#### [Open / Close Principle [Principio Abierto / Cerrado]]({% post_url 2011-05-16-SOLID-principio-abierto-cerrado %})
Clases, módulos y funciones deben ser abierta para extender y cerrada para modificar.

#### Liskov Substitution Principle [Principio de Sustitución de Liskov]
Al usar una clase base los subtipos de esta pueden ser cambiados.

#### Interface Segregation Principle [Principio de Segregación de Interfaces]
Un cliente no debe estar obligado implementar Interfaces que no usa.

#### Dependency Inversion Principle [Principio de Inversión de Dependencias]
Módulos de alto nivel no deben depender de módulos de bajo nivel. Las dependencias entre estos deben ser sobre abstracciones no sobre clases concretas.

La buena aplicación de estos principios al comienzo no suele ser tan sencillo, puede tomar cierto tiempo mientras se acumula experiencia y se conoce más el paradigma de objetos. Además de otras ventajas significativas como código fácil de mantener y de testear.


text:
class CreateOmertaLoggerUserRankHistories < ActiveRecord::Migration
  def change
    create_table :omerta_logger_user_rank_histories do |t|
      t.datetime :date
      t.integer :rank
      t.references :user, index: true
    end
  end
end


text:
package divconq.web.dcui;

import java.io.PrintStream;

import w3.html.Form;
import divconq.util.StringUtil;
import divconq.web.WebContext;
import divconq.web.dcui.Nodes;
import divconq.xml.XElement;

public class AdvForm extends Form {
	protected String fname = null;
	protected String recordOrder = null;
	protected String recordMap = null;

    public AdvForm() {
    	super();
	}

    public AdvForm(Object... args) {
    	super(args);
	}

	@Override
	public void parseElement(WebContext ctx, Nodes nodes, XElement xel) {
		Attributes attrs = HtmlUtil.initAttrs(xel);

		if (xel.hasAttribute("Prefix"))
			attrs.add("Prefix", xel.getRawAttribute("Prefix"));

		if (xel.hasAttribute("AlwaysNew"))
			attrs.add("AlwaysNew", xel.getRawAttribute("AlwaysNew"));

		this.fname = xel.getAttribute("Name");

		if (xel.hasAttribute("RecordOrder"))
			this.recordOrder = xel.getRawAttribute("RecordOrder");

		if (xel.hasAttribute("RecordMap"))
			this.recordMap = xel.getRawAttribute("RecordMap");

        this.myArguments = new Object[] { attrs, ctx.getDomain().parseXml(ctx, xel) };

		nodes.add(this);

		//super.parseElement(view, nodes, xel);
	}

    @Override
    public boolean writeDynamic(PrintStream buffer, String tabs, boolean first) {
    	this.name = "Form";

    	this.attributes.put("Name", this.fname);		// only with dynamic, let stream appear as "form"

    	if (StringUtil.isNotEmpty(this.recordOrder))
        	this.attributes.put("RecordOrder", this.recordOrder);

    	if (StringUtil.isNotEmpty(this.recordMap))
        	this.attributes.put("RecordMap", this.recordMap);

    	return super.writeDynamic(buffer, tabs, first);
    }
}


text:
<WMS_Tile_Service version="0.1.0">
  <Service>
    <Name>OnEarth:WMS:Tile</Name>
    <Title>WMS Tile Service</Title>
    <Abstract>Tiled WMS service, tiled in a global grid</Abstract>
    <KeywordList>
      <Keyword>WMS</Keyword>
      <Keyword>Tile</Keyword>
      <Keyword>OnEarth</Keyword>
      <Keyword>Global</Keyword>
      <Keyword>Earth</Keyword>
    </KeywordList>
    <OnlineResource xlink:href="http://localhost/oe-status/" xlink:type="simple" xmlns:xlink="http://www.w3.orf/1999/xlink"/>
    <ContactInformation>
      <ContactPersonPrimary>
        <ContactPerson></ContactPerson>
        <ContactOrganization></ContactOrganization>
      </ContactPersonPrimary>
      <ContactElectronicMailAddress></ContactElectronicMailAddress>
    </ContactInformation>
    <Fees>none</Fees>
    <AccessConstraints>none</AccessConstraints>
  </Service>
</WMS_Tile_Service>


text:
using System.Data;

namespace IronFoundry.ServiceBroker.Models
{
    public interface IDatabaseBuilder
    {
        void CreateDatabase(string databaseName, Plan plan);
        Credentials CreateBinding(string databaseName, string bindingId, Plan plan);
        void RemoveBinding(string databaseName, string bindingId);
        void DropDatabase(string databaseName);
    }
}


text:
'use strict';
module.exports = function (grunt) {
	grunt.initConfig({
		dependencyCheck: {
			files: ['fixture/index.js'],
			options: {
				package: 'fixture'
			}
		}
	});

	grunt.loadTasks('tasks');

	grunt.registerTask('default', ['dependencyCheck']);

	var match = false;

	grunt.warn = function (str) {
		if (/Dependencies not listed/.test(str)) {
			match = true;
		}
	};

	process.on('exit', function () {
		if (!match) {
			process.exit(1);
		}
	});
};


text:
'use strict';

import type  {
  NavigationSceneRendererProps,
} from 'NavigationTypeDefinition';

/**
 * React component PropTypes Definitions. Consider using this as a supplementary
 * measure with `NavigationTypeDefinition`. This helps to capture the propType
 * error at run-time, where as `NavigationTypeDefinition` capture the flow
 * type check errors at build time.
 */

const Animated = require('react-native').Animated;
const React = require('react');

const {PropTypes} = React;

/* NavigationAction */
const action =  PropTypes.shape({
  type: PropTypes.string.isRequired,
});

/* NavigationAnimatedValue  */
const animatedValue = PropTypes.instanceOf(Animated.Value);

/* NavigationState  */
const navigationState = PropTypes.shape({
  key: PropTypes.string.isRequired,
});

/* NavigationParentState  */
const navigationParentState = PropTypes.shape({
  index: PropTypes.number.isRequired,
  key: PropTypes.string.isRequired,
  children: PropTypes.arrayOf(navigationState),
});

/* NavigationLayout */
const layout = PropTypes.shape({
  height: animatedValue,
  initHeight: PropTypes.number.isRequired,
  initWidth: PropTypes.number.isRequired,
  isMeasured: PropTypes.bool.isRequired,
  width: animatedValue,
});

/* NavigationScene */
const scene = PropTypes.shape({
  index: PropTypes.number.isRequired,
  isStale: PropTypes.bool.isRequired,
  key: PropTypes.string.isRequired,
  navigationState,
});

/* NavigationSceneRendererProps */
const SceneRendererProps = {
  layout: layout.isRequired,
  navigationState: navigationParentState.isRequired,
  onNavigate: PropTypes.func.isRequired,
  position: animatedValue.isRequired,
  scene: scene.isRequired,
  scenes: PropTypes.arrayOf(scene).isRequired,
};

const SceneRenderer = PropTypes.shape(SceneRendererProps);

/* NavigationPanPanHandlers */
const panHandlers = PropTypes.shape({
  onMoveShouldSetResponder: PropTypes.func.isRequired,
  onMoveShouldSetResponderCapture: PropTypes.func.isRequired,
  onResponderEnd: PropTypes.func.isRequired,
  onResponderGrant: PropTypes.func.isRequired,
  onResponderMove: PropTypes.func.isRequired,
  onResponderReject: PropTypes.func.isRequired,
  onResponderRelease: PropTypes.func.isRequired,
  onResponderStart: PropTypes.func.isRequired,
  onResponderTerminate: PropTypes.func.isRequired,
  onResponderTerminationRequest: PropTypes.func.isRequired,
  onStartShouldSetResponder: PropTypes.func.isRequired,
  onStartShouldSetResponderCapture: PropTypes.func.isRequired,
});

/**
 * Helper function that extracts the props needed for scene renderer.
 */
function extractSceneRendererProps(
  props: NavigationSceneRendererProps,
): NavigationSceneRendererProps {
  return {
    layout: props.layout,
    navigationState: props.navigationState,
    onNavigate: props.onNavigate,
    position: props.position,
    scene: props.scene,
    scenes: props.scenes,
  };
}

module.exports = {
  // helpers
  extractSceneRendererProps,

  // Bundled propTypes.
  SceneRendererProps,

  // propTypes
  action,
  navigationParentState,
  navigationState,
  panHandlers,
  SceneRenderer,
};


text:
from base import BasePlanner, PlanningError, ClonedPlanningMethod, UnsupportedPlanningError
import openravepy

class SBPLPlanner(BasePlanner):
    def __init__(self):
        super(SBPLPlanner, self).__init__()

        try:
            self.planner = openravepy.RaveCreatePlanner(self.env, 'SBPL')
        except openravepy.openrave_exception:
            raise UnsupportedPlanningError('Unable to create SBPL module')

    def setupEnv(self, env):
        self.env = env
        try:
            self.problem = openravepy.RaveCreateProblem(self.env, 'SBPL')
        except openravepy.openrave_exception:
            raise UnsupportedPlanningError('Unable to create SBPL module.')

    def __str__(self):
        return 'SBPL'

    def SetPlannerParameters(self, params_yaml):
        self.planner_params = params_yaml

    @ClonedPlanningMethod
    def PlanToBasePose(self, robot, goal_pose, timelimit=60.0, return_first=False, **kw_args):
        """
        Plan to a base pose using SBPL
        @param robot
        @param goal_pose desired base pose
        @param timelimit timeout in seconds
        @param return_first return the first path found (if true, the planner will run until a path is found, ignoring the time limit)
        """
        params = openravepy.Planner.PlannerParameters()

        from openravepy import DOFAffine
        robot.SetActiveDOFs([], DOFAffine.X | DOFAffine.Y | DOFAffine.RotationAxis)
        params.SetRobotActiveJoints(robot)

        config_spec = openravepy.RaveGetAffineConfigurationSpecification(DOFAffine.X | DOFAffine.Y | DOFAffine.RotationAxis, robot)
        #params.SetConfigurationSpecification(self.env, config_spec) # This breaks

        goal_config = openravepy.RaveGetAffineDOFValuesFromTransform(goal_pose,
                                                                     DOFAffine.X | DOFAffine.Y | DOFAffine.RotationAxis)

        params.SetGoalConfig(goal_config)

        # Setup default extra parameters
        extra_params = self.planner_params

        limits = robot.GetAffineTranslationLimits();
        extents = [limits[0][0], limits[1][0], limits[0][1], limits[1][1]];
        extra_params["extents"] = extents

        extra_params["timelimit"] = timelimit
        if return_first:
            extra_params["return_first"] = 1
        else:
            extra_params["return_first"] = 0

        extra_params["initial_eps"] = 1.0

        for key, value in kw_args.iteritems():
            extra_params[key] = value

        params.SetExtraParameters(str(extra_params))
        traj = openravepy.RaveCreateTrajectory(self.env, '')

        try:
            self.planner.InitPlan(robot, params)
            status = self.planner.PlanPath(traj, releasegil=True)

        except Exception as e:
            raise PlanningError('Planning failed with error: {0:s}'.format(e))

        from openravepy import PlannerStatus
        if status not in [ PlannerStatus.HasSolution, PlannerStatus.InterruptedWithSolution ]:
            raise PlanningError('Planner returned with status {0:s}.'.format(str(status)))

        return traj


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer-when-downgrade">

<title>retalls - La vista cansada</title>
<meta name="description" content="">

<link rel="alternate" type="application/rss+xml" href="https://carlesbellver.github.io/tags/retalls/index.xml" title="La vista cansada" />
<link rel="icon" type="image/x-icon" href="https://carlesbellver.github.io/favicon.ico">
<link rel="apple-touch-icon-precomposed" href="https://carlesbellver.github.io/favicon.png">

<link rel="stylesheet" href="https://carlesbellver.github.io/css/light.css?rnd=1602439751" />

<link rel="stylesheet" href="https://carlesbellver.github.io/css/style.css?rnd=1602439751" />

<meta property="og:title" content="retalls" />
<meta property="og:description" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://carlesbellver.github.io/tags/retalls/" />
<meta property="og:updated_time" content="2020-10-01T16:20:42+00:00" />

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="retalls"/>
<meta name="twitter:description" content=""/>

    Anar al contingut principal

    La vista cansada

        Informació

        Etiquetes

Etiqueta: retalls

        Totes les etiquetes

📎 System Fonts in CSS

…getting a feature into the spec is one thing and getting it into the browser is quite another. Luckily the adoption of system-ui has been quick.

2018-03-29

#retalls

📎 Every attempt to manage academia makes it worse

...tan bon punt intentes mesurar com de bé ho fa la gent, passaran a optimitzar tot allò que mesures, en lloc d'esforçar-se a fer de debò un bon treball.

2018-03-28

#retalls

📎 Redirect FB algorithms now and 4 lessons from Cambridge Analytica

... les correlacions tenen els seus mèrits científics (argh!), els humans es poden perfilar en només dotze "m'agrada", qualsevol mesurament es pot utilitzar contra nosaltres, i els professors semblen més ètics que els científics.

2018-03-28

#retalls

📎 We Cannot Build Peace on Empty Stomachs

John Boyd Orr, 1945. Al cap i a la fi, la fam és el més gran de tots els polítics.

2018-03-27

#retalls

📎 Bitcoin's Academic Pedigree

El concepte de les criptomonedes es basa en idees oblidades de la literatura científica. Bitcoin va resultar insòlit i reeixit no perquè cap dels seus elements se situés a l'avantguarda de la investigació, sinó perquè combinava idees antigues de molts camps anteriorment no relacionats entre ells.

2018-03-26

#retalls

📎 25 Years of EdTech: Learning objects

Per què van fallar els objectes d'aprenentatge?
 1) Sobreenginyeria 2) Debats semàntics 3) Paradoxa de reutilització 4) Manca de familiaritat.

2018-03-26

#retalls

📎 Monarquía como la belga o república como la helvética

Jaime Miquel, 2013. Espanya és un dels estats més antics del món, pero mai ha estat una nació.

2018-03-26

#retalls

📎 Jack el Destripador en Lavapiés

Así pues, como el fiscal Torres Dulce y el cineasta Garci supieron ver en su desahogo holmesiano sobre el acabamiento del Madrid decimonónico, también en Lavapiés, Jack el Destripador es emprendedor inmobiliario.

2018-03-25

#retalls

La informació que Facebook diu que té de tu

          Després de l'escàndol de Cambridge Analytica, l'última notícia que he llegit sobre les llibertats que Facebook es pren —i ens treu— és que ha recollit i mantingut un registre amb les nostres trucades, en els telèfons amb sistema operatiu Android, mentre tècnicament li ha estat possible (fins que Google ha anat ajustant i endurint els permisos de les aplicacions).

          Continua

2018-03-25

#retalls

📎 Facebook scraped call, text message data for years from Android phones

Si vau donar permís a Facebook per a accedir als vostres contactes abans de la versió d'Android 4.1, amb això també vau autoritzar l'accés al registre de trucades i missatges.

2018-03-25

#retalls

                articles posteriors

                articles anteriors

Carles Bellver Torlà

    <button class="theme-switcher">
        Tema fosc
    </button>