text:
"""
@author: Ryuichi Takanobu
@e-mail: gxly15@mails.tsinghua.edu.cn; truthless11@gmail.com
"""
import numpy as np
from parse import FLAGS

def similarity(A, B):
    return np.dot(A, B) / (np.linalg.norm(A) * np.linalg.norm(B))

def HSMI(batch_obs, action_list):
    val, cnt, precluster, cluster = .0, 0, None, None
    for idx, obs in enumerate(batch_obs):
        if idx > 0:
            if action_list[idx] != action_list[idx-1]:
                cnt += 1
                if precluster is not None:
                    val += similarity(np.mean(cluster, axis=0), np.mean(precluster, axis=0))
                precluster = cluster
                cluster = np.array([obs])
            else:
                cluster = np.vstack([cluster, obs])
        else:
            cluster = np.array([obs])
    if precluster is not None:  # last cluster
        val += similarity(np.mean(cluster, axis=0), np.mean(precluster, axis=0))
    return -val / cnt if cnt > 0 else .0

def determine(model, batch_obs, keywords, labels):
    cluster, reward = np.zeros([1, FLAGS.embed_units]), .0
    for idx, obs in enumerate(batch_obs):
        full_obs = np.hstack([obs, np.mean(cluster, axis=0)])
        action = labels[idx]
        cluster = np.vstack([cluster, obs]) if idx > 0 and action == model.ep_as[0][-1] else np.array([obs])
        reward += FLAGS.continuity * (int(model.ep_as[0][-1] == action) - int(model.ep_as[0][-1] != action)) * similarity(batch_obs[idx-1], obs) if idx > 1 else 0
        reward += FLAGS.keyword * keywords[idx][1] if keywords[idx][0] == action else 0
        if idx == len(keywords) - 1:
            reward /= idx + 1
            full_actions = model.ep_as[0] + [action]
            reward += HSMI(batch_obs, full_actions)
        model.store_transition(full_obs, action, 0)
    return reward

def pretrain_pn(model, sess, observations, batch_sizes, keywords, labels):
    st, ed, cnt, loss, ep_rs_total = 0, 0, 0, .0, .0
    while ed < len(keywords):
        st, ed, cnt = ed, ed+batch_sizes[cnt], cnt+1
        reward = determine(model, observations[st:ed], keywords[st:ed], labels[st:ed])
        loss += model.prelearn(sess, reward, FLAGS.keep_prob)
        ep_rs_total += reward
    sess.run(model.epoch_add_op)
    return loss / len(keywords), ep_rs_total / len(keywords), labels

def explore(model, sess, batch_obs, keywords):
    reward = [.0] * FLAGS.sample_round
    for n_round in range(FLAGS.sample_round):
        prev_act, cluster = np.zeros(FLAGS.labels, dtype=np.int), np.zeros([1, FLAGS.embed_units])
        for idx, obs in enumerate(batch_obs):
            full_obs = np.hstack([obs, np.mean(cluster, axis=0)])
            action = model.choose_action(sess, full_obs, prev_act, True)
            prev_act = np.eye(FLAGS.labels, dtype=np.int)[action]
            cluster = np.vstack([cluster, obs]) if idx > 0 and action == model.ep_as[n_round][-1] else np.array([obs])
            reward[n_round] += FLAGS.continuity * (int(model.ep_as[n_round][-1] == action) - int(model.ep_as[n_round][-1] != action)) * similarity(batch_obs[idx-1], obs) if idx > 1 else 0
            reward[n_round] += FLAGS.keyword * keywords[idx][1] if keywords[idx][0] == action else 0
            if idx == len(keywords) - 1:
                reward[n_round] /= idx + 1
                full_actions = model.ep_as[n_round] + [action]
                reward[n_round] += HSMI(batch_obs, full_actions)
            model.store_transition(full_obs, action, n_round)
    return reward

def train_pn(model, sess, observations, batch_sizes, keywords):
    st, ed, cnt, loss, ep_rs_total, labels = 0, 0, 0, .0, .0, np.zeros(len(keywords), dtype=np.int)
    while ed < len(keywords):
        st, ed, cnt = ed, ed+batch_sizes[cnt], cnt+1
        reward = explore(model, sess, observations[st:ed], keywords[st:ed])
        labels[st:ed] = model.ep_as[0]
        ep_rs_total += np.sum(reward) / FLAGS.sample_round
        loss += model.learn(sess, reward, FLAGS.keep_prob)
    sess.run(model.epoch_add_op)
    return loss / len(keywords), ep_rs_total / len(keywords), labels

def exploit(model, sess, batch_obs, keywords):
    prev_act, cluster, reward = np.zeros(FLAGS.labels, dtype=np.int), np.zeros([1, FLAGS.embed_units]), .0
    for idx, obs in enumerate(batch_obs):
        full_obs = np.hstack([obs, np.mean(cluster, axis=0)])
        action = model.choose_action(sess, full_obs, prev_act, False)
        prev_act = np.eye(FLAGS.labels, dtype=np.int)[action]
        cluster = np.vstack([cluster, obs]) if idx > 0 and action == model.ep_as[0][-1] else np.array([obs])
        reward += FLAGS.continuity * (int(model.ep_as[0][-1] == action) - int(model.ep_as[0][-1] != action)) * similarity(batch_obs[idx-1], obs) if idx > 1 else 0
        reward += FLAGS.keyword * keywords[idx][1] if keywords[idx][0] == action else 0
        if idx == len(keywords) - 1:
            reward /= idx + 1
            full_actions = model.ep_as[0] + [action]
            reward += HSMI(batch_obs, full_actions)
        model.store_transition(full_obs, action, 0)
    return reward

def develop_pn(model, sess, observations, batch_sizes, keywords):
    st, ed, cnt, loss, ep_rs_total, labels = 0, 0, 0, .0, .0, np.zeros(len(keywords), dtype=np.int)
    while ed < len(keywords):
        st, ed, cnt = ed, ed+batch_sizes[cnt], cnt+1
        reward = exploit(model, sess, observations[st:ed], keywords[st:ed])
        labels[st:ed] = model.ep_as[0]
        loss += model.verify(sess, reward)
        ep_rs_total += reward
    return loss / len(keywords), ep_rs_total / len(keywords), labels

def test(model, sess, batch_obs):
    prev_act, cluster = np.zeros(FLAGS.labels, dtype=np.int), np.zeros([1, FLAGS.embed_units])
    for idx, obs in enumerate(batch_obs):
        full_obs = np.hstack([obs, np.mean(cluster, axis=0)])
        action = model.choose_action(sess, full_obs, prev_act, False)
        prev_act = np.eye(FLAGS.labels, dtype=np.int)[action]
        cluster = np.vstack([cluster, obs]) if idx > 0 and action == model.ep_as[0][-1] else np.array([obs])
        model.store_transition(full_obs, action, 0)

def evaluate_pn(model, sess, observations, batch_sizes, keywords, labels):
    st, ed, cnt, acc = 0, 0, 0, .0
    while ed < len(keywords):
        st, ed, cnt = ed, ed+batch_sizes[cnt], cnt+1
        test(model, sess, observations[st:ed])
        acc += np.sum(np.equal(model.ep_as[0], labels[st:ed]))
        model.clean()
    return acc / len(keywords)

def inference_pn(model, sess, observations, batch_sizes, keywords, part):
    st, ed, cnt = 0, 0, 0
    predicted_labels = np.zeros(len(keywords), np.int)
    while ed < len(keywords):
        st, ed, cnt = ed, ed+batch_sizes[cnt], cnt+1
        exploit(model, sess, observations[st:ed], keywords[st:ed])
        predicted_labels[st:ed] = model.ep_as[0]
        model.clean()
    np.savetxt(FLAGS.train_dir_pn+'/labels_'+part, predicted_labels, fmt='%d')
    return predicted_labels


text:
require 'test/unit'

class DynamicSnippetTest < Test::Unit::TestCase
  # Replace this with your real tests.
  def test_this_plugin
    # FIXME -- flunk
  end
end

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.Owin.Security.Authorization;

namespace Umbraco.RestApi.Security
{
    /// <summary>
    /// An AuthZ requirement for validating that the user has permission for a media item
    /// </summary>
    public class MediaPermissionRequirement : IAuthorizationRequirement
    {
    }
}


text:
function filter = create_gmus_filter(R, C, u)

nscale = 5;

filter = zeros(R,C);

for v = 0:4
    filter = filter + LogGaborWavelet( R, C, u, v); % Create the Gabor filter
end

filter = filter ./ nscale;

% save(['filters\gmus_filter_u' num2str(u)], 'filter');


text:
package org.bidtime.dbutils.data;

public enum PropAdapt {
	NULL, NOTNULL, FULL
}


text:
import {Component} from '@angular/core';

/**
 * @title Testing with MatProgressSpinnerHarness
 */
@Component({
  selector: 'progress-spinner-harness-example',
  templateUrl: 'progress-spinner-harness-example.html',
})
export class ProgressSpinnerHarnessExample {
  value: number;
}


text:
<!DOCTYPE html>

    <title>CSS Test (Transforms): rotateX(180deg) scaleZ(-1)</title>
    <link rel="author" title="Matt Woodrow" href="mailto:mwoodrow@mozilla.com">
    <link rel="author" title="Aryeh Gregor" href="mailto:ayg@aryeh.name">
    <link rel="help" href="http://www.w3.org/TR/css-transforms-2/#three-d-transform-functions">
    <meta name="assert" content="This tests that rotateX(180deg) scaleZ(-1) is
    the same as scaleY(-1).  (The scaleZ(-1) should have no effect here.)">
    <link rel="match" href="transform3d-scale-007-ref.html">
    <link rel="mismatch" href="transform3d-scale-001-notref.html">


text:
package com.github.jekinchen.flatjni;

import java.nio.*;
import java.lang.*;
import java.util.*;
import android.support.annotation.Nullable;
import com.google.flatbuffers.*;

