text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>HSBC Premier</title>
    <meta name="description" content="" />
    <link href="//fonts.googleapis.com/css?family=Noto+Sans:300,400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Noto+Serif:400,700,400italic" rel="stylesheet" type="text/css">
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="//www.agency-showcase.com/themes/mirum/assets/css/style.css?v=1.0.0" rel="stylesheet" type="text/css">
    <link href="//www.agency-showcase.com/themes/mirum/assets/css/animate.min.css?v=1.0.0" rel="stylesheet" type="text/css">
    <link href="//www.agency-showcase.com/themes/mirum/favicon.ico" rel="shortcut icon">
    <link rel="canonical" href="http://www.agency-showcase.com/2015/10/23/HSBC-Premier.html" />

    <meta property="og:site_name" content="Mirum Singapore Agency Showcase" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="HSBC Premier" />
    <meta property="og:description" content="Client: The Hongkong and Shanghai Banking Corporation (HSBC) Project: Future of Retirement: Demonstrating Thought Leadership Client Background Every year since 2005, HSBC has published The Future of Retirement, an independent study on global retirement trends. Yet as competitors..." />
    <meta property="og:url" content="http://www.agency-showcase.com/2015/10/23/HSBC-Premier.html" />
    <meta property="og:image" content="https://cloud.githubusercontent.com/assets/14326240/10627548/8713e7ea-77ed-11e5-953d-4c41f930fc16.jpg" />
    <meta property="article:published_time" content="2015-10-22T16:00:00.000Z" />
    <meta property="article:modified_time" content="2015-10-23T07:00:28.082Z" />
    <meta property="article:tag" content="HSBC" />
    <meta property="article:tag" content="Premier" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="HSBC Premier" />
    <meta name="twitter:description" content="Client: The Hongkong and Shanghai Banking Corporation (HSBC) Project: Future of Retirement: Demonstrating Thought Leadership Client Background Every year since 2005, HSBC has published The Future of Retirement, an independent study on global retirement trends. Yet as competitors..." />
    <meta name="twitter:url" content="http://www.agency-showcase.com/2015/10/23/HSBC-Premier.html" />
    <meta name="twitter:image:src" content="https://cloud.githubusercontent.com/assets/14326240/10627548/8713e7ea-77ed-11e5-953d-4c41f930fc16.jpg" />

    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Mirum Singapore Agency Showcase" href="http://www.agency-showcase.com/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Mirum Singapore Agency Showcase

HSBC Premier

         <time class="timesince date" data-timesince="1445529600" datetime="2015-10-23T00:00" title="23 October 2015">2015-10-23 00:00:00<ago class="ago"></time>
             HSBC,  Premier
             Mirum Singapore

Client: The Hongkong and Shanghai Banking Corporation (HSBC)

Project: Future of Retirement: Demonstrating Thought Leadership

Client Background

Every year since 2005, HSBC has published The Future of Retirement, an independent study on global retirement trends. Yet as competitors like DBS and OCBC venture into this lucrative sphere, HSBC wanted to reaffirm its position in the Singapore market as a thought leader in retirement planning.

The Objective

To drive awareness and conversion of HSBC Premier retirement products and services by leveraging on content marketing.

The Idea

We came up with a Future of Retirement microsite that explored the themes in the FoR report in greater detail.

The Result

Cntent was published regularly under the buckets of Motivate, Educate, and Act, ensuring that users left the site feeling empowered to act on their future and to reach out to HSBC for wealth planning advice.

A platform for the retirement conversation - The site features an effective mix of long form and short form articles, profiles, factoids, and in the future—videos.

Vist Site

          Privacy | Terms | A WPP Company

Copyright © 2015 Mirum Singapore


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

/**
 * User Helpers
 *
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		Phil Sturgeon
 */

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

/**
 * Return a users display name based on settings
 *
 * @param int $user the users id
 * @return  string
 */
function user_displayname($user)
{
    if (is_numeric($user))
    {
        $user = ci()->ion_auth->get_user($user);
    }

    $user = (array) $user;

	// Static var used for cache
	if ( ! isset($_users))
	{
		static $_users = array();
	}

	// check it exists
	if (isset($_users[$user['id']]))
	{
		return $_users[$user['id']];
	}

    $user_name = empty($user['display_name']) ? $user['username'] : $user['display_name'];

    if (ci()->settings->enable_profiles)
    {
        $user_name = anchor('users/profile/view/' . $user['id'], $user_name);
    }

	$_users[$user['id']] = $user_name;

    return $user_name;
}
/* End of file users/helpers/user_helper.php */

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Air Toolkit - Test Page</title>
    <link rel="stylesheet" href="/media/css/context/style.css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
  </head>

  <body>
    <div id="content">
      Hai.
    </div>
  </body>
</html>


text:
using System.Security.Cryptography;

namespace Tamir.SharpSsh.jsch.jce
{
    /* -*-mode:java; c-basic-offset:2; -*- */
    /*
	Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

	  1. Redistributions of source code must retain the above copyright notice,
		 this list of conditions and the following disclaimer.

	  2. Redistributions in binary form must reproduce the above copyright
		 notice, this list of conditions and the following disclaimer in
		 the documentation and/or other materials provided with the distribution.

	  3. The names of the authors may not be used to endorse or promote products
		 derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
	FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
	INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
	LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
	OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
	EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	*/

    public class KeyPairGenRSA : jsch.KeyPairGenRSA
    {
        private byte[] d; // private
        private byte[] e; // public
        private byte[] n;

        private byte[] c; //  coefficient
        private byte[] ep; // exponent p
        private byte[] eq; // exponent q
        private byte[] p; // prime p
        private byte[] q; // prime q

        private RSAParameters RSAKeyInfo;

        public void init(int key_size)
        {
            //    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            //    keyGen.initialize(key_size, new SecureRandom());
            //    KeyPair pair = keyGen.generateKeyPair();
            //
            //    PublicKey pubKey=pair.getPublic();
            //    PrivateKey prvKey=pair.getPrivate();

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(key_size);
            RSAKeyInfo = rsa.ExportParameters(true);

            //    d=((RSAPrivateKey)prvKey).getPrivateExponent().toByteArray();
            //    e=((RSAPublicKey)pubKey).getPublicExponent().toByteArray();
            //    n=((RSAKey)prvKey).getModulus().toByteArray();
            //
            //    c=((RSAPrivateCrtKey)prvKey).getCrtCoefficient().toByteArray();
            //    ep=((RSAPrivateCrtKey)prvKey).getPrimeExponentP().toByteArray();
            //    eq=((RSAPrivateCrtKey)prvKey).getPrimeExponentQ().toByteArray();
            //    p=((RSAPrivateCrtKey)prvKey).getPrimeP().toByteArray();
            //    q=((RSAPrivateCrtKey)prvKey).getPrimeQ().toByteArray();

            d = RSAKeyInfo.D;
            e = RSAKeyInfo.Exponent;
            n = RSAKeyInfo.Modulus;

            c = RSAKeyInfo.InverseQ;
            ep = RSAKeyInfo.DP;
            eq = RSAKeyInfo.DQ;
            p = RSAKeyInfo.P;
            q = RSAKeyInfo.Q;
        }

        public byte[] getD()
        {
            return d;
        }

        public byte[] getE()
        {
            return e;
        }

        public byte[] getN()
        {
            return n;
        }

        public byte[] getC()
        {
            return c;
        }

        public byte[] getEP()
        {
            return ep;
        }

        public byte[] getEQ()
        {
            return eq;
        }

        public byte[] getP()
        {
            return p;
        }

        public byte[] getQ()
        {
            return q;
        }

        public RSAParameters KeyInfo
        {
            get { return RSAKeyInfo; }
        }
    }
}


text:
package com.googlecode.jmapper.integrationtest.performance;

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

import com.googlecode.jmapper.integrationtest.Performance;
import com.googlecode.jmapper.integrationtest.config.Constants;
import com.googlecode.jmapper.integrationtest.operations.bean.MapD;
import com.googlecode.jmapper.integrationtest.operations.bean.MapS;

public class MapPerformanceTest extends Performance<MapD, MapS> {

	@Override
	protected MapD staticMapping(MapS source) {
	   MapD destination = new MapD();
	   if(source.getAMapS()!=null){
		   destination.setATreeMapD(new TreeMap<String, String>(source.getAMapS()));
	   }
	   if(source.getAHashMapS()!=null){
		   destination.setAMapD(source.getAHashMapS());
	   }
	   if(source.getASortedMapS()!=null){
		   destination.setAHashMapD(new HashMap<String, String>(source.getASortedMapS()));
	   }
	   if(source.getATreeMapS()!=null){
		   destination.setASortedMapD(source.getATreeMapS());
	   }
	   return destination;
	}

	@Override
	protected MapS getSource() {
		return new MapS(put(new HashMap<String,String>(), "aMapS"),
						put(new HashMap<String,String>(), "aHashMapS"),
						put(new TreeMap<String,String>(), "aSortedMapS"),
						put(new TreeMap<String,String>(), "aTreeMapS"));
	}

	@Override
	protected int getInternalWeight() {
		return 10000;
	}

	@Override
	protected String titleOfTest() {
		return Constants.MapPerformanceTest;
	}

	private <T extends Map<E,E>,E> T  put(T map,E...elements ){
		for (E element : elements)	map.put(element,element);
		return map;
	}

}


text:
package emlab.gen.role;

import static org.junit.Assert.assertEquals;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import emlab.gen.domain.agent.DecarbonizationModel;
import emlab.gen.domain.agent.EnergyProducer;
import emlab.gen.domain.agent.Government;
import emlab.gen.domain.agent.NationalGovernment;
import emlab.gen.domain.contract.Loan;
import emlab.gen.domain.gis.Zone;
import emlab.gen.domain.market.CO2Auction;
import emlab.gen.domain.market.ClearingPoint;
import emlab.gen.domain.market.CommodityMarket;
import emlab.gen.domain.market.electricity.ElectricitySpotMarket;
import emlab.gen.domain.market.electricity.Segment;
import emlab.gen.domain.market.electricity.SegmentLoad;
import emlab.gen.domain.technology.Interconnector;
import emlab.gen.domain.technology.IntermittentResourceProfile;
import emlab.gen.domain.technology.PowerGeneratingTechnology;
import emlab.gen.domain.technology.PowerGridNode;
import emlab.gen.domain.technology.PowerPlant;
import emlab.gen.domain.technology.Substance;
import emlab.gen.repository.BidRepository;
import emlab.gen.repository.MarketRepository;
import emlab.gen.repository.PowerPlantDispatchPlanRepository;
import emlab.gen.repository.Reps;
import emlab.gen.repository.SegmentLoadRepository;
import emlab.gen.repository.ZoneRepository;
import emlab.gen.role.market.ClearIterativeCO2AndElectricitySpotMarketTwoCountryRole;
import emlab.gen.role.market.DetermineResidualLoadCurvesForTwoCountriesRole;
import emlab.gen.role.market.SubmitOffersToElectricitySpotMarketRole;
import emlab.gen.role.operating.DetermineFuelMixRole;
import emlab.gen.trend.HourlyCSVTimeSeries;
import emlab.gen.trend.LinearTrend;
import emlab.gen.trend.TriangularTrend;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/emlab-gen-test-context.xml" })
@Transactional
public class DetermineResidualLoadCurveTest {

