text:
import * as WebAuthnJSON from "@github/webauthn-json"
import { post } from "@rails/request.js"

async function callback(url, body) {
  const response = await post(url, { body: JSON.stringify(body) })
  if (response.ok) {
    response.json.then(result => {
      window.location.replace(result.redirect_path)
    })
  } else {
    if (response.statusCode === 422) {
      const errorMessage = document.getElementById("security-key-error-message")
      errorMessage.classList.remove("hidden")
    } else {
      console.error(response)
    }
  }
}

function create(nickname, credentialOptions) {
  WebAuthnJSON.create({ "publicKey": credentialOptions }).then(function(credential) {
    let params = { "credential": credential, "nickname": nickname }
    callback("/settings/security_keys", params)
  }).catch(function(error) {
    const errorMessage = document.getElementById("security-key-error-message")
    errorMessage.classList.remove("hidden")
    console.error(error)
  })
}

function get(credentialOptions) {
  WebAuthnJSON.get({ "publicKey": credentialOptions }).then(function(credential) {
    let params = { "user": { "credential": credential } }
    callback("login", params)
  }).catch(function(error) {
    const errorMessage = document.getElementById("security-key-error-message")
    errorMessage.classList.remove("hidden")
    console.error(error)
  })
}

export { create, get }


text:
package com.plasmaconduit.conveyance

import com.plasmaconduit.conveyance.valves.{SingleAssignmentValve, CompositeValve}

import scala.concurrent.{ExecutionContext, Future}

