text:
RSpec.describe WTT do

  describe 'active protection' do
    it 'provides a helper function to set an env variable flag' do
      WTT.active=true
      expect(WTT.active?).to eq true
      expect(ENV[WTT::ENV_ACTIVE_FLAG]).to eq '1'

      WTT.active=false
      expect(WTT.active?).to eq false
      expect(ENV[WTT::ENV_ACTIVE_FLAG]).to be_nil
    end

    it 'provides a helper function to set an env variable flag for a block' do
      WTT.with_active_env do
        expect(WTT.active?).to eq true
        expect(ENV[WTT::ENV_ACTIVE_FLAG]).to eq '1'
      end
      WTT.active=false
      expect(WTT.active?).to eq false
      expect(ENV[WTT::ENV_ACTIVE_FLAG]).to be_nil
    end
  end

  describe 'reject filters' do
    it 'has default filters' do
      WTT.configure
      expect(WTT.configuration.reject_filters.count).to_not eq 0
    end

    it 'allows you to add filters' do
      WTT.configure do |config|
        config.use_default_filters = false
        config.add_reject_filter 'fake_filter'
      end
      expect(WTT.configuration.reject_filters.last).to eq 'fake_filter'
    end
  end

  describe 'remote coverage' do
    it 'can start/stop a coverage service' do
      WTT.configure do |config|
        config.traced_port = 4242
      end

      WTT.start_service
      expect(WTT.trace_service).to_not be_nil

      service = DRbObject.new_with_uri('druby://localhost:4242')

      expect{service.coverage}.to_not raise_error

      WTT.stop_service
      service = DRbObject.new_with_uri('druby://localhost:4242')
      expect{service.coverage}.to raise_error
    end

    it 'allows you to add filters' do
      WTT.configure do |config|
        config.add_reject_filter 'fake_filter'
      end
      expect(WTT.configuration.reject_filters.last).to eq 'fake_filter'
    end

    it 'allows you to add remove coverage services' do
      WTT.configure do |config|
        config.add_remote 'druby://fake_remote'
      end
      expect(WTT.configuration.remotes.last).to eq 'druby://fake_remote'
    end

    it 'adds the protocol prefix to remotes if missing' do
      WTT.configure do |config|
        config.add_remote 'fake_remote'
      end
      expect(WTT.configuration.remotes.last).to eq 'druby://fake_remote'
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import

import os
import fs.utils
import fs.path
from fs.osfs import OSFS

class DataService(object):

    def __init__(self, fs):
        self.fs = fs

    def __repr__(self):
        return "<{}:{} object at {}>".format(
            self.__class__.__name__, self.fs.__class__.__name__, hex(id(self)))

    def upload(self, filepath, service_path, remove=False):
        '''
        "Upload" a file to a service

        This copies a file from the local filesystem into the ``DataService``'s
        filesystem. If ``remove==True``, the file is moved rather than copied.

        If ``filepath`` and ``service_path`` paths are the same, ``upload``
        deletes the file if ``remove==True`` and returns.

        Parameters
        ----------
        filepath : str
            Relative or absolute path to the file to be uploaded on the user's
            filesystem

        service_path: str
            Path to the destination for the file on the ``DataService``'s
            filesystem

        remove : bool
            If true, the file is moved rather than copied
        '''

        local = OSFS(os.path.dirname(filepath))

        # Skip if source and dest are the same
        if self.fs.hassyspath(service_path) and (
            self.fs.getsyspath(service_path) == local.getsyspath(
                os.path.basename(filepath))):

            if remove:
                os.remove(filepath)

            return

        if not self.fs.isdir(fs.path.dirname(service_path)):
            self.fs.makedir(
                fs.path.dirname(service_path),
                recursive=True,
                allow_recreate=True)

        if remove:
            fs.utils.movefile(
                local,
                os.path.basename(filepath),
                self.fs,
                service_path)

        else:
            fs.utils.copyfile(
                local,
                os.path.basename(filepath),
                self.fs,
                service_path)


text:
package qrt

import (
	"sort"
)

// MysqlQrtBucket : https://www.percona.com/doc/percona-server/5.6/diagnostics/response_time_distribution.html
// Represents a row from information_schema.Query_Response_Time
type MysqlQrtBucket struct {
	time  float64
	count int64
	total float64
}

// MysqlQrtHistogram represents a histogram containing MySQLQRTBuckets. Where each bucket is a bin.
type MysqlQrtHistogram []MysqlQrtBucket

// NewMysqlQrtBucket Public way to return a QRT bucket to be appended to a Histogram
func NewMysqlQrtBucket(time float64, count int64, total float64) MysqlQrtBucket {
	return MysqlQrtBucket{time, count, total}
}

// Sort for QRT Histogram
func (h MysqlQrtHistogram) Len() int      { return len(h) }
func (h MysqlQrtHistogram) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h MysqlQrtHistogram) Less(i, j int) bool {
	return h[i].time < h[j].time
}

// Count for QRT Histogram
func (h MysqlQrtHistogram) Count() int64 {
	var total int64
	total = 0

	for _, v := range h {
		total += v.count
	}

	return total
}

// Percentile for QRTHistogram
// p should be p/100 where p is requested percentile (example: 0.10 for 10th percentile)
// Percentile is defined as the weighted of the percentiles of
// lowest bin that is greater than the requested percentile rank
func (h MysqlQrtHistogram) Percentile(p float64) float64 {
	var r float64
	var curPctl int64
	var pctl float64

	// Order all of the values in the data set in ascending order (least to greatest).
	sort.Sort(MysqlQrtHistogram(h))

	// Rank = N * P
	r = float64(h.Count()) * p

	// Find the tgt percentile, make it an average because using histogram buckets
	for i, v := range h {
		curPctl += v.count
		if float64(curPctl) >= r {
			pctl = h[i].total / float64(h[i].count)
			break
		}
	}

	return pctl
}


text:
<!-- Copyright 2015 Braden Farmer

     Licensed 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.
-->

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <CheckBoxPreference
        android:defaultValue="false"
        android:key="hide_notification"
        android:title="@string/pref_title_hide_notification" />

    <ListPreference
        android:defaultValue="turn-off"
        android:entries="@array/pref_notification_action_list"
        android:entryValues="@array/pref_notification_action_list_values"
        android:key="notification_action_2"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"
        android:title="@string/pref_title_notification_action_2" />

    <ListPreference
        android:defaultValue="lock-device"
        android:entries="@array/pref_notification_action_list"
        android:entryValues="@array/pref_notification_action_list_values"
        android:key="notification_action"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"
        android:title="@string/pref_title_notification_action" />

    <Preference
        android:key="system_notification_settings"
        android:title="@string/system_notification_settings" >
    </Preference>

</PreferenceScreen>


text:
To add the `apollo-coroutines-support` module to your project, first add the following dependency to your gradle file

```groovy
implementation "com.apollographql.apollo3:apollo-coroutines-support:$apollo_version"
```


text:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * The Class StreamReaderThread. This is used to poll the streams of
 * the subprocess
 */
public class StreamReaderThread extends Thread {

  /** The input stream. */
  private InputStream inputStream;

  /**
   * Instantiates a new stream reader thread.
   *
   * @param inputStream: the stream
   */
  public StreamReaderThread(InputStream inputStream) {
    this.inputStream = inputStream;
  }

  /**
   * Entry Point of the thread to run
   */
  public void run() {
    try {
      BufferedReader bufferedReader =
          new BufferedReader(new InputStreamReader(inputStream));

      // Keep reading output of any input stream so that stream stays
      // empty for other process and thus prevents deadlock situations

      while (bufferedReader.readLine() != null) {}
    } catch (Exception e) {}
  }
}


text:
import time
from collections import defaultdict

import pandas as pd
from rnaseq_lib.utils import rexpando
from rnaseq_lib.web import _rget
from rnaseq_lib.tissues import grep_cancer_terms

def query_drug(drug):
    """
    Search OpenFDA drug label API by name

    :param str drug: Drug to query by
    :return: Response containing first match
    :rtype: requests.models.Response
    """
    # Clean input
    drug = drug.lower()

    # Look for drug label on openFDA
    for d in [drug, drug.capitalize(), drug.upper()]:
        for name in ['generic_name', 'brand_name']:
            url = 'https://api.fda.gov/drug/label.json?search=openfda.{}:{}&limit=1'.format(name, d)
            time.sleep(0.1)
            r = _rget(url)
            if r:
                return r
    return None

def drugs_by_query(query, limit=100, field='indications_and_usage'):
    """
    Search OpenFDA API for drugs that match query

    :param str query: Query string to search by
    :param int limit: Limit request, cannot be higher than 100
    :param str field: OpenFDA field to search. Example: "openfda.brand_name"
    :return: Return drugs by query term
    :rtype: list(tuple(str, str))
    """
    assert limit <= 100, 'OpenFDA API does not allow a limit higher than 100'
    url = 'https://api.fda.gov/drug/label.json?search={}:{}&limit={}'.format(field, query, limit)
    r = _rget(url)
    if r:
        # Convert to JSON
        r = r.json()

        # Get total number of hits
        total_terms = r['meta']['results']['total']
        print 'Found a total of {} terms'.format(total_terms)

        # Collect first batch
        drugs = [(','.join(x['openfda']['brand_name']), ','.join(x['openfda']['generic_name']))
                 for x in r['results']]

        # Collect results in batches
        skip = limit
        for _ in xrange(int(total_terms) / limit):
            time.sleep(1)
            print 'Collecting samples {} - {}'.format(skip, skip + limit)
            r = _rget(url + '&skip={}'.format(skip))
            if r:
                r = r.json()
                drugs.extend([(','.join(x['openfda']['brand_name']), ','.join(x['openfda']['generic_name']))
                              for x in r['results']])
                skip += limit
        return drugs
    else:
        return None

