text:
using EloBuddy;
using EloBuddy.SDK;
using EloBuddy.SDK.Events;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Menu.Values;
using System;
using System.Collections.Generic;
using System.Linq;
using EloBuddy.SDK.Rendering;
using System.Text;
using System.Threading.Tasks;
using static EloBuddy.SDK.Geometry.Polygon;
using Color = System.Drawing.Color;

namespace Ark_Yi
{
    class Program
    {
        public static Spell.Targeted Q;
        public static Spell.Active W, E, R;
        public static Spell.Active Wc;
        public static AIHeroClient _player = Player.Instance;
        public static Item tiamat, botrk, cutlass, ghostblade, hydra;
        public static Menu RootMenu, ComboMenu, KsMenu;
        static void Main(string[] args)
        {
            Loading.OnLoadingComplete += OnLoadingComplete;
        }
        public static
            void OnLoadingComplete(EventArgs args)
        {
            if (_player.ChampionName != "MasterYi") return;

            Chat.Print("Ark-Yi Loaded successfully", Color.Purple);

            Q = new Spell.Targeted(SpellSlot.Q, 600);
            W = new Spell.Active(SpellSlot.W);
            E = new Spell.Active(SpellSlot.E);
            R = new Spell.Active(SpellSlot.R);

            Wc = new Spell.Active(SpellSlot.W);

            tiamat = new Item(ItemId.Tiamat_Melee_Only, 400);
            botrk = new Item(ItemId.Blade_of_the_Ruined_King);
            cutlass = new Item(ItemId.Bilgewater_Cutlass);
            ghostblade = new Item(ItemId.Youmuus_Ghostblade);
            hydra = new Item(ItemId.Ravenous_Hydra_Melee_Only, 400);

            RootMenu = MainMenu.AddMenu("Ark-Yi", "Ark-Yi");
            ComboMenu = RootMenu.AddSubMenu("Combo", "Combo");
            ComboMenu.Add("useQ", new CheckBox("Use Q"));
            ComboMenu.Add("useW", new CheckBox("Use W"));
            ComboMenu.Add("autoW", new Slider("Use w automatically if Hp(%) <=", 25, 0, 100));
            ComboMenu.Add("useE", new CheckBox("Use E"));
            ComboMenu.Add("useR", new ComboBox("Use R", 0, "Never", "Always", "Number of Enemies"));
            ComboMenu.Add("Rcount", new Slider("Number of Enemies for R", 3, 0, 5));
            ComboMenu.Add("reicombo", new CheckBox("Use Botrk/Cutlass on Combo"));
            ComboMenu.Add("tiamatcombo", new CheckBox("Use Tiamat/Hydra on Combo"));
            ComboMenu.Add("ghostbladeR", new CheckBox("Cast Ghostblade with R"));
            ComboMenu.AddSeparator();
            ComboMenu.Add("drawQ", new CheckBox("Draw Q"));
            ComboMenu.AddSeparator();
            ComboMenu.AddLabel("Jungle Clear");
            ComboMenu.Add("ejg", new CheckBox("E Jungle Clear"));
            ComboMenu.Add("qjg", new CheckBox("Q Jungle Clear"));
            ComboMenu.Add("qmanajg", new Slider("Min. Mana Q/E", 35, 0, 100));
            KsMenu = RootMenu.AddSubMenu("KsMenu", "KsMenu");
            KsMenu.Add("reiks", new CheckBox("Use Botrk/Cutlass for ks"));
            KsMenu.Add("hydraks", new CheckBox("Use Hydra/Tiamat for ks"));
            KsMenu.Add("Qks", new CheckBox("Use Q for Ks"));

            Game.OnUpdate += Game_OnUpdate;
            Obj_AI_Base.OnProcessSpellCast += OnSpellCast;
            Obj_AI_Base.OnSpellCast += OnSpellCast;
            Spellbook.OnCastSpell += OnCast;
            Obj_AI_Base.OnSpellCast += BeforeAttack;
            Drawing.OnDraw += OnDraw;
        }

        static void BeforeAttack(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args)
        {
            if (!sender.IsMe && !args.Target.IsValid) return;

            if (args.Target is AIHeroClient)
            {
                if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo))
                {
                    if (ComboMenu["useE"].Cast<CheckBox>().CurrentValue)
                    {
                        E.Cast();
                    }
                    if (ComboMenu["useR"].Cast<ComboBox>().CurrentValue == 2)
                    {
                        R.Cast();
                        if (ComboMenu["ghostbladeR"].Cast<CheckBox>().CurrentValue)
                        {
                            ghostblade.Cast();
                        }
                    }
                    if (ComboMenu["useR"].Cast<ComboBox>().CurrentValue == 3)
                    {
                        var qntR = ComboMenu["Rcount"].Cast<Slider>().CurrentValue;
                        if (_player.CountEnemyChampionsInRange(Q.Range) >= qntR)
                        {
                            R.Cast();
                            if (ComboMenu["ghostbladeR"].Cast<CheckBox>().CurrentValue)
                            {
                                ghostblade.Cast();
                            }
                        }
                    }
                }

            }
        }
        private static void OnCast(Spellbook Sender, SpellbookCastSpellEventArgs args)
        {
            var ghostbladeon = ComboMenu["ghostbladeR"].Cast<CheckBox>().CurrentValue;
            if (args.Slot == SpellSlot.R && ghostbladeon) ghostblade.Cast();
        }
        private static void OnSpellCast(Obj_AI_Base Sender, GameObjectProcessSpellCastEventArgs args)
        {
            if (!Sender.IsMe || !args.Target.IsValid) return;

            if (args.Target is AIHeroClient && args.Target.IsValid)
            {
                var target = TargetSelector.GetTarget(botrk.Range, DamageType.Magical);
                if (target != null)
                {
                    if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo))
                    {
                        if (target.HealthPercent <= 50)
                        {
                            if (botrk.IsOwned() && botrk.IsReady())
                            {
                                botrk.Cast(target);
                            }
                            if (cutlass.IsOwned() && cutlass.IsReady())
                            {
                                cutlass.Cast(target);
                            }
                        }
                    }
                }

            }
        }
        static void Ks()
        {
            var qks = KsMenu["Qks"].Cast<CheckBox>().CurrentValue;
            var target = TargetSelector.GetTarget(Q.Range, DamageType.Physical);
            if (qks && Q.IsReady())
            {
                if (target.IsValid && target.Health < Q.GetSpellDamage(target))
                {
                    Q.Cast(target);
                }
            }
            if (target.Health < target.MaxHealth * 10 / 100 && botrk.IsOwned() && botrk.IsReady())
            {
                botrk.Cast(target);
            }
            if (target.Health < 100 && cutlass.IsOwned() && cutlass.IsReady())
            {
                cutlass.Cast(target);
            }
        }
        public static
            void Game_OnUpdate(EventArgs args)
        {
            if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.Combo))
            {
                Combo();
            }
            if (Orbwalker.ActiveModesFlags.HasFlag(Orbwalker.ActiveModes.JungleClear))
            {
                Jgclear();
            }
            Ks();
            AutoW();
        }
        public static
            void AutoW()
        {
            var autouseW = ComboMenu["autoW"].Cast<Slider>().CurrentValue;
            var useW = ComboMenu["useW"].Cast<CheckBox>().CurrentValue;
            if (useW && _player.HealthPercent <= autouseW)
            {
                W.Cast();
            }
        }
        public static
            void Combo()
        {
            var _target = TargetSelector.GetTarget(Q.Range - 100, DamageType.Physical);
            var useTiamat = ComboMenu["tiamatcombo"].Cast<CheckBox>().CurrentValue;

            if (_target != null)
            {
                if (Q.IsReady() && Q.IsInRange(_target))
                {
                    Q.Cast(_target);
                }
                if (TargetSelector.GetTarget(_player.AttackRange, DamageType.Physical) != null)
                {
                    E.Cast();
                }
                if (_target.HealthPercent <= 50 && tiamat.IsOwned() && tiamat.IsReady() && useTiamat)
                {
                    tiamat.Cast();
                    Orbwalker.ResetAutoAttack();
                }
                if (_target.HealthPercent <= 50 && hydra.IsOwned() && hydra.IsReady() && useTiamat)
                {
                    if (_player.HasBuff("DoubleStrikeReady"))
                    {
                        hydra.Cast();
                        Orbwalker.ResetAutoAttack();
                    }
                }
            }
        }
        private static
            void OnDraw(EventArgs args)
        {
            if (DrawQ())
            {
                new EloBuddy.SDK.Rendering.Circle { Color = Color.LawnGreen, Radius = Q.Range, BorderWidth = 2f }.Draw(_player.Position);
            }
        }
        public static bool DrawQ()
        {
            return ComboMenu["drawQ"].Cast<CheckBox>().CurrentValue;
        }
        public static void Jgclear()
        {
            var monster = EntityManager.MinionsAndMonsters.GetJungleMonsters(_player.Position, _player.GetAutoAttackRange()).FirstOrDefault();
            var manaQ = ComboMenu["qmanajg"].Cast<Slider>().CurrentValue;
            var qjg = ComboMenu["qjg"].Cast<CheckBox>().CurrentValue;
            var ejg = ComboMenu["ejg"].Cast<CheckBox>().CurrentValue;
            if (E.IsReady() && ejg &&
                EntityManager.MinionsAndMonsters.GetJungleMonsters(_player.Position, _player.GetAutoAttackRange()).Any())
            {
                E.Cast();
            }
            if (monster != null)
            {
                if (Q.IsReady() && qjg && _player.ManaPercent >= manaQ)
                {
                    Q.Cast(monster);
                }
            }
        }

    }
}


text:
<?php

function throwException() {
    throw new Exception('test');
}

function gen() {
    yield 'foo';
    strlen("foo", "bar", throwException());
    yield 'bar';
}

$gen = gen();

var_dump($gen->current());

try {
    $gen->next();
} catch (Exception $e) {
    echo 'Caught exception with message "', $e->getMessage(), '"', "\n";
}

var_dump($gen->current());

?>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

namespace LNF.Data.ClientAccountMatrix
{
    public class MatrixUserHeader
    {
        public int ClientOrgID { get; set; }
        public string DisplayName { get; set; }
        public string Key { get; set; }

        public void Render(StringBuilder sb)
        {
            sb.AppendFormat("{1}	", Key, HeaderText());
        }