final case class Conduit[F, A](open: Pump[F, A] => Valve) {

  def contains(item: A): Conduit[F, Boolean] = {
    Conduit[F, Boolean]({ pump =>
      open(Pump({
        case PumpedInput(value) => if (value == item) pump.last(true) else Continue
        case PumpedError(error) => pump.error(error)
        case PumpComplete()     => pump.last(false)
      }))
    })
  }

  def defaultIfEmpty(default: A): Conduit[F, A] = {
    Conduit({ pump =>
      @volatile var found = false
      open(Pump({
        case PumpedInput(value) =>
          found = true
          pump.next(value)
        case PumpedError(error) => pump.error(error)
        case PumpComplete()     => if (!found) pump.last(default) else pump.completed()
      }))
    })
  }

  def ensure(f: => Unit): Conduit[F, A] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) => pump.next(value)
        case PumpedError(error) =>
          f
          pump.error(error)
        case PumpComplete() =>
          f
          pump.completed()
      }))
    })
  }

  def flatten[B]: Conduit[F, B] = {
    Conduit({ pump =>
      @volatile var isStopped      = false
      @volatile var index          = 0
      @volatile var step: NextStep = Continue
      val group = CompositeValve[Long]()
      val outer = SingleAssignmentValve()
      group.add(index, outer)
      outer.setValve(open(Pump({
        case PumpedInput(innerConduit) =>
          // runtime contracts ... this kind of sucks.
          require(
            innerConduit.isInstanceOf[Conduit[F, B]],
            "Attempting to flatten an unnested Conduit!"
          )
          index          += 1
          val position   = index
          val innerValve = SingleAssignmentValve()
          group.add(position, innerValve)
          // asInstanceOf ... seriously!? gross
          innerValve.setValve(innerConduit.asInstanceOf[Conduit[F, B]].open(Pump({
            case PumpedInput(value) =>
              step = pump.next(value)
              step
            case PumpedError(error) =>
              group.close()
              pump.error(error)
            case PumpComplete() =>
              group.remove(position)
              if (isStopped && group.valves.size == 1) {
                pump.completed()
              } else {
                Stop
              }
          })))
          step
        case PumpedError(error) =>
          pump.error(error)
        case PumpComplete() =>
          isStopped = true
          if (group.valves.size == 1) pump.completed() else Stop
      })))
    })
  }

  def flatMap[B](f: A => Conduit[F, B]): Conduit[F, B] = {
    map(f).flatten
  }

  def map[B](f: A => B): Conduit[F, B] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) => pump.next(f(value))
        case PumpedError(error) => pump.error(error)
        case PumpComplete()     => pump.completed()
      }))
    })
  }

  def mapError[F2](f: F => F2): Conduit[F2, A] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) => pump.next(value)
        case PumpedError(error) => pump.error(f(error))
        case PumpComplete()     => pump.completed()
      }))
    })
  }

  def foldLeft[B](m: B)(f: (B, A) => B): Conduit[F, B] = {
    @volatile var acc = m
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) =>
          acc = f(acc, value)
          Continue
        case PumpedError(error) =>
          pump.error(error)
        case PumpComplete() =>
          pump.last(acc)
      }))
    })
  }

  def concat(right: Conduit[F, A]): Conduit[F, A] = {
    Conduit({ pump =>
      val valve = CompositeValve[String]()
      valve.add("left", open(Pump[F, A]({
        case PumpedInput(value) => pump.next(value)
        case PumpedError(error) => pump.error(error)
        case PumpComplete()     =>
          valve.add("right", right.open(Pump[F, A]({
            case PumpedInput(value) => pump.next(value)
            case PumpedError(error) => pump.error(error)
            case PumpComplete()     => pump.completed()
          })))
          Stop
      })))
      valve
    })
  }

  def take(n: Int): Conduit[F, A] = {
    Conduit({ pump =>
      @volatile var o = 0
      open(Pump({
        case PumpedInput(value) =>
          o = o + 1
          if (o < n) pump.next(value) else pump.last(value)
        case PumpedError(error) =>
          pump.error(error)
        case PumpComplete() =>
          pump.completed()
      }))
    })
  }

  def drop(n: Int): Conduit[F, A] = {
    Conduit({ pump =>
      @volatile var o = 0
      open(Pump({
        case PumpedInput(value) =>
          o += 1
          if (o > n) pump.next(value) else Continue
        case PumpedError(error) =>
          pump.error(error)
        case PumpComplete() =>
          pump.completed()
      }))
    })
  }

  def elementAt(offset: Int): Conduit[F, A] = {
    Conduit({ pump =>
      @volatile var o = 0
      open(Pump({
        case PumpedInput(value) =>
          if (offset == o) {
            pump.last(value)
          } else {
            o += 1
            Continue
          }
        case PumpedError(error) =>
          pump.error(error)
        case PumpComplete() =>
          pump.completed()
      }))
    })
  }

  def elementAtOrDefault(offset: Int, default: A): Conduit[F, A] = {
    elementAt(offset).defaultIfEmpty(default)
  }

  def filter(p: A => Boolean): Conduit[F, A] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) => if (p(value)) pump.next(value) else Continue
        case PumpedError(error) => pump.error(error)
        case PumpComplete()     => pump.completed()
      }))
    })
  }

  def find(p: A => Boolean): Conduit[F, A] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) => if (p(value)) pump.last(value) else Continue
        case PumpedError(error) => pump.error(error)
        case PumpComplete()     => pump.completed()
      }))
    })
  }

  def isEmpty: Conduit[F, Boolean] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) => pump.last(false)
        case PumpedError(error) => pump.error(error)
        case PumpComplete()     => pump.last(true)
      }))
    })
  }

  def last: Conduit[F, A] = {
    Conduit({ pump =>
      @volatile var current: Option[A] = None
      open(Pump({
        case PumpedInput(value) =>
          current = Some(value)
          Continue
        case PumpedError(error) =>
          pump.error(error)
        case PumpComplete() =>
          current match {
            case None    => pump.completed()
            case Some(n) => pump.last(n)
          }
      }))
    })
  }

  def onErrorReturn(f: F => A): Conduit[F, A] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) => pump.next(value)
        case PumpedError(error) => pump.last(f(error))
        case PumpComplete()     => pump.completed()
      }))
    })
  }

  def onErrorResumeNext(f: F => Conduit[F, A]): Conduit[F, A] = {
    Conduit({ pump =>
      open(Pump({
        case PumpedInput(value) =>
          pump.next(value)
        case PumpedError(error) =>
          f(error).open(Pump({
            case PumpedInput(value)  => pump.next(value)
            case PumpedError(error2) => pump.error(error2)
            case PumpComplete()      => pump.completed()
          }))
          Stop
        case PumpComplete() =>
          pump.completed()
      }))
    })
  }

  def scan[B](init: B)(f: (B, A) => B): Conduit[F, B] = {
    Conduit({ pump =>
      @volatile var acc = init
      open(Pump({
        case PumpedInput(value) =>
          acc = f(acc, value)
          pump.next(acc)
        case PumpedError(error) =>
          pump.error(error)
        case PumpComplete() =>
          pump.completed()
      }))
    })
  }

  def toBox: Box[F, Seq[A]] = {
    Box({ conveyor =>
      foldLeft(Seq[A]())({ (m, n) => m :+ n }).open(Pump({
        case PumpedInput(value) =>
          conveyor.convey(value)
          Stop
        case PumpedError(error) =>
          conveyor.error(error)
          Stop
        case PumpComplete() =>
          Stop
      }))
    })
  }

  def headToBox: Box[F, A] = {
    Box({ conveyor =>
      open(Pump({
        case PumpedInput(value) =>
          conveyor.convey(value)
          Stop
        case PumpedError(error) =>
          conveyor.error(error)
          Stop
        case PumpComplete() =>
          Stop
      }))
    })
  }

}