def drugs_to_dataframe(drugs):
    """
    Convert a list of drugs to an OpenFDA DataFrame

    :param list(str) drugs:
    :return: DataFrame of OpenFDA information
    """
    # Create dictionary to store table info
    info = defaultdict(list)

    # For each drug, query openFDA
    for drug in drugs:
        drug = drug.lower()
        r = query_drug(drug)
        if r:
            hits = rexpando(r.json()).results

            # If more than one hit is returned, find exact match
            if len(hits) != 1:
                for h in hits:
                    if drug in h.openfda.brand_name.lower() or drug in h.openfda.generic_name.lower():
                        res = h
            else:
                res = hits[0]

            # Collect info if description references cancer
            if 'indications_and_usage' in res:
                usage = res.indications_and_usage[0] if type(
                    res.indications_and_usage) is list else res.indications_and_usage
                if [x for x in usage.replace('\n', '.').split('.') if 'cancer' in x]:

                    # Get generic name
                    try:
                        info['generic_name'].append(str(res.openfda.generic_name).strip("u'[]"))
                    except AttributeError:
                        info['generic_name'].append(None)

                    # Get brand name
                    try:
                        info['brand_name'].append(str(res.openfda.brand_name).strip("u'[]"))
                    except AttributeError:
                        info['brand_name'].append(None)

                    # Get usage
                    try:
                        info['usage'].append(str(res.indications_and_usage).strip('[]'))
                    except AttributeError:
                        info['usage'].append(None)

                    # Get mechanism of action
                    try:
                        info['mech_action'].append(str(res.mechanism_of_action).strip('[]'))
                    except AttributeError:
                        try:
                            info['mech_action'].append(str(res.clinical_pharmacology).strip('[]'))
                        except AttributeError:
                            info['mech_action'].append(None)

    return pd.DataFrame.from_dict(info)

def indications_and_usage(drug):
    """
    Returns indications and usage, split by cancer terms

    :param str drug: Name of drug
    :return: Indications and usage split by cancer terms
    :rtype: str
    """
    r = query_drug(drug)
    if not r:
        print 'No drug found'
        return None

    return '\n\n'.join(grep_cancer_terms(str(rexpando(
        r.json()['results'][0])['indications_and_usage'])))


text:
import React, { Component } from 'react';
import Link from 'next/link';
import Head from 'next/head';
import axios from 'axios';
import { filter, map, sortBy } from 'lodash';
import Router from 'next/router';
import moment from 'moment';
import { nextConnect } from '../store';
import { FETCH_EVENTS } from '../actions/types';
import { getVenue, getArtists, BASE_URL, IMAGE_URL } from '../actions';
import HeaderSocial from '../components/HeaderSocial';
import HeaderNav from '../components/HeaderNav';
import HeaderLogin from '../components/HeaderLogin';
import BottomMenu from '../components/Home/BottomMenu';
import BottomLatestNews from '../components/Home/BottomLatestNews';
import Footer from '../components/Footer';
import { buildUrl } from '../helpers';

class Show extends Component {
  static async getInitialProps({ req, store }) {
    if (req) {
      const response = await axios.get(`${BASE_URL}/events`);
      store.dispatch({
        type: FETCH_EVENTS,
        payload: response.data.events,
      });
      const show = filter(response.data.events, (event) => event.id === req.params.id);

      return { show };
    }
    return {};
  }

  constructor(props) {
    super(props);
    this.state = { show: null, address: {}, artists: [], artist: '' };
    this.onSubmit = this.onSubmit.bind(this);
  }

  componentWillMount() {
    if (!this.props.show) {
      let id = decodeURI(Router.router.as);
      id = id.split('/')[2];
      const show = filter(this.props.events, (event) => event.id === id);
      this.setState({ show });
    }
  }

  componentDidMount() {
    const show = this.state.show || this.props.show;
    getVenue(show[0].venue_id, (address) => {
      this.setState({ address });
    });

    getArtists(show[0].id, (artists) => {
      this.setState({ artists });
    });
  }

  onSubmit(e) {
    e.preventDefault();
    const artist = this.state.artist;
    const show = this.state.show || this.props.show;
    let url = show[0].url;
    url = buildUrl(url, artist);
    location.href = url;
  }

  render() {
    const show = this.state.show || this.props.show;
    const sortedArtists = sortBy(this.state.artists, 'full_name');

    return (

          <title>Shows - Conception arts</title>
          <meta name="viewport" content="initial-scale=1.0, width=device-width" />

                <Link prefetch href="/index">

                </Link>

                  <HeaderLogin />
                  <HeaderNav />
                  <HeaderSocial />

                SHOWS

                Check out these city shows

                      {show[0].name.text}

                      {moment(show[0].start.local).format('MMMM Do YYYY')} -
                      {this.state.address.address && this.state.address.address.address_1}

                      {moment(show[0].start.local).format('h:mm a')} -
                      {moment(show[0].end.local).format('h:mm a')} | {this.state.address.name}

{show[0].description.text}

                Purchase Tickets

                Please support our artists by clicking on their Profile to Purchase a ticket

                To purchase without an artist please click here

                  <form onSubmit={this.onSubmit}>

                      <select name="" id="" onChange={(evt) => this.setState({ artist: evt.target.value })}>
                        <option value="">SELECT AN ARTIST ...</option>
                        {map(sortedArtists, (artist) =>
                          <option value={artist.user_token} key={artist.user_token}>{artist.full_name}</option>)}
                      </select>

                      <input type="submit" value="BUY TICKETS" />

                  </form>

                  {map(this.state.artists, (artist) => (

                            <Link
                              prefetch
                              href={`/artist?user_token=${artist.user_token}`}
                              as={`/artist/${artist.user_token}`}
                            ><img src={`${IMAGE_URL}/${artist.photo}`} alt="" />
                            </Link>

                              {artist.full_name}

                              {artist.genre}

                            <Link
                              prefetch
                              href={`/artist?user_token=${artist.user_token}`}
                              as={`/artist/${artist.user_token}`}
                            >

                                view

                            </Link>

                  ))}

          <BottomLatestNews />
          <BottomMenu />

    );
  }
}

Show.propTypes = {
  show: React.PropTypes.array,
  events: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    events: state.events,
  };
}

/**
 * Connect to Redux store.
 */
export default nextConnect(mapStateToProps, null)(Show);


text:
define(function () {

    return React.createClass({

        displayName: "displayHours",

        // lifecycle
        //mixins: [logMixin],

        // properties
        propTypes: {
            day: React.PropTypes.number.isRequired,
            week: React.PropTypes.number.isRequired,
            hours: React.PropTypes.number.isRequired
        },

        // render
        render: function() {

            return React.DOM.span(

                // attributes
                {
                    key: this.props.day,
                    "data-week": this.props.week,
                    "data-day": this.props.day
                },

                // content
                this.props.hours

            )

        }

    });

});


text:
#if defined(BUILD_FEATURE_OPENTHREAD) && defined(BUILD_FEATURE_OPENTHREAD_DIAGS)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <nlassert.h>
#include <nlplatform.h>
#include <nlproduct_config.h>
#include <nlplatform/nlplatform_diags.h>
#include <nlplatform/nlgpio.h>
#include <nlplatform/nlradio.h>
#include "nlradio_priv.h"

#include <openthread/platform/radio.h>
#include <openthread/platform/alarm-milli.h>

#include <nrf52x/device/nrf52840_bitfields.h>

struct Command
{
    const char *mName;
    void (*mCommand)(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen);
};

#if defined(PIN_6LO_FEM_CRX) && defined(PIN_6LO_FEM_CTX)
static void ProcessFemMode(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen);
#endif
static void ProcessGpio(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen);
static void ProcessRFPowerDcDcEn(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen);
#if defined(PIN_DYBUCK_EN)
static void ProcessVoltage(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen);

#if defined(BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM)
static void ProcessTransmit(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen);

#if defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
static void ProcessTxPower(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen);
#endif

#endif // BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM
#endif // PIN_DYBUCK_EN

static int32_t sPacketsLeftToTransmit;
static uint32_t sRepeatPeriodMilliseconds;
static bool sUserPayload;
static otInstance *sInstance;
static otRadioFrame *sTxPacket;

static const struct Command sCommands[] =
{
    { "dcdcen",   &ProcessRFPowerDcDcEn },
#if defined(PIN_6LO_FEM_CRX) && defined(PIN_6LO_FEM_CTX)
    { "femmode",  &ProcessFemMode },
#endif
    { "gpio",     &ProcessGpio },
#if defined(PIN_DYBUCK_EN)
    { "vcc2",     &ProcessVoltage },
#if defined(BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM)
    { "transmit", &ProcessTransmit },
#if defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
    { "txPower",  &ProcessTxPower },
#endif
#endif // defined(BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM)
#endif // defined(PIN_DYBUCK_EN)
};

#if defined(PIN_DYBUCK_EN)
static const char *const voltage_table[] = {
    "v0",  // EN|SEL0|SEL1|SEL2: 1000
    "v1",  // EN|SEL0|SEL1|SEL2: 1001
    "v2",  // EN|SEL0|SEL1|SEL2: 1010
    "v3",  // EN|SEL0|SEL1|SEL2: 1011
    "v4",  // EN|SEL0|SEL1|SEL2: 1100
    "v5",  // EN|SEL0|SEL1|SEL2: 1101
    "v6",  // EN|SEL0|SEL1|SEL2: 1110
    "v7",  // EN|SEL0|SEL1|SEL2: 1111
};
#endif // PIN_DYBUCK_EN

#if defined(PIN_6LO_FEM_CRX) && defined(PIN_6LO_FEM_CTX)
static const struct {
    uint8_t csd_value:1;
    uint8_t cps_value:1;
    uint8_t crx_value:1;
    uint8_t ctx_value:1;
    uint8_t chl_value:1;
    uint8_t unused:3;
} femmode_table[] =
{
    {
        // DEEP SLEEP MODE: CSD|CPS|CRX|CTX|CHL: 00000
        .csd_value = 0,
        .cps_value = 0,
        .crx_value = 0,
        .ctx_value = 0,
        .chl_value = 0,
    },
    {
        // RECEIVE LNA MODE: CSD|CPS|CRX|CTX|CHL: 10100
        .csd_value = 1,
        .cps_value = 0,
        .crx_value = 1,
        .ctx_value = 0,
        .chl_value = 0,
    },
    {
        // TX HIGH-POWER MODE: CSD|CPS|CRX|CTX|CHL: 10011
        .csd_value = 1,
        .cps_value = 0,
        .crx_value = 0,
        .ctx_value = 1,
        .chl_value = 1,
    },
    {
        // TX LOW-POWER MODE: CSD|CPS|CRX|CTX|CHL: 10010
        .csd_value = 1,
        .cps_value = 0,
        .crx_value = 0,
        .ctx_value = 1,
        .chl_value = 0,
    },
    {
        // RX BYPASS MODE: CSD|CPS|CRX|CTX|CHL: 11100
        .csd_value = 1,
        .cps_value = 1,
        .crx_value = 1,
        .ctx_value = 0,
        .chl_value = 0,
    },
    {
        // TX BYPASS MODE: CSD|CPS|CRX|CTX|CHL: 11010
        .csd_value = 1,
        .cps_value = 1,
        .crx_value = 0,
        .ctx_value = 1,
        .chl_value = 0,
    },
    {
        // SLEEP MODE: CSD|CPS|CRX|CTX|CHL: 10000
        .csd_value = 1,
        .cps_value = 0,
        .crx_value = 0,
        .ctx_value = 0,
        .chl_value = 0,
    },
};
#endif // PIN_6LO_FEM_CRX && PIN_6LO_FEM_CTX

