text:
import sys
import types  # noqa
import logging
import asyncio
import inspect
from functools import partial

try:
    from asyncio import ensure_future
except ImportError:  # pragma: no cover
    from asyncio import async as ensure_future  # noqa

from pomp.core.base import (  # noqa
    BaseQueue,
    BaseRequest,
    BaseResponse,
    BaseHttpResponse,
    BaseCrawlException,
)
from pomp.core.utils import iterator, switch_to_asyncio  # noqa
from pomp.core.engine import StopCommand
from pomp.core.engine import Pomp as SyncPomp

from pomp.contrib.concurrenttools import (
    _run_crawler_worker, ConcurrentCrawler,
)

async def _co(value):
    if inspect.iscoroutine(value):
        return await value
    return value

def _wrap_to_future(value):
    if inspect.iscoroutine(value):
        return ensure_future(value)
    return value

log = logging.getLogger(__name__)

class SimpleAsyncioQueue(BaseQueue):

    def __init__(self, use_lifo=False):
        self.q = asyncio.Queue() if use_lifo else asyncio.LifoQueue()

    async def get_requests(self, count=None):
        return await self.q.get()

    async def put_requests(self, requests):
        await self.q.put(requests)

class AioPomp(SyncPomp):
    DEFAULT_QUEUE_CLASS = SimpleAsyncioQueue
    LOCK_FACTORY = asyncio.Lock

    async def pump(self, crawler):
        """Start crawling

        :param crawler: isntance of :class:`pomp.core.base.BaseCrawler`
        """
        await self.prepare(crawler)

        # add ENTRY_REQUESTS to the queue
        next_requests = getattr(crawler, 'ENTRY_REQUESTS', None)
        if next_requests:
            await self._put_requests(iterator(next_requests))

        _pending_iteration_tasks = []

        def _on_iterations_task_done(task, future):
            _pending_iteration_tasks.remove(task)

        while True:

            if self.queue_lock and self.queue_semaphore_value <= 0:
                await self.queue_lock.acquire()

            next_requests = await self.queue.get_requests(
                count=self.queue_semaphore_value
            )

            if isinstance(next_requests, StopCommand):
                break

            # process requests and do not block loop
            task = asyncio.ensure_future(
                self.process_requests(
                    iterator(next_requests), crawler,
                )
            )
            _pending_iteration_tasks.append(task)
            task.add_done_callback(
                partial(_on_iterations_task_done, task)
            )

        # loop ended, but we have pending tasks - wait
        if _pending_iteration_tasks:
            log.debug(
                "Wait pending iteration tasks: %s",
                len(_pending_iteration_tasks),
            )
            await asyncio.wait(_pending_iteration_tasks)

        await self.finish(crawler)

    # some kind of python magic
    # read SyncPomp.* sources, add async/await/adapters by `# asyncio: `
    # directive and inject to this class as native methods
    exec('\n'.join(switch_to_asyncio(SyncPomp.prepare)))
    exec('\n'.join(switch_to_asyncio(SyncPomp.process_requests)))
    exec('\n'.join(switch_to_asyncio(SyncPomp.response_callback)))
    exec('\n'.join(switch_to_asyncio(SyncPomp.on_response)))
    exec('\n'.join(switch_to_asyncio(SyncPomp.on_parse_result)))
    exec('\n'.join(switch_to_asyncio(SyncPomp._request_done)))
    exec('\n'.join(switch_to_asyncio(SyncPomp._process_items)))
    exec('\n'.join(switch_to_asyncio(SyncPomp._put_requests)))
    exec('\n'.join(switch_to_asyncio(SyncPomp._req_middlewares)))
    exec('\n'.join(switch_to_asyncio(SyncPomp._resp_middlewares)))
    exec('\n'.join(switch_to_asyncio(SyncPomp._exception_middlewares)))
    exec('\n'.join(switch_to_asyncio(SyncPomp.finish)))

class AioConcurrentCrawler(ConcurrentCrawler):

    async def process(self, response):
        try:
            return await asyncio.get_event_loop().run_in_executor(
                self.executor,
                _run_crawler_worker,
                self.worker_params,
                response,
            )
        except Exception as e:
            log.exception('Exception on %s', response)
            return BaseCrawlException(
                response=response,
                exception=e,
                exc_info=sys.exc_info(),
            )


text:
import type { CodeRange } from '../../shared/CodeRange';

export type LinkedCodeRange = {
    readonly source: CodeRange;
    readonly result: CodeRange;
};

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>@yield('title')</title>
		<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

		<link rel="stylesheet" href="{{url('/css/bootstrap.min.css')}}">
		<link rel="stylesheet" href="{{url('/css/login.css')}}">

Servei de gestió de cuina

					<form class="form-inline" id="FORMULARI" action="login" method="POST" align="center">

						{!! csrf_field() !!}

							E-Mail
							<input type="email" name="email" class="form-control" value="{{ old('email') }}">

							Password
							<input type="password" name="password" class="form-control">

					  <button type="submit" class="btn btn-default">Iniciar sessió</button>
					</form>

				@if(\Auth::check())

{{ \Auth::user()->username }}

								<button type="submit" class="btn btn-default">Tancar sessió</button>

				@endif

		@yield('content')

	        	© 2016 - {{ env('APP_NAME') }}


text:
package futures;

public class JobWithResult implements Runnable {
	private int a, b, result;
	private Exception e;

	JobWithResult(int a, int b) {
		this.a = a;
		this.b = b;
	}

	@Override
	public void run() {
		try {
			this.result = a / b;
		} catch (Exception e) {
			System.out.println("Oops, an exception raised; storing for later.");
			this.e = e;
		}
	}

	public int getResult() throws Exception {
		if (e != null)
			throw e;

		return result;
	}

	public static void main(String... args) throws InterruptedException {

		JobWithResult jwr = new JobWithResult(4, 0);

		Thread t = new Thread(jwr);

		t.start();

		System.out.println("Waiting for thread to complete...");
		t.join();

		System.out.println("All done.");
		try {
			System.out.println(jwr.getResult());
		} catch (Exception e) {
			System.out.println("Ooops: " + e.toString());
		}

	}
}