        public string HeaderText()
        {
            if (string.IsNullOrEmpty(DisplayName))
                return string.Empty;
            return DisplayName.Replace(" ", "
");
        }
    }
}


text:
#ifndef TRTRI_SOURCE_INCLUDES_H
#define TRTRI_SOURCE_INCLUDES_H
#include <cstddef>
#include "TrtriKernelSourceIncludes.cpp"

//**** compiler flags
//**** online compilation flags
const char * const TrtriBuildOptions = "-cl-std=CL2.0";
const char * const TrtribinBuildOptions = "-cl-std=CL2.0";

/*mod 192 dtrsm*/
extern const char * const diag_dtrtri_upper_192_12_src;
extern unsigned char *diag_dtrtri_upper_192_12_bin;
extern size_t diag_dtrtri_upper_192_12_binSize;

extern const char * const triple_dgemm_update_192_12_R_src;
extern unsigned char *triple_dgemm_update_192_12_R_bin;
extern size_t triple_dgemm_update_192_12_R_binSize;

extern const char * const triple_dgemm_update_192_24_PART1_R_src;
extern unsigned char *triple_dgemm_update_192_24_PART1_R_bin;
extern size_t triple_dgemm_update_192_24_PART1_R_binSize;

extern const char * const triple_dgemm_update_192_24_PART2_R_src;
extern unsigned char *triple_dgemm_update_192_24_PART2_R_bin;
extern size_t triple_dgemm_update_192_24_PART2_R_binSize;

extern const char * const triple_dgemm_update_192_48_PART1_R_src;
extern unsigned char *triple_dgemm_update_192_48_PART1_R_bin;
extern size_t triple_dgemm_update_192_48_PART1_R_binSize;

extern const char * const triple_dgemm_update_192_48_PART2_R_src;
extern unsigned char *triple_dgemm_update_192_48_PART2_R_bin;
extern size_t triple_dgemm_update_192_48_PART2_R_binSize;

extern const char * const triple_dgemm_update_192_96_PART1_R_src;
extern unsigned char *triple_dgemm_update_192_96_PART1_R_bin;
extern size_t triple_dgemm_update_192_96_PART1_R_binSize;

extern const char * const triple_dgemm_update_192_96_PART2_R_src;
extern unsigned char *triple_dgemm_update_192_96_PART2_R_bin;
extern size_t triple_dgemm_update_192_96_PART2_R_binSize;

/*mod 128 dtrsm*/
/*upper*/
extern const char * const  diag_dtrtri_upper_128_16_src;
extern unsigned char *diag_dtrtri_upper_128_16_bin;
extern size_t diag_dtrtri_upper_128_16_binSize;

extern const char * const  triple_dgemm_update_128_16_R_src;
extern unsigned char *triple_dgemm_update_128_16_R_bin;
extern size_t triple_dgemm_update_128_16_R_binSize;

extern const char * const  triple_dgemm_update_128_32_PART1_R_src;
extern unsigned char *triple_dgemm_update_128_32_PART1_R_bin;
extern size_t triple_dgemm_update_128_32_PART1_R_binSize;

extern const char * const  triple_dgemm_update_128_32_PART2_R_src;
extern unsigned char *triple_dgemm_update_128_32_PART2_R_bin;
extern size_t triple_dgemm_update_128_32_PART2_R_binSize;

extern const char * const  triple_dgemm_update_128_64_PART1_R_src;
extern unsigned char *triple_dgemm_update_128_64_PART1_R_bin;
extern size_t triple_dgemm_update_128_64_PART1_R_binSize;

extern const char * const  triple_dgemm_update_128_64_PART2_R_src;
extern unsigned char *triple_dgemm_update_128_64_PART2_R_bin;
extern size_t triple_dgemm_update_128_64_PART2_R_binSize;

extern const char * const  triple_dgemm_update_128_ABOVE64_PART1_R_src;
extern unsigned char *triple_dgemm_update_128_ABOVE64_PART1_R_bin;
extern size_t triple_dgemm_update_128_ABOVE64_PART1_R_binSize;

extern const char * const  triple_dgemm_update_128_ABOVE64_PART2_R_src;
extern unsigned char *triple_dgemm_update_128_ABOVE64_PART2_R_bin;
extern size_t triple_dgemm_update_128_ABOVE64_PART2_R_binSize;

extern const char * const  triple_dgemm_update_128_ABOVE64_PART3_R_src;
extern unsigned char *triple_dgemm_update_128_ABOVE64_PART3_R_bin;
extern size_t triple_dgemm_update_128_ABOVE64_PART3_R_binSize;

/*lower*/
extern const char * const  diag_dtrtri_lower_128_16_src;
extern unsigned char *diag_dtrtri_lower_128_16_bin;
extern size_t diag_dtrtri_lower_128_16_binSize;

extern const char * const  triple_dgemm_update_128_16_PART1_L_src;
extern unsigned char *triple_dgemm_update_128_16_PART1_L_bin;
extern size_t triple_dgemm_update_128_16_PART1_L_binSize;

extern const char * const  triple_dgemm_update_128_16_PART2_L_src;
extern unsigned char *triple_dgemm_update_128_16_PART2_L_bin;
extern size_t triple_dgemm_update_128_16_PART2_L_binSize;

extern const char * const  triple_dgemm_update_128_32_PART1_L_src;
extern unsigned char *triple_dgemm_update_128_32_PART1_L_bin;
extern size_t triple_dgemm_update_128_32_PART1_L_binSize;

extern const char * const  triple_dgemm_update_128_32_PART2_L_src;
extern unsigned char *triple_dgemm_update_128_32_PART2_L_bin;
extern size_t triple_dgemm_update_128_32_PART2_L_binSize;

extern const char * const  triple_dgemm_update_128_64_PART1_L_src;
extern unsigned char *triple_dgemm_update_128_64_PART1_L_bin;
extern size_t triple_dgemm_update_128_64_PART1_L_binSize;

extern const char * const  triple_dgemm_update_128_64_PART2_L_src;
extern unsigned char *triple_dgemm_update_128_64_PART2_L_bin;
extern size_t triple_dgemm_update_128_64_PART2_L_binSize;

extern const char * const  triple_dgemm_update_128_ABOVE64_PART1_L_src;
extern unsigned char *triple_dgemm_update_128_ABOVE64_PART1_L_bin;
extern size_t triple_dgemm_update_128_ABOVE64_PART1_L_binSize;

extern const char * const  triple_dgemm_update_128_ABOVE64_PART2_L_src;
extern unsigned char *triple_dgemm_update_128_ABOVE64_PART2_L_bin;
extern size_t triple_dgemm_update_128_ABOVE64_PART2_L_binSize;

extern const char * const  triple_dgemm_update_128_ABOVE64_PART3_L_src;
extern unsigned char *triple_dgemm_update_128_ABOVE64_PART3_L_bin;
extern size_t triple_dgemm_update_128_ABOVE64_PART3_L_binSize;

#endif


text:
package dsalg

import (
	"bytes"
	"fmt"
)

type DequeNode struct {
	next, prev *DequeNode
	Value      interface{}
}

func (n *DequeNode) reattach(next, prev *DequeNode, v interface{}) {
	// Detach from Non-Nil Next Node
	if n.next != nil {
		n.next.prev = n.prev
	}
	// Detach from Non-Nil Prev Node
	if n.prev != nil {
		n.prev.next = n.next
	}
	// Update Current Node
	n.next, n.prev, n.Value = next, prev, v
}

type LinkedDeque struct {
	fnBack      func() *DequeNode
	fnFront     func() *DequeNode
	fnPushBack  func(interface{}) *DequeNode
	fnPushFront func(interface{}) *DequeNode
	fnPopBack   func() interface{}
	fnPopFront  func() interface{}
	back        *DequeNode
	front       *DequeNode
	len         int
	cap         int
}

func (q *LinkedDeque) backImpl() *DequeNode {
	if q.len == 0 {
		return nil
	}
	return q.back
}

func (q *LinkedDeque) frontImpl() *DequeNode {
	if q.len == 0 {
		return nil
	}
	return q.front
}

func (q *LinkedDeque) pushBackImpl(v interface{}) *DequeNode {
	// Empty Queue
	if q.len == 0 {
		q.back.Value = v
		q.len++
		return q.back
	}
	// Back Does Not Point to Edge Node
	if q.back.next != nil {
		q.back = q.back.next
		q.back.Value = v
		q.len++
		return q.back
	}
	// Back Points to Edge Node
	// Reuse a node from before the front or create a new one
	newBack := q.front.prev
	if newBack == nil {
		newBack = &DequeNode{nil, q.back, v}
		q.cap++
	} else {
		newBack.reattach(nil, q.back, v)
	}
	// Update Back Node
	q.back.next = newBack
	q.back = newBack
	q.len++
	return q.back
}

func (q *LinkedDeque) pushFrontImpl(v interface{}) *DequeNode {
	// Empty Queue
	if q.len == 0 {
		q.front.Value = v
		q.len++
		return q.front
	}
	// Front Does Not Point to Edge Node
	if q.front.prev != nil {
		q.front = q.front.prev
		q.front.Value = v
		q.len++
		return q.front
	}
	// Front Points to Edge Node
	// Reuse a node from after the back or create a new one
	newFront := q.back.next
	if newFront == nil {
		newFront = &DequeNode{q.front, nil, v}
		q.cap++
	} else {
		newFront.reattach(q.front, nil, v)
	}
	// Update Front Node
	q.front.prev = newFront
	q.front = newFront
	q.len++
	return q.front
}

func (q *LinkedDeque) popBackImpl() interface{} {
	// Empty Queue
	if q.len == 0 {
		panic("Empty queue")
	}
	n := q.back
	// More-Than-One-Element Queue
	if q.len > 1 {
		q.back = q.back.prev
	}
	// Non-Empty Queue
	q.len--
	return n.Value
}

func (q *LinkedDeque) popFrontImpl() interface{} {
	// Empty Queue
	if q.len == 0 {
		panic("Empty queue")
	}
	n := q.front
	// More-Than-One-Element Queue
	if q.len > 1 {
		q.front = q.front.next
	}
	// Non-Empty Queue
	q.len--
	return n.Value
}

func NewLinkedDeque() *LinkedDeque {
	n := &DequeNode{}
	q := &LinkedDeque{
		back:  n,
		front: n,
		cap:   1,
	}
	q.fnBack, q.fnFront = q.backImpl, q.frontImpl
	q.fnPushBack, q.fnPushFront = q.pushBackImpl, q.pushFrontImpl
	q.fnPopBack, q.fnPopFront = q.popBackImpl, q.popFrontImpl
	return q
}

func (q *LinkedDeque) Back() *DequeNode {
	return q.fnBack()
}

func (q *LinkedDeque) Front() *DequeNode {
	return q.fnFront()
}

func (q *LinkedDeque) PushBack(v interface{}) *DequeNode {
	return q.fnPushBack(v)
}

func (q *LinkedDeque) PushFront(v interface{}) *DequeNode {
	return q.fnPushFront(v)
}

func (q *LinkedDeque) PopBack() interface{} {
	return q.fnPopBack()
}

func (q *LinkedDeque) PopFront() interface{} {
	return q.fnPopFront()
}

func (q *LinkedDeque) BackValue() interface{} {
	return q.Back().Value
}

func (q *LinkedDeque) FrontValue() interface{} {
	return q.Front().Value
}

func (q *LinkedDeque) PushBackValue(v interface{}) {
	q.PushBack(v)
}

func (q *LinkedDeque) PushFrontValue(v interface{}) {
	q.PushFront(v)
}

func (q *LinkedDeque) Reverse() {
	q.fnBack, q.fnFront = q.fnFront, q.fnBack
	q.fnPushBack, q.fnPushFront = q.fnPushFront, q.fnPushBack
	q.fnPopBack, q.fnPopFront = q.fnPopFront, q.fnPopBack
}

func (q *LinkedDeque) Len() int {
	return q.len
}

func (q *LinkedDeque) Cap() int {
	return q.cap
}

func (q *LinkedDeque) IsEmpty() bool {
	return q.len == 0
}

func (q *LinkedDeque) IsFull() bool {
	return false
}

func (q *LinkedDeque) String() string {
	var buffer bytes.Buffer
	ptr := q.front
	if ptr != nil {
		for ptr.prev != nil {
			ptr = ptr.prev
		}
	}
	buffer.WriteString("<- ")
	for ptr != nil {
		buffer.WriteString(fmt.Sprintf("%v", ptr.Value))
		if ptr == q.front {
			buffer.WriteString("(F)")
		}
		if ptr == q.back {
			buffer.WriteString("(B)")
		}
		if ptr.next != nil {
			buffer.WriteString(" <-> ")
		}
		ptr = ptr.next
	}
	buffer.WriteString(" ->")
	return buffer.String()
}


text:
namespace Microsoft.WindowsAzure.Management.HDInsight.Framework.Rest
{
    using System;
    using System.IO;
    using System.Reflection;