    Logger logger = Logger.getLogger(RenewableTargetInvestmentRoleTest.class);

    @Autowired
    Reps reps;

    @Autowired
    SegmentLoadRepository segmentLoadRepository;

    @Autowired
    MarketRepository marketRepository;

    @Autowired
    BidRepository bidRepository;

    @Autowired
    PowerPlantDispatchPlanRepository plantDispatchPlanRepository;

    @Autowired
    ZoneRepository zoneRepository;

    @Autowired
    ClearIterativeCO2AndElectricitySpotMarketTwoCountryRole clearIterativeCO2AndElectricitySpotMarketTwoCountryRole;

    @Autowired
    SubmitOffersToElectricitySpotMarketRole submitOffersToElectricitySpotMarketRole;

    @Autowired
    DetermineFuelMixRole determineFuelMixRole;

    @Autowired
    DetermineResidualLoadCurvesForTwoCountriesRole determineResidualLoadCurvesForTwoCountriesRole;

    // 6 power plants in two markets, one intermittent power plant in each.
    @Before
    @Transactional
    public void setUp() throws Exception {
        DecarbonizationModel model = new DecarbonizationModel();
        model.setCo2TradingImplemented(false);
        model.setRealRenewableDataImplemented(false);
        model.setIterationSpeedFactor(3);
        model.setIterationSpeedCriterion(0.005);
        model.setCapDeviationCriterion(0.03);
        model.persist();

        Government gov = new Government().persist();
        LinearTrend co2TaxTrend = new LinearTrend().persist();
        co2TaxTrend.setStart(0);
        co2TaxTrend.setIncrement(0);
        gov.setCo2TaxTrend(co2TaxTrend);

        CO2Auction co2Auction = new CO2Auction().persist();

        Zone zone1 = new Zone();
        Zone zone2 = new Zone();
        zone1.setName("Zone 1");

        zone2.setName("Zone2");

        zone1.persist();
        zone2.persist();

        NationalGovernment natGov1 = new NationalGovernment().persist();
        NationalGovernment natGov2 = new NationalGovernment().persist();

        natGov1.setGovernedZone(zone1);
        natGov2.setGovernedZone(zone2);

        LinearTrend minCo2TaxTrend1 = new LinearTrend().persist();
        minCo2TaxTrend1.setStart(0);
        minCo2TaxTrend1.setIncrement(0);
        natGov1.setMinNationalCo2PriceTrend(minCo2TaxTrend1);

        LinearTrend minCo2TaxTrend2 = new LinearTrend().persist();
        minCo2TaxTrend2.setStart(0);
        minCo2TaxTrend2.setIncrement(0);
        natGov2.setMinNationalCo2PriceTrend(minCo2TaxTrend2);

        HourlyCSVTimeSeries load1TimeSeries = new HourlyCSVTimeSeries();
        load1TimeSeries.setFilename("/data/ZoneALoad.csv");

        HourlyCSVTimeSeries load2TimeSeries = new HourlyCSVTimeSeries();
        load2TimeSeries.setFilename("/data/ZoneBLoad.csv");

        load1TimeSeries.persist();
        load2TimeSeries.persist();

        PowerGridNode node1 = new PowerGridNode();
        PowerGridNode node2 = new PowerGridNode();
        node1.setCapacityMultiplicationFactor(1);
        node2.setCapacityMultiplicationFactor(1);
        node1.setZone(zone1);
        node2.setZone(zone2);
        node1.setName("Node1");
        node2.setName("Node2");
        node1.setHourlyDemand(load1TimeSeries);
        node2.setHourlyDemand(load2TimeSeries);
        node1.persist();
        node2.persist();

        HashSet<PowerGridNode> intNodes = new HashSet<PowerGridNode>();
        intNodes.add(node1);
        intNodes.add(node2);

        Interconnector interconnector = new Interconnector().persist();
        interconnector.setConnections(intNodes);
        interconnector.setCapacity(0);

        Segment S1 = new Segment();
        S1.setLengthInHours(10);
        S1.setSegmentID(1);
        S1.persist();

        Segment S2 = new Segment();
        S2.setLengthInHours(20);
        S2.setSegmentID(2);
        S2.persist();

        Segment S3 = new Segment();
        S3.setLengthInHours(20);
        S3.setSegmentID(3);
        S3.persist();

        Segment S4 = new Segment();
        S4.setLengthInHours(20);
        S4.setSegmentID(4);
        S4.persist();

        SegmentLoad segmentLoadMarket1S2 = new SegmentLoad().persist();
        segmentLoadMarket1S2.setSegment(S2);
        // segmentLoadMarket1S2.setBaseLoad(500.01);

        SegmentLoad segmentLoadMarket2S2 = new SegmentLoad().persist();
        segmentLoadMarket2S2.setSegment(S2);
        // segmentLoadMarket2S2.setBaseLoad(399.99);

        SegmentLoad segmentLoadMarket1S1 = new SegmentLoad().persist();
        segmentLoadMarket1S1.setSegment(S1);
        // segmentLoadMarket1S1.setBaseLoad(790);

        SegmentLoad segmentLoadMarket2S1 = new SegmentLoad().persist();
        segmentLoadMarket2S1.setSegment(S1);
        // segmentLoadMarket2S1.setBaseLoad(600);

        SegmentLoad segmentLoadMarket1S3 = new SegmentLoad().persist();
        segmentLoadMarket1S3.setSegment(S3);
        // segmentLoadMarket1S1.setBaseLoad(790);

        SegmentLoad segmentLoadMarket2S3 = new SegmentLoad().persist();
        segmentLoadMarket2S3.setSegment(S3);

        SegmentLoad segmentLoadMarket1S4 = new SegmentLoad().persist();
        segmentLoadMarket1S4.setSegment(S4);
        // segmentLoadMarket1S1.setBaseLoad(790);

        SegmentLoad segmentLoadMarket2S4 = new SegmentLoad().persist();
        segmentLoadMarket2S4.setSegment(S4);
        // segmentLoadMarket2S1.setBaseLoad(600);

        Set<SegmentLoad> segmentLoads1 = new HashSet<SegmentLoad>();
        segmentLoads1.add(segmentLoadMarket1S1);
        segmentLoads1.add(segmentLoadMarket1S2);
        segmentLoads1.add(segmentLoadMarket1S3);
        segmentLoads1.add(segmentLoadMarket1S4);

        Set<SegmentLoad> segmentLoads2 = new HashSet<SegmentLoad>();
        segmentLoads2.add(segmentLoadMarket2S1);
        segmentLoads2.add(segmentLoadMarket2S2);
        segmentLoads2.add(segmentLoadMarket2S3);
        segmentLoads2.add(segmentLoadMarket2S4);

        TriangularTrend demandGrowthTrend = new TriangularTrend();
        demandGrowthTrend.setMax(1);
        demandGrowthTrend.setMin(1);
        demandGrowthTrend.setStart(1);
        demandGrowthTrend.setTop(1);

        demandGrowthTrend.persist();

        ElectricitySpotMarket market1 = new ElectricitySpotMarket();
        market1.setName("Market1");
        market1.setZone(zone1);
        market1.setLoadDurationCurve(segmentLoads1);
        market1.setDemandGrowthTrend(demandGrowthTrend);
        market1.setValueOfLostLoad(2000);
        market1.persist();

        ElectricitySpotMarket market2 = new ElectricitySpotMarket();
        market2.setZone(zone2);
        market2.setName("Market2");
        market2.setLoadDurationCurve(segmentLoads2);
        market2.setDemandGrowthTrend(demandGrowthTrend);
        market2.setValueOfLostLoad(2000);
        market2.persist();

        Substance coal = new Substance().persist();
        coal.setName("Coal");
        coal.setEnergyDensity(1000);
        Substance gas = new Substance().persist();
        gas.setName("Gas");
        gas.setEnergyDensity(1000);

        CommodityMarket coalMarket =  new CommodityMarket().persist();
        CommodityMarket gasMarket = new CommodityMarket().persist();

        coalMarket.setSubstance(coal);
        gasMarket.setSubstance(gas);

        LinearTrend coalPrice = new LinearTrend().persist();
        coalPrice.setStart(3);
        coalPrice.setIncrement(1);

        LinearTrend gasPrice = new LinearTrend().persist();
        gasPrice.setStart(6);
        coalPrice.setIncrement(2);

        HashSet<Substance> fuelMixCoal = new HashSet<Substance>();
        fuelMixCoal.add(coal);

        HashSet<Substance> fuelMixGas = new HashSet<Substance>();
        fuelMixGas.add(gas);

        PowerGeneratingTechnology coalTech = new PowerGeneratingTechnology();
        coalTech.setFuels(fuelMixCoal);
        coalTech.setPeakSegmentDependentAvailability(1);
        coalTech.setBaseSegmentDependentAvailability(1);

        PowerGeneratingTechnology gasTech = new PowerGeneratingTechnology();
        gasTech.setFuels(fuelMixGas);
        gasTech.setPeakSegmentDependentAvailability(1);
        gasTech.setBaseSegmentDependentAvailability(1);

        PowerGeneratingTechnology windTech = new PowerGeneratingTechnology();
        windTech.setName("WindTech");
        windTech.setIntermittent(true);

        coalTech.persist();
        gasTech.persist();
        windTech.persist();

        IntermittentResourceProfile windIntermittentResourceProfile1 = new IntermittentResourceProfile();
        windIntermittentResourceProfile1.setIntermittentTechnology(windTech);
        windIntermittentResourceProfile1.setIntermittentProductionNode(node1);
        windIntermittentResourceProfile1.setFilename("/data/ResLFA.csv");

        IntermittentResourceProfile windIntermittentResourceProfile2 = new IntermittentResourceProfile();
        windIntermittentResourceProfile2.setIntermittentTechnology(windTech);
        windIntermittentResourceProfile2.setIntermittentProductionNode(node2);
        windIntermittentResourceProfile2.setFilename("/data/ResLFB.csv");

        windIntermittentResourceProfile1.persist();
        windIntermittentResourceProfile2.persist();

        EnergyProducer market1Prod1 = new EnergyProducer();
        market1Prod1.setName("market1Prod1");
        market1Prod1.setCash(0);
        market1Prod1.setPriceMarkUp(1);
        market1Prod1.setInvestorMarket(market1);

        EnergyProducer market1Prod2 = new EnergyProducer();
        market1Prod2.setCash(0);
        market1Prod2.setPriceMarkUp(1);
        market1Prod2.setName("market1Prod2");
        market1Prod2.setInvestorMarket(market1);

        EnergyProducer market2Prod1 = new EnergyProducer();
        market2Prod1.setCash(0);
        market2Prod1.setPriceMarkUp(1);
        market2Prod1.setName("market2Prod1");
        market2Prod1.setInvestorMarket(market2);

        EnergyProducer market2Prod2 = new EnergyProducer();
        market2Prod2.setCash(0);
        market2Prod2.setPriceMarkUp(1);
        market2Prod2.setName("market2Prod2");
        market2Prod2.setInvestorMarket(market2);

        market1Prod1.persist();
        market1Prod2.persist();
        market2Prod1.persist();

        Loan l1 = new Loan();
        l1.setAmountPerPayment(6000);
        l1.setNumberOfPaymentsDone(10);
        l1.setTotalNumberOfPayments(15);

        Loan l2 = new Loan();
        l2.setAmountPerPayment(5000);
        l2.setNumberOfPaymentsDone(29);
        l2.setTotalNumberOfPayments(19);

        Loan l3 = new Loan();
        l3.setAmountPerPayment(4000);
        l3.setNumberOfPaymentsDone(8);
        l3.setTotalNumberOfPayments(13);

        Loan l4 = new Loan();
        l4.setAmountPerPayment(3000);
        l4.setNumberOfPaymentsDone(7);
        l4.setTotalNumberOfPayments(12);

        Loan l5 = new Loan();
        l5.setAmountPerPayment(2000);
        l5.setNumberOfPaymentsDone(6);
        l5.setTotalNumberOfPayments(11);

        Loan l6 = new Loan();
        l6.setAmountPerPayment(1000);
        l6.setNumberOfPaymentsDone(5);
        l6.setTotalNumberOfPayments(10);

        l1.persist();
        l2.persist();
        l3.persist();
        l4.persist();
        l5.persist();
        l6.persist();

        // At 3 Eur/GJ has a mc of 24 Eur/Mwh
        PowerPlant pp1 = new PowerPlant();
        pp1.setTechnology(coalTech);
        pp1.setOwner(market1Prod1);
        pp1.setActualFixedOperatingCost(99000);
        pp1.setLoan(l1);
        pp1.setActualNominalCapacity(700);
        pp1.setActualEfficiency(0.45);
        pp1.setLocation(node1);
        pp1.setActualPermittime(0);
        pp1.setConstructionStartTime(-2);
        pp1.setActualLeadtime(0);
        pp1.setDismantleTime(10);
        pp1.setExpectedEndOfLife(10);
        pp1.setName("CoalInM1");

        // At 3 Eur/GJ has a mc of 27 Eur/MWh
        PowerPlant pp2 = new PowerPlant();
        pp2.setTechnology(coalTech);
        pp2.setOwner(market2Prod1);
        pp2.setActualFixedOperatingCost(99000);
        pp2.setLoan(l2);
        pp2.setActualNominalCapacity(1300);
        pp2.setActualEfficiency(0.40);
        pp2.setLocation(node2);
        pp2.setActualPermittime(0);
        pp2.setConstructionStartTime(-2);
        pp2.setActualLeadtime(0);
        pp2.setDismantleTime(10);
        pp2.setExpectedEndOfLife(10);
        pp2.setName("CoalInM2");

        // At 6 Eur/GJ has a mc of 36
        PowerPlant pp3 = new PowerPlant();
        pp3.setTechnology(gasTech);
        pp3.setOwner(market1Prod1);
        pp3.setActualFixedOperatingCost(99000);
        pp3.setLoan(l3);
        pp3.setActualNominalCapacity(650);
        pp3.setActualEfficiency(0.60);
        pp3.setLocation(node1);
        pp3.setActualPermittime(0);
        pp3.setConstructionStartTime(-2);
        pp3.setActualLeadtime(0);
        pp3.setDismantleTime(1000);
        pp3.setExpectedEndOfLife(2);
        pp3.setName("GasInM1");

        // At 6 Eur/GJ has a mc of 40 Eur/MWh
        PowerPlant pp4 = new PowerPlant();
        pp4.setTechnology(gasTech);
        pp4.setOwner(market2Prod2);
        pp4.setActualFixedOperatingCost(99000);
        pp4.setLoan(l3);
        pp4.setActualNominalCapacity(1000);
        pp4.setActualEfficiency(0.54);
        pp4.setLocation(node2);
        pp4.setActualPermittime(0);
        pp4.setConstructionStartTime(-2);
        pp4.setActualLeadtime(0);
        pp4.setDismantleTime(10);
        pp4.setExpectedEndOfLife(10);
        pp4.setName("GasInM2");

        pp1.persist();
        pp2.persist();
        pp3.persist();
        pp4.persist();

        // At 6 Eur/GJ has a mc of 36
        PowerPlant ppRes1 = new PowerPlant();
        ppRes1.setTechnology(windTech);
        ppRes1.setOwner(market1Prod1);
        ppRes1.setActualFixedOperatingCost(99000);
        ppRes1.setLoan(l5);
        ppRes1.setActualNominalCapacity(7000);
        ppRes1.setActualEfficiency(1);
        ppRes1.setLocation(node1);
        ppRes1.setActualPermittime(0);
        ppRes1.setConstructionStartTime(-8);
        ppRes1.setActualLeadtime(0);
        ppRes1.setDismantleTime(1000);
        ppRes1.setExpectedEndOfLife(2);
        ppRes1.setName("WindInM1");

        // At 6 Eur/GJ has a mc of 40 Eur/MWh
        PowerPlant ppRes2 = new PowerPlant();
        ppRes2.setTechnology(windTech);
        ppRes2.setOwner(market2Prod2);
        ppRes2.setActualFixedOperatingCost(99000);
        ppRes2.setLoan(l6);
        ppRes2.setActualNominalCapacity(17000);
        ppRes2.setActualEfficiency(1);
        ppRes2.setLocation(node2);
        ppRes2.setActualPermittime(0);
        ppRes2.setConstructionStartTime(-6);
        ppRes2.setActualLeadtime(0);
        ppRes2.setDismantleTime(10);
        ppRes2.setExpectedEndOfLife(10);
        ppRes2.setName("WindInM2");

        ppRes1.persist();
        ppRes2.persist();

        ClearingPoint coalClearingPoint = new ClearingPoint().persist();
        coalClearingPoint.setAbstractMarket(coalMarket);
        coalClearingPoint.setTime(0);
        coalClearingPoint.setPrice(3);
        coalClearingPoint.setVolume(1000);
        coalClearingPoint.setForecast(false);

        ClearingPoint gasClearingPoint = new ClearingPoint().persist();
        gasClearingPoint.setAbstractMarket(gasMarket);
        gasClearingPoint.setTime(0);
        gasClearingPoint.setPrice(6);
        gasClearingPoint.setVolume(1000);
        gasClearingPoint.setForecast(false);

    }