text:
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="css/reset.css">

    <link rel="stylesheet" href="css/style.css">

    <title>Animated Page Transition #2 | CodyHouse</title>

                    <svg class="nc-icon outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24">
                        <g transform="translate(0, 0)">
                            <polygon fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" points="12,2 3,10 3,23 9,23 9,16 15,16 15,23 21,23 21,10 " stroke-linejoin="miter"></polygon>
                        </g>
                    </svg>
                    Intro

                    <svg class="nc-icon outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24">
                        <g transform="translate(0, 0)">
                            <polyline data-color="color-2" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" points=" 16,7 16,2 8,2 8,7 " stroke-linejoin="miter"></polyline>
                            <rect x="1" y="7" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" width="22" height="15" stroke-linejoin="miter"></rect>
                            <line fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" x1="5" y1="7" x2="5" y2="22" stroke-linejoin="miter"></line>
                            <line fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" x1="19" y1="7" x2="19" y2="22" stroke-linejoin="miter"></line>
                        </g>
                    </svg>
                    Services

                    <svg class="nc-icon outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24">
                        <g transform="translate(0, 0)">
                            <rect x="1" y="1" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" width="22" height="22" stroke-linejoin="miter"></rect>
                            <rect data-color="color-2" x="5" y="5" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" width="5" height="5" stroke-linejoin="miter"></rect>
                            <rect data-color="color-2" x="14" y="5" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" width="5" height="5" stroke-linejoin="miter"></rect>
                            <rect data-color="color-2" x="5" y="14" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" width="5" height="5" stroke-linejoin="miter"></rect>
                            <rect data-color="color-2" x="14" y="14" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" width="5" height="5" stroke-linejoin="miter"></rect>
                        </g>
                    </svg>
                    Projects

                    <svg class="nc-icon outline" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="24px" height="24px" viewBox="0 0 24 24">
                        <g transform="translate(0, 0)">
                            <polyline data-color="color-2" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" points=" 19,7 12,14 5,7 " stroke-linejoin="miter"></polyline>
                            <rect x="1" y="3" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" width="22" height="18" stroke-linejoin="miter"></rect>
                            <line data-color="color-2" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" x1="7" y1="15" x2="5" y2="17" stroke-linejoin="miter"></line>
                            <line data-color="color-2" fill="none" stroke="#4a5261" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" x1="17" y1="15" x2="19" y2="17" stroke-linejoin="miter"></line>
                        </g>
                    </svg>
                    Contact

Animated Page Transition #2

                    Some text here

                Scroll Down

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae illo veritatis ea deserunt aliquam blanditiis, voluptas optio, voluptate ut accusamus veniam numquam, porro! Cum minima a molestiae, similique voluptate, perferendis vel iusto quam suscipit delectus dolore ducimus possimus illo molestias voluptas labore optio consequuntur sapiente pariatur libero nam temporibus. Laudantium!

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae illo veritatis ea deserunt aliquam blanditiis, voluptas optio, voluptate ut accusamus veniam numquam, porro! Cum minima a molestiae, similique voluptate, perferendis vel iusto quam suscipit delectus dolore ducimus possimus illo molestias voluptas labore optio consequuntur sapiente pariatur libero nam temporibus. Laudantium!

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae illo veritatis ea deserunt aliquam blanditiis, voluptas optio, voluptate ut accusamus veniam numquam, porro! Cum minima a molestiae, similique voluptate, perferendis vel iusto quam suscipit delectus dolore ducimus possimus illo molestias voluptas labore optio consequuntur sapiente pariatur libero nam temporibus. Laudantium!

                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae illo veritatis ea deserunt aliquam blanditiis, voluptas optio, voluptate ut accusamus veniam numquam, porro! Cum minima a molestiae, similique voluptate, perferendis vel iusto quam suscipit delectus dolore ducimus possimus illo molestias voluptas labore optio consequuntur sapiente pariatur libero nam temporibus. Laudantium!


text:
#ifndef	WEAKPRNG_H
#define	WEAKPRNG_H

#include <stddef.h>
#include <stdint.h>

struct crypto_weakprng {
	uint32_t buffer[16];
	uint32_t key[8];
	uint32_t nonce[4];
};

#define	crypto_weakprng_SEEDBYTES	32

void		crypto_weakprng_seed(struct crypto_weakprng *, const void *);
uint32_t	crypto_weakprng_32(struct crypto_weakprng *);
uint64_t	crypto_weakprng_64(struct crypto_weakprng *);
void		crypto_weakprng_buf(struct crypto_weakprng *, void *, size_t);
uintmax_t	crypto_weakprng_below(struct crypto_weakprng *, uintmax_t);

int		crypto_weakprng_selftest(void);

#endif	/* WEAKPRNG_H */