object Conduit {

  def empty[F, A]: Conduit[F, A] = {
    Conduit({ pump =>
      pump.completed()
      Valve({() => })
    })
  }

  def of[F, A](n: A): Conduit[F, A] = {
    Conduit({ pump =>
      pump.next(n)
      pump.completed()
      Valve({() => })
    })
  }

  def error[F, A](f: F): Conduit[F, A] = {
    Conduit({ pump =>
      pump.error(f)
      Valve({() => })
    })
  }

  def never[F, A]: Conduit[F, A] = {
    Conduit({ pump => Valve({() => }) })
  }

  def from[F, A](i: Iterable[A]): Conduit[F, A] = {
    Conduit({ pump =>
      for (n <- i) yield pump.next(n)
      pump.completed()
      Valve({() => })
    })
  }

  def fromFuture[A](f: Future[A])(implicit ec: ExecutionContext): Conduit[Throwable, A] = {
    Conduit({ pump =>
      f.onSuccess({ case s => {
        pump.next(s)
        pump.completed()
      }})
      f.onFailure({case e => pump.error(e)})

      Valve({() => })
    })
  }

}

redpajama_set_name: RedPajamaGithub


text:
* Add Support for the 'Special Instructions'
* Testing for correct binary output

### After High Priority

* Modularize testing

### Backburner

* Make a op generator so I don't have to code each op entirely by hand.
* Add my own bit manipulation library to support auto-detection of bit_length
* Use Cython for bit manipulation
* Examples


text:
<?php defined('SYSPATH') or die('No direct access allowed.');

$lang = array
(
	'file_not_found' => 'The specified file, %s, was not found. Please verify that files exist by using file_exists() before using them.',
	'requires_GD2'   => 'The Captcha library requires GD2 with FreeType support. Please see http://php.net/gd_info for more information.',

	// Words of varying length for the Captcha_Word_Driver to pick from
	// Note: use only alphanumeric characters
	'words' => array
	(
		'cd', 'tv', 'it', 'to', 'be', 'or',
		'sun', 'car', 'dog', 'bed', 'kid', 'egg',
		'bike', 'tree', 'bath', 'roof', 'road', 'hair',
		'hello', 'world', 'earth', 'beard', 'chess', 'water',
		'barber', 'bakery', 'banana', 'market', 'purple', 'writer',
		'america', 'release', 'playing', 'working', 'foreign', 'general',
		'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling',
		'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders',
	),

	// Riddles for the Captcha_Riddle_Driver to pick from
	// Note: use only alphanumeric characters
	'riddles' => array
	(
		array('Do you hate spam? (yes or no)', 'yes'),
		array('Are you a robot? (yes or no)', 'no'),
		array('Fire is... (hot or cold)', 'hot'),
		array('The season after fall is...', 'winter'),
		array('Which day of the week is it today?', strftime('%A')),
		array('Which month of the year are we in?', strftime('%B')),
	),
);


text:
<?php namespace Fungku\NetSuite\Classes;

class ContactCategory extends Record {
	public $name;
	public $private;
	public $sync;
	public $isInactive;
	public $internalId;
	public $externalId;
	static $paramtypesmap = array(
		"name" => "string",
		"private" => "boolean",
		"sync" => "boolean",
		"isInactive" => "boolean",
		"internalId" => "string",
		"externalId" => "string",
	);
}


text:
STARTING_PORT = 6000

# attempt to import production settings, so they can overwrite dev options
try:
    from .local_settings import *
except ImportError:
    pass


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HL7Parser
{
    public interface IEntity
    {
        string EntityName { get; set;}
    }
}