@SuppressWarnings("unused")
public final class SumParam extends Table {
  public static SumParam getRootAsSumParam(ByteBuffer _bb) { return getRootAsSumParam(_bb, new SumParam()); }
  public static SumParam getRootAsSumParam(ByteBuffer _bb, SumParam obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
  public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; }
  public SumParam __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }

  public int i() { int o = __offset(4); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
  public int j() { int o = __offset(6); return o != 0 ? bb.getInt(o + bb_pos) : 0; }

  public static int createSumParam(FlatBufferBuilder builder,
      int i,
      int j) {
    builder.startObject(2);
    SumParam.addJ(builder, j);
    SumParam.addI(builder, i);
    return SumParam.endSumParam(builder);
  }

  public static void startSumParam(FlatBufferBuilder builder) { builder.startObject(2); }
  public static void addI(FlatBufferBuilder builder, int i) { builder.addInt(0, i, 0); }
  public static void addJ(FlatBufferBuilder builder, int j) { builder.addInt(1, j, 0); }
  public static int endSumParam(FlatBufferBuilder builder) {
    int o = builder.endObject();
    return o;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="black3">#ff999999</color>
    <color name="bg_gray">#ffd6d6d6</color>
    <color name="abs__background_holo_light">#fff3f3f3</color>
    <color name="abs__background_holo_dark">#ff000000</color>
    <color name="abs__bright_foreground_holo_dark">@color/abs__background_holo_light</color>
</resources>


text:
package com.sample;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class ProcessMain {

	public static void main(String[] args) throws Exception {

		KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();

	    KieSession ksession2 = kc.newKieSession("sample-process-rules");

		Account account = new Account();
        account.setMoney(0);
		ksession2.insert(account);
		ksession2.startProcess("com.sample.HelloWorld");
		ksession2.fireAllRules();

	}

}


text:
#import \"ViewController.h\"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [self becomeFirstResponder];
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if(event.type  ==  UIEventSubtypeMotionShake)
    {
        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@\"%@/whip.mp3\", [[NSBundle mainBundle] resourcePath]]];

        NSError *error;
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        player.numberOfLoops = 0;
        [player play];

	}
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

@end


text:
PLWeakCompatibility
===================

Do you like ARC but need to support older OSes? Do you contemplate dropping support for Mac OS X 10.6 or iOS 4 just so you can use `__weak`? Good news! Now you can use `__weak` on those older OSes by just dropping a file into your project and adding a couple of compiler flags.

`PLWeakCompatibility` is a set of stubs that implement the Objective-C runtime functions the compiler uses to make `__weak` work. It automatically calls through to the real runtime functions if they're present (i.e. your app is running on iOS5+ or Mac OS X 10.7+) and uses its own implementation if they're not.

To use `PLWeakCompatibility`:

1. Drop `PLWeakCompatibilityStubs.m` into your project.
2. Add these flags to your Other C Flags in your Xcode target settings: `-Xclang -fobjc-runtime-has-weak`.
3. There is no step 3!

Note that, by default, `PLWeakCompatibility` uses `MAZeroingWeakRef` to handle `__weak` *if* `MAZeroingWeakRef` is present. If not, it uses its own, less sophisticated, internal implementation. If you are already using `MAZeroingWeakRef`, then `PLWeakCompatibility` will take advantage of it. If you're not, you don't need it. There is nothing you need to do to enable the use of `MAZeroingWeakRef`, it will simply be used if it's in your project.

Implementation Notes
--------------------

The built-in weak reference implementation is basic but serviceable. It works by swizzling out `-release` and `-dealloc` on target classes directly. This means that every instance of any weakly referenced class takes a performance hit for those operations, even for instances which are not themselves weakly referenced.

This swizzling *should* be benign, but as with all things runtime manipulation, problems may occur. In particular, I do not anticipate weak references to bridged CoreFoundation objects working at all, and there may be conflicts with Key-Value Observing. The good news is that, since the `PLWeakCompatibility` implementation is only active on older OSes, you have stable targets to test against, and can know that future updates won't affect compatibility.

Compatibility Notes
-------------------

`PLWeakCompatibility` *should* be fully compatible with any OS/architecture/compiler combination which supports ARC. Since the calls are generated at compile time, and the stubs simply call through to Apple's implementations when available, it's extremely unlikely that a future OS update will break an app that uses `PLWeakCompatibility`. All of the tricky business happens on OSes which will not receive further updates.

It is possible that a future version of Xcode will include a compiler which does not get along with these stubs. We consider this possibility to be unlikely, but it's possible in theory. If it does happen, you may continue to build using an old compiler for as long as you support iOS 4 or Mac OS 10.6, and we also hope to be able to fix up any incompatibilities in the unlikely event that this occurs.


text:
package com.miguelbcr.ui.rx_paparazzo2.interactors;

import io.reactivex.Observable;

abstract class UseCase<D> {
  abstract Observable<D> react();
}


text:
@extends('layout')

@section('seo')
<title>{{ trans('layout.title_register') }}</title>
@stop

@section('content')

                    {{ trans('layout.title_register') }}

                        <form class="login-form mt-lg" method="POST" action="{{ url('/auth/register') }}">
                        {!! csrf_field() !!}

                            {{ trans('layout.label_username') }}
                            <input class="form-control" type="text" name="name" id="registerName" value="{{ old('name') }}">
                            {{ $errors->first('name') }}

                            {{ trans('layout.label_email') }}
                            <input class="form-control" type="email" name="email" id="registerEmail" value="{{ old('email') }}">
                            {{ $errors->first('email') }}

                            {{ trans('layout.label_password') }}
                            <input class="form-control" type="password" name="password" id="registerPassword">
                            {{ $errors->first('password') }}

                            {{ trans('layout.label_confirmpassword') }}
                            <input class="form-control" type="password" name="password_confirmation"  id="registerPassword2">

                            <button class="btn btn-primary" type="submit">{{ trans('layout.btn_register') }}</button>

                        </form>

@stop


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkRenderPassWrap.h"
#include "vtkCameraPassWrap.h"
#include "vtkObjectWrap.h"
#include "vtkWindowWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkCameraPassWrap::ptpl;

VtkCameraPassWrap::VtkCameraPassWrap()
{ }

VtkCameraPassWrap::VtkCameraPassWrap(vtkSmartPointer<vtkCameraPass> _native)
{ native = _native; }

VtkCameraPassWrap::~VtkCameraPassWrap()
{ }

void VtkCameraPassWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkCameraPass").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("CameraPass").ToLocalChecked(), ConstructorGetter);
}

void VtkCameraPassWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkCameraPassWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkRenderPassWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkRenderPassWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkCameraPassWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "GetAspectRatioOverride", GetAspectRatioOverride);
	Nan::SetPrototypeMethod(tpl, "getAspectRatioOverride", GetAspectRatioOverride);

	Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
	Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);

	Nan::SetPrototypeMethod(tpl, "GetDelegatePass", GetDelegatePass);
	Nan::SetPrototypeMethod(tpl, "getDelegatePass", GetDelegatePass);

	Nan::SetPrototypeMethod(tpl, "IsA", IsA);
	Nan::SetPrototypeMethod(tpl, "isA", IsA);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "ReleaseGraphicsResources", ReleaseGraphicsResources);
	Nan::SetPrototypeMethod(tpl, "releaseGraphicsResources", ReleaseGraphicsResources);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

	Nan::SetPrototypeMethod(tpl, "SetAspectRatioOverride", SetAspectRatioOverride);
	Nan::SetPrototypeMethod(tpl, "setAspectRatioOverride", SetAspectRatioOverride);

	Nan::SetPrototypeMethod(tpl, "SetDelegatePass", SetDelegatePass);
	Nan::SetPrototypeMethod(tpl, "setDelegatePass", SetDelegatePass);