text:
module Signs.Sign (Type(..), Term(..),Sign(..),abstract_concrete,abstract_concrete',asList,reduceSign) where

import Signs.Type
import Signs.Inference
import Signs.Term
import Signs.Reductions
import Signs.Parse
import Signs.Tex
import Data.List

-- Sign datatype : an abstract term with multiple untyped concrete terms
data Sign = Sign
  { abstract :: Term
  , concretes :: [Term]
  } deriving (Eq)

instance Tex Sign where
  tex = typedTripleTex

-- reduces all terms in a sign
reduceSign (Sign a c) = Sign (reduce a) (map reduce c)

-- Pretty prints a sign
typedTripleTex (Sign absTerm [stringTerm,semTerm])  = case typeOfE $ reduce absTerm of
  Right absTyp -> array [ [ hcat [tex absTerm ,  text " : "  <> (texStyle "ABSTRACT" absTyp) , text " = "  ] ] , [pair]   ]
    where pair =  array [string,semant]
          string = [text "\\langle" ,  texTerm "STRING" stringTerm  ]
          semant = [ text ","       ,  texTerm "SEM" semTerm  , text "\\rangle"]
  Left error -> text $ "typedTriple : " ++ show error

asList (Sign a b) = a : b

instance Show Sign where
 show s = concat
  [ case abstract s of
      constant@(Con s t) -> show constant ++ " :: " ++ show t
      x -> show x ++ " :: " ++ (case typeOfE x of Right typ -> show typ ; Left err -> show err)
  , " = \n\t< "
  ,   intercalate "\n\t, " $
        map ( \term -> concat [show $ reduce term ," :: ",(show . typeOfE . reduce) term]) (concretes s)
  , "\n \t>"
  ]

instance Parse Sign where parseDef = signParser

signParser = do
  { abscon <- con
  ; reservedOp "="
  ; concretes <- tupleOf term
  ; return (Sign abscon concretes)
  }

tupleOf p = parseList (string "<") (do {ws ; p}) (do ws ; reservedOp "," ; ws) (ws >> string ">")

-- combinator to parse signs like  content1 = < content2 .... >
abstract_concrete p = abstract_concrete' p p

abstract_concrete' q p = do
  a <- q
  optional spaces
  reservedOp "="
  optional spaces
  c <- tupleOf p
  return (a,c)


text:
package org.apache.spark.mllib.fim

import org.apache.spark.annotation.Experimental
import org.apache.spark.rdd.RDD

import scala.reflect.ClassTag

/**
  * :: Experimental ::
  *
  * Model trained by [[PHybridFIN]], which holds frequent itemsets.
  *
  * @param freqItemsets frequent itemset, which is an RDD of [[(Array[Item], Long)]]
  * @tparam Item item type
  */
@Experimental
class FIModel[Item: ClassTag](val freqItemsets: RDD[(Array[Item], Long)]) extends Serializable


text:
import contextlib
import math
import numpy as np
import os
import time
import unittest

import paddle
import paddle.dataset.conll05 as conll05
import paddle.fluid as fluid

word_dict, verb_dict, label_dict = conll05.get_dict()
word_dict_len = len(word_dict)
label_dict_len = len(label_dict)
pred_dict_len = len(verb_dict)

mark_dict_len = 2
word_dim = 32
mark_dim = 5
hidden_dim = 512
depth = 8
mix_hidden_lr = 1e-3

IS_SPARSE = True
PASS_NUM = 10
BATCH_SIZE = 10

embedding_name = 'emb'

def load_parameter(file_name, h, w):
    with open(file_name, 'rb') as f:
        f.read(16)  # skip header.
        return np.fromfile(f, dtype=np.float32).reshape(h, w)

def db_lstm(word, predicate, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, mark,
            **ignored):
    # 8 features
    predicate_embedding = fluid.layers.embedding(
        input=predicate,
        size=[pred_dict_len, word_dim],
        dtype='float32',
        is_sparse=IS_SPARSE,
        param_attr='vemb')

    mark_embedding = fluid.layers.embedding(
        input=mark,
        size=[mark_dict_len, mark_dim],
        dtype='float32',
        is_sparse=IS_SPARSE)

    word_input = [word, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2]
    emb_layers = [
        fluid.layers.embedding(
            size=[word_dict_len, word_dim],
            input=x,
            param_attr=fluid.ParamAttr(
                name=embedding_name, trainable=False)) for x in word_input
    ]
    emb_layers.append(predicate_embedding)
    emb_layers.append(mark_embedding)

    hidden_0_layers = [
        fluid.layers.fc(input=emb, size=hidden_dim, act='tanh')
        for emb in emb_layers
    ]

    hidden_0 = fluid.layers.sums(input=hidden_0_layers)

    lstm_0 = fluid.layers.dynamic_lstm(
        input=hidden_0,
        size=hidden_dim,
        candidate_activation='relu',
        gate_activation='sigmoid',
        cell_activation='sigmoid')

    # stack L-LSTM and R-LSTM with direct edges
    input_tmp = [hidden_0, lstm_0]

    for i in range(1, depth):
        mix_hidden = fluid.layers.sums(input=[
            fluid.layers.fc(input=input_tmp[0], size=hidden_dim, act='tanh'),
            fluid.layers.fc(input=input_tmp[1], size=hidden_dim, act='tanh')
        ])

        lstm = fluid.layers.dynamic_lstm(
            input=mix_hidden,
            size=hidden_dim,
            candidate_activation='relu',
            gate_activation='sigmoid',
            cell_activation='sigmoid',
            is_reverse=((i % 2) == 1))

        input_tmp = [mix_hidden, lstm]

    feature_out = fluid.layers.sums(input=[
        fluid.layers.fc(input=input_tmp[0], size=label_dict_len, act='tanh'),
        fluid.layers.fc(input=input_tmp[1], size=label_dict_len, act='tanh')
    ])

    return feature_out

def to_lodtensor(data, place):
    seq_lens = [len(seq) for seq in data]
    cur_len = 0
    lod = [cur_len]
    for l in seq_lens:
        cur_len += l
        lod.append(cur_len)
    flattened_data = np.concatenate(data, axis=0).astype("int64")
    flattened_data = flattened_data.reshape([len(flattened_data), 1])
    res = fluid.LoDTensor()
    res.set(flattened_data, place)
    res.set_lod([lod])
    return res

def create_random_lodtensor(lod, place, low, high):
    data = np.random.random_integers(low, high, [lod[-1], 1]).astype("int64")
    res = fluid.LoDTensor()
    res.set(data, place)
    res.set_lod([lod])
    return res

def train(use_cuda, save_dirname=None, is_local=True):
    # define network topology
    word = fluid.layers.data(
        name='word_data', shape=[1], dtype='int64', lod_level=1)
    predicate = fluid.layers.data(
        name='verb_data', shape=[1], dtype='int64', lod_level=1)
    ctx_n2 = fluid.layers.data(
        name='ctx_n2_data', shape=[1], dtype='int64', lod_level=1)
    ctx_n1 = fluid.layers.data(
        name='ctx_n1_data', shape=[1], dtype='int64', lod_level=1)
    ctx_0 = fluid.layers.data(
        name='ctx_0_data', shape=[1], dtype='int64', lod_level=1)
    ctx_p1 = fluid.layers.data(
        name='ctx_p1_data', shape=[1], dtype='int64', lod_level=1)
    ctx_p2 = fluid.layers.data(
        name='ctx_p2_data', shape=[1], dtype='int64', lod_level=1)
    mark = fluid.layers.data(
        name='mark_data', shape=[1], dtype='int64', lod_level=1)
    feature_out = db_lstm(**locals())
    target = fluid.layers.data(
        name='target', shape=[1], dtype='int64', lod_level=1)
    crf_cost = fluid.layers.linear_chain_crf(
        input=feature_out,
        label=target,
        param_attr=fluid.ParamAttr(
            name='crfw', learning_rate=mix_hidden_lr))
    avg_cost = fluid.layers.mean(crf_cost)

    # TODO(qiao)
    # check other optimizers and check why out will be NAN
    sgd_optimizer = fluid.optimizer.SGD(
        learning_rate=fluid.layers.exponential_decay(
            learning_rate=0.01,
            decay_steps=100000,
            decay_rate=0.5,
            staircase=True))
    sgd_optimizer.minimize(avg_cost)

    # TODO(qiao)
    # add dependency track and move this config before optimizer
    crf_decode = fluid.layers.crf_decoding(
        input=feature_out, param_attr=fluid.ParamAttr(name='crfw'))

    train_data = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.conll05.test(), buf_size=8192),
        batch_size=BATCH_SIZE)

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    feeder = fluid.DataFeeder(
        feed_list=[
            word, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, predicate, mark, target
        ],
        place=place)
    exe = fluid.Executor(place)

    def train_loop(main_program):
        exe.run(fluid.default_startup_program())
        embedding_param = fluid.global_scope().find_var(
            embedding_name).get_tensor()
        embedding_param.set(
            load_parameter(conll05.get_embedding(), word_dict_len, word_dim),
            place)

        start_time = time.time()
        batch_id = 0
        for pass_id in xrange(PASS_NUM):
            for data in train_data():
                cost = exe.run(main_program,
                               feed=feeder.feed(data),
                               fetch_list=[avg_cost])
                cost = cost[0]

                if batch_id % 10 == 0:
                    print("avg_cost:" + str(cost))
                    if batch_id != 0:
                        print("second per batch: " + str((time.time(
                        ) - start_time) / batch_id))
                    # Set the threshold low to speed up the CI test
                    if float(cost) < 60.0:
                        if save_dirname is not None:
                            # TODO(liuyiqun): Change the target to crf_decode
                            fluid.io.save_inference_model(save_dirname, [
                                'word_data', 'verb_data', 'ctx_n2_data',
                                'ctx_n1_data', 'ctx_0_data', 'ctx_p1_data',
                                'ctx_p2_data', 'mark_data'
                            ], [feature_out], exe)
                        return

                batch_id = batch_id + 1

    if is_local:
        train_loop(fluid.default_main_program())
    else:
        port = os.getenv("PADDLE_INIT_PORT", "6174")
        pserver_ips = os.getenv("PADDLE_INIT_PSERVERS")  # ip,ip...
        eplist = []
        for ip in pserver_ips.split(","):
            eplist.append(':'.join([ip, port]))
        pserver_endpoints = ",".join(eplist)  # ip:port,ip:port...
        trainers = int(os.getenv("TRAINERS"))
        current_endpoint = os.getenv("POD_IP") + ":" + port
        trainer_id = int(os.getenv("PADDLE_INIT_TRAINER_ID"))
        training_role = os.getenv("TRAINING_ROLE", "TRAINER")
        t = fluid.DistributeTranspiler()
        t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers)
        if training_role == "PSERVER":
            pserver_prog = t.get_pserver_program(current_endpoint)
            pserver_startup = t.get_startup_program(current_endpoint,
                                                    pserver_prog)
            exe.run(pserver_startup)
            exe.run(pserver_prog)
        elif training_role == "TRAINER":
            train_loop(t.get_trainer_program())