text:
package com.yuzhou.rss.ui;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yuzhou.rss.R;
import com.yuzhou.rss.parser.RssItem;

import java.io.InputStream;
import java.net.URL;

/**
 * Created by yuzhou on 2015/09/02.
 */
public class ItemFragment extends Fragment implements Html.ImageGetter
{

    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static ItemFragment newInstance(RssItem item)
    {
        ItemFragment f = new ItemFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putParcelable("rss_item", item);
        f.setArguments(args);

        return f;
    }

    private RssItem rssItem;
    private TextView tvContent;

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        rssItem = getArguments().getParcelable("rss_item");
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.fragment_item_list, container, false);
        TextView title = (TextView) v.findViewById(R.id.article__title);
        tvContent = (TextView) v.findViewById(R.id.article__content);

        title.setText(rssItem.getTitle());
        Spanned spanned = Html.fromHtml(rssItem.getContent(), this, null);
        tvContent.setText(spanned);

        return v;
    }

    @Override
    public Drawable getDrawable(String source)
    {
        LevelListDrawable d = new LevelListDrawable();
        Drawable empty = getResources().getDrawable(R.color.white);
        d.addLevel(0, 0, empty);
        d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());

        new LoadImage().execute(source, d);
        return d;
    }

    class LoadImage extends AsyncTask<Object, Void, Bitmap>
    {
        private LevelListDrawable mDrawable;

        @Override
        protected Bitmap doInBackground(Object... params)
        {
            String source = (String) params[0];
            mDrawable = (LevelListDrawable) params[1];
            try {
                InputStream is = new URL(source).openStream();
                return BitmapFactory.decodeStream(is);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap)
        {
            if (bitmap != null) {
                BitmapDrawable d = new BitmapDrawable(bitmap);
                mDrawable.addLevel(1, 1, d);
                mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                mDrawable.setLevel(1);
                CharSequence t = tvContent.getText();
                tvContent.setText(t);
            }
        }
    }

}


text:
import Component from '@ember/component';
import Analytics from 'ember-osf/mixins/analytics';
/**
 * @module ember-preprints
 * @submodule components
 */

/**
 * Confirm remove self component
 *
 * Requires user to confirm they wish to remove
 * themselves from the preprint
 *
 * Sample usage:
 * ```handlebars
 * {{confirm-remove-self
 *  isOpen=showModalSharePreprint
 *  shareButtonDisabled=shareButtonDisabled
 *  savePreprint=(action 'savePreprint')
 *  title=title
 *  buttonLabel=buttonLabel
 *}}
 * ```
 * @class confirm-share-preprint
 */
export default Component.extend(Analytics, {
    isOpen: false,
    actions: {
        close() {
            this.get('metrics')
                .trackEvent({
                    category: 'button',
                    action: 'click',
                    label: 'Edit - Close remove self modal',
                });
            this.set('isOpen', false);
        },
    },
});


text:
package org.pathvisio.libgpml.util;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import junit.framework.TestCase;

/**
 * Tests for ColorUtils class.
 *
 * @author finterly
 */
public class TestColorUtils extends TestCase {

	public void testHexToColorToHex() {
		// hex strings tests
		List<String> hexTests = new ArrayList<String>(Arrays.asList("#b4b46419", "#00000000", "#ffffff"));
		// color object equivalent of hex string tests
		List<Color> colorTests = new ArrayList<Color>(
				Arrays.asList(new Color(180, 180, 100, 25), new Color(0, 0, 0, 0),new Color(255, 255, 255, 255)));
		for (int i = 0; i < hexTests.size(); i++) {
			// convert hex string to color object
			Color color = ColorUtils.hexToColor(hexTests.get(i));
			// assert converted color object is equivalent to control color
			assertEquals(color.getRed(), colorTests.get(i).getRed());
			assertEquals(color.getGreen(), colorTests.get(i).getGreen());
			assertEquals(color.getBlue(), colorTests.get(i).getBlue());
			assertEquals(color.getAlpha(), colorTests.get(i).getAlpha());
			//convert color back to hex string
			String hex = ColorUtils.colorToHex(color, true);
			// assert hex string returned is the same
			assertEquals(hex, hexTests.get(i));

		}
	}