#ifdef VTK_NODE_PLUS_VTKCAMERAPASSWRAP_INITPTPL
	VTK_NODE_PLUS_VTKCAMERAPASSWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkCameraPassWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		vtkSmartPointer<vtkCameraPass> native = vtkSmartPointer<vtkCameraPass>::New();
		VtkCameraPassWrap* obj = new VtkCameraPassWrap(native);
		obj->Wrap(info.This());
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkCameraPassWrap::GetAspectRatioOverride(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	double r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetAspectRatioOverride();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkCameraPassWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetClassName();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkCameraPassWrap::GetDelegatePass(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	vtkRenderPass * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetDelegatePass();
	VtkRenderPassWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkRenderPassWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkRenderPassWrap *w = new VtkRenderPassWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkCameraPassWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->IsA(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkCameraPassWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	vtkCameraPass * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkCameraPassWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkCameraPassWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkCameraPassWrap *w = new VtkCameraPassWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkCameraPassWrap::ReleaseGraphicsResources(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkWindowWrap::ptpl))->HasInstance(info[0]))
	{
		VtkWindowWrap *a0 = ObjectWrap::Unwrap<VtkWindowWrap>(info[0]->ToObject());
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->ReleaseGraphicsResources(
			(vtkWindow *) a0->native.GetPointer()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkCameraPassWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
		vtkCameraPass * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObject *) a0->native.GetPointer()
		);
		VtkCameraPassWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkCameraPassWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkCameraPassWrap *w = new VtkCameraPassWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkCameraPassWrap::SetAspectRatioOverride(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsNumber())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetAspectRatioOverride(
			info[0]->NumberValue()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkCameraPassWrap::SetDelegatePass(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkCameraPassWrap *wrapper = ObjectWrap::Unwrap<VtkCameraPassWrap>(info.Holder());
	vtkCameraPass *native = (vtkCameraPass *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkRenderPassWrap::ptpl))->HasInstance(info[0]))
	{
		VtkRenderPassWrap *a0 = ObjectWrap::Unwrap<VtkRenderPassWrap>(info[0]->ToObject());
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetDelegatePass(
			(vtkRenderPass *) a0->native.GetPointer()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}


text:
```
docker build -t nginx .
```

#Create folder
```
mkdir -p /data/nginx/conf/sites-enabled
mkdir -p /data/nginx/conf/certs
mkdir -p /data/nginx/conf/conf.d
mkdir -p /data/var/log/nginx
mkdir -p /data/web/
cp config_default /data/nginx/conf/sites-enabled/default
touch /data/web/index.html
echo '123' > /data/web/index.html
```
#Create docker container
```
docker run --name test-nginx -it -d  \
-v /data/nginx/conf/sites-enabled:/etc/nginx/sites-enabled \
-v /data/nginx/conf/certs:/etc/nginx/certs \
-v /data/nginx/conf/conf.d:/etc/nginx/conf.d \
-v /data/var/log/nginx:/var/log/nginx \
-v /data/web:/data/web \
-p 8080:80 \
-p 8443:443 \
--dns 172.17.0.1 \
--restart always \
nginx
```


text:
namespace BugLogger.Api.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using AutoMapper;
    using BugLogger.Api.Infrastructure;
    using BugLogger.Models;

    public class BugResponcseModel : IMapFrom<Bug>, IHaveCustomMappings
    {
        [Required]
        [MaxLength(100)]
        public string Text { get; set; }

        [Required]
        [Range(typeof(DateTime), "1/1/2015", "31/12/2050")]
        public DateTime Logged { get; set; }

        public string BugStatus { get; set; }

        public void CreateMappings(IConfiguration config)
        {
            config.CreateMap<Bug, BugResponcseModel>()
                .ForMember(s => s.BugStatus, opts => opts.MapFrom(s => s.BugStatus.ToString()));
        }
    }
}


text:
<!doctype html>

    <meta charset="utf-8">

<title>Big Data Hadoop MapReduce - Daniel Tech Blog</title>
<meta name="description" content="">

<meta property="og:type" content="article">
<meta property="og:locale" content="en_US">
<meta property="og:site_name" content="Daniel Tech Blog">
<meta property="og:title" content="Big Data Hadoop MapReduce">
<meta property="og:url" content="http://localhost:4001/notes/10Hours-Big-Data-Hadoop-MapReduce/">

  <meta property="og:description" content="">

  <meta property="article:published_time" content="2018-11-04T00:00:00+11:00">

<link rel="canonical" href="http://localhost:4001/notes/10Hours-Big-Data-Hadoop-MapReduce/">

<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Daniel Tech Blog Feed">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/assets/css/main.css">

        Daniel Tech Blog

              Algorithm

              System Design

              Mathematics

              Security

              Notes

              书单

        <button class="search__toggle" type="button">
          Toggle search
          <svg class="icon" width="16" height="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15.99 16">
            <path d="M15.5,13.12L13.19,10.8a1.69,1.69,0,0,0-1.28-.55l-0.06-.06A6.5,6.5,0,0,0,5.77,0,6.5,6.5,0,0,0,2.46,11.59a6.47,6.47,0,0,0,7.74.26l0.05,0.05a1.65,1.65,0,0,0,.5,1.24l2.38,2.38A1.68,1.68,0,0,0,15.5,13.12ZM6.4,2A4.41,4.41,0,1,1,2,6.4,4.43,4.43,0,0,1,6.4,2Z" transform="translate(-.01)"></path>
          </svg>
        </button>

        <button class="greedy-nav__toggle hidden" type="button">
          Toggle menu

        </button>

    <meta itemprop="headline" content="Big Data Hadoop MapReduce">
    <meta itemprop="description" content="">
    <meta itemprop="datePublished" content="November 04, 2018">

Big Data Hadoop MapReduce

Kanye West - POWER

     Categories:

      notes

 Updated: <time datetime="2018-11-04T00:00:00+11:00">November 04, 2018</time>

      Previous

      Next

<input type="text" id="search" class="search-input" tabindex="-1" placeholder="Enter your search term..." />

Follow:

 Feed

© 2019 Daniel Zhang. Powered by Jekyll & Minimal Mistakes.

Please enable JavaScript to view the comments powered by Disqus.


text:
package org.wso2.siddhi.query.api.query.input;

import org.wso2.siddhi.query.api.definition.AbstractDefinition;
import org.wso2.siddhi.query.api.definition.StreamDefinition;
import org.wso2.siddhi.query.api.definition.TableDefinition;
import org.wso2.siddhi.query.api.exception.SourceNotExistException;
import org.wso2.siddhi.query.api.query.QueryEventSource;
import org.wso2.siddhi.query.api.query.input.handler.Filter;
import org.wso2.siddhi.query.api.query.input.handler.Transformer;
import org.wso2.siddhi.query.api.query.input.handler.Window;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

public class WindowStream implements SingleStream {

    protected String streamId;
    protected StreamDefinition streamDefinition;
    protected String streamReferenceId;
    protected Filter filter = null;
    protected Window window = null;
    protected Transformer transformer = null;
    protected QueryEventSource queryEventSource = null;

    public WindowStream(BasicStream basicStream, Window window) {
        this.streamId = basicStream.getStreamId();
        this.streamDefinition = (StreamDefinition) basicStream.getDefinition();
        this.streamReferenceId = basicStream.getStreamReferenceId();
        this.filter = basicStream.getFilter();
        this.transformer = basicStream.getTransformer();
        this.window = window;
    }

    public StreamDefinition getStreamDefinition() {
        return streamDefinition;
    }

    public void setStreamDefinition(StreamDefinition streamDefinition) {
        this.streamDefinition = streamDefinition;
    }

    public String getStreamId() {
        return streamId;
    }

    public String getStreamReferenceId() {
        return streamReferenceId;
    }

    public WindowStream setStreamReferenceId(String streamReferenceId) {
        this.streamReferenceId = streamReferenceId;
        return this;
    }

    @Override
    public List<String> getStreamIds() {
        List<String> list = new ArrayList<String>();
        list.add(streamId);
        return list;
    }

    @Override
    public List<QueryEventSource> constructQueryEventSourceList(
            ConcurrentMap<String, AbstractDefinition> streamTableDefinitionMap,
            List<QueryEventSource> queryEventSources) {
        AbstractDefinition definition = streamTableDefinitionMap.get(streamId);
        if (definition == null) {
            throw new SourceNotExistException("Stream definition not exist! No steam defined with stream ID: " + streamId);
        }
        if (definition instanceof TableDefinition) {
            throw new SourceNotExistException(streamId + " is not a Stream but a Table, and it cant have window");
        }
        streamDefinition = (StreamDefinition) definition;
        queryEventSource = new QueryEventSource(streamId, streamReferenceId,
                                                streamDefinition,
                                                filter, transformer, window);

        queryEventSources.add(queryEventSource);
        return queryEventSources;
    }

    public Filter getFilter() {
        return filter;
    }

    @Override
    public QueryEventSource getQueryEventSource() {
        return queryEventSource;
    }

    public Window getWindow() {
        return window;
    }

    public Transformer getTransformer() {
        return transformer;
    }
}


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx_hal.h"
#include "stm32l1xx.h"
#include "stm32l1xx_it.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/

/******************************************************************************/
/*            Cortex-M3 Processor Interruption and Exception Handlers         */
/******************************************************************************/

/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  HAL_SYSTICK_IRQHandler();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32L1xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32l1xx.s).                    */
/******************************************************************************/

/* USER CODE BEGIN 1 */

//ISR for USART-1
extern UART_HandleTypeDef huart1;

void USART1_IRQHandler(void)             //refer startup_stm32l100xc.s for list of pre-defined interrupt handlers
{
  HAL_UART_IRQHandler(&huart1);          //interrupt routine for UART
}
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
#include <Scene.h>
#include <Components/Transform.h>
#include <Components/Mesh.h>
#include <Components/Alarm.h>
#include <Entity/Entity.h>

#include "Bullet.h"
#include "Components/Bullet.h"

namespace Spectacle
{
	Gunship::Entity CreateBullet( Gunship::Scene& scene,
	                              Gunship::Vector3 position,
	                              Gunship::Vector3 direction )
	{
		Gunship::Entity bullet = scene.entities().Create();
/*
		Gunship::Components::Transform::Handle bulletTransform =
			bullet.assign< Gunship::Components::Transform >(
				scene,
				position,
				Gunship::Quaternion::IDENTITY,
				Gunship::Vector3( 0.25f, 0.25f, 0.25f ) );
		bullet.assign< Bullet >( direction.normalisedCopy(), 25.0f );
		bullet.assign< Gunship::Components::Mesh >( scene, bulletTransform, "Cube.mesh" );
		bullet.assign< Gunship::Components::Alarm >(
			0.5f,
			[]( Gunship::Scene& scene, Gunship::Entity entity )
			{
				entity.destroy();
			} );
*/
		return bullet;
	}
}


text:
import logging

import oauth2

import requests
import factual.common.session

class Session(factual.common.session.BaseSession):
	_url_pat = "%(api_base)s/t/%(table_id)s/%(action)s?%(query)s"
	def __init__(
				self,
				consumer_key=None,
				consumer_secret=None,
				api_key=None, # deprecated
				api_base="http://api.v3.factual.com"
				):
		'''
		Construct a Session object to hold OAuth credentials. Provide an OAuth consumer
		key and consumer secret to use with the Factual API.

		n.b. Providing only an api_key or only a consumer_key will fall back to
		     authenticating requests via the KEY query string parameter, skipping
			 OAuth entirely. This behavior is deprecated in the v3 API.
		'''
		self.consumer_key = consumer_key if consumer_key else api_key
		self.consumer_secret = consumer_secret
		self.api_base = api_base

		if api_key:
			logging.warn("The api_key parameter is deprecated in the v3 API. Use OAuth.")

		if self.consumer_secret:
			self.consumer = oauth2.Consumer(consumer_key, consumer_secret)
			self.oauth_signature_method = oauth2.SignatureMethod_HMAC_SHA1()
		else:
			self.consumer = None
			logging.warn("Non-OAuth requests are deprecated in the v3 API. Pass both a consumer key and secret to use OAuth.")

	def get_url(self, request):
		query = request.get_query()
		if not self.consumer:
			# fall back to api_key behavior
			query = "%s&KEY=%s" % (query, self.consumer_key,)
		return self._url_pat % {
				'api_base': self.api_base,
				'table_id': request.table,
				'action':   request.action,
				'query':    query
			}
	def get_headers(self, request, defaults={}):
		headers = {}
		if self.consumer:
			# only do OAuth if we have a consumer_secret to use, else fall back to api_key in URL

			# todo: check that Factual API is always GET/blank body/not form encoded
			oauth_request = oauth2.Request.from_consumer_and_token(
								consumer=self.consumer,
								token=None,

								http_method="GET",
								body="",
								is_form_encoded=False,

								http_url=self.get_url(request),
								parameters=None
								)

			# pass None as the Token since Factual's API is 2-legged OAuth only
			oauth_request.sign_request(self.oauth_signature_method, self.consumer, None)
			headers.update(oauth_request.to_header())
		headers.update(defaults)
		return headers
	def read(self, table):
		'''Build a Read request on the provided Table type using this Session. See the requests module for details.'''
		return requests.Read(self, table)