def infer(use_cuda, save_dirname=None):
    if save_dirname is None:
        return

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)

    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        # Use fluid.io.load_inference_model to obtain the inference program desc,
        # the feed_target_names (the names of variables that will be feeded
        # data using feed operators), and the fetch_targets (variables that
        # we want to obtain data from using fetch operators).
        [inference_program, feed_target_names,
         fetch_targets] = fluid.io.load_inference_model(save_dirname, exe)

        lod = [0, 4, 10]
        word = create_random_lodtensor(
            lod, place, low=0, high=word_dict_len - 1)
        pred = create_random_lodtensor(
            lod, place, low=0, high=pred_dict_len - 1)
        ctx_n2 = create_random_lodtensor(
            lod, place, low=0, high=word_dict_len - 1)
        ctx_n1 = create_random_lodtensor(
            lod, place, low=0, high=word_dict_len - 1)
        ctx_0 = create_random_lodtensor(
            lod, place, low=0, high=word_dict_len - 1)
        ctx_p1 = create_random_lodtensor(
            lod, place, low=0, high=word_dict_len - 1)
        ctx_p2 = create_random_lodtensor(
            lod, place, low=0, high=word_dict_len - 1)
        mark = create_random_lodtensor(
            lod, place, low=0, high=mark_dict_len - 1)

        # Construct feed as a dictionary of {feed_target_name: feed_target_data}
        # and results will contain a list of data corresponding to fetch_targets.
        assert feed_target_names[0] == 'word_data'
        assert feed_target_names[1] == 'verb_data'
        assert feed_target_names[2] == 'ctx_n2_data'
        assert feed_target_names[3] == 'ctx_n1_data'
        assert feed_target_names[4] == 'ctx_0_data'
        assert feed_target_names[5] == 'ctx_p1_data'
        assert feed_target_names[6] == 'ctx_p2_data'
        assert feed_target_names[7] == 'mark_data'

        results = exe.run(inference_program,
                          feed={
                              feed_target_names[0]: word,
                              feed_target_names[1]: pred,
                              feed_target_names[2]: ctx_n2,
                              feed_target_names[3]: ctx_n1,
                              feed_target_names[4]: ctx_0,
                              feed_target_names[5]: ctx_p1,
                              feed_target_names[6]: ctx_p2,
                              feed_target_names[7]: mark
                          },
                          fetch_list=fetch_targets,
                          return_numpy=False)
        print(results[0].lod())
        np_data = np.array(results[0])
        print("Inference Shape: ", np_data.shape)

def main(use_cuda, is_local=True):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    # Directory for saving the trained model
    save_dirname = "label_semantic_roles.inference.model"

    train(use_cuda, save_dirname, is_local)
    infer(use_cuda, save_dirname)

class TestLabelSemanticRoles(unittest.TestCase):
    def test_cuda(self):
        with self.scope_prog_guard():
            main(use_cuda=True)

    def test_cpu(self):
        with self.scope_prog_guard():
            main(use_cuda=False)

    @contextlib.contextmanager
    def scope_prog_guard(self):
        prog = fluid.Program()
        startup_prog = fluid.Program()
        scope = fluid.core.Scope()
        with fluid.scope_guard(scope):
            with fluid.program_guard(prog, startup_prog):
                yield

if __name__ == '__main__':
    unittest.main()


text:
<?php

/**
 * Class for caching/storing URLs/links in memory.
 *
 * @package phpcrawl
 * @internal
 */
class PHPCrawlerMemoryURLCache extends PHPCrawlerURLCacheBase
{
  protected $urls = array();
  protected $url_map = array();

  /**
   * Returns the next URL from the cache that should be crawled.
   *
   * @return PhpCrawlerURLDescriptor
   */
  public function getNextUrl()
  {
    //PHPCrawlerBenchmark::start("getting_cached_url");

    $max_pri_lvl = $this->getMaxPriorityLevel();

    @reset($this->urls[$max_pri_lvl]);
    while (list($key) = @each($this->urls[$max_pri_lvl]))
    {
      $UrlDescriptor_next = $this->urls[$max_pri_lvl][$key];
      unset($this->urls[$max_pri_lvl][$key]);
      break;
    }

    // If there's no URL in the priority-level-array left -> unset
    if (count($this->urls[$max_pri_lvl]) == 0) unset($this->urls[$max_pri_lvl]);

    //PHPCrawlerBenchmark::stop("getting_cached_url");

    return $UrlDescriptor_next;
  }

  /**
   * Returns all URLs currently cached in the URL-cache.
   *
   * @return array Numeric array containing all URLs as PHPCrawlerURLDescriptor-objects
   */
  public function getAllURLs()
  {
    $URLs = array();

    @reset($this->urls);
    while (list($pri_lvl) = @each($this->urls))
    {
      $cnt = count($this->urls[$pri_lvl]);
      for ($x=0; $x<$cnt; $x++)
      {
        $URLs[] = &$this->urls[$pri_lvl][$x];
      }
    }

    return $URLs;
  }

  /**
   * Removes all URLs and all priority-rules from the URL-cache.
   */
  public function clear()
  {
    $this->urls = array();
    $this->url_map = array();
    $this->url_priorities = array();
  }

  /**
   * Adds an URL to the url-cache
   *
   * @param PHPCrawlerURLDescriptor $UrlDescriptor
   */
  public function addURL(PHPCrawlerURLDescriptor $UrlDescriptor)
  {
    if ($UrlDescriptor == null) return;

    // Hash of the URL
    $map_key = $this->getDistinctURLHash($UrlDescriptor);

    // If URL already in cache -> abort
    if($map_key != null && isset($this->url_map[$map_key])) return;

    // Retrieve priority-level
    $priority_level = $this->getUrlPriority($UrlDescriptor->url_rebuild);

    // Add URL to URL-Array
    $this->urls[$priority_level][] = $UrlDescriptor;

    // Add URL to URL-Map
    if ($this->url_distinct_property != self::URLHASH_NONE)
      $this->url_map[$map_key] = true;
  }

  /**
   * Adds an bunch of URLs to the url-cache
   *
   * @param array $urls  A numeric array containing the URLs as PHPCrawlerURLDescriptor-objects
   */
  public function addURLs($urls)
  {
    //PHPCrawlerBenchmark::start("caching_urls");

    $cnt = count($urls);
    for ($x=0; $x<$cnt; $x++)
    {
      if ($urls[$x] != null)
      {
        $this->addURL($urls[$x]);
      }
    }

    //PHPCrawlerBenchmark::stop("caching_urls");
  }