    @Test
    public void determineResidualLoadCurveRoleTest() {

        DecarbonizationModel model = reps.genericRepository.findFirst(DecarbonizationModel.class);

        determineResidualLoadCurvesForTwoCountriesRole.act(model);

        for (SegmentLoad segmentLoad : reps.segmentLoadRepository.findAll()) {
            if (segmentLoad.getElectricitySpotMarket().getName() == "Market1") {
                switch (segmentLoad.getSegment().getSegmentID()) {
                case 1:
                    assertEquals("SegmentLoad Market 1, Segment 1", 1156.95, segmentLoad.getBaseLoad(), 0.001);
                    break;
                case 2:
                    assertEquals("SegmentLoad Market 1, Segment 2", 718.95, segmentLoad.getBaseLoad(), 0.001);
                    break;
                }
            } else if (segmentLoad.getElectricitySpotMarket().getName() == "Market2") {
                switch (segmentLoad.getSegment().getSegmentID()) {
                case 1:
                    assertEquals("SegmentLoad Market 2, Segment 1", 2313.9, segmentLoad.getBaseLoad(), 0.001);
                    break;
                case 2:
                    assertEquals("SegmentLoad Market 2, Segment 2", 1437.9, segmentLoad.getBaseLoad(), 0.001);
                    break;
                }
            }
        }
    }

    private long getCurrentTick() {
        return 0;
    }

}

// }


text:
require 'spec_helper'

describe ErrorTracking::ProjectErrorTrackingSetting do
  include ReactiveCachingHelpers

  set(:project) { create(:project) }

  subject { create(:project_error_tracking_setting, project: project) }

  describe 'Associations' do
    it { is_expected.to belong_to(:project) }
  end

  describe 'Validations' do
    context 'when api_url is over 255 chars' do
      it 'fails validation' do
        subject.api_url = 'https://' + 'a' * 250

        expect(subject).not_to be_valid
        expect(subject.errors.messages[:api_url]).to include('is too long (maximum is 255 characters)')
      end
    end

    context 'With unsafe url' do
      it 'fails validation' do
        subject.api_url = "https://replaceme.com/'><script>alert(document.cookie)</script>"

        expect(subject).not_to be_valid
      end
    end

    context 'URL path' do
      it 'fails validation with wrong path' do
        subject.api_url = 'http://gitlab.com/project1/something'

        expect(subject).not_to be_valid
        expect(subject.errors.messages[:api_url]).to include('path needs to start with /api/0/projects')
      end

      it 'passes validation with correct path' do
        subject.api_url = 'http://gitlab.com/api/0/projects/project1/something'

        expect(subject).to be_valid
      end
    end
  end

  describe '#sentry_external_url' do
    let(:sentry_url) { 'https://sentrytest.gitlab.com/api/0/projects/sentry-org/sentry-project' }

    before do
      subject.api_url = sentry_url
    end

    it 'returns the correct url' do
      expect(subject.class).to receive(:extract_sentry_external_url).with(sentry_url).and_call_original

      result = subject.sentry_external_url

      expect(result).to eq('https://sentrytest.gitlab.com/sentry-org/sentry-project')
    end
  end

  describe '#sentry_client' do
    it 'returns sentry client' do
      expect(subject.sentry_client).to be_a(Sentry::Client)
    end
  end

  describe '#list_sentry_issues' do
    let(:issues) { [:list, :of, :issues] }

    let(:opts) do
      { issue_status: 'unresolved', limit: 10 }
    end

    let(:result) do
      subject.list_sentry_issues(**opts)
    end

    context 'when cached' do
      let(:sentry_client) { spy(:sentry_client) }

      before do
        stub_reactive_cache(subject, issues, opts)
        synchronous_reactive_cache(subject)

        expect(subject).to receive(:sentry_client).and_return(sentry_client)
      end

      it 'returns cached issues' do
        expect(sentry_client).to receive(:list_issues).with(opts)
          .and_return(issues)

        expect(result).to eq(issues: issues)
      end
    end

    context 'when not cached' do
      it 'returns nil' do
        expect(subject).not_to receive(:sentry_client)

        expect(result).to be_nil
      end
    end
  end
end


text:
Axes that follow a cartesian grid are known as 'Cartesian Axes'. Cartesian axes are used for line, bar, and bubble charts. Four cartesian axes are included in Chart.js by default.

