text:
resource_name :bleemeo_service

property  :id,
          String,
          name_property: true,
          identity: true

property  :file_prefix,
          Integer,
          default: node['bleemeo']['file_prefix']['service'],
          identity: true

property  :parameters,
          Hash

load_current_value do
  path = "/etc/bleemeo/agent.conf.d/#{file_prefix}-service-#{id}.conf"
  # get some attributes from existing configuration file
  if ::File.exist?(path)
    parameters YAML.safe_load(::File.read(path))['service'][0]
  end
end

default_action :create
action :create do
  # Create directory to prevent faillure
  directory '/etc/bleemeo/agent.conf.d' do
    recursive true
  end

  service = new_resource.parameters
  service['id'] = new_resource.id

  # Write configuration file
  file [
    '', 'etc', 'bleemeo', 'agent.conf.d',
    "#{new_resource.file_prefix}-service-#{new_resource.id}.conf"
  ].join('/') do
    action :create
    content({ 'service' => [service] }.to_yaml)
    notifies :restart, 'service[bleemeo-agent]'
  end
end

action :delete do
  file [
    '', 'etc', 'bleemeo', 'agent.conf.d',
    "#{new_resource.file_prefix}-service-#{new_resource.id}.conf"
  ].join('/') do
    action :delete
    notifies :restart, 'service[bleemeo-agent]'
  end
end


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AdminSponsor extends Model
{
    protected $table = 'admin_users';

    protected $fillable = [
      'username','email','name','password','avatar'
    ];

}

redpajama_set_name: RedPajamaGithub


text:
<?php

return [
    // Components
    'components' => [
        'status' => [
            1 => 'Fungerar',
            2 => 'Prestandaproblem',
            3 => 'Mindre avbrott',
            4 => 'Större avbrott',
        ],
    ],

    // Incidents
    'incidents' => [
        'none'          => 'Inga händelser har rapporterats.',
        'past'          => 'Tidigare händelser',
        'previous_week' => 'Förra veckan',
        'next_week'     => 'Nästa vecka',
        'none'          => 'Inga händelser har rapporterats.',
        'scheduled'     => 'Planerat underhåll',
        'scheduled_at'  => ', schemalagda: tidsstämpel',
        'status'        => [
            0 => 'Schemalagd', // TODO: Hopefully remove this.
            1 => 'Undersöker',
            2 => 'Identifierat',
            3 => 'Bevakar',
            4 => 'Löst',
        ],
    ],

    // Service Status
    'service' => [
        'good'  => '[0,1] System operational|[2,Inf] All systems are operational',
        'bad'   => '[0,1] The system is currently experiencing issues|[2,Inf] Some systems are experiencing issues',
        'major' => '[0,1] The service experiencing a major outage|[2,Inf] Some systems are experiencing a major outage',
    ],

    'api' => [
        'regenerate' => 'Generera om API-nyckel',
        'revoke'     => 'Återkalla API-nyckel',
    ],

    // Metrics
    'metrics' => [
        'filter' => [
            'last_hour' => 'Last Hour',
            'hourly'    => 'Senaste 12 timmarna',
            'weekly'    => 'Vecka',
            'monthly'   => 'Månad',
        ],
    ],

    // Subscriber
    'subscriber' => [
        'subscribe' => 'Prenumerera för att få de senaste uppdateringarna',
        'button'    => 'Prenumerera',
        'email'     => [
            'subscribe'          => 'Prenumerera på epost-uppdateringar.',
            'subscribed'         => 'Du har börjat prenumerera på e-postmeddelanden, vänligen kontrollera din e-post för att bekräfta din prenumeration.',
            'verified'           => 'Din epost-prenumeration har bekräftats. Tack!',
            'unsubscribe'        => 'Avbeställ epost-uppdateringar.',
            'unsubscribed'       => 'Din epost-prenumeration har avbrutits.',
            'failure'            => 'Något blev fel med prenumerationen.',
            'already-subscribed' => 'Cannot subscribe :email because they\'re already subscribed.',
            'verify'             => [
                'text'           => "Vänligen bekräfta din epost-prenumeration för: :app_name-statusuppdateringar.\n:link\nTack, :app_name",
                'html-preheader' => 'Vänligen bekräfta din epost-prenumeration på statusuppdateringar för :app_name.',
                'html'           => '
Vänligen bekräfta din epost-prenumeration på :app_names statusuppdateringar.

: länk

Tack, :app_name
',
            ],
            'maintenance' => [
                'text'           => "Nytt underhåll har schemalagts för :app_name.\nTack du, :app_name",
                'html-preheader' => 'Nytt underhåll har schemalagts för :app_name.',
                'html'           => '
Nytt underhåll har schemalagts för :app_name.
',
            ],
            'incident' => [
                'text'           => "Nya händelser har rapporterats hos :app_name.\nTack, :app_name",
                'html-preheader' => 'Nya händelser har rapporterats hos :app_name.',
                'html'           => '
Nya händelser har rapporterats hos :app_name.

Tack, :app_name
',
            ],
            'component' => [
                'subject'        => 'Component Status Update',
                'text'           => 'The component :component_name has seen a status change. The component is now at :component_human_status.\nThank you, :app_name',
                'html-preheader' => 'Component Update from :app_name',
                'html'           => '
The component :component_name has seen a status change. The component is now at :component_human_status.

Thank you, :app_name
',
                'tooltip-title'  => 'Subscribe to notifications for :component_name.',
            ],
        ],
    ],

    'users' => [
        'email' => [
            'invite' => [
                'text'           => "Du har blivit inbjuden till teamet för :app_names statussida, registrera dig genom att trycka på länken.\n:link\nTack, :app_name",
                'html-preheader' => 'Du har blivit inbjuden till teamet för :app_name.',
                'html'           => '
Du har blivit inbjuden till teamet :app_names statussida. Registrera dig genom att trycka på  den här länken

Tack, :app_name
',
            ],
        ],
    ],

    'signup' => [
        'title'    => 'Registrera dig',
        'username' => 'Username',
        'email'    => 'Email',
        'password' => 'Password',
        'success'  => 'Ditt konto har skapats.',
        'failure'  => 'Något gick fel med registreringen.',
    ],

    'system' => [
        'update' => 'There is a newer version of Cachet available. You can learn how to update here!',
    ],

    // Modal
    'modal' => [
        'close'     => 'Close',
        'subscribe' => [
            'title'  => 'Subscribe to component updates?',
            'body'   => 'Enter your email address to subscribe to updates for this component. If you\'re already subscribed, you\'ll receive emails for this component too.',
            'button' => 'Prenumerera',
        ],
    ],

    // Other
    'powered_by'      => ': app statussida drivs av  Cachet.',
    'about_this_site' => 'Om sidan',
    'rss-feed'        => 'RSS',
    'atom-feed'       => 'Atom',
    'feed'            => 'Statusflöde',

];


text:
#include <aws/eventbridge/model/Secondary.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace EventBridge
{
namespace Model
{

Secondary::Secondary() :
    m_routeHasBeenSet(false)
{
}

Secondary::Secondary(JsonView jsonValue) :
    m_routeHasBeenSet(false)
{
  *this = jsonValue;
}

Secondary& Secondary::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Route"))
  {
    m_route = jsonValue.GetString("Route");

    m_routeHasBeenSet = true;
  }

  return *this;
}

JsonValue Secondary::Jsonize() const
{
  JsonValue payload;

  if(m_routeHasBeenSet)
  {
   payload.WithString("Route", m_route);

  }

  return payload;
}

} // namespace Model
} // namespace EventBridge
} // namespace Aws


text:
<?php namespace UnderStated\Examples\AutoStateExample;

use UnderStated\States\State;

/**
 * Class AutoSetupState
 * @package Examples\WhenReadyHandler
 */
class AutoSetupState extends State
{
    /**
     * An array of constraints preventing transition away
     * from this state. Keyed by the handlers signature.
     *
     * @var array
     */
    protected $constraints = [
        'haveCoffee' => false,
        'readyUpLlamas' => false,
        'releasePigeons' => false
    ];

    /**
     * Start the automatic setup by calling the checkReady
     * method. This will run through all the constraints and
     * run their handlers and finally transitioning to ready.
     *
     * @param State $state
     * @return bool
     */
    public function onEnter(State $state)
    {
        $this->checkReady();

        return parent::onEnter($state);
    }

    /**
     * Enjoy a nice cup of coffee before you
     * do anything else.
     */
    public function haveCoffee()
    {
        $this->constraints['haveCoffee'] = true;

        $this->checkReady();
    }

    /**
     * Everyone needs their Llamas readied up.
     */
    public function readyUpLlamas()
    {
        $this->constraints['readyUpLlamas'] = true;

        $this->checkReady();
    }

    /**
     * Without your homing pigeons you'd be lost.
     * Lets make sure they're released.
     */
    public function releasePigeons()
    {
        $this->constraints['releasePigeons'] = true;

        $this->checkReady();
    }

    /**
     * Check if the state can transition or has to handle more
     * setup methods before a transition can occur.
     */
    protected function checkReady()
    {
        $next = array_keys($this->constraints, false);

        if (count($next) > 0) {
            $this->handle($next[0], []);
        } else {
            $this->transition('ready');
        }
    }

    /**
     * Stop accidental transition out of this state without pre-conditions
     * having been met.
     *
     * @param State $state
     * @return bool
     */
    public function onExit(State $state)
    {
        parent::onExit($state);

        return count(array_keys($this->constraints, true)) === count($this->constraints);
    }
}


text:
package dotty.tools.dotc.classpath

import dotty.tools.io.ClassPath.RootPackage

/**
 * Common methods related to package names represented as String
 */
object PackageNameUtils {

  /**
   * @param fullClassName full class name with package
   * @return (package, simple class name)
   */
  inline def separatePkgAndClassNames(fullClassName: String): (String, String) = {
    val lastDotIndex = fullClassName.lastIndexOf('.')
    if (lastDotIndex == -1)
      (RootPackage, fullClassName)
    else
      (fullClassName.substring(0, lastDotIndex).nn, fullClassName.substring(lastDotIndex + 1).nn)
  }

  def packagePrefix(inPackage: String): String = if (inPackage == RootPackage) "" else inPackage + "."

  /**
   * `true` if `packageDottedName` is a package directly nested in `inPackage`, for example:
   *   - `packageContains("scala", "scala.collection")`
   *   - `packageContains("", "scala")`
   */
  def packageContains(inPackage: String, packageDottedName: String) = {
    if (packageDottedName.contains("."))
      packageDottedName.startsWith(inPackage) && packageDottedName.lastIndexOf('.') == inPackage.length
    else inPackage == ""
  }
}


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: releng/9.3/sys/boot/pc98/loader/main.c 243448 2012-11-23 13:35:17Z nyan $");

/*
 * MD bootstrap main() and assorted miscellaneous
 * commands.
 */

#include <stand.h>
#include <stddef.h>
#include <string.h>
#include <machine/bootinfo.h>
#include <machine/cpufunc.h>
#include <sys/param.h>
#include <sys/reboot.h>