void nlplatform_diags(otInstance *aInstance, int argc, char *argv[], char *aOutput, size_t aOutputMaxLen)
{
    sInstance = aInstance;
    if (sTxPacket == NULL)
    {
        sTxPacket = otPlatRadioGetTransmitBuffer(sInstance);
    }
    if (argc > 0)
    {
        unsigned int i;

        for (i = 0; i < ARRAY_SIZE(sCommands); i++)
        {
            if (strcmp(argv[0], sCommands[i].mName) == 0)
            {
                sCommands[i].mCommand(argc - 1, ((argc > 1) ? &argv[1]: NULL), aOutput, aOutputMaxLen);
                break;
            }
        }

        if (i == ARRAY_SIZE(sCommands))
        {
           snprintf(aOutput, aOutputMaxLen, "diagnostics feature '%s' is not supported\n", argv[0]);
        }
    }
    else
    {
        snprintf(aOutput, aOutputMaxLen, "diagnostics feature is not specified\n");
    }
}

void nlplatform_diags_alarm(otInstance *aInstance)
{
    // check if we were cancelled
    if (sPacketsLeftToTransmit)
    {
        if (sUserPayload)
        {
            // increment the seq_num in the user payload to help distinguish them
            // for packet error rate testing.  don't increment the seq_num for
            // generated packets that RF team typically uses for factory calibration.
            ieee802154_packet_t *tx_packet = (ieee802154_packet_t*)&sTxPacket->mPsdu[-NLOT_RADIO_PRE_TX_PSDU_PADDING_OCTETS];
            tx_packet->mpdu.seq_num++;
        }

#if defined(BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM) && defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
        // Instruct product layer FEM module to skip powercal table lookup & use the FEM settings came as part of the transmit command
        nlproduct_FEM_use_factory_txpower_settings();
#endif

        otPlatRadioTransmit(aInstance, sTxPacket);

#if defined(BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM) && defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
        // Reset the use of hardcoded factory fem settings to restore the powercal table lookup.
        nlproduct_FEM_reset_use_factory_txpower_settings();
#endif

        if (sPacketsLeftToTransmit > 0)
        {
            sPacketsLeftToTransmit--;
        }
        if (sPacketsLeftToTransmit)
        {
            // schedule for next packet
            otPlatAlarmMilliStartAt(aInstance, 0, sRepeatPeriodMilliseconds);
        }
    }
}

static void ProcessRFPowerDcDcEn(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen)
{
    if (argc == 1)
    {
        if (atoi(argv[0]) == 0)
        {
            NRF_POWER->DCDCEN = 0;
            snprintf(aOutput, aOutputMaxLen, "dcdcen is disabled\n");
        }
        else
        {
            NRF_POWER->DCDCEN = 1;
            snprintf(aOutput, aOutputMaxLen, "dcdcen is enabled\n");
        }
    }
    else
    {
        snprintf(aOutput, aOutputMaxLen, "error parameter\n");
    }
}

static void ProcessGpio(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen)
{
    bool isSet = strcmp(argv[0], "set") == 0;
    bool isGet = strcmp(argv[0], "get") == 0;

    if (argc == 2 && isGet)
    {
        if (atoi(argv[1]) == -1)
        {
            printf("spinning to cause watchdog\n");
            while(1);
        }
        else if (atoi(argv[1]) == -2)
        {
            printf("causing an assert failure\n");
            assert(0);
            while(1);
        }
        else if (atoi(argv[1]) == -3)
        {
            printf("rebooting\n");
            nlplatform_reset(NL_RESET_REASON_SW_REQUESTED);
            while(1);
        }

        // get gpio_num
        snprintf(aOutput, aOutputMaxLen, "GPIO current input is %d\n", nlgpio_get_value(atoi(argv[1])));
    }
    else if (argc == 3 && isSet)
    {
        // set gpio_num value
        nlgpio_set_output(atoi(argv[1]), atoi(argv[2]));
        snprintf(aOutput, aOutputMaxLen, "GPIO set output value succeeded\n");
    }
    else if (argc == 4 && isSet)
    {
        // accepts a gpio config param as argv[2] but ignores it.
        // set gpio_num pin_config value
        nlgpio_set_output(atoi(argv[1]), atoi(argv[3]));
        snprintf(aOutput, aOutputMaxLen, "GPIO set output value succeeded\n");
    }
    else
    {
        snprintf(aOutput, aOutputMaxLen,
                          "Error: Illegal arguments\n"
                           "Usage:\n"
                           "   gpio get <pinnum>\n"
                           "   gpio set <pinnum> <value>\n"
                           "   gpio set <pinnum> <config> <value>\n");
    }
}

#if defined(PIN_DYBUCK_EN)
static void ProcessVoltage(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen)
{
    bool error = false;

    if (argc == 1)
    {
        unsigned int i;

        for (i = 0; i < ARRAY_SIZE(voltage_table); i++)
        {
            if (strcmp(voltage_table[i], argv[0]) == 0)
            {
                break;
            }
        }

        if (i < ARRAY_SIZE(voltage_table))
        {
            nlgpio_set_output(PIN_DYBUCK_EN, 1);
            nlgpio_set_output(PIN_DYBUCK_SEL0, (i >> 2) & 0x1);
            nlgpio_set_output(PIN_DYBUCK_SEL1, (i >> 1) & 0x1);
            nlgpio_set_output(PIN_DYBUCK_SEL2, i & 0x1);
            snprintf(aOutput, aOutputMaxLen, "Set %s voltage value succeeded\n", argv[0]);
        }
        else
        {
            error = true;
        }
    }

    if (argc == 0 || argc > 1 || error)
    {
        snprintf(aOutput, aOutputMaxLen,
                          "Error: Illegal arguments\n"
                           "Usage:\n"
                           "   vcc2 <voltage value>\n"
                           "   <voltage value>:v0 ~ v7\n");
    }
}

#if defined(BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM)
// Similar to the generic OT diags cmd "send" and "repeat" except all the needed information
// for the transmit is given on the cmd line, including vcc2 for FEM + tx_power
// encoded together as the power argument to otPlatRadioTransmit(), channel,
// count, interval, payload. Count is the number of packets to transmit (-1 for infinite).
// Interval is the time in milliseconds between packets.
// Payload is a string of hex digits, two characters per octet. The number of octets in
// the payload string is the length of the payload. A negative payload number means send
// a generated number of bytes as the payload instead of using the user specified payload.
static void ProcessTransmit(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen)
{
    bool error = false;

    if (argc == 1)
    {
        if (strcmp("stop", argv[0]) == 0)
        {
            if (sPacketsLeftToTransmit)
            {
                otPlatAlarmMilliStop(sInstance);
                sRepeatPeriodMilliseconds = 0;
                sPacketsLeftToTransmit = 0;
                snprintf(aOutput, aOutputMaxLen,
                         "Stopped previous transmit operation\n");
            }
            else
            {
                snprintf(aOutput, aOutputMaxLen,
                         "Error: transmit not in progress\n");
            }
        }
        else
        {
            error = true;
        }
    }
    else if (argc == 7)
    {
        unsigned int i;
        int chl_setting = strtol(argv[0], NULL, 10);
        int txpower_setting = strtol(argv[2], NULL, 10);
        int channel = strtol(argv[3], NULL, 10);
        int num_packets = strtol(argv[4], NULL, 10);
        int packet_length = 0;
#if defined(BUILD_FEATURE_USE_NORDIC_OT_RADIO_DRIVER)
        uint8_t temp_channel;
#endif

        if (sPacketsLeftToTransmit)
        {
            snprintf(aOutput, aOutputMaxLen,
                     "Error: repeating transmit already active, stop first\n");
            goto out;
        }

        if ((num_packets < 1) && (num_packets != -1))
        {
            snprintf(aOutput, aOutputMaxLen,
                     "Error: num_packets must be 1 or more, or -1 for infinite\n");
            error = true;
            goto err_out;
        }

        if ((chl_setting < 0) || (chl_setting > 2))
        {
            snprintf(aOutput, aOutputMaxLen, "Error: Valid FEM mode(CHL) must be between 0 and 2\n");
            error = true;
            goto err_out;
        }

        for (i = 0; i < ARRAY_SIZE(voltage_table); i++)
        {
            if (strcmp(voltage_table[i], argv[1]) == 0)
            {
                break;
            }
        }

        if (i < ARRAY_SIZE(voltage_table))
        {
#if defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
            nlproduct_encode_factory_transmit_power(chl_setting, i, txpower_setting);
#else
            nlencoded_transmit_power_t encoded_power = nlproduct_encode_transmit_power(chl_setting, i, txpower_setting);
            otPlatRadioSetTransmitPower(sInstance, encoded_power.raw_int);
#endif
        }
        else
        {
            snprintf(aOutput, aOutputMaxLen, "Error: VCC2 must be between 0 and 7\n");
            error = true;
            goto err_out;
        }

        if (channel < 11 || channel > 26)
        {
            snprintf(aOutput, aOutputMaxLen, "Error: Channel must be between 11 and 26\n");
            error = true;
            goto err_out;
        }

        // payload is expected to be an ascii hex string, or a single negative
        // integer that specifies the number of octets to send in a
        // generated payload.
        const char *payload_string = argv[6];
        if (payload_string[0] == '-')
        {
            packet_length = -strtol(payload_string, NULL, 10);
            if (packet_length < 0 || packet_length > OT_RADIO_FRAME_MAX_SIZE)
            {
                snprintf(aOutput, aOutputMaxLen,
                         "Error: payload length %d too long, max is %d\n", packet_length, OT_RADIO_FRAME_MAX_SIZE);
                error = true;
                goto err_out;
            }
            for (i = 0; i <  packet_length - 2; i++) // last 2 octets of packet_length is CRC added by driver
            {
                sTxPacket->mPsdu[i] = i;
            }
            sUserPayload = false;
        }
        else
        {
            // convert two characters at a time to hex digits for the psdu.
            char buf[3];
            buf[2] = 0; // null terminate
            i = 0;
            while (*payload_string)
            {
                buf[0] = *payload_string++;
                buf[1] = *payload_string++;
                sTxPacket->mPsdu[i++] = strtoul(buf, NULL, 16);
            }
            if (i == 0)
            {
                snprintf(aOutput, aOutputMaxLen,
                         "Error: no valid payload provided\n");
                error = true;
                goto err_out;
            }
            packet_length = i + 2; // add 2 for the crc/fcs bytes
            if (i > OT_RADIO_FRAME_MAX_SIZE)
            {
                snprintf(aOutput, aOutputMaxLen,
                         "Error: payload string %d too long, max is %d octets\n", i - 2, OT_RADIO_FRAME_MAX_SIZE - 2);
                error = true;
                goto err_out;
            }
            sUserPayload = true;
        }

        sTxPacket->mChannel = channel;
        sTxPacket->mLength = packet_length;

#if defined(BUILD_FEATURE_USE_NORDIC_OT_RADIO_DRIVER)
       /* With each diag transmit command we could have a diff set of FEM settings for the current channel which needs to be applied before transmit.
        * Radio driver channel caching feature avoids the use of these FEM settings if the incoming channel matches the cached channel.
        * So to bypass this radio driver behavior, create a temporary channel change by going into adjecent channel.
        */
        temp_channel = (channel == 26) ? 11 : (channel + 1);
        otPlatRadioReceive(sInstance, temp_channel);
#endif

        if ((num_packets == -1) || (num_packets > 1))
        {
            sRepeatPeriodMilliseconds = strtoul(argv[5], NULL, 10);
            if (sRepeatPeriodMilliseconds == 0)
            {
                snprintf(aOutput, aOutputMaxLen,
                         "Error: repeat period must be non-zero\n");
                goto out;
            }
            sPacketsLeftToTransmit = num_packets;
            otPlatAlarmMilliStartAt(sInstance, otPlatAlarmMilliGetNow(), sRepeatPeriodMilliseconds);
            if (num_packets == -1)
            {
                snprintf(aOutput, aOutputMaxLen,
                         "sending infinite packets of length %u, of %s payload, channel %d, with delay of %u ms\r\n",
                         sTxPacket->mLength, sUserPayload ? "user provided" : "auto generated",
                         sTxPacket->mChannel, sRepeatPeriodMilliseconds);
            }
            else
            {
                snprintf(aOutput, aOutputMaxLen,
                         "sending %u packets of length %u, of %s payload, channel %d, with delay of %u ms\r\n",
                         num_packets, sTxPacket->mLength, sUserPayload ? "user provided" : "auto generated",
                         sTxPacket->mChannel, sRepeatPeriodMilliseconds);
            }
        }
        else
        {
            snprintf(aOutput, aOutputMaxLen, "sending one packet of length %u, channel %d\r\n",
                     sTxPacket->mLength, sTxPacket->mChannel);

#if defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
            // Instruct product layer FEM module to skip powercal table lookup & use the FEM settings came as part of the transmit command
            nlproduct_FEM_use_factory_txpower_settings();
#endif

            otPlatRadioTransmit(sInstance, sTxPacket);

#if defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
            // Reset the use of hardcoded factory fem settings to restore the powercal table lookup.
            nlproduct_FEM_reset_use_factory_txpower_settings();
#endif

            sPacketsLeftToTransmit = 0;
            sRepeatPeriodMilliseconds = 0;
        }
    }
err_out:
    if (argc == 0 || argc > 8 || error)
    {
        snprintf(aOutput, aOutputMaxLen,
                 "Usage:\ttransmit [stop | <chl> <vcc2> <txpwr> <chan> <#pkts> <repeat_ms> <payload>]\n"
                 "\te.g. transmit 0 v7 0 11 -1 16 -64\n"
                 "\te.g. transmit 0 v7 0 11 100 100 000c000000560a00010030b418\n");
    }
out:
    return;
}