    /// <summary>
    /// A contracts class that mimics the functionality of <see cref="System.Diagnostics.Contracts"/>.
    /// </summary>
    internal static class Contract
    {
        /// <summary>
        /// Wrapper for the CodeContract Requries method.
        /// </summary>
        /// <typeparam name="T">Exception type to be thrown.</typeparam>
        /// <param name="condition">Whether the condition was true or false.</param>
        /// <param name="message">The message to be set in the exception.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Personal preference")]
        public static void Requires<T>(bool condition, string message = null) where T : Exception
        {
            if (!condition)
            {
                // Find the constructor that has a String param
                Type type = typeof(T);
                ConstructorInfo cinfo = type.GetConstructor(new Type[] { typeof(string) });
                if (cinfo == null)
                {
                    throw default(T);
                }

                throw (Exception)cinfo.Invoke(new object[] { message ?? "Requires condition failed." });
            }
        }

        /// <summary>
        /// Assumes the specified condition.
        /// </summary>
        /// <param name="condition">If set to <c>true</c> [condition].</param>
        /// <param name="message">The message.</param>
        /// <exception cref="System.IO.InvalidDataException">Thrown when <paramref name="condition"/> is false.</exception>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Personal Preference")]
        public static void Assume(bool condition, string message = null)
        {
            if (!condition)
            {
                throw new InvalidDataException(message ?? "Contract.Assume failure");
            }
        }

        /// <summary>
        /// Asserts the specified condition.
        /// </summary>
        /// <param name="condition">If set to <c>true</c> [condition].</param>
        /// <param name="message">The message.</param>
        /// <exception cref="System.IO.InvalidDataException">Thrown when the condition is failed.</exception>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Preference")]
        public static void Assert(bool condition, string message = null)
        {
            if (!condition)
            {
                throw new InvalidDataException(message ?? "Contract.Assert failure");
            }
        }

        /// <summary>
        /// Asserts the not null.
        /// </summary>
        /// <param name="arg">The arg.</param>
        /// <param name="message">The message.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static void AssertNotNull(object arg, string message)
        {
            if (arg == null)
            {
                throw new ArgumentNullException(message);
            }
        }

        /// <summary>
        /// Asserts the arg not null.
        /// </summary>
        /// <param name="arg">The arg.</param>
        /// <param name="argName">The argName.</param>
        /// <exception cref="System.ArgumentNullException">When arg is null.</exception>
        public static void AssertArgNotNull(object arg, string argName)
        {
            if (arg == null)
            {
                throw new ArgumentNullException(argName);
            }
        }