text:
<?php
/**
 * Celebros Qwiser - WordPress
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish correct extension functionality.
 * If you wish to customize it, please contact Celebros.
 *
 * @category    Celebros
 * @package     Celebros_Conversionpro
 *
 */
class Celebros_Conversionpro_Model_Api_QwiserProducts
{
	var $Count = 0;	//the number of products.
	var $Items;	//indexer .

	Function Celebros_Conversionpro_Model_Api_QwiserProducts($xml_Products)
	{
		if(is_object($xml_Products))
		{
			$xml_productsNodes = $xml_Products->child_nodes();
			$xml_productsNodes = getDomElements($xml_productsNodes);
			$this->Count = count($xml_productsNodes);

			for ($i = 0 ; $i <= $this->Count - 1;$i++)
			{
				$ProdNode = $xml_productsNodes[$i];

				$products_product = new Celebros_Conversionpro_Model_Api_QwiserProduct($ProdNode);
// 				$this->Items[$i] = Mage::getModel('conversionpro/Product', $ProdNode);
				$this->Items[$i] = $products_product;

			}
		}
	}

}
?>


text:
package ex7;

import javax.swing.JOptionPane;

public class ex7 {
	public static void main(String[] args){

		float x;
		float r;

		x = Float.parseFloat(JOptionPane.showInputDialog(null,"Digite o seu salário: "));

		r = (float) ((x*0.3)+x);

			if(r<500){
			JOptionPane.showMessageDialog(null,"você possui reajuste salarial, que ficará:"+r);
			}else if(x>500){
				JOptionPane.showMessageDialog(null," você não possui reajuste salarial!!! T.T");

}
	}
}


text:
class ManageIQ::Providers::Inventory::Persister
  require 'json'
  require 'yaml'
  require_nested :Builder

  attr_reader :manager, :target, :collections, :tag_mapper

  include ::ManageIQ::Providers::Inventory::Persister::Builder::PersisterHelper

  # @param manager [ManageIQ::Providers::BaseManager] A manager object
  # @param target [Object] A refresh Target object
  def initialize(manager, target = nil)
    @manager = manager
    @target  = target

    @collections = {}

    initialize_inventory_collections
  end

  # Persists InventoryCollection objects into the DB
  def persist!
    InventoryRefresh::SaveInventory.save_inventory(manager, inventory_collections)
  end

  # Returns Persister object loaded from a passed JSON
  #
  # @param json_data [String] input JSON data
  # @return [ManageIQ::Providers::Inventory::Persister] Persister object loaded from a passed JSON
  def self.from_json(json_data)
    from_hash(JSON.parse(json_data))
  end

  # Returns serialized Persisted object to JSON
  # @return [String] serialized Persisted object to JSON
  def to_json
    JSON.dump(to_hash)
  end

  # @return [Config::Options] Options for the manager type
  def options
    @options ||= Settings.ems_refresh[manager.class.ems_type]
  end

  # @return [Array<InventoryRefresh::InventoryCollection>] array of InventoryCollection objects of the persister
  def inventory_collections
    collections.values
  end

  # @return [Array<Symbol>] array of InventoryCollection object names of the persister
  def inventory_collections_names
    collections.keys
  end

  def strategy
    nil
  end

  def saver_strategy
    :default
  end

  # Persisters for targeted refresh can override to true
  def targeted?
    false
  end

  def parent
    manager.presence
  end

  def assert_graph_integrity?
    !Rails.env.production?
  end

  # @return [InventoryRefresh::InventoryCollection] returns a defined InventoryCollection or undefined method
  def method_missing(method_name, *arguments, &block)
    if inventory_collections_names.include?(method_name)
      self.class.define_collections_reader(method_name)
      send(method_name)
    else
      super
    end
  end

  # @return [Boolean] true if InventoryCollection with passed method_name name is defined
  def respond_to_missing?(method_name, _include_private = false)
    inventory_collections_names.include?(method_name) || super
  end

  # Defines a new attr reader returning InventoryCollection object
  def self.define_collections_reader(collection_key)
    define_method(collection_key) do
      collections[collection_key]
    end
  end

  def self.provider_module
    ManageIQ::Providers::Inflector.provider_module(self).name
  end

  protected

  def initialize_inventory_collections
    # can be implemented in a subclass
  end

  def case_sensitive_labels?
    true
  end

  def initialize_tag_mapper
    @tag_mapper ||= ProviderTagMapping.mapper(:case_sensitive_labels => case_sensitive_labels?)
    collections[:tags_to_resolve] = @tag_mapper.tags_to_resolve_collection
  end

  # @return [Hash] entire Persister object serialized to hash
  def to_hash
    collections_data = collections.map do |_, collection|
      next if collection.data.blank? &&
              collection.targeted_scope.primary_references.blank? &&
              collection.all_manager_uuids.nil? &&
              collection.skeletal_primary_index.index_data.blank?

      collection.to_hash
    end.compact

    {
      :ems_id      => manager.id,
      :class       => self.class.name,
      :collections => collections_data
    }
  end

  class << self
    protected

    # Returns Persister object built from serialized data
    #
    # @param persister_data [Hash] serialized Persister object in hash
    # @return [ManageIQ::Providers::Inventory::Persister] Persister object built from serialized data
    def from_hash(persister_data)
      # Extract the specific Persister class
      persister_class = persister_data['class'].constantize
      unless persister_class < ManageIQ::Providers::Inventory::Persister
        raise "Persister class must inherit from a ManageIQ::Providers::Inventory::Persister"
      end

      ems = ManageIQ::Providers::BaseManager.find(persister_data['ems_id'])
      persister = persister_class.new(
        ems,
        InventoryRefresh::TargetCollection.new(:manager => ems) # TODO(lsmola) we need to pass serialized targeted scope here
      )

      persister_data['collections'].each do |collection|
        inventory_collection = persister.collections[collection['name'].try(:to_sym)]
        raise "Unrecognized InventoryCollection name: #{inventory_collection}" if inventory_collection.blank?

        inventory_collection.from_hash(collection, persister.collections)
      end
      persister
    end
  end
end


