text:
require "spec_helper"
require "net/ssh"
require "net/ssh/multi"

describe Chef::Knife::Ssh do
  let(:query_result) { double("chef search results") }

  before do
    Chef::Config[:client_key] = CHEF_SPEC_DATA + "/ssl/private_key.pem"
    @knife = Chef::Knife::Ssh.new
    @knife.merge_configs
    @node_foo = {}
    @node_foo["fqdn"] = "foo.example.org"
    @node_foo["ipaddress"] = "10.0.0.1"
    @node_foo["cloud"] = {}

    @node_bar = {}
    @node_bar["fqdn"] = "bar.example.org"
    @node_bar["ipaddress"] = "10.0.0.2"
    @node_bar["cloud"] = {}

  end

  describe "#configure_session" do
    context "manual is set to false (default)" do
      before do
        @knife.config[:manual] = false
        allow(query_result).to receive(:search).with(any_args).and_yield(@node_foo).and_yield(@node_bar)
        allow(Chef::Search::Query).to receive(:new).and_return(query_result)
      end

      def self.should_return_specified_attributes
        it "returns an array of the attributes specified on the command line OR config file, if only one is set" do
          @node_bar["config"] = "10.0.0.2"
          @node_foo["config"] = "10.0.0.1"
          @knife.config[:attribute] = "ipaddress"
          Chef::Config[:knife][:ssh_attribute] = "ipaddress" # this value will be in the config file
          expect(@knife).to receive(:session_from_list).with([["10.0.0.1", nil], ["10.0.0.2", nil]])
          @knife.configure_session
        end

        it "returns an array of the attributes specified on the command line even when a config value is set" do
          @node_bar["config"] = "10.0.0.2"
          @node_foo["config"] = "10.0.0.1"
          Chef::Config[:knife][:ssh_attribute] = "config_file" # this value will be in the config file
          @knife.config[:attribute] = "ipaddress" # this is the value of the command line via #configure_attribute
          expect(@knife).to receive(:session_from_list).with([["10.0.0.1", nil], ["10.0.0.2", nil]])
          @knife.configure_session
        end
      end

      it "searchs for and returns an array of fqdns" do
        expect(@knife).to receive(:session_from_list).with([
          ["foo.example.org", nil],
          ["bar.example.org", nil],
        ])
        @knife.configure_session
      end

      should_return_specified_attributes

      context "when cloud hostnames are available" do
        before do
          @node_foo["cloud"]["public_hostname"] = "ec2-10-0-0-1.compute-1.amazonaws.com"
          @node_bar["cloud"]["public_hostname"] = "ec2-10-0-0-2.compute-1.amazonaws.com"
        end
        it "returns an array of cloud public hostnames" do
          expect(@knife).to receive(:session_from_list).with([
            ["ec2-10-0-0-1.compute-1.amazonaws.com", nil],
            ["ec2-10-0-0-2.compute-1.amazonaws.com", nil],
          ])
          @knife.configure_session
        end

        should_return_specified_attributes
      end

      context "when cloud hostnames are available but empty" do
        before do
          @node_foo["cloud"]["public_hostname"] = ""
          @node_bar["cloud"]["public_hostname"] = ""
        end

        it "returns an array of fqdns" do
          expect(@knife).to receive(:session_from_list).with([
            ["foo.example.org", nil],
            ["bar.example.org", nil],
          ])
          @knife.configure_session
        end

        should_return_specified_attributes
      end

      it "should raise an error if no host are found" do
        allow(query_result).to receive(:search).with(any_args)
        expect(@knife.ui).to receive(:fatal)
        expect(@knife).to receive(:exit).with(10)
        @knife.configure_session
      end

      context "when there are some hosts found but they do not have an attribute to connect with" do
        before do
          @node_foo["fqdn"] = nil
          @node_bar["fqdn"] = nil
        end

        it "should raise a specific error (CHEF-3402)" do
          expect(@knife.ui).to receive(:fatal).with(/^2 nodes found/)
          expect(@knife).to receive(:exit).with(10)
          @knife.configure_session
        end
      end
    end

    context "manual is set to true" do
      before do
        @knife.config[:manual] = true
      end

      it "returns an array of provided values" do
        @knife.instance_variable_set(:@name_args, ["foo.example.org bar.example.org"])
        expect(@knife).to receive(:session_from_list).with(["foo.example.org", "bar.example.org"])
        @knife.configure_session
      end
    end
  end

  describe "#get_ssh_attribute" do
    # Order of precedence for ssh target
    # 1) command line attribute
    # 2) configuration file
    # 3) cloud attribute
    # 4) fqdn
    before do
      Chef::Config[:knife][:ssh_attribute] = nil
      @knife.config[:attribute] = nil
      @node_foo["cloud"]["public_hostname"] = "ec2-10-0-0-1.compute-1.amazonaws.com"
      @node_bar["cloud"]["public_hostname"] = ""
    end

    it "should return fqdn by default" do
      expect(@knife.get_ssh_attribute({ "fqdn" => "fqdn" })).to eq("fqdn")
    end

    it "should return cloud.public_hostname attribute if available" do
      expect(@knife.get_ssh_attribute(@node_foo)).to eq("ec2-10-0-0-1.compute-1.amazonaws.com")
    end

    it "should favor to attribute_from_cli over config file and cloud" do
      @knife.config[:attribute] = "command_line"
      Chef::Config[:knife][:ssh_attribute] = "config_file"
      @node_foo["config"] = "command_line"
      @node_foo["knife_config"] = "config_file"
      expect( @knife.get_ssh_attribute(@node_foo)).to eq("command_line")
    end

    it "should favor config file over cloud and default" do
      Chef::Config[:knife][:ssh_attribute] = "config_file"
      @node_foo["knife_config"] = "config_file"
      expect( @knife.get_ssh_attribute(@node_foo)).to eq("config_file")
    end

    it "should return fqdn if cloud.hostname is empty" do
      expect( @knife.get_ssh_attribute(@node_bar)).to eq("bar.example.org")
    end
  end

  describe "#session_from_list" do
    before :each do
      @knife.instance_variable_set(:@longest, 0)
      ssh_config = { :timeout => 50, :user => "locutus", :port => 23 }
      allow(Net::SSH).to receive(:configuration_for).with("the.b.org", true).and_return(ssh_config)
    end

    it "uses the port from an ssh config file" do
      @knife.session_from_list([["the.b.org", nil]])
      expect(@knife.session.servers[0].port).to eq(23)
    end

    it "uses the port from a cloud attr" do
      @knife.session_from_list([["the.b.org", 123]])
      expect(@knife.session.servers[0].port).to eq(123)
    end

    it "defaults to a timeout of 120 seconds" do
      @knife.session_from_list([["the.b.org", nil]])
      expect(@knife.session.servers[0].options[:timeout]).to eq(120)
    end

    it "uses the timeout from Chef Config" do
      Chef::Config[:knife][:ssh_timeout] = 5
      @knife.config[:ssh_timeout] = nil
      @knife.session_from_list([["the.b.org", nil]])
      expect(@knife.session.servers[0].options[:timeout]).to eq(5)
    end

    it "uses the timeout from knife config" do
      @knife.config[:ssh_timeout] = 6
      @knife.session_from_list([["the.b.org", nil]])
      expect(@knife.session.servers[0].options[:timeout]).to eq(6)
    end

    it "uses the user from an ssh config file" do
      @knife.session_from_list([["the.b.org", 123]])
      expect(@knife.session.servers[0].user).to eq("locutus")
    end
  end

  describe "#ssh_command" do
    let(:execution_channel) { double(:execution_channel, :on_data => nil) }
    let(:session_channel) { double(:session_channel, :request_pty => nil) }

    let(:execution_channel2) { double(:execution_channel, :on_data => nil) }
    let(:session_channel2) { double(:session_channel, :request_pty => nil) }

    let(:session) { double(:session, :loop => nil) }

    let(:command) { "false" }

    before do
      expect(execution_channel).
        to receive(:on_request).
        and_yield(nil, double(:data_stream, :read_long => exit_status))

      expect(session_channel).
        to receive(:exec).
        with(command).
        and_yield(execution_channel, true)

      expect(execution_channel2).
        to receive(:on_request).
        and_yield(nil, double(:data_stream, :read_long => exit_status2))

      expect(session_channel2).
        to receive(:exec).
        with(command).
        and_yield(execution_channel2, true)

      expect(session).
        to receive(:open_channel).
        and_yield(session_channel).
        and_yield(session_channel2)
    end

    context "both connections return 0" do
      let(:exit_status) { 0 }
      let(:exit_status2) { 0 }

      it "returns a 0 exit code" do
        expect(@knife.ssh_command(command, session)).to eq(0)
      end
    end

    context "the first connection returns 1 and the second returns 0" do
      let(:exit_status) { 1 }
      let(:exit_status2) { 0 }

      it "returns a non-zero exit code" do
        expect(@knife.ssh_command(command, session)).to eq(1)
      end
    end

    context "the first connection returns 1 and the second returns 2" do
      let(:exit_status) { 1 }
      let(:exit_status2) { 2 }

      it "returns a non-zero exit code" do
        expect(@knife.ssh_command(command, session)).to eq(2)
      end
    end
  end

  describe "#run" do
    before do
      @query = Chef::Search::Query.new
      expect(@query).to receive(:search).and_yield(@node_foo)
      allow(Chef::Search::Query).to receive(:new).and_return(@query)
      allow(@knife).to receive(:ssh_command).and_return(exit_code)
      @knife.name_args = ["*:*", "false"]
    end

    context "with an error" do
      let(:exit_code) { 1 }

      it "should exit with a non-zero exit code" do
        expect(@knife).to receive(:exit).with(exit_code)
        @knife.run
      end
    end

    context "with no error" do
      let(:exit_code) { 0 }

      it "should not exit" do
        expect(@knife).not_to receive(:exit)
        @knife.run
      end
    end
  end

  describe "#configure_password" do
    before do
      @knife.config.delete(:ssh_password_ng)
      @knife.config.delete(:ssh_password)
    end

    context "when setting ssh_password_ng from knife ssh" do
      # in this case ssh_password_ng exists, but ssh_password does not
      it "should prompt for a password when ssh_passsword_ng is nil" do
        @knife.config[:ssh_password_ng] = nil
        expect(@knife).to receive(:get_password).and_return("mysekretpassw0rd")
        @knife.configure_password
        expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd")
      end

      it "should set ssh_password to false if ssh_password_ng is false" do
        @knife.config[:ssh_password_ng] = false
        expect(@knife).not_to receive(:get_password)
        @knife.configure_password
        expect(@knife.config[:ssh_password]).to be_falsey
      end

      it "should set ssh_password to ssh_password_ng if we set a password" do
        @knife.config[:ssh_password_ng] = "mysekretpassw0rd"
        expect(@knife).not_to receive(:get_password)
        @knife.configure_password
        expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd")
      end
    end

    context "when setting ssh_password from knife bootstrap / knife * server create" do
      # in this case ssh_password exists, but ssh_password_ng does not
      it "should set ssh_password to nil when ssh_password is nil" do
        @knife.config[:ssh_password] = nil
        expect(@knife).not_to receive(:get_password)
        @knife.configure_password
        expect(@knife.config[:ssh_password]).to be_nil
      end

      it "should set ssh_password to false when ssh_password is false" do
        @knife.config[:ssh_password] = false
        expect(@knife).not_to receive(:get_password)
        @knife.configure_password
        expect(@knife.config[:ssh_password]).to be_falsey
      end

      it "should set ssh_password to ssh_password if we set a password" do
        @knife.config[:ssh_password] = "mysekretpassw0rd"
        expect(@knife).not_to receive(:get_password)
        @knife.configure_password
        expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd")
      end
    end
    context "when setting ssh_password in the config variable" do
      before(:each) do
        Chef::Config[:knife][:ssh_password] = "my_knife_passw0rd"
      end
      context "when setting ssh_password_ng from knife ssh" do
        # in this case ssh_password_ng exists, but ssh_password does not
        it "should prompt for a password when ssh_passsword_ng is nil" do
          @knife.config[:ssh_password_ng] = nil
          expect(@knife).to receive(:get_password).and_return("mysekretpassw0rd")
          @knife.configure_password
          expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd")
        end

        it "should set ssh_password to the configured knife.rb value if ssh_password_ng is false" do
          @knife.config[:ssh_password_ng] = false
          expect(@knife).not_to receive(:get_password)
          @knife.configure_password
          expect(@knife.config[:ssh_password]).to eq("my_knife_passw0rd")
        end

        it "should set ssh_password to ssh_password_ng if we set a password" do
          @knife.config[:ssh_password_ng] = "mysekretpassw0rd"
          expect(@knife).not_to receive(:get_password)
          @knife.configure_password
          expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd")
        end
      end

      context "when setting ssh_password from knife bootstrap / knife * server create" do
        # in this case ssh_password exists, but ssh_password_ng does not
        it "should set ssh_password to the configured knife.rb value when ssh_password is nil" do
          @knife.config[:ssh_password] = nil
          expect(@knife).not_to receive(:get_password)
          @knife.configure_password
          expect(@knife.config[:ssh_password]).to eq("my_knife_passw0rd")
        end

        it "should set ssh_password to the configured knife.rb value when ssh_password is false" do
          @knife.config[:ssh_password] = false
          expect(@knife).not_to receive(:get_password)
          @knife.configure_password
          expect(@knife.config[:ssh_password]).to eq("my_knife_passw0rd")
        end

        it "should set ssh_password to ssh_password if we set a password" do
          @knife.config[:ssh_password] = "mysekretpassw0rd"
          expect(@knife).not_to receive(:get_password)
          @knife.configure_password
          expect(@knife.config[:ssh_password]).to eq("mysekretpassw0rd")
        end
      end
    end
  end