	public void testStringToColor() {
		// strings tests
		List<String> strTests = new ArrayList<String>(Arrays.asList("white", "Transparent", "blue"));
		// color object equivalent of hex string tests
		List<Color> colorTests = new ArrayList<Color>(
				Arrays.asList(new Color(255, 255, 255, 255), new Color(0, 0, 0, 0),new Color(0, 0, 255, 255)));
		for (int i = 0; i < strTests.size(); i++) {
			// convert hex string to color object
			Color color = ColorUtils.stringToColor(strTests.get(i));
			// assert converted color object is equivalent to control color
			assertEquals(color.getRed(), colorTests.get(i).getRed());
			assertEquals(color.getGreen(), colorTests.get(i).getGreen());
			assertEquals(color.getBlue(), colorTests.get(i).getBlue());
			assertEquals(color.getAlpha(), colorTests.get(i).getAlpha());
		}
	}

	public void testTransparency() {
		Color color = ColorUtils.hexToColor("00000000");
		Color color2 = ColorUtils.hexToColor("ffffff00");
		assertTrue(ColorUtils.isTransparent(color));
		assertTrue(ColorUtils.isTransparent(color2));
	}

}


text:
namespace maestropanel.plesklib.Models
{
    using System.Xml.Serialization;

    [XmlRoot("packet")]
    public class SiteGetPacket
    {
        public SiteGetPacket()
        {
            this.site = new SiteGetSiteNode();
        }

        [XmlElement("site")]
        public SiteGetSiteNode site { get; set; }
    }

    public class SiteGetSiteNode
    {
        public SiteGetSiteNode()
        {
            this.get = new SiteGetNode();
        }

        [XmlElement("get")]
        public SiteGetNode get { get; set; }
    }

    public class SiteGetNode
    {

        public SiteGetNode()
        {
            this.filter = new SiteGetFilterNode();
            this.dataset = new SiteGetDataSetNode();
        }

        [XmlElement("filter")]
        public SiteGetFilterNode filter { get; set; }

        [XmlElement("dataset")]
        public SiteGetDataSetNode dataset { get; set; }
    }

    public class SiteGetFilterNode
    {
        [XmlElement("name")]
        public string Name { get; set; }
    }

    public class SiteGetDataSetNode
    {
        public SiteGetDataSetNode()
        {
            this.Hosting = new SiteGetDataSetHostingNode();
        }

        [XmlElement("hosting")]
        public SiteGetDataSetHostingNode Hosting { get; set; }
    }

    public class SiteGetDataSetHostingNode
    {

    }

}


text:
#include "py/mpconfig.h"

#if MICROPY_MBFS && BLUETOOTH_SD

#include "drivers/flash.h"
#include "drivers/bluetooth/ble_drv.h"
#include "nrf_soc.h"

// Rotates bits in `value` left `shift` times.
STATIC inline uint32_t rotate_left(uint32_t value, uint32_t shift) {
    return (value << shift) | (value >> (32 - shift));
}

STATIC volatile flash_state_t flash_operation_state = FLASH_STATE_BUSY;

STATIC void operation_init() {
    flash_operation_state = FLASH_STATE_BUSY;
}

void flash_operation_finished(flash_state_t result) {
    flash_operation_state = result;
}

STATIC bool operation_wait(uint32_t result) {
    if (ble_drv_stack_enabled() != 1) {
        // SoftDevice is not enabled, no event will be generated.
        return result == NRF_SUCCESS;
    }

    if (result != NRF_SUCCESS) {
        // In all other (non-success) cases, the command hasn't been
        // started and no event will be generated.
        return false;
    }

    // Wait until the event has been generated.
    while (flash_operation_state == FLASH_STATE_BUSY) {
        sd_app_evt_wait();
    }

    // Now we can safely continue, flash operation has completed.
    return flash_operation_state == FLASH_STATE_SUCCESS;
}

void flash_write_byte(uint32_t address, uint8_t b) {
    uint32_t address_aligned = address & ~3;

    // Value to write - leave all bits that should not change at 0xff.
    uint32_t value = 0xffffff00 | b;

    // Rotate bits in value to an aligned position.
    value = rotate_left(value, (address & 3) * 8);

    while (1) {
        operation_init();
        uint32_t result = sd_flash_write((uint32_t*)address_aligned, &value, 1);
        if (operation_wait(result)) break;
    }
}