#if defined(BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV)
static void ProcessTxPower(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen)
{
    int target_power;
    uint16_t reg_code;

    if (argc != 2)
    {
        return;
    }

    reg_code = atoi(argv[0]);
    target_power = strtol(argv[1], NULL, 10);

    snprintf(aOutput, aOutputMaxLen, "Setting PowerCal override reg_code(%u) target_power(%d)\n", reg_code, target_power);

    nlproduct_factory_override_reg_domain(reg_code);
    nlradio_set_target_txpower(target_power);
}
#endif // BUILD_FEATURE_TXPOWLOOKUP_TABLE_IN_SYSENV

#endif // BUILD_FEATURE_PRODUCT_HAS_RADIO_FEM
#endif // PIN_DYBUCK_EN

#if defined(PIN_6LO_FEM_CRX) && defined(PIN_6LO_FEM_CTX)
static void ProcessFemMode(int argc, char *argv[], char *aOutput, size_t aOutputMaxLen)
{
    bool error = false;

    if (argc == 1)
    {
        unsigned int mode = atoi(argv[0]);

        if (mode < ARRAY_SIZE(femmode_table))
        {
#if !defined(PIN_6LO_FEM_CSD)
            // if PIN_6LOW_FEM_CSD is not defined in product config header, FEM mode 0 would not be supported
            if (mode == 0)
            {
                error = true;
                goto exit;
            }
#else
            nlgpio_set_output(PIN_6LO_FEM_CSD, femmode_table[mode].csd_value);
#endif

#if !defined(PIN_6LO_FEM_CHL)
            // if PIN_6LO_FEM_CHL is not defined in product config header, FEM mode 2 would not be supported
            if (mode == 2)
            {
                error = true;
                goto exit;
            }
#else
            nlgpio_set_output(PIN_6LO_FEM_CHL, femmode_table[mode].chl_value);
#endif

#if !defined(PIN_6LO_FEM_CPS)
            // if PIN_6LO_FEM_CPS is not defined in product config header, FEM mode 4,5 would not be supported
            if (mode == 4 || mode == 5)
            {
                error = true;
                goto exit;
            }
#else
            nlgpio_set_output(PIN_6LO_FEM_CPS, femmode_table[mode].cps_value);
#endif

            nlgpio_set_output(PIN_6LO_FEM_CRX, femmode_table[mode].crx_value);
            nlgpio_set_output(PIN_6LO_FEM_CTX, femmode_table[mode].ctx_value);
            snprintf(aOutput, aOutputMaxLen, "Set FEM mode %s succeeded\n", argv[0]);
        }
        else
        {
            error = true;
        }
    }

#if !defined(PIN_6LO_FEM_CSD) || !defined(PIN_6LO_FEM_CPS) || !defined(PIN_6LO_FEM_CHL)
exit:
#endif

    if (argc == 0 || argc > 1 || error)
    {
        snprintf(aOutput, aOutputMaxLen,
                          "Error: Illegal arguments\n"
                           "Usage:\n"
                           "   femmode <mode>\n"
                           "   <mode>:"
#if defined(PIN_6LO_FEM_CSD)
                           "0, "
#endif
                           "1, "
#if defined(PIN_6LO_FEM_CHL)
                           "2, "
#endif
                           "3, "
#if defined(PIN_6LO_FEM_CPS)
                           "4, 5, "
#endif
                           "6\n"
                           );
    }
}
#endif // PIN_6LO_FEM_CRX && PIN_6LO_FEM_CTX

#endif // defined(BUILD_FEATURE_OPENTHREAD) && defined(BUILD_FEATURE_OPENTHREAD_DIAGS)


text:
So you want to run your own copy of pypip.in?
#############################################
:date: 2014-07-26 23:40
:author: kura
:category: coding
:tags: python, pypipins, pypip.in, shields
:slug: so-you-want-to-run-your-own-copy-of-pypip.in

.. contents::
    :backlinks: none

While pypip.in is available under the MIT license on `GitHub
<https://github.com/badges/pypipins>`_, it's not explained how to really use it
properly.

You can gather how to set-up the Python source of the project and get the
`Twisted <https://twistedmatrix.com>`_ process running, this is totally reliant
on using the `img.shields.io <https://img.shields.io>`_.

I decided to write this article explaining how to install your own copy of the
shields nodejs code, pypipin itself and even cover off supervisord and Varnish
too.

shields & nodejs
================

nodejs
------

First of all you'll need to get the latest source code copy of nodejs from the
`nodejs download page <http://nodejs.org/download/>`_.

Extract it.

.. code-block:: none bash

    tar -xvzf node-<VERSION>.tar.gz

.. code-block:: none bash

    cd node-<VERSION>

You'll need to install the build tools, if you don't have them already.

.. code-block:: none bash

    sudo apt-get install build-essential

And then make and install node.

.. code-block:: none bash

    make && sudo make install

Redis
-----

Redis is used to temporarily store PyPI responses.

.. code-block:: none bash

    sudo apt-get install redis-server

shields
-------

You'll need to install git for the next step.

.. code-block:: none bash

    sudo apt-get install git-core

And get a copy of the shields repository.

.. code-block:: none bash

    git clone git@github.com:badges/shields.git

Once it's checked out, you'll need to install it's requirements.

.. code-block:: none bash

    cd shields && npm install

You can confirm this works by running the shields server.

.. code-block:: none bash

    node server 8080

pypipin
=======

Clone the shields repository, the same way you did for shields above.

.. code-block:: none bash

    git clone git@github.com:badges/pypipins.git

To do this properly, you'll need to make sure you have virtualenv for Python.

.. code-block:: none bash

    sudo apt-get install python-dev
    wget -O - https://bootstrap.pypa.io/get-pip.py | sudo python
    sudo pip install virtualenv

Next, you'll need to create a virtual environment.

.. code-block:: none bash

    virtualenv /path/to/where/you/want/it/

Then you can active it.

.. code-block:: none bash

    . /path/to/your/virtualenv/bin/activate

And install the dev requirements from the pypipins directory.

.. code-block:: none bash

    pip install -r /path/to/pypipins/clone/requirements-dev.txt

You'll need to edit shields.py, commenting out the img.shields.io host and
uncommon the local one.

.. code-block:: none python

    /path/to/pypipins/clone/shields/shields.py

    # SHIELD_URL = "http://img.shields.io/badge/%s-%s-%s.%s"
    SHIELD_URL = "http://localhost:9000/badge/%s-%s-%s.%s"  # pypip.in uses a local version of img.shields.io

Once this is done, you can test the pypipins server.

.. code-block:: none bash

    /path/to/your/virtualenv/bin/python /path/to/pypipins/clone/shields/shields.py

supervisor(d)
=============

Always install supervisor from apt, rather than from pip.

.. code-block:: none bash

    sudo apt-get install supervisor

Then cd to where conf.d config files are stored for supervisor.

.. code-block:: none bash

    cd /etc/supervisor/conf.d/