end


text:
use std::cell::Cell;

fn main() {
    unsafe {
        let root0 = Cell::new(42);
        let wildcard = &root0 as *const Cell<i32> as usize as *const Cell<i32>;
        // empty the stack to unknown (via SRW reborrow from wildcard)
        let _ref0 = &*wildcard;
        // Do a non-SRW reborrow from wildcard to start building up a stack again.
        // Now new refs start being inserted at idx 0, pushing the unique_range up.
        let _refn = &*&*&*&*&*(wildcard.cast::<i32>());
        // empty the stack again, but this time with unique_range.start sitting at some high index.
        let _ref0 = &*wildcard;
        // and do a read which tries to clear the uniques
        wildcard.cast::<i32>().read();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<md-toolbar color="primary">

{{ title + '.name' | translate }}

</md-toolbar>

  <md-card class="card">
    <form #cardForm="ngForm" (ngSubmit)="encrypt()">
      <md-card-content>
        <md-input-container class="full-width">
          <textarea class="textarea-vertical" mdInput placeholder="{{ 'app.inputText' | translate }}"
                    [(ngModel)]="text" name="inputText" required>
          </textarea>
        </md-input-container>
        <md-input-container class="full-width mb20">
          <textarea class="textarea-vertical" mdInput placeholder="{{ 'cesarWithKey.inputKey' | translate }}"
                    [(ngModel)]="key" name="key" required>
          </textarea>
        </md-input-container>
        <md-select class="full-width mb20" placeholder="{{ 'app.chooseAlphabet' | translate }}"
                   [(ngModel)]="alphabet" name="alphabet" required>
          <md-option *ngFor="let alphabet of alphabets" [value]="alphabet.name">
            {{ 'alphabets.'+ alphabet.name | translate }}
          </md-option>
        </md-select>
        <md-input-container class="full-width">
          <textarea class="textarea-vertical" mdInput [disabled]="!encryptedText">{{encryptedText}}</textarea>
        </md-input-container>
      </md-card-content>
      <md-card-actions class="ml0">
        <button md-button type="submit" [disabled]="cardForm.form.invalid">{{ 'app.encode' | translate }}</button>
      </md-card-actions>
    </form>
  </md-card>


text:
#region Copyright (c) 2013 Jens Thiel, http://thielj.github.io/MetroFramework

#endregion

/**************************************************************************************

                        GENERATED FILE - DO NOT EDIT

 **************************************************************************************/

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;

// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable PossibleNullReferenceException

namespace MetroFramework.Controls
{

	/**************************************************************************************

							GENERATED FILE - DO NOT EDIT

	 **************************************************************************************/

    #region MetroCheckBox

    public partial class MetroCheckBox
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroLabel

    public partial class MetroLabel
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroLink

    public partial class MetroLink
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroRadioButton

    public partial class MetroRadioButton
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroSelectableLabel

    public partial class MetroSelectableLabel
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroTabControl

    public partial class MetroTabControl
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroTextBox

    public partial class MetroTextBox
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroToggle

    public partial class MetroToggle
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

    #region MetroTrackBar

    public partial class MetroTrackBar
    {

		/**************************************************************************************
									GENERATED FILE - DO NOT EDIT
		 **************************************************************************************/

		private bool _useStyleColors = false;
        [DefaultValue(false)]
        [Category(MetroDefaults.CatAppearance)]
        public bool UseStyleColors
        {
            get { return _useStyleColors; } set { _useStyleColors = value; Invalidate(); }
        }

		[Conditional("DEBUG")]
		private void UseStyleColor()
		{
			// nothing
		}

        public override Color EffectiveForeColor
        {
            get { return ShouldSerializeForeColor() || !UseStyleColors || MetroControlState != "Normal" ? base.EffectiveForeColor : GetStyleColor(); }
        }

    }

    #endregion

}


text:
layout: post
date: 2009-02-06
time: "09:00:00"
author: "Greg Wilson"
title: Sharing Data Isn't That Easy
category: ["Content", "Noticed"]
---

Interesting post from Systeme D called "ShareAlike considered harmful" (for geo data, anyway).  I should give this to my students and ask them to think it through...


text:
<?php

declare(strict_types=1);

namespace Tomaj\NetteApi\Test\Response;

use Nette\Http\Request;
use Nette\Http\Response;
use Nette\Http\UrlScript;
use PHPUnit\Framework\TestCase;
use Tomaj\NetteApi\Response\JsonApiResponse;

class JsonApiResponseTest extends TestCase
{
    public function testCreatingResponse()
    {
        $jsonResponse = new JsonApiResponse(200, ['asdasd' => 'asdsd']);
        $this->assertEquals(200, $jsonResponse->getCode());

        $this->expectOutputString('{"asdasd":"asdsd"}');
        $jsonResponse->send(new Request(new UrlScript()), new Response());
    }
}


text:
"""Fichier contenant l'action pratiquer_talent."""

from primaires.format.fonctions import supprimer_accents
from primaires.scripting.action import Action
from primaires.scripting.instruction import ErreurExecution

class ClasseAction(Action):

    """Fait pratiquer un talent à un personnage.

    Contrairement à l'action 'enseigner_talent', cette action se
    base sur la difficulté d'apprentissage d'un talent pour
    "l'apprendre naturellement". Si l'apprentissage réussit, le
    personnage verra le message "Vous progressez dans
    l'apprentissage du talent...".

    """

    @classmethod
    def init_types(cls):
        cls.ajouter_types(cls.pratiquer_talent, "Personnage", "str")
        cls.ajouter_types(cls.pratiquer_talent, "Personnage", "str", "Fraction")

    @staticmethod
    def pratiquer_talent(personnage, nom_talent, probabilite=1):
        """Fait pratiquer le talent au personnage spécifié.

        Paramètres à entrer :

          * personnage : le personnage à qui l'on veut enseigner le talent
          * nom_talent : le nom du talent, sous la forme d'une chaîne
          * probabilite (optionnelle) : un nombre influençant l'apprentissage.

        La probabilité est un nombre entre 0 et 1 qui affecte
        l'apprentissage du talent. La probabilité par défaut
        est de 1. Si la probabilité est plus faible, apprendre
        le talent devient plus difficile. Par exemple, une
        probabilité de 1/2 (0.5) rend l'apprentissage deux fois
        plus difficile. Il est parfois utile de faire varier la
        difficulté de l'apprentissage d'un talent (par exemple,
        en fonction de la qualité des actions réussies par le
        personnage).

        Exemple d'utilisation :

          pratiquer_talent personnage "apprivoisement"
          # Le personnage va peut-être apprendre le talent
          pratiquer_talent personnage "apprivoisement" 1/3
          # C'est trois fois moins probable

        """
        nom_talent = supprimer_accents(nom_talent).lower()
        cle = None
        talent = None
        for t_talent in importeur.perso.talents.values():
            if supprimer_accents(t_talent.nom) == nom_talent:
                talent = t_talent
                cle = talent.cle
                break

        if talent is None:
            raise ErreurExecution("talent inconnu : {}".format(repr(
                    nom_talent)))

        personnage.pratiquer_talent(cle, 1 / float(probabilite))


text:
 0">

Mis cursos

    <input type="text" ng-model="searchText" placeholder="Buscar curso" />

 0">

{{ enrollment.course.title }}

 0">

    Aún no has adquirido un curso. Ver catálogo.


text:
package pmem

import (
	"bytes"
	"io"
	"io/ioutil"
	"reflect"
	"sync"
	"unsafe"
)

const pageSize = 4096

// Mem represents a section of memory that is usable by the DMA controller.
//
// Since this is physically allocated memory, that could potentially have been
// allocated in spite of OS consent, for example by asking the GPU directly, it
// is important to call Close() before process exit.
type Mem interface {
	io.Closer
	// Bytes returns the user space memory mapped buffer address as a slice of
	// bytes.
	//
	// It is the raw view of the memory from this process.
	Bytes() []byte
	// AsPOD initializes a pointer to a POD (plain old data) to point to the
	// memory mapped region.
	//
	// pp must be a pointer to:
	//
	// - pointer to a base size type (uint8, int64, float32, etc)
	// - struct
	// - array of the above
	// - slice of the above
	//
	// and the value must be nil. Returns an error otherwise.
	//
	// If a pointer to a slice is passed in, it is initialized to the length and
	// capacity set to the maximum number of elements this slice can represent.
	//
	// The pointer initialized points to the same address as Bytes().
	AsPOD(pp interface{}) error
	// PhysAddr is the physical address. It can be either 32 bits or 64 bits,
	// depending on the bitness of the OS kernel, not on the user mode build,
	// e.g. you could have compiled on a 32 bits Go toolchain but running on a
	// 64 bits kernel.
	PhysAddr() uint64
}

// MemAlloc represents contiguous physically locked memory that was allocated.
//
// The memory is mapped in user space.
//
// MemAlloc implements Mem.
type MemAlloc struct {
	View
}

// Close unmaps the physical memory allocation.
func (m *MemAlloc) Close() error {
	if err := munlock(m.orig); err != nil {
		return err
	}
	return munmap(m.orig)
}

// Alloc allocates a continuous chunk of physical memory.
//
// Size must be rounded to 4Kb. Allocations of 4Kb will normally succeed.
// Allocations larger than 64Kb will likely fail due to kernel memory
// fragmentation; rebooting the host or reducing the number of running programs
// may help.
//
// The allocated memory is uncached.
func Alloc(size int) (*MemAlloc, error) {
	if size == 0 || size&(pageSize-1) != 0 {
		return nil, wrapf("allocated memory must be rounded to %d bytes", pageSize)
	}
	if isLinux && !isWSL() {
		return allocLinux(size)
	}
	return nil, wrapf("memory allocation is not supported on this platform")
}

//

var (
	wslOnce    sync.Once
	isWSLValue bool
)

// uallocMemLocked allocates user space memory and requests the OS to have the
// chunk to be locked into physical memory.
func uallocMemLocked(size int) ([]byte, error) {
	// It is important to write to the memory so it is forced to be present.
	b, err := uallocMem(size)
	if err == nil {
		for i := range b {
			b[i] = 0
		}
		if err := mlock(b); err != nil {
			// Ignore the unmap error.
			_ = munmap(b)
			return nil, wrapf("locking %d bytes failed: %v", size, err)
		}
	}
	return b, err
}

// allocLinux allocates physical memory and returns a user view to it.
func allocLinux(size int) (*MemAlloc, error) {
	// TODO(maruel): Implement the "shotgun approach". Allocate a ton of 4Kb
	// pages and lock them. Then look at their physical pages and only keep the
	// one useful. Then create a linear mapping in memory to simplify the user
	// mode with a single linear user space virtual address but keep the
	// individual page alive with their initial allocation. When done release
	// each individual page.
	if size > pageSize {
		return nil, wrapf("large allocation is not yet implemented")
	}
	// First allocate a chunk of user space memory.
	b, err := uallocMemLocked(size)
	if err != nil {
		return nil, err
	}
	pages := make([]uint64, (size+pageSize-1)/pageSize)
	// Figure out the physical memory addresses.
	for i := range pages {
		pages[i], err = virtToPhys(toRaw(b[pageSize*i:]))
		if err != nil {
			return nil, err
		}
		if pages[i] == 0 {
			return nil, wrapf("failed to read page %d", i)
		}
	}
	for i := 1; i < len(pages); i++ {
		// Fail if the memory is not contiguous.
		if pages[i] != pages[i-1]+pageSize {
			return nil, wrapf("failed to allocate %d bytes of continugous physical memory; page %d =0x%x; page %d=0x%x", size, i, pages[i], i-1, pages[i-1])
		}
	}

	return &MemAlloc{View{Slice: b, phys: pages[0], orig: b}}, nil
}

// virtToPhys returns the physical memory address backing a virtual
// memory address.
func virtToPhys(virt uintptr) (uint64, error) {
	physPage, err := ReadPageMap(virt)
	if err != nil {
		return 0, err
	}
	if physPage&(1<<63) == 0 {
		// If high bit is not set, the page doesn't exist.
		return 0, wrapf("0x%08x has no physical address", virt)
	}
	// Strip flags. See linux documentation on kernel.org for more details.
	physPage &^= 0x1FF << 55
	return physPage * pageSize, nil
}

func toRaw(b []byte) uintptr {
	header := *(*reflect.SliceHeader)(unsafe.Pointer(&b))
	return header.Data
}

// isWSL returns true if running under Windows Subsystem for Linux.
func isWSL() bool {
	wslOnce.Do(func() {
		if c, err := ioutil.ReadFile("/proc/sys/kernel/osrelease"); err == nil {
			isWSLValue = bytes.Contains(c, []byte("Microsoft"))
		}
	})
	return isWSLValue
}

var _ Mem = &MemAlloc{}


text:
//-----------------------------------------------------------------------------
// <copyright file="FtpConfigInfo.cs" company="WheelMUD Development Team">
//   Copyright (c) WheelMUD Development Team.  See LICENSE.txt.  This file is
//   subject to the Microsoft Public License.  All other rights reserved.
// </copyright>
// //
//   Created: June 16, 2010 by Fastalanasa.
//
//-----------------------------------------------------------------------------

namespace WheelMUD.Ftp
{
    /// FTP configuration information class.
    public class FtpConfigInfo
    {
        /// Gets or sets the server root folder.
        public string ServerRootFolder { get; set; }
    }
}


text:
'use strict';

const { join, sep } = require('path');
const Promise = require('bluebird');
const File = require('./file');
const { Pattern, createSha1Hash } = require('hexo-util');
const { createReadStream, readdir, stat, watch } = require('hexo-fs');
const { magenta } = require('picocolors');
const { EventEmitter } = require('events');
const { isMatch, makeRe } = require('micromatch');

const defaultPattern = new Pattern(() => ({}));

class Box extends EventEmitter {
  constructor(ctx, base, options) {
    super();

    this.options = Object.assign({
      persistent: true,
      awaitWriteFinish: {
        stabilityThreshold: 200
      }
    }, options);

    if (!base.endsWith(sep)) {
      base += sep;
    }

    this.context = ctx;
    this.base = base;
    this.processors = [];
    this._processingFiles = {};
    this.watcher = null;
    this.Cache = ctx.model('Cache');
    this.File = this._createFileClass();
    let targets = this.options.ignored || [];
    if (ctx.config.ignore && ctx.config.ignore.length) {
      targets = targets.concat(ctx.config.ignore);
    }
    this.ignore = targets;
    this.options.ignored = targets.map(s => toRegExp(ctx, s)).filter(x => x);
  }
  _createFileClass() {
    const ctx = this.context;

    class _File extends File {
      render(options) {
        return ctx.render.render({
          path: this.source
        }, options);
      }

      renderSync(options) {
        return ctx.render.renderSync({
          path: this.source
        }, options);
      }
    }

    _File.prototype.box = this;

    return _File;
  }

  addProcessor(pattern, fn) {
    if (!fn && typeof pattern === 'function') {
      fn = pattern;
      pattern = defaultPattern;
    }

    if (typeof fn !== 'function') throw new TypeError('fn must be a function');
    if (!(pattern instanceof Pattern)) pattern = new Pattern(pattern);

    this.processors.push({
      pattern,
      process: fn
    });
  }

  _readDir(base, prefix = '') {
    const results = [];
    return readDirWalker(base, results, this.ignore, prefix)
      .return(results)
      .map(path => this._checkFileStatus(path))
      .map(file => this._processFile(file.type, file.path).return(file.path));
  }

  _checkFileStatus(path) {
    const { Cache, context: ctx } = this;
    const src = join(this.base, path);

    return Cache.compareFile(
      escapeBackslash(src.substring(ctx.base_dir.length)),
      () => getHash(src),
      () => stat(src)
    ).then(result => ({
      type: result.type,
      path
    }));
  }

  process(callback) {
    const { base, Cache, context: ctx } = this;

    return stat(base).then(stats => {
      if (!stats.isDirectory()) return;

      // Check existing files in cache
      const relativeBase = escapeBackslash(base.substring(ctx.base_dir.length));
      const cacheFiles = Cache.filter(item => item._id.startsWith(relativeBase)).map(item => item._id.substring(relativeBase.length));

      // Handle deleted files
      return this._readDir(base)
        .then(files => cacheFiles.filter(path => !files.includes(path)))
        .map(path => this._processFile(File.TYPE_DELETE, path));
    }).catch(err => {
      if (err && err.code !== 'ENOENT') throw err;
    }).asCallback(callback);
  }

  _processFile(type, path) {
    if (this._processingFiles[path]) {
      return Promise.resolve();
    }

    this._processingFiles[path] = true;

    const { base, File, context: ctx } = this;

    this.emit('processBefore', {
      type,
      path
    });

    return Promise.reduce(this.processors, (count, processor) => {
      const params = processor.pattern.match(path);
      if (!params) return count;

      const file = new File({
        source: join(base, path),
        path,
        params,
        type
      });

      return Reflect.apply(Promise.method(processor.process), ctx, [file])
        .thenReturn(count + 1);
    }, 0).then(count => {
      if (count) {
        ctx.log.debug('Processed: %s', magenta(path));
      }

      this.emit('processAfter', {
        type,
        path
      });
    }).catch(err => {
      ctx.log.error({err}, 'Process failed: %s', magenta(path));
    }).finally(() => {
      this._processingFiles[path] = false;
    }).thenReturn(path);
  }

  watch(callback) {
    if (this.isWatching()) {
      return Promise.reject(new Error('Watcher has already started.')).asCallback(callback);
    }

    const { base } = this;

    function getPath(path) {
      return escapeBackslash(path.substring(base.length));
    }

    return this.process().then(() => watch(base, this.options)).then(watcher => {
      this.watcher = watcher;

      watcher.on('add', path => {
        this._processFile(File.TYPE_CREATE, getPath(path));
      });

      watcher.on('change', path => {
        this._processFile(File.TYPE_UPDATE, getPath(path));
      });

      watcher.on('unlink', path => {
        this._processFile(File.TYPE_DELETE, getPath(path));
      });

      watcher.on('addDir', path => {
        let prefix = getPath(path);
        if (prefix) prefix += '/';

        this._readDir(path, prefix);
      });
    }).asCallback(callback);
  }

  unwatch() {
    if (!this.isWatching()) return;

    this.watcher.close();
    this.watcher = null;
  }

  isWatching() {
    return Boolean(this.watcher);
  }
}

function escapeBackslash(path) {
  // Replace backslashes on Windows
  return path.replace(/\\/g, '/');
}

function getHash(path) {
  const src = createReadStream(path);
  const hasher = createSha1Hash();

  const finishedPromise = new Promise((resolve, reject) => {
    src.once('error', reject);
    src.once('end', resolve);
  });

  src.on('data', chunk => { hasher.update(chunk); });

  return finishedPromise.then(() => hasher.digest('hex'));
}

function toRegExp(ctx, arg) {
  if (!arg) return null;
  if (typeof arg !== 'string') {
    ctx.log.warn('A value of "ignore:" section in "_config.yml" is not invalid (not a string)');
    return null;
  }
  const result = makeRe(arg);
  if (!result) {
    ctx.log.warn('A value of "ignore:" section in "_config.yml" can not be converted to RegExp:' + arg);
    return null;
  }
  return result;
}

function isIgnoreMatch(path, ignore) {
  return path && ignore && ignore.length && isMatch(path, ignore);
}

function readDirWalker(base, results, ignore, prefix) {
  if (isIgnoreMatch(base, ignore)) return Promise.resolve();

  return Promise.map(readdir(base).catch(err => {
    if (err && err.code === 'ENOENT') return [];
    throw err;
  }), async path => {
    const fullpath = join(base, path);
    const stats = await stat(fullpath);
    const prefixdPath = `${prefix}${path}`;
    if (stats.isDirectory()) {
      return readDirWalker(fullpath, results, ignore, `${prefixdPath}/`);
    }
    if (!isIgnoreMatch(fullpath, ignore)) {
      results.push(prefixdPath);
    }
  });
}

module.exports = Box;


text:
package com.bitdubai.sub_app.intra_user.preference_settings;

import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantGetDefaultLanguageException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantGetDefaultSkinException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantLoadWalletSettings;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantSaveWalletSettings;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantSetDefaultLanguageException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantSetDefaultSkinException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.interfaces.SubAppSettings;

import java.util.UUID;

/**
 * Created by mati on 2015.08.24..
 */
public class IntraUserPreferenceSettings implements SubAppSettings {
    /**
     * This method let us know the default language of a wallet
     *
     * @return the identifier of the default language of the wallet
     * @throws CantGetDefaultLanguageException
     */
    @Override
    public UUID getDefaultLanguage() throws CantGetDefaultLanguageException {
        //TODO METODO CON RETURN NULL - OJO: solo INFORMATIVO de ayuda VISUAL para DEBUG - Eliminar si molesta
        return null;
    }

    /**
     * This method let us know the default skin of a wallet
     *
     * @return the identifier of the default skin of the wallet
     * @throws CantGetDefaultSkinException
     */
    @Override
    public UUID getDefaultSkin() throws CantGetDefaultSkinException {
        //TODO METODO CON RETURN NULL - OJO: solo INFORMATIVO de ayuda VISUAL para DEBUG - Eliminar si molesta
        return null;
    }

    /**
     * This method let us set the default language for a wallet
     *
     * @param languageId the identifier of the language to set as default
     * @throws CantSetDefaultLanguageException
     */
    @Override
    public void setDefaultLanguage(UUID languageId) throws CantSetDefaultLanguageException {
        //TODO METODO NO IMPLEMENTADO AUN - OJO: solo INFORMATIVO de ayuda VISUAL para DEBUG - Eliminar si molesta
    }

    /**
     * This method let us set the default skin for a wallet
     *
     * @param skinId the identifier of the skin to set as default
     * @throws CantSetDefaultSkinException
     */
    @Override
    public void setDefaultSkin(UUID skinId) throws CantSetDefaultSkinException {
        //TODO METODO NO IMPLEMENTADO AUN - OJO: solo INFORMATIVO de ayuda VISUAL para DEBUG - Eliminar si molesta
    }

    /**
     * This method let us set the preference settings for a wallet
     *
     * @param walletPreferenceSettings
     * @param walletPublicKey
     * @throws CantSetDefaultSkinException
     */
    @Override
    public void setPreferenceSettings(String walletPreferenceSettings, String walletPublicKey) throws CantSaveWalletSettings {
        //TODO METODO NO IMPLEMENTADO AUN - OJO: solo INFORMATIVO de ayuda VISUAL para DEBUG - Eliminar si molesta
    }

    /**
     * This method let us get the preference settings for a wallet
     *
     * @param walletPublicKey
     * @return preference settings of a wallet
     * @throws CantGetDefaultSkinException
     */
    @Override
    public String getPreferenceSettings(String walletPublicKey) throws CantLoadWalletSettings {
        //TODO METODO CON RETURN NULL - OJO: solo INFORMATIVO de ayuda VISUAL para DEBUG - Eliminar si molesta
        return null;
    }
}


text:
from mldb import mldb, MldbUnitTest, ResponseException

class MLDB1907ValueDescriptionError(MldbUnitTest):  # noqa

    @classmethod
    def setUpClass(cls):
        pass

    def test_value_desc_on_wrong_params(self):
        with self.assertRaisesRegex(ResponseException,
                                     'Binding builtin function sqrt: expected 1 argument, got 2'):
            mldb.query("select sqrt(2, NULL)")

        with self.assertRaisesRegex(ResponseException,
                                     'Binding builtin function sqrt: expected 1 argument, got 2'):
            mldb.query("select sqrt(2, 1)")

if __name__ == '__main__':
    mldb.run_tests()


text:
(function(window, document) { 'use strict';

require.config({
    waitSeconds: 30,
    baseUrl : '/app/',
    paths: {
        'ngCookies' : 'libs/angular-cookies/angular-cookies.min',
        'diacritics': 'libs/diacritic/diacritics',
        'text'      : 'libs/requirejs-text/text'

        // loaded from Bch.UI.ngView c# module
        //'jquery'    : 'libs/jquery/dist/jquery.min',
        //'lodash'    : 'libs/lodash/lodash.min',
        //'angular'   : 'libs/angular-flex/angular-flex',
        //'ngRoute'   : 'libs/angular-route/angular-route.min',
        //'ngSanitize': 'libs/angular-sanitize/angular-sanitize.min',
    },
    shim: {
        'ngCookies' : { deps: ['angular'] }

        // loaded from Bch.UI.ngView c# module
        //'angular'              : { deps: ['libs/angular/angular.min'] },
        //'libs/angular/angular' : { deps: ['jquery'] },
        //'ngRoute'              : { deps: ['angular'] },
        //'ngSanitize'           : { deps: ['angular'] },
    }
});

// Define module loaded from Bch.UI.ngView c# module;

if (!require.defined('jquery'))     { define('jquery',     [],          function()   { return window.$; }); }
if (!require.defined('lodash'))     { define('lodash',     [],          function()   { return window._; }); }
if (!require.defined('angular'))    { define('angular',    [],          function()   { return window.angular; }); }
if (!require.defined('ngRoute'))    { define('ngRoute',    ['angular'], function(ng) { return ng.module('ngRoute'); }); }
if (!require.defined('ngSanitize')) { define('ngSanitize', ['angular'], function(ng) { return ng.module('ngSanitize'); }); }

// BOOT
require(['angular', 'app', 'routes'], function(ng, app) {
    ng.element(document).ready(function(){
        ng.bootstrap(document, [app.name]);
    });
});

})(window, document);

// MISC

//==================================================
// Fix IE Console
// Protect window.console method calls, e.g. console is not defined on IE
// unless dev tools are open, and IE doesn't define console.debug
//==================================================
(function(a){a.console||(a.console={});for(var c="log info warn error debug trace dir group groupCollapsed groupEnd time timeEnd profile profileEnd dirxml assert count markTimeline timeStamp clear".split(" "),d=function(){},b=0;b<c.length;b++)a.console[c[b]]||(a.console[c[b]]=d)})(window); //jshint ignore:line


text:
package org.apache.apex.malhar.lib.state.spillable.inmem;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import org.apache.apex.malhar.lib.state.spillable.Spillable;

import com.google.common.collect.Lists;

/**
 * An in memory implementation of the {@link Spillable.SpillableArrayList} interface.
 * @param <T> The type of the data stored in the {@link InMemSpillableArrayList}
 */
public class InMemSpillableArrayList<T> implements Spillable.SpillableArrayList<T>
{
  private List<T> list = Lists.newArrayList();

  @Override
  public int size()
  {
    return list.size();
  }

  @Override
  public boolean isEmpty()
  {
    return list.isEmpty();
  }

  @Override
  public boolean contains(Object o)
  {
    return list.contains(o);
  }

  @Override
  public Iterator<T> iterator()
  {
    return list.iterator();
  }

  @Override
  public Object[] toArray()
  {
    return list.toArray();
  }

  @Override
  public <T1> T1[] toArray(T1[] t1s)
  {
    return list.toArray(t1s);
  }

  @Override
  public boolean add(T t)
  {
    return list.add(t);
  }

  @Override
  public boolean remove(Object o)
  {
    return list.remove(o);
  }

  @Override
  public boolean containsAll(Collection<?> collection)
  {
    return list.containsAll(collection);
  }

  @Override
  public boolean addAll(Collection<? extends T> collection)
  {
    return list.addAll(collection);
  }

  @Override
  public boolean addAll(int i, Collection<? extends T> collection)
  {
    return list.addAll(i, collection);
  }

  @Override
  public boolean removeAll(Collection<?> collection)
  {
    return list.removeAll(collection);
  }

  @Override
  public boolean retainAll(Collection<?> collection)
  {
    return list.retainAll(collection);
  }

  @Override
  public void clear()
  {
    list.clear();
  }

  @Override
  public T get(int i)
  {
    return list.get(i);
  }

  @Override
  public T set(int i, T t)
  {
    return list.set(i, t);
  }

  @Override
  public void add(int i, T t)
  {
    list.add(i, t);
  }

  @Override
  public T remove(int i)
  {
    return list.remove(i);
  }

  @Override
  public int indexOf(Object o)
  {
    return list.indexOf(o);
  }

  @Override
  public int lastIndexOf(Object o)
  {
    return list.lastIndexOf(o);
  }

  @Override
  public ListIterator<T> listIterator()
  {
    return list.listIterator();
  }

  @Override
  public ListIterator<T> listIterator(int i)
  {
    return list.listIterator(i);
  }

  @Override
  public List<T> subList(int i, int i1)
  {
    return list.subList(i, i1);
  }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Validation_callables extends MY_Model {

	/**
	 * undocumented method
	 */
	public function __construct()
	{
		parent::__construct();

		$this->config->load('examples/password_strength');
	}

	// -----------------------------------------------------------------------

	/**
	 * Check the supplied password strength.
	 * Please keep in mind that this is a very rudimentary way to check
	 * password strength. Some devs may consider rolling their own solution,
	 * or possibly using something like zxcvbn instead. Zxcvbn is available
	 * at https://github.com/dropbox/zxcvbn
	 *
	 * @param   string  the supplied password
	 * @return  mixed   bool
	 */
	public function _check_password_strength( $password )
	{
		// Password length
		$max = config_item('max_chars_for_password') > 0
			? config_item('max_chars_for_password')
			: '';
		$regex = '(?=.{' . config_item('min_chars_for_password') . ',' . $max . '})';
		$error = '
Minimal ' . config_item('min_chars_for_password') . ' karakter
';

		if( config_item('max_chars_for_password') > 0 )
                    $error .= '
tidak lebih dari ' . config_item('max_chars_for_password') . ' karakter
';

		// Digit(s) required
		if( config_item('min_digits_for_password') > 0 )
		{
                    $regex .= '(?=(?:.*[0-9].*){' . config_item('min_digits_for_password') . ',})';
                    $plural = config_item('min_digits_for_password') > 1 ? 's' : '';
                    $error .= '
' . config_item('min_digits_for_password') . ' angka' . $plural . '
';
		}

		// Lower case letter(s) required
		if( config_item('min_lowercase_chars_for_password') > 0 )
		{
                    $regex .= '(?=(?:.*[a-z].*){' . config_item('min_lowercase_chars_for_password') . ',})';
                    $plural = config_item('min_lowercase_chars_for_password') > 1 ? 's' : '';
                    $error .= '
' . config_item('min_lowercase_chars_for_password') . ' huruf kecil' . $plural . '
';
		}

		// Upper case letter(s) required
		if( config_item('min_uppercase_chars_for_password') > 0 )
		{
                    $regex .= '(?=(?:.*[A-Z].*){' . config_item('min_uppercase_chars_for_password') . ',})';
                    $plural = config_item('min_uppercase_chars_for_password') > 1 ? 's' : '';
                    $error .= '
' . config_item('min_uppercase_chars_for_password') . ' huruf besar' . $plural . '
';
		}

		// Non-alphanumeric char(s) required
		if( config_item('min_non_alphanumeric_chars_for_password') > 0 )
		{
                    $regex .= '(?=(?:.*[^a-zA-Z0-9].*){' . config_item('min_non_alphanumeric_chars_for_password') . ',})';
                    $plural = config_item('min_non_alphanumeric_chars_for_password') > 1 ? 's' : '';
                    $error .= '
' . config_item('min_non_alphanumeric_chars_for_password') . ' non-alphanumeric character' . $plural . '
';
		}

		if( preg_match( '/^' . $regex . '.*$/', $password ) )
		{
                    return TRUE;
		}

		$this->form_validation->set_message(
                    '_check_password_strength',
                    'Password harus memiliki:

                                ' . $error . '

                    '
		);

		return FALSE;
	}

	// --------------------------------------------------------------

}

/* End of file Validaton_callables.php */
/* Location: /community_auth/models/examples/Validation_callables.php */


text:
<html>
<body style='text-align:center'>
<img src='icon.png' />
La da dada da dee daddaaaaa
</body>
</html>


text:
namespace EntityFunctors.Extensions
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;

    public static class TypeExtensions
    {
        //a thread-safe way to hold default instances created at run-time
        private static readonly ConcurrentDictionary<Type, object> TypeDefaults = new ConcurrentDictionary<Type, object>();

        public static object GetDefaultValue(this Type type)
        {
            return type.IsValueType ? TypeDefaults.GetOrAdd(type, Activator.CreateInstance) : null;
        }

        public static ConstantExpression GetDefaultExpression(this Type type)
        {
            return Expression.Constant(type.GetDefaultValue(), type);
        }

        public static Type GetItemType(this Type enumerableType)
        {
            var target =
                enumerableType
                .GetInterfaces()
                .Union(new[] {enumerableType})
                .FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>));

            if (target == null)
                throw new ArgumentException(string.Format("Type {0} doesn't implement IEnumerable<T>", enumerableType.Name));

            return target.GetGenericArguments()[0];
        }

        public static bool TryGetItemType(this Type candidate, out Type itemType)
        {
            itemType = null;

            var target =
                candidate
                .GetInterfaces()
                .Union(new[] { candidate })
                .FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>));

            if (target != null)
                itemType = target.GetGenericArguments()[0];

            return itemType != null;
        }
    }
}