void flash_page_erase(uint32_t pageaddr) {
    while (1) {
        operation_init();
        uint32_t result = sd_flash_page_erase(pageaddr / FLASH_PAGESIZE);
        if (operation_wait(result)) break;
    }
}

void flash_write_bytes(uint32_t dst, const uint8_t *src, uint32_t num_bytes) {
    const uint8_t *src_end = src + num_bytes;

    // sd_flash_write does not accept unaligned addresses so we have to
    // work around that by writing all unaligned addresses byte-by-byte.

    // Write first bytes to align the write address.
    while (src != src_end && (dst & 0b11)) {
        flash_write_byte(dst, *src);
        dst++;
        src++;
    }

    // Write as many words as possible.
    // dst is now aligned, src possibly not.
    while (src_end - src >= 4) {
        uint8_t buf[4] __attribute__((aligned(4)));
        for (int i = 0; i < 4; i++) {
            buf[i] = ((uint8_t*)src)[i];
        }
        operation_init();
        uint32_t result = sd_flash_write((uint32_t*)dst, (const uint32_t*)&buf, 1);
        if (operation_wait(result)) {
            // If it is successfully written, go to the next word.
            src += 4;
            dst += 4;
        }
    }

    // Write remaining unaligned bytes.
    while (src != src_end) {
        flash_write_byte(dst, *src);
        dst++;
        src++;
    }
}

#endif // MICROPY_MBFS


text:
package org.nutz.dao;

import java.sql.Connection;

public interface ConnCallback {

    void invoke(Connection conn) throws Exception;

}


text:
/**
 * Event table -- add new_event_type, class_id, exam_id columns (and appropriate foreign keys)
 */

alter table event add class_id number(20,0);
alter table event add exam_id number(20,0);
alter table event add new_event_type number(10,0);
alter table event add req_attd number(1,0);

alter table event
  add constraint fk_event_class foreign key (class_id)
  references class_ (uniqueid) on delete cascade;

 alter table event
  add constraint fk_event_exam foreign key (exam_id)
  references exam (uniqueid) on delete cascade;

/**
 * Populate new_event_type
 **/

update event e set e.new_event_type = 0 where e.event_type = (select t.uniqueid from event_type t where t.reference = 'class');
update event e set e.new_event_type = 1 where e.event_type = (select t.uniqueid from event_type t where t.reference = 'final');
update event e set e.new_event_type = 2 where e.event_type = (select t.uniqueid from event_type t where t.reference = 'evening');
update event e set e.new_event_type = 3, e.req_attd=1 where e.event_type = (select t.uniqueid from event_type t where t.reference = 'otherWithConflict');
update event e set e.new_event_type = 3, e.req_attd=0 where e.event_type = (select t.uniqueid from event_type t where t.reference = 'otherNoConflict');
update event e set e.new_event_type = 4 where e.event_type = (select t.uniqueid from event_type t where t.reference = 'special');

/**
 * Swap new_event_type for event_type and drop event_type table
 **/

alter table event drop constraint fk_event_event_type;
alter table event drop column event_type;
alter table event rename column new_event_type to event_type;
alter table event add constraint nn_event_type check (event_type is not null);
alter table meeting drop constraint fk_meeting_event_type;
alter table meeting drop column event_type;
drop table event_type;

/**
 * Populate exam id for examination events
 **/

update event e set e.exam_id = (select x.uniqueid from exam x where x.event_id=e.uniqueid) where e.event_type in (1, 2);
update event e set e.class_id = (select a.class_id from assignment a where a.event_id=e.uniqueid) where e.event_type = 0;

/**
 * Delete redundant related course info
 **/

delete from related_course_info where event_id in (select e.uniqueid from event e where e.event_type != 3);

/**
 * Delete event_id from exams and assignments
 **/

alter table assignment drop constraint fk_assignment_event;
alter table assignment drop column event_id;
alter table exam drop constraint fk_exam_event;
alter table exam drop column event_id;

/*
 * Update database version
 */

update application_config set value='26' where name='tmtbl.db.version';

commit;


text:
<?php

namespace Slick\Di\Exception;

use LogicException;
use Slick\Di\Exception;

/**
 * InvalidArgumentException
 *
 * @package   Slick\Di\Exception
 * @author    Filipe Silva <silvam.filipe@gmail.com>
 */
class InvalidArgumentException extends LogicException implements Exception
{

}


text:
namespace DentistSpace.Services.Contracts
{
    using System.Linq;
    using DentistSpace.Data.Models;