#include "bootstrap.h"
#include "common/bootargs.h"
#include "libi386/libi386.h"
#include "libpc98/libpc98.h"
#include "btxv86.h"

CTASSERT(sizeof(struct bootargs) == BOOTARGS_SIZE);
CTASSERT(offsetof(struct bootargs, bootinfo) == BA_BOOTINFO);
CTASSERT(offsetof(struct bootargs, bootflags) == BA_BOOTFLAGS);
CTASSERT(offsetof(struct bootinfo, bi_size) == BI_SIZE);

/* Arguments passed in from the boot1/boot2 loader */
static struct bootargs *kargs;

static u_int32_t	initial_howto;
static u_int32_t	initial_bootdev;
static struct bootinfo	*initial_bootinfo;

struct arch_switch	archsw;		/* MI/MD interface boundary */

static void		extract_currdev(void);
static int		isa_inb(int port);
static void		isa_outb(int port, int value);
void			exit(int code);

/* from vers.c */
extern	char bootprog_name[], bootprog_rev[], bootprog_date[], bootprog_maker[];

/* XXX debugging */
extern char end[];

static void *heap_top;
static void *heap_bottom;

static uint64_t
pc98_loadaddr(u_int type, void *data, uint64_t addr)
{
	struct stat st;

	if (type == LOAD_ELF)
		return (roundup(addr, PAGE_SIZE));

	/* We cannot use 15M-16M area on pc98. */
	if (type == LOAD_RAW && addr < 0x1000000 && stat(data, &st) == 0 &&
	    (st.st_size == -1 || addr + st.st_size > 0xf00000))
		addr = 0x1000000;
	return (addr);
}

int
main(void)
{
    int			i;

    /* Set machine type to PC98_SYSTEM_PARAMETER. */
    set_machine_type();

    /* Pick up arguments */
    kargs = (void *)__args;
    initial_howto = kargs->howto;
    initial_bootdev = kargs->bootdev;
    initial_bootinfo = kargs->bootinfo ? (struct bootinfo *)PTOV(kargs->bootinfo) : NULL;

    /* Initialize the v86 register set to a known-good state. */
    bzero(&v86, sizeof(v86));
    v86.efl = PSL_RESERVED_DEFAULT | PSL_I;

    /*
     * Initialise the heap as early as possible.  Once this is done, malloc() is usable.
     */
    bios_getmem();

#if defined(LOADER_BZIP2_SUPPORT)
    if (high_heap_size > 0) {
	heap_top = PTOV(high_heap_base + high_heap_size);
	heap_bottom = PTOV(high_heap_base);
	if (high_heap_base < memtop_copyin)
	    memtop_copyin = high_heap_base;
    } else
#endif
    {
	heap_top = (void *)PTOV(bios_basemem);
	heap_bottom = (void *)end;
    }
    setheap(heap_bottom, heap_top);

    /*
     * XXX Chicken-and-egg problem; we want to have console output early, but some
     * console attributes may depend on reading from eg. the boot device, which we
     * can't do yet.
     *
     * We can use printf() etc. once this is done.
     * If the previous boot stage has requested a serial console, prefer that.
     */
    bi_setboothowto(initial_howto);
    if (initial_howto & RB_MULTIPLE) {
	if (initial_howto & RB_SERIAL)
	    setenv("console", "comconsole vidconsole", 1);
	else
	    setenv("console", "vidconsole comconsole", 1);
    } else if (initial_howto & RB_SERIAL)
	setenv("console", "comconsole", 1);
    else if (initial_howto & RB_MUTE)
	setenv("console", "nullconsole", 1);
    cons_probe();

    /*
     * Initialise the block cache
     */
    bcache_init(32, 512);	/* 16k cache XXX tune this */

    /*
     * Special handling for PXE and CD booting.
     */
    if (kargs->bootinfo == 0) {
	/*
	 * We only want the PXE disk to try to init itself in the below
	 * walk through devsw if we actually booted off of PXE.
	 */
	if (kargs->bootflags & KARGS_FLAGS_PXE)
	    pxe_enable(kargs->pxeinfo ? PTOV(kargs->pxeinfo) : NULL);
	else if (kargs->bootflags & KARGS_FLAGS_CD)
	    bc_add(initial_bootdev);
    }

    archsw.arch_autoload = i386_autoload;
    archsw.arch_getdev = i386_getdev;
    archsw.arch_copyin = i386_copyin;
    archsw.arch_copyout = i386_copyout;
    archsw.arch_readin = i386_readin;
    archsw.arch_isainb = isa_inb;
    archsw.arch_isaoutb = isa_outb;
    archsw.arch_loadaddr = pc98_loadaddr;

    /*
     * March through the device switch probing for things.
     */
    for (i = 0; devsw[i] != NULL; i++)
	if (devsw[i]->dv_init != NULL)
	    (devsw[i]->dv_init)();
    printf("BIOS %dkB/%dkB available memory\n", bios_basemem / 1024, bios_extmem / 1024);
    if (initial_bootinfo != NULL) {
	initial_bootinfo->bi_basemem = bios_basemem / 1024;
	initial_bootinfo->bi_extmem = bios_extmem / 1024;
    }

    printf("\n");
    printf("%s, Revision %s\n", bootprog_name, bootprog_rev);
    printf("(%s, %s)\n", bootprog_maker, bootprog_date);

    extract_currdev();				/* set $currdev and $loaddev */
    setenv("LINES", "24", 1);			/* optional */

    interact();			/* doesn't return */

    /* if we ever get here, it is an error */
    return (1);
}

/*
 * Set the 'current device' by (if possible) recovering the boot device as
 * supplied by the initial bootstrap.
 *
 * XXX should be extended for netbooting.
 */
static void
extract_currdev(void)
{
    struct i386_devdesc		new_currdev;
    int				major;
    int				biosdev = -1;

    /* Assume we are booting from a BIOS disk by default */
    new_currdev.d_dev = &biosdisk;

    /* new-style boot loaders such as pxeldr and cdldr */
    if (kargs->bootinfo == 0) {
        if ((kargs->bootflags & KARGS_FLAGS_CD) != 0) {
	    /* we are booting from a CD with cdboot */
	    new_currdev.d_dev = &bioscd;
	    new_currdev.d_unit = bc_bios2unit(initial_bootdev);
	} else if ((kargs->bootflags & KARGS_FLAGS_PXE) != 0) {
	    /* we are booting from pxeldr */
	    new_currdev.d_dev = &pxedisk;
	    new_currdev.d_unit = 0;
	} else {
	    /* we don't know what our boot device is */
	    new_currdev.d_kind.biosdisk.slice = -1;
	    new_currdev.d_kind.biosdisk.partition = 0;
	    biosdev = -1;
	}
    } else if ((initial_bootdev & B_MAGICMASK) != B_DEVMAGIC) {
	/* The passed-in boot device is bad */
	new_currdev.d_kind.biosdisk.slice = -1;
	new_currdev.d_kind.biosdisk.partition = 0;
	biosdev = -1;
    } else {
	new_currdev.d_kind.biosdisk.slice = B_SLICE(initial_bootdev) - 1;
	new_currdev.d_kind.biosdisk.partition = B_PARTITION(initial_bootdev);
	biosdev = initial_bootinfo->bi_bios_dev;
	major = B_TYPE(initial_bootdev);

	/*
	 * If we are booted by an old bootstrap, we have to guess at the BIOS
	 * unit number.  We will lose if there is more than one disk type
	 * and we are not booting from the lowest-numbered disk type
	 * (ie. SCSI when IDE also exists).
	 */
	if ((biosdev == 0) && (B_TYPE(initial_bootdev) != 2)) {	/* biosdev doesn't match major */
	    if (B_TYPE(initial_bootdev) == 6)
		biosdev = 0x30 + B_UNIT(initial_bootdev);
	    else
		biosdev = (major << 3) + 0x80 + B_UNIT(initial_bootdev);
	}
    }
    new_currdev.d_type = new_currdev.d_dev->dv_type;

    /*
     * If we are booting off of a BIOS disk and we didn't succeed in determining
     * which one we booted off of, just use disk0: as a reasonable default.
     */
    if ((new_currdev.d_type == biosdisk.dv_type) &&
	((new_currdev.d_unit = bd_bios2unit(biosdev)) == -1)) {
	printf("Can't work out which disk we are booting from.\n"
	       "Guessed BIOS device 0x%x not found by probes, defaulting to disk0:\n", biosdev);
	new_currdev.d_unit = 0;
    }

    env_setenv("currdev", EV_VOLATILE, i386_fmtdev(&new_currdev),
	       i386_setcurrdev, env_nounset);
    env_setenv("loaddev", EV_VOLATILE, i386_fmtdev(&new_currdev), env_noset,
	       env_nounset);
}

COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);

static int
command_reboot(int argc, char *argv[])
{
    int i;

    for (i = 0; devsw[i] != NULL; ++i)
	if (devsw[i]->dv_cleanup != NULL)
	    (devsw[i]->dv_cleanup)();

    printf("Rebooting...\n");
    delay(1000000);
    __exit(0);
}

/* provide this for panic, as it's not in the startup code */
void
exit(int code)
{
    __exit(code);
}

COMMAND_SET(heap, "heap", "show heap usage", command_heap);

static int
command_heap(int argc, char *argv[])
{
    mallocstats();
    printf("heap base at %p, top at %p, upper limit at %p\n", heap_bottom,
      sbrk(0), heap_top);
    return(CMD_OK);
}

/* ISA bus access functions for PnP. */
static int
isa_inb(int port)
{

    return (inb(port));
}

static void
isa_outb(int port, int value)
{

    outb(port, value);
}


text:
id: bad87fee1348bd9aedf06756
title: Override Class Declarations with Inline Styles
challengeType: 0
videoUrl: 'https://scrimba.com/c/cGJDRha'
forumTopicId: 18252
dashedName: override-class-declarations-with-inline-styles
---

# --description--

So we've proven that id declarations override class declarations, regardless of where they are declared in your `style` element CSS.

There are other ways that you can override CSS. Do you remember inline styles?

# --instructions--

Use an inline style to try to make our `h1` element white. Remember, inline styles look like this:

```html
<h1 style="color: green;">
```

Leave the `blue-text` and `pink-text` classes on your `h1` element.

# --hints--

Your `h1` element should have the class `pink-text`.

```js
assert($('h1').hasClass('pink-text'));
```

Your `h1` element should have the class `blue-text`.

```js
assert($('h1').hasClass('blue-text'));
```

Your `h1` element should have the id of `orange-text`.

```js
assert($('h1').attr('id') === 'orange-text');
```

Your `h1` element should have an inline style.

```js
assert(document.querySelector('h1[style]'));
```

Your `h1` element should be white.

```js
assert($('h1').css('color') === 'rgb(255, 255, 255)');
```

# --seed--

## --seed-contents--