text:
<?php
// Copyright (c) 2010 The Fajr authors (see AUTHORS).
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file in the project root directory.

/**
 * Contains class that runs callback on destruction.
 *
 * @package    Libfajr
 * @subpackage Base
 * @author     Peter Perešíni <ppershing+fajr@gmail.com>
 * @filesource
 */
namespace libfajr\base;

/**
 * Closure class represents "cleaner". It is used to run callbacks
 * in its own destruction.
 *
 * Warnings: Be careful with references to ClosureRunner
 * (otherwise it may be destroyed at unpredictable times)
 * and also note, that if you pass class callback to ClosureRunner,
 * the class won't be destroyed before ClosureRunner.
 *
 * Example usage:
 * <code>
 * <?php
 * function do_something_with_object() {
 *  $closure = new ClosureRunner(array($this, 'cleanInternalState'),
 *                               some, arguments, to, cleanInternalState')
 *  $closure2 = new ClosureRunner('end_session');
 *  now do heavy work with possible exceptions, returns and other magic
 * }
 *
 * do_something_with_object();
 * // $this->cleanInternalState(some,arguments,to,cleanInternalState') and
 * // end_session() will be called automatically whatever you do
 * ?>
 * </code>
 */
class ClosureRunner
{
  /** @var array $args arguments to the callback */
  private $args = null;