In here, you'll need to create a configuration for the shields nodejs server
and also for pypipins server.

.. code-block:: none

    shields.conf

    [program:shields]
    directory=/path/to/shields/
    command=node server 9000
    stdout_logfile=/var/log/supervisor/shields.log
    stderr_logfile=/var/log/supervisor/shields.error.log
    user=www-data
    group=www-data
    autostart=true
    autorestart=true

.. code-block:: none

    pypipin.conf

    [program:pypipin]
    command=/path/to/virtualenv/bin/python /path/to/pypipin/clone/shields/shields.py
    stdout_logfile=/var/log/supervisor/pypipin.log
    stderr_logfile=/var/log/supervisor/pypipin.error.log
    user=www-data
    group=www-data
    autostart=true
    autorestart=true

Once this is done, you'll need to load them in to supervisor itself.

.. code-block:: none bash

    sudo supervisorctl

.. code-block:: none

    reread
    add shields
    add pypipin

Now supervisor will automatically start both processes and keep them alive.

Varnish
=======

The final step is to put Varnish in front of the system to cache images for you.
The shields server has the ability to use redis for caching but, I'd rather do
this with a proper HTTP cache rather than use redis.

.. code-block:: none bash

    sudo apt-get install varnish

Tell Varnish to run on port 80.

.. code-block:: none

    /etc/default/varnish

    DAEMON_OPTS="-a :80 \
                 -T localhost:6082 \
                 -f /etc/varnish/default.vcl \
                 -S /etc/varnish/secret \
                 -s malloc,256m"

This will run the Varnish HTTP server on port 80 and keep it's admin interface
hidden from the world, binding it to port 6082 on the lo interface.

The final step is to tell Varnish about the pypipins server.

.. code-block:: none

    /etc/varnish/default.vcl

    backend default {
        .host = "127.0.0.1";
        .port = "8888";
    }

    sub vcl_recv {
        if (req.request != "GET") {
            return(pipe);
        }

        if (req.request == "GET") {
            remove req.http.cookie;
            remove req.http.authenticate;
            remove req.http.Etag;
            remove req.http.If-None-Match;
            return(lookup);
        }
        return(pass);
    }

    sub vcl_fetch {
        if (beresp.status >= 300) {
            return(hit_for_pass);
        }

        set beresp.ttl = 1h;
        set beresp.grace = 6h;
        unset beresp.http.Set-Cookie;
        unset beresp.http.Etag;
        unset beresp.http.Cache-Control;
        set beresp.http.Cache-Control = "no-cache";
        return (deliver);
    }

    sub vcl_deliver {
          if (obj.hits > 0) {
                set resp.http.X-Cache = "HIT";
                set resp.http.X-Cache-Hits = obj.hits;
          } else {
                set resp.http.X-Cache = "MISS";
          }
    }

All done, restart Varnish.

.. code-block:: none bash

    sudo /etc/init.d/varnish restart

You'll be able to go to `http://yourserver.tld/download/<PACKAGE>/badge.svg
<http://yourserver.tld/download/PACKAGE/badge.svg>`_ and everything should be
working as expected.

Notes on PyPy
=============

I personally use PyPy for running the pypipins server because, it's a long
running process and PyPy speeds it up wonderfully.

If you're using Debian 7, the latest version of PyPy as of writing is 2.3.1 and
requires libffi6, if you're using one of the prebuilt binaries. libffi6 is only
available in Jessie which is currently in testing.

You can either use an older version of PyPy or, backport libffi6 from Jessie.

.. code-block:: none

    /etc/apt/sources.list

    deb ftp://ftp.debian.org/debian/ jessie main

.. code-block:: none

    /etc/apt/preferences.d/jessie

    Package: *
    Pin: release a=wheezy
    Pin-Priority: 900

    Package: libffi*
    Pin: release a=jessie
    Pin-Priority: 910

This will keep all packages pinned to wheezy except libffi+wildcard, which will
be pulled from Jessie.

You can then simply install libffi6 from Jessie.

.. code-block:: none bash

    sudo apt-get update
    sudo apt-get -u install libffi6/jessie

SSL
===

If you want to use SSL with your shields, you'll need to install nginx in front
of Varnish.

So instead of running Varnish on port 80, as shown above. Put it on a different
port, install and use nginx as you would for any other website and simply proxy
all requests back to Varnish.


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0007_auto_20180628_0411'),
    ]

    operations = [
        migrations.CreateModel(
            name='EBook',
            fields=[
            ],
            options={
                'proxy': True,
                'indexes': [],
            },
            bases=('core.book',),
        ),
        migrations.AddField(
            model_name='book',
            name='added',
            field=models.DateTimeField(blank=True, null=True),
        ),
    ]


text:
QuickSpecBegin(SDLSubscribeWaypointsSpec)

QuickSpecEnd


text:
module CustomerScoring
  VERSION = "0.1.0"
end


text:
define('TQRCodeCtrl', function(require, exports, module){
    var $ = jQuery;
    var Base = require('base');
    var TQRCodeCtrl = Base.extend({

        initialize: function(config) {
            TQRCodeCtrl.superclass.initialize.call(this, config);
			this.$config = config;
			this.$img = $('#' + config.selector);
        },

        setValue: function(value) {
            this.$img.attr('src', '').attr('src', value);
        }

    });
    exports.TQRCodeCtrl = window.TQRCodeCtrl = TQRCodeCtrl;
});


text:
package chav1961.purelib.ui.interfaces;

public enum StandardWizards {

}


text:
package main

import (
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"strconv"
	"time"

	"github.com/yuin/gopher-lua"
)

var (
	// shell contains the current shell used when running shell commands
	shell = "bash"

	// flg contains all flags from the command line
	flg *flags

	// subcommands are the targets defiend in Lua
	subcommands = make(targets)

	// done is used for signaling that we should abort the blade target execution
	// and quit
	done chan struct{}

	// currentTarget is the name of the curret running target
	// This is used when generating error messages for fatal errors when running
	// targets.
	currentTarget string

	errAbort           = errors.New("user: abort")
	errUndefinedTarget = errors.New("fatal: undefined target")
)

type target struct {
	cmd     *lua.LFunction
	help    string
	compgen compgenerator
	valid   bool
}

type targets map[string]*target

func (t targets) get(fn *lua.LFunction) (subcmd *target, name string) {
	for name, subcmd := range t {
		if subcmd.cmd == fn {
			return subcmd, name
		}
	}

	subcmd = &target{cmd: fn}
	name = "tmp-dummy-" + strconv.Itoa(len(t))
	t[name] = subcmd
	return subcmd, name
}

func (t targets) rename(from, to string) error {
	if _, ok := t[from]; !ok {
		return fmt.Errorf("Target not found: %v", from)
	}

	t[to] = t[from]
	delete(t, from)
	t[to].valid = true
	return nil
}

func (t targets) validate() {
	for _, subcmd := range t {
		if !subcmd.valid {
			fmt.Fprintf(os.Stderr, "fatal: no command bound to target\n")
			fmt.Fprintf(os.Stderr, "fatal: check blade.help and blade.compgen calls\n")
			fmt.Fprintf(os.Stderr, "debug: the following functions are ok:\n")
			t.printValidTargets()
			os.Exit(1)
		}
	}
}

func (t targets) printValidTargets() {
	for name, subcmd := range t {
		if subcmd.valid {
			fmt.Fprintf(os.Stderr, "debug:  * %v\n", name)
		}
	}
}

type flags struct {
	debug       bool
	genBashConf bool
	compgen     bool
	compCWords  int
	bladefile   string
}

func init() {
	flg = &flags{}
	flag.BoolVar(&flg.debug, "debug", false, "Enable debug output")
	flag.BoolVar(&flg.compgen, "compgen", false, "Used for bash compleation")
	flag.BoolVar(&flg.genBashConf, "generate-bash-conf", false, "Generate bash completion configuration")
	flag.IntVar(&flg.compCWords, "comp-cwords", 0, "Used for bash compleation")
	flag.StringVar(&flg.bladefile, "f", "", "Absolute path to non default blade file")
}

// setupInterupt is used for catching ctrl-c when we want to abort the current
// running target.
func setupInterupt() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	go func() {
		sig := <-c
		emit("Received: %v", sig)
		if done != nil {
			emit("Signaling shutdown")
			close(done)
		} else {
			fmt.Fprintf(os.Stderr, "aborting: due to %v signal\n", sig)
		}
	}()
}

func main() {
	flag.Parse()

	if flg.genBashConf {
		generateBashConfig()
		return
	}

	if flg.compgen {
		compgen()
		return
	}

	setupInterupt()

	L, blade, cmd := setupEnv()

	if flag.Arg(0) == "help" {
		printHelp(L)
		return
	}

	target := flag.Arg(0)

	err := setup(L, blade, target)
	if err != nil {
		emitErr("%v: setup", err)
		return
	}
	defer teardown(L, blade, target)

	if flag.NArg() == 0 {
		defaultTarget(L, blade)
		return
	}

	if flag.NArg() > 0 {
		err := lookupLFunc(L, cmd, target)
		if err != nil {
			emitFatal("%v", err)
		}

		customTarget(L, cmd, target, flag.Args()[1:])
		wait(done)
		return
	}
}

func pause() {
	if done != nil {
		return
	}

	emit("Setting up done chanel")
	done = make(chan struct{})
}

func wait(ch chan struct{}) {
	if ch == nil {
		return
	}

	emit("Waiting for done signal")
	fmt.Printf("watching: ctrl-c to abort\n")
	for {
		select {
		case <-ch:
			emit("Done waiting")
			return
		default:
			time.Sleep(10 * time.Millisecond)
		}
	}
}

func emit(msgfmt string, args ...interface{}) {
	if flg.debug == false {
		return
	}
	log.Printf(msgfmt, args...)
}

func emitErr(msgfmt string, args ...interface{}) {
	fmt.Fprintf(os.Stdout, msgfmt, args...)
}

func emitFatal(msgfmt string, args ...interface{}) {
	fmt.Fprintf(os.Stdout, msgfmt, args...)
	os.Exit(1)
}


text:
package errors

import (
	orgerrors "github.com/pkg/errors"
)

func Wrapd(err *error, msg string) {
	*err = orgerrors.Wrap(*err, msg)
}

func Wrapdf(err *error, fmt string, args ...interface{}) {
	*err = orgerrors.Wrapf(*err, fmt, args...)
}


text:
using System;