* [linear](./linear.md#linear-cartesian-axis)
* [logarithmic](./logarithmic.md#logarithmic-cartesian-axis)
* [category](./category.md#category-cartesian-axis)
* [time](./time.md#time-cartesian-axis)

# Common Configuration

All of the included cartesian axes support a number of common options.

| Name | Type | Default | Description
| -----| ---- | --------| -----------
| `type` | `String` | | Type of scale being employed. Custom scales can be created and registered with a string key. This allows changing the type of an axis for a chart.
| `position` | `String` | | Position of the axis in the chart. Possible values are: `'top'`, `'left'`, `'bottom'`, `'right'`
| `id` | `String` | | The ID is used to link datasets and scale axes together. [more...](#axis-id)
| `gridLines` | `Object` | | Grid line configuration. [more...](../styling.md#grid-line-configuration)
| `scaleLabel` | `Object` | | Scale title configuration. [more...](../labelling.md#scale-title-configuration)
| `ticks` | `Object` | | Tick configuration. [more...](#tick-configuration)

## Tick Configuration
The following options are common to all cartesian axes but do not apply to other axes.

| Name | Type | Default | Description
| -----| ---- | --------| -----------
| `autoSkip` | `Boolean` | `true` | If true, automatically calculates how many labels that can be shown and hides labels accordingly. Turn it off to show all labels no matter what
| `autoSkipPadding` | `Number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled. *Note: Only applicable to horizontal scales.*
| `labelOffset` | `Number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the y direction for the x axis, and the x direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas*
| `maxRotation` | `Number` | `90` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.*
| `minRotation` | `Number` | `0` | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.*
| `mirror` | `Boolean` | `false` | Flips tick labels around axis, displaying the labels inside the chart instead of outside. *Note: Only applicable to vertical scales.*
| `padding` | `Number` | `10` | Padding between the tick label and the axis. *Note: Only applicable to horizontal scales.*

## Axis ID
The properties `dataset.xAxisID` or `dataset.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used.

```javascript
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
            // This dataset appears on the first axis
            yAxisID: 'first-y-axis'
        }, {
            // This dataset appears on the second axis
            yAxisID: 'second-y-axis'
        }]
    },
    options: {
        scales: {
            yAxes: [{
                id: 'first-y-axis',
                type: 'linear'
            }, {
                id: 'second-y-axis',
                type: 'linear'
            }]
        }
    }
});
```

# Creating Multiple Axes

With cartesian axes, it is possible to create multiple X and Y axes. To do so, you can add multiple configuration objects to the `xAxes` and `yAxes` properties. When adding new axes, it is important to ensure that you specify the type of the new axes as default types are **not** used in this case.

In the example below, we are creating two Y axes. We then use the `yAxisID` property to map the datasets to their correct axes.

```javascript
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
            data: [20, 50, 100, 75, 25, 0],
            label: 'Left dataset'

            // This binds the dataset to the left y axis
            yAxisID: 'left-y-axis'
        }, {
            data: [0.1, 0.5, 1.0, 2.0, 1.5, 0]
            label: 'Right dataset'

            // This binds the dataset to the right y axis
            yAxisID: 'right-y-axis',
        }],
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
    },
    options: {
        scales: {
            yAxes: [{
                id: 'left-y-axis',
                type: 'linear',
                position: 'left'
            }, {
                id: 'right-y-axis',
                type: 'linear',
                position: 'right'
            }]
        }
    }
});
```


text:
from datetime import datetime
from django.test import TestCase
from django.conf import settings
from squawk.gateway.dummy import DummyGateway
from squawk.models import TransmissionLog
import squawk.lib
import simplejson as json

class SquawkTestCase(TestCase):
    def assertIsJSON(self, s):
        try:
            rval = json.loads(s)
        except json.JSONDecodeError:
            self.fail("Value '%s' is not a valid JSON string" %s)

    def assertStatus(self, response, status):
        if response.status_code != status:
            self.fail("Status %d != %d" % (response.status_code, status))

    def makeJSONmessage(self, msg):
        return '{"message": "%s"}' % msg

class TestContactHandlers(SquawkTestCase):
    fixtures = ['testdata']

    def setUp(self):
        self.valid_key = '12345678901234567890'
        self.valid_admin = '1af89877901234567890'
        self.invalid_key = '11111111111111111111'
        # force gateway to re-load and be the dummy
        squawk.gateway.gateway(new_gateway = "DummyGateway")
        # we'll explicitly dequeue in the tests
        settings.SEND_IN_PROCESS = True

    def test_get_contact_data(self):
        response = self.client.get('/contact/demo-user/', data = {'api_key' : self.valid_admin})
        self.assertStatus(response, 200)
        self.assertIsJSON(response.content)

    def test_get_disabled_contact_data(self):
        response = self.client.get('/contact/disabled-user/', data = {'api_key' : self.valid_admin})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_get_contact_non_admin(self):
        response = self.client.get('/contact/demo-user/', data = {'api_key' : self.valid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_get_contact_invalid_user(self):
        response = self.client.get('/contact/fake-user/', data = {'api_key' : self.valid_admin})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_get_contact_invalid_user_invalid_key(self):
        response = self.client.get('/contact/fake-user/', data = {'api_key' : self.invalid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_get_contact_no_api_key(self):
        response = self.client.get('/contact/demo-user/')
        self.assertStatus(response, 500)
        self.assertIsJSON(response.content)

    def test_post_contact_no_api_key(self):
        response = self.client.post('/contact/demo-user/')
        self.assertStatus(response, 500)
        self.assertIsJSON(response.content)

    def test_post_to_contact(self):
        response = self.client.post('/contact/demo-user/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 201)
        self.assertIsJSON(response.content)
        rval = json.loads(response.content)
        self.assertEqual(rval['message'], 'OK')
        self.assertTrue('notification_id' in rval)
        # don't know the notification ID but know it will be 32 chars long
        self.assertEqual(len(rval['notification_id']), 32)

    def test_post_to_disabled_contact(self):
        response = self.client.post('/contact/disabled-user/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_post_to_contact_empty_message(self):
        response = self.client.post('/contact/demo-user/', data = {'api_key':self.valid_key,
                                                                   'message':''})
        self.assertStatus(response, 500)
        self.assertEqual(response.content, self.makeJSONmessage("Empty message"))
        self.assertIsJSON(response.content)

    def test_post_to_contact_no_message(self):
        response = self.client.post('/contact/demo-user/', data = {'api_key':self.valid_key,})
        self.assertStatus(response, 500)
        self.assertEqual(response.content,  self.makeJSONmessage("Empty message"))
        self.assertIsJSON(response.content)

    def test_post_to_contact_invalid_key(self):
        response = self.client.post('/contact/demo-user/', data = {'api_key':self.invalid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_post_to_fake_contact(self):
        response = self.client.post('/contact/fake-user/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

#    def test_post_to_enabled_contact_no_enabled_endpoints(self):
#        self.fail("No test")

    def test_post_to_fake_contact_invalid_key(self):
        response = self.client.post('/contact/fake-user/', data = {'api_key':self.invalid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_put_request(self):
        response = self.client.put('/contact/demo-user/', data = {'api_key':self.valid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

class TestGroupHandlers(SquawkTestCase):
    fixtures = ['testdata']

    def setUp(self):
        self.valid_key = '12345678901234567890'
        self.valid_admin = '1af89877901234567890'
        self.invalid_key = '11111111111111111111'
        # force gateway to re-load
        squawk.gateway.gateway(new_gateway = "DummyGateway")
        # we'll explicitly dequeue in the tests
        settings.SEND_IN_PROCESS = True

    def test_get_group_data(self):
        response = self.client.get('/group/demo-group/', data = {'api_key' : self.valid_admin})
        self.assertStatus(response, 200)
        self.assertIsJSON(response.content)

    def test_get_disabled_group_data(self):
        response = self.client.get('/group/disabled-group/', data = {'api_key' : self.valid_admin})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_get_group_non_admin(self):
        response = self.client.get('/group/demo-group/', data = {'api_key' : self.valid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_get_group_invalid_user(self):
        response = self.client.get('/group/fake-group/', data = {'api_key' : self.valid_admin})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_get_group_invalid_user_invalid_key(self):
        response = self.client.get('/group/fake-group/', data = {'api_key' : self.invalid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_get_group_no_api_key(self):
        response = self.client.get('/group/demo-group/')
        self.assertStatus(response, 500)
        self.assertIsJSON(response.content)

    def test_post_group_no_api_key(self):
        response = self.client.post('/group/demo-group/')
        self.assertStatus(response, 500)
        self.assertIsJSON(response.content)

    def test_post_to_group(self):
        response = self.client.post('/group/demo-group/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 201)
        self.assertIsJSON(response.content)
        rval = json.loads(response.content)
        self.assertEqual(rval['message'], 'OK')
        self.assertTrue('notification_id' in rval)
        # don't know the notification ID but know it will be 32 chars long
        self.assertEqual(len(rval['notification_id']), 32)

    def test_post_to_disabled_group(self):
        response = self.client.post('/group/disabled-group/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_post_to_group_empty_message(self):
        response = self.client.post('/group/demo-group/', data = {'api_key':self.valid_key,
                                                                   'message':''})
        self.assertStatus(response, 500)
        self.assertEqual(response.content, self.makeJSONmessage("Empty message"))
        self.assertIsJSON(response.content)

    def test_post_to_group_no_message(self):
        response = self.client.post('/group/demo-group/', data = {'api_key':self.valid_key,})
        self.assertStatus(response, 500)
        self.assertEqual(response.content, self.makeJSONmessage("Empty message"))
        self.assertIsJSON(response.content)

#    def test_post_to_group_with_some_invalid_users(self):
#        """ @todo: Would need to bork the DB to do this so not testing... actually...
# on second thoughts... this occurs if the phone number is bad and the gateway returns
# error. Need to sort this test."""
#        response = self.client.post('/group/demo-partial-group/', data = {'api_key':self.valid_key,
#                                                                   'message':'The message'})
#        self.assertStatus(response, 202)

    def test_post_to_group_invalid_key(self):
        response = self.client.post('/group/demo-group/', data = {'api_key':self.invalid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_post_to_fake_group(self):
        response = self.client.post('/group/fake-group/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_post_to_fake_group_invalid_key(self):
        response = self.client.post('/group/fake-group/', data = {'api_key':self.invalid_key,
                                                                   'message':'The message'})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_put_request(self):
        response = self.client.put('/group/demo-group/', data = {'api_key':self.valid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

class TestEventHandlers(SquawkTestCase):
    fixtures = ['testdata']

    def setUp(self):
        self.valid_key = '12345678901234567890'
        self.valid_admin = '1af89877901234567890'
        self.invalid_key = '11111111111111111111'
        # force gateway to re-load
        squawk.gateway.gateway(new_gateway = "DummyGateway")
        # we'll explicitly dequeue in the tests
        settings.SEND_IN_PROCESS = True

    def test_event_invalid_key(self):
        response = self.client.post('/event/server-overload/', data = {'api_key':self.invalid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_event_no_api_key(self):
        response = self.client.post('/event/server-overload/')
        self.assertStatus(response, 500)
        self.assertIsJSON(response.content)

    def test_event_fake_event(self):
        response = self.client.post('/event/fake-event/', data = {'api_key':self.valid_key})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_event_fake_event_invalid_key(self):
        response = self.client.post('/event/fake-event/', data = {'api_key':self.invalid_key})
        self.assertStatus(response, 403)
        self.assertIsJSON(response.content)

    def test_valid_event_send(self):
        response = self.client.post('/event/server-overload/', data = {'api_key':self.valid_key})
        self.assertStatus(response, 201)
        #squawk.lib.dequeue()
        self.assertEqual(squawk.gateway.gateway().LAST_MESSAGE, "Test server overload event : ")
        self.assertIsJSON(response.content)

    def test_send_to_disabled_event(self):
        response = self.client.post('/event/disabled-event/', data = {'api_key':self.valid_key})
        self.assertStatus(response, 404)
        self.assertIsJSON(response.content)

    def test_event_additional_args(self):
        response = self.client.post('/event/server-overload/', data = {'api_key':self.valid_key,
                                                                       'x' : 10,
                                                                       'y' : 'hello'})
        self.assertStatus(response, 201)
        #squawk.lib.dequeue()
        self.assertEqual(squawk.gateway.gateway().LAST_MESSAGE, "Test server overload event hello: 10")
        self.assertIsJSON(response.content)

class TestDeliveryStatusCallback(SquawkTestCase):
    """ Test callback handlers for delivery status. """
    fixtures = ['testdata']

    def setUp(self):
        self.valid_key = '12345678901234567890'
        # force gateway to re-load
        squawk.gateway.gateway(new_gateway = "DummyGateway")
        # we'll explicitly dequeue in the tests
        settings.SEND_IN_PROCESS = True
        squawk.gateway.gateway().GATEWAY_MID = squawk.lib.create_notification_id()
        settings.GATEWAY_ENABLE_ACK = True
        settings.GATEWAY_CALLBACK_METHOD = "POST"

        # create the sample sent message which will have the gateway response code set
        # as above
        response = self.client.post('/contact/demo-user/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        #squawk.lib.dequeue()
        self.response_timestamp = datetime(2008, 1, 10, 21, 20)

    def test_callback_delivered(self):
        """ This tests the demo callback handler NOT one of the real handlers. """
        data = { 'apiMsgId' : squawk.gateway.gateway().GATEWAY_MID,
                 'status' : '004',
                 'charge' : '0.3',
                 'timestamp' : '1200000000'
                }
        response = self.client.post('/ack/', data = data)
        log_entry = TransmissionLog.objects.get(gateway_response = squawk.gateway.gateway().GATEWAY_MID)

        self.assertEqual(log_entry.charge, 0.3)
        self.assertEqual(log_entry.gateway_status, 'Received by recipient')
        self.assertTrue(log_entry.delivery_confirmed)
        self.assertEqual(log_entry.status_timestamp, self.response_timestamp)

    def test_callback_delivered_to_gateway(self):
        """ This tests the demo callback handler NOT one of the real handlers. """
        data = { 'apiMsgId' : squawk.gateway.gateway().GATEWAY_MID,
                 'status' : '003',
                 'charge' : '0.3',
                 'timestamp' : '1200000000'
                }
        response = self.client.post('/ack/', data = data)

        log_entry = TransmissionLog.objects.get(gateway_response = squawk.gateway.gateway().GATEWAY_MID)
        self.assertStatus(response, 200)
        self.assertEqual(log_entry.charge, 0.3)
        self.assertEqual(log_entry.gateway_status, 'Delivered to gateway')
        self.assertFalse(log_entry.delivery_confirmed)
        self.assertEqual(log_entry.status_timestamp, self.response_timestamp)

class TestClickatellDeliveryStatusCallback(SquawkTestCase):
    """ Test callback handlers for delivery status in the Clickatell
handler. """
    fixtures = ['testdata']

    def setUp(self):
        self.valid_key = '12345678901234567890'
        self.GATEWAY_MID = squawk.lib.create_notification_id()
        self.init_gateway("DummyGateway")
        settings.GATEWAY_ENABLE_ACK = True
        settings.GATEWAY_CALLBACK_METHOD = "POST"

        # create the sample sent message which will have the gateway response code set
        # as above
        response = self.client.post('/contact/demo-user/', data = {'api_key':self.valid_key,
                                                                   'message':'The message'})
        #squawk.lib.dequeue()
        self.response_timestamp = datetime(2008, 1, 10, 21, 20)

    def init_gateway(self, gateway):
        # force gateway to re-load
        squawk.gateway.gateway(new_gateway = gateway)
        # we'll explicitly dequeue in the tests
        settings.SEND_IN_PROCESS = True
        squawk.gateway.gateway().GATEWAY_MID = self.GATEWAY_MID
        settings.GATEWAY_ENABLE_ACK = True

    def test_callback_delivered(self):
        # switch to clickatell to test that handler
        self.init_gateway("ClickatellGateway")
        data = { 'apiMsgId' : squawk.gateway.gateway().GATEWAY_MID,
                 'status' : '004',
                 'charge' : '0.3',
                 'timestamp' : '1200000000'
                }
        response = self.client.post('/ack/', data = data)
        log_entry = TransmissionLog.objects.get(gateway_response = squawk.gateway.gateway().GATEWAY_MID)

        self.assertStatus(response, 200)
        self.assertEqual(log_entry.charge, 0.3)
        self.assertEqual(log_entry.gateway_status, 'Received by recipient')
        self.assertTrue(log_entry.delivery_confirmed)
        self.assertEqual(log_entry.status_timestamp, self.response_timestamp)

    def test_callback_delivered_to_gateway(self):
        self.init_gateway("ClickatellGateway")
        data = { 'apiMsgId' : squawk.gateway.gateway().GATEWAY_MID,
                 'status' : '003',
                 'charge' : '0.3',
                 'timestamp' : '1200000000'
                }
        response = self.client.post('/ack/', data = data)

        log_entry = TransmissionLog.objects.get(gateway_response = squawk.gateway.gateway().GATEWAY_MID)
        self.assertStatus(response, 200)
        self.assertEqual(log_entry.charge, 0.3)
        self.assertEqual(log_entry.gateway_status, 'Delivered to gateway')
        self.assertFalse(log_entry.delivery_confirmed)
        self.assertEqual(log_entry.status_timestamp, self.response_timestamp)

class TestLogging(SquawkTestCase):
    """ Basic test that log entries can be made via dummy gateway. """
    fixtures = ['testdata']

    def setUp(self):
        self.valid_key = '12345678901234567890'
        # force gateway to re-load
        squawk.gateway.gateway(new_gateway = "DummyGateway")
        # we'll explicitly dequeue in the tests
        settings.SEND_IN_PROCESS = True
        squawk.gateway.gateway().GATEWAY_MID = squawk.lib.create_notification_id()

    def test_contact_log_entry(self):
        response = self.client.post('/contact/demo-user/', data = {'api_key':self.valid_key,
                                                                   'message':'The second message'})
        #squawk.lib.dequeue()
        try:
            log_entry = TransmissionLog.objects.get(gateway_response = squawk.gateway.gateway().GATEWAY_MID)
            self.assertEqual(log_entry.gateway_response, squawk.gateway.gateway().GATEWAY_MID)
            self.assertEqual(log_entry.message, 'The second message')
            self.assertTrue(log_entry.send_ok)
            self.assertEqual(log_entry.notification_type, 'contact')
            self.assertEqual(log_entry.notification_slug, 'demo-user')
        except TransmissionLog.MultipleObjectsReturned:
            self.fail("More than one log entry found on send to contact")

    def test_group_log_entry(self):
        response = self.client.post('/group/demo-group/', data = {'api_key':self.valid_key,
                                                                   'message':'The second message'}
                                    )
        #squawk.lib.dequeue()
        rval = json.loads(response.content)
        nid = rval['notification_id']
        log_entries = TransmissionLog.objects.filter(notification_id = nid)
        self.assertEqual(len(log_entries), 2)

        # check log entry for send to each contact in the group is right
        contacts = []
        for log_entry in log_entries:
            self.assertEqual(log_entry.gateway_response, squawk.gateway.gateway().GATEWAY_MID)
            self.assertEqual(log_entry.message, 'The second message')
            self.assertTrue(log_entry.send_ok)
            self.assertEqual(log_entry.notification_type, 'group')
            self.assertEqual(log_entry.notification_slug, 'demo-group')
            self.assertFalse(log_entry.contact in contacts)
            contacts.append(log_entry.contact)


text:
package cz.droidboy.wifibeacon;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import java.util.List;

import cz.droidboy.wibeacon.range.ProximityMonitor;
import cz.droidboy.wifibeacon.util.PrefUtils;
import cz.droidboy.wibeacon.range.ProximityScanner;
import cz.droidboy.wibeacon.range.ScanFilter;

/**
 * @author Jonas Sevcik
 */
public class WiFiDetectionService extends Service implements ProximityMonitor.MonitoringListener {

    public static final String UPDATE_COMMAND_KEY = "update";
    public static final int UPDATE_COMMAND = 0;
    private static final String TAG = WiFiDetectionService.class.getSimpleName();
    private static final int UPDATE_INTERVAL = 10_000; //millis
    private static final int NOTIFICATION_ID = 0;
    private ProximityMonitor mMonitor;
    private WifiManager.WifiLock mWifiLock;
    private BroadcastReceiver mWifiDisabledReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
                if (state == WifiManager.WIFI_STATE_DISABLING || state == WifiManager.WIFI_STATE_DISABLED) {
                    stopSelf();
                }
            }
        }
    };
    private NotificationManager mNotificationManager;
    private NotificationCompat.Builder mBuilder;

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        super.onCreate();
        if (Build.VERSION.SDK_INT < 18) {
            acquireWifiLock();
            registerReceiver(mWifiDisabledReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
        }

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender()
                .setHintHideIcon(true);
        PendingIntent viewPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_wifi_notification)
                .setContentTitle("APs found")
                .setContentIntent(viewPendingIntent)
                .setLights(0x0048a610, 500, 5000)
                .extend(wearableExtender);

        mMonitor = new ProximityMonitor(this, this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        mMonitor.startMonitoringAPs(PrefUtils.prepareFilter(this), UPDATE_INTERVAL);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
        mMonitor.stopMonitoringAPs();

        if (Build.VERSION.SDK_INT < 18) {
            releaseWifiLock();
            unregisterReceiver(mWifiDisabledReceiver);
        }
    }

    private void acquireWifiLock() {
        WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mWifiLock = manager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, TAG);
        mWifiLock.setReferenceCounted(false);
        mWifiLock.acquire();
    }

    private void releaseWifiLock() {
        if (mWifiLock != null) {
            if (mWifiLock.isHeld()) {
                mWifiLock.release();
            }
            mWifiLock = null;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onEnterRegion(List<ScanResult> results) {
        Log.d(TAG, "onEnterRegion");
        mBuilder.setContentText(String.valueOf(results.size()));
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

    @Override
    public void onDwellRegion(List<ScanResult> results) {
        Log.d(TAG, "onDwellRegion");
        //nothing
    }

    @Override
    public void onExitRegion(ScanFilter filter) {
        Log.d(TAG, "onExitRegion");
        mNotificationManager.cancel(NOTIFICATION_ID);
    }

}


text:
package org.knowm.xchange.lgo.dto;

import si.mazi.rescu.HttpStatusExceptionSupport;

public class LgoException extends HttpStatusExceptionSupport {}


text:
module Checkoff
  module Internal
    module SearchUrl
      module CustomFieldVariant
        # base class for handling different custom_field_#{gid}.variant params
        class CustomFieldVariant
          def initialize(gid, remaining_params)
            @gid = gid
            @remaining_params = remaining_params
          end

          private

          attr_reader :gid, :remaining_params
        end

        # custom_field_#{gid}.variant = 'less_than'
        class LessThan < CustomFieldVariant
          def convert
            max_param = "custom_field_#{gid}.max"
            case remaining_params.keys
            when [max_param]
              convert_single_custom_field_less_than_params_max_param(max_param)
            else
              raise "Teach me how to handle #{remaining_params}"
            end
          end

          private

          def convert_single_custom_field_less_than_params_max_param(max_param)
            max_values = remaining_params.fetch(max_param)
            unless max_values.length == 1
              raise "Teach me how to handle these remaining keys for #{max_param}: #{remaining_params}"
            end

            max_value = max_values[0]
            empty_task_selector = []
            [{ "custom_fields.#{gid}.less_than" => max_value }, empty_task_selector]
          end
        end

        # custom_field_#{gid}.variant = 'is_not'
        class IsNot < CustomFieldVariant
          def convert
            case remaining_params.keys
            when ["custom_field_#{gid}.selected_options"]
              convert_single_custom_field_is_not_params_selected_options
            else
              raise "Teach me how to handle #{remaining_params}"
            end
          end

          private

          def convert_single_custom_field_is_not_params_selected_options
            selected_options = remaining_params.fetch("custom_field_#{gid}.selected_options")
            raise "Teach me how to handle #{remaining_params}" unless selected_options.length == 1

            [{ "custom_fields.#{gid}.is_set" => 'true' },
             ['not',
              ['custom_field_gid_value_contains_any_gid',
               gid,
               selected_options.fetch(0).split('~')]]]
          end
        end

        # custom_field_#{gid}.variant = 'no_value'
        class NoValue < CustomFieldVariant
          def convert
            unless remaining_params.length.zero?
              raise "Teach me how to handle these remaining keys for #{variant_key}: #{remaining_params}"
            end

            empty_task_selector = []
            [{ "custom_fields.#{gid}.is_set" => 'false' }, empty_task_selector]
          end
        end

        # custom_field_#{gid}.variant = 'is'
        class Is < CustomFieldVariant
          def convert
            unless remaining_params.length == 1
              raise "Teach me how to handle these remaining keys for #{variant_key}: #{remaining_params}"
            end

            key, values = remaining_params.to_a[0]
            convert_custom_field_is_arg(key, values)
          end

          private

          def convert_custom_field_is_arg(key, values)
            empty_task_selector = []

            if key.end_with? '.selected_options'
              raise "Too many values found for #{key}: #{values}" if values.length != 1

              return [{ "custom_fields.#{gid}.value" => values[0] },
                      empty_task_selector]
            end

            raise "Teach me how to handle #{key} = #{values}"
          end
        end
      end
    end
  end
end


text:
//
// DateFormat.cs
//
// Author:
//	Zachary Gramana  <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Globalization;

namespace Sharpen
{
	public abstract class DateFormat
	{
		public const int DEFAULT = 2;

		public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle)
		{
			return GetDateTimeInstance (dateStyle, timeStyle, CultureInfo.CurrentCulture);
		}

		public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle, CultureInfo aLocale)
		{
			return new SimpleDateFormat (aLocale.DateTimeFormat.FullDateTimePattern, aLocale);
		}

		TimeZoneInfo timeZone;

		public DateFormat ()
		{
		}

		public abstract DateTime Parse (string value);

		public TimeZoneInfo GetTimeZone ()
		{
			return timeZone;
		}

		public void SetTimeZone (TimeZoneInfo timeZone)
		{
			this.timeZone = timeZone;
		}

		public abstract string Format (DateTime time);
	}
}


text:
import base64
import codecs
import logging
import os
from io import BytesIO

from ..types import Any

logger = logging.getLogger(__name__)

PNG_FORMAT = "png"
JPG_FORMAT = "jpeg"
GIF_FORMAT = "gif"
PDF_FORMAT = "pdf"
SVG_FORMAT = "svg"
EPS_FORMAT = "eps"
B64_FORMAT = "base64"

def make_snapshot(
    engine: Any,
    file_name: str,
    output_name: str,
    delay: float = 2,
    pixel_ratio: int = 2,
    is_remove_html: bool = False,
    **kwargs,
):
    logger.info("Generating file ...")
    file_type = output_name.split(".")[-1]

    content = engine.make_snapshot(
        html_path=file_name,
        file_type=file_type,
        delay=delay,
        pixel_ratio=pixel_ratio,
        **kwargs,
    )
    if file_type in [SVG_FORMAT, B64_FORMAT]:
        save_as_text(content, output_name)
    else:
        # pdf, gif, png, jpeg
        content_array = content.split(",")
        if len(content_array) != 2:
            raise OSError(content_array)

        image_data = decode_base64(content_array[1])

        if file_type in [PDF_FORMAT, GIF_FORMAT, EPS_FORMAT]:
            save_as(image_data, output_name, file_type)
        elif file_type in [PNG_FORMAT, JPG_FORMAT]:
            save_as_png(image_data, output_name)
        else:
            raise TypeError(f"Not supported file type '{file_type}'")

    if "/" not in output_name:
        output_name = os.path.join(os.getcwd(), output_name)

    if is_remove_html and not file_name.startswith("http"):
        os.unlink(file_name)
    logger.info(f"File saved in {output_name}")

def decode_base64(data: str) -> bytes:
    """Decode base64, padding being optional.

    :param data: Base64 data as an ASCII byte string
    :returns: The decoded byte string.
    """
    missing_padding = len(data) % 4
    if missing_padding != 0:
        data += "=" * (4 - missing_padding)
    return base64.decodebytes(data.encode("utf-8"))

def save_as_png(image_data: bytes, output_name: str):
    with open(output_name, "wb") as f:
        f.write(image_data)

def save_as_text(image_data: str, output_name: str):
    with codecs.open(output_name, "w", encoding="utf-8") as f:
        f.write(image_data)

def save_as(image_data: bytes, output_name: str, file_type: str):
    try:
        from PIL import Image

        m = Image.open(BytesIO(image_data))
        m.load()
        color = (255, 255, 255)
        b = Image.new("RGB", m.size, color)
        b.paste(m, mask=m.split()[3])
        b.save(output_name, file_type, quality=100)
    except ModuleNotFoundError:
        raise Exception(f"Please install PIL for {file_type} image type")


text:
package Net::Upwork::API::Routers::Hr::Clients::Offers;

use strict;
use warnings;
use parent "Net::Upwork::API";

use constant ENTRY_POINT => Net::Upwork::API::Client::ENTRY_POINT_API;

=pod

=head1 NAME

Auth

=head1 FUNCTIONS

=over 4

=item new($api)

Create a new object for accessing Auth API

B<Parameters>

$api

    API object

=cut

sub new {
    my ($class, $api) = @_;
    return Net::Upwork::API::init_router($class, $api, ENTRY_POINT);
}

=item get_list

    Get list of offers

B<Parameters>

$params

    Hash of parameters

B<Return value>

    JSON response as a string

=cut

sub get_list {
    my $self = shift;
    my %params = @_;

    return $self->client()->get("/offers/v1/clients/offers", %params);
}

=item get_specific

    Get specific offer

B<Parameters>

$reference

    Offer reference

$params

    Hash of parameters

B<Return value>

    JSON response as a string

=cut

sub get_specific {
    my $self = shift;
    my $reference = shift;
    my %params = @_;

    return $self->client()->get("/offers/v1/clients/offers/" . $reference, %params);
}

=item make_offer

    Make an Offer

B<Parameters>

$params

    Hash of parameters

B<Return value>

    JSON response as a string

=cut

sub make_offer {
    my $self = shift;
    my %params = @_;

    return $self->client()->post("/offers/v1/clients/offers", %params);
}

=back

=head1 AUTHOR

Maksym Novozhylov C<< <mnovozhilov@upwork.com> >>

=head1 COPYRIGHT

Copyright E<copy> Upwork Global Corp., 2015

=cut

1;


text:
'use strict';

/**
 * DailyMotion renderer
 *
 * Uses <iframe> approach and uses DailyMotion API to manipulate it.
 * @see https://developer.dailymotion.com/player
 *
 */
const DailyMotionApi = {
	/**
	 * @type {Boolean}
	 */
	isSDKStarted: false,
	/**
	 * @type {Boolean}
	 */
	isSDKLoaded: false,
	/**
	 * @type {Array}
	 */
	iframeQueue: [],

	/**
	 * Create a queue to prepare the creation of <iframe>
	 *
	 * @param {Object} settings - an object with settings needed to create <iframe>
	 */
	enqueueIframe: (settings) => {

		if (DailyMotionApi.isLoaded) {
			DailyMotionApi.createIframe(settings);
		} else {
			DailyMotionApi.loadIframeApi();
			DailyMotionApi.iframeQueue.push(settings);
		}
	},

	/**
	 * Load DailyMotion API script on the header of the document
	 *
	 */
	loadIframeApi: () => {
		if (!DailyMotionApi.isSDKStarted) {
			const e = document.createElement('script');
			e.async = true;
			e.src = 'https://api.dmcdn.net/all.js';
			const s = document.getElementsByTagName('script')[0];
			s.parentNode.insertBefore(e, s);
			DailyMotionApi.isSDKStarted = true;
		}
	},

	/**
	 * Process queue of DailyMotion <iframe> element creation
	 *
	 */
	apiReady: () => {

		DailyMotionApi.isLoaded = true;
		DailyMotionApi.isSDKLoaded = true;

		while (DailyMotionApi.iframeQueue.length > 0) {
			const settings = DailyMotionApi.iframeQueue.pop();
			DailyMotionApi.createIframe(settings);
		}
	},

	/**
	 * Create a new instance of DailyMotion API player and trigger a custom event to initialize it
	 *
	 * @param {Object} settings - an object with settings needed to create <iframe>
	 */
	createIframe: (settings) => {

		const
			player = DM.player(settings.container, {
				height: settings.height || '100%',
				width: settings.width || '100%',
				video: settings.videoId,
				params: Object.assign({api: true}, settings.params),
				origin: location.host
			});

		player.addEventListener('apiready', () => {
			window['__ready__' + settings.id](player, {paused: true, ended: false});
		});
	},

	/**
	 * Extract ID from DailyMotion's URL to be loaded through API
	 * Valid URL format(s):
	 * - http://www.dailymotion.com/embed/video/x35yawy
	 * - http://dai.ly/x35yawy
	 *
	 * @param {String} url
	 * @return {String}
	 */
	getDailyMotionId: (url) => {
		const
			parts = url.split('/'),
			lastPart = parts[parts.length - 1],
			dashParts = lastPart.split('_')
		;

		return dashParts[0];
	}
};

const DailyMotionIframeRenderer = {
	name: 'dailymotion_iframe',

	options: {
		prefix: 'dailymotion_iframe',

		dailymotion: {
			width: '100%',
			height: '100%',
			params: {
				autoplay: false,
				chromeless: 1,
				info: 0,
				logo: 0,
				related: 0
			}
		}
	},

	/**
	 * Determine if a specific element type can be played with this render
	 *
	 * @param {String} type
	 * @return {Boolean}
	 */
	canPlayType: (type) => ~['video/dailymotion', 'video/x-dailymotion'].indexOf(type.toLowerCase()),

	/**
	 * Create the player instance and add all native events/methods/properties as possible
	 *
	 * @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
	 * @param {Object} options All the player configuration options passed through constructor
	 * @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
	 * @return {Object}
	 */
	create: (mediaElement, options, mediaFiles) => {

		const
			dm = {},
			apiStack = [],
			readyState = 4
		;

		let
			events,
			dmPlayer = null,
			dmIframe = null
		;

		dm.options = options;
		dm.id = mediaElement.id + '_' + options.prefix;
		dm.mediaElement = mediaElement;

		// wrappers for get/set
		const
			props = mejs.html5media.properties,
			assignGettersSetters = (propName) => {

				// add to flash state that we will store

				const capName = `${propName.substring(0, 1).toUpperCase()}${propName.substring(1)}`;

				dm[`get${capName}`] = () => {
					if (dmPlayer !== null) {
						const value = null;

						// figure out how to get dm dta here
						switch (propName) {
							case 'currentTime':
								return dmPlayer.currentTime;

							case 'duration':
								return isNaN(dmPlayer.duration) ? 0 : dmPlayer.duration;

							case 'volume':
								return dmPlayer.volume;

							case 'paused':
								return dmPlayer.paused;

							case 'ended':
								return dmPlayer.ended;

							case 'muted':
								return dmPlayer.muted;

							case 'buffered':
								const percentLoaded = dmPlayer.bufferedTime,
									duration = dmPlayer.duration;
								return {
									start: () => {
										return 0;
									},
									end: () => {
										return percentLoaded / duration;
									},
									length: 1
								};
							case 'src':
								return mediaElement.originalNode.getAttribute('src');

							case 'readyState':
								return readyState;
						}

						return value;
					} else {
						return null;
					}
				};

				dm[`set${capName}`] = (value) => {
					if (dmPlayer !== null) {

						switch (propName) {

							case 'src':
								const url = typeof value === 'string' ? value : value[0].src;

								dmPlayer.load(DailyMotionApi.getDailyMotionId(url));
								break;

							case 'currentTime':
								dmPlayer.seek(value);
								break;

							case 'muted':
								if (value) {
									dmPlayer.setMuted(true);
								} else {
									dmPlayer.setMuted(false);
								}
								setTimeout(() => {
									const event = mejs.Utils.createEvent('volumechange', dm);
									mediaElement.dispatchEvent(event);
								}, 50);
								break;

							case 'volume':
								dmPlayer.setVolume(value);
								setTimeout(() => {
									const event = mejs.Utils.createEvent('volumechange', dm);
									mediaElement.dispatchEvent(event);
								}, 50);
								break;

							case 'readyState':
								const event = mejs.Utils.createEvent('canplay', dm);
								mediaElement.dispatchEvent(event);
								break;

							default:
								console.log('dm ' + dm.id, propName, 'UNSUPPORTED property');
								break;
						}

					} else {
						// store for after "READY" event fires
						apiStack.push({type: 'set', propName: propName, value: value});
					}
				};

			}
		;

		for (let i = 0, total = props.length; i < total; i++) {
			assignGettersSetters(props[i]);
		}

		// add wrappers for native methods
		const
			methods = mejs.html5media.methods,
			assignMethods = (methodName) => {

				// run the method on the native HTMLMediaElement
				dm[methodName] = () => {
					if (dmPlayer !== null) {

						// DO method
						switch (methodName) {
							case 'play':
								return dmPlayer.play();
							case 'pause':
								return dmPlayer.pause();
							case 'load':
								return null;

						}

					} else {
						apiStack.push({type: 'call', methodName: methodName});
					}
				};

			}
		;

		for (let i = 0, total = methods.length; i < total; i++) {
			assignMethods(methods[i]);
		}

		// Initial method to register all DailyMotion events when initializing <iframe>
		window['__ready__' + dm.id] = (_dmPlayer) => {

			mediaElement.dmPlayer = dmPlayer = _dmPlayer;

			// do call stack
			if (apiStack.length) {
				for (let i = 0, total = apiStack.length; i < total; i++) {

					const stackItem = apiStack[i];

					if (stackItem.type === 'set') {
						const
							propName = stackItem.propName,
							capName = `${propName.substring(0, 1).toUpperCase()}${propName.substring(1)}`
							;

						dm[`set${capName}`](stackItem.value);

					} else if (stackItem.type === 'call') {
						dm[stackItem.methodName]();
					}
				}
			}

			dmIframe = document.getElementById(dm.id);

			// a few more events
			events = ['mouseover', 'mouseout'];
			const assignEvents = (e) => {
				const event = mejs.Utils.createEvent(e.type, dm);
				mediaElement.dispatchEvent(event);
			};

			for (let i = 0, total = events.length; i < total; i++) {
				dmIframe.addEventListener(events[i], assignEvents, false);
			}

			// BUBBLE EVENTS up
			events = mejs.html5media.events;
			events = events.concat(['click', 'mouseover', 'mouseout']);
			const assignNativeEvents = (eventName) => {

				// Deprecated event; not consider it
				if (eventName !== 'ended') {

					dmPlayer.addEventListener(eventName, (e) => {
						const event = mejs.Utils.createEvent(e.type, dmPlayer);
						mediaElement.dispatchEvent(event);
					});
				}

			};

			for (let i = 0, total = events.length; i < total; i++) {
				assignNativeEvents(events[i]);
			}

			// Custom DailyMotion events
			dmPlayer.addEventListener('ad_start', () => {
				let event = mejs.Utils.createEvent('play', dmPlayer);
				mediaElement.dispatchEvent(event);

				event = mejs.Utils.createEvent('progress', dmPlayer);
				mediaElement.dispatchEvent(event);

				event = mejs.Utils.createEvent('timeupdate', dmPlayer);
				mediaElement.dispatchEvent(event);
			});
			dmPlayer.addEventListener('ad_timeupdate', () => {
				const event = mejs.Utils.createEvent('timeupdate', dmPlayer);
				mediaElement.dispatchEvent(event);
			});
			dmPlayer.addEventListener('ad_pause', () => {
				const event = mejs.Utils.createEvent('pause', dmPlayer);
				mediaElement.dispatchEvent(event);
			});
			dmPlayer.addEventListener('ad_end', () => {
				const event = mejs.Utils.createEvent('ended', dmPlayer);
				mediaElement.dispatchEvent(event);
			});
			dmPlayer.addEventListener('video_start', () => {
				let event = mejs.Utils.createEvent('play', dmPlayer);
				mediaElement.dispatchEvent(event);

				event = mejs.Utils.createEvent('timeupdate', dmPlayer);
				mediaElement.dispatchEvent(event);
			});
			dmPlayer.addEventListener('video_end', () => {
				const event = mejs.Utils.createEvent('ended', dmPlayer);
				mediaElement.dispatchEvent(event);
			});
			dmPlayer.addEventListener('progress', () => {
				const event = mejs.Utils.createEvent('timeupdate', dmPlayer);
				mediaElement.dispatchEvent(event);
			});
			dmPlayer.addEventListener('durationchange', () => {
				const event = mejs.Utils.createEvent('timeupdate', dmPlayer);
				mediaElement.dispatchEvent(event);
			});

			// give initial events
			const initEvents = ['rendererready', 'loadeddata', 'loadedmetadata', 'canplay'];

			for (let i = 0, total = initEvents.length; i < total; i++) {
				const event = mejs.Utils.createEvent(initEvents[i], dm);
				mediaElement.dispatchEvent(event);
			}
		};

		const dmContainer = document.createElement('div');
		dmContainer.id = dm.id;
		mediaElement.appendChild(dmContainer);
		if (mediaElement.originalNode) {
			dmContainer.style.width = mediaElement.originalNode.style.width;
			dmContainer.style.height = mediaElement.originalNode.style.height;
		}
		mediaElement.originalNode.style.display = 'none';

		const
			videoId = DailyMotionApi.getDailyMotionId(mediaFiles[0].src),
			dmSettings = Object.assign({
				id: dm.id,
				container: dmContainer,
				videoId: videoId,
				autoplay: mediaElement.originalNode.autoplay
			}, dm.options.dailymotion);

		DailyMotionApi.enqueueIframe(dmSettings);

		dm.hide = () => {
			dm.stopInterval();
			dm.pause();
			if (dmIframe) {
				dmIframe.style.display = 'none';
			}
		};
		dm.show = () => {
			if (dmIframe) {
				dmIframe.style.display = '';
			}
		};
		dm.setSize = (width, height) => {
			dmIframe.width = width;
			dmIframe.height = height;
		};
		dm.destroy = () => {
			dmPlayer.destroy();
		};
		dm.interval = null;

		dm.startInterval = () => {
			dm.interval = setInterval(() => {
				DailyMotionApi.sendEvent(dm.id, dmPlayer, 'timeupdate', {
					paused: false,
					ended: false
				});
			}, 250);
		};
		dm.stopInterval = () => {
			if (dm.interval) {
				clearInterval(dm.interval);
			}
		};

		return dm;
	}
};

/*
 * Register DailyMotion event globally
 *
 */
mejs.Utils.typeChecks.push((url) => /\/\/((www\.)?dailymotion\.com|dai\.ly)/i.test(url) ? 'video/x-dailymotion' : null);

window.dmAsyncInit = () => {
	DailyMotionApi.apiReady();
};

mejs.Renderers.add(DailyMotionIframeRenderer);


text:
[![Build Status](https://travis-ci.org/Opfura/SchoolBundle.svg?branch=master)](https://travis-ci.org/Opfura/SchoolBundle)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/bf6efba4-b5a9-4c0e-a732-5c405f7c77ff/mini.png)](https://insight.sensiolabs.com/projects/bf6efba4-b5a9-4c0e-a732-5c405f7c77ff)

School BUndle for Opfura project


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Cosmos.Debug.Common;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace Cosmos.Debug.Common
{
    /// Handles the dialog between the Debug Stub embedded in a debugged Cosmos Kernel and
    /// our Debug Engine hosted in Visual Studio. This abstract class is communication protocol
    /// independent. Sub-classes exist that manage the wire level details of the communications.
    ///
    public abstract partial class DebugConnector : IDisposable
    {
        // MtW: This class used to use async (BeginRead/EndRead) reading, which gave some weird bug.
        // The issue was that randomly it wouldn't return any data anymore, resulting in freezes of the kernel.

        public Action<Exception> ConnectionLost;
        public Action<UInt32> CmdTrace;
        public Action<UInt32> CmdBreak;
        public Action<byte[]> CmdMethodContext;
        public Action<string> CmdText;
        public Action<string> CmdMessageBox;
        public Action CmdStarted;
        public Action<string> OnDebugMsg;
        public Action<byte[]> CmdRegisters;
        public Action<byte[]> CmdFrame;
        public Action<byte[]> CmdStack;
        public Action<byte[]> CmdPong;
        public Action<byte, byte, byte[]> CmdChannel;
        public Action<UInt32> CmdStackCorruptionOccurred;
        public Action<UInt32> CmdNullReferenceOccurred;
        public Action<UInt32> CmdSimpleNumber;
        public Action<Exception> Error;

        protected byte mCurrentMsgType;
        protected AutoResetEvent mCmdWait = new AutoResetEvent(false);

        private StreamWriter mDebugWriter = StreamWriter.Null; //new StreamWriter(@"e:\dcdebug.txt", false) { AutoFlush = true };

        // This member used to be public. The SetConnectionHandler has been added.
        private Action Connected;

        protected void HandleError(Exception E)
        {
            if (Error != null)
            {
                Error(E);
            }
            else
            {
                throw new Exception("Unhandled exception occurred!", E);
            }
        }

        /// Descendants must invoke this method whenever they detect an incoming connection.
        public void DoConnected()
        {
            if (Connected != null)
            {
                Connected();
            }
        }

        /// Defines the handler to be invoked when a connection occurs on this condector. This
        /// method is for use by the AD7Process instance.
        /// <param name="handler">The handler to be notified when a connection occur.</param>
        public void SetConnectionHandler(Action handler)
        {
            Connected = handler;
        }

        ///
        /// Method to do debug logging of the debug connector itself.
        ///
        [Conditional("DEBUGCONNECTOR_DEBUG")]
        protected void DebugLog(string message)
        {
            // even when this method doesn't do anything, DON'T REMOVE IT
            // it's used when debugging the DebugConnector, as it provides insights to what happens
        }

        protected void DoDebugMsg(string aMsg, bool aOnlyIfConnected)
        {
            if (IsConnected || aOnlyIfConnected == false)
            {
                System.Diagnostics.Debug.WriteLine(aMsg);
                if (OnDebugMsg != null)
                {
                    OnDebugMsg(aMsg);
                }
            }
        }

        protected bool mSigReceived = false;
        public bool SigReceived
        {
            get { return mSigReceived; }
        }

        // Is stream alive? Other side may not be responsive yet, use SigReceived instead for this instead
        public abstract bool IsConnected
        {
            get;
        }

        private int mDataSize;
        private List<byte[]> MethodContextDatas = new List<byte[]>();
        private List<byte[]> MemoryDatas = new List<byte[]>();

        public void DeleteBreakpoint(int aID)
        {
            SetBreakpoint(aID, 0);
        }

        protected UInt32 GetUInt32(byte[] aBytes, int aOffset)
        {
            return (UInt32)((aBytes[aOffset + 3] << 24) | (aBytes[aOffset + 2] << 16)
               | (aBytes[aOffset + 1] << 8) | aBytes[aOffset + 0]);
        }

        protected UInt16 GetUInt16(byte[] aBytes, int aOffset)
        {
            return (UInt16)((aBytes[aOffset + 1] << 8) | aBytes[aOffset + 0]);
        }

        protected void PacketMsg(byte[] aPacket)
        {
            mCurrentMsgType = aPacket[0];

            //DoDebugMsg(String.Format("DC - PacketMsg: {0}", DebugConnectorStreamWithTimeouts.BytesToString(aPacket, 0, aPacket.Length)));
            //DoDebugMsg("DC - " + mCurrentMsgType);
            // Could change to an array, but really not much benefit
            switch (mCurrentMsgType)
            {
                case Ds2Vs.TracePoint:
                    DebugLog("DC Recv: TracePoint");
                    Next(4, PacketTracePoint);
                    break;

                case Ds2Vs.BreakPoint:
                    DebugLog("DC Recv: BreakPoint");
                    Next(4, PacketBreakPoint);
                    break;

                case Ds2Vs.Message:
                    DebugLog("DC Recv: Message");
                    Next(2, PacketTextSize);
                    break;

                case Ds2Vs.MessageBox:
                    DebugLog("DC Recv: MessageBox");
                    Next(2, PacketMessageBoxTextSize);
                    break;

                case Ds2Vs.Started:
                    DebugLog("DC Recv: Started");
                    // Call WaitForMessage first, else it blocks because Ds2Vs.Started triggers
                    // other commands which need responses.
                    WaitForMessage();

                    // Guests never get the first byte sent. So we send a noop.
                    // This dummy byte seems to clear out the serial channel.
                    // Its never received, but if it ever is, its a noop anyways.
                    SendCmd(Vs2Ds.Noop);

                    // Send signature
                    var xData = new byte[4];
                    Array.Copy(BitConverter.GetBytes(Cosmos.Debug.Common.Consts.SerialSignature), 0, xData, 0, 4);
                    SendRawData(xData);

                    CmdStarted();
                    break;

                case Ds2Vs.Noop:
                    DebugLog("DC Recv: Noop");
                    // MtW: When implementing Serial support for debugging on real hardware, it appears
                    //      that when booting a machine, in the bios it emits zero's to the serial port.
                    // Kudzu: Made a Noop command to handle this
                    WaitForMessage();
                    break;

                case Ds2Vs.CmdCompleted:
                    DebugLog("DC Recv: CmdCompleted");
                    Next(1, PacketCmdCompleted);
                    break;

                case Ds2Vs.MethodContext:
                    DebugLog("DC Recv: MethodContext");
                    Next(mDataSize, PacketMethodContext);
                    break;

                case Ds2Vs.MemoryData:
                    DebugLog("DC Recv: MemoryData");
                    Next(mDataSize, PacketMemoryData);
                    break;

                case Ds2Vs.Registers:
                    DebugLog("DC Recv: Registers");
                    Next(40, PacketRegisters);
                    break;

                case Ds2Vs.Frame:
                    DebugLog("DC Recv: Frame");
                    Next(-1, PacketFrame);
                    break;

                case Ds2Vs.Stack:
                    DebugLog("DC Recv: Stack");
                    Next(-1, PacketStack);
                    break;

                case Ds2Vs.Pong:
                    DebugLog("DC Recv: Pong");
                    Next(0, PacketPong);
                    break;

                case Ds2Vs.StackCorruptionOccurred:
                    DebugLog("DC Recv: StackCorruptionOccurred");
                    Next(4, PacketStackCorruptionOccurred);
                    break;

                case Ds2Vs.NullReferenceOccurred:
                    DebugLog("DC Recv: NullReferenceOccurred");
                    Next(4, PacketNullReferenceOccurred);
                    break;

                case Ds2Vs.SimpleNumber:
                    DebugLog("DC Recv: SimpleNumber");
                    Next(4, PacketSimpleNumber);
                    break;

                default:
                    if (mCurrentMsgType > 128)
                    {
                        // other channels than debugstub
                        DebugLog("DC Recv: Console");
                        // copy to local variable, so the anonymous method will get the correct value!
                        var xChannel = mCurrentMsgType;
                        Next(1, data => PacketOtherChannelCommand(xChannel, data));
                        break;
                    }
                    // Exceptions crash VS so use MsgBox instead
                    DebugLog("Unknown debug command: " + mCurrentMsgType);
                    // Despite it being unkonwn, we try again. Normally this will
                    // just cause more unknowns, but can be useful for debugging.
                    WaitForMessage();
                    break;
            }
        }

        public virtual void Dispose()
        {
            if (mDebugWriter != null)
            {
                mDebugWriter.Dispose();
                mDebugWriter = null;
            }
            if (mBackgroundThread != null)
            {
                mBackgroundThread.Abort();
                mBackgroundThread.Join();
                mBackgroundThread = null;
            }
            GC.SuppressFinalize(this);
        }

        // Signature is sent after garbage emitted during init of serial port.
        // For more info see note in DebugStub where signature is transmitted.
        protected byte[] mSigCheck = new byte[4] { 0, 0, 0, 0 };
        protected virtual void WaitForSignature(byte[] aPacket)
        {
            mSigCheck[0] = mSigCheck[1];
            mSigCheck[1] = mSigCheck[2];
            mSigCheck[2] = mSigCheck[3];
            mSigCheck[3] = aPacket[0];
            var xSig = GetUInt32(mSigCheck, 0);
            DebugLog("DC: Sig Byte " + aPacket[0].ToString("X2").ToUpper() + " : " + xSig.ToString("X8").ToUpper());
            if (xSig == Consts.SerialSignature)
            {
                // Sig found, wait for messages
                mSigReceived = true;
                SendTextToConsole("SigReceived!");
                DebugLog("SigReceived");
                WaitForMessage();
            }
            else
            {
                SendPacketToConsole(aPacket);
                // Sig not found, keep looking
                Next(1, WaitForSignature);
            }
        }

        protected void SendPacketToConsole(byte[] aPacket)
        {
            CmdChannel(129, 0, aPacket);
        }

        protected void SendTextToConsole(string aText)
        {
            SendPacketToConsole(Encoding.UTF8.GetBytes(aText));
        }

    }
}


text:
using System.Reflection;

[assembly: AssemblyTitle("FluentWindsor.Cachely")]


text:
package org.frozenarc.zeframework.processingtube;

import org.frozenarc.zeframework.connector.ActionViewConnector;
import org.frozenarc.zeframework.evententities.EventEntities;
import org.frozenarc.zeframework.model.Model;

/**
 * The class is used if no class is defined in config.
 * @author Manan
 */
public class DefaultProcessingTube extends AbstractProcessingTube {

    @Override
    public void beforeProcessAction(Model[] models, ActionViewConnector connector, EventEntities entities) {

    }

    @Override
    public void afterProcessAction(Model[] models, ActionViewConnector connector, EventEntities entities) {

    }

    @Override
    public void beforeProcessView(Model[] models, ActionViewConnector connector, EventEntities entities) {

    }

    @Override
    public void afterProcessView(Model[] models, ActionViewConnector connector, EventEntities entities) {

    }

}


text:
class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :posts
end