  /** @var callback $callback */
  private $callback = null;

  /**
   * Construct the closure
   *
   * @param callback      $callback function to call on destruction
   * @param argument_list $var_args arguments to pass to closure callback
   */
  public function __construct($callback)
  {
    $this->callback = $callback;
    $this->args = func_get_args();
    // Warning: we can't call func_get_args as a parameter to array_shift!
    array_shift($this->args);
  }

  /**
   * Destructor. Runs the callback.
   */
  public function __destruct()
  {
    call_user_func_array($this->callback, $this->args);
  }

}


text:
<?php
require_once __DIR__ . '/bootstrap.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app->before(function () use ($app) {
    foreach ($app['config']['location'] as $path) {
        if (!is_dir($path)) {
            throw new \Exception("There was an issue loading the content. Is your content location correct?");
        }
    }
});

$app->mount('/', new Chula\ControllerProvider\HomePage());

$app->mount(
    '/' . $app['config']['admin_path'],
    new Chula\ControllerProvider\Admin()
);

$app->mount(
    '/{page}',
    new Chula\ControllerProvider\Loader()
);

$app->mount(
    '/' . $app['config']['admin_path'] . '/new',
    new Chula\ControllerProvider\NewPage()
);

$app->mount(
    '/' . $app['config']['admin_path'] . '/delete',
    new Chula\ControllerProvider\DeletePage()
);