    public interface IDentistService
    {
        IQueryable<Dentist> GetDentists(string filter);

        Dentist GetDentistById(string dentistId);
    }
}


text:
import deepFreeze from 'deep-freeze';
import getFlaws from './getFlaws';

it('should return correct values for flaws', () => {
  const state = {
    character: {
      merits: [
        {
          name: 'Calm Heart',
          points: 1
        }
      ],
      flaws: [
        {
          name: 'Bad Sight',
          points: 2
        },
        {
          name: 'Blood Rot',
          points: 5
        }
      ]
    }
  };

  deepFreeze(state);

  const result = getFlaws(state);

  expect(result).toEqual({
    selected: state.character.flaws,
    currentPoints: 7,
    availablePoints: 0
  });
});


text:
function AppPreferencesLocalStorage() {

}

AppPreferencesLocalStorage.prototype.fetch = function(successCallback, errorCallback, dict, key) {

	var self = this;

	var args = this.prepareKey ('get', dict, key);

	if (!args.key) {
		errorCallback ();
		return;
	}

	var key = args.key;

	if (args.dict)
		key = args.dict + '.' + args.key;

	var result = window.localStorage.getItem (key);

	var value = result;
	if (result) {
		try {
			value = JSON.parse (result);
		} catch (e) {
		}
		successCallback (value);
	} else {
		errorCallback();
	}
};

AppPreferencesLocalStorage.prototype.store = function(successCallback, errorCallback, dict, key, value) {

	var self = this;

	var args = this.prepareKey ('set', dict, key, value);

	if (!args.key || args.value === null || args.value === undefined) {
		errorCallback ();
		return;
	}

	var key = args.key;

	if (args.dict)
		key = args.dict + '.' + args.key;

	var value = JSON.stringify (args.value);

	window.localStorage.setItem (key, value);

	successCallback ();
};

module.exports = new AppPreferencesLocalStorage();


text:
package unity

import (
	"bufio"
	"regexp"

	"github.com/fatih/color"
)

const (
	REMOTE_ASSET_CACHE_MATCHER = `RemoteAssetCache\s-\s.*\s-\ssuccess:(true|false),\s.*key:([a-zA-Z0-9]+)\s.*extension:'(.*)',\stime\selapsed:\s(.*)\sseconds`
)

type RemoteAssetCacheParser struct {
	color   *color.Color
	matcher *regexp.Regexp
}

func NewRemoteAssetCacheParser() *RemoteAssetCacheParser {
	white := color.New(color.FgWhite)
	return &RemoteAssetCacheParser{
		color:   white,
		matcher: regexp.MustCompile(REMOTE_ASSET_CACHE_MATCHER),
	}
}

func (parser *RemoteAssetCacheParser) Match(line string, reader *bufio.Reader) bool {

	if match := parser.matcher.FindStringSubmatch(line); len(match) > 0 {
		parser.color.Printf("%s %s %s success: %s\n", match[2], match[3], match[4], match[1])
		return true
	}

	return false
}


text:
using System;
using Server;
using Server.Items;

namespace Server.Mobiles
{
	[CorpseName( "a ghostly corpse" )]
	public class Bogle : BaseCreature
	{
		[Constructable]
		public Bogle() : base( AIType.AI_Mage, FightMode.Closest, 10, 1, 0.2, 0.4 )
		{
			Name = "a bogle";
			Body = 153;
			BaseSoundID = 0x482;

			SetStr( 76, 100 );
			SetDex( 76, 95 );
			SetInt( 36, 60 );

			SetHits( 46, 60 );

			SetDamage( 7, 11 );

			SetSkill( SkillName.EvalInt, 55.1, 70.0 );
			SetSkill( SkillName.Magery, 55.1, 70.0 );
			SetSkill( SkillName.MagicResist, 55.1, 70.0 );
			SetSkill( SkillName.Tactics, 45.1, 60.0 );
			SetSkill( SkillName.Wrestling, 45.1, 55.0 );

			Fame = 4000;
			Karma = -4000;

			VirtualArmor = 28;
			PackItem( Loot.RandomWeapon() );
			PackItem( new Bone() );
		}

		public override void GenerateLoot()
		{
			AddLoot( LootPack.Meager );
		}

		public override bool BleedImmune{ get{ return true; } }
		public override Poison PoisonImmune{ get{ return Poison.Lethal; } }