  /**
   * Checks whether there are URLs left in the cache or not.
   *
   * @return bool
   */
  public function containsURLs()
  {
    if (count($this->urls) == 0) return false;
    else return true;
  }

  /**
   * Has no function in this class.
   */
  public function cleanup()
  {
  }

  /**
   * Has no function in this class.
   */
  public function purgeCache()
  {
  }

  /**
   * Has no function in this memory-cache.
   */
  public function markUrlAsFollowed(PHPCrawlerURLDescriptor $UrlDescriptor)
  {
  }

  /**
   * Returns the highest priority-level an URL exists in cache for.
   *
   * @return int
   */
  protected function getMaxPriorityLevel()
  {
    $defined_priority_levels = array_keys($this->urls);
    rsort($defined_priority_levels);
    return $defined_priority_levels[0];
  }
}
?>


text:
'use babel';

/* @flow*/
import type { TextEditor } from 'atom';
import { Observable } from 'rxjs';
import { UPDATE_EDITOR, errorAction, testAction } from '../actions';
import { observableFromSubscribeFunction } from './../../helpers';
import { handleGutter } from '../../decorate-manager';
import type { TesterAction } from '../../types';

export default function updateEditor(action$: Observable<TesterAction>): Observable<TesterAction> {
  return action$.ofType(UPDATE_EDITOR)
    .switchMap((action: TesterAction) => {
      if (action.payload && action.payload.editor) {
        const textEditor: TextEditor = action.payload.editor;
        let subscription = Observable.fromPromise(handleGutter(textEditor)).switchMap(() => Observable.empty());
        if (atom.config.get('tester.testOnSave') && textEditor) {
          subscription = observableFromSubscribeFunction(callback => textEditor.onDidSave(callback)).mapTo(testAction());
        }
        if (atom.config.get('tester.testOnOpen')) {
          subscription = Observable.concat(
           Observable.of(testAction()),
           subscription,
         );
        }
        return subscription;
      }
      return Observable.empty();
    })
    .catch(err => Observable.of(errorAction(err)));
}


text:
include_recipe 'chef-openstack::mysql-common'

bash 'create database for cinder' do
  not_if("mysql -uroot -p#{node['mysql']['server_root_password']} -e 'SHOW DATABASES' | grep #{node['cinder']['db']['name']}")
  code <<-CODE
    mysql -uroot -p#{node['mysql']['server_root_password']} -e "CREATE DATABASE #{node['cinder']['db']['name']};"
    mysql -uroot -p#{node['mysql']['server_root_password']} -e "GRANT ALL PRIVILEGES ON #{node['cinder']['db']['name']}.* TO '#{node['cinder']['db']['username']}'@'localhost' IDENTIFIED BY '#{node['cinder']['db']['password']}';"
    mysql -uroot -p#{node['mysql']['server_root_password']} -e "GRANT ALL PRIVILEGES ON #{node['cinder']['db']['name']}.* TO '#{node['cinder']['db']['username']}'@'#{node[:cinder][:private_ip]}' IDENTIFIED BY '#{node['cinder']['db']['password']}';"
  CODE
  notifies :restart, resources(:service => 'mysql'), :immediately
end


text:
RSpec.describe 'teletype' do
  xit "prints available commands and global options" do
    command = "teletype"

    out = `#{command}`

    expect(out).to eq(<<-OUT)
#{TTY::CLI.top_banner}Commands:
  teletype add COMMAND_NAME [OPTIONS]  # Add a command to the command line app.
  teletype help [COMMAND]              # Describe available commands or one specific command
  teletype new PROJECT_NAME [OPTIONS]  # Create a new command line app skeleton.
  teletype version                     # TTY version

Options:
      [--no-color]                 # Disable colorization in output.
  -r, [--dry-run], [--no-dry-run]  # Run but do not make any changes.
      [--debug], [--no-debug]      # Run with debug logging.

OUT
  end
end


text:
//
//  NSAttributedString+HTHMarkdown.h
//
//  Copyright (c) 2014 Heiko Theuner. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 * A class category for Markdown in attributed strings.
 */
@interface NSAttributedString (HTHMarkdown)

/**
 * Only supports markdown for images (from the bundle) w/o alt text
 *
 * @param theMarkdown e.g. @"here is my clock !(Icon Clock)", "Icon Clock" is the image name in Image.xcassets
 * @param theAttributes Don't forget to set @{ NSFontAttributeName : [UIFont ...] }
 * @return Returns an NSAttributedString object initialized with the characters of aString and the attributes of attributes.
 */
- (instancetype)initWithMarkdown:(NSString *)theMarkdown attributes:(NSDictionary *)theAttributes;

@end


text:
// {{{ Imports.

import React, { PropTypes } from 'react'; // eslint-disable-line no-unused-vars
import mui from 'material-ui';

import emptyFunction from '../../node_modules/react/lib/emptyFunction';

// }}}

let ThemeManager = new mui.Styles.ThemeManager();

function withContext(ComposedComponent) {
  return class WithContext {

    static propTypes = {
      context: PropTypes.shape({
        onInsertCss: PropTypes.func,
        onSetTitle: PropTypes.func,
        onSetMeta: PropTypes.func,
        onPageNotFound: PropTypes.func
      })
    };

    static childContextTypes = {
      muiTheme: PropTypes.object,
      onInsertCss: PropTypes.func.isRequired,
      onSetTitle: PropTypes.func.isRequired,
      onSetMeta: PropTypes.func.isRequired,
      onPageNotFound: PropTypes.func.isRequired
    };

    getChildContext() {
      let context = this.props.context;
      return {
        muiTheme: ThemeManager.getCurrentTheme(),
        onInsertCss: context.onInsertCss || emptyFunction,
        onSetTitle: context.onSetTitle || emptyFunction,
        onSetMeta: context.onSetMeta || emptyFunction,
        onPageNotFound: context.onPageNotFound || emptyFunction
      };
    }

    render() {
      let { context, ...other } = this.props; // eslint-disable-line no-unused-vars
      return <ComposedComponent {...other} />;
    }

  };
}

export default withContext;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<<<<<<< HEAD

<title>J-Index</title>
<meta name="date" content="2017-08-23">
=======

<title>J-Index</title>
<meta name="date" content="2017-07-16">
>>>>>>> parent of 881573c... v0.2! Documentation Logging
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J K L M N O P R S T V W

J

Jarvis - Class in com.nlstn.jarvis

This class is the main class of the whole project.

Jarvis() - Constructor for class com.nlstn.jarvis.Jarvis

JarvisModule - Class in com.nlstn.jarvis

Jarvis is divided up into several modules, which all are responsible for managing one area.

JarvisModule(String) - Constructor for class com.nlstn.jarvis.JarvisModule

Instantiates a new JarvisModule with the given name.