$app->mount(
    '/' . $app['config']['admin_path'] . '/edit',
    new Chula\ControllerProvider\EditPage()
);

$app->mount(
    '/' . $app['config']['admin_path'] . '/publish',
    new Chula\ControllerProvider\PublishDraft()
);

$app->get(
    '/login',
    function (Request $request) use ($app) {
        return $app['twig']->render(
            'admin_login.twig',
            array(
              'error'         => $app['security.last_error']($request),
              'last_username' => $app['session']->get('_security.last_username'),
            )
        );
    }
);

$app->error(function (\Exception $e, $code) use ($app) {
    switch ($code) {
        case 404:
            $message = 'Those monkeys couldn\'t find the page you were after, hard luck.';
            return $app['twig']->render('user_404.twig', array('message' => $message));
            break;
        default:
            $message = $e->getMessage();
            return $app['twig']->render('user_error.twig', array('message' => $message));
    }
});

$app->run();


text:
<?php

namespace DvsaMotTest\ViewModel\MotTestCertificate;

class VehicleTable
{
    const SINGLE_OLDER_TEST_TEXT = '1 older test';
    const MANY_OLDER_TESTS_TEXT = '%s older tests';

    private $registration;
    private $vin;
    private $make;
    private $model;
    private $firstTest;
    private $olderTests;
    private $olderTestsCount = 0;
    private $index = 0;