namespace Abp.Domain.Entities.Auditing
{
    /// <summary>
    /// A shortcut of <see cref="CreationAuditedEntity{TPrimaryKey}"/> for most used primary key type (<see cref="int"/>).
    /// </summary>
    [Serializable]
    public abstract class CreationAuditedEntity : CreationAuditedEntity<int>
    {

    }
}


text:
exports.config = {
  allScriptsTimeout: 11000,

  suites: {
    clean: ['clean/clean.js'],
    restAPI: [
      'restAPI/adminResource.js',
      'restAPI/infoResource.js',
      'restAPI/logoutResource.js',
      'restAPI/configurationResource.js',
      'restAPI/jmx.js',
      'restAPI/stageLibraryResource.js',
      'restAPI/pipelineStoreResource.js'
    ],
    ui: [
      'ui/pipelineHomePage.js',
      'ui/homePage.js',
      'ui/createPipeline.js',
      'ui/previewTest.js',
      'ui/configurationPage.js',
      'ui/jvmMetricsPage.js',
      'ui/logPage.js'
    ],
    single: [
      'restAPI/createTestPipelines.js'
    ]
  },

  framework: 'jasmine',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000
  },

  capabilities: {
    'phantomjs.binary.path': require('phantomjs').path,
    'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG']
  },

  onPrepare: function() {
    browser.sleep(3000);
    browser.driver.manage().window().setSize(1400, 750);
    browser.ignoreSynchronization = true;
    browser.driver.get(browser.baseUrl + 'login.html');

    browser.driver.findElement(by.id('usernameId')).sendKeys('admin');
    browser.driver.findElement(by.id('passwordId')).sendKeys('admin');
    browser.driver.findElement(by.id('loginId')).click();

    browser.getCapabilities().then(function (cap) {
      browser.browserName = cap.caps_.browserName;
    });

    // Login takes some time, so wait until it's done.
    return browser.driver.wait(function() {
      return browser.driver.getCurrentUrl().then(function(url) {
        return true;
      });
    });
  }
};


text:
// Copyright 2012 Traceur Authors.
//
// Licensed 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.

import {
  CURRENT,
  RESULT
} from '../../syntax/PredefinedName.js';
import {State} from './State.js';
import {
  createAssignmentStatement,
  createIdentifierExpression,
  createMemberExpression,
  createReturnStatement,
  createThisExpression,
  createTrueLiteral
} from '../ParseTreeFactory.js';

/**
 * Represents a simple yield expression that has been added to a StateMachine.
 */
export class YieldState extends State {
  /**
   * @param {number} id
   * @param {number} fallThroughState
   * @param {ParseTree} expression
   */
  constructor(id, fallThroughState, expression) {
    super(id);
    this.fallThroughState = fallThroughState;
    this.expression = expression;
  }

  /**
   * @param {number} oldState
   * @param {number} newState
   * @return {YieldState}
   */
  replaceState(oldState, newState) {
    return new this.constructor(
        State.replaceStateId(this.id, oldState, newState),
        State.replaceStateId(this.fallThroughState, oldState, newState),
        this.expression);
  }

  /**
   * @param {FinallyState} enclosingFinally
   * @param {number} machineEndState
   * @param {ErrorReporter} reporter
   * @return {Array.<ParseTree>}
   */
  transform(enclosingFinally, machineEndState, reporter) {
    return [
      // 'this' refers to the '$G' object from
      // GeneratorTransformer.transformGeneratorBody
      //
      // this.$current = expression;
      createAssignmentStatement(
          createMemberExpression(createThisExpression(), CURRENT),
          this.expression),
      // either:
      //      $state = this.fallThroughState;
      //      return true;
      // or:
      //      $state = enclosingFinally.finallyState;
      //      $fallThrough = this.fallThroughState;
      //      return true;
      ...State.generateAssignState(enclosingFinally, this.fallThroughState),
      createReturnStatement(createTrueLiteral())
    ];
  }
}


text:
message( "External project - ITK" )

find_package(Git)
if(NOT GIT_FOUND)
  message(ERROR "Cannot find git. git is required for Superbuild")
endif()

option( USE_GIT_PROTOCOL "If behind a firewall turn this off to use http instead." ON)

set(git_protocol "git")
if(NOT USE_GIT_PROTOCOL)
  set(git_protocol "http")
endif()

set( ITK_DEPENDENCIES )
set( _vtkoptions )

if( ${USE_SYSTEM_VTK} MATCHES "OFF" )
  set( ITK_DEPENDENCIES VTK ${ITK_DEPENDENCIES} )
else()
  if( ${VTK_MAJOR_VERSION} EQUAL 6 )
    set( _vtkoptions
      -DModule_ITKVtkGlue:BOOL=ON
      -DVTK_DIR:PATH=${VTK_DIR}
    )
  endif()
endif()

if( ${USE_SYSTEM_HDF5} MATCHES "OFF" )
  set( ITK_DEPENDENCIES HDF5 ${ITK_DEPENDENCIES} )
endif()

ExternalProject_Add(ITK
  DEPENDS ${ITK_DEPENDENCIES}
  GIT_REPOSITORY ${git_protocol}://itk.org/ITK.git
  GIT_TAG v4.5.0
  SOURCE_DIR ITK
  BINARY_DIR ITK-build
  UPDATE_COMMAND ""
  PATCH_COMMAND ""
  CMAKE_GENERATOR ${EP_CMAKE_GENERATOR}
  CMAKE_ARGS
    ${ep_common_args}
  	${cmake_hdf5_libs}
    -DBUILD_EXAMPLES:BOOL=OFF
    -DBUILD_SHARED_LIBS:BOOL=ON
    -DBUILD_TESTING:BOOL=OFF
    -DCMAKE_BUILD_TYPE:STRING=${BUILD_TYPE}
    -DITK_BUILD_DEFAULT_MODULES:BOOL=ON
    -DModule_ITKReview:BOOL=ON
    -DITK_LEGACY_REMOVE:BOOL=ON
    -DCMAKE_INSTALL_PREFIX:PATH=${INSTALL_DEPENDENCIES_DIR}
    -DITK_USE_SYSTEM_HDF5:BOOL=ON
    -DHDF5_DIR:PATH=${HDF5_DIR}
    ${_vtkoptions}
)

set( ITK_DIR ${INSTALL_DEPENDENCIES_DIR}/lib/cmake/ITK-4.5/ )


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Voice;
use app\models\VoiceSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * VoiceController implements the CRUD actions for Voice model.
 */
class VoiceController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Voice models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new VoiceSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Voice model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Voice model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Voice();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model = $this->getLists($model);
            $model->weights[count($model->weights)] = count($model->weights);
            $model->weight = count($model->weights) - 1;

            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Voice model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model = $this->getLists($model);

            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Voice model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Voice model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Voice the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Voice::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function getLists($model){
        $model->action_models = Voice::getActionModels();
        if((!isset($model->action_model) or empty($model->action_model)) and '0' !== $model->action_model){
            $model->action_model = key($model->action_models);
        }

        $model->action_model_ids = Voice::getModelIds($model->action_model);
        if((!isset($model->action_model_id) or empty($model->action_model_id)) and '0' !== $model->action_model_id){
            $model->action_model_id = key($model->action_model_ids);
        }

        $model->action_model_fields = Voice::getModelFields($model->action_model, $model->action_model_id);
        if((!isset($model->action_model_field) or empty($model->action_model_field)) and '0' !== $model->action_model_field){
            $model->action_model_field = key($model->action_model_fields);
        }

        $model->weights = Voice::getWeights();

        return $model;
    }

    public function actionAjaxGetModels(){
        $models = Voice::getModels();
        return json_encode($models);
    }

    public function actionAjaxGetModelIds($model){
        $model_ids = Voice::getModelIds($model);
        return json_encode($model_ids);
    }

    public function actionAjaxGetModelFields($model, $model_id){
        $model_fields = Voice::getModelFields($model, $model_id);
        return json_encode($model_fields);
    }
}


text:
//----------------------------------------------------------------------------------
#ifndef RENDERTEXTOBJECT_H
#define RENDERTEXTOBJECT_H
//----------------------------------------------------------------------------------
//Класс текста объекта мира
class CRenderTextObject : public CRenderObject
{
public:
    bool Transparent = false;

    CRenderTextObject();
    virtual ~CRenderTextObject();

    CRenderTextObject *m_NextDraw{ NULL };
    CRenderTextObject *m_PrevDraw{ NULL };

    //Вытащить из очереди
    void UnlinkDraw();

    //Наверх очереди
    void ToTop();
};
//----------------------------------------------------------------------------------
#endif
//----------------------------------------------------------------------------------


text:
package org.takes.misc;

import com.google.common.base.Joiner;
import java.util.Arrays;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

/**
 * Test case for {@link Transform}.
 *
 * @author Jason Wong (super132j@yahoo.com)
 * @version $Id$
 * @since 0.15.2
 */
public final class TransformTest {

    /**
     * Transform can transform list.
     */
    @Test
    public void transformsList() {
        MatcherAssert.assertThat(
            Joiner.on(" ").join(
                new Transform<String, String>(
                    Arrays.asList("one", "two", "three"),
                    new TransformAction<String, String>() {
                        @Override
                        public String transform(final String element) {
                            return element.concat("t");
                        }
                    }
                )
            ),
            Matchers.equalTo("onet twot threet")
        );
    }

}


text:
package org.globus.io.streams;

import java.io.OutputStream;
import java.io.IOException;
import java.io.FileOutputStream;

public class GlobusFileOutputStream extends GlobusOutputStream {

    private OutputStream output;

    public GlobusFileOutputStream(String file, boolean append)
	throws IOException {
	output = new FileOutputStream(file, append);
    }

    public void abort() {
	try {
	    output.close();
	} catch(Exception e) {}
    }

    public void close()
	throws IOException {
	output.close();
    }

    public void write(byte [] msg)
	throws IOException {
	output.write(msg);
    }

    public void write(byte [] msg, int from, int length)
	throws IOException {
	output.write(msg, from, length);
    }

    public void write(int b)
	throws IOException {
	output.write(b);
    }

    public void flush()
	throws IOException {
	output.flush();
    }

}


text:
namespace arc {

class ArcPackageSyncableService;

class ArcPackageSyncableServiceFactory : public ProfileKeyedServiceFactory {
 public:
  ArcPackageSyncableServiceFactory(const ArcPackageSyncableServiceFactory&) =
      delete;
  ArcPackageSyncableServiceFactory& operator=(
      const ArcPackageSyncableServiceFactory&) = delete;

  static ArcPackageSyncableService* GetForBrowserContext(
      content::BrowserContext* context);

  static ArcPackageSyncableServiceFactory* GetInstance();