A B C D E F G H I J K L M N O P R S T V W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class PerfEntityMetricBase extends DynamicData
{
  public ManagedObjectReference entity;

  public ManagedObjectReference getEntity()
  {
    return this.entity;
  }

  public void setEntity(ManagedObjectReference entity)
  {
    this.entity=entity;
  }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi;

import com.intellij.openapi.util.TextRange;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * Represents an f-string, a special kind of interpolated string literal introduced in Python 3.6.
 *
 * Unlike {@link PyPlainStringElement} these elements are composite and consist of several kinds of tokens
 * and normal PSI trees for embedded expressions.
 *
 * @see com.jetbrains.python.PyTokenTypes#FSTRING_START
 * @see com.jetbrains.python.PyTokenTypes#FSTRING_TEXT
 * @see PyFStringFragment
 * @see com.jetbrains.python.PyTokenTypes#FSTRING_END
 */
public interface PyFormattedStringElement extends PyStringElement, PyElement {
  /**
   * Returns a list of replacement fields containing expressions which values should be embedded into this literal content.
   *

   * Note that only top-level fields are included in the result. To access optional fragments that might appear in
   * format specifier of a another fragment one should use {@link PyFStringFragment#getFormatPart()} and
   * {@link PyFStringFragmentFormatPart#getFragments()}.
   */
  @NotNull
  List<PyFStringFragment> getFragments();

  /**
   * Returns ranges of literal parts of an f-string, e.g. all other parts of an f-string content that don't belong to
   * expression fragments.
   *

   * These ranges don't include literal format specifier parts of fragments and should be completely
   * covered by {@link PyStringElement#getContentRange()}.
   *

   * For instance, for the following f-string:
   *

   *

   *   f'foo{bar:format}baz'
   *

   *

   * this method will return ranges {@code (2, 5)} and {@code (14, 17)}.
   */
  @NotNull
  List<TextRange> getLiteralPartRanges();
}


text:
<?php
use BergclubPlugin\MVC\Models\Option;

/**
 *  remove all the entries from WP options table
 */

Option::remove('mitgliederbeitraege');
$tourenarten = Option::get('tourenarten');
foreach ($tourenarten as $key => $value) {
    Option::remove($key);
}

Option::remove('tourenarten');


text:
using System;
using System.Threading.Tasks;
using FluentAssertions.Extensions;
using Xunit;
using Xunit.Sdk;

namespace FluentAssertions.Specs.Specialized;

public class TaskCompletionSourceAssertionSpecs
{
#if NET6_0_OR_GREATER

    public class NonGeneric
    {
        [Fact]
        public async Task When_it_completes_in_time_it_should_succeed()
        {
            // Arrange
            var subject = new TaskCompletionSource();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).CompleteWithinAsync(1.Seconds());
            subject.SetResult();
            timer.Complete();

            // Assert
            await action.Should().NotThrowAsync();
        }

        [Fact]
        public async Task When_it_did_not_complete_in_time_it_should_fail()
        {
            // Arrange
            var subject = new TaskCompletionSource();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).CompleteWithinAsync(1.Seconds(), "test {0}", "testArg");
            timer.Complete();

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Expected subject to complete within 1s because test testArg.");
        }

        [Fact]
        public async Task When_it_is_null_it_should_fail()
        {
            // Arrange
            TaskCompletionSource subject = null;

            // Act
            Func<Task> action = () => subject.Should().CompleteWithinAsync(1.Seconds());

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Expected subject to complete within 1s, but found <null>.");
        }

        [Fact]
        public async Task When_it_completes_in_time_and_it_is_not_expected_it_should_fail()
        {
            // Arrange
            var subject = new TaskCompletionSource();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).NotCompleteWithinAsync(1.Seconds(), "test {0}", "testArg");
            subject.SetResult();
            timer.Complete();

            // Assert
            await action.Should().ThrowAsync<XunitException>().WithMessage("*to not complete within*because test testArg*");
        }

        [Fact]
        public async Task When_it_did_not_complete_in_time_and_it_is_not_expected_it_should_succeed()
        {
            // Arrange
            var subject = new TaskCompletionSource();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).NotCompleteWithinAsync(1.Seconds());
            timer.Complete();

            // Assert
            await action.Should().NotThrowAsync();
        }

        [Fact]
        public async Task When_it_is_null_and_we_validate_to_not_complete_it_should_fail()
        {
            // Arrange
            TaskCompletionSource subject = null;

            // Act
            Func<Task> action = () => subject.Should().NotCompleteWithinAsync(1.Seconds(), "test {0}", "testArg");

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Expected subject to not complete within 1s because test testArg, but found <null>.");
        }

        [Fact]
        public async Task When_accidentally_using_equals_it_should_throw_a_helpful_error()
        {
            // Arrange
            var subject = new TaskCompletionSource();

            // Act
            Func<Task> action = () => Task.FromResult(subject.Should().Equals(subject));

            // Assert
            await action.Should().ThrowAsync<NotSupportedException>().WithMessage("Equals is not part of Fluent Assertions. Did you mean CompleteWithinAsync() instead?");
        }
    }
#endif

    public class Generic
    {
        [Fact]
        public async Task When_it_completes_in_time_it_should_succeed()
        {
            // Arrange
            var subject = new TaskCompletionSource<bool>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).CompleteWithinAsync(1.Seconds());
            subject.SetResult(true);
            timer.Complete();

            // Assert
            await action.Should().NotThrowAsync();
        }

        [Fact]
        public async Task When_it_completes_in_time_and_result_is_expected_it_should_succeed()
        {
            // Arrange
            var subject = new TaskCompletionSource<int>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = async () => (await subject.Should(timer).CompleteWithinAsync(1.Seconds())).Which.Should().Be(42);
            subject.SetResult(42);
            timer.Complete();

            // Assert
            await action.Should().NotThrowAsync();
        }

        [Fact]
        public async Task When_it_completes_in_time_and_async_result_is_expected_it_should_succeed()
        {
            // Arrange
            var subject = new TaskCompletionSource<int>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).CompleteWithinAsync(1.Seconds()).WithResult(42);
            subject.SetResult(42);
            timer.Complete();

            // Assert
            await action.Should().NotThrowAsync();
        }

        [Fact]
        public async Task When_it_completes_in_time_and_result_is_not_expected_it_should_fail()
        {
            // Arrange
            var testSubject = new TaskCompletionSource<int>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = async () =>
                (await testSubject.Should(timer).CompleteWithinAsync(1.Seconds())).Which.Should().Be(42);
            testSubject.SetResult(99);
            timer.Complete();

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Expected *testSubject* to be 42, but found 99 (difference of 57).");
        }

        [Fact]
        public async Task When_it_completes_in_time_and_async_result_is_not_expected_it_should_fail()
        {
            // Arrange
            var testSubject = new TaskCompletionSource<int>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => testSubject.Should(timer).CompleteWithinAsync(1.Seconds()).WithResult(42);
            testSubject.SetResult(99);
            timer.Complete();

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Expected testSubject to be 42, but found 99.");
        }

        [Fact]
        public async Task When_it_did_not_complete_in_time_it_should_fail()
        {
            // Arrange
            var subject = new TaskCompletionSource<bool>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).CompleteWithinAsync(1.Seconds(), "test {0}", "testArg");
            timer.Complete();

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Expected subject to complete within 1s because test testArg.");
        }

        [Fact]
        public async Task When_it_is_null_it_should_fail()
        {
            // Arrange
            TaskCompletionSource<bool> subject = null;

            // Act
            Func<Task> action = () => subject.Should().CompleteWithinAsync(1.Seconds());

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Expected subject to complete within 1s, but found <null>.");
        }

        [Fact]
        public async Task When_it_completes_in_time_and_it_is_not_expected_it_should_fail()
        {
            // Arrange
            var subject = new TaskCompletionSource<bool>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).NotCompleteWithinAsync(1.Seconds(), "test {0}", "testArg");
            subject.SetResult(true);
            timer.Complete();

            // Assert
            await action.Should().ThrowAsync<XunitException>().WithMessage("Did not expect*to complete within*because test testArg*");
        }

        [Fact]
        public async Task When_it_did_not_complete_in_time_and_it_is_not_expected_it_should_succeed()
        {
            // Arrange
            var subject = new TaskCompletionSource<bool>();
            var timer = new FakeClock();

            // Act
            Func<Task> action = () => subject.Should(timer).NotCompleteWithinAsync(1.Seconds());
            timer.Complete();

            // Assert
            await action.Should().NotThrowAsync();
        }

        [Fact]
        public async Task When_it_is_null_and_we_validate_to_not_complete_it_should_fail()
        {
            // Arrange
            TaskCompletionSource<bool> subject = null;

            // Act
            Func<Task> action = () => subject.Should().NotCompleteWithinAsync(1.Seconds(), "test {0}", "testArg");

            // Assert
            await action.Should().ThrowAsync<XunitException>()
                .WithMessage("Did not expect subject to complete within 1s because test testArg, but found <null>.");
        }

        [Fact]
        public async Task When_accidentally_using_equals_with_generic_it_should_throw_a_helpful_error()
        {
            // Arrange
            var subject = new TaskCompletionSource<bool>();

            // Act
            Func<Task<bool>> action = () => Task.FromResult(subject.Should().Equals(subject));

            // Assert
            await action.Should().ThrowAsync<NotSupportedException>().WithMessage("Equals is not part of Fluent Assertions. Did you mean CompleteWithinAsync() instead?");
        }
    }
}