    /**
     * @param string $registration
     */
    public function setRegistration($registration)
    {
        $this->registration = $registration;
    }

    /**
     * @return string
     */
    public function getRegistration()
    {
        return $this->registration;
    }

    /**
     * @return string
     */
    public function getVin()
    {
        return $this->vin;
    }

    /**
     * @param string $vin
     */
    public function setVin($vin)
    {
        $this->vin = $vin;
    }

    /**
     * @return string
     */
    public function getMakeAndModel()
    {
        return sprintf('%s, %s', $this->make, $this->model);
    }

    /**
     * @param string $make
     */
    public function setMake($make)
    {
        $this->make = $make;
    }

    public function getMake()
    {
        return $this->make;
    }

    /**
     * @param string $model
     */
    public function setModel($model)
    {
        $this->model = $model;
    }

    public function getModel()
    {
        return $this->model;
    }

    /**
     * @param MotTestCertificateTableItem $test
     */
    public function addRow(MotTestCertificateTableItem $test)
    {
        if ($this->firstTest == null) {
            $this->firstTest = $test;
        } else {
            $this->olderTests[] = $test;
            ++$this->olderTestsCount;
        }
    }

    /**
     * @return MotTestCertificateTableItem[]
     */
    public function getOlderTests()
    {
        return $this->olderTests;
    }

    public function getAllTests()
    {
        yield $this->firstTest;

        foreach ($this->olderTests as $olderTest) {
            yield $olderTest;
        }
    }

    public function getTotalTestCount()
    {
        return ($this->firstTest ? 1 : 0) + $this->olderTestsCount;
    }

    public function areThereOlderTests()
    {
        return $this->olderTestsCount > 0;
    }

    public function getOlderTestsSplitText()
    {
        return $this->olderTestsCount == 1 ?
            self::SINGLE_OLDER_TEST_TEXT
            : sprintf(self::MANY_OLDER_TESTS_TEXT, $this->olderTestsCount);
    }

    /**
     * @return MotTestCertificateTableItem
     */
    public function getFirstTest()
    {
        return $this->firstTest;
    }

    /**
     * @return int
     */
    public function getIndex()
    {
        return $this->index;
    }

    /**
     * @return string
     */
    public function getToggleTableClassName()
    {
        return 'toggle-table-'.$this->getIndex();
    }

    /**
     * @param int $index
     */
    public function setIndex($index)
    {
        $this->index = $index;
    }
}


text:
/**
 * Contains {@code AggregateOperation} and its several variants, as well
 * as a builder object for the aggregate operations.
 *
 * @since 3.0
 */
package com.hazelcast.jet.aggregate;


text:
import ToObject = require('../2016/ToObject');
export = ToObject;


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Mike Day (mdday@us.ibm.com)
//
// Modified By: Mary Hinton (m.hinton@verizon.net)
//              Sushma Fernandes (sushma_fernandes@hp.com)
//              Yi Zhou, Hewlett-Packard Company (yi_zhou@hp.com)
//              Tony Fiorentino (fiorentino_tony@emc.com)
//              Roger Kumpf, Hewlett-Packard Company (roger_kumpf@hp.com)
//              Steve Hills (steve.hills@ncr.com)
//              Josephine Eskaline Joyce, IBM (jojustin@in.ibm.com) - Bug#2032, 2031
//
//%/////////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <process.h>    /* _beginthread, _endthread */
#include <tchar.h>
#include <direct.h>
#include <Pegasus/Common/MessageLoader.h> //l10n
#include <Pegasus/Common/Thread.h>  // l10n
#include <Pegasus/Server/CIMServer.h>

#include "Service.cpp"

PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;

static const char* _ALREADY_RUNNING_NAME = 0;

//-------------------------------------------------------------------------
// GLOBALS
//-------------------------------------------------------------------------
static Mutex _cimserverLock;
static ServerProcess* _server_proc = 0;
static bool _shutdown = false;
static Service pegasus_service;
static HANDLE pegasus_service_event = NULL;
static LPCSTR g_cimservice_key  = TEXT("SYSTEM\\CurrentControlSet\\Services\\%s");
static LPCSTR g_cimservice_home = TEXT("home");
static int g_argc = 0;
static char **g_argv = 0;