text:
/*global require:true */
require(['backbone', 'jquery'], function (Backbone, jquery) {
  $('#versions').append('
Backbone: ' + Backbone.VERSION + '
');

  var DumbView = Backbone.View.extend({
    tagName: "li",
    render: function(){
      var view = this;
      var list = $("

");
      list.append('
Length: ' + this.collection.length + '
');
      list.append('
Total Length: ' + this.collection.totalLength + '
');
      list.append('
Query options: ' + JSON.stringify(this.collection.cloudant_options) + '
');
      // Print 10 rows out to the screen
      _.each(this.collection.first(5), function(doc){
        list.append('

' + JSON.stringify(doc) + '

');
      });
      $(view.id).html(list);
    },
    initialize: function(args){
      this.collection = args.collection;
      this.collection.on("reset", this.render, this);
      this.collection.on("add", this.render, this);
    }
  });

  // Bit of a hack to load out non- require module code
  require(['backbone.cloudant'], function () {
    $('#versions').append('
Backbone.Cloudant: ' + Backbone.Cloudant.VERSION + '
');
    Backbone.Cloudant.database = "http://db.ovdinfo.net/ovdinfo";

    // start the change handler
    Backbone.Cloudant.changeHandler();

    var all_docs = new Backbone.Cloudant.Docs.Collection();

    var all_docs_view = new DumbView({collection: all_docs, id: '#all_docs'});

    all_docs.fetch().fail(function(){console.log('Could not load all_docs collection');});

    var view = new Backbone.Cloudant.View.Collection();
    view.design = 'app';
    view.view = 'test';
    view.cloudant_options = {"reduce": false, "limit": 10};

    var view_view = new DumbView({collection: view, id: '#view'});

    view.fetch().fail(function(){console.log('Could not load view collection');});

    var reducedview = new Backbone.Cloudant.View.Collection({"watch": true});
    reducedview.design = 'app';
    reducedview.view = 'test';
    reducedview.cloudant_options = {"reduce": true, "group": true};

    var reduced_view_view = new DumbView({collection: reducedview, id: '#reduced_view'});

    reducedview.fetch().fail(function(){console.log('Could not load reduced view collection');});

    var watchedview = new Backbone.Cloudant.View.Collection({"watch": true});
    watchedview.design = 'app';
    watchedview.view = 'test';
    watchedview.cloudant_options = {"reduce": false, "limit": 10, "descending": true};

    var watchedview_view = new DumbView({collection: watchedview, id: '#watchedview'});

    watchedview.fetch().fail(function(){console.log('Could not load watched view collection');});

    var search = new Backbone.Cloudant.Search.Collection();
    search.design = 'app';
    search.index = 'mysearch';
    search.cloudant_options = {"q": "a:1", "limit": 2};

    var search_view = new DumbView({collection: search, id: '#search'});

    search.fetch().fail(function(){console.log('Could not load search collection');});

    var limited_all_docs = new Backbone.Cloudant.Docs.Collection();
    limited_all_docs.cloudant_options = {"limit": 2, "skip": 5};
    console.log(limited_all_docs);
    var limited_all_docs_view = new DumbView({collection: limited_all_docs, id: '#limited_all_docs'});

    limited_all_docs.fetch().fail(function(){console.log('Could not load all_docs collection');});

    function testFetchMore(){
      limited_all_docs.fetchMore();
      search.fetchMore();
    }
    setTimeout(testFetchMore, 3000);

    function addDocs(){
      var doc = new Backbone.Cloudant.Model();
      doc.set("a", Math.floor(Math.random()*11));
      doc.save();

      function loop(){
        addDocs();
      }

      setTimeout(loop, 10000);
    }
    addDocs();
  });
});


text:
package software.amazon.awssdk.services.json;

import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.regions.Region;

@Generated("software.amazon.awssdk:codegen")
public class SimpleMethodsIntegrationTest {
    private static JsonClient client;

    @BeforeClass
    public static void setup() {
        if (JsonClient.serviceMetadata().regions().isEmpty()) {
            client = JsonClient.builder().region(Region.US_EAST_1).build();
        } else if (JsonClient.serviceMetadata().regions().contains(Region.AWS_GLOBAL)) {
            client = JsonClient.builder().region(Region.AWS_GLOBAL).build();
        } else if (JsonClient.serviceMetadata().regions().contains(Region.US_EAST_1)) {
            client = JsonClient.builder().region(Region.US_EAST_1).build();
        } else {
            client = JsonClient.builder().region(JsonClient.serviceMetadata().regions().get(0)).build();
        }
    }

    @Test
    public void paginatedOperationWithResultKey_SimpleMethod_Succeeds() throws Exception {
        client.paginatedOperationWithResultKey();
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Webx Root Context Configuration.  -->
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:services="http://www.alibaba.com/schema/services"
    xmlns:request-contexts="http://www.alibaba.com/schema/services/request-contexts"
    xmlns:session-encoders="http://www.alibaba.com/schema/services/request-contexts/session/encoders"
    xmlns:model-encoders="http://www.alibaba.com/schema/services/request-contexts/session/model-encoders"
    xmlns:session-idgens="http://www.alibaba.com/schema/services/request-contexts/session/idgens"
    xmlns:session-stores="http://www.alibaba.com/schema/services/request-contexts/session/stores"
    xmlns:ml-adapters="http://www.alibaba.com/schema/services/module-loader/adapters"
    xmlns:ml-factories="http://www.alibaba.com/schema/services/module-loader/factories"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:rewrite-handlers="http://www.alibaba.com/schema/services/request-contexts/rewrite/handlers"
    xsi:schemaLocation="
        http://www.alibaba.com/schema/services http://localhost:8080/schema/services.xsd
        http://www.alibaba.com/schema/services/request-contexts http://localhost:8080/schema/services-request-contexts.xsd
        http://www.alibaba.com/schema/services/request-contexts/session/encoders http://localhost:8080/schema/services-request-contexts-session-encoders.xsd
        http://www.alibaba.com/schema/services/request-contexts/session/idgens http://localhost:8080/schema/services-request-contexts-session-idgens.xsd
        http://www.alibaba.com/schema/services/request-contexts/session/stores http://localhost:8080/schema/services-request-contexts-session-stores.xsd
        http://www.alibaba.com/schema/services/request-contexts/session/model-encoders http://localhost:8080/schema/services-request-contexts-session-model-encoders.xsd
        http://www.alibaba.com/schema/services/module-loader/adapters http://localhost:8080/schema/services-module-loader-adapters.xsd
        http://www.alibaba.com/schema/services/module-loader/factories http://localhost:8080/schema/services-module-loader-factories.xsd
        http://www.springframework.org/schema/beans http://localhost:8080/schema/www.springframework.org/schema/beans/spring-beans.xsd
        http://www.alibaba.com/schema/services/request-contexts/rewrite/handlers http://localhost:8080/schema/services-request-contexts-rewrite-handlers.xsd
    ">

    <!-- 支持${xxx}替换。 -->
    <services:property-placeholder>
        <services:property key="component">common</services:property>
    </services:property-placeholder>

    <!-- 共享配置。 -->
    <beans:import resource="common/webx-component-and-root.xml" />

    <!-- 异常管道。 -->
    <beans:import resource="common/pipeline-exception.xml" />

    <!-- 资源装载。 -->
    <beans:import resource="common/resources.xml" />

    <!-- URI生成。 -->
    <beans:import resource="common/uris.xml" />

    <!-- URI重定向。 -->
    <beans:import resource="common/rewrite.xml" />

    <!-- 应用资源 -->
    <beans:import resource="classpath:META-INF/spring/dubbo-admin.xml" />

    <!-- 综合设置。 -->
    <services:webx-configuration>
        <!-- 默认将productionMode设为true,建议在jetty插件中设置-DproductionMode=false。 -->
        <services:productionMode>true</services:productionMode>
        <services:components defaultComponent="home" />
    </services:webx-configuration>

    <!-- 设置request/response/session。 -->
    <services:request-contexts xmlns="http://www.alibaba.com/schema/services/request-contexts">
        <rewrite>
        	<rule pattern=".*\.htm">
				<substitution uri="$0" flags="L,QSA" />
			</rule>
			<rule pattern=".*">
				<substitution flags="L,QSA" />
				<handlers>
					<rewrite-handlers:handler
						class="com.alibaba.dubbo.governance.web.common.interceptor.RestfuleUrlRewriter" />
				</handlers>
			</rule>
        </rewrite>
        <basic />
        <buffered />
        <lazy-commit />
        <parser />
        <set-locale defaultLocale="zh_CN" defaultCharset="UTF-8" />
        <session>
            <id>
                <cookie path="/" maxAge="0" httpOnly="true" />
            </id>
            <stores>
                <session-stores:cookie-store id="temporaryCookie">
                    <session-stores:cookie name="tmp" />
                </session-stores:cookie-store>
            </stores>
            <store-mappings>
                <match name="*" store="temporaryCookie" />
            </store-mappings>
        </session>
    </services:request-contexts>

    <!-- 支持上传文件。 -->
    <services:upload sizeMax="5M" />

    <!-- 将beans暴露给模板。这里定义的tools可被所有components之间共享。 -->
    <services:pull xmlns="http://www.alibaba.com/schema/services/pull/factories">
        <utils />
        <page-tool />
        <control-tool />
        <uris-tool />
        <form-tool />
        <factory id="i18n" class="com.alibaba.dubbo.governance.web.common.pulltool.I18nMessageTool" p:singleton="true" />
        <factory id="custTool" class="com.alibaba.dubbo.governance.web.common.pulltool.ToolUtil"/>
        <factory id="tool" class="com.alibaba.dubbo.governance.web.common.pulltool.ToolUtil"/>
    </services:pull>

    <services:form/>

    <!-- 装载模块。 -->
    <services:module-loader>
        <ml-factories:class-modules>
            <ml-factories:search-packages type="$1" packages="com.alibaba.dubbo.governance.web.common.module.*" />
        </ml-factories:class-modules>
    </services:module-loader>

	<beans:bean id="messageResourceService" class="com.alibaba.dubbo.governance.biz.common.i18n.impl.MessageResourceServiceImpl">
		<beans:property name="messageSource" ref="messageSource" />
	</beans:bean>
</beans:beans>


text:
import * as React from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';

export default function SelectVariants() {
  const [age, setAge] = React.useState('');

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (

      <FormControl variant="standard" sx={{ m: 1, minWidth: 120 }}>
        <InputLabel id="demo-simple-select-standard-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-standard-label"
          id="demo-simple-select-standard"
          value={age}
          onChange={handleChange}
          label="Age"
        >
          <MenuItem value="">
            None
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
      <FormControl variant="filled" sx={{ m: 1, minWidth: 120 }}>
        <InputLabel id="demo-simple-select-filled-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-filled-label"
          id="demo-simple-select-filled"
          value={age}
          onChange={handleChange}
        >
          <MenuItem value="">
            None
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>

  );
}


text:
<ion-view view-title="" hide-nav-bar="true">

          <button  style='    position: absolute;
    bottom: 0;
    z-index: 22;
    color: darkgray;
    margin-left: 15px;' class=" button button-positive button-clear no-animation"
                  ng-click="startApp()"  ng-cloak>
            {{'Finalizar'|translate}}
          </button>

        <ion-slide-box on-slide-changed="slideChanged(index)">

    <ion-slide style='
    background-color: #f3f3f3; '>

{{'Demo1Titulo'|translate}}

{{'Demo1'|translate}}

          </ion-slide>

          <ion-slide style='
    background-color: #f3f3f3; '>

{{'Demo2Titulo'|translate}}

{{'Demo2'|translate}}

          </ion-slide>

          <ion-slide style='
    background-color: #f3f3f3; '>

{{'Demo3Titulo'|translate}}

{{'Demo3'|translate}}

          </ion-slide>

          <ion-slide style='
    background-color: #f3f3f3; '>

{{'Demo4Titulo'|translate}}

{{'Demo4'|translate}}

          </ion-slide>

          <ion-slide style='
    background-color: #f3f3f3; '>

{{'Demo5Titulo'|translate}}

{{'Demo5'|translate}}

          </ion-slide>

        </ion-slide-box>
      </ion-view>


text:
package com.johncalilung.tic_tac_toe;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity {

    // Member Variables
    private char mHumanPlayerMark;
    private RadioButton mMarkedButton;
    private Button mPlayButton;
    private RadioGroup mRadioGroupMark;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPlayButton = (Button) findViewById(R.id.play_button);
        mRadioGroupMark = (RadioGroup) findViewById(R.id.radio_mark_choice);

        mPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, GameActivity.class);
                i.putExtra("HUMAN_PLAYER_MARK", getHumanPlayerMark());
                startActivity(i);
            }
        });

        mRadioGroupMark.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mMarkedButton = (RadioButton) findViewById(checkedId);
                mHumanPlayerMark = mMarkedButton.getText().charAt(0);
            }
        });
    }

    private char getHumanPlayerMark() {
        return mHumanPlayerMark;
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

/*============================================================
**
**
**
**
**
** Purpose: Exception for accessing a path that doesn't exist.
**
**
===========================================================*/
using System;
using System.Runtime.Serialization;

namespace System.IO {
    /*
     * Thrown when trying to access a directory that doesn't exist on disk.
     * From COM Interop, this exception is thrown for 2 HRESULTS:
     * the Win32 errorcode-as-HRESULT ERROR_PATH_NOT_FOUND (0x80070003)
     * and STG_E_PATHNOTFOUND (0x80030003).
     */
    [Serializable]
    [System.Runtime.InteropServices.ComVisible(true)]
    public class DirectoryNotFoundException : IOException {
        public DirectoryNotFoundException()
            : base(Environment.GetResourceString("Arg_DirectoryNotFoundException")) {
            SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
        }

        public DirectoryNotFoundException(String message)
            : base(message) {
            SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
        }

        public DirectoryNotFoundException(String message, Exception innerException)
            : base(message, innerException) {
            SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
        }

        protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
        }
    }
}


text:
#ifndef RUBY_OPENCV_CVSIZE2D32F_H
#define RUBY_OPENCV_CVSIZE2D32F_H

#include "opencv.h"

#define __NAMESPACE_BEGIN_CVSIZE2D32F namespace cCvSize2D32f {
#define __NAMESPACE_END_CVSIZE2D32F }

__NAMESPACE_BEGIN_OPENCV
__NAMESPACE_BEGIN_CVSIZE2D32F

VALUE rb_class();

void init_ruby_class();

VALUE rb_compatible_q(VALUE klass, VALUE object);

VALUE rb_allocate(VALUE klass);
VALUE rb_initialize(int argc, VALUE *argv, VALUE self);
VALUE rb_width(VALUE self);
VALUE rb_set_width(VALUE self, VALUE width);
VALUE rb_height(VALUE self);
VALUE rb_set_height(VALUE self, VALUE height);

VALUE rb_to_s(VALUE self);
VALUE rb_to_ary(VALUE self);

VALUE new_object(CvSize2D32f size);

__NAMESPACE_END_CVSIZE2D32F

inline CvSize2D32f*
CVSIZE2D32F(VALUE object)
{
  CvSize2D32f *ptr;
  Data_Get_Struct(object, CvSize2D32f, ptr);
  return ptr;
}

inline CvSize2D32f
VALUE_TO_CVSIZE2D32F(VALUE object)
{
  if (cCvSize2D32f::rb_compatible_q(cCvSize2D32f::rb_class(), object)) {
    return cvSize2D32f(NUM2DBL(rb_funcall(object, rb_intern("width"), 0)),
                       NUM2DBL(rb_funcall(object, rb_intern("height"), 0)));
  }
  else {
    raise_compatible_typeerror(object, cCvSize2D32f::rb_class());
  }
  throw "Should never reach here";
}

__NAMESPACE_END_OPENCV

#endif // RUBY_OPENCV_CVSIZE2D32F_H


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>TabArtStation</title>
  <link rel="stylesheet" href="css/index.css">
  <link rel="stylesheet" href="vender/icono.min.css">

      <select id="sorting">
        <option value="none">None</option>
        <option value="trending">Trending</option>
        <option value="latest">Latest</option>
      </select>


text:
'''
Copyright (C) 2022, WAFW00F Developers.
See the LICENSE file for copying permission.
'''

NAME = 'KeyCDN (KeyCDN)'

def is_waf(self):
    schemes = [
        self.matchHeader(('Server', 'KeyCDN'))
    ]
    if any(i for i in schemes):
        return True
    return False


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>ThingSpeak Communication Library For Arduino and ESP8266</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ThingSpeak Communication Library

Enables an Arduino or ESP8266 to write or read data to or from ThingSpeak™

Main Page

Data Structures

ThingSpeak

src

src Directory Reference

Files

<address class="footer">

          See the accompaning licence file for licensing information

          Copyright © 2017 The MathWorks, Inc.

</address>


text:
namespace web_server {

struct UiTemplateParams {
    StringView title;
    const decltype(web_worker::Context::session)& session;
    StringView notifications;
};

void begin_ui_template(http::Response& resp, UiTemplateParams params);
void end_ui_template(http::Response& resp);
std::string sim_template_params(const decltype(web_worker::Context::session)& session);

} // namespace web_server


text:
/* Hide VE edit tab and section edit things by default, and unhide them if VE is available. */
.client-nojs #ca-ve-edit, .ve-not-available #ca-ve-edit,
.client-nojs .mw-editsection-divider, .ve-not-available .mw-editsection-divider,
.client-nojs .mw-editsection-visualeditor, .ve-not-available .mw-editsection-visualeditor {
	display: none;
}


text:
/*---------------------------------------------------------------
  :: sails-mysql
  -> adapter
---------------------------------------------------------------*/

// Dependencies
var async = require('async');
var _ = require('underscore');
_.str = require('underscore.string');
var mysql = require('mysql');
var Query = require('./query');
var utils = require('./utils');

// Get SQL waterline lib
var sql = require('./sql.js');

module.exports = (function() {

  // Keep track of all the dbs used by the app
  var dbs = {};

  var adapter = {

    // Whether this adapter is syncable (yes)
    syncable: true,

    defaults: {
      pool: true,
      connectionLimit: 10,
      waitForConnections: true
    },

    escape: function(val) {
      return mysql.escape(val);
    },

    escapeId: function(name) {
      return mysql.escapeId(name);
    },

    // Direct access to query
    query: function(collectionName, query, data, cb) {
      if (_.isFunction(data)) {
        cb = data;
        data = null;
      }

      spawnConnection(function(connection, cb) {

        // Run query
        if (data) connection.query(query, data, cb);
        else connection.query(query, cb);

      }, dbs[collectionName].config, cb);
    },

    registerCollection: function(collection, cb) {
      var def = _.clone(collection);
      var key = def.identity;

      if(dbs[key]) return cb();
      dbs[key.toString()] = def;

      // Create a Connection Pool if set
      if (def.config.pool) {
        adapter.pool = mysql.createPool(_.extend(marshalConfig(def.config), {
          connectionLimit: def.config.connectionLimit,
          waitForConnections: def.config.waitForConnections
        }));
      }

      return cb();
    },

    teardown: function(cb) {
      var my = this;

      if (adapter.defaults.pool) {
        // TODO: Drain pool
      }

      cb();
    },

    // Fetch the schema for a collection
    // (contains attributes and autoIncrement value)
    describe: function(collectionName, cb) {
      var self = this;

      spawnConnection(function __DESCRIBE__(connection, cb) {

        var tableName = mysql.escapeId(dbs[collectionName].identity);

        var query = 'DESCRIBE ' + tableName;
        var pkQuery = "SHOW INDEX FROM " + tableName + ";";

        connection.query(query, function __DESCRIBE__(err, schema) {
          if (err) {
            if (err.code === 'ER_NO_SUCH_TABLE') {
              return cb();
            } else return cb(err);
          }

          connection.query(pkQuery, function(err, pkResult) {
            if(err) return cb(err);

            // Loop through Schema and attach extra attributes
            schema.forEach(function(attr) {

              // Set Primary Key Attribute
              if(attr.Key === 'PRI') {
                attr.primaryKey = true;

                // If also an integer set auto increment attribute
                if(attr.Type === 'int(11)') {
                  attr.autoIncrement = true;
                }
              }

              // Set Unique Attribute
              if(attr.Key === 'UNI') {
                attr.unique = true;
              }
            });

            // Loop Through Indexes and Add Properties
            pkResult.forEach(function(result) {
              schema.forEach(function(attr) {
                if(attr.Field !== result.Column_name) return;
                attr.indexed = true;
              });
            });

            // Convert mysql format to standard javascript object
            var normalizedSchema = sql.normalizeSchema(schema);

            // Set Internal Schema Mapping
            dbs[collectionName].schema = normalizedSchema;

            // TODO: check that what was returned actually matches the cache
            cb(null, normalizedSchema);
          });

        });
      }, dbs[collectionName].config, cb);
    },

    // Create a new collection
    define: function(collectionName, definition, cb) {
      spawnConnection(function __DEFINE__(connection, cb) {

        var def = dbs[collectionName];

        // Escape table name
        collectionName = mysql.escapeId(def.identity);

        // Iterate through each attribute, building a query string
        var schema = sql.schema(collectionName, definition);

        // Build query
        var query = 'CREATE TABLE ' + collectionName + ' (' + schema + ')';

        // Run query
        connection.query(query, function __DEFINE__(err, result) {
          if (err) return cb(err);
          cb(null, result);
        });

      }, dbs[collectionName].config, cb);
    },

    // Drop an existing collection
    drop: function(collectionName, cb) {
      spawnConnection(function __DROP__(connection, cb) {

        // Escape table name
        collectionName = mysql.escapeId(dbs[collectionName].identity);

        // Build query
        var query = 'DROP TABLE ' + collectionName;

        // Run query
        connection.query(query, function __DROP__(err, result) {
          if (err) {
            if (err.code === 'ER_BAD_TABLE_ERROR') {
              result = null;
            } else return cb(err);
          }
          cb(null, result);
        });
      }, dbs[collectionName].config, cb);
    },

    //
    addAttribute: function (collectionName, attrName, attrDef, cb) {
      spawnConnection(function(connection, cb) {
        var query = sql.addColumn(dbs[collectionName].identity, attrName, attrDef);

        // sails.log.verbose("ADD COLUMN QUERY ",query);

        // Run query
        connection.query(query, function(err, result) {
          if (err) return cb(err);

          // TODO: marshal response to waterline interface
          cb(err);
        });

      }, dbs[collectionName].config, cb);
    },

    //
    removeAttribute: function (collectionName, attrName, cb) {
      spawnConnection(function(connection, cb) {
        var query = sql.removeColumn(dbs[collectionName].identity, attrName);

        // sails.log.verbose("REMOVE COLUMN QUERY ",query);

        // Run query
        connection.query(query, function(err, result) {
          if (err) return cb(err);

          // TODO: marshal response to waterline interface
          cb(err);
        });

      }, dbs[collectionName].config, cb);
    },

    // No custom alter necessary-- alter can be performed by using the other methods (addAttribute, removeAttribute)
    // you probably want to use the default in waterline core since this can get complex
    // (that is unless you want some enhanced functionality-- then please be my guest!)

    // Create one or more new models in the collection
    create: function(collectionName, data, cb) {
      spawnConnection(function(connection, cb) {

        // Prepare values
        Object.keys(data).forEach(function(value) {
          data[value] = utils.prepareValue(data[value]);
        });

        var query = sql.insertQuery(dbs[collectionName].identity, data);

        // Run query
        connection.query(query, function(err, result) {

          if (err) return cb(err);

          // Build model to return
          var model = _.extend({}, data, {

            // TODO: look up the autoIncrement attribute and increment that instead of assuming `id`
            id: result.insertId
          });

          // Build a Query Object
          var _query = new Query(dbs[collectionName].definition);

          // Cast special values
          var values = _query.cast(model);

          cb(err, values);
        });
      }, dbs[collectionName].config, cb);
    },

    // Override of createEach to share a single connection
    // instead of using a separate connection for each request
    createEach: function (collectionName, valuesList, cb) {
      spawnConnection(function(connection, cb) {

        var records = [];

        async.eachSeries(valuesList, function (data, cb) {

          // Prepare values
          Object.keys(data).forEach(function(value) {
            data[value] = utils.prepareValue(data[value]);
          });

          // Run query
          var query = sql.insertQuery(dbs[collectionName].identity, data) + '; ';

          connection.query(query, function(err, results) {
            if (err) return cb(err);
            records.push(results.insertId);
            cb();
          });
        }, function(err) {
          if(err) return cb(err);

          // Build a Query to get newly inserted records
          var query = "SELECT * FROM " + dbs[collectionName].identity + " WHERE id IN (" + records + ");";

          // Run Query returing results
          connection.query(query, function(err, results) {
            if(err) return cb(err);

            var values = [];

            // Build a Query Object
            var _query = new Query(dbs[collectionName].definition);

            results.forEach(function(result) {
              values.push(_query.cast(result));
            });

            cb(null, values);
          });
        });

      }, dbs[collectionName].config, cb);
    },

    // Find one or more models from the collection
    // using where, limit, skip, and order
    // In where: handle `or`, `and`, and `like` queries
    find: function(collectionName, options, cb) {
      spawnConnection(function(connection, cb) {

        // Check if this is an aggregate query and that there is something to return
        if(options.groupBy || options.sum || options.average || options.min || options.max) {
          if(!options.sum && !options.average && !options.min && !options.max) {
            return cb(new Error('Cannot groupBy without a calculation'));
          }
        }

        // Build find query
        var query = sql.selectQuery(dbs[collectionName].identity, options);

        // Run query
        connection.query(query, function(err, result) {
          if(err) return cb(err);

          var values = [];

          // Build a Query Object
          var _query = new Query(dbs[collectionName].definition);

          result.forEach(function(item) {
            values.push(_query.cast(item));
          });

          cb(null, values);
        });
      }, dbs[collectionName].config, cb);
    },

    // Stream one or more models from the collection
    // using where, limit, skip, and order
    // In where: handle `or`, `and`, and `like` queries
    stream: function(collectionName, options, stream) {
      spawnConnection(function(connection, cb) {

        // Build find query
        var query = sql.selectQuery(dbs[collectionName].identity, options);

        // Run query
        var dbStream = connection.query(query);

        // Handle error, an 'end' event will be emitted after this as well
        dbStream.on('error', function(err) {
          stream.end(err); // End stream
          cb(err); // Close connection
        });

        // the field packets for the rows to follow
        dbStream.on('fields', function(fields) {});

        // Pausing the connnection is useful if your processing involves I/O
        dbStream.on('result', function(row) {
          connection.pause();
          stream.write(row, function() {
            connection.resume();
          });
        });

        // all rows have been received
        dbStream.on('end', function() {
          stream.end(); // End stream
          cb(); // Close connection
        });
      }, dbs[collectionName].config);
    },

    // Update one or more models in the collection
    update: function(collectionName, options, values, cb) {
      spawnConnection(function(connection, cb) {

        // Escape table name
        var tableName = mysql.escapeId(dbs[collectionName].identity);

        // Find the record before updating it
        var criteria = sql.serializeOptions(dbs[collectionName].identity, options);

        var query = 'SELECT id FROM ' + tableName + ' ' + criteria;

        connection.query(query, function(err, results) {
          if(err) return cb(err);

          var ids = [];

          results.forEach(function(result) {
            ids.push(result.id);
          });

          // Prepare values
          Object.keys(values).forEach(function(value) {
            values[value] = utils.prepareValue(values[value]);
          });

          // Build query
          var query = 'UPDATE ' + tableName + ' SET ' + sql.updateCriteria(dbs[collectionName].identity, values) + ' ';

          query += sql.serializeOptions(dbs[collectionName].identity, options);

          // Run query
          connection.query(query, function(err, result) {
            if (err) return cb(err);

            var criteria;

            if(ids.length === 1) {
              criteria = { where: { id: ids[0] }, limit: 1 };
            } else {
              criteria = { where: { id: ids }};
            }

            // the update was successful, select the updated records
            adapter.find(collectionName, criteria, function(err, models) {
              if (err) return cb(err);

              var values = [];

              // Build a Query Object
              var _query = new Query(dbs[collectionName].definition);

              models.forEach(function(item) {
                values.push(_query.cast(item));
              });

              cb(err, values);
            });
          });

        });
      }, dbs[collectionName].config, cb);
    },

    // Delete one or more models from the collection
    destroy: function(collectionName, options, cb) {
      spawnConnection(function(connection, cb) {

        // Escape table name
        var tableName = mysql.escapeId(dbs[collectionName].identity);

        // Build query
        var query = 'DELETE FROM ' + tableName + ' ';

        query += sql.serializeOptions(dbs[collectionName].identity, options);

        // Run query
        connection.query(query, function(err, result) {

          var resultArray = [];

          // Normalize Result Array
          if(Array.isArray(result)) {
            result.forEach(function(value) {
              resultArray.push(value.insertId);
            });

            return cb(null, resultArray);
          }

          resultArray.push(result.insertId);
          cb(err, resultArray);
        });
      }, dbs[collectionName].config, cb);
    },

    // Identity is here to facilitate unit testing
    // (this is optional and normally automatically populated based on filename)
    identity: 'sails-mysql'
  };

  //////////////                 //////////////////////////////////////////
  ////////////// Private Methods //////////////////////////////////////////
  //////////////                 //////////////////////////////////////////

  // Wrap a function in the logic necessary to provision a connection
  // (either grab a free connection from the pool or create a new one)
  // cb is optional (you might be streaming)
  function spawnConnection(logic, config, cb) {

    // Use a new connection each time
    if (!config.pool) {
      var connection = mysql.createConnection(marshalConfig(config));
      connection.connect(function(err) {
        afterwards(err, connection);
      });
    }

    // Use connection pooling
    else {
      adapter.pool.getConnection(afterwards);
    }

    // Run logic using connection, then release/close it

    function afterwards(err, connection) {
      if (err) {
        console.error("Error spawning mySQL connection:");
        console.error(err);
        connection.end();
        return cb(err);
      }

      // console.log("Provisioned new connection.");
      // handleDisconnect(connection, config);

      logic(connection, function(err, result) {

        if (err) {
          console.error("Logic error in mySQL ORM.");
          console.error(err);
          connection.end();
          return cb && cb(err);
        }

        connection.end(function(err) {
          if (err) {
            console.error("MySQL connection killed with error:");
            console.error(err);
          }
          return cb && cb(err, result);
        });
      });
    }
  }

  function handleDisconnect(connection, config) {
    connection.on('error', function(err) {
      // if (!err.fatal) {
      //  return;
      // }

      if (!err || err.code !== 'PROTOCOL_CONNECTION_LOST') {
        // throw err;
      }

      console.error('Re-connecting lost connection: ' + err.stack);
      console.error(err);

      connection = mysql.createConnection(marshalConfig(config));
      connection.connect();
      // connection = mysql.createConnection(connection.config);
      // handleDisconnect(connection);
      // connection.connect();
    });
  }

  // Convert standard adapter config
  // into a custom configuration object for node-mysql
  function marshalConfig(config) {
    return {
      host: config.host,
      socketPath: config.socketPath || null,
      user: config.user,
      password: config.password,
      database: config.database
    };
  }

  return adapter;
})();


text:
package pl.filmbox.configurations;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;

@Configuration
public class ValidationConfig {

    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename("/validation");
        source.setUseCodeAsDefaultMessage(true);
        return source;
    }
}


text:
namespace SelfLoadRO.DataAccess.ERLevel
{
    public partial class C07_Country_ChildDto
    {
    }
}


text:
<?php
require_once '../PHPWord.php';

// New Word Document
$PHPWord = new PHPWord();

// New portrait section
$section = $PHPWord->createSection();

// Add header
$header = $section->createHeader();
$table = $header->addTable();
$table->addRow();
$table->addCell(4500)->addText('This is the header.');
$table->addCell(4500)->addImage('_earth.jpg', array('width'=>50, 'height'=>50, 'align'=>'right'));

// Add footer
$footer = $section->createFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', array('align'=>'center'));

// Write some text
$section->addTextBreak();
$section->addText('Some text...');

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('HeaderFooter.docx');
?>


text:
package org.apache.camel.component.aws.s3.client;

import org.apache.camel.component.aws.s3.S3Configuration;
import org.apache.camel.component.aws.s3.client.impl.S3ClientIAMOptimizedImpl;
import org.apache.camel.component.aws.s3.client.impl.S3ClientStandardImpl;

/**
 * Factory class to return the correct type of AWS S3 aws.
 */
public final class S3ClientFactory {

    private S3ClientFactory() {
        // Prevent instantiation of this factory class.
        throw new RuntimeException("Do not instantiate a Factory class! Refer to the class "
                                   + "to learn how to properly use this factory implementation.");
    }

    /**
     * Return the correct aws s3 client (based on remote vs local).
     * @param maxConnections max connections
     * @return AWSS3Client
     */
    public static S3Client getAWSS3Client(S3Configuration configuration, int maxConnections) {
        return configuration.isUseIAMCredentials() ? new S3ClientIAMOptimizedImpl(configuration, maxConnections)
                : new S3ClientStandardImpl(configuration, maxConnections);
    }
}


text:
<?php

/**
 * @file
 * theme implementation to display a node.
 *
 * Available variables:
 * for info on available variables see modules/node/node.tpl.php
 *
 * @see template_preprocess()
 * @see template_preprocess_node()
 * @see this_theme_preprocess_node()
 * @see template_process()
 */
?>
<article class="<?php print $classes; ?>"<?php print $attributes; ?> role="article">

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>" rel="bookmark"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($unpublished): ?>

<?php print t('Unpublished'); ?>

  <?php endif; ?>

  <?php if ($display_submitted): ?>

      <?php print $user_picture; ?>

<?php print $submitted; ?>

  <?php endif; ?>

  <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>
  <?php print render($content['links']); ?>
  <?php print render($content['comments']); ?>


text:
package net.openhft.chronicle.bytes;

import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.io.AbstractReferenceCounted;
import net.openhft.chronicle.core.onoes.ExceptionKey;
import net.openhft.chronicle.core.onoes.Slf4jExceptionHandler;
import net.openhft.chronicle.core.threads.CleaningThread;
import net.openhft.chronicle.core.threads.ThreadDump;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static net.openhft.chronicle.core.io.AbstractCloseable.waitForCloseablesToClose;
import static net.openhft.chronicle.core.io.AbstractReferenceCounted.assertReferencesReleased;

public class BytesTestCommon {

    private final Map<Predicate<ExceptionKey>, String> ignoredExceptions = new LinkedHashMap<>();
    private final Map<Predicate<ExceptionKey>, String> expectedExceptions = new LinkedHashMap<>();
    protected ThreadDump threadDump;
    protected Map<ExceptionKey, Integer> exceptions;
    protected boolean finishedNormally;

    public BytesTestCommon() {
        // Allocation of 0 chunk in D:\BuildAgent\work\9605994e6a194885\single-mapped-file21723892241386086929bin took 0.509 ms.
        ignoreException("Allocation of ");
    }

    static boolean contains(String text, String message) {
        return text != null && text.contains(message);
    }

    @Before
    @BeforeEach
    public void enableReferenceTracing() {
        AbstractReferenceCounted.enableReferenceTracing();
    }

    @Before
    @BeforeEach
    public void threadDump() {
        threadDump = new ThreadDump();
    }

    public void checkThreadDump() {
        threadDump.assertNoNewThreads();
    }

    @Before
    @BeforeEach
    public void recordExceptions() {
        exceptions = Jvm.recordExceptions();
    }

    @Before
    public void assumeFinishedNormally() {
        finishedNormally = true;
    }

    public void ignoreException(String message) {
        ignoreException(k -> contains(k.message, message) || (k.throwable != null && contains(k.throwable.getMessage(), message)), message);
    }

    public void expectException(String message) {
        expectException(k -> contains(k.message, message) || (k.throwable != null && contains(k.throwable.getMessage(), message)), message);
    }

    public void ignoreException(Predicate<ExceptionKey> predicate, String description) {
        ignoredExceptions.put(predicate, description);
    }

    public void expectException(Predicate<ExceptionKey> predicate, String description) {
        expectedExceptions.put(predicate, description);
    }

    public void checkExceptions() {
        for (Map.Entry<Predicate<ExceptionKey>, String> expectedException : expectedExceptions.entrySet()) {
            if (!exceptions.keySet().removeIf(expectedException.getKey()))
                throw new AssertionError("No error for " + expectedException.getValue());
        }
        expectedExceptions.clear();

        for (Map.Entry<Predicate<ExceptionKey>, String> ignoredException : ignoredExceptions.entrySet()) {
            if (!exceptions.keySet().removeIf(ignoredException.getKey()))
                Slf4jExceptionHandler.DEBUG.on(getClass(), "Ignored " + ignoredException.getValue());
        }
        ignoredExceptions.clear();

        if (Jvm.hasException(exceptions)) {
            final String msg = exceptions.size() + " exceptions were detected: " + exceptions.keySet().stream().map(ek -> ek.message).collect(Collectors.joining(", "));
            Jvm.dumpException(exceptions);
            Jvm.resetExceptionHandlers();
            throw new AssertionError(msg);
        }
    }

    @After
    @AfterEach
    public void afterChecks() {
        cleanResources();

        if (finishedNormally) {
            assertReferencesReleased();
            checkThreadDump();
            checkExceptions();
        }
    }

    private static void cleanResources() {
        CleaningThread.performCleanup(Thread.currentThread());

        // find any discarded resources.
        System.gc();
        waitForCloseablesToClose(100);
    }

    protected static void deleteIfPossible(@NotNull final File file) {
        cleanResources();

        if (file.exists() && !file.delete()) {
            Jvm.error().on(MappedMemoryTest.class, "Unable to delete " + file.getAbsolutePath());
        }
    }
}


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { NgbdNavKeep } from './nav-keep-content';

@NgModule({
  imports: [BrowserModule, NgbModule],
  declarations: [NgbdNavKeep],
  exports: [NgbdNavKeep],
  bootstrap: [NgbdNavKeep]
})
export class NgbdNavKeepModule {
}


text:
package com.willy.example;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.willy.ratingbar.ScaleRatingBar;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by willy on 2017/10/3.
 */

public class MyAdapter
        extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private Context mContext;
    private List<Float> list;

    public MyAdapter(Context context) {
        mContext = context;
        list = new ArrayList<>();

        for (int i = 1; i < 20; i++) {
            list.add(i % 6f);
        }
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_ratingbar, null);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        holder.ratingBar.setTag(position);
        holder.ratingBar.setRating(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyViewHolder
            extends RecyclerView.ViewHolder {

        private ScaleRatingBar ratingBar;

        public MyViewHolder(View itemView) {
            super(itemView);
//            ratingBar = itemView.findViewById(R.id.ratingBar);
//            ratingBar = itemView.findViewById(R.id.ratingBar);
            ratingBar = itemView.findViewById(R.id.ratingBar);
            ratingBar.setOnRatingChangeListener((ratingBar, rating, fromUser) -> {
                int position = (int) ratingBar.getTag();
                list.set(position, rating);
            });
        }
    }
}


text:
"""

"""

import ast
import operator
from collections import deque
from . import ASTOptimization

class ConstantFolding(ASTOptimization):
    """

    """

    @property
    def name(self) -> str:
        return 'Constant folding'

    @property
    def description(self) -> str:
        return ''

    @property
    def level(self) -> int:
        return 1

    _operators = \
        { ast.Add	  : operator.add
        , ast.Sub	  : operator.sub
        , ast.Mult    : operator.mul
        , ast.FloorDiv: operator.floordiv
        , ast.Div     : operator.truediv
        , ast.Pow 	  : operator.pow
        , ast.LShift  : operator.lshift
        , ast.RShift  : operator.rshift
        , ast.Mod     : operator.mod
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._has_names    = deque()
        self._iter_targets = set()

    def convert(self, node):
        code     = compile(node, '<string>', mode = 'eval')
        value    = eval(code)
        new_node = ast.parse(str(value), mode = 'eval')
        if isinstance(new_node, ast.Expression):
            new_node = new_node.body
        new_node = self.generic_visit(new_node)
        node     = ast.copy_location(new_node, node)
        node     = ast.fix_missing_locations(node)
        return node

    def fold(self, node):
        self._has_names.append(False)
        node = self.generic_visit(node)
        if not self._has_names.pop():
            try:
                node = self.convert(node)
            except TypeError as exc:
                if  not isinstance(node, ast.Expression) \
                and str(exc).startswith('expected Expression node, got'):
                    try:
                        node = self.convert(ast.Expression(body=node))
                    except:
                        pass
            except:
                pass
        return node

    def comprehension(self, node):
        iter_targets = set(g.target.id for g in node.generators)
        self._iter_targets |= iter_targets
        node = self.fold(node)
        self._iter_targets -= iter_targets
        return node

    def visit_BinOp(self, node):
        node  = self.generic_visit(node)
        left  = node.left
        right = node.right
        if all(isinstance(value, ast.Num) for value in (left, right)):
            if isinstance(node.op, tuple(self._operators.keys())):
                val  = self._operators[type(node.op)](left.n, right.n)
                node = ast.copy_location(ast.Num(n = val), node)
                return node
        elif all(isinstance(value, ast.Str) for value in (left, right)):
           if isinstance(node.op, ast.Add):
                val  = left.s + right.s
                node = ast.copy_location(ast.Str(s = val), node)
                return node
        return self.fold(node)

    #def visit_GeneratorExp(self, node):
    #    return self.comprehension(node)

    def visit_ListComp(self, node):
        return self.comprehension(node)

    def visit_DictComp(self, node):
        return self.comprehension(node)

    def visit_Call(self, node):
        return self.fold(node)

    def visit_Name(self, node):
        if  self._has_names \
        and not (  node.id in __builtins__
                or not isinstance(node.ctx, ast.Load)
                or node.id in self._iter_targets
                ):
            self._has_names.pop()
            self._has_names.append(True)
        return self.generic_visit(node)


text:
require 'spec_helper'

os = @platforms['Ubuntu 12.04']

describe 'oe-postgresql::create_db' do

  let(:chef_run) {
    runner(attributes = os, environment = os[:environment])
  }

  before do
    Chef::EncryptedDataBagItem.stub(:load).with(
      chef_run.node['postgresql']['data_bag']['users'],
      chef_run.node['postgresql']['data_bag_item']['users']
    ).and_return(os[:data_bags][:db][:users])
  end

  context 'When databases dont exist' do

    os[:postgresql]['databases'].each { |db|
      it "Should create database #{db['name']}" do
        stub_command("echo \"SELECT datname FROM pg_database WHERE datname = '#{db['name']}';\" | psql -t | grep '#{db['name']}'").and_return(false)

        chef_run.converge(described_recipe)
        expect(chef_run).to run_execute("create-db-#{db['name']}")
      end
    }

  end

  context 'When databases exist' do
     os[:postgresql]['databases'].each { |db|
      it "Should not create database #{db['name']}" do
        stub_command("echo \"SELECT datname FROM pg_database WHERE datname = '#{db['name']}';\" | psql -t | grep '#{db['name']}'").and_return(true)

        chef_run.converge(described_recipe)
        expect(chef_run).not_to run_execute("create-db-#{db['name']}")
      end
    }
  end

  #context 'Without required attributes' do
  #  pending 'not implemented'
  #end

end


text:
A application for watching for SteamSales using the store.steampowered.com API.

To setup the project.
  * Install Webstorm
  * Install Dart SDK with Dartium
  * Clone this repo into your local workspace
  * Load this project in Webstorm
  * Click on the pubspec.yaml file.
    * In the upper right of the Webstorm IDE, there should be bar with "pub" actions
    * Click Get Dependencies. This goes out and pulls in all of the packages that we are using. Very neat part of Dart.
  * You should be able to run the index.html file and see a barbones webpage. Right now, there is some background api calls running, so      the server will need to be correctly setup. More information about that can be found on the server repo readme.


text:
from subprocess import check_output

def main():
  pass
if __name__ == '__main__':
  main()


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Basic ComboGrid - jQuery EasyUI Demo</title>
	<link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="../../themes/icon.css">
	<link rel="stylesheet" type="text/css" href="../demo.css">

Basic ComboGrid

Click the right arrow button to show the DataGrid.

			<select class="easyui-combogrid" style="width:100%" data-options="
					panelWidth: 500,
					idField: 'itemid',
					textField: 'productname',
					url: 'datagrid_data1.json',
					method: 'get',
					columns: [[
						{field:'itemid',title:'Item ID',width:80},
						{field:'productname',title:'Product',width:120},
						{field:'listprice',title:'List Price',width:80,align:'right'},
						{field:'unitcost',title:'Unit Cost',width:80,align:'right'},
						{field:'attr1',title:'Attribute',width:200},
						{field:'status',title:'Status',width:60,align:'center'}
					]],
					fitColumns: true,
					label: 'Select Item:',
					labelPosition: 'top'
				">
			</select>