text:
/**
 * @file lrsdp.cpp
 * @author Ryan Curtin
 *
 * An implementation of Monteiro and Burer's formulation of low-rank
 * semidefinite programs (LR-SDP).
 *
 * This file is part of mlpack 2.0.1.
 *
 * mlpack is free software; you may redstribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef __MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_IMPL_HPP
#define __MLPACK_CORE_OPTIMIZERS_SDP_LRSDP_IMPL_HPP

#include "lrsdp.hpp"

namespace mlpack {
namespace optimization {

template <typename SDPType>
LRSDP<SDPType>::LRSDP(const size_t numSparseConstraints,
                      const size_t numDenseConstraints,
                      const arma::mat& initialPoint) :
    function(numSparseConstraints, numDenseConstraints, initialPoint),
    augLag(function)
{ }

template <typename SDPType>
double LRSDP<SDPType>::Optimize(arma::mat& coordinates)
{
  augLag.Sigma() = 10;
  augLag.Optimize(coordinates, 1000);

  return augLag.Function().Evaluate(coordinates);
}

} // namespace optimization
} // namespace mlpack

#endif


text:
struct clk {
	struct list_head      list;
	struct module        *owner;
	struct clk           *parent;
	const char           *name;
	int		      id;
	int		      usage;
	unsigned long         rate;
	unsigned long         ctrlbit;

	int		    (*enable)(struct clk *, int enable);
	int		    (*set_rate)(struct clk *c, unsigned long rate);
	unsigned long	    (*get_rate)(struct clk *c);
	unsigned long	    (*round_rate)(struct clk *c, unsigned long rate);
	int		    (*set_parent)(struct clk *c, struct clk *parent);
};

/* other clocks which may be registered by board support */

extern struct clk s3c24xx_dclk0;
extern struct clk s3c24xx_dclk1;
extern struct clk s3c24xx_clkout0;
extern struct clk s3c24xx_clkout1;
extern struct clk s3c24xx_uclk;

extern struct clk clk_usb_bus;

/* core clock support */

extern struct clk clk_f;
extern struct clk clk_h;
extern struct clk clk_p;
extern struct clk clk_mpll;
extern struct clk clk_upll;
extern struct clk clk_xtal;

/* exports for arch/arm/mach-s3c2410
 *
 * Please DO NOT use these outside of arch/arm/mach-s3c2410
*/

extern struct mutex clocks_mutex;

extern int s3c2410_clkcon_enable(struct clk *clk, int enable);

extern int s3c24xx_register_clock(struct clk *clk);
extern int s3c24xx_register_clocks(struct clk **clk, int nr_clks);

extern int s3c24xx_setup_clocks(unsigned long xtal,
				unsigned long fclk,
				unsigned long hclk,
				unsigned long pclk);


text:
var MovieAppRouter = Backbone.Router.extend({
	initialize: function(params) {
		this.model = new MovieAppModel();
		this.view = new MovieAppView({model: this.model});
		params.append_at.append(this.view.render().el);
	},

	routes: {
		"movies/add": "add",
		"movies/remove/:number": "remove"
	},

	add: function() {
		app.model.movies.add(
			new Movie({
				title: 'The Matrix ' + Math.floor(Math.random()*11),
				format: 'dvd'
			})
		);
		this.navigate(); // reset location so we can trigger again
	},

	remove: function(cid) {
		app.model.movies.remove(app.model.movies.getByCid(cid));
	}
});


text:
kubectl -n kube-system delete svc kube-dns
kubectl -n kube-system delete sa kube-dns
kubectl -n kube-system delete cm kube-dns
kubectl -n kube-system delete deployment kube-dns


text:
package org.springframework.cloud.netflix.zuul.filters.pre;

import javax.servlet.http.HttpServletRequest;

import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.DEBUG_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * Pre {@link ZuulFilter} that sets {@link RequestContext} debug attributes to true if the
 * "debug" request parameter is set.
 *
 * @author Spencer Gibb
 */
public class DebugFilter extends ZuulFilter {

	private static final DynamicBooleanProperty ROUTING_DEBUG = DynamicPropertyFactory
			.getInstance().getBooleanProperty(ZuulConstants.ZUUL_DEBUG_REQUEST, false);

	private static final DynamicStringProperty DEBUG_PARAMETER = DynamicPropertyFactory
			.getInstance().getStringProperty(ZuulConstants.ZUUL_DEBUG_PARAMETER, "debug");

	@Override
	public String filterType() {
		return PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return DEBUG_FILTER_ORDER;
	}

	@Override
	public boolean shouldFilter() {
		HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
		if ("true".equals(request.getParameter(DEBUG_PARAMETER.get()))) {
			return true;
		}
		return ROUTING_DEBUG.get();
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		ctx.setDebugRouting(true);
		ctx.setDebugRequest(true);
		return null;
	}

}


text:
require 'test_helper'