//  Constants representing the command line options.
static const char OPTION_INSTALL[] = "install";
static const char OPTION_REMOVE[]  = "remove";
static const char OPTION_START[]   = "start";
static const char OPTION_STOP[]    = "stop";

//-------------------------------------------------------------------------
// PROTOTYPES
//-------------------------------------------------------------------------
int cimserver_windows_main(int flag, int argc, char **argv);
static bool _getRegInfo(const char *lpchKeyword, char *lpchRetValue);
static bool _setRegInfo(const char *lpchKeyword, const char *lpchValue);

//-------------------------------------------------------------------------
// NO-OPs for windows platform
//-------------------------------------------------------------------------
int ServerProcess::cimserver_fork(void) { return(0); }
void ServerProcess::notify_parent(int id) { return; }
long ServerProcess::get_server_pid(void) { return 0; }
void ServerProcess::set_parent_pid(int pid) {}
int ServerProcess::get_proc(int pid) { return 0; }
int ServerProcess::cimserver_kill(int id) { return(0); }
void cimserver_exitRC(int rc) {}
int ServerProcess::cimserver_initialize(void) { return 0; }
int ServerProcess::cimserver_wait(void) { return 0; }

//-------------------------------------------------------------------------
// Helper for platform specific handling
//-------------------------------------------------------------------------

ServerProcess::ServerProcess()
{
    //be sure to call cimserver_set_process right after instantiating this in order for everything to work
}

ServerProcess::~ServerProcess()
{
}

void ServerProcess::cimserver_set_process(void* p)
{
    AutoMutex am( _cimserverLock );
    _server_proc = static_cast<ServerProcess *>(p);
    if(_server_proc && _shutdown)
        _server_proc->cimserver_stop();

    pegasus_service = Service(getProcessName());
    _ALREADY_RUNNING_NAME = getProcessName();
}

void signal_shutdown()
{
    AutoMutex am( _cimserverLock );
    _shutdown = true;
    if( _server_proc )
        _server_proc->cimserver_stop();
}

//-------------------------------------------------------------------------
// Run main server asynchronously
//-------------------------------------------------------------------------
static unsigned __stdcall cimserver_windows_thread( void* parm )
{
    int argc = 0;
    int rc = _server_proc->cimserver_run( g_argc, g_argv, false );
    SetEvent(pegasus_service_event);
    _endthreadex( rc );
    return rc;
}

//-------------------------------------------------------------------------
//  Windows NT Service Control Code
//-------------------------------------------------------------------------

//-------------------------------------------------------------------------
// START/STOP handler
//-------------------------------------------------------------------------
int cimserver_windows_main(int flag, int argc, char *argv[])
{
    switch( flag )
    {
    case Service::STARTUP_FLAG:
    {
        //
        // Start up main run in a separate thread and wait for it to finish.
        //

        unsigned threadid = 0;
        g_argc = argc;
        g_argv = argv;
        HANDLE hThread = (HANDLE)_beginthreadex( NULL, 0, cimserver_windows_thread, NULL, 0, &threadid );
        if( hThread == NULL )
            return 1;

        WaitForSingleObject( pegasus_service_event, INFINITE );

        //
        // Shutdown the cimserver.
        //

        signal_shutdown();

        //
        // Make sure we upate the SCM that our stop is pending.
        // Wait for the main run thread to exit.
        //

        DWORD dwCheckPoint = 1; // service code should have already started at 0

        while( WaitForSingleObject( hThread, 3000 ) == WAIT_TIMEOUT )
        {
            pegasus_service.report_status(
                SERVICE_STOP_PENDING, NO_ERROR, dwCheckPoint++, 5000 );
        }

        CloseHandle( hThread );

        break;
    }
    case Service::SHUTDOWN_FLAG:
        SetEvent(pegasus_service_event);
        break;

    default:
        break;
    }

    return 0;
}

//-------------------------------------------------------------------------
// IS RUNNING?
//-------------------------------------------------------------------------

class AlreadyRunning
{
public:
    AlreadyRunning(): alreadyRunning( true ), event( NULL )
    {
    }
    ~AlreadyRunning()
    {
        if( event != NULL )
            CloseHandle( event );
    }

    void Init()
    {
        if( event == NULL )
        {
            event = CreateEvent( NULL, TRUE, TRUE, _ALREADY_RUNNING_NAME );
            if( event != NULL && GetLastError() != ERROR_ALREADY_EXISTS )
                alreadyRunning = false;
        }
    }

    bool IsAlreadyRunning()
    {
        return alreadyRunning;
    }

    bool alreadyRunning;
    HANDLE event;
};

AlreadyRunning _alreadyRunning;

Boolean ServerProcess::isCIMServerRunning(void)
{
    //Service::State state;
    //pegasus_service.GetState(&state);
    //return (state == Service::SERVICE_STATE_RUNNING) ? true : false;

    // We do it this way so this will work when run as a
    // console process and a Windows service.
    AlreadyRunning ar;
    ar.Init();
    return ar.IsAlreadyRunning();
}

//-------------------------------------------------------------------------
// INSTALL
//-------------------------------------------------------------------------
bool cimserver_install_nt_service(char *service_name)
{
  Service::ReturnCode status = Service::SERVICE_RETURN_SUCCESS;
  char filename[_MAX_PATH] = {0};
  char displayname[_MAX_PATH] = {0};
  char descriptionname[_MAX_PATH] = {0};

  // If service name is specified, override default
  if (service_name == NULL)
    {
      strcpy(displayname, _server_proc->getExtendedName());
    }
  else
    {
      pegasus_service.SetServiceName(service_name);
      sprintf(displayname, "%s - %s", _server_proc->getExtendedName(), service_name);
    }

  strcpy(descriptionname, _server_proc->getDescription());

  if(0 != GetModuleFileName(NULL, filename, sizeof(filename)))
  {
     status = pegasus_service.Install(displayname, descriptionname, filename);

     // Upon success, set home in registry
     if (status == Service::SERVICE_RETURN_SUCCESS)
     {
      char pegasus_homepath[_MAX_PATH];
      System::extract_file_path(filename, pegasus_homepath);
      pegasus_homepath[strlen(pegasus_homepath)-1] = '\0';
      strcpy(filename, pegasus_homepath);
      System::extract_file_path(filename, pegasus_homepath);
      pegasus_homepath[strlen(pegasus_homepath)-1] = '\0';
      _setRegInfo(g_cimservice_home, pegasus_homepath);
     }
  }
  else
  {
    status = (Service::ReturnCode) GetLastError();
  }
  return (status == Service::SERVICE_RETURN_SUCCESS) ? true : false;
}

//-------------------------------------------------------------------------
// REMOVE
//-------------------------------------------------------------------------
bool cimserver_remove_nt_service(char *service_name)
{
  Service::ReturnCode status = Service::SERVICE_RETURN_SUCCESS;

  // If service name is specified, override default
  if (service_name != NULL)
    {
      pegasus_service.SetServiceName(service_name);
    }

  status = pegasus_service.Remove();

  return (status == Service::SERVICE_RETURN_SUCCESS) ? true : false;
}

//-------------------------------------------------------------------------
// START
//-------------------------------------------------------------------------
bool cimserver_start_nt_service(char *service_name, int num_args, char **service_args)
{
  Service::ReturnCode status = Service::SERVICE_RETURN_SUCCESS;

  // If service name is specified, override default
  if (service_name != NULL)
    {
      pegasus_service.SetServiceName(service_name);
    }

  if(num_args > 0 && service_args != NULL)
  {
      pegasus_service.SetServiceArgs(num_args, service_args);
  }

  status = pegasus_service.Start(5);

  return (status == Service::SERVICE_RETURN_SUCCESS) ? true : false;
}

//-------------------------------------------------------------------------
// STOP
//-------------------------------------------------------------------------
bool cimserver_stop_nt_service(char *service_name)
{
  Service::ReturnCode status = Service::SERVICE_RETURN_SUCCESS;

  // If service name is specified, override default
  if (service_name != NULL)
    {
      pegasus_service.SetServiceName(service_name);
    }

  status = pegasus_service.Stop(5);

  return (status == Service::SERVICE_RETURN_SUCCESS) ? true : false;
}

//-------------------------------------------------------------------------
// HELPER Utilities
//-------------------------------------------------------------------------
static bool _getRegInfo(const char *lpchKeyword, char *lpchRetValue)
{
  HKEY   hKey;
  DWORD  dw                   = _MAX_PATH;
  char   subKey[_MAX_PATH]    = {0};

  sprintf(subKey, g_cimservice_key, pegasus_service.GetServiceName());

  if ((RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                    subKey,
                    0,
                    KEY_READ,
                    &hKey)) != ERROR_SUCCESS)
    {
      return false;
    }

  if ((RegQueryValueEx(hKey,
                       lpchKeyword,
                       NULL,
                       NULL,
                       (LPBYTE)lpchRetValue,
                       &dw)) != ERROR_SUCCESS)
    {
      RegCloseKey(hKey);
      return false;
    }

  RegCloseKey(hKey);

  return true;
}