```html
<style>
  body {
    background-color: black;
    font-family: monospace;
    color: green;
  }
  #orange-text {
    color: orange;
  }
  .pink-text {
    color: pink;
  }
  .blue-text {
    color: blue;
  }
</style>
<h1 id="orange-text" class="pink-text blue-text">Hello World!</h1>
```

# --solutions--

```html
<style>
  body {
    background-color: black;
    font-family: monospace;
    color: green;
  }
  #orange-text {
    color: orange;
  }
  .pink-text {
    color: pink;
  }
  .blue-text {
    color: blue;
  }
</style>
<h1 id="orange-text" class="pink-text blue-text" style="color: white">Hello World!</h1>
```


text:
WScript.Flag("-wasmI64");
WScript.Flag("-wasmcheckversion-");
function createView(bytes) {
  const buffer = new ArrayBuffer(bytes.length);
  const view = new Uint8Array(buffer);
  for (let i = 0; i < bytes.length; ++i) {
    view[i] = bytes.charCodeAt(i);
  }
  return view;
}
async function main() {
  const {instance: {exports: {foo, bar}}} = await WebAssembly.instantiate(WebAssembly.wabt.convertWast2Wasm(`
(module
  (func (export "foo") (result i64) (i64.extend_u/i32 (i32.const 0x80000000)))
  (func (export "bar") (result i64) (i64.extend_u/i32 (i32.const 0xabcdef12)))
)`));
  foo();
  bar();

  try {
    new WebAssembly.Module(createView(`\x00asm\x01\x00\x00\x00\xff\xff\xff\xff\x7f\x00\x00\x00`));
    console.log("Should have had an error");
  } catch (e) {
    if (!(e instanceof WebAssembly.CompileError && e.message.includes("Invalid known section opcode"))) {
      throw e;
    }
  }
  try {
    new WebAssembly.Module(createView(`\x00asm\x01\x00\x00\x00\x7f\x00\x00\x00`));
    console.log("Should have had an error");
  } catch (e) {
    if (!(e instanceof WebAssembly.CompileError && e.message.includes("Invalid known section opcode"))) {
      throw e;
    }
  }

  {
    const mod = new WebAssembly.Module(WebAssembly.wabt.convertWast2Wasm(`
(module
  (func (export "foo") (result i32) (i32.const 0))
)`));
    const instance1 = new WebAssembly.Instance(mod);
    const instance2 = new WebAssembly.Instance(mod);

    // Change the type of the function on the first instance
    instance1.exports.foo.asdf = 5;
    instance1.exports.foo();
    // Make sure the entrypoint has been correctly updated on the second instance
    instance2.exports.foo();
  }
}

main().then(() => console.log("PASSED"), err => {
  console.log(err.stack);
});


text:
require File.expand_path('../shared/valid_civil', __FILE__)
require 'date'

ruby_version_is "" ... "1.9" do
  describe "Date.exist?" do
    it_behaves_like :date_valid_civil?, :exist?
  end
end


text:
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using CsvHelper;
using CsvHelper.Configuration;

namespace Qwack.Providers.CSV
{
    public class NYMEXFutureParser
    {
        private readonly ConcurrentDictionary<string, List<NYMEXFutureRecord>> _cache = new();
        private static readonly NYMEXFutureParser instance = new();

        public List<NYMEXFutureRecord> Parse(string fileName)
        {
            if (_cache.TryGetValue(fileName, out var record))
                return record;

            var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using var sr = new StreamReader(fs);
            var cfg = new CsvConfiguration(CultureInfo.InvariantCulture)
            {
                HasHeaderRecord = true,
                BadDataFound = null,
            };

            using var csv = new CsvReader(sr, cfg);
            csv.Context.RegisterClassMap<NYMEXFutureRecordMap>();
            var list = csv.GetRecords<NYMEXFutureRecord>().ToList();
            _cache.TryAdd(fileName, list);

            return list;
        }

        public List<NYMEXFutureRecord> Parse(StreamReader sr)
        {
            var cfg = new CsvConfiguration(CultureInfo.InvariantCulture)
            {
                HasHeaderRecord = true,
                BadDataFound = null,
            };

            using var csv = new CsvReader(sr, cfg);
            csv.Context.RegisterClassMap<NYMEXFutureRecordMap>();
            var list = csv.GetRecords<NYMEXFutureRecord>().ToList();

            return list;
        }

        static NYMEXFutureParser()
        {
        }

        private NYMEXFutureParser()
        {
        }

        public static NYMEXFutureParser Instance => instance;
    }

    public class NYMEXFutureRecord
    {
        public string Symbol { get; set; }
        public int ContractMonth { get; set; }
        public int ContractYear { get; set; }
        public int? ContractDay { get; set; }
        public string Contract { get; set; }
        public string Description { get; set; }
        public double? Open { get; set; }
        public double? High { get; set; }
        public double? Low { get; set; }
        public double? Last { get; set; }
        public double? Settle { get; set; }
        public string Change { get; set; }
        public int Volume { get; set; }
        public double? PriorSettle { get; set; }
        public int? PriorVolume { get; set; }
        public int? PriorOI { get; set; }
        public string TradeDate { get; set; }
    }

    public sealed class NYMEXFutureRecordMap : ClassMap<NYMEXFutureRecord>
    {
        public NYMEXFutureRecordMap()
        {
            Map(m => m.Symbol).Name("PRODUCT SYMBOL");
            Map(m => m.ContractMonth).Name("CONTRACT MONTH");
            Map(m => m.ContractYear).Name("CONTRACT YEAR");
            Map(m => m.ContractDay).Name("CONTRACT DAY");
            Map(m => m.Contract).Name("CONTRACT");
            Map(m => m.Description).Name("PRODUCT DESCRIPTION");
            Map(m => m.Open).Name("OPEN");
            Map(m => m.High).Name("HIGH");
            Map(m => m.Low).Name("LOW");
            Map(m => m.Last).Name("LAST");
            Map(m => m.Settle).Name("SETTLE");
            Map(m => m.Change).Name("PT CHG");
            Map(m => m.Volume).Name("EST. VOL");
            Map(m => m.PriorSettle).Name("PRIOR SETTLE");
            Map(m => m.PriorVolume).Name("PRIOR VOL");
            Map(m => m.PriorOI).Name("PRIOR INT");
            Map(m => m.TradeDate).Name("TRADEDATE");
        }

    }
}