 private:
  friend struct base::DefaultSingletonTraits<ArcPackageSyncableServiceFactory>;

  ArcPackageSyncableServiceFactory();
  ~ArcPackageSyncableServiceFactory() override;

  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
};

}  // namespace arc

#endif  // CHROME_BROWSER_UI_APP_LIST_ARC_ARC_PACKAGE_SYNCABLE_SERVICE_FACTORY_H_


text:
layout: post
category : courses
title: "Deeplearning.ai Notes: Structuring Machine Learning Projects"
tags : [course, notes, ml]
---
{% include JB/setup %}

My notes from: https://www.coursera.org/learn/machine-learning-projects

## ML Strategy
Chain of assumptions:
* Fit training set well on cost function
	* Bigger network
	* Try different optimisation function
* Fit dev set well on cost function
	* Add Regularisation
	* Bigger training set
* Fit test set well on cost function
	* Bigger dev set
* Performs well in real world
	* Change dev set
	* Change cost function

*Single number evaluation metric*
Makes it much easy to assess if things are working and make comparisons.

Precision: out of the predictions made for a class, what percentage where correct e.g. out of the results classified X, P% were correct
Recall: out of the actual classifications for a class, what percent were correctly classified e.g. R% of class X were classified as X

F1 score = `2/ (1/P + 1/R)`, average of P and R

*Satisficing & Optimising metric*
Could combine Accuracy and Running time e.g. `cost = accuracy - 0.5*running time` though this is a bit artificial. Could instead set a limit e.g.  maximise accuracy within a certain running time. Optimising accuracy while satisficing running time.

*Train, dev, test sets*
Choose from the same distribution.
Up to 10,000 training samples, can use a 70|30 or 60|20|20 split. Over that use 1% for dev and test sets.

*Bayes Optimal Error*
Limit at which it becomes impossible to generate better predictions. Accuracy doesn't improve beyond this limit. Theoretical best function.
Can use human level error as an approximation for Bayes error.

Avoidable Bias: if training set error is far off human (Bayes) error, focus on bias reduction techniques;
Variance: if training set error is close to human (Bayes) error but dev set error is larger, focus on variance reduction techniques.

*Surpassing human level*
Good at structured data, not so good at natural perception. Good at lots of data.
* Online advertising
* Product recommendations
* Logistics (predicting transit time)
* Loan approvals

Even getting good at natural perception tasks:
* NLP
* Some image recognition

*Improving your models performance*
1. You can fit the training set well, avoidable bias.
	* Train a bigger model
	* Train longer/better optimisation algorithms: momentum, RMSprop, Adam
	* NN architecture/hyperparameters search
2. The training set performance generalises  well to the dev/test sets, variance
	* More data
	* Regularisation: L2, dropout, data augmentation
	* NN architecture/hyperparameters search

### Error Anlaysis
Review the errors (mislabeled examples, both positive and negative) to determine what issues are best worth investigating.
Evaluate multiple ideas in parallel.

*Cleaning incorrectly labeled data*
DL algorithms are quite robust to random errors in the data set. They are less robust to systematic errors.

During testing against he dev set, record incorrectly labeled results and review that they were labelled correctly.
Review:
* Overall dev set error
* Errors due to incorrect labels
* Errors due to other causes
If the errors due to incorrectly labeled results are due to incorrect labels then it's worth rectifying.

Consider examining examples your algorithm got right as well as ones it got right. It may have got it "right" even though it was incorrectly labeled.

*Build quickly, iterate*
If tackling a new problem:
* Set up dev/test set and metric
* Build initial system quickly
* Use Bias/Variance analysis & Error analysis to prioritise next steps

### Mismatched training and dev/test set

*Training and test distributions that differ*
If adding a new data source that has limited examples, just adding it to your existing large data source won't be affective as only a limited number will end up being part of the dev and test sets.  You'd be better of in this case to skew your data set to spread the new data source more evenly across training, dev and test.

*Estimating Bias and Variance*
The way this is measured changes when you dev and test sets don't come from the same distribution as your training set.
This can result in a bigger difference between the training error and dev error. To avoid this you can create an additional "training-dev" set from the same distribution as the training set, this allows you to perform error analysis on this new set to check for variance issues in your model from the training set by taking the new data out of the equation. Big difference between training and training-dev indicates a variance issue, while a big difference between training-dev and dev indicates a data mismatch issue.

Look for differences in errors between:
* Human (Bayes) -> Training Set = Avoidable Bias
* Training Set -> Training Dev Set = Variance
* Training Dev Set -> Dev Set = Data Mismatch
* Dev Set -> Test Set = Overfitting to dev set

*Addressing data mismatch*
Not great systematic ways to address data mismatch.
Carry out manual error analysis and try to understand the differences between training and dev/test sets.
Make training data more similar; or collect more data similar to dev/test sets.

Artificial data synthesis, manipulating the training data to better reflect the dev/test data. e.g. adding background noise to audio. Risk of overfitting to artificial scenario.

### Learning from Multiple Tasks

*Transfer Learning*
Using part of a trained Neural Network to help solve another task. To do this make use of the earlier layers, retraining the later layers with the new data set. Often referred to pre-training and fine-tuning.

Makes sense when you have a lot of data from the problem you're transferring from but not much where you're training to.
* Task A and Task B have the same input x e.g. (image).
* You have a lot more data for A than B.
* Low level features from A could be helpful for learning B.

*Multi-task Learning*
Rather than assigning a single label to an input, you assign them multiple labels. To this you can use logistic regression but don't use softmax at the last layer.

This could be done by creating multiple Neural Networks but it's more efficient if it can be done by training a single model to produce multiple labels.
* training on a set of tasks that could benefit from having shared low level features
* the amount of data for each task is similar
* can train a big enough neural network to do well on all the tasks

### End-to-end Deep Learning
Requires a large dataset. Removes the need for intermediate steps.
Excludes ability to add hand designed components which can allow humans to inject knowledge (though this can be a double edged sword that doesn't allow new patterns to be found).


text:
<!doctype html>
<meta charset=utf-8>
<title>DOMException constructor</title>
<link rel=help href="https://heycam.github.io/webidl/#es-DOMException-constructor-object">
<link rel=help href="https://people.mozilla.org/~jorendorff/es6-draft.html#sec-error.prototype.message">
<link rel=help href="https://people.mozilla.org/~jorendorff/es6-draft.html#sec-error.prototype.name">


text:
<?php

class Onxshop_Router {

	var $request;

	var $modules;

	var $Onxshop;

	/**
	 * Process Action
	 * return Onxshop object
	 */

	function processAction($request) {

		/**
		 * expand request and check modules list
		 */

		if ($this->request = $this->setRequest($request)) $modules = $this->_explodeRequest($this->getRequest());

		if (!is_array($modules)) {

			die("Onxshop_Router: Can't explodeRequest " . htmlspecialchars($request));

		}

		$this->setModules($modules);

		/**
		 * Initialise Onxshop object(s)
		 */

		if (count($modules) > 1) {

			$descendants = array_reverse($modules);
			foreach ($descendants as $key=>$descendant) {

				if ($key > 0) {
					$subOnxshop = $_Onxshop[$key - 1];
				} else {
					$subOnxshop = false;
				}

				$classname = $this->_prepareCallBack($descendant);
				$_Onxshop[$key] = new $classname($descendant, $subOnxshop);
			}

			$this->Onxshop = $_Onxshop[count($descendants) - 1];

		} else {

			$classname = $this->_prepareCallBack($modules[0]);
			$this->Onxshop = new $classname($modules[0]);

		}

		return $this->Onxshop;
	}

	/**
	 * prepare CallBack function
	 */

	private function _prepareCallBack($request) {

		$file = preg_replace("/([A-Za-z0-9_\/]*).*/", "\\1", $request);
		if (file_exists(ONXSHOP_DIR . "controllers/{$file}.php") || file_exists(ONXSHOP_PROJECT_DIR . "controllers/{$file}.php")) {
			require_once("controllers/{$file}.php");
			$classname = "Onxshop_Controller_" . preg_replace("/\//", "_", $file);
		} else {
			$classname = "Onxshop_Controller";
		}

		return $classname;
	}

	/**
	 * Router
	 * @return array
	 */
	function _explodeRequest($request) {

		/**
		 * Parse request - explode modules
		 */

		$modules= array();

		/**
		 * get list of modules
		 */

		$match_result = preg_match_all('/[^.~]*(~[^~]*~)?/i', $request, $match);

		foreach ($match[0] as $item) {
			if ($item != '') $modules[] = $item;
		}

		//little protection against DOS
		if (count($modules) > 20) trigger_error('Onxshop: too many modules in one request', E_USER_ERROR);

		//print_r($modules);

		if (count($modules) == 0) return false;
		else return $modules;
	}

    /**
     * set modules
     *
     * @param unknown_type $modules
     * @return unknown
     */

	function setModules($modules) {

		if (is_array($modules)) {
			//we have descendants
			$this->modules = $modules;
			return true;
		} else {
			$this->modules = $modules;
		}

	}

    /**
     * get modules
     *
     * @return unknown
     */
	function getModules() {

		return $this->modules;

	}

	/**
	 * set request
	 *
	 * @param unknown_type $request
	 */

	public function setRequest($request) {

		if (preg_match('/[^a-z0-9\-\._\/\&\=\{\}\$\[\]|%@]&+/i', $request)) {

			die('Invalid request: ' . htmlspecialchars($request));

		} else {

			return $request;
		}
	}

    /**
     * get request
     *
     * @return unknown
     */
	function getRequest() {

		return $this->request;

	}

}


text:
<?php
require_once('customer.php');

// Generate a JSON-formatted string that holds the name and location of each customer.
$places .= '\'{"type": "FeatureCollection","features": [';

// Append data from each row
$comma = "";
foreach (get_sample_customers() as $customer) {
  $places .= $comma.'{ "type": "Feature", "properties": { "name": "'.$customer->first_name." ".$customer->last_name.'" }, "geometry": { "type": "Point", "coordinates": [ '.$customer->longitude.', '.$customer->latitude.' ] } }';
  $comma = ",";
}

$places .= ']}\'';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Customers</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/queue-async/1.0.7/queue.min.js"></script>
  <script src="http://d3js.org/topojson.v0.min.js"></script>
  <script src="vis.js"></script>
  <script type="text/javascript">
    function show_customers() {
      create_map(JSON.parse(<?php echo $places; ?>));
    }
    window.onload = show_customers;
  </script>
</body>
</html>


text:
<?php

/**
 * Fired during plugin deactivation
 *
 * @link       http://example.com
 * @since      1.0.0
 *
 * @package    Plugin_Name
 * @subpackage Plugin_Name/includes
 */

/**
 * Fired during plugin deactivation.
 *
 * This class defines all code necessary to run during the plugin's deactivation.
 *
 * @since      1.0.0
 * @package    Plugin_Name
 * @subpackage Plugin_Name/includes
 * @author     Your Name <email@example.com>
 */
class PPS_Deactivator {

	/**
	 * Short Description. (use period)
	 *
	 * Long Description.
	 *
	 * @since    1.0.0
	 */
	public static function deactivate() {

	}

}


text:
package org.uberfire.client.perspective;

import com.google.gwt.core.client.JavaScriptObject;

public class JSPartDefinition extends JavaScriptObject {

    protected JSPartDefinition() {
    }

    public final native String getPlaceName() /*-{
        return this.place;
    }-*/;

    public final native JavaScriptObject getParameters() /*-{
        return this.parameters;
    }-*/;

    public final native String getContextId()  /*-{
        return this.context_id;
    }-*/;

    public final native String getContextDisplayModeAsString()  /*-{
        return this.context_display_mode;
    }-*/;
}


text:
'use strict';

var childProcess = require('child_process');
var spawn = childProcess.spawn;
var exec = childProcess.exec;

module.exports = function (pid, signal, callback) {
    var tree = {};
    var pidsToProcess = {};
    tree[pid] = [];
    pidsToProcess[pid] = 1;

    if (typeof signal === 'function' && callback === undefined) {
      callback = signal;
      signal = undefined;
    }

    switch (process.platform) {
    case 'win32':
        exec('taskkill /pid ' + pid + ' /T /F', callback);
        break;
    case 'darwin':
        buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
          return spawn('pgrep', ['-P', parentPid]);
        }, function () {
            killAll(tree, signal, callback);
        });
        break;
    // case 'sunos':
    //     buildProcessTreeSunOS(pid, tree, pidsToProcess, function () {
    //         killAll(tree, signal, callback);
    //     });
    //     break;
    default: // Linux
        buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
          return spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
        }, function () {
            killAll(tree, signal, callback);
        });
        break;
    }
};