static bool _setRegInfo(const char *lpchKeyword, const char *lpchValue)
{
  HKEY   hKey;
  DWORD  dw                   = _MAX_PATH;
  char   home_key[_MAX_PATH]  = {0};
  char   subKey[_MAX_PATH]    = {0};

  if (lpchKeyword == NULL || lpchValue == NULL)
    return false;

  sprintf(subKey, g_cimservice_key, pegasus_service.GetServiceName());

  if ((RegCreateKeyEx (HKEY_LOCAL_MACHINE,
                      subKey,
                      0,
                      NULL,
                      0,
                      KEY_ALL_ACCESS,
                      NULL,
                      &hKey,
                      NULL) != ERROR_SUCCESS))
    {
      return false;
    }

  if ((RegSetValueEx(hKey,
                     lpchKeyword,
                     0,
                     REG_SZ,
                     (CONST BYTE *)lpchValue,
                     (DWORD)(strlen(lpchValue)+1))) != ERROR_SUCCESS)
    {
      RegCloseKey(hKey);
      return false;
    }

  RegCloseKey(hKey);

  return true;
}

//void ServerProcess::setHome(const String& home)
String ServerProcess::getHome(void)
{
    String home = String::EMPTY;

  // Determine the absolute path to the running program
  char exe_pathname[_MAX_PATH] = {0};
  char home_pathname[_MAX_PATH] = {0};
  if(0 != GetModuleFileName(NULL, exe_pathname, sizeof(exe_pathname)))
  {

    // Pegasus home search rules:
    // - look in registry (if set)
    // - if not found, look in PEGASUS_HOME (if set)
    // - if not found, use exe directory minus one level

    bool found_reg = _getRegInfo("home", home_pathname);
    if (found_reg == true)
      {
        // Make sure home matches
        String current_home(home_pathname);
        String current_exe(exe_pathname);
        current_home.toLower();
        current_exe.toLower();

        Uint32 pos = current_exe.find(current_home);
        if (pos != PEG_NOT_FOUND)
          {
            home = home_pathname;
          }
        else
          {
            found_reg = false;
          }
      }
    if (found_reg == false)
      {
        const char* tmp = getenv("PEGASUS_HOME");
        if (tmp)
          {
            home = tmp;
          }
        else
          {
            // ASSUMPTION: At a minimum, the cimserver program is running
            // from a "bin" directory
            home = FileSystem::extractFilePath(exe_pathname);
            home.remove(home.size()-1, 1);
            home = FileSystem::extractFilePath(home);
            home.remove(home.size()-1, 1);
          }
      }
  }
    return home;
}

//
// Our console control handler
//

static BOOL WINAPI ControlHandler( DWORD dwCtrlType )
{
    switch( dwCtrlType )
    {
    case CTRL_BREAK_EVENT:  // use Ctrl+C or Ctrl+Break to simulate
    case CTRL_C_EVENT:      // SERVICE_CONTROL_STOP in debug mode
    {
        signal_shutdown();
        return TRUE;
    }
    }
    return FALSE;
}

//
// Platform specific run
//

int ServerProcess::platform_run( int argc, char** argv, Boolean shutdownOption )
{
    //
    // Check for my command line options
    //

    for( int i = 1; i < argc; )
    {
        const char* arg = argv[i];

        // Check for -option
        if (*arg == '-')
        {
            // Get the option
            const char* option = arg + 1;

            if (strcmp(option, OPTION_INSTALL) == 0)
            {
                //
                // Install as a NT service
                //
                char *opt_arg = NULL;
                if (i+1 < argc)
                {
                    opt_arg = argv[i+1];

                }
                if(cimserver_install_nt_service(opt_arg))
                {
                    //l10n
                    //cout << "\nPegasus installed as NT Service";
                    MessageLoaderParms parms(
                        "src.Server.cimserver.INSTALLED_NT_SERVICE",
                        "\nPegasus installed as a Windows service");
                    cout << MessageLoader::getMessage(parms) << endl;
                    exit(0);
                }
                else
                {
                    exit(0);
                }
            }
            else if (strcmp(option, OPTION_REMOVE) == 0)
            {
                //
                // Remove Pegasus as an NT service
                //
                char *opt_arg = NULL;
                if (i+1 < argc)
                {
                    opt_arg = argv[i+1];
                }
                if(cimserver_remove_nt_service(opt_arg))
                {
                    //l10n
                    //cout << "\nPegasus removed as NT Service";
                    MessageLoaderParms parms(
                        "src.Server.cimserver.REMOVED_NT_SERVICE",
                        "\nPegasus removed as a Windows service");
                    cout << MessageLoader::getMessage(parms) << endl;
                    exit(0);
                }
                else
                {
                    exit(0);
                }

            }
            else if (strcmp(option, OPTION_START) == 0)
            {
                //
                // Start as a NT service
                //
                char *opt_arg = NULL;
                int num_args = 0;
                if (i+1 < argc)
                {
                    opt_arg = argv[i+1];
                    num_args = argc - 3;
                }
                else
                {
                    num_args = argc - 2;
                }

                char **service_args = &argv[1];
                if(cimserver_start_nt_service(opt_arg, num_args, service_args))
                {
                    //l10n
                    //cout << "\nPegasus started as NT Service";
                    MessageLoaderParms parms(
                        "src.Server.cimserver.STARTED_NT_SERVICE",
                        "\nPegasus started as a Windows service");
                    cout << MessageLoader::getMessage(parms) << endl;
                    exit(0);
                }
                else
                {
                    exit(0);
                }
            }
            else if (strcmp(option, OPTION_STOP) == 0)
            {
                //
                // Stop as a NT service
                //
                char *opt_arg = NULL;
                if (i+1 < argc)
                {
                    opt_arg = argv[i+1];
                }
                if(cimserver_stop_nt_service(opt_arg))
                {
                    //l10n
                    //cout << "\nPegasus stopped as NT Service";
                    MessageLoaderParms parms(
                        "src.Server.cimserver.STOPPED_NT_SERVICE",
                        "\nPegasus stopped as a Windows service");
                    cout << MessageLoader::getMessage(parms) << endl;
                    exit(0);
                }
                else
                {
                    exit(0);
                }
            }
            else
                i++;
        }
        else
            i++;
    }

    //
    // Signal ourself as running
    //

    if( !shutdownOption )
        _alreadyRunning.Init();

    //
    // Check if already running
    //
    // Hmm, when starting as a service, should we do this here (before
    // starting the control dispatcher)?  If we do then the SCM reports
    // a dumb message to the user.  If we don't, and it in the serviceProc
    // then the service will start up then die silently.
    //

    if( !shutdownOption && _alreadyRunning.IsAlreadyRunning() )
    {
        MessageLoaderParms parms(
            "src.Server.cimserver.UNABLE_TO_START_SERVER_ALREADY_RUNNING",
            "Unable to start CIMServer.\nCIMServer is already running." );
        Logger::put(
            Logger::ERROR_LOG, "CIMServer", Logger::SEVERE,
            MessageLoader::getMessage(parms) );
        PEGASUS_STD(cerr) << MessageLoader::getMessage(parms) << PEGASUS_STD(endl);
        return 1;
    }

    //
    // Check if running from a console window. If so then just run
    // as a console process.
    //

    char console_title[ _MAX_PATH ] = {0};
    if( GetConsoleTitle( console_title, _MAX_PATH ) > 0 )
    {
        SetConsoleCtrlHandler( ControlHandler, TRUE );

        return cimserver_run( argc, argv, shutdownOption );
    }

    //
    // Run as a service
    //

    pegasus_service_event = CreateEvent( NULL, FALSE, FALSE, NULL );

    Service::ReturnCode status;
    status = pegasus_service.Run( cimserver_windows_main );

    if( status != Service::SERVICE_RETURN_SUCCESS )
    {
        // todo: put into localized messages when messages unfreezes.
        Logger::put_l(
            Logger::ERROR_LOG, "CIMServer", Logger::SEVERE,
            "src.Server.cimserver_windows.LISTENING_ON_HTTP_PORT",
            "Error during service run: code = $0.", status );
        return 1;
    }

    return 0;
}


text:
@interface RHAudioMessage : RHMessageData

@property (nonatomic, copy) NSString *audioUrl;

@end


text:
package com.logginghub.utils.sof;

import com.logginghub.utils.StringUtils;

public class SofUnknownTypeException extends SofException {
    private static final long serialVersionUID = 1L;
    private int version;
    private int length;
    private int flags;
    private int type;
    private int fields;

    public SofUnknownTypeException(int version, int length, int flags, int type, int fields) {
        this.version = version;
        this.length = length;
        this.flags = flags;
        this.type = type;
        this.fields = fields;
    }

    public String getHeaderSummary() {
        return StringUtils.format("[type={} version={} length={} flags={} fields={}]", type, version, length, flags, fields);
    }

    public int getVersion() {
        return version;
    }

    public int getFields() {
        return fields;
    }

    public int getFlags() {
        return flags;
    }

    public int getLength() {
        return length;
    }

    public int getType() {
        return type;
    }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMapelsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('mapels', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name',20)->unique();
            $table->string('fullname',100)->unique();
            $table->string('image')->nullable();
            $table->char('colour',6)->nullable();
            $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('mapels');
    }
}