class IntegrationTest < Test::Unit::TestCase

  def setup
    Factory.define :user, :class => 'user' do |f|
      f.first_name 'Jimi'
      f.last_name  'Hendrix'
      f.admin       false
      f.email {|a| "#{a.first_name}.#{a.last_name}@example.com".downcase }
    end

    Factory.define Post, :default_strategy => :attributes_for do |f|
      f.name   'Test Post'
      f.association :author, :factory => :user
    end

    Factory.define :admin, :class => User do |f|
      f.first_name 'Ben'
      f.last_name  'Stein'
      f.admin       true
      f.sequence(:username) { |n| "username#{n}" }
      f.email { Factory.next(:email) }
    end

    Factory.define :guest, :parent => :user do |f|
      f.last_name 'Anonymous'
      f.username  'GuestUser'
    end

    Factory.sequence :email do |n|
      "somebody#{n}@example.com"
    end
  end

  def teardown
    Factory.factories.clear
  end

  context "a generated attributes hash" do

    setup do
      @attrs = Factory.attributes_for(:user, :first_name => 'Bill')
    end

    should "assign all attributes" do
      assert_equal [:admin, :email, :first_name, :last_name],
                   @attrs.keys.sort {|a, b| a.to_s <=> b.to_s }
    end

    should "correctly assign lazy, dependent attributes" do
      assert_equal "bill.hendrix@example.com", @attrs[:email]
    end

    should "override attrbutes" do
      assert_equal 'Bill', @attrs[:first_name]
    end

    should "not assign associations" do
      assert_nil Factory.attributes_for(:post)[:author]
    end

  end

  context "a built instance" do

    setup do
      @instance = Factory.build(:post)
    end

    should "not be saved" do
      assert @instance.new_record?
    end

    should "assign associations" do
      assert_kind_of User, @instance.author
    end

    should "save associations" do
      assert !@instance.author.new_record?
    end

    should "not assign both an association and its foreign key" do
      assert_equal 1, Factory.build(:post, :author_id => 1).author_id
    end

  end

  context "a created instance" do

    setup do
      @instance = Factory.create('post')
    end

    should "be saved" do
      assert !@instance.new_record?
    end

    should "assign associations" do
      assert_kind_of User, @instance.author
    end

    should "save associations" do
      assert !@instance.author.new_record?
    end

  end

  context "a generated mock instance" do

    setup do
      @stub = Factory.stub(:user, :first_name => 'Bill')
    end

    should "assign all attributes" do
      [:admin, :email, :first_name, :last_name].each do |attr|
        assert_not_nil @stub.send(attr)
      end
    end

    should "correctly assign lazy, dependent attributes" do
      assert_equal "bill.hendrix@example.com", @stub.email
    end

    should "override attrbutes" do
      assert_equal 'Bill', @stub.first_name
    end

    should "not assign associations" do
      assert_nil Factory.stub(:post).author
    end

  end

  context "an instance generated by a factory with a custom class name" do

    setup do
      @instance = Factory.create(:admin)
    end

    should "use the correct class name" do
      assert_kind_of User, @instance
    end

    should "use the correct factory definition" do
      assert @instance.admin?
    end

  end

  context "an instance generated by a factory that inherits from another factory" do
    setup do
      @instance = Factory.create(:guest)
    end

    should "use the class name of the parent factory" do
      assert_kind_of User, @instance
    end

    should "have attributes of the parent" do
      assert_equal 'Jimi', @instance.first_name
    end

    should "have attributes defined in the factory itself" do
      assert_equal 'GuestUser', @instance.username
    end

    should "have attributes that have been overriden" do
      assert_equal 'Anonymous', @instance.last_name
    end
  end

  context "an attribute generated by a sequence" do

    setup do
      @email = Factory.attributes_for(:admin)[:email]
    end

    should "match the correct format" do
      assert_match /^somebody\d+@example\.com$/, @email
    end

    context "after the attribute has already been generated once" do

      setup do
        @another_email = Factory.attributes_for(:admin)[:email]
      end

      should "match the correct format" do
        assert_match /^somebody\d+@example\.com$/, @email
      end

      should "not be the same as the first generated value" do
        assert_not_equal @email, @another_email
      end

    end

  end

  context "an attribute generated by an in-line sequence" do

    setup do
      @username = Factory.attributes_for(:admin)[:username]
    end

    should "match the correct format" do
      assert_match /^username\d+$/, @username
    end

    context "after the attribute has already been generated once" do

      setup do
        @another_username = Factory.attributes_for(:admin)[:username]
      end

      should "match the correct format" do
        assert_match /^username\d+$/, @username
      end

      should "not be the same as the first generated value" do
        assert_not_equal @username, @another_username
      end

    end

  end

  context "a factory with a default strategy specified" do
    should "generate instances according to the strategy" do
      assert_kind_of Hash, Factory(:post)
    end
  end

end


text:
import { OnInit } from "@angular/core";
import { Item } from "./item";
import { ItemService } from "./item.service";
export declare class ItemsComponent implements OnInit {
    private itemService;
    items: Item[];
    constructor(itemService: ItemService);
    ngOnInit(): void;
}


text:
import observableModule = require("data/observable");
import pagesModule = require("ui/page");
import model = require("./model");
import labelModule = require("ui/label");
import listPickerModule = require("ui/list-picker");
import datePickerModule = require("ui/date-picker");
import timePickerModule = require("ui/time-picker");

var viewModel: model.WebViewModel;
var page: pagesModule.Page;
var label: labelModule.Label;
var listPicker: listPickerModule.ListPicker;
var datePicker: datePickerModule.DatePicker;
var timePicker: timePickerModule.TimePicker;

export function onPageLoaded(args: observableModule.EventData) {
    viewModel = new model.WebViewModel();
    page = <pagesModule.Page>args.object;
    page.bindingContext = viewModel;

    label = page.getViewById<labelModule.Label>("label");
    listPicker = page.getViewById<listPickerModule.ListPicker>("listPicker");
    datePicker = page.getViewById<datePickerModule.DatePicker>("datePicker");
    timePicker = page.getViewById<timePickerModule.TimePicker>("timePicker");

    viewModel.items = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    viewModel.selectedIndex = 5;

    viewModel.day = 9;
    viewModel.month = 2;
    viewModel.year = 1980;

    viewModel.hour = 17;
    viewModel.minute = 50;
}

export function onTap(args: observableModule.EventData) {
    console.log("onTap");

    viewModel.items = ["Male", "Female"];
    viewModel.selectedIndex = 1;

    viewModel.day = viewModel.day + 1;
    viewModel.month = viewModel.month + 1;
    viewModel.year = viewModel.year + 1;

    viewModel.hour = viewModel.hour + 1;
    viewModel.minute = viewModel.minute + 1;
}


text:
export interface Form {
	[ key: string ]: any
}

export class FormData {

	private name: string;
	private value: string;

	constructor ( name: string = "", value: string = "" ) {
		this.name = name;
		this.value = value;
	}

	public getName (): string {
		return this.name;
	}
	public setName ( name: string ): FormData {
		this.name = name;
		return this;
	}

	public getValue (): string {
		return this.value;
	}
	public setValue ( value: string ): FormData {
		this.value = value;
		return this;
	}

	public build (): Form {
		let formData: Form;
		formData[ this.getName() ] = this.getValue();
		return formData;
	}
}