function killAll (tree, signal, callback) {
    var killed = {};
    try {
        Object.keys(tree).forEach(function (pid) {
            tree[pid].forEach(function (pidpid) {
                if (!killed[pidpid]) {
                    killPid(pidpid, signal);
                    killed[pidpid] = 1;
                }
            });
            if (!killed[pid]) {
                killPid(pid, signal);
                killed[pid] = 1;
            }
        });
    } catch (err) {
        if (callback) {
            return callback(err);
        } else {
            throw err;
        }
    }
    if (callback) {
        return callback();
    }
}

function killPid(pid, signal) {
    try {
        process.kill(parseInt(pid, 10), signal);
    }
    catch (err) {
        if (err.code !== 'ESRCH') throw err;
    }
}

function buildProcessTree (parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
    var ps = spawnChildProcessesList(parentPid);
    var allData = '';
    ps.stdout.on('data', function (data) {
        var data = data.toString('ascii');
        allData += data;
    });

    var onClose = function (code) {
        delete pidsToProcess[parentPid];

        if (code != 0) {
            // no more parent processes
            if (Object.keys(pidsToProcess).length == 0) {
                cb();
            }
            return;
        }

        allData.match(/\d+/g).forEach(function (pid) {
          pid = parseInt(pid, 10);
          tree[parentPid].push(pid);
          tree[pid] = [];
          pidsToProcess[pid] = 1;
          buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
        });
    };

    ps.on('close', onClose);
}


text:
package com.ajjpj.afoundation.function;

/**
 * @author arno
 */
public interface APredicateNoThrow<T> extends APredicate<T, RuntimeException> {
    boolean apply(T o);
}


text:
package co.nubetech.hiho.mapreduce.lib.db.apache;

import java.util.Date;

/**
 * Implement DBSplitter over date/time values returned by an Oracle db.
 * Make use of logic from DateSplitter, since this just needs to use
 * some Oracle-specific functions on the formatting end when generating
 * InputSplits.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class OracleDateSplitter extends DateSplitter {

  @SuppressWarnings("unchecked")
  @Override
  protected String dateToString(Date d) {
    // Oracle Data objects are always actually Timestamps
    return "TO_TIMESTAMP('" + d.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')";
  }
}


text:
namespace views {
class GroupboxView;
class Label;
class NativeButton;
class TableView;
}

class DefaultEncodingComboboxModel;
class FontDisplayView;
class TableModel;

///////////////////////////////////////////////////////////////////////////////
// FontsPageView

class FontsPageView : public OptionsPageView,
                      public views::Combobox::Listener,
                      public SelectFontDialog::Listener,
                      public views::ButtonListener {
 public:
  explicit FontsPageView(Profile* profile);
  virtual ~FontsPageView();

  // views::ButtonListener implementation:
  virtual void ButtonPressed(views::Button* sender);

  // views::Combobox::Listener implementation:
  virtual void ItemChanged(views::Combobox* combo_box,
                           int prev_index,
                           int new_index);

  // SelectFontDialog::Listener implementation:
  virtual void FontSelected(const gfx::Font& font, void* params);

  // Save Changes made to relevent pref members associated with this tab.
  // This is public since it is called by FontsLanguageWindowView in its
  // Dialog Delegate Accept() method.
  void SaveChanges();

 protected:
  // OptionsPageView implementation:
  virtual void InitControlLayout();
  virtual void NotifyPrefChanged(const std::wstring* pref_name);

 private:
  enum FontTypeBeingChanged {
    NONE,
    SERIF,
    SANS_SERIF,
    FIXED_WIDTH
  };

  // Init Dialog controls.
  void InitFontLayout();
  void InitEncodingLayout();

  bool serif_button_pressed_;
  bool sans_serif_button_pressed_;
  bool fixed_width_button_pressed_;
  bool encoding_dropdown_clicked_;

  views::Label* fonts_group_title_;
  views::Label* encoding_group_title_;

  views::View* fonts_contents_;
  views::View* encoding_contents_;

  // Fonts settings.
  // Select Font dialogs.
  scoped_refptr<SelectFontDialog> select_font_dialog_;

  // Buttons.
  views::NativeButton* fixed_width_font_change_page_button_;
  views::NativeButton* serif_font_change_page_button_;
  views::NativeButton* sans_serif_font_change_page_button_;

  // FontDisplayView objects to display selected font.
  FontDisplayView* fixed_width_font_display_view_;
  FontDisplayView* serif_font_display_view_;
  FontDisplayView* sans_serif_font_display_view_;

  // Labels to describe what is to be changed.
  views::Label* fixed_width_font_label_;
  views::Label* serif_font_label_;
  views::Label* sans_serif_font_label_;

  // Advanced Font names and sizes as PrefMembers.
  StringPrefMember serif_name_;
  StringPrefMember sans_serif_name_;
  StringPrefMember fixed_width_name_;
  IntegerPrefMember serif_size_;
  IntegerPrefMember sans_serif_size_;
  IntegerPrefMember fixed_width_size_;
  int serif_font_size_pixel_;
  int sans_serif_font_size_pixel_;
  int fixed_width_font_size_pixel_;
  StringPrefMember default_encoding_;
  bool font_changed_;

  // Windows font picker flag;
  FontTypeBeingChanged font_type_being_changed_;

  // Default Encoding.
  scoped_ptr<DefaultEncodingComboboxModel> default_encoding_combobox_model_;
  views::Label* default_encoding_combobox_label_;
  views::Combobox* default_encoding_combobox_;
  std::wstring default_encoding_selected_;
  bool default_encoding_changed_;

  DISALLOW_EVIL_CONSTRUCTORS(FontsPageView);
};

#endif  // #ifndef CHROME_BROWSER_VIEWS_OPTIONS_FONTS_PAGE_VIEW_H__


text:
using System;
using System.IO;
using System.Threading.Tasks;

using JetBrains.Annotations;

using Tauco.Dicom.Shared;

namespace Tauco.Dicom.Network
{
    /// <summary>
    /// Provides method for downloading files from the DICOM server.
    /// </summary>
    internal interface IDicomDownloader<TInfo>
    {
        /// <summary>
        /// Performs asynchronous file download identified by given <paramref name="identifier"/> from the DICOM server.
        /// </summary>
        /// <param name="identifier">Specifies file to be downloaded</param>
        /// <param name="downloadAction">Specifies action which will be performed once server gets the file</param>
        /// <returns>Async result of the request</returns>
        Task DownloadAsync([NotNull] InfoIdentifier identifier, Func<InfoIdentifier, InfoIdentifier, Stream> downloadAction = null);
    }
}


text:
<?php
return [
    'title' => 'Experimentos',
    'all' => 'Todos os experimentos',
    'name' => 'Nome',
    'description' => 'Descrição',
    'tags' => 'Tags',
    'duration' => 'Duração',
    'resources' => 'Recursos',
    'target' => 'Alvo',
    'elementary' => 'Ensino fundamental I',
    'secondary' => 'Ensino fundamental II',
    'high' => 'Ensino médio',
    'higher' => 'Ensino superior',
    'subject' => 'Disciplina',
    'physics' => 'Física',
    'biology' => 'Biologia',
    'chemistry' => 'Química',
    'robotics' => 'Robótica',
    'science' => 'Ciências',
    'language' => 'Idioma',
    'pt' => 'Português',
    'en' => 'Inglês',
    'es' => 'Espanhol',
    'difficulty' => 'Dificuldade',
    'interaction' => 'Interação',
    'thumbnail' => 'Imagem',
    'maintenance' => 'Manutenção',
    /* Create */
    'create' => 'Criar experimento',
    'package' => 'Pacote de Arquivos do Experimento (.zip)',
    'details' => 'Detalhes',
    'files' => 'Arquivos',
    /* Edit */
    'edit' => 'Editar experimento',
    /* Delete */
    'delete' => 'Deletar experimento',
    'embeed' => 'Incorporar',
    'report' => 'Gerar Relatório',
    'csvexport' => 'Exportar arquivo CSV',
    'end_rep' => 'Sua sessão terminou. Clique em "Gerar Relatório" para baixar um documento com os resultados da experiência ou clique em "Sair" para deixar esta página.',
    'end' => 'Sua sessão terminou. Clique em "Sair" para deixar esta página.',
    'pack' => 'Um exemplo de pacote de arquivos para um experimento pode ser encontrado no ',
    'queue' => 'Fila',
        ];