text:
[http://lrnk.co.uk/drawing/index.html](http://lrnk.co.uk/drawing/index.html)

Built on angular-seed:  [http://github.com/angular/angular-seed](http://github.com/angular/angular-seed)

Requires node.js and npm: [http://nodejs.org/](http://nodejs.org/).

### Install Dependencies
```
npm install
```

### Run the Application
```
npm start
```

Then browse to the app at `http://localhost:8000/app/index.html`.


text:
xlReg

[xlReg](clusterReg.html) is a tool, primarily intended for use in testing,
which facilitates the formation of
[clusters,](https://jddixon.github.io/xlattice/cluster.html)
groups of cooperating
[nodes.](https://jddixon.github.io/xlattice/node.html)

On registration, a client (an xLattice cluster member)
is issued a globally unique NodeID, a 256-bit random value.
Once it has an ID, the member can create and/or join clusters.

A cluster has
a maximum size set when it is created.  When members join the cluster they
register their two RSA public keys and one or more IP addresses.
If the cluster only supports communications between members, members
register only one IP address.  If non-member clients are allowed to
communicate with the cluster, members register a second address for
that purpose.  It is possible that certain applications may require
additional IP addresses.  (The first address is used for communications
between cluster members.  Any second address is used for communications
between cluster members acting as servers and their clients.)

When a member has completed registration, it can retrieve
the configuration data other members have registered.

The xlReg server, its clients, and the cluster members, are all
[XLattice nodes](https://jddixon.github.io/xlattice/node.html)
which means that each has

* a unique [NodeID](https://jddixon.github.io/xlattice/nodeID.html)
* two RSA keys, one for encrypting data and the other for creating
  digital signatures
* at least one address (such as a TCP/IP connection) on which it
  listens at all times
* and optionally a local file system


text:
.class public Lcom/samsung/android/settings/search/SearchResultItem$Builder;
.super Ljava/lang/Object;
.source "SearchResultItem.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/settings/search/SearchResultItem;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "Builder"
.end annotation

# instance fields
.field protected mAction:Ljava/lang/String;

.field protected mBreadcrumbs:Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/List",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation
.end field

.field protected mCategory_id:Ljava/lang/String;

.field protected mClassName:Ljava/lang/String;

.field protected mEntries:Ljava/lang/String;

.field protected mExtras:Landroid/os/Bundle;

.field protected mIcon:Landroid/graphics/drawable/Drawable;

.field protected mIconResId:I

.field protected mKey:Ljava/lang/String;

.field protected mKeywords:Ljava/lang/String;

.field protected mMenu_path:Ljava/lang/String;

.field protected mMenu_type:I

.field protected mRank:I

.field public mRankPath:Ljava/lang/String;

.field protected mResultPayload:Lcom/android/settings/search2/ResultPayload;

.field protected mScreenTitle:Ljava/lang/String;

.field protected mSummary:Ljava/lang/String;

.field protected mTargetCls:Ljava/lang/String;

.field protected mTargetPkg:Ljava/lang/String;

.field protected mTitle:Ljava/lang/String;

.field protected mTitleEn:Ljava/lang/String;

# direct methods
.method public constructor <init>()V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/16 v0, 0x2a

    iput v0, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mRank:I

    return-void
.end method

# virtual methods
.method public addAction(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mAction:Ljava/lang/String;

    return-object p0
.end method

.method public addCategoryId(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mCategory_id:Ljava/lang/String;

    return-object p0
.end method

.method public addClassName(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mClassName:Ljava/lang/String;

    return-object p0
.end method

.method public addEntries(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mEntries:Ljava/lang/String;

    return-object p0
.end method

.method public addExtras(Landroid/os/Bundle;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mExtras:Landroid/os/Bundle;

    return-object p0
.end method

.method public addIconRes(I)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mIconResId:I

    return-object p0
.end method

.method public addKey(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mKey:Ljava/lang/String;

    return-object p0
.end method

.method public addKeywords(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mKeywords:Ljava/lang/String;

    return-object p0
.end method

.method public addMenuPath(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mMenu_path:Ljava/lang/String;

    return-object p0
.end method

.method public addMenuType(I)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mMenu_type:I

    return-object p0
.end method

.method public addPayload(Lcom/android/settings/search2/ResultPayload;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mResultPayload:Lcom/android/settings/search2/ResultPayload;

    return-object p0
.end method

.method public addRankPath(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mRankPath:Ljava/lang/String;

    return-object p0
.end method

.method public addScreenTitle(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mScreenTitle:Ljava/lang/String;

    return-object p0
.end method

.method public addSummary(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mSummary:Ljava/lang/String;

    return-object p0
.end method

.method public addTargetCls(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mTargetCls:Ljava/lang/String;

    return-object p0
.end method

.method public addTargetPkg(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mTargetPkg:Ljava/lang/String;

    return-object p0
.end method

.method public addTitle(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mTitle:Ljava/lang/String;

    return-object p0
.end method

.method public addTitleEn(Ljava/lang/String;)Lcom/samsung/android/settings/search/SearchResultItem$Builder;
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mTitleEn:Ljava/lang/String;

    return-object p0
.end method

.method public build()Lcom/samsung/android/settings/search/SearchResultItem;
    .locals 2

    iget-object v0, p0, Lcom/samsung/android/settings/search/SearchResultItem$Builder;->mTitle:Ljava/lang/String;

    if-nez v0, :cond_0

    new-instance v0, Ljava/lang/IllegalArgumentException;

    const-string/jumbo v1, "SearchResultItem missing title argument"

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0

    :cond_0
    new-instance v0, Lcom/samsung/android/settings/search/SearchResultItem;

    invoke-direct {v0, p0}, Lcom/samsung/android/settings/search/SearchResultItem;-><init>(Lcom/samsung/android/settings/search/SearchResultItem$Builder;)V

    return-object v0
.end method


text:
layout: post
title: "Pengalaman kontribusi di Kubernetes"
tags:
    - development
    - kubernetes
    - opensource

category: [development]
comments: true
published: true
page_type: long
---

[![](/images/posts/kubernetes-commit.jpg)](/images/posts/kubernetes-commit.jpg)

[Pengalaman pertama](https://github.com/kubernetes/community/pull/4176) dalam kontribusi ke dalam project opensource yang besar seperti Kubernetes, memang ini hanya mengubah beberapa kata dalam dokumentasinya, tapi perasaannya bisa dibilang luar biasa, bisa menjadi bagian, atau menyumbangkan apa yang bisa disumbangkan, tidak hanya kode, intinya proyek opensource adalah semacam gotong royong.

Saya sendiri menggunakan Kubernetes untuk developement, ngulik apa saja yang bisa dilakukan.

Untuk kontribusi di proyek ini memang memiliki tahapan-tahapan yang dibutuhkan untuk membuktikan kita adalah nyata, manusia yang hendak berkontribusi, seperti memiliki digital signature di [CNCF](https://identity.linuxfoundation.org/projects/cncf) Linux Foundation untuk menandatangani _agreement_, untuk lebih lengkapnya silakan lihat [_guide_ ini](https://github.com/kubernetes/community/tree/master/contributors/guide) atau [ini](https://github.com/kubernetes/community/blob/master/contributors/guide/contributor-cheatsheet/README-id.md ) (dibuat bersama-sama kontributor Indonesia lain).

Proses dari commit dan kemudian membuat Pull Request (PR) ke upstream cukup cepat, selain ada bot, ada juga PR master yang akan melihat PR tersebut dan jika lolos maka akan di commit ke branch master.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>corpus.sinhala.crawler.controller</groupId>
	<artifactId>corpus.sinhala.crawler.controller</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>corpus.sinhala.crawler.controller</name>
	<url>http://maven.apache.org</url>
	<properties>
		<maven.compiler.target>1.7</maven.compiler.target>
		<maven.compiler.source>1.7</maven.compiler.source>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.31</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.4</version>
				<!-- nothing here -->
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.2.1</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<mainClass>corpus.sinhala.crawler.controller.Controller</mainClass>
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>

	</build>
</project>


text:
function binarySearch(object, array, comparator)
{
    var first = 0;
    var last = array.length - 1;

    while (first <= last) {
        var mid = (first + last) >> 1;
        var c = comparator(object, array[mid]);
        if (c > 0)
            first = mid + 1;
        else if (c < 0)
            last = mid - 1;
        else
            return mid;
    }

    // Return the nearest lesser index, "-1" means "0, "-2" means "1", etc.
    return -(first + 1);
}

Object.defineProperty(Array.prototype, "binaryIndexOf", { value: function(value, comparator)
{
    var result = binarySearch(value, this, comparator);
    return result >= 0 ? result : -1;
}});

function insertionIndexForObjectInListSortedByFunction(anObject, aList, aFunction)
{
    var index = binarySearch(anObject, aList, aFunction);
    if (index < 0)
        // See binarySearch implementation.
        return -index - 1;
    else {
        // Return the first occurance of an item in the list.
        while (index > 0 && aFunction(anObject, aList[index - 1]) === 0)
            index--;
        return index;
    }
}


text:
package org.drools.compiler.lang.descr;

import java.util.List;

public interface ConditionalElementDescr {

    public void insertBeforeLast(final Class<?> clazz ,final BaseDescr baseDescr );

    public void addDescr(BaseDescr baseDescr);

    public boolean removeDescr(BaseDescr baseDescr);

    public void addOrMerge(final BaseDescr baseDescr);

    public List<? extends BaseDescr> getDescrs();
}


text:
<?php

/**
 * dmSetting module configuration.
 *
 * @package    tourel
 * @subpackage dmSetting
 * @author     thibault d
 * @version    SVN: $Id: form.php 12474 2008-10-31 10:41:27Z fabien $
 */
class DmSettingAdminForm extends BaseDmSettingForm
{
}


text:
import * as QRCode from "qrcode.react";
import * as React from "react";

const qrcodes = [
	<QRCode value="https://github.com/DefinitelyTyped/DefinitelyTyped"/>,
	<QRCode value="https://github.com/DefinitelyTyped/DefinitelyTyped" size={64}/>,
	<QRCode value="https://github.com/DefinitelyTyped/DefinitelyTyped" bgColor="#555555"/>,
	<QRCode value="https://github.com/DefinitelyTyped/DefinitelyTyped" fgColor="#aaaaaa"/>,
	<QRCode value="https://github.com/DefinitelyTyped/DefinitelyTyped" level="L"/>,
	<QRCode value="https://github.com/DefinitelyTyped/DefinitelyTyped" level="H"/>,
	<QRCode value="https://github.com/DefinitelyTyped/DefinitelyTyped" size={256} bgColor="pink" fgColor="red" level="Q"/>,
];


text:
import {AST, BindingPipe, LiteralPrimitive} from '@angular/compiler/src/expression_parser/ast';
import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {Parser} from '@angular/compiler/src/expression_parser/parser';
import {beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing';

import {isBlank, isPresent} from '../../src/facade/lang';

import {Unparser} from './unparser';

export function main() {
  function createParser() { return new Parser(new Lexer()); }

  function parseAction(text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
    return createParser().parseAction(text, location);
  }

  function parseBinding(text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
    return createParser().parseBinding(text, location);
  }

  function parseTemplateBindings(
      text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
    return createParser().parseTemplateBindings(text, location).templateBindings;
  }

  function parseInterpolation(
      text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
    return createParser().parseInterpolation(text, location);
  }

  function parseSimpleBinding(
      text: any /** TODO #9100 */, location: any /** TODO #9100 */ = null): any {
    return createParser().parseSimpleBinding(text, location);
  }

  function unparse(ast: AST): string { return new Unparser().unparse(ast); }

  function checkInterpolation(exp: string, expected?: string) {
    var ast = parseInterpolation(exp);
    if (isBlank(expected)) expected = exp;
    expect(unparse(ast)).toEqual(expected);
  }

  function checkBinding(exp: string, expected?: string) {
    var ast = parseBinding(exp);
    if (isBlank(expected)) expected = exp;
    expect(unparse(ast)).toEqual(expected);
  }

  function checkAction(exp: string, expected?: string) {
    var ast = parseAction(exp);
    if (isBlank(expected)) expected = exp;
    expect(unparse(ast)).toEqual(expected);
  }

  function expectActionError(text: any /** TODO #9100 */) {
    return expect(() => parseAction(text));
  }

  function expectBindingError(text: any /** TODO #9100 */) {
    return expect(() => parseBinding(text));
  }

  describe('parser', () => {
    describe('parseAction', () => {
      it('should parse numbers', () => { checkAction('1'); });

      it('should parse strings', () => {
        checkAction('\'1\'', '"1"');
        checkAction('"1"');
      });

      it('should parse null', () => { checkAction('null'); });

      it('should parse unary - expressions', () => {
        checkAction('-1', '0 - 1');
        checkAction('+1', '1');
      });

      it('should parse unary ! expressions', () => {
        checkAction('!true');
        checkAction('!!true');
        checkAction('!!!true');
      });

      it('should parse multiplicative expressions',
         () => { checkAction('3*4/2%5', '3 * 4 / 2 % 5'); });

      it('should parse additive expressions', () => { checkAction('3 + 6 - 2'); });

      it('should parse relational expressions', () => {
        checkAction('2 < 3');
        checkAction('2 > 3');
        checkAction('2 <= 2');
        checkAction('2 >= 2');
      });

      it('should parse equality expressions', () => {
        checkAction('2 == 3');
        checkAction('2 != 3');
      });

      it('should parse strict equality expressions', () => {
        checkAction('2 === 3');
        checkAction('2 !== 3');
      });

      it('should parse expressions', () => {
        checkAction('true && true');
        checkAction('true || false');
      });

      it('should parse grouped expressions', () => { checkAction('(1 + 2) * 3', '1 + 2 * 3'); });

      it('should ignore comments in expressions', () => { checkAction('a //comment', 'a'); });

      it('should retain // in string literals',
         () => { checkAction(`"http://www.google.com"`, `"http://www.google.com"`); });

      it('should parse an empty string', () => { checkAction(''); });

      describe('literals', () => {
        it('should parse array', () => {
          checkAction('[1][0]');
          checkAction('[[1]][0][0]');
          checkAction('[]');
          checkAction('[].length');
          checkAction('[1, 2].length');
        });

        it('should parse map', () => {
          checkAction('{}');
          checkAction('{a: 1}[2]');
          checkAction('{}["a"]');
        });

        it('should only allow identifier, string, or keyword as map key', () => {
          expectActionError('{(:0}').toThrowError(
              new RegExp('expected identifier, keyword, or string'));
          expectActionError('{1234:0}')
              .toThrowError(new RegExp('expected identifier, keyword, or string'));
        });
      });

      describe('member access', () => {
        it('should parse field access', () => {
          checkAction('a');
          checkAction('a.a');
        });

        it('should only allow identifier or keyword as member names', () => {
          expectActionError('x.(').toThrowError(new RegExp('identifier or keyword'));
          expectActionError('x. 1234').toThrowError(new RegExp('identifier or keyword'));
          expectActionError('x."foo"').toThrowError(new RegExp('identifier or keyword'));
        });

        it('should parse safe field access', () => {
          checkAction('a?.a');
          checkAction('a.a?.a');
        });
      });

      describe('method calls', () => {
        it('should parse method calls', () => {
          checkAction('fn()');
          checkAction('add(1, 2)');
          checkAction('a.add(1, 2)');
          checkAction('fn().add(1, 2)');
        });
      });

      describe('functional calls', () => {
        it('should parse function calls', () => { checkAction('fn()(1, 2)'); });
      });

      describe('conditional', () => {
        it('should parse ternary/conditional expressions', () => {
          checkAction('7 == 3 + 4 ? 10 : 20');
          checkAction('false ? 10 : 20');
        });

        it('should throw on incorrect ternary operator syntax', () => {
          expectActionError('true?1').toThrowError(new RegExp(
              'Parser Error: Conditional expression true\\?1 requires all 3 expressions'));
        });
      });

      describe('assignment', () => {
        it('should support field assignments', () => {
          checkAction('a = 12');
          checkAction('a.a.a = 123');
          checkAction('a = 123; b = 234;');
        });

        it('should throw on safe field assignments', () => {
          expectActionError('a?.a = 123')
              .toThrowError(new RegExp('cannot be used in the assignment'));
        });

        it('should support array updates', () => { checkAction('a[0] = 200'); });
      });

      it('should error when using pipes',
         () => { expectActionError('x|blah').toThrowError(new RegExp('Cannot have a pipe')); });

      it('should store the source in the result',
         () => { expect(parseAction('someExpr').source).toBe('someExpr'); });

      it('should store the passed-in location',
         () => { expect(parseAction('someExpr', 'location').location).toBe('location'); });

      it('should throw when encountering interpolation', () => {
        expectActionError('{{a()}}').toThrowErrorWith(
            'Got interpolation ({{}}) where expression was expected');
      });
    });

    describe('general error handling', () => {
      it('should throw on an unexpected token', () => {
        expectActionError('[1,2] trac').toThrowError(new RegExp('Unexpected token \'trac\''));
      });

      it('should throw a reasonable error for unconsumed tokens', () => {
        expectActionError(')').toThrowError(
            new RegExp('Unexpected token \\) at column 1 in \\[\\)\\]'));
      });

      it('should throw on missing expected token', () => {
        expectActionError('a(b').toThrowError(
            new RegExp('Missing expected \\) at the end of the expression \\[a\\(b\\]'));
      });
    });

    describe('parseBinding', () => {
      describe('pipes', () => {
        it('should parse pipes', () => {
          checkBinding('a(b | c)', 'a((b | c))');
          checkBinding('a.b(c.d(e) | f)', 'a.b((c.d(e) | f))');
          checkBinding('[1, 2, 3] | a', '([1, 2, 3] | a)');
          checkBinding('{a: 1} | b', '({a: 1} | b)');
          checkBinding('a[b] | c', '(a[b] | c)');
          checkBinding('a?.b | c', '(a?.b | c)');
          checkBinding('true | a', '(true | a)');
          checkBinding('a | b:c | d', '((a | b:c) | d)');
          checkBinding('a | b:(c | d)', '(a | b:(c | d))');
        });

        it('should only allow identifier or keyword as formatter names', () => {
          expectBindingError('"Foo"|(').toThrowError(new RegExp('identifier or keyword'));
          expectBindingError('"Foo"|1234').toThrowError(new RegExp('identifier or keyword'));
          expectBindingError('"Foo"|"uppercase"').toThrowError(new RegExp('identifier or keyword'));
        });

        it('should parse quoted expressions', () => { checkBinding('a:b', 'a:b'); });

        it('should not crash when prefix part is not tokenizable',
           () => { checkBinding('"a:b"', '"a:b"'); });

        it('should ignore whitespace around quote prefix', () => { checkBinding(' a :b', 'a:b'); });

        it('should refuse prefixes that are not single identifiers', () => {
          expectBindingError('a + b:c').toThrowError();
          expectBindingError('1:c').toThrowError();
        });
      });

      it('should store the source in the result',
         () => { expect(parseBinding('someExpr').source).toBe('someExpr'); });

      it('should store the passed-in location',
         () => { expect(parseBinding('someExpr', 'location').location).toBe('location'); });

      it('should throw on chain expressions', () => {
        expect(() => parseBinding('1;2')).toThrowError(new RegExp('contain chained expression'));
      });

      it('should throw on assignment', () => {
        expect(() => parseBinding('a=2')).toThrowError(new RegExp('contain assignments'));
      });

      it('should throw when encountering interpolation', () => {
        expectBindingError('{{a.b}}').toThrowErrorWith(
            'Got interpolation ({{}}) where expression was expected');
      });

      it('should parse conditional expression', () => { checkBinding('a < b ? a : b'); });

      it('should ignore comments in bindings', () => { checkBinding('a //comment', 'a'); });

      it('should retain // in string literals',
         () => { checkBinding(`"http://www.google.com"`, `"http://www.google.com"`); });

      it('should retain // in : microsyntax', () => { checkBinding('one:a//b', 'one:a//b'); });

    });

    describe('parseTemplateBindings', () => {

      function keys(templateBindings: any[]) {
        return templateBindings.map(binding => binding.key);
      }

      function keyValues(templateBindings: any[]) {
        return templateBindings.map(binding => {
          if (binding.keyIsVar) {
            return 'let ' + binding.key + (isBlank(binding.name) ? '=null' : '=' + binding.name);
          } else {
            return binding.key + (isBlank(binding.expression) ? '' : `=${binding.expression}`)
          }
        });
      }

      function exprSources(templateBindings: any[]) {
        return templateBindings.map(
            binding => isPresent(binding.expression) ? binding.expression.source : null);
      }

      it('should parse an empty string', () => { expect(parseTemplateBindings('')).toEqual([]); });

      it('should parse a string without a value',
         () => { expect(keys(parseTemplateBindings('a'))).toEqual(['a']); });

      it('should only allow identifier, string, or keyword including dashes as keys', () => {
        var bindings = parseTemplateBindings('a:\'b\'');
        expect(keys(bindings)).toEqual(['a']);

        bindings = parseTemplateBindings('\'a\':\'b\'');
        expect(keys(bindings)).toEqual(['a']);

        bindings = parseTemplateBindings('"a":\'b\'');
        expect(keys(bindings)).toEqual(['a']);

        bindings = parseTemplateBindings('a-b:\'c\'');
        expect(keys(bindings)).toEqual(['a-b']);

        expect(() => {
          parseTemplateBindings('(:0');
        }).toThrowError(new RegExp('expected identifier, keyword, or string'));

        expect(() => {
          parseTemplateBindings('1234:0');
        }).toThrowError(new RegExp('expected identifier, keyword, or string'));
      });

      it('should detect expressions as value', () => {
        var bindings = parseTemplateBindings('a:b');
        expect(exprSources(bindings)).toEqual(['b']);

        bindings = parseTemplateBindings('a:1+1');
        expect(exprSources(bindings)).toEqual(['1+1']);
      });

      it('should detect names as value', () => {
        var bindings = parseTemplateBindings('a:let b');
        expect(keyValues(bindings)).toEqual(['a', 'let b=\$implicit']);
      });

      it('should allow space and colon as separators', () => {
        var bindings = parseTemplateBindings('a:b');
        expect(keys(bindings)).toEqual(['a']);
        expect(exprSources(bindings)).toEqual(['b']);

        bindings = parseTemplateBindings('a b');
        expect(keys(bindings)).toEqual(['a']);
        expect(exprSources(bindings)).toEqual(['b']);
      });

      it('should allow multiple pairs', () => {
        var bindings = parseTemplateBindings('a 1 b 2');
        expect(keys(bindings)).toEqual(['a', 'aB']);
        expect(exprSources(bindings)).toEqual(['1 ', '2']);
      });

      it('should store the sources in the result', () => {
        var bindings = parseTemplateBindings('a 1,b 2');
        expect(bindings[0].expression.source).toEqual('1');
        expect(bindings[1].expression.source).toEqual('2');
      });

      it('should store the passed-in location', () => {
        var bindings = parseTemplateBindings('a 1,b 2', 'location');
        expect(bindings[0].expression.location).toEqual('location');
      });

      it('should support var notation with a deprecation warning', () => {
        var bindings = createParser().parseTemplateBindings('var i', null);
        expect(keyValues(bindings.templateBindings)).toEqual(['let i=\$implicit']);
        expect(bindings.warnings).toEqual([
          '"var" inside of expressions is deprecated. Use "let" instead!'
        ]);
      });

      it('should support # notation with a deprecation warning', () => {
        var bindings = createParser().parseTemplateBindings('#i', null);
        expect(keyValues(bindings.templateBindings)).toEqual(['let i=\$implicit']);
        expect(bindings.warnings).toEqual([
          '"#" inside of expressions is deprecated. Use "let" instead!'
        ]);
      });

      it('should support let notation', () => {
        var bindings = parseTemplateBindings('let i');
        expect(keyValues(bindings)).toEqual(['let i=\$implicit']);

        bindings = parseTemplateBindings('let i');
        expect(keyValues(bindings)).toEqual(['let i=\$implicit']);

        bindings = parseTemplateBindings('let a; let b');
        expect(keyValues(bindings)).toEqual(['let a=\$implicit', 'let b=\$implicit']);

        bindings = parseTemplateBindings('let a; let b;');
        expect(keyValues(bindings)).toEqual(['let a=\$implicit', 'let b=\$implicit']);

        bindings = parseTemplateBindings('let i-a = k-a');
        expect(keyValues(bindings)).toEqual(['let i-a=k-a']);

        bindings = parseTemplateBindings('keyword let item; let i = k');
        expect(keyValues(bindings)).toEqual(['keyword', 'let item=\$implicit', 'let i=k']);

        bindings = parseTemplateBindings('keyword: let item; let i = k');
        expect(keyValues(bindings)).toEqual(['keyword', 'let item=\$implicit', 'let i=k']);

        bindings = parseTemplateBindings('directive: let item in expr; let a = b', 'location');
        expect(keyValues(bindings)).toEqual([
          'directive', 'let item=\$implicit', 'directiveIn=expr in location', 'let a=b'
        ]);
      });

      it('should parse pipes', () => {
        var bindings = parseTemplateBindings('key value|pipe');
        var ast = bindings[0].expression.ast;
        expect(ast).toBeAnInstanceOf(BindingPipe);
      });
    });

    describe('parseInterpolation', () => {
      it('should return null if no interpolation',
         () => { expect(parseInterpolation('nothing')).toBe(null); });

      it('should parse no prefix/suffix interpolation', () => {
        var ast = parseInterpolation('{{a}}').ast;
        expect(ast.strings).toEqual(['', '']);
        expect(ast.expressions.length).toEqual(1);
        expect(ast.expressions[0].name).toEqual('a');
      });

      it('should parse prefix/suffix with multiple interpolation', () => {
        var originalExp = 'before {{ a }} middle {{ b }} after';
        var ast = parseInterpolation(originalExp).ast;
        expect(new Unparser().unparse(ast)).toEqual(originalExp);
      });

      it('should throw on empty interpolation expressions', () => {
        expect(() => parseInterpolation('{{}}'))
            .toThrowErrorWith(
                'Parser Error: Blank expressions are not allowed in interpolated strings');

        expect(() => parseInterpolation('foo {{  }}'))
            .toThrowErrorWith(
                'Parser Error: Blank expressions are not allowed in interpolated strings');
      });

      it('should parse conditional expression',
         () => { checkInterpolation('{{ a < b ? a : b }}'); });

      it('should parse expression with newline characters', () => {
        checkInterpolation(`{{ 'foo' +\n 'bar' +\r 'baz' }}`, `{{ "foo" + "bar" + "baz" }}`);
      });

      it('should support custom interpolation', () => {
        const parser = new Parser(new Lexer());
        const ast = parser.parseInterpolation('{% a %}', null, {start: '{%', end: '%}'}).ast as any;
        expect(ast.strings).toEqual(['', '']);
        expect(ast.expressions.length).toEqual(1);
        expect(ast.expressions[0].name).toEqual('a');
      });

      describe('comments', () => {
        it('should ignore comments in interpolation expressions',
           () => { checkInterpolation('{{a //comment}}', '{{ a }}'); });

        it('should retain // in single quote strings', () => {
          checkInterpolation(`{{ 'http://www.google.com' }}`, `{{ "http://www.google.com" }}`);
        });

        it('should retain // in double quote strings', () => {
          checkInterpolation(`{{ "http://www.google.com" }}`, `{{ "http://www.google.com" }}`);
        });

        it('should ignore comments after string literals',
           () => { checkInterpolation(`{{ "a//b" //comment }}`, `{{ "a//b" }}`); });

        it('should retain // in complex strings', () => {
          checkInterpolation(
              `{{"//a\'//b\`//c\`//d\'//e" //comment}}`, `{{ "//a\'//b\`//c\`//d\'//e" }}`);
        });

        it('should retain // in nested, unterminated strings',
           () => { checkInterpolation(`{{ "a\'b\`" //comment}}`, `{{ "a\'b\`" }}`); });
      });

    });

    describe('parseSimpleBinding', () => {
      it('should parse a field access', () => {
        var p = parseSimpleBinding('name');
        expect(unparse(p)).toEqual('name');
      });

      it('should parse a constant', () => {
        var p = parseSimpleBinding('[1, 2]');
        expect(unparse(p)).toEqual('[1, 2]');
      });

      it('should throw when the given expression is not just a field name', () => {
        expect(() => parseSimpleBinding('name + 1'))
            .toThrowErrorWith(
                'Host binding expression can only contain field access and constants');
      });

      it('should throw when encountering interpolation', () => {
        expect(() => parseSimpleBinding('{{exp}}'))
            .toThrowErrorWith('Got interpolation ({{}}) where expression was expected');
      });
    });

    describe('wrapLiteralPrimitive', () => {
      it('should wrap a literal primitive', () => {
        expect(unparse(createParser().wrapLiteralPrimitive('foo', null))).toEqual('"foo"');
      });
    });
  });
}


text:
/*
 * vim:ts=4:sw=4:expandtab
 *
 * i3bar - an xcb-based status- and ws-bar for i3
 * © 2010 Axel Wagner and contributors (see also: LICENSE)
 *
 * mode.c: Handle mode event and show current binding mode in the bar
 *
 */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <yajl/yajl_parse.h>
#include <yajl/yajl_version.h>

#include "common.h"

/* A datatype to pass through the callbacks to save the state */
struct mode_json_params {
    char *json;
    char *cur_key;
    mode *mode;
};

/*
 * Parse a string (change)
 *
 */
static int mode_string_cb(void *params_, const unsigned char *val, size_t len) {
    struct mode_json_params *params = (struct mode_json_params *)params_;

    if (!strcmp(params->cur_key, "change")) {
        /* Save the name */
        params->mode->name = i3string_from_markup_with_length((const char *)val, len);
        /* Save its rendered width */
        params->mode->width = predict_text_width(params->mode->name);

        DLOG("Got mode change: %s\n", i3string_as_utf8(params->mode->name));
        FREE(params->cur_key);

        return 1;
    }

    return 0;
}

/*
 * Parse a key.
 *
 * Essentially we just save it in the parsing state
 *
 */
static int mode_map_key_cb(void *params_, const unsigned char *keyVal, size_t keyLen) {
    struct mode_json_params *params = (struct mode_json_params *)params_;
    FREE(params->cur_key);

    params->cur_key = smalloc(sizeof(unsigned char) * (keyLen + 1));
    strncpy(params->cur_key, (const char *)keyVal, keyLen);
    params->cur_key[keyLen] = '\0';

    return 1;
}

/* A datastructure to pass all these callbacks to yajl */
static yajl_callbacks mode_callbacks = {
    .yajl_string = mode_string_cb,
    .yajl_map_key = mode_map_key_cb,
};

/*
 * Start parsing the received JSON string
 *
 */
void parse_mode_json(char *json) {
    /* FIXME: Fasciliate stream processing, i.e. allow starting to interpret
     * JSON in chunks */
    struct mode_json_params params;

    mode binding;

    params.cur_key = NULL;
    params.json = json;
    params.mode = &binding;

    yajl_handle handle;
    yajl_status state;

    handle = yajl_alloc(&mode_callbacks, NULL, (void *)&params);

    state = yajl_parse(handle, (const unsigned char *)json, strlen(json));

    /* FIXME: Propper error handling for JSON parsing */
    switch (state) {
        case yajl_status_ok:
            break;
        case yajl_status_client_canceled:
        case yajl_status_error:
            ELOG("Could not parse mode event!\n");
            exit(EXIT_FAILURE);
            break;
    }

    /* We don't want to indicate default binding mode */
    if (strcmp("default", i3string_as_utf8(params.mode->name)) == 0)
        I3STRING_FREE(params.mode->name);

    /* Set the new binding mode */
    set_current_mode(&binding);

    yajl_free(handle);

    FREE(params.cur_key);
}


text:
print('main.py was successfully called')
print('this is the new main.py')

import os
print('imported os')

try:
    print('contents of ./lib/python2.7/site-packages/ etc.')
    print(os.listdir('./lib'))
    print(os.listdir('./lib/python2.7'))
    print(os.listdir('./lib/python2.7/site-packages'))
except OSError:
    print('could not look in dirs')
    print('this is expected on desktop')

import flask
print('flask1???')

print('contents of this dir', os.listdir('./'))

import flask
print('flask???')

import sys
print('pythonpath is', sys.path)

from flask import Flask
app = Flask(__name__)

from flask import (Flask, url_for, render_template, request, redirect,
                   flash)

print('imported flask etc')
print('importing pyjnius')

from jnius import autoclass
Context = autoclass('android.content.Context')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
activity = PythonActivity.mActivity

vibrator = activity.getSystemService(Context.VIBRATOR_SERVICE)

ActivityInfo = autoclass('android.content.pm.ActivityInfo')

@app.route('/')
def page1():
    return render_template('index.html')

@app.route('/page2')
def page2():
    return render_template('page2.html')

@app.route('/vibrate')
def vibrate():
    args = request.args
    if 'time' not in args:
        print('ERROR: asked to vibrate but without time argument')
    print('asked to vibrate', args['time'])

    vibrator.vibrate(float(args['time']) * 1000)
    print('vibrated')

@app.route('/loadUrl')
def loadUrl():
    args = request.args
    if 'url' not in args:
        print('ERROR: asked to open an url but without url argument')
    print('asked to open url', args['url'])
    activity.loadUrl(args['url'])

@app.route('/orientation')
def orientation():
    args = request.args
    if 'dir' not in args:
        print('ERROR: asked to orient but no dir specified')
    direction = args['dir']
    if direction not in ('horizontal', 'vertical'):
        print('ERROR: asked to orient to neither horizontal nor vertical')

    if direction == 'horizontal':
        activity.setRequestedOrientation(
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
    else:
        activity.setRequestedOrientation(
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)

from os import curdir
from os.path import realpath
print('curdir', realpath(curdir))
if realpath(curdir).startswith('/data'):
    app.run(debug=False)
else:
    app.run(debug=True)


text:
package com.baidu.beidou.navimgr.auth.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.beidou.navimgr.auth.constant.UserWebConstant;
import com.baidu.beidou.navimgr.auth.vo.User;
import com.baidu.beidou.navimgr.common.interceptor.WebCommonInterceptor;
import com.baidu.beidou.navimgr.util.HttpUtils;
import com.baidu.beidou.navimgr.util.IPUtils;
import com.baidu.beidou.navimgr.util.ThreadContext;

/**
 * ClassName: AccessLogInterceptor <br/>
 * Function: 访问日志记录拦截器,作为最外层拦截器实现,特别注意需要负责线程上下文ThreadContext的管理
 *
 * @author zhangxu04
 */
public class AccessLogInterceptor extends WebCommonInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(LoginInterceptor.class);

    /**
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#afterCompletion(javax.servlet.http
     * .HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
                                Exception arg3) throws Exception {
        try {
            String ip = IPUtils.getIpAddr(arg0);
            String browser = HttpUtils.getHttpBrowser(arg0);
            String url = HttpUtils.getFullURL(arg0);
            long elapsedTime = System.currentTimeMillis()
                    - (Long) (ThreadContext.getContext(UserWebConstant.CTX_START_TIME));
            LOG.info(getAccessLog(ip, getUser(), getUserId(), browser, url, elapsedTime));
        } catch (Exception e) {
            LOG.error("Failed to take down access log. " + e.getMessage(), e);
        } finally {
            ThreadContext.clean(); // clear thread context
        }
    }

    /**
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http
     * .HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        ThreadContext.init(); // init thread context
        ThreadContext.putContext(UserWebConstant.CTX_START_TIME, System.currentTimeMillis());
        return true;
    }

    /**
     * 获得访问者
     *
     * @return User
     */
    protected User getUser() {
        User visitor = ThreadContext.getSessionVisitor();
        if (visitor != null) {
            return visitor;
        }
        return null;
    }

    /**
     * 获得请求中要操作的userId
     *
     * @return 用户id
     */
    protected Integer getUserId() {
        Integer userId = ThreadContext.getContext(UserWebConstant.CTX_USERID);
        if (userId != null) {
            return userId;
        }
        return null;
    }

    /**
     * 日志操作记录-人员类型
     */
    protected static enum AccessLogType {
        /**
         * 管理员操作
         */
        MANAGER,

        /**
         * 前端用户
         */
        PORTAL_USER,
    }

    /**
     * 记录访问日志
     *
     * @param ip          访问IP
     * @param visitor     访问者
     * @param userId      用户id
     * @param browser     浏览器
     * @param url         访问URL
     * @param elapsedTime 请求耗时
     *
     * @return 记录日志行
     */
    private String getAccessLog(String ip, User visitor, Integer userId, String browser,
                                String url, long elapsedTime) {
        StringBuilder sb = new StringBuilder();
        sb.append(null != ip ? ip : "unknown").append("\t");

        if (visitor == null) {
            sb.append("-\t-\t");
        } else {
            if (userId == null) {
                sb.append("-\t");
            } else {
                sb.append(
                        visitor.getUserId() == userId ? AccessLogType.PORTAL_USER
                                : AccessLogType.MANAGER).append("\t");
            }
            sb.append(visitor.getUserId()).append(",").append(visitor.getUserName()).append(",")
                    .append(visitor.getRoles()).append("\t");
        }

        sb.append(null != userId ? userId : "-").append("\t");
        sb.append(url).append("\t");
        sb.append(browser).append("\t");
        sb.append(elapsedTime).append("ms");
        return sb.toString();
    }

}


text:
Target apps, proxies and policies are configured in:
> in apps/gateway/config/config.exs

Demo users are configured in:
> apps/directory/config/config.exs

### Run
Run target apps on their configured localhost port.

To run trident
```
in the trident_umbrella directory
$ mix deps.get
$ mix compile
$ iex -S mix run --no-halt
```


text:
layout: post
title: How to configure Coupon Carrier to trigger your MailChimp Automation for new subscribers
---

**Note! This is an advanced integration that requires some knowledge within [MailChimp Automations](https://mailchimp.com/features/automation/) and merge fields.**

The simple way to setup Coupon Carrier is to let it send out the email to the subscriber.
The complete guide on how to set that up is available [here]({% post_url 2016-10-13-Send-unique-codes-to-new-mailchimp-subscribers %}).

But if you want more control over the content you can create your own automation email and let Coupon Carrier trigger that to be sent to the subscriber instead.
This involves the following steps:

* Add a merge field to your list
* Create a MailChimp automation of the correct type that can be triggered
* Configure Coupon Carrier to trigger the automation

### How does it work?
When Coupon Carrier receives a notification that a new subscriber has been added to your list it picks one of the available unique codes and applies it to the subscribers merge field that you've configured.
It then triggers the selected automation to be sent to the subscriber. This means that when the email is sent it can include the code via a merge tag since that was just added to the subscriber.

### Add a merge field to your list
We need a merge tag to be able to store the unique code in the subscribers profile.
Create a merge field called *COUPON* of the type *Text*.
This can be anything but in this guide we will assume it's named *COUPON*.
You can also deselect the *Visible?* checkbox. This ensures that this field don't show up in any subscribe form if you have any.
![Create merge tag]({{ site.baseurl }}/images/screenshots/create-merge-tag.png)

### Create the MailChimp automation
There are many types of automations in MailChimp. We want to create an automation that only sends an email when some third-party app (Coupon Carrier in this case) triggers it to be sent to a specific subscriber.
Coupon Carrier can only trigger one specific type of automation, called **API 3.0**. It's available under the *Integrations* category.

**Note! Only automations that are created using this type can be triggered by Coupon Carrier.**
![Create API 3.0 Automation]({{ site.baseurl }}/images/screenshots/create-automation-1.png)

When the automation has been created there is usually tree sample emails created in the workflow.
In this case we only want one email so you can remove the other two emails.

The next step is to configure the trigger. The default is to have the email sent 1 day after the automation is triggered.
We don't want the subscriber to have to wait 1 whole day for their email so let's change this to *Immediately* instead.
To edit the trigger click the *Edit trigger* link at the top of the workflow.

![Automation Trigger]({{ site.baseurl }}/images/screenshots/automation-trigger.png)

Click the *Design email* button to edit the email. Proceed by entering all the details according to your needs.
When you get to design your email you need to add the merge tag at the place where you want your code to be shown.
A merge tag is added using the following format *\*\|Field name\|\**. So in your case you should add **\*\|COUPON\|\***.

![Automation design]({{ site.baseurl }}/images/screenshots/automation-design.png)

The final step in creating the automation is to enable it. Proceed to the *Confirm* step of the wizard and then click *Start Workflow*.
If the workflow isn't started no emails can be triggered so this is an important step.

![Automation start]({{ site.baseurl }}/images/screenshots/automation-start.png)

### Configure Coupon Carrier to trigger the automation

The final part is to configure Coupon Carrier to trigger the email. Login to your Coupon Carrier account and head over to the *Welcome Email* tab.
First we need to tell Coupon Carrier to store the code in a merge field, called *Coupon* in our case, so select that in the list.

The second part is to select *Send your email using a MailChimp Automation* and select the automation workflow that you've just created.
If the automation is disabled it means that it's not the correct type or that it's not started.

Remember to save your changes and you're good to go.

![Configure trigger]({{ site.baseurl }}/images/screenshots/trigger-automation.png)

Contact us at [support@couponcarrier.io](mailto:support+help@couponcarrier.io) if you have any questions or if you need additional help.


text:
import random
import re

from bot.plugins.base import BasePlugin
from bot.plugins.commands import command
from bot.plugins.events import StopCommandExecution, command_resolved, receiver
from bot.users.decorators import bot_admin_required

BASE_PROBABILITY = 0.1  # 10% to start with

class Plugin(BasePlugin):

    MESSAGES = [
        "Meh, maybe later",
        "I don't feel like it",
        "Go and ask someone else, I'm on my coffee break",
        "You again? Go annoy @Google or something",
        "Why don't you do something yourself for once?",
    ]

    PROBABILITY = BASE_PROBABILITY

    IGNORE_COMMANDS = [
        'reset probability',
    ]

    @receiver(command_resolved)
    async def refuse_command(self, command, handler):
        if random.random() < self.PROBABILITY and command.command.name not in self.IGNORE_COMMANDS:
            msg = random.choice(self.MESSAGES)
            await command.reply(msg)
            raise StopCommandExecution()

    @command(pattern=re.compile(r'(?P<prob>0\.[\d]+)'))
    async def set_probability(self, command):
        self.PROBABILITY = float(command.args.prob)
        await command.reply(f"Probability set to {self.PROBABILITY}")

    @command()
    async def show_probability(self, command):
        await command.reply("It's {0:.2%} likely that I'll refuse commands".format(self.PROBABILITY))

    @command()
    @bot_admin_required
    async def reset_probability(self, command):
        self.PROBABILITY = BASE_PROBABILITY
        await command.reply("Reset mutiny likelikehood to {0:.2%}".format(self.PROBABILITY))

    @command(pattern=re.compile(r'(?P<message>[\w\.!?,@<> ]+)'))
    async def add_mutiny_message(self, command):
        self.MESSAGES.append(command.args.message)
        await command.reply("Added `{}`".format(command.args.message))


text:
"use strict";

var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };

var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };

var BindingLanguage = exports.BindingLanguage = (function () {
  function BindingLanguage() {
    _classCallCheck(this, BindingLanguage);
  }

  _prototypeProperties(BindingLanguage, null, {
    inspectAttribute: {
      value: function inspectAttribute(resources, attrName, attrValue) {
        throw new Error("A BindingLanguage must implement inspectAttribute(...)");
      },
      writable: true,
      configurable: true
    },
    createAttributeInstruction: {
      value: function createAttributeInstruction(resources, element, info, existingInstruction) {
        throw new Error("A BindingLanguage must implement createAttributeInstruction(...)");
      },
      writable: true,
      configurable: true
    },
    parseText: {
      value: function parseText(resources, value) {
        throw new Error("A BindingLanguage must implement parseText(...)");
      },
      writable: true,
      configurable: true
    }
  });

  return BindingLanguage;
})();

Object.defineProperty(exports, "__esModule", {
  value: true
});


text:
set -e  # If occur any error, exit

function to_console {
    echo -e "\n*** $1 ***\n"
}

cd $(dirname $0) && cd ..

to_console "creating virtual env on venv folder"
virtualenv venv

to_console "Activating virtualenv"
source venv/bin/activate

to_console "Checking up dependencies"
if [ ! -z "$1" ]
    then
        to_console "Running with proxy "$1
        pip install -r venv/dev_requirements.txt --proxy=$1
    else
        to_console 'Runing with no proxy'
        pip install -r venv/dev_requirements.txt
fi

cd appengine

if [ -d lib ]; then
    rm lib
fi
to_console "Creating symlink on plugins/appengine/lib so installed libs become visible to Google App Engine"
ln -s ../venv/lib/python2.7/site-packages lib

if [ -d apps ]; then
    rm apps
fi
to_console "Creating symlink on plugins/appengine/apps so apps become visible to Google App Engine"
ln -s ../apps apps


text:
layout: kanji
v4: 1285
v6: 1379
kanji: 躍
keyword: leap
elements: leap, wooden leg, mouth, stop, footprint, futon, feathers, wings, turkey
strokes: 21
image: E8BA8D
on-yomi: ヤク
kun-yomi: おど.る
permalink: /rtk/躍/
prev: 跳
next: 践
---

1) [decamer0n] 10-5-2007(140): Well, there are weekdays weekday (#576 曜) and there are laundry days laundry (#577 濯), and on February 29th leap day, the manufacturer recommends servicing or replacing your peg leg because they tend to wear out every 4 years.

2) [pm215] 19-4-2008(120): [Story for people following katsuo in making feathers+turkey a 'futon' primitive] If you're going to leap from a high place, better hope there's a futon below -- otherwise you're going to break your leg at the very least...

3) [Katsuo] 31-8-2010(80): Tip: feathers + turkey : This combination of primitives appears six times in Heisig, so it's worthwhile giving it a name. I suggest "futon" (your futon is made from turkey feathers). REF: weekday (#576 曜) , laundry (#577 濯), leap (FRAME 1285), outstanding (#2272 擢), twinkle (#2534 燿), shimmering (#2880 耀). Story: I leap out of bed so fast that my wooden leg gets left behind in the futon.

4) [marydj] 2-11-2007(41): The turkey with a peg leg is trying to leap across the canyon. He flaps his wings wildly and feathers  fly but he doesn't make it.

5) [aircawn] 20-12-2006(30): I've always imagined a leap involving one leg instead of two, which would be a jump. Using your only good leg for propulsion, not the pegleg, you try to leap over the canyon. Even with the aid of feathers, you fly like a turkey and fall like stone. This is very Roadrunneresque.


text:
package com.sissi.pipeline;

import com.sissi.protocol.Protocol;

/**
 * @author kim 2013年12月23日
 */
public interface InputMatcher {

	public boolean match(Protocol protocol);
}


text:
layout: post
title: C++ Lecture Series
categories: blog
tags: [Coding]
author: diehlpk
---
This summer the [Stellar Group](http://stellar.cct.lsu.edu) holds a C++ Summer Lecture Series. The aim of these lectures is to provide more understanding of modern C++. Most new users of [HPX](http://stellar.cct.lsu.edu/tag/hpx/) get confused or frustrated because of a lack in understanding the new C++ features. These talk give a introduction to the new C++ features and help to understand the concept of HPX:

# Lectures

* [C++ Lecture 1 - The Standard Template Library](https://www.youtube.com/watch?v=asGZTCR53KY&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z)
* [C++ Lecture 2 - Template Programing](https://www.youtube.com/watch?v=iU3wsiJ5mts&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z&index=2)
* [C++ Lecture 3 - Modern Paralization Techniques](https://www.youtube.com/watch?v=1DUW5Qw3eck&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z&index=3)
* [C++ Lecture 4 - Template Meta Programming](https://www.youtube.com/watch?v=6PWUByLZO0g&index=4&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z)
* [C++ Lecture 5 - SFINAE ](https://www.youtube.com/watch?v=r8rH8k67AzQ&index=5&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z)
* [C++ Lecture 6 - Function Objects](https://www.youtube.com/watch?v=yZFBA7aqOec&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z&index=6)
* [C++ Lecture 7 - Function Objects and Bind](https://www.youtube.com/watch?v=kGPb0rfozak&index=7&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z)
* [C++ Lecture 8 - Calling Conventions and Move Semantics](https://www.youtube.com/watch?v=eWnl-eAX-mQ&index=8&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z)
* [C++ Lecture 9 - Forwarding References](https://www.youtube.com/watch?v=8p0CC02pYrk&index=9&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z)
* [C++ Lecture 10 - HPX and HPX Threading](https://www.youtube.com/watch?v=klr7-jBLMMI&list=PL7vEgTL3FalY2eBxud1wsfz8OKvE9sd_z&index=10)

# Literature
All source example files and the slides are available [here](https://github.com/STEllAR-GROUP/cpp_lectures_2016/tree/fdb9233301a8fa3be7fa8ce5fd1147b5cd0b1d03).

## C++ Lecture 1
* Niklaus Wirth, Algorithms + Data Structures = Programs, Prentice-Hall, 1985 [link](http://www.ethoberon.ethz.ch/WirthPubl/AD.pdf)


text:
/* global describe, expect, test */

const Maybe = require('../../src/maybe');

describe('Data.Maybe', () => {
  describe('Maybe.toValidation', () => {
    test('It should return a Success if the Maybe is Just', () => {
      const validation = Maybe.toValidation(Maybe.Just());

      expect(validation.isSuccess()).toBe(true);
    });

    test('It should return a Failure if the Maybe is Nothing', () => {
      const validation = Maybe.toValidation(Maybe.Nothing);

      expect(validation.isFailure()).toBe(true);
    });
  });

  describe('Maybe#toValidation', () => {
    test('It should return a Success if the instance is a Just', () => {
      expect(Maybe.Just.of().toValidation().isSuccess()).toBe(true);
    });

    test('It should return a Failure if the instance is a Nothing', () => {
      expect(Maybe.Nothing.of().toValidation().isFailure()).toBe(true);
    });
  });
});


text:
<?php

/**
 * Advanced_Sidebar_Menu_Widgets_Page
 *
 * Parent child menu based on pages.
 *
 * @author Mat Lipe
 * @since  7.0.0
 *
 */
class Advanced_Sidebar_Menu_Widget_Page extends Advanced_Sidebar_Menu__Widget__Widget {
	const TITLE = Advanced_Sidebar_Menu_Menus_Abstract::TITLE;
	const INCLUDE_PARENT = Advanced_Sidebar_Menu_Menus_Abstract::INCLUDE_PARENT;
	const INCLUDE_CHILDLESS_PARENT = Advanced_Sidebar_Menu_Menus_Abstract::INCLUDE_CHILDLESS_PARENT;
	const ORDER_BY = Advanced_Sidebar_Menu_Menus_Abstract::ORDER_BY;
	const USE_PLUGIN_STYLES = Advanced_Sidebar_Menu_Menus_Abstract::USE_PLUGIN_STYLES;
	const EXCLUDE = Advanced_Sidebar_Menu_Menus_Abstract::EXCLUDE;
	const DISPLAY_ALL = Advanced_Sidebar_Menu_Menus_Abstract::DISPLAY_ALL;
	const LEVELS = Advanced_Sidebar_Menu_Menus_Abstract::LEVELS;

	protected static $defaults = array(
		self::TITLE                    => false,
		self::INCLUDE_PARENT           => false,
		self::INCLUDE_CHILDLESS_PARENT => false,
		self::ORDER_BY                 => 'menu_order',
		self::USE_PLUGIN_STYLES        => false,
		self::EXCLUDE                  => false,
		self::DISPLAY_ALL              => false,
		self::LEVELS                   => 1,
	);

	protected static $hooked = false;

	public function __construct() {
		$widget_ops  = array(
			'classname'   => 'advanced-sidebar-menu',
			'description' => __( 'Creates a menu of all the pages using the child/parent relationship', 'advanced-sidebar-menu' ),
		);
		$control_ops = array(
			'width' => 620,
		);

		parent::__construct( 'advanced_sidebar_menu', __( 'Advanced Sidebar Pages Menu', 'advanced-sidebar-menu' ), $widget_ops, $control_ops );

		if ( ! self::$hooked ) {
			self::$hooked = true;
			$this->hook();
		}

	}

	protected function hook() {
		add_action( 'advanced-sidebar-menu/widget/page/left-column', array( $this, 'box_display' ), 5, 1 );
		add_action( 'advanced-sidebar-menu/widget/page/left-column', array( $this, 'box_styles' ), 10, 1 );
		add_action( 'advanced-sidebar-menu/widget/page/left-column', array( $this, 'box_order' ), 15, 1 );
		add_action( 'advanced-sidebar-menu/widget/page/left-column', array( $this, 'box_exclude' ), 20, 1 );

	}

	public function box_display( array $instance ) {
		?>

				<?php $this->checkbox( self::INCLUDE_PARENT ); ?>

					<?php esc_html_e( 'Display highest level parent page', 'advanced-sidebar-menu' ); ?>

				<?php $this->checkbox( self::INCLUDE_CHILDLESS_PARENT ); ?>

					<?php esc_html_e( 'Display menu when there is only the parent page', 'advanced-sidebar-menu' ); ?>

				<?php $this->checkbox( self::DISPLAY_ALL, self::LEVELS ); ?>

					<?php esc_html_e( 'Always display child pages', 'advanced-sidebar-menu' ); ?>

			<div
				data-js="<?php echo esc_attr( $this->get_field_id( self::LEVELS ) ); ?>"
				<?php $this->hide_element( self::DISPLAY_ALL, self::LEVELS ); ?>>

						<?php esc_html_e( 'Levels to display', 'advanced-sidebar-menu' ); ?>:
					<select
						name="<?php echo esc_attr( $this->get_field_name( self::LEVELS ) ); ?>">
						<?php
						for ( $i = 1; $i < 6; $i ++ ) {
							?>
							<option
								value="<?php echo esc_attr( $i ); ?>" <?php selected( $i, (int) $instance[ self::LEVELS ] ); ?>>
								<?php echo esc_html( $i ); ?>
							</option>

							<?php
						}
						?>
					</select>

			<?php do_action( 'advanced-sidebar-menu/widget/page/display-box', $instance, $this ); ?>

		<?php
	}

	public function box_styles( array $instance ) {
		?>

				<?php $this->checkbox( self::USE_PLUGIN_STYLES ); ?>

					<?php esc_html_e( "Use this plugin's default styling", 'advanced-sidebar-menu' ); ?>

			<?php do_action( 'advanced-sidebar-menu/widget/page/styles-box', $instance, $this ); ?>

		<?php
	}

	public function box_order( array $instance ) {
		?>

					<?php esc_html_e( 'Order by', 'advanced-sidebar-menu' ); ?>:

				<select
					id="<?php echo esc_attr( $this->get_field_id( self::ORDER_BY ) ); ?>"
					name="<?php echo esc_attr( $this->get_field_name( self::ORDER_BY ) ); ?>">
					<?php
					$order_by = (array) apply_filters( 'advanced-sidebar-menu/widget/page/order-by-options', array(
						'menu_order' => 'Page Order',
						'post_title' => 'Title',
						'post_date'  => 'Published Date',
					) );

					foreach ( $order_by as $key => $order ) {
						printf( '<option value="%s" %s>%s</option>', esc_attr( $key ), selected( $instance[ self::ORDER_BY ], $key, false ), esc_html( $order ) );
					}
					?>
				</select>

			<?php do_action( 'advanced-sidebar-menu/widget/page/order-box', $instance, $this ); ?>

		<?php
	}

	public function box_exclude( array $instance ) {
		?>

					<?php esc_html_e( 'Pages to exclude (ids), comma separated', 'advanced-sidebar-menu' ); ?>:

				<input
					id="<?php echo esc_attr( $this->get_field_id( self::EXCLUDE ) ); ?>"
					name="<?php echo esc_attr( $this->get_field_name( self::EXCLUDE ) ); ?>"
					class="widefat"
					type="text"
					value="<?php echo esc_attr( $instance[ self::EXCLUDE ] ); ?>"/>

			<?php
			do_action( 'advanced-sidebar-menu/widget/page/exclude-box', $instance, $this );
			?>

		<?php
	}

	/**
	 * Form
	 *
	 * @since 7.2.1
	 *
	 * @param array $instance
	 *
	 * @return void
	 */
	public function form( $instance ) {
		$instance = $this->set_instance( $instance, self::$defaults );
		do_action( 'advanced-sidebar-menu/widget/page/before-form', $instance, $this );
		?>

				<?php esc_html_e( 'Title', 'advanced-sidebar-menu' ); ?>:

			<input
				id="<?php echo esc_attr( $this->get_field_id( self::TITLE ) ); ?>"
				name="<?php echo esc_attr( $this->get_field_name( self::TITLE ) ); ?>"
				class="widefat"
				type="text"
				value="<?php echo esc_attr( $instance[ self::TITLE ] ); ?>"/>

			<?php
			do_action( 'advanced-sidebar-menu/widget/page/left-column', $instance, $this );
			if ( has_action( 'advanced_sidebar_menu_page_widget_form' ) ) {
				?>

					<?php do_action( 'advanced_sidebar_menu_page_widget_form', $this->get_field_id( 'parent_only' ), $this, $instance ); ?>

				<?php
			}
			?>

			<?php

			//@deprecated action
			do_action( 'advanced_sidebar_menu_after_widget_form', $instance, $this );

			do_action( 'advanced-sidebar-menu/widget/page/right-column', $instance, $this );
			?>

		<?php
		do_action( 'advanced-sidebar-menu/widget/page/after-form', $instance, $this );
	}

	/**
	 * Update
	 *
	 * @param array $new_instance
	 * @param array $old_instance
	 *
	 * @return array|mixed
	 */
	public function update( $new_instance, $old_instance ) {
		$new_instance['exclude'] = strip_tags( $new_instance['exclude'] );

		return apply_filters( 'advanced_sidebar_menu_page_widget_update', $new_instance, $old_instance );
	}

	/**
	 * Widget Output
	 *
	 * @since 7.0.0
	 *
	 * @see   \Advanced_Sidebar_Menu_Menus_Page
	 *
	 * @param array $args
	 * @param array $instance
	 *
	 * @return void
	 */
	public function widget( $args, $instance ) {
		$instance = wp_parse_args( $instance, self::$defaults );
		$asm      = Advanced_Sidebar_Menu_Menus_Page::factory( $instance, $args );

		do_action( 'advanced_sidebar_menu_widget_pre_render', $asm, $this );

		$asm->render();

	}
}