		public Bogle( Serial serial ) : base( serial )
		{
		}

		public override OppositionGroup OppositionGroup
		{
			get{ return OppositionGroup.FeyAndUndead; }
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );
			writer.Write( (int) 0 );
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );
			int version = reader.ReadInt();
		}
	}
}


text:
"use strict";

module.exports = require("./_strict")(require("./common"));


text:
---
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

# WebViews в Android

В этом руководстве показано, как встраивать компонент Cordova WebView в рамках более крупных приложений Android. Дополнительные сведения о том, как эти компоненты могут взаимодействовать друг с другом смотрите раздел "Расширения приложения".

Если вы не знакомы с Android, следует сначала ознакомиться с "Руководство для платформы Android" и установить последнюю версию Android перед тем как пробовать делать не обычное встраивание WebView в ваше приложение. Начиная с Cordova 1.9, платформа Android опирается на компонент `CordovaWebView`, который построен на устаревшем компоненте `CordovaActivity`, который был до версии 1.9.

1.  Следуя этим инструкциям, убедитесь, что у вас есть дистрибутив последней версии Cordova. Скачайте его с [cordova.apache.org][1] и распакуйте пакет для Android.

2.  Перейдите в каталог `/framework` пакета Android и запустить `ant jar` . Это создаёт `.jar` файл Cordova, вида `/framework/cordova-x.x.x.jar`.

3.  Скопируйте файл `.jar` в каталог `/libs` Android-проекта.

4.  Добавьте в приложение следующий файл `/res/xml/main.xml`, с `layout_height`, `layout_width` и `id` модицифированными в соответствии с нуждами приложения:

        <org.apache.cordova.CordovaWebView
            android:id="@+id/tutorialView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

5.  Измените вашу деятельность так, чтобы этот класс реализовал `CordovaInterface`. Вы должны реализовать описанные методы этого интерфейса. Вы можете скопировать их из `/framework/src/org/apache/cordova/CordovaActivity.java`, или реализовать их самостоятельно. В следующем фрагменте кода показано простое приложение, которое опирается на интерфейс. Обратите внимание, что id упоминаемого окна соответствует `id` атрибут, указанный в XML-фрагменте показаном выше:

        public class CordovaViewTestActivity extends Activity implements CordovaInterface {
            CordovaWebView cwv;
            /* Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                cwv = (CordovaWebView) findViewById(R.id.tutorialView);
                Config.init(this);
                cwv.loadUrl(Config.getStartUrl());
            }

6.  Если приложение должно использовать камеру, реализуйте следующее:

        @Override
        public void setActivityResultCallback(CordovaPlugin plugin) {
            this.activityResultCallback = plugin;
        }
        /**
         * Launch an activity for which you would like a result when it finished. When this activity exits,
         * your onActivityResult() method is called.
         *
         * @param command           The command object
         * @param intent            The intent to start
         * @param requestCode       The request code that is passed to callback to identify the activity
         */
        public void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode) {
            this.activityResultCallback = command;
            this.activityResultKeepRunning = this.keepRunning;

            // If multitasking turned on, then disable it for activities that return results
            if (command != null) {
                this.keepRunning = false;
            }

            // Start activity
            super.startActivityForResult(intent, requestCode);
        }

        @Override
        /**
         * Called when an activity you launched exits, giving you the requestCode you started it with,
         * the resultCode it returned, and any additional data from it.
         *
         * @param requestCode       The request code originally supplied to startActivityForResult(),
         *                          allowing you to identify who this result came from.
         * @param resultCode        The integer result code returned by the child activity through its setResult().
         * @param data              An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
         */
        protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
            super.onActivityResult(requestCode, resultCode, intent);
            CordovaPlugin callback = this.activityResultCallback;
            if (callback != null) {
                callback.onActivityResult(requestCode, resultCode, intent);
            }
        }

7.  Наконец, не забудьте добавить пул потоков, иначе у плагинов не будет потоков, на которых они будет выполняться:

        @Override
        public ExecutorService getThreadPool() {
            return threadPool;
        }

8.  Скопируйте файлы HTML и JavaScript приложения в каталог `/assets/www` проекта Android.

9.  Скопируйте `config.xml` файл из `/framework/res/xml` в каталог `/res/xml` проекта.

 [1]: http://cordova.apache.org