        /// <summary>
        /// Asserts the arg not null or empty.
        /// </summary>
        /// <param name="arg">The arg.</param>
        /// <param name="argname">The argName.</param>
        /// <exception cref="System.ArgumentNullException">When arg is null or empty.</exception>
        /// <exception cref="System.ArgumentException">Argument cannot be empty</exception>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Personal preference", MessageId = "argName")]
        public static void AssertArgNotNullOrEmpty(string arg, string argname)
        {
            if (arg == null)
            {
                throw new ArgumentNullException(argname);
            }

            if (string.IsNullOrEmpty(arg))
            {
                throw new ArgumentException("Argument cannot be empty", argname);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd">
    <fixture name="storeGroup"
             module="Magento_Store"
             type="flat"
             entity_type="store_group"
             collection="Magento\Store\Model\ResourceModel\Group\Collection"
             repository_class="Magento\Store\Test\Repository\StoreGroup"
             handler_interface="Magento\Store\Test\Handler\StoreGroup\StoreGroupInterface"
             class="Magento\Store\Test\Fixture\StoreGroup">
        <field name="group_id" is_required="1" />
        <field name="website_id" source="Magento\Store\Test\Fixture\StoreGroup\WebsiteId" />
        <field name="name" is_required="" />
        <field name="root_category_id" source="Magento\Store\Test\Fixture\StoreGroup\CategoryId" />
        <field name="default_store_id" is_required="" />
    </fixture>
</config>


text:
package ch.sbb.maven.plugins.iib.mojos;

import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration;
import static org.twdata.maven.mojoexecutor.MojoExecutor.element;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment;
import static org.twdata.maven.mojoexecutor.MojoExecutor.goal;
import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.name;
import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin;
import static org.twdata.maven.mojoexecutor.MojoExecutor.version;

import java.io.File;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.twdata.maven.mojoexecutor.MojoExecutor.Element;
import org.twdata.maven.mojoexecutor.MojoExecutor.ExecutionEnvironment;

/**
 * Installs a zipped-up, IIB9 project into the user's local maven repository.
 *
 *
 * @author Brett Shelley, 2016
 */
@Mojo(name = "install-zip", defaultPhase = LifecyclePhase.INSTALL)
public class InstallZipMojo extends AbstractMojo {

    /**
     * The Maven Project Object
     */
    @Parameter(property = "project", required = true, readonly = true)
    protected MavenProject project;

    /**
     * The Maven Session Object
     */
    @Parameter(property = "session", required = true, readonly = true)
    protected MavenSession session;

    /**
     * The Maven PluginManager Object
     */
    @Component
    protected BuildPluginManager buildPluginManager;

    @Parameter(property = "zipFilePath", required = true, defaultValue = "${project.build.directory}/${project.artifactId}-${project.version}.zip")
    protected String zipFilePath;

    public void execute() throws MojoFailureException, MojoExecutionException
    {

        try
        {
            File file = new File(zipFilePath);
            if (!file.exists())
            {
                String message = "The zip file '" + file.getAbsolutePath() + "' is missing";
                getLog().error(message);
                throw new MojoFailureException(message);
            }

            // / attempt to add the pom file
            Element pomElement = null; //
            String pomFilePath = project.getBasedir().getAbsolutePath() + File.separator + "pom.xml";
            File pomFile = new File(pomFilePath);
            if (!pomFile.exists())
            {
                getLog().warn("no pom file could be located at " + pomFilePath);
                pomElement = element("generatePom", "true");
            }
            else
            {
                pomElement = element("pomFile", pomFilePath);
            }

            // unpack all IIB dependencies that match the given scope (compile)
            Plugin plugin = plugin(groupId("org.apache.maven.plugins"), artifactId("maven-install-plugin"), version("2.5.2"));
            String goal = goal("install-file");
            Xpp3Dom xpp3Dom = configuration(
                    element(name("file"), zipFilePath), // / Output location.
                    element(name("repositoryLayout"), "default"), // / Comma Separated list of Types to include
                    element(name("artifactId"), project.getArtifactId()),
                    element(name("version"), project.getVersion()),
                    element(name("packaging"), "zip"),
                    element(name("groupId"), project.getGroupId()),
                    pomElement

                    );

            ExecutionEnvironment executionEnvironment = executionEnvironment(project, session, buildPluginManager);
            executeMojo(plugin, goal, xpp3Dom, executionEnvironment);

        } catch (Exception e)
        {
            throw new MojoFailureException(e.toString());
        }

    }

}


text:
USE [msdb]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[MaintenanceConfig](
	[ConfigurationType] [varchar](50) NOT NULL,
	[ConfigurationSettings] [xml] NULL,
 CONSTRAINT [pk_MaintenanceConfig_ConfigurationType] PRIMARY KEY CLUSTERED (
	[ConfigurationType] ASC)
  WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON))
GO


text:
<!DOCTYPE html>
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Zakaj naj dodam račun?</title>
<link rel="shortcut icon" href="https://www.ubuntu.si/favicon.ico">
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">

Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu

Domov

Novice

Forum

Kaj je Ubuntu?

Pogosta vprašanja

Skupnost

Povezave

 »  Namizni vodnik Ubuntu » Nastavitve » Spletni računi »

Zakaj naj dodam račun?

Dodajanje svojih računov prinaša izbiro storitev kot so koledar, klepet in e-pošta neposredno na vaše namizje in s tem storitve neopazno postanejo del vaše uporabniške izkušnje. Z dodajanjem računov, lahko uporabljate več različnih klepetov hkrati. Samo enkrat nastavite svoj račun in vedno, ko zaženete računalnik, bodo vsi računi in storitve, ki ste jih dodali, pripravljeni za vas.

Več podrobnosti

Spletni računi — Dodaj račune,  Odstrani račune,  Onemogoči storitve

Material v tem dokumentu je na voljo pod prosto licenco. To je prevod dokumentacije Ubuntu, ki jo je sestavila Ubuntu dokumentacijska ekipa za Ubuntu. V slovenščino jo je prevedla skupina Ubuntu prevajalcev. Za poročanje napak v prevodih v tej dokumentaciji ali Ubuntuju pošljite sporočilo na dopisni seznam.


text:
using FM4CC.Environment;
using FM4CC.Simulation;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FM4CC.FaultModels.ControllerComparison.GUI
{
    /// <summary>
    /// Interaction logic for ConfigurationControl.xaml
    /// </summary>
    public partial class ConfigurationControl : UserControl, IConfigurationControl
    {
        ControllerComparisonFaultModelConfiguration configuration;
        SimulationSettings simulationSettings;

        public ConfigurationControl(FaultModelConfiguration configuration, SimulationSettings simulationSettings)
        {
            InitializeComponent();
            LoadConfiguration(configuration);
            this.simulationSettings = simulationSettings;

        }

        public bool Validate()
        {
            if (this.NumberHeatMapRegionsNumUpDown.Value != null && ((double)this.NumberHeatMapRegionsNumUpDown.Value) <= 0)
            {
                MessageBox.Show("Invalid setting", "Invalid heat map divison factor", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            if (this.PointsPerRegionNumUpDown.Value != null && ((double)this.PointsPerRegionNumUpDown.Value) <= 0)
            {
                MessageBox.Show("Invalid setting", "Invalid no. of points per region", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            if ((!ModelPathTextBox.Text.Contains(".mdl") && !ModelPathTextBox.Text.Contains(".slx")) || !File.Exists(this.ModelPathTextBox.Text))
            {
                MessageBox.Show("Invalid model path, expected a MATLAB model file (.mdl, .slx)", "Model missing", MessageBoxButton.OK, MessageBoxImage.Stop);
                return false;
            }

            if (!ModelSettingsPathTextBox.Text.Contains(".m") || !File.Exists(this.ModelSettingsPathTextBox.Text))
            {
                MessageBox.Show("Invalid model settings path, expected a MATLAB script file (.m)", "Model settings missing", MessageBoxButton.OK, MessageBoxImage.Stop);
                return false;
            }

            if (this.DesiredValueNameTextBox.Text == null || this.DesiredValueNameTextBox.Text == "")
            {
                MessageBox.Show("Please specify the name of the desired variable.", "Invalid setting", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            if (this.ActualValueNameTextBox.Text == null || this.ActualValueNameTextBox.Text == "")
            {
                MessageBox.Show("Please specify the name of the actual variable.", "Invalid setting", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            Save();

            return true;
        }

        public void Save()
        {
            configuration.SetValue("Regions", Convert.ToDouble(Math.Abs((double)this.NumberHeatMapRegionsNumUpDown.Value)));
            configuration.SetValue("PointsPerRegion", Convert.ToDouble(Math.Abs((double)this.PointsPerRegionNumUpDown.Value)));

            configuration.SetValue("UseAdaptiveRandomSearch", ((string)this.ExplorationAlgorithmComboBox.SelectedItem) == "AdaptiveRandomSearch" ? true : false);
            configuration.SetValue("OptimizationAlgorithm", this.LocalSeachAlgorithmComboBox.SelectedItem);

            configuration.SetValue("Compared_ModelFile", this.ModelPathTextBox.Text);
            configuration.SetValue("Compared_ModelConfigurationFile", this.ModelSettingsPathTextBox.Text);
            configuration.SetValue("Compared_DesiredVariableName", this.DesiredValueNameTextBox.Text);
            configuration.SetValue("Compared_ActualVariableName", this.ActualValueNameTextBox.Text);

            if (this.DisturbanceValueNameTextBox.Text != null)
            {
                configuration.SetValue("Compared_DisturbanceVariableName", this.DisturbanceValueNameTextBox.Text);
            }
            else
            {
                configuration.SetValue("Compared_DisturbanceVariableName", "");
            }

            List<string> requirements = new List<string>();

            int i = 0;

            foreach (CheckBox cb in RequirementsStackPanel.Children)
            {
                if (i > 1)
                {
                    if ((bool)cb.IsChecked) requirements.Add(cb.Content as string);
                }
                else
                {
                    if (i == 0 && ((bool)cb.IsChecked))
                    {
                        requirements.Add("MaxDeviation");
                    }
                    else if ((bool)cb.IsChecked)
                    {
                        requirements.Add("MeanDeviation");
                    }
                }

                i++;
            }
            configuration.SetValue("Requirements", requirements, "complex");

        }

        private void LoadConfiguration(FaultModelConfiguration configuration)
        {
            this.configuration = (ControllerComparisonFaultModelConfiguration)configuration;

            this.ExplorationAlgorithmComboBox.Items.Add("AdaptiveRandomSearch");
            this.ExplorationAlgorithmComboBox.Items.Add("RandomSearch");

            this.LocalSeachAlgorithmComboBox.Items.Add("AcceleratedSimulatedAnnealing");
            this.LocalSeachAlgorithmComboBox.Items.Add("SimulatedAnnealing");
            this.LocalSeachAlgorithmComboBox.Items.Add("PatternSearch");
            this.LocalSeachAlgorithmComboBox.Items.Add("MultiStart");
            this.LocalSeachAlgorithmComboBox.Items.Add("GlobalSearch");
            this.LocalSeachAlgorithmComboBox.Items.Add("GeneticAlgorithm");

            ReloadConfiguration();
        }

        public void ReloadConfiguration()
        {
            List<string> requirements = configuration.GetValue("Requirements", "complex") as List<string>;

            this.ExplorationAlgorithmComboBox.SelectedIndex = ((bool)configuration.GetValue("UseAdaptiveRandomSearch"))?0:1;
            this.LocalSeachAlgorithmComboBox.SelectedValue = (string)configuration.GetValue("OptimizationAlgorithm");

            foreach (string requirement in requirements)
            {
                switch (requirement)
                {
                    case "Stability":
                        StabilityCheckBox.IsChecked = true;
                        break;
                    case "Precision":
                        PrecisionCheckBox.IsChecked = true;
                        break;
                    case "Smoothness":
                        SmoothnessCheckBox.IsChecked = true;
                        break;
                    case "Responsiveness":
                        ResponsivenessCheckBox.IsChecked = true;
                        break;
                    case "Steadiness":
                        SteadinessCheckBox.IsChecked = true;
                        break;
                    case "MaxDeviation":
                        MaxDeviationCheckBox.IsChecked = true;
                        break;
                    case "MeanDeviation":
                        MeanDeviationCheckBox.IsChecked = true;
                        break;
                    default:
                        break;
                }
            }

            this.NumberHeatMapRegionsNumUpDown.Value = (double)configuration.GetValue("Regions") as double?;
            this.PointsPerRegionNumUpDown.Value = (double)configuration.GetValue("PointsPerRegion") as double?;

            this.ModelPathTextBox.Text = (string)configuration.GetValue("Compared_ModelFile");
            this.ModelSettingsPathTextBox.Text = (string)configuration.GetValue("Compared_ModelConfigurationFile");
            this.DesiredValueNameTextBox.Text = (string)configuration.GetValue("Compared_DesiredVariableName");
            this.ActualValueNameTextBox.Text = (string)configuration.GetValue("Compared_ActualVariableName");
            this.DisturbanceValueNameTextBox.Text = (string)configuration.GetValue("Compared_DisturbanceVariableName");
        }

        private void ModelBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fbd = new OpenFileDialog();
            fbd.ShowDialog();
            this.ModelPathTextBox.Text = fbd.FileName;
        }

        private void ModelSettingsBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fbd = new OpenFileDialog();
            fbd.ShowDialog();
            this.ModelSettingsPathTextBox.Text = fbd.FileName;
        }
    }
}


text:
// Copyright © 2013 Şafak Gür. All rights reserved.
// Use of this source code is governed by the MIT License (MIT).

namespace Dawn.Net.Sockets.Tests
{
    using System;
    using System.Net;
    using System.Net.Sockets;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    ///     Contains unit tests for <see cref="SocketAwaitable" /> class.
    /// </summary>
    [TestClass]
    public class SocketAwaitableTests
    {
        #region Methods
        /// <summary>
        ///     Tests the constructor of <see cref="SocketAwaitable" /> class.
        /// </summary>
        [TestMethod]
        public void TestInitialization()
        {
            // Default values.
            var awaitable = new SocketAwaitable();
            Assert.IsNull(awaitable.AcceptSocket);

            var awaiter = awaitable.GetAwaiter();
            Assert.IsTrue(awaiter.IsCompleted);
            Assert.AreEqual(awaiter.GetResult(), SocketError.Success);
        }

        /// <summary>
        ///     Tests <see cref="SocketAwaitable.Buffer" />.
        /// </summary>
        [TestMethod]
        public void TestBuffer()
        {
            // Default buffer values.
            var awaitable = new SocketAwaitable();
            Assert.IsNotNull(awaitable.Buffer.Array);
            Assert.AreEqual(awaitable.Buffer.Array.Length, 0);
            Assert.AreEqual(awaitable.Buffer.Offset, 0);
            Assert.AreEqual(awaitable.Buffer.Count, 0);

            // Default transferred values.
            Assert.IsNotNull(awaitable.Transferred.Array);
            Assert.AreEqual(awaitable.Transferred.Array.Length, 0);
            Assert.AreEqual(awaitable.Transferred.Offset, 0);
            Assert.AreEqual(awaitable.Transferred.Count, 0);

            // Assign a null buffer.
            var nullBuffer = default(ArraySegment<byte>);
            Assert.IsNull(nullBuffer.Array);

            awaitable.Buffer = nullBuffer;
            Assert.IsNotNull(awaitable.Buffer.Array);
            Assert.AreEqual(awaitable.Buffer.Array.Length, 0);
            Assert.AreEqual(awaitable.Buffer.Offset, 0);
            Assert.AreEqual(awaitable.Buffer.Count, 0);

            // Assign a valid buffer.
            var data = new byte[32];
            var buffer = new ArraySegment<byte>(data, 8, 16);

            awaitable.Buffer = buffer;
            Assert.AreSame(awaitable.Buffer.Array, data);
            Assert.AreEqual(awaitable.Buffer.Offset, buffer.Offset);
            Assert.AreEqual(awaitable.Buffer.Count, buffer.Count);

            // Clear awaitable.
            awaitable.Clear();
            Assert.IsNotNull(awaitable.Buffer.Array);
            Assert.AreEqual(awaitable.Buffer.Array.Length, 0);
            Assert.AreEqual(awaitable.Buffer.Offset, 0);
            Assert.AreEqual(awaitable.Buffer.Count, 0);
        }

        /// <summary>
        ///     Tests <see cref="SocketAwaitable.RemoteEndPoint" />.
        /// </summary>
        [TestMethod]
        public void TestRemoteEndPoint()
        {
            // Default value.
            var awaitable = new SocketAwaitable();
            Assert.IsNull(awaitable.RemoteEndPoint);

            // Assign value.
            var endPoint = new IPEndPoint(IPAddress.Loopback, IPEndPoint.MaxPort);
            awaitable.RemoteEndPoint = endPoint;
            Assert.AreSame(awaitable.RemoteEndPoint, endPoint);

            // Clear awaitable.
            awaitable.Clear();
            Assert.IsNull(awaitable.RemoteEndPoint);
        }

        /// <summary>
        ///     Tests <see cref="SocketAwaitable.SocketFlags" />.
        /// </summary>
        [TestMethod]
        public void TestSocketFlags()
        {
            // Default value.
            var awaitable = new SocketAwaitable();
            Assert.AreEqual(awaitable.SocketFlags, SocketFlags.None);

            // Assign value.
            awaitable.SocketFlags = SocketFlags.Broadcast;
            Assert.AreEqual(awaitable.SocketFlags, SocketFlags.Broadcast);

            // Clear awaitable.
            awaitable.Clear();
            Assert.AreEqual(awaitable.SocketFlags, SocketFlags.None);
        }

        /// <summary>
        ///     Tests <see cref="SocketAwaitable.GetAwaiter" />.
        /// </summary>
        [TestMethod]
        public void TestGettingAwaiter()
        {
            var awaitable = new SocketAwaitable();
            var awaiter = awaitable.GetAwaiter();
            Assert.IsTrue(awaiter.IsCompleted);
            Assert.AreEqual(awaiter.GetResult(), default(SocketError));
        }

        /// <summary>
        ///     Tests <see cref="SocketAwaitable.Dispose" />.
        /// </summary>
        [TestMethod]
        public void TestDisposing()
        {
            var awaitable = new SocketAwaitable();
            Assert.IsFalse(awaitable.IsDisposed);

            awaitable.Dispose();
            Assert.IsTrue(awaitable.IsDisposed);
        }
        #endregion
    }
}


text:
import { ReduxActionDispatcher, ReduxActionFunction, ReduxReducerDecorator } from '@harmowatch/redux-decorators';

function printList(actions: string[]) {

  return actions
    .map(action => `- "${action}"`)
    .join('\n');

}

export function compare(actual: Function, ...expected: ReduxActionFunction[]): jasmine.CustomMatcherResult {

  const expectedActionTypes = expected.map(ReduxActionDispatcher.getType);

  const givenActionTypes = []
    .concat(ReduxReducerDecorator.get(actual))
    .map(type => ReduxActionDispatcher.getType(type));

  const actionsNotListeningTo = expectedActionTypes
    .filter(type => !givenActionTypes.includes(type));

  const pass = actionsNotListeningTo.length === 0;

  if (expectedActionTypes.length === 1) {
    return {
      pass,
      message: `Expected the reducer to listen for action "${expectedActionTypes[ 0 ]}", but it doesn\'t!`,
    };
  } else if (expectedActionTypes.length > 1) {
    return {
      pass,
      message: `
Expected the reducer to listen for the actions:
${printList(expectedActionTypes)}

But it did not listen to:
${printList(actionsNotListeningTo)}
          `.trim(),
    };
  }

}

export function toReduceOn(): jasmine.CustomMatcher {
  return {compare};
}


text:
/**
 * Created by s.van.den.berg on 18-12-2014.
 */
var gulp = require('gulp');

// Include Our Plugins
var sass = require('gulp-sass');

// Compile Our Sass
gulp.task('sass', function() {
    return gulp.src('sass/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('live/css'));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('sass/*.scss', ['sass']);
});

// Default Task
gulp.task('default', ['watch']);


text:
class AddVariantAuctionMethodToSpreeAllegroStoreProducts < ActiveRecord::Migration
  def change
    add_reference :spree_allegro_store_products, :variant_auction_method
  end
end


text:
package download

import (
	"fmt"
	"io"
	"log"
	"strconv"
	"time"

	"github.com/osuripple/cheesegull/api"
	"github.com/osuripple/cheesegull/downloader"
	"github.com/osuripple/cheesegull/housekeeper"
	"github.com/osuripple/cheesegull/models"
)

func errorMessage(c *api.Context, code int, err string) {
	c.WriteHeader("Content-Type", "text/plain; charset=utf-8")
	c.Code(code)
	c.Write([]byte(err))
}

func existsQueryKey(c *api.Context, s string) bool {
	_, ok := c.Request.URL.Query()[s]
	return ok
}

// Download is the handler for a request to download a beatmap
func Download(c *api.Context) {
	// get the beatmap ID
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		errorMessage(c, 400, "Malformed ID")
		return
	}

	// fetch beatmap set and make sure it exists.
	set, err := models.FetchSet(c.DB, id, false)
	if err != nil {
		c.Err(err)
		errorMessage(c, 500, "Could not fetch set")
		return
	}
	if set == nil {
		errorMessage(c, 404, "Set not found")
		return
	}
	if set.RankedStatus <= 0 {
		errorMessage(c, 406, "Unranked beatmap sets are currently not available for download, following a warning")
		return
	}

	// use novideo only when we are requested to get a beatmap having a video
	// and novideo is in the request
	noVideo := set.HasVideo && existsQueryKey(c, "novideo")

	cbm, shouldDownload := c.House.AcquireBeatmap(&housekeeper.CachedBeatmap{
		ID:         id,
		NoVideo:    noVideo,
		LastUpdate: set.LastUpdate,
	})

	if shouldDownload {
		err := downloadBeatmap(c.DLClient, cbm, c.House)
		if err != nil {
			c.Err(err)
			errorMessage(c, 500, "Internal error")
			return
		}
	} else {
		cbm.MustBeDownloaded()
	}

	cbm.SetLastRequested(time.Now())

	if cbm.FileSize() == 0 {
		errorMessage(c, 504, "The beatmap could not be downloaded (probably got deleted from the osu! website)")
		return
	}

	f, err := cbm.File()
	if err != nil {
		c.Err(err)
		errorMessage(c, 500, "Internal error")
		return
	}
	defer f.Close()

	c.WriteHeader("Content-Type", "application/octet-stream")
	c.WriteHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fmt.Sprintf("%d %s - %s.osz", set.ID, set.Artist, set.Title)))
	c.WriteHeader("Content-Length", strconv.FormatUint(uint64(cbm.FileSize()), 10))
	c.Code(200)

	_, err = io.Copy(c, f)
	if err != nil {
		c.Err(err)
	}
}

func downloadBeatmap(c *downloader.Client, b *housekeeper.CachedBeatmap, house *housekeeper.House) error {
	log.Println("[⬇]", b.String())

	var fileSize uint64
	defer func() {
		// We need to wrap this inside a function because this way the arguments
		// to DownloadCompleted are actually evaluated during the defer call.
		b.DownloadCompleted(fileSize, house)
	}()

	// Start downloading.
	r, err := c.Download(b.ID, b.NoVideo)
	if err != nil {
		if err == downloader.ErrNoRedirect {
			return nil
		}
		return err
	}
	defer r.Close()

	// open the file we will write the beatmap into
	f, err := b.CreateFile()
	if err != nil {
		return err
	}
	defer f.Close()

	fSizeRaw, err := io.Copy(f, r)
	fileSize = uint64(fSizeRaw)
	if err != nil {
		return err
	}
	return nil
}

func init() {
	api.GET("/d/:id", Download)
}


text:
package monix.eval

import minitest.SimpleTestSuite
import monix.execution.Scheduler.Implicits.global

import scala.concurrent.{Await, TimeoutException}
import scala.concurrent.duration._

object TaskBlockingSuite extends SimpleTestSuite {
  test("blocking on future should work") {
    val source1 = Task.evalAsync(100)
    val source2 = Task.evalAsync(200).onErrorHandleWith { case e: Exception => Task.raiseError(e) }

    val derived = source1.map { x =>
      val r = Await.result(source2.runToFuture, 10.seconds)
      r + x
    }

    val result = Await.result(derived.runToFuture, 10.seconds)
    assertEquals(result, 300)
  }

  test("blocking on async") {
    for (_ <- 0 until 1000) {
      val task = Task.evalAsync(1)
      assertEquals(task.runSyncUnsafe(Duration.Inf), 1)
    }
  }

  test("blocking on async.flatMap") {
    for (_ <- 0 until 1000) {
      val task = Task.evalAsync(1).flatMap(_ => Task.evalAsync(2))
      assertEquals(task.runSyncUnsafe(Duration.Inf), 2)
    }
  }

  test("blocking on memoize") {
    for (_ <- 0 until 1000) {
      val task = Task.evalAsync(1).flatMap(_ => Task.evalAsync(2)).memoize
      assertEquals(task.runSyncUnsafe(Duration.Inf), 2)
      assertEquals(task.runSyncUnsafe(Duration.Inf), 2)
    }
  }

  test("timeout exception") {
    intercept[TimeoutException] {
      Task.never[Unit].runSyncUnsafe(100.millis)
    }
    ()
  }
}


text:
layout: post
title: Rational Root Theorem
date: 2015-07-18 21:53:00 +04:00
---

The Rational Root Theorem
--------------------------

Let $$f(x)=a_{n}x^n+a_{n-1}x^{n-1}+...+a_0$$ be an integer polynomial. Then the rational roots theorem states that all rational roots of $$f$$ have the form $$p/q$$ where $$p\mid a_0$$ and $$q\mid a_{n}$$. To see that $$p\mid a_0$$, plut $$p/q$$ into $$f$$ and then clear the denominator so that we have

$$
p^na_n+\cdots+q^na_0=0,
$$
so then considering the equation modulo $$q$$ gives the result. For the other result, consider the equation modulo $$p$$.

Here is an easy application:

Let $$f(x)=x^3+6x^2-32$$. Define $$T_{c,f}(x)=\sum_{n=0}^\infty a_n(x-c)^n$$ to be the Taylor series centered at $$c$$ of $$f$$. For what values does $$a_0=0$$.

* $$c=3,2$$
* $$c=-3,3,-2$$
* $$c=4,2$$
* $$c=-4,2,-2$$
* $$c=-4,2$$

The term $$a_n$$ is $$f^{(n)}(c)$$, so this is just asking for where $$f(x)=0$$. Now we are only presented with integer roots, So, by the rational roots theorem, we see that these roots must be divisors of $$32$$. So, we nede only check $$\pm 2,4$$. In particular we know that only one of each of these will be a root because the leading term is odd and the remaining terms are even. Now plugging in $$4$$ and $$2$$, we find the roots $$-4$$ and $$2$$.


text:
package com.codingspezis.android.metalonly.player.stream.metadata;

import com.codingspezis.android.metalonly.player.*;
import com.codingspezis.android.metalonly.player.favorites.*;

import org.slf4j.*;

import java.util.*;

/**
 * parses interpret title genre and moderator from meta data
 */
public class Metadata {

    public static final int REQUIRED_NUMBER_OF_STARS = 3;
    public static final int MODERATOR_SLICE = 1;
    public static final int GENRE_SLICE = 2;
    public static final String DEFAULT_MODEDRATOR = "MetalHead OnAir";
    public static final String DEFAULT_GENRE = "Mixed Metal";
    public static final Metadata DEFAULT_METADATA = new Metadata("", "", "", "");
    private static final String TAG = Metadata.class.getSimpleName();
    private static final Logger LOGGER = LoggerFactory.getLogger(TAG);
    private String interpret = "";
    private String title = "";
    private String genre = "";
    private String moderator = "";

    private Metadata(String moderator, String genre, String interpret, String title) {
        this.moderator = moderator;
        this.genre = genre;
        this.interpret = interpret;
        this.title = title;
    }

    /**
     * Parses the given data string into a Metadata object
     *
     * @param data the string to be parsed
     * @return a new Metadata object. Silently returns default object if something goes wrong
     */
    public static Metadata fromString(String data) {
        final String genre, moderator, interpret, title;
        try {
            if (numberOfStars(data) >= REQUIRED_NUMBER_OF_STARS) {
                String[] slices = data.split("\\*");
                genre = slices[GENRE_SLICE].trim();
                moderator = slices[MODERATOR_SLICE].trim();
                data = slices[0].trim();
            } else {
                moderator = DEFAULT_MODEDRATOR;
                genre = DEFAULT_GENRE;
            }
            interpret = data.substring(0, data.indexOf(" - ")).trim();
            title = data.substring(data.indexOf(" - ") + 2).trim();
            return new Metadata(moderator, genre, interpret, title);

        } catch (Exception e) {
            return DEFAULT_METADATA;
        }

    }

    /**
     * checks string str for occurrence of '*'
     *
     * @param toCount string to check
     * @return number of char '*' containing in str
     */
    private static int numberOfStars(String toCount) {
        if (BuildConfig.DEBUG) LOGGER.debug("numberOfStars({})", toCount);

        final String withoutStars = toCount.replaceAll("\\*", "");

        final int lengthWithStars = toCount.length();
        final int lengthWithoutStars = withoutStars.length();

        final int result = lengthWithStars - lengthWithoutStars;
        if (BuildConfig.DEBUG) LOGGER.debug("numberOfStars({}) -> ", toCount, result);

        return result;

    }

    public String getTitle() {
        return title;
    }

    public String getGenre() {
        return genre;
    }

    public String getModerator() {
        return moderator;
    }

    public Song toSong() {
        if (BuildConfig.DEBUG) LOGGER.debug("toSong()");
        long date = Calendar.getInstance().getTimeInMillis();

        moderator.replace(" OnAir", "");

        Song song = new Song(interpret, title, moderator, date);

        if (BuildConfig.DEBUG) LOGGER.debug("toSong() -> {}", song);
        return song;
    }

    @Override
    public String toString() {
        return "Metadata{" +
                "interpret='" + interpret + '\'' +
                ", title='" + title + '\'' +
                ", genre='" + genre + '\'' +
                ", moderator='" + moderator + '\'' +
                '}';
    }
}


text:
<?php namespace Fisharebest\Localization\Locale;

use Fisharebest\Localization\Territory\TerritoryLu;

class LocaleDeLu extends LocaleDe {
	public function territory() {
		return new TerritoryLu;
	}
}


text:
@interface OCTDefaultFileStorage ()

@property (copy, nonatomic) NSString *saveFileName;
@property (copy, nonatomic) NSString *baseDirectory;
@property (copy, nonatomic) NSString *temporaryDirectory;

@end

@implementation OCTDefaultFileStorage

#pragma mark -  Lifecycle

- (instancetype)initWithBaseDirectory:(NSString *)baseDirectory temporaryDirectory:(NSString *)temporaryDirectory
{
    return [self initWithToxSaveFileName:nil baseDirectory:baseDirectory temporaryDirectory:temporaryDirectory];
}

- (instancetype)initWithToxSaveFileName:(NSString *)saveFileName
                          baseDirectory:(NSString *)baseDirectory
                     temporaryDirectory:(NSString *)temporaryDirectory
{
    self = [super init];

    if (! self) {
        return nil;
    }

    if (! saveFileName) {
        saveFileName = @"save";
    }

    self.saveFileName = [saveFileName stringByAppendingString:@".tox"];
    self.baseDirectory = baseDirectory;
    self.temporaryDirectory = temporaryDirectory;

    return self;
}

#pragma mark -  OCTFileStorageProtocol

- (NSString *)pathForToxSaveFile
{
    return [self.baseDirectory stringByAppendingPathComponent:self.saveFileName];
}

- (NSString *)pathForDatabase
{
    return [self.baseDirectory stringByAppendingPathComponent:@"database"];
}

- (NSString *)pathForDownloadedFilesDirectory
{
    return [self.baseDirectory stringByAppendingPathComponent:@"downloads"];
}

- (NSString *)pathForUploadedFilesDirectory
{
    return [self.baseDirectory stringByAppendingPathComponent:@"uploads"];
}

- (NSString *)pathForTemporaryFilesDirectory
{
    return self.temporaryDirectory;
}

- (NSString *)pathForAvatarsDirectory
{
    return [self.baseDirectory stringByAppendingPathComponent:@"avatars"];
}

@end


text:
import React from 'react';

import BranchesTable from './BranchesTable';

import { UILibPureComponents } from '../components';

import UILibContext from '../components/UILibContext';
import { WithInfo } from './BranchInfoRow.story';

export default {
    component: BranchesTable,
};

export const WithOneBranch = (props) => (
    <UILibContext.Provider value={UILibPureComponents}>
        <BranchesTable {...props} />
    </UILibContext.Provider>
);

WithOneBranch.args = {
    repo: {
        branches: [
            {
                ...WithInfo.args.branch,
            },
        ],
    },
};


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PatchInstance = exports.State = exports.Patcher = void 0;
// import * as config from 'config';
const controller_1 = require("./controller");
const util = require("./util");
const data = require("./data");
const config_1 = require("./config");
const controller_wrapper_1 = require("./controller-wrapper");
const queue_1 = require("./queue");
class Patcher {
    /**
     * Starts a new installation/update, or resumes the operation if it was closed prematurely.
     * If the game is already managed by another joltron instance, joltron will send back an abort message and terminate itself.
     * client voodoo will re-emit this as a fatal error.
     *
     * This function returns immediately after launching the joltron executable.
     *
     * @param localPackage
     * @param getAuthToken a callback that joltron will use to fetch a new game api token for the package it's patching.
     * @param options
     */
    static async patch(localPackage, getAuthToken, options) {
        options = options || {};
        const dir = localPackage.install_dir;
        const port = await util.findFreePort();
        const gameUid = localPackage.update
            ? `${localPackage.update.id}-${localPackage.update.build.id}`
            : `${localPackage.id}-${localPackage.build.id}`;
        const args = [
            '--port',
            port.toString(),
            '--dir',
            dir,
            '--game',
            gameUid,
            '--platform-url',
            config_1.Config.domain + '/x/updater/check-for-updates',
            '--wait-for-connection',
            '5',
            '--symbiote',
            '--no-loader',
            '--no-self-update',
        ];
        if (options.authToken) {
            args.push('--auth-token', options.authToken);
        }
        if (options.runLater) {
            args.push('--launch');
        }
        args.push('install');
        // As far as joltron is concerned, an installation can also be an update, therefore it might need the migration file.
        await controller_1.Controller.ensureMigrationFile(localPackage);
        const controller = await controller_1.Controller.launchNew(args);
        return this.manageInstanceInQueue(new PatchInstance(controller, getAuthToken));
    }
    static async patchReattach(port, pid, authTokenGetter) {
        return this.manageInstanceInQueue(new PatchInstance(new controller_1.Controller(port, { process: pid }), authTokenGetter));
    }
    static manageInstanceInQueue(instance) {
        // Queue.manage(instance);
        instance.on('resumed', () => {
            queue_1.Queue.manage(instance);
        });
        return instance;
    }
}
exports.Patcher = Patcher;
var State;
(function (State) {
    State[State["Starting"] = 0] = "Starting";
    State[State["Downloading"] = 1] = "Downloading";
    State[State["Patching"] = 2] = "Patching";
    State[State["Finished"] = 3] = "Finished";
})(State = exports.State || (exports.State = {}));
class PatchInstance extends controller_wrapper_1.ControllerWrapper {
    constructor(controller, authTokenGetter) {
        super(controller);
        this.authTokenGetter = authTokenGetter;
        this.on('patcherState', (state) => {
            console.log('patcher got state: ' + state);
            const oldState = this._state;
            this._state = this._getState(state);
            // Only emit state if it's changed
            if (oldState !== this._state) {
                console.log('patcher emitting state: ' + this._state);
                this.controller.emit('state', this._state);
            }
        })
            .on('updateFailed', reason => {
            // If the update was canceled the 'context canceled' will be emitted as the updateFailed reason.
            if (reason === 'context canceled') {
                return;
            }
            this.controller.emit('done', reason);
        })
            .on('updateFinished', () => {
            this.controller.emit('done');
        });
        this._state = State.Starting;
        this._isPaused = false;
        this.getState().then(() => {
            queue_1.Queue.manage(this);
            if (this._isPaused) {
                this.controller.sendResume();
            }
        });
    }
    async getState() {
        const state = await this.controller.sendGetState(false);
        this._isPaused = state.isPaused;
        this._state = this._getState(state.patcherState);
    }
    _getState(state) {
        switch (state) {
            case data.PatcherState.Start:
            case data.PatcherState.Preparing:
                return State.Starting;
            case data.PatcherState.Download:
            case data.PatcherState.UpdateReady: // not really considered downloading, but it is the step right before extracting.
                return State.Downloading;
            case data.PatcherState.PrepareExtract:
            case data.PatcherState.Extract:
            case data.PatcherState.Cleanup:
                return State.Patching;
            case data.PatcherState.Finished:
                return State.Finished;
            default:
                throw new Error('Invalid state received: ' + state);
        }
    }
    get state() {
        return this._state;
    }
    isDownloading() {
        return this._state === State.Starting || this._state === State.Downloading;
    }
    isPatching() {
        return this._state === State.Patching;
    }
    isFinished() {
        return this._state === State.Finished;
    }
    isRunning() {
        return !this._isPaused;
    }
    getAuthToken() {
        return this.authTokenGetter();
    }
    async resume(options) {
        options = options || {};
        if (!options.authToken &&
            (this._state === State.Starting || this._state === State.Downloading)) {
            options.authToken = await this.authTokenGetter();
        }
        const result = await this.controller.sendResume(options);
        if (result.success) {
            this._isPaused = false;
        }
        return result;
    }
    async pause(queue) {
        const result = await this.controller.sendPause({ queue: !!queue });
        if (result.success) {
            this._isPaused = true;
        }
        return result;
    }
    cancel(waitOnlyForSend) {
        return this.controller.sendCancel(undefined, waitOnlyForSend);
    }
}
exports.PatchInstance = PatchInstance;


text:
<% if (rf.canShowReferenceID()) { %>

Reference ID

    <%= Formbuilder.templates['edit/reference_id']({rf: rf}) %>

<% } %>

Details

        <%= Formbuilder.templates['edit/label_description']({rf: rf}) %>

        <%= Formbuilder.templates['edit/checkboxes']() %>


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>mango.core.have_same_subd_decomp — mango 0.9.8 documentation</title>

    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="top" title="mango 0.9.8 documentation" href="../index.html" />
    <link rel="up" title="Fundamental Data Structures and Functions (mango.core)" href="../core.html" />
    <link rel="next" title="mango.core.isDds" href="mango.core.isDds.html" />
    <link rel="prev" title="mango.core.itemfreq" href="mango.core.itemfreq.html" />

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Fundamental Data Structures and Functions  (<tt class="docutils literal">mango.core</tt>) »

mango.core.have_same_subd_decomp¶

<tt class="descclassname">mango.core.</tt><tt class="descname">have_same_subd_decomp</tt><big>(</big>dds0, dds1<big>)</big>¶

Returns <tt class="samp docutils literal">True</tt> if pairs of non-halo-sub-domains on all processes have the
same (global) non-halo-sub-domain origin index and
same non-halo-sub-domain shape. Note: performs an MPI allreduce operation.

<col class="field-name" />
<col class="field-body" />

Parameters:

dds0 (<tt class="xref py py-obj docutils literal">mango.Dds</tt>) – Array.

dds1 (<tt class="xref py py-obj docutils literal">mango.Dds</tt>) – Array.

Return type:
<tt class="xref py py-obj docutils literal">bool</tt>

Returns:
<tt class="samp docutils literal">True</tt> if MPI non-halo-subdomain decomposition is the
same for <tt class="samp docutils literal">dds0</tt> and <tt class="samp docutils literal">dds1</tt>.

Previous topic

mango.core.itemfreq

Next topic

mango.core.isDds

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Fundamental Data Structures and Functions  (<tt class="docutils literal">mango.core</tt>) »

        © Copyright 2014, Department of Applied Mathematics, The Australian National University.
      Created using Sphinx 1.2.3.


text:
r"""
Very simple script to replace a template with another one.

It also converts the old MediaWiki boilerplate format to the new format.

Syntax: python template.py [-remove] [xml[:filename]] oldTemplate [newTemplate]

Specify the template on the command line. The program will pick up the template
page, and look for all pages using it. It will then automatically loop over
them, and replace the template.

Command line options:

-remove      Remove every occurrence of the template from every article

-subst       Resolves the template by putting its text directly into the
             article. This is done by changing {{...}} or {{msg:...}} into
             {{subst:...}}.
             Substitution is not available inside <ref>...</ref>,
             <gallery>...</gallery>, <poem>...</poem> and <pagelist ... />
             tags.

-assubst     Replaces the first argument as old template with the second
             argument as new template but substitutes it like -subst does.
             Using both options -remove and -subst in the same command line has
             the same effect.

-xml         retrieve information from a local dump
             (https://download.wikimedia.org). If this argument isn't given,
             info will be loaded from the maintenance page of the live wiki.
             argument can also be given as "-xml:filename.xml".

-onlyuser:   Only process pages edited by a given user

-skipuser:   Only process pages not edited by a given user

-timestamp:  (With -onlyuser or -skipuser). Only check for a user where his
             edit is not older than the given timestamp. Timestamp must be
             writen in MediaWiki timestamp format which is "%Y%m%d%H%M%S".
             If this parameter is missed, all edits are checked but this is
             restricted to the last 100 edits.

-summary:    Lets you pick a custom edit summary. Use quotes if edit summary
             contains spaces.

-always      Don't bother asking to confirm any of the changes, Just Do It.

-addcat:     Appends the given category to every page that is edited. This is
             useful when a category is being broken out from a template
             parameter or when templates are being upmerged but more
             information must be preserved.

other:       First argument is the old template name, second one is the new
             name.

             If you want to address a template which has spaces, put quotation
             marks around it, or use underscores.

Examples:

If you have a template called [[Template:Cities in Washington]] and want to
change it to [[Template:Cities in Washington state]], start

    python pwb.py template "Cities in Washington" "Cities in Washington state"

Move the page [[Template:Cities in Washington]] manually afterwards.

If you have a template called [[Template:test]] and want to substitute it only
on pages in the User: and User talk: namespaces, do:

    python pwb.py template test -subst -namespace:2 -namespace:3

Note that -namespace: is a global Pywikibot parameter

This next example substitutes the template lived with a supplied edit summary.
It only performs substitutions in main article namespace and doesn't prompt to
start replacing. Note that -putthrottle: is a global Pywikibot parameter.

    python pwb.py template -putthrottle:30 -namespace:0 lived -subst -always \
        -summary:"BOT: Substituting {{lived}}, see [[WP:SUBST]]."

This next example removes the templates {{cfr}}, {{cfru}}, and {{cfr-speedy}}
from five category pages as given:

    python pwb.py template cfr cfru cfr-speedy -remove -always \
        -page:"Category:Mountain monuments and memorials" \
        -page:"Category:Indian family names" \
        -page:"Category:Tennis tournaments in Belgium" \
        -page:"Category:Tennis tournaments in Germany" \
        -page:"Category:Episcopal cathedrals in the United States" \
        -summary:"Removing Cfd templates from category pages that survived."

This next example substitutes templates test1, test2, and space test on all
pages:

    python pwb.py template test1 test2 "space test" -subst -always

"""
#
# (C) Daniel Herding, 2004
# (C) Rob W.W. Hooft, 2003-2005
# (C) xqt, 2009-2017
# (C) Pywikibot team, 2004-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

__version__ = '$Id$'
#

import re

from warnings import warn

import pywikibot

from pywikibot import i18n, pagegenerators, textlib, Bot

from pywikibot.exceptions import ArgumentDeprecationWarning
from pywikibot.pagegenerators import XMLDumpPageGenerator
from pywikibot.tools import deprecated

from scripts.replace import ReplaceRobot as ReplaceBot

@deprecated('XMLDumpPageGenerator')
class XmlDumpTemplatePageGenerator(XMLDumpPageGenerator):

    """
    Generator which yields Pages that transclude a template.

    These pages will be retrieved from a local XML dump file
    (cur table), and may not still transclude the template.
    """

    def __init__(self, templates, xmlfilename):
        """
        Constructor.

        Arguments:
            * templateNames - A list of Page object representing the searched
                              templates
            * xmlfilename   - The dump's path, either absolute or relative

        """
        self.templates = templates
        self.xmlfilename = xmlfilename
        mysite = pywikibot.Site()
        # regular expression to find the original template.
        # {{vfd}} does the same thing as {{Vfd}}, so both will be found.
        # The old syntax, {{msg:vfd}}, will also be found.
        templatePatterns = []
        for template in self.templates:
            templatePattern = template.title(withNamespace=False)
            if mysite.namespaces[10].case == 'first-letter':
                templatePattern = '[%s%s]%s' % (templatePattern[0].upper(),
                                                templatePattern[0].lower(),
                                                templatePattern[1:])
            templatePattern = re.sub(' ', '[_ ]', templatePattern)
            templatePatterns.append(templatePattern)
        templateRegex = re.compile(
            r'\{\{ *([mM][sS][gG]:)?(?:%s) *(?P<parameters>\|[^}]+|) *}}'
            % '|'.join(templatePatterns))

        super(XmlDumpTemplatePageGenerator, self).__init__(
            xmlfilename, site=mysite, text_predicate=templateRegex.search)

class TemplateRobot(ReplaceBot):

    """This bot will replace, remove or subst all occurrences of a template."""

    def __init__(self, generator, templates, **kwargs):
        """
        Constructor.

        @param generator: the pages to work on
        @type generator: iterable
        @param templates: a dictionary which maps old template names to
            their replacements. If remove or subst is True, it maps the
            names of the templates that should be removed/resolved to None.
        @type templates: dict
        """
        self.availableOptions.update({
            'subst': False,
            'remove': False,
            'summary': None,
            'addedCat': None,
        })

        Bot.__init__(self, generator=generator, **kwargs)

        self.templates = templates

        # get edit summary message if it's empty
        if not self.getOption('summary'):
            comma = self.site.mediawiki_message('comma-separator')
            params = {'list': comma.join(self.templates.keys()),
                      'num': len(self.templates)}

            if self.getOption('remove'):
                self.options['summary'] = i18n.twtranslate(
                    self.site, 'template-removing', params)
            elif self.getOption('subst'):
                self.options['summary'] = i18n.twtranslate(
                    self.site, 'template-substituting', params)
            else:
                self.options['summary'] = i18n.twtranslate(
                    self.site, 'template-changing', params)

        replacements = []
        exceptions = {}
        builder = textlib._MultiTemplateMatchBuilder(self.site)
        for old, new in self.templates.items():
            templateRegex = builder.pattern(old)

            if self.getOption('subst') and self.getOption('remove'):
                replacements.append((templateRegex,
                                     r'{{subst:%s\g<parameters>}}' % new))
                exceptions['inside-tags'] = ['ref', 'gallery', 'poem',
                                             'pagelist', ]
            elif self.getOption('subst'):
                replacements.append((templateRegex,
                                     r'{{subst:%s\g<parameters>}}' % old))
                exceptions['inside-tags'] = ['ref', 'gallery', 'poem',
                                             'pagelist', ]
            elif self.getOption('remove'):
                replacements.append((templateRegex, ''))
            else:
                template = pywikibot.Page(self.site, new, ns=10)
                if not template.exists():
                    pywikibot.warning(u'Template "%s" does not exist.' % new)
                    if not pywikibot.input_yn('Do you want to proceed anyway?',
                                              default=False, automatic_quit=False):
                        continue
                replacements.append((templateRegex,
                                     r'{{%s\g<parameters>}}' % new))

        super(TemplateRobot, self).__init__(
            generator, replacements, exceptions,
            always=self.getOption('always'),
            addedCat=self.getOption('addedCat'),
            summary=self.getOption('summary'))

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    templateNames = []
    templates = {}
    options = {}
    # If xmlfilename is None, references will be loaded from the live wiki.
    xmlfilename = None
    user = None
    skip = False
    timestamp = None

    # read command line parameters
    local_args = pywikibot.handle_args(args)

    # Avoid conflicts with pagegenerators.py parameters.
    if any(arg.startswith('-category:') for arg in local_args):
        warn('-category (to append a category to each edited page) has been'
             ' renamed to -addcat; make sure you are using the correct param.',
             ArgumentDeprecationWarning)

    site = pywikibot.Site()
    genFactory = pagegenerators.GeneratorFactory()
    for arg in local_args:
        if arg == '-remove':
            options['remove'] = True
        elif arg == '-subst':
            options['subst'] = True
        elif arg == '-assubst':
            options['subst'] = options['remove'] = True
        elif arg == '-always':
            options['always'] = True
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlfilename = pywikibot.input(
                    u'Please enter the XML dump\'s filename: ')
            else:
                xmlfilename = arg[5:]
        elif arg.startswith('-addcat:'):
            options['addedCat'] = arg[len('-addcat:'):]
        elif arg.startswith('-summary:'):
            options['summary'] = arg[len('-summary:'):]
        elif arg.startswith('-onlyuser:'):
            user = arg[len('-onlyuser:'):]
        elif arg.startswith('-skipuser:'):
            user = arg[len('-skipuser:'):]
            skip = True
        elif arg.startswith('-timestamp:'):
            timestamp = arg[len('-timestamp:'):]
        else:
            if not genFactory.handleArg(arg):
                templateName = pywikibot.Page(site, arg, ns=10)
                templateNames.append(templateName.title(withNamespace=False))

    if not templateNames:
        pywikibot.bot.suggest_help(missing_parameters=['templates'])
        return False

    if options.get('subst', False) ^ options.get('remove', False):
        for templateName in templateNames:
            templates[templateName] = None
    else:
        try:
            for i in range(0, len(templateNames), 2):
                templates[templateNames[i]] = templateNames[i + 1]
        except IndexError:
            pywikibot.output('Unless using solely -subst or -remove, '
                             'you must give an even number of template names.')
            return

    oldTemplates = []
    for templateName in templates.keys():
        oldTemplate = pywikibot.Page(site, templateName, ns=10)
        oldTemplates.append(oldTemplate)

    if xmlfilename:
        builder = textlib._MultiTemplateMatchBuilder(site)
        predicate = builder.search_any_predicate(oldTemplates)

        gen = XMLDumpPageGenerator(
            xmlfilename, site=site, text_predicate=predicate)
    else:
        gen = genFactory.getCombinedGenerator()

    if not gen:
        gens = [
            pagegenerators.ReferringPageGenerator(t, onlyTemplateInclusion=True)
            for t in oldTemplates
        ]
        gen = pagegenerators.CombinedPageGenerator(gens)
        gen = pagegenerators.DuplicateFilterPageGenerator(gen)
    if user:
        gen = pagegenerators.UserEditFilterGenerator(gen, user, timestamp, skip,
                                                     max_revision_depth=100,
                                                     show_filtered=True)

    if not genFactory.gens:
        # make sure that proper namespace filtering etc. is handled
        gen = genFactory.getCombinedGenerator(gen)

    if not genFactory.nopreload:
        gen = pagegenerators.PreloadingGenerator(gen)

    bot = TemplateRobot(gen, templates, site=site, **options)
    bot.run()

if __name__ == "__main__":
    try:
        main()
    except Exception:
        pywikibot.error("Fatal error:", exc_info=True)


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var http_1 = require("@angular/http");
var config_1 = require("../config");
var grocery_1 = require("./grocery");
var Rx_1 = require("rxjs/Rx");
require("rxjs/add/operator/map");
var GroceryListService = (function () {
    function GroceryListService(_http) {
        this._http = _http;
    }
    GroceryListService.prototype.load = function () {
        return this._http.get(config_1.Config.apiUrl + "Groceries", {
            headers: this.getHeaders()
        })
            .map(function (res) { return res.json(); })
            .map(function (data) {
            var groceryList = [];
            data.Result.forEach(function (grocery) {
                groceryList.push(new grocery_1.Grocery(grocery.Id, grocery.Name, grocery.Done || false, grocery.Deleted || false));
            });
            return groceryList;
        })
            .catch(this.handleErrors);
    };
    GroceryListService.prototype.add = function (name) {
        return this._http.post(config_1.Config.apiUrl + "Groceries", JSON.stringify({ Name: name }), { headers: this.getHeaders() })
            .map(function (res) { return res.json(); })
            .map(function (data) {
            return new grocery_1.Grocery(data.Result.Id, name, false, false);
        })
            .catch(this.handleErrors);
    };
    GroceryListService.prototype._put = function (id, data) {
        return this._http.put(config_1.Config.apiUrl + "Groceries/" + id, JSON.stringify(data), { headers: this.getHeaders() })
            .catch(this.handleErrors);
    };
    GroceryListService.prototype.setDeleteFlag = function (item) {
        return this._put(item.id, { Deleted: !item.deleted });
    };
    GroceryListService.prototype.restore = function (groceries) {
        var indeces = [];
        groceries.forEach(function (grocery) {
            indeces.push(grocery.id);
        });
        var headers = this.getHeaders();
        headers.append("X-Everlive-Filter", JSON.stringify({
            "Id": {
                "$in": indeces
            }
        }));
        return this._http.put(config_1.Config.apiUrl + "Groceries", JSON.stringify({
            Deleted: false,
            Done: false
        }), { headers: headers })
            .catch(this.handleErrors);
    };
    GroceryListService.prototype.toggleDoneFlag = function (item) {
        return this._put(item.id, { Done: !item.done });
    };
    GroceryListService.prototype.deleteForever = function (item) {
        return this._http.delete(config_1.Config.apiUrl + "Groceries/" + item.id, { headers: this.getHeaders() })
            .map(function (res) { return res.json(); })
            .catch(this.handleErrors);
    };
    GroceryListService.prototype.getHeaders = function () {
        var headers = new http_1.Headers();
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", "Bearer " + config_1.Config.token);
        return headers;
    };
    GroceryListService.prototype.handleErrors = function (error) {
        console.log(JSON.stringify(error.json()));
        return Rx_1.Observable.throw(error);
    };
    GroceryListService = __decorate([
        core_1.Injectable(),
        __metadata('design:paramtypes', [http_1.Http])
    ], GroceryListService);
    return GroceryListService;
}());
exports.GroceryListService = GroceryListService;
//# sourceMappingURL=grocery-list.service.js.map


text:
/*global beforeEach, describe, it, Stem */

describe('TagSet Model', function () {
    'use strict';

    beforeEach(function () {
        this.TagSetModel = new Stem.Models.TagSet({
            tags: new Stem.Collections.Tags([
                new Stem.Models.Tag({label: 'label 1', selected: false}),
                new Stem.Models.Tag({label: 'label 2', selected: true}),
                new Stem.Models.Tag({label: 'label 3', selected: true})
            ])
        });
    });

    it('should default title to "Tags"', function() {
        this.TagSetModel.get('title').should.equal('Tags');
    });

    it('should return the set of selected tags', function() {
        this.TagSetModel.getSelectedTags().length.should.equal(2);
        this.TagSetModel.getSelectedTags().should.include('label 2');
        this.TagSetModel.getSelectedTags().should.include('label 3');
    });

});


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

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'SharedBounty.disabled'
        db.add_column(u'bountyfulcoinsapp_sharedbounty', 'disabled',
                      self.gf('django.db.models.fields.BooleanField')(default=False),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'SharedBounty.disabled'
        db.delete_column(u'bountyfulcoinsapp_sharedbounty', 'disabled')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'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': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'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', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
            u'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', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'bountyfulcoinsapp.bounty': {
            'Meta': {'object_name': 'Bounty'},
            'amount': ('django.db.models.fields.DecimalField', [], {'default': '0.0', 'max_digits': '20', 'decimal_places': '2'}),
            'currency': ('django.db.models.fields.CharField', [], {'default': "'BTC'", 'max_length': '15'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'link': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['bountyfulcoinsapp.Link']"}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        },
        u'bountyfulcoinsapp.link': {
            'Meta': {'object_name': 'Link'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'url': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '200'})
        },
        u'bountyfulcoinsapp.sharedbounty': {
            'Meta': {'object_name': 'SharedBounty'},
            'bounty': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['bountyfulcoinsapp.Bounty']", 'unique': 'True'}),
            'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'disabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'users_voted': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}),
            'votes': ('django.db.models.fields.IntegerField', [], {'default': '1'})
        },
        u'bountyfulcoinsapp.tag': {
            'Meta': {'object_name': 'Tag'},
            'bounties': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'tags'", 'symmetrical': 'False', 'to': u"orm['bountyfulcoinsapp.Bounty']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'})
        },
        u'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'}),
            u'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'})
        }
    }

    complete_apps = ['bountyfulcoinsapp']


text:
[![Build Status]](https://travis-ci.org/mantoni/live-list.js)
[![SemVer]](http://semver.org)
[![License]](https://github.com/mantoni/live-list.js/blob/master/LICENSE)

Fast linked list with live iterator. The list can be modified while iterating
over the items.

## Install with npm

```
npm install live-list
```

## Browser compatibility

To use this module in a browser, download the npm package and then use
[Browserify](http://browserify.org) to create a standalone version.

## Usage

```js
var List = require('live-list').List;

var l = new List();
l.push(3);
l.unshift(1);
l.insert(2, 3);

var v, i = l.iterator();
while ((v = i.next()) !== undefined) {
  console.log(v);
}
```

## List API

- `length`: Reflects the number of items in the list
- `push(value)`: Appends a value to the list
- `unshift(value)`: Prepends a value to the list
- `insert(value, before)`: Inserts a value before another value
- `remove(value)`: Removes the given value from the list
- `removeAll()`: Removes all values from the list
- `toArray()`: Returns a new array with all values in the list
- `iterator()`: Returns a new `Iterator`

## Iterator API

The iterator is derived from [min-iterator][] and extends the API with these
functions:

- `insert(value)`: Inserts a value into the list before the value
  returned by the last call to `next()`
- `remove()`: Removes the value from the list that was returned
  by the last call to `next()`

[min-iterator]: https://github.com/mantoni/min-iterator.js

## License

MIT

[Build Status]: http://img.shields.io/travis/mantoni/live-list.js.svg
[SemVer]: http://img.shields.io/:semver-%E2%9C%93-brightgreen.svg
[License]: http://img.shields.io/npm/l/live-list.svg


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Rc. Secc. Accad. Sci. Ist. Bologna, sér. 6 6: 123 (1909)

#### Original name
Pilobolus borzianus var. geminatus Morini, 1909

### Remarks
null


text:
require 'test_helper'

class InaccurateWorkerTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  def test_truth
    assert true
  end
end