text:
import React, { useState } from 'react';
import Helmet from 'react-helmet';
import { Link, RouteComponentProps } from 'react-router-dom';

import services from 'web/libs/services';
import { getReferrer } from 'jslib/helpers/url';
import { getRootUrl } from 'web/libs/paths';
import JoinForm from './JoinForm';
import Logo from '../Icons/Logo';
import Flash from '../Common/Flash';
import { updateAuthEmail } from '../../store/form';
import { getCurrentUser } from '../../store/auth';
import authStyles from '../Common/Auth.scss';
import { useSelector, useDispatch } from '../../store';

interface Props extends RouteComponentProps<any> {}

const Join: React.FunctionComponent<Props> = ({ location }) => {
  const [errMsg, setErrMsg] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const { formData } = useSelector(state => {
    return {
      formData: state.form
    };
  });
  const dispatch = useDispatch();

  const referrer = getReferrer(location);

  async function handleJoin(email, password, passwordConfirmation) {
    if (!email) {
      setErrMsg('Please enter an email.');
      return;
    }
    if (!password) {
      setErrMsg('Please enter a pasasword.');
      return;
    }
    if (!passwordConfirmation) {
      setErrMsg('The passwords do not match.');
      return;
    }

    setErrMsg('');
    setSubmitting(true);

    try {
      await services.users.register({ email, password });

      // guestOnly HOC will redirect the user accordingly after the current user is fetched
      await dispatch(getCurrentUser());
      dispatch(updateAuthEmail(''));
    } catch (err) {
      console.log(err);
      setErrMsg(err.message);
      setSubmitting(false);
    }
  }

  return (

      <Helmet>
        <title>Join</title>
      </Helmet>

          <Logo fill="#252833" width={60} height={60} />

Join Dnote

          {referrer && (
            <Flash kind="info" wrapperClassName={authStyles['referrer-flash']}>
              Please join to continue.
            </Flash>
          )}

            {errMsg && (
              <Flash kind="danger" wrapperClassName={authStyles['error-flash']}>
                {errMsg}
              </Flash>
            )}

            <JoinForm
              onJoin={handleJoin}
              submitting={submitting}
              email={formData.auth.email}
            />

Already have an account?

            <Link to="/login" className={authStyles.cta}>
              Sign in
            </Link>

  );
};

export default Join;

redpajama_set_name: RedPajamaGithub


text:
subroutine permute_vec_in_place_int(map,vec)
  integer, intent(in) :: map(:)
  integer, intent(in out) :: vec(size(map))
  if (maxval(map) > size(vec) .or. minval(map) < 1) then
     write(error_unit,"('Error: Invalid reference in map')")
     stop
  end if
  vec = vec(map)
end subroutine permute_vec_in_place_int


text:
"""

Quick similarity calculations

"""

from ontobio.golr.golr_associations import search_associations, GolrFields
import scipy.stats # TODO - move
import scipy as sp # TODO - move

M=GolrFields()

def get_object_closure(subject, object_category=None, **kwargs):
    """
    Find all terms used to annotate subject plus ancestors
    """
    results = search_associations(subject=subject,
                                  object_category=object_category,
                                  select_fields=[],
                                  facet_fields=[M.OBJECT_CLOSURE],
                                  facet_limit=-1,
                                  rows=0,
                                  **kwargs)
    return set(results['facet_counts'][M.OBJECT_CLOSURE].keys())

def subject_pair_overlap(subject1, subject2, object_category=None, **kwargs):
    """
    Jaccard similarity
    """
    set1 = get_object_closure(subject1,
                              object_category=object_category,
                              **kwargs)
    set2 = get_object_closure(subject2,
                              object_category=object_category,
                              **kwargs)
    return len(set1.intersection(set2)), len(set1.union(set2))

def subject_pair_simj(subject1, subject2, **kwargs):
    """
    Jaccard similarity
    """
    i, u = subject_pair_overlap(subject1, subject2, **kwargs)
    if i==0:
        return 0.0
    return i / u


text:
import { workspacesExec, toWorkspacesExecOptions } from '../exec';
import * as path from 'path';
import * as processes from '../../../utils/processes';
import containDeep from 'jest-expect-contain-deep';
import fixtures from 'fixturez';

const f = fixtures(__dirname);

jest.mock('../../../utils/processes');

const unsafeProcesses: any & typeof processes = processes;
const binDir = path.join('node_modules', '.bin');

function assertSpawn(opts) {
  expect(unsafeProcesses.spawn).toHaveBeenCalledWith(
    opts.cmd,
    opts.args,
    containDeep({
      cwd: opts.cwd,
      env: {
        PATH: expect.stringContaining(opts.PATH)
      }
    })
  );
}

describe('bolt workspaces exec', () => {
  test('running in a project', async () => {
    let projectDir = f.copy('project-with-bins');
    let fooWorkspaceDir = path.join(projectDir, 'packages', 'foo');
    let barWorkspaceDir = path.join(projectDir, 'packages', 'bar');
    let projectBinDir = path.join(projectDir, binDir);
    let fooBinDir = path.join(fooWorkspaceDir, binDir);
    let barBinDir = path.join(barWorkspaceDir, binDir);

    await workspacesExec(
      toWorkspacesExecOptions([], {
        cwd: projectDir,
        '--': ['dep-with-bin']
      })
    );

    expect(unsafeProcesses.spawn).toHaveBeenCalledTimes(2);
    expect(unsafeProcesses.spawn).toHaveBeenCalledWith(
      'dep-with-bin',
      [],
      containDeep({
        cwd: barWorkspaceDir,
        env: {
          PATH: expect.stringContaining(barBinDir + ':' + projectBinDir)
        }
      })
    );
    expect(unsafeProcesses.spawn).toHaveBeenCalledWith(
      'dep-with-bin',
      [],
      containDeep({
        cwd: fooWorkspaceDir,
        env: {
          PATH: expect.stringContaining(fooBinDir + ':' + projectBinDir)
        }
      })
    );
  });

  test('running from inside a workspace', async () => {
    let projectDir = f.copy('project-with-bins');
    let fooWorkspaceDir = path.join(projectDir, 'packages', 'foo');
    let barWorkspaceDir = path.join(projectDir, 'packages', 'bar');
    let projectBinDir = path.join(projectDir, binDir);
    let fooBinDir = path.join(fooWorkspaceDir, binDir);
    let barBinDir = path.join(barWorkspaceDir, binDir);

    await workspacesExec(
      toWorkspacesExecOptions([], {
        cwd: fooWorkspaceDir,
        '--': ['dep-with-bin']
      })
    );

    expect(unsafeProcesses.spawn).toHaveBeenCalledTimes(2);
    expect(unsafeProcesses.spawn).toHaveBeenCalledWith(
      'dep-with-bin',
      [],
      containDeep({
        cwd: barWorkspaceDir,
        env: {
          PATH: expect.stringContaining(barBinDir + ':' + projectBinDir)
        }
      })
    );
    expect(unsafeProcesses.spawn).toHaveBeenCalledWith(
      'dep-with-bin',
      [],
      containDeep({
        cwd: fooWorkspaceDir,
        env: {
          PATH: expect.stringContaining(fooBinDir + ':' + projectBinDir)
        }
      })
    );
  });

  test('running from inside a workspace that doesnt have the command', async () => {
    let projectDir = f.copy('project-with-bins');
    let fooWorkspaceDir = path.join(projectDir, 'packages', 'foo');
    let barWorkspaceDir = path.join(projectDir, 'packages', 'bar');
    let projectBinDir = path.join(projectDir, binDir);
    let fooBinDir = path.join(fooWorkspaceDir, binDir);
    let barBinDir = path.join(barWorkspaceDir, binDir);

    await workspacesExec(
      toWorkspacesExecOptions([], {
        cwd: barWorkspaceDir,
        '--': ['dep-with-bin']
      })
    );

    expect(unsafeProcesses.spawn).toHaveBeenCalledTimes(2);
    expect(unsafeProcesses.spawn).toHaveBeenCalledWith(
      'dep-with-bin',
      [],
      containDeep({
        cwd: barWorkspaceDir,
        env: {
          PATH: expect.stringContaining(barBinDir + ':' + projectBinDir)
        }
      })
    );
    expect(unsafeProcesses.spawn).toHaveBeenCalledWith(
      'dep-with-bin',
      [],
      containDeep({
        cwd: fooWorkspaceDir,
        env: {
          PATH: expect.stringContaining(fooBinDir + ':' + projectBinDir)
        }
      })
    );
  });
});


text:
package jpl.ch22.ex12;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.Scanner;

public class MyReader {
	private static final String PATH = "src/jpl/ch22/ex12/sample.txt";
	/**
	 * Scannerを使って入力されたAttrの属性を読み込む
	 * @param source
	 * @return
	 * @throws IOException
	 */
	public static Attributed readAttrs(Reader source) throws IOException {
		Attributed<String> attrs = new AttributedImpl();
        Scanner in = null;
        try {
            in = new Scanner(source);
            while (in.hasNextLine()) {
                String[] kv = in.nextLine().split("=");
                attrs.add(new Attr<>(kv[0], kv[1]));
            }
        } finally {
            if (in != null)
                in.close();
        }
        return attrs;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(PATH));
            Attributed<String> attrs = readAttrs(in);
            Iterator<Attr<String>> it = attrs.attrs();
            while (it.hasNext())
                System.out.println(it.next());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                in.close();
        }
	}
}


text:
package eu.thog92.universalat.hook;

import eu.thog92.universalat.loader.ATClassLoader;
import eu.thog92.universalat.loader.IClassTransformer;
import eu.thog92.universalat.modifier.ModifierClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * WIP Fix for bukkit plugins ClassLoader
 */
public class ClassLoaderTransformer implements IClassTransformer
{
    ModifierClassTransformer modifierClassTransformer = new ModifierClassTransformer();

    @Override
    public byte[] transform(String name, String transformedName, byte[] basicClass)
    {
        if (!name.endsWith("PluginClassLoader"))
            return basicClass;

        ClassNode classNode = new ClassNode();
        ClassReader reader = new ClassReader(basicClass);
        reader.accept(classNode, 0);

        classNode.superName = "eu/thog92/universalat/loader/ATClassLoader";
        List<MethodNode> methods = classNode.methods;

        InsnList modifiedInst = new InsnList();
        InsnList findClassHook = new InsnList();
        findClassHook.add(new VarInsnNode(Opcodes.ALOAD, 0));
        findClassHook.add(new VarInsnNode(Opcodes.ALOAD, 1));
        findClassHook.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, classNode.name, "findClass", "(Ljava/lang/String;)Ljava/lang/Class;", false)); // java/net/URLClassLoader.findClass:(Ljava/lang/String;)Ljava/lang/Class;
        findClassHook.add(new InsnNode(Opcodes.ARETURN));
        List<MethodNode> toRemove = new ArrayList<MethodNode>();
        for (MethodNode methodNode : methods)
        {
            if (methodNode.name.equals("<init>"))
            {
                InsnList list = methodNode.instructions;

                int superID = -1;
                for (int i = 0; i < list.size(); i++)
                {
                    AbstractInsnNode insn = list.get(i);

                    modifiedInst.add(insn);
                    if(superID == i)
                    {
                        modifiedInst.add(new VarInsnNode(Opcodes.ALOAD, 0));
                        modifiedInst.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                                "eu/thog92/universalat/hook/BukkitLaunchClassLoader",
                                "updateClassLoader",
                                "(Ljava/lang/ClassLoader;)V",
                                false));
                    }

/*                    if(insn.getOpcode() == Opcodes.PUTFIELD && insn instanceof FieldInsnNode && ((FieldInsnNode) insn).desc.contains("JavaPlugin"))
                    {
                        modifiedInst.add(new FieldInsnNode(Opcodes.GETFIELD, classNode.name, ((FieldInsnNode) insn).name, ((FieldInsnNode) insn).desc));
                        modifiedInst.add(new VarInsnNode(Opcodes.ALOAD, 0));
                        modifiedInst.add(new MethodInsnNode(Opcodes.INVOKESTATIC, classNode.name, "putInstance", "(Lorg/bukkit/plugin/java/JavaPlugin;Ljava/lang/ClassLoader;)Lorg/bukkit/plugin/java/JavaPlugin;", false));
                    }
                    */

                    if (insn.getOpcode() == Opcodes.ALOAD && insn instanceof VarInsnNode)
                    {
                        VarInsnNode aload = (VarInsnNode) insn;

                        // ClassLoader for super
                        if (aload.var == 2)
                        {

                            // get super call and hook it
                            MethodInsnNode caller = (MethodInsnNode) methodNode.instructions.get(i + 1);
                            superID = i + 1;
                            caller.owner = classNode.superName;
                            caller.desc = "([Ljava/net/URL;)V";
                            modifiedInst.add(new MethodInsnNode(Opcodes.INVOKESTATIC,
                                    "eu/thog92/universalat/hook/ClassLoaderTransformer",
                                    "makeSources",
                                    "([Ljava/net/URL;Ljava/lang/ClassLoader;)[Ljava/net/URL;",
                                    false));
                            continue;
                        }
                    }
                }
                methodNode.instructions = modifiedInst;
            } else if (methodNode.name.equals("findClass"))
            {
                System.out.println("PATCHING... ");
                if (methodNode.desc.equals("(Ljava/lang/String;Z)Ljava/lang/Class;"))
                {
                    methodNode.instructions.clear();
                    methodNode.localVariables = new ArrayList<LocalVariableNode>(5);
                    methodNode.instructions.add(findClassHook);
                } else
                {
                    toRemove.add(methodNode);
                }
            }
        }
        methods.removeAll(toRemove);

        ClassWriter writer = new ClassWriter(0);
        classNode.accept(writer);
        byte[] patched = writer.toByteArray();
        return patched;
    }

    public static URL[] makeSources(URL[] urls, ClassLoader classLoader)
    {
        if (classLoader instanceof ATClassLoader)
        {
            ATClassLoader launchClassLoader = (ATClassLoader) classLoader;
            launchClassLoader.addURL(urls[0]);
            System.out.println("PluginClassLoader hook called!" + urls[0]);
            return concat(concat(urls, launchClassLoader.getURLs()), launchClassLoader.getSources().toArray(new URL[launchClassLoader.getSources().size()]));
        }

        return urls;
    }

    private static URL[] concat(URL[] a, URL[] b)
    {
        int aLen = a.length;
        int bLen = b.length;
        URL[] c = new URL[aLen + bLen];
        System.arraycopy(a, 0, c, 0, aLen);
        System.arraycopy(b, 0, c, aLen, bLen);
        return c;
    }
}


text:
import * as http from 'http';
import * as url from 'url';
import * as fs from 'fs';

import {ORIGIN_URL, BASE_URL} from '../../common';
import {NgZone, Inject, Optional} from '@angular/core';
import {XHR} from '@angular/compiler';
import {PromiseWrapper, PromiseCompleter} from '@angular/core/src/facade/promise';

export class NodeXHRImpl extends XHR {
  _baseUrl: string;
  constructor(
    public ngZone: NgZone,
    @Optional() @Inject(ORIGIN_URL) private _originUrl: string = '',
    @Optional() @Inject(BASE_URL) _baseUrl?: string) {
    super();
    this._baseUrl = _baseUrl || '/';
  }

  get(templateUrl: string): Promise<string> {
    const completer: PromiseCompleter<string> = PromiseWrapper.completer();
    const parsedUrl = url.parse(url.resolve(url.resolve(this._originUrl, this._baseUrl), templateUrl));

    if (parsedUrl.protocol === 'file:') {
      this.ngZone.run(() => {
        fs.readFile(parsedUrl.path, (err, data) => {
          if (err) {
            return completer.reject(`Failed to load ${templateUrl} with error ${err}`);
          }
          this.ngZone.run(() => {
            completer.resolve(data.toString());
          });
        });
      });
    } else {
      this.ngZone.run(() => {
        http.get(parsedUrl, (res) => {
          res.setEncoding('utf8');

          const status = res.statusCode;

          if (200 <= status && status <= 300) {
            let data = '';

            res.on('data', (chunk) => {
              data += chunk;
            });
            res.on('end', () => {
              this.ngZone.run(() => {
                completer.resolve(data);
              });
            });

          } else {
            this.ngZone.run(() => {
              completer.reject(`Failed to load ${templateUrl}`, null);
            });
          }

          // consume response body
          res.resume();
        }).on('error', (e) => {
          this.ngZone.run(() => {
            completer.reject(`Failed to load ${templateUrl}`, null);
          });
        });
      });
    }

    return completer.promise;
  }
}


text:
package org.apache.solr.core;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.cloud.AbstractFullDistribZkTestBase;
import org.apache.solr.handler.TestBlobHandler;
import org.apache.solr.util.RESTfulServerProvider;
import org.apache.solr.util.RestTestHarness;
import org.apache.solr.util.SimplePostTool;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static java.util.Arrays.asList;
import static org.apache.solr.handler.TestSolrConfigHandlerCloud.compareValues;

public class TestDynamicLoading extends AbstractFullDistribZkTestBase {
  static final Logger log =  LoggerFactory.getLogger(TestDynamicLoading.class);
  private List<RestTestHarness> restTestHarnesses = new ArrayList<>();

  private void setupHarnesses() {
    for (final SolrClient client : clients) {
      RestTestHarness harness = new RestTestHarness(new RESTfulServerProvider() {
        @Override
        public String getBaseURL() {
          return ((HttpSolrClient)client).getBaseURL();
        }
      });
      restTestHarnesses.add(harness);
    }
  }

  @BeforeClass
  public static void enableRuntimeLib() throws Exception {
    System.setProperty("enable.runtime.lib", "true");
  }

  @Override
  public void distribTearDown() throws Exception {
    super.distribTearDown();
    for (RestTestHarness r : restTestHarnesses) {
      r.close();
    }
  }

  @Test
  public void testDynamicLoading() throws Exception {
    System.setProperty("enable.runtime.lib", "true");
    setupHarnesses();

    String blobName = "colltest";
    boolean success = false;

    HttpSolrClient randomClient = (HttpSolrClient) clients.get(random().nextInt(clients.size()));
    String baseURL = randomClient.getBaseURL();
    baseURL = baseURL.substring(0, baseURL.lastIndexOf('/'));
    String payload = "{\n" +
        "'add-runtimelib' : { 'name' : 'colltest' ,'version':1}\n" +
        "}";
    RestTestHarness client = restTestHarnesses.get(random().nextInt(restTestHarnesses.size()));
    TestSolrConfigHandler.runConfigCommand(client, "/config?wt=json", payload);
    TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/config/overlay?wt=json",
        null,
        Arrays.asList("overlay", "runtimeLib", blobName, "version"),
        1l, 10);

    payload = "{\n" +
        "'create-requesthandler' : { 'name' : '/test1', 'class': 'org.apache.solr.core.BlobStoreTestRequestHandler' , 'runtimeLib' : true }\n" +
        "}";

    client = restTestHarnesses.get(random().nextInt(restTestHarnesses.size()));
    TestSolrConfigHandler.runConfigCommand(client,"/config?wt=json",payload);
    TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/config/overlay?wt=json",
        null,
        Arrays.asList("overlay", "requestHandler", "/test1", "class"),
        "org.apache.solr.core.BlobStoreTestRequestHandler",10);

    Map map = TestSolrConfigHandler.getRespMap("/test1?wt=json", client);

    assertNotNull(TestBlobHandler.getAsString(map), map = (Map) map.get("error"));
    assertEquals(TestBlobHandler.getAsString(map), ".system collection not available", map.get("msg"));

    TestBlobHandler.createSystemCollection(new HttpSolrClient(baseURL, randomClient.getHttpClient()));
    waitForRecoveriesToFinish(".system", true);

    map = TestSolrConfigHandler.getRespMap("/test1?wt=json", client);

    assertNotNull(map = (Map) map.get("error"));
    assertEquals("full output " + TestBlobHandler.getAsString(map), "no such blob or version available: colltest/1" , map.get("msg"));
    payload = " {\n" +
        "  'set' : {'watched': {" +
        "                    'x':'X val',\n" +
        "                    'y': 'Y val'}\n" +
        "             }\n" +
        "  }";

    TestSolrConfigHandler.runConfigCommand(client,"/config/params?wt=json",payload);
    TestSolrConfigHandler.testForResponseElement(
        client,
        null,
        "/config/params?wt=json",
        cloudClient,
        Arrays.asList("response", "params", "watched", "x"),
        "X val",
        10);

    for(int i=0;i<100;i++) {
      map = TestSolrConfigHandler.getRespMap("/test1?wt=json", client);
      if("X val".equals(map.get("x"))){
         success = true;
         break;
      }
      Thread.sleep(100);
    }
    ByteBuffer jar = null;

//     jar = persistZip("/tmp/runtimelibs.jar.bin", TestDynamicLoading.class, RuntimeLibReqHandler.class, RuntimeLibResponseWriter.class, RuntimeLibSearchComponent.class);
//    if(true) return;

    jar = getFileContent("runtimecode/runtimelibs.jar.bin");
    TestBlobHandler.postAndCheck(cloudClient, baseURL, blobName, jar, 1);

    payload = "{\n" +
        "'create-requesthandler' : { 'name' : '/runtime', 'class': 'org.apache.solr.core.RuntimeLibReqHandler' , 'runtimeLib':true }," +
        "'create-searchcomponent' : { 'name' : 'get', 'class': 'org.apache.solr.core.RuntimeLibSearchComponent' , 'runtimeLib':true }," +
        "'create-queryResponseWriter' : { 'name' : 'json1', 'class': 'org.apache.solr.core.RuntimeLibResponseWriter' , 'runtimeLib':true }" +
        "}";
    client = restTestHarnesses.get(random().nextInt(restTestHarnesses.size()));
    TestSolrConfigHandler.runConfigCommand(client, "/config?wt=json", payload);

    Map result = TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/config/overlay?wt=json",
        null,
        Arrays.asList("overlay", "requestHandler", "/runtime", "class"),
        "org.apache.solr.core.RuntimeLibReqHandler", 10);
    compareValues(result, "org.apache.solr.core.RuntimeLibResponseWriter", asList("overlay", "queryResponseWriter", "json1", "class"));
    compareValues(result, "org.apache.solr.core.RuntimeLibSearchComponent", asList("overlay", "searchComponent", "get", "class"));

    result = TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/runtime?wt=json",
        null,
        Arrays.asList("class"),
        "org.apache.solr.core.RuntimeLibReqHandler", 10);
    compareValues(result, MemClassLoader.class.getName(), asList( "loader"));

    result = TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/runtime?wt=json1",
        null,
        Arrays.asList("wt"),
        "org.apache.solr.core.RuntimeLibResponseWriter", 10);
    compareValues(result, MemClassLoader.class.getName(), asList( "loader"));

    result = TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/get?abc=xyz",
        null,
        Arrays.asList("get"),
        "org.apache.solr.core.RuntimeLibSearchComponent", 10);
    compareValues(result, MemClassLoader.class.getName(), asList( "loader"));

    jar = getFileContent("runtimecode/runtimelibs_v2.jar.bin");
    TestBlobHandler.postAndCheck(cloudClient, baseURL, blobName, jar, 2);
    payload = "{\n" +
        "'update-runtimelib' : { 'name' : 'colltest' ,'version':2}\n" +
        "}";
    client = restTestHarnesses.get(random().nextInt(restTestHarnesses.size()));
    TestSolrConfigHandler.runConfigCommand(client, "/config?wt=json", payload);
    TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/config/overlay?wt=json",
        null,
        Arrays.asList("overlay", "runtimeLib", blobName, "version"),
        2l, 10);

    result = TestSolrConfigHandler.testForResponseElement(client,
        null,
        "/get?abc=xyz",
        null,
        Arrays.asList("Version"),
        "2", 10);

    payload = " {\n" +
        "  'set' : {'watched': {" +
        "                    'x':'X val',\n" +
        "                    'y': 'Y val'}\n" +
        "             }\n" +
        "  }";

    TestSolrConfigHandler.runConfigCommand(client,"/config/params?wt=json",payload);
    TestSolrConfigHandler.testForResponseElement(
        client,
        null,
        "/config/params?wt=json",
        cloudClient,
        Arrays.asList("response", "params", "watched", "x"),
        "X val",
        10);
   result = TestSolrConfigHandler.testForResponseElement(
        client,
        null,
        "/test1?wt=json",
        cloudClient,
        Arrays.asList("x"),
        "X val",
        10);

    payload = " {\n" +
        "  'set' : {'watched': {" +
        "                    'x':'X val changed',\n" +
        "                    'y': 'Y val'}\n" +
        "             }\n" +
        "  }";

    TestSolrConfigHandler.runConfigCommand(client,"/config/params?wt=json",payload);
    result = TestSolrConfigHandler.testForResponseElement(
        client,
        null,
        "/test1?wt=json",
        cloudClient,
        Arrays.asList("x"),
        "X val changed",
        10);
  }

  public static ByteBuffer getFileContent(String f) throws IOException {
    ByteBuffer jar;
    try (FileInputStream fis = new FileInputStream(getFile(f))) {
      byte[] buf = new byte[fis.available()];
      fis.read(buf);
      jar = ByteBuffer.wrap(buf);
    }
    return jar;
  }

  public static  ByteBuffer persistZip(String loc, Class... classes) throws IOException {
    ByteBuffer jar = generateZip(classes);
    try (FileOutputStream fos =  new FileOutputStream(loc)){
      fos.write(jar.array(), 0, jar.limit());
      fos.flush();
    }
    return jar;
  }

  public static ByteBuffer generateZip(Class... classes) throws IOException {
    ZipOutputStream zipOut = null;
    SimplePostTool.BAOS bos = new SimplePostTool.BAOS();
    zipOut = new ZipOutputStream(bos);
    zipOut.setLevel(ZipOutputStream.DEFLATED);
    for (Class c : classes) {
      String path = c.getName().replace('.', '/').concat(".class");
      ZipEntry entry = new ZipEntry(path);
      ByteBuffer b = SimplePostTool.inputStreamToByteArray(c.getClassLoader().getResourceAsStream(path));
      zipOut.putNextEntry(entry);
      zipOut.write(b.array(), 0, b.limit());
      zipOut.closeEntry();
    }
    zipOut.close();
    return bos.getByteBuffer();
  }

}


text:
function install()
{
    umask '0022'

    # Install Package

    installPackages 'logrotate'

    # Configure Logrotate

    if [[ "$(isUbuntuDistributor)" = 'true' ]]
    then
        cp -f "$(dirname "${BASH_SOURCE[0]}")/../files/logrotate.conf.apt" '/etc/logrotate.conf'
    else
        cp -f "$(dirname "${BASH_SOURCE[0]}")/../files/logrotate.conf.rpm" '/etc/logrotate.conf'
    fi

    info '/etc/logrotate.conf'
    indentString '  ' "$(cat '/etc/logrotate.conf')"

    # Configure Cron

    cp -f -p '/etc/cron.daily/logrotate' '/etc/cron.hourly/logrotate'

    info '\n/etc/cron.hourly/logrotate'
    indentString '  ' "$(cat '/etc/cron.hourly/logrotate')"

    umask '0077'
}

function main()
{
    source "$(dirname "${BASH_SOURCE[0]}")/../../../libraries/util.bash"

    header 'INSTALLING LOGROTATE'

    checkRequireLinuxSystem
    checkRequireRootUser

    install
    installCleanUp
}

main "${@}"


text:
Module ecron_sup
================

Module ecron_sup

* [Description](#description)
* [Function Index](#index)
* [Function Details](#functions)

Supervisor module.

__Authors:__ Francesca Gangemi ([`francesca.gangemi@erlang-solutions.com`](mailto:francesca.gangemi@erlang-solutions.com)).

Function Index

init/1	Whenever a supervisor is started using supervisor:start_link/2,3,
this function is called by the new process to find out about restart strategy,
maximum restart frequency and child specifications.

start_link/0	Starts the supervisor.

Function Details

init/1

init(Args) -> {ok, {SupFlags, [ChildSpec]}} | ignore

Whenever a supervisor is started using supervisor:start_link/2,3,
this function is called by the new process to find out about restart strategy,
maximum restart frequency and child specifications.

start_link/0

start_link() -> {ok, Pid} | ignore | {error, Error}

Starts the supervisor


text:
package io.github.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.utility;

import java.util.logging.Logger;
import org.openscience.cdk.formula.MolecularFormulaRange;
import org.openscience.cdk.interfaces.IIsotope;
import org.openscience.cdk.interfaces.IMolecularFormula;

import io.github.mzmine.datamodel.impl.SimpleIsotopePattern;
import io.github.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.datamodel.ProcessedDataPoint;
import io.github.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.datamodel.results.DPPIsotopePatternResult;
import io.github.mzmine.modules.visualization.spectra.simplespectra.datapointprocessing.datamodel.results.DPPResult.ResultType;
import io.github.mzmine.util.FormulaUtils;
import io.github.mzmine.util.IsotopePatternUtils;

/**
 * Used to calculate parameter values based on the results of data point processing modules.
 *
 * @author SteffenHeu steffen.heuckeroth@gmx.de / s_heuc03@uni-muenster.de
 *
 */
public class DynamicParameterUtils {

  private static Logger logger = Logger.getLogger(DynamicParameterUtils.class.getName());

  private static float lowerElementBoundaryPercentage = 0.75f;
  private static float upperElementBoundaryPercentage = 1.5f;

  public static float getLowerElementBoundaryPercentage() {
    return lowerElementBoundaryPercentage;
  }

  public static float getUpperElementBoundaryPercentage() {
    return upperElementBoundaryPercentage;
  }

  public static void setLowerElementBoundaryPercentage(float lowerElementBoundaryPercentage) {
    DynamicParameterUtils.lowerElementBoundaryPercentage = lowerElementBoundaryPercentage;
  }

  public static void setUpperElementBoundaryPercentage(float upperElementBoundaryPercentage) {
    DynamicParameterUtils.upperElementBoundaryPercentage = upperElementBoundaryPercentage;
  }

  /**
   * Creates an ElementParameter based on the previous processing results. If no results were
   * detected, the default value is returned. Upper and lower boundaries are chosen according to
   * lowerElementBoundaryPercentage and upperElementBoundaryPercentage values of this utility class.
   * These values can be set via {@link #setLowerElementBoundaryPercentage} and
   * {@link #setUpperElementBoundaryPercentage}. The elements contained in
   *
   * @param dp The data point to build a parameter for.
   * @param def The default set of parameters.
   * @return The built ElementsCompositionRangeParameter
   */
  public static MolecularFormulaRange buildFormulaRangeOnIsotopePatternResults(
      ProcessedDataPoint dp, MolecularFormulaRange def) {

    DPPIsotopePatternResult result =
        (DPPIsotopePatternResult) dp.getFirstResultByType(ResultType.ISOTOPEPATTERN);
    if (result == null)
      return def;

    if (!(result.getValue() instanceof SimpleIsotopePattern))
      return def;

    SimpleIsotopePattern pattern = (SimpleIsotopePattern) result.getValue();
    String form = IsotopePatternUtils.makePatternSuggestion(pattern.getIsotopeCompositions());

    MolecularFormulaRange range = new MolecularFormulaRange();

    IMolecularFormula formula = FormulaUtils.createMajorIsotopeMolFormula(form);
    if (formula == null) {
      logger.finest("could not generate formula for m/z " + dp.getMZ() + " " + form);
      return def;
    }

    for (IIsotope isotope : def.isotopes())
      range.addIsotope(isotope, def.getIsotopeCountMin(isotope), def.getIsotopeCountMax(isotope));

    for (IIsotope isotope : formula.isotopes()) {
      if (range.contains(isotope))
        continue;

      int count = formula.getIsotopeCount(isotope);

      range.addIsotope(isotope, (int) (count * lowerElementBoundaryPercentage),
          (int) (count * upperElementBoundaryPercentage));
    }

    for (IIsotope isotope : range.isotopes()) {
      int min = range.getIsotopeCountMin(isotope);
      int max = range.getIsotopeCountMax(isotope);
      // logger.info("m/z = " + dp.getMZ() + " " + isotope.getSymbol() + "
      // " + min + " - " + max);
    }

    return range;
  }

}


text:
package com.wincom.actor.editor.test2;

import org.eclipse.swt.graphics.Point;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

	public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
		super(configurer);
	}

	public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
		return new ApplicationActionBarAdvisor(configurer);
	}

	public void preWindowOpen() {
		IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
		configurer.setInitialSize(new Point(400, 300));
		configurer.setShowCoolBar(false);
		configurer.setShowStatusLine(false);
		configurer.setTitle("TutoGEF RCP"); //$NON-NLS-1$
	}

}


text:
package org.apache.kylin.job.cmd;

import org.apache.kylin.common.util.CliCommandExecutor;
import org.apache.kylin.job.constant.JobStepStatusEnum;
import org.apache.kylin.job.exception.JobException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.*;

/**
 * @author xjiang
 *
 */
public class ShellCmd implements IJobCommand {

    private static Logger log = LoggerFactory.getLogger(ShellCmd.class);

    private final String executeCommand;
    private final ICommandOutput output;
    private final boolean isAsync;
    private final CliCommandExecutor cliCommandExecutor;

    private FutureTask<Integer> future;

    protected ShellCmd(String executeCmd, ICommandOutput out, String host, String user, String password, boolean async) {
        this.executeCommand = executeCmd;
        this.output = out;
        cliCommandExecutor = new CliCommandExecutor();
        cliCommandExecutor.setRunAtRemote(host, user, password);
        this.isAsync = async;
    }

    public ShellCmd(String executeCmd, String host, String user, String password, boolean async) {
        this(executeCmd, new ShellCmdOutput(), host, user, password, async);
    }

    @Override
    public ICommandOutput execute() throws JobException {

        final ExecutorService executor = Executors.newSingleThreadExecutor();
        future = new FutureTask<Integer>(new Callable<Integer>() {
            public Integer call() throws JobException, IOException {
                executor.shutdown();
                return executeCommand(executeCommand);
            }
        });
        executor.execute(future);

        int exitCode = -1;
        if (!isAsync) {
            try {
                exitCode = future.get();
                log.info("finish executing");
            } catch (CancellationException e) {
                log.debug("Command is cancelled");
                exitCode = -2;
            } catch (Exception e) {
                throw new JobException("Error when execute job " + executeCommand, e);
            } finally {
                if (exitCode == 0) {
                    output.setStatus(JobStepStatusEnum.FINISHED);
                } else if (exitCode == -2) {
                    output.setStatus(JobStepStatusEnum.DISCARDED);
                } else {
                    output.setStatus(JobStepStatusEnum.ERROR);
                }
                output.setExitCode(exitCode);
            }
        }
        return output;
    }

    protected int executeCommand(String command) throws JobException, IOException {
        output.reset();
        output.setStatus(JobStepStatusEnum.RUNNING);
        return cliCommandExecutor.execute(command, output).getFirst();
    }

    @Override
    public void cancel() throws JobException {
        future.cancel(true);
    }

    public static void main(String[] args) throws JobException {
        ShellCmdOutput output = new ShellCmdOutput();
        ShellCmd shellCmd = new ShellCmd(args[0], output, args[1], args[2], args[3], false);
        shellCmd.execute();

        System.out.println("============================================================================");
        System.out.println(output.getExitCode());
        System.out.println(output.getOutput());
    }
}


text:
<?php

namespace Konsulting\Laravel\Transformer\RulePacks;

use Illuminate\Support\Collection;

class CoreRulePack extends RulePack
{
    /**
     * Convert empty values to null.
     *
     * @param  mixed  $value
     * @return mixed
     */
    public function ruleNullIfEmpty($value)
    {
        return empty($value) ? null : $value;
    }

    /**
     * Convert empty string values to null.
     *
     * @param  mixed  $value
     * @return mixed
     */
    public function ruleNullIfEmptyString($value)
    {
        return (is_string($value) && $value === '') ? null : $value;
    }

    /**
     * Stop processing rules if null.
     *
     * @param $value
     * @return mixed
     */
    public function ruleBailIfNull($value)
    {
        $this->transformer->bail(is_null($value));

        return $value;
    }

    /**
     * Return null if empty, and stop processing rules.
     *
     * @param $value
     * @return null
     */
    public function ruleReturnNullIfEmpty($value)
    {
        return $this->ruleBailIfNull($this->ruleNullIfEmpty($value));
    }

    /**
     * Return null if empty string, and stop processing rules.
     *
     * @param $value
     * @return null
     */
    public function ruleReturnNullIfEmptyString($value)
    {
        return $this->ruleBailIfNull($this->ruleNullIfEmptyString($value));
    }

    /**
     * Drop field if value is null.
     *
     * @param $value
     * @return null
     */
    public function ruleDropIfNull($value)
    {
        $this->transformer->drop(is_null($value));

        return $value;
    }

    /**
     * Drop field if value equates to empty.
     *
     * @param $value
     * @return null
     */
    public function ruleDropIfEmpty($value)
    {
        return $this->ruleDropIfNull($this->ruleNullIfEmpty($value));
    }

    /**
     * Drop field if value equates to empty string.
     *
     * @param $value
     * @return null
     */
    public function ruleDropIfEmptyString($value)
    {
        return $this->ruleDropIfNull($this->ruleNullIfEmptyString($value));
    }

    /**
     * Trim surrounding whitespace.
     *
     * @param  $value
     * @param  string  $trim
     * @return string
     */
    public function ruleTrim($value, $trim = null)
    {
        return is_string($value)
            ? is_null($trim) ? trim($value) : trim($value, $trim)
            : $value;
    }

    /**
     * @param $value
     * @return string
     */
    public function ruleUppercase($value)
    {
        return strtoupper($this->ruleString($value));
    }

    /**
     * @param $value
     * @return string
     */
    public function ruleLowercase($value)
    {
        return strtolower($this->ruleString($value));
    }

    public function ruleString($value)
    {
        try {
            return is_array($value) ? str_putcsv($value) : (string) $value;
        } catch (\Exception $e) {
            return '';
        }
    }

    public function ruleBoolean($value)
    {
        return (bool) $value;
    }

    public function ruleArray($value)
    {
        return (array) $value;
    }

    public function ruleCollection($value)
    {
        return Collection::make($this->ruleArray($value));
    }

    public function ruleJson($value)
    {
        return $this->ruleCollection($value)->toJson();
    }

    public function ruleFloat($value)
    {
        return (float) preg_replace('/[^\d,.]/', '', $value);
    }

    public function ruleInteger($value)
    {
        return (int) $this->ruleFloat($value);
    }

    /**
     * Alias of ruleInteger.
     */
    public function ruleInt($value)
    {
        return $this->ruleInteger($value);
    }

    public function ruleDateTime($value, $timezone = null)
    {
        return new \DateTime($value, $timezone);
    }

    public function ruleDateTimeImmutable($value, $timezone = null)
    {
        return new \DateTimeImmutable($value, $timezone);
    }

    public function ruleRegexReplace($value, $regex = '*', $replace = '')
    {
        return preg_replace('/' . $regex . '/', $replace, $value);
    }

    /*
     * Return only numeric characters
     */
    public function ruleNumeric($value)
    {
        return preg_replace('/[^\pN]/u', '', $value);
    }

    /*
     * Return only alphabetic characters
     */
    public function ruleAlpha($value)
    {
        return preg_replace('/[^\pL\pM\s]/u', '', $value);
    }

    /*
     * Return only alphabetic characters, underscore or dash
     */
    public function ruleAlphaDash($value)
    {
        return preg_replace('/[^\pL\pM\s_-]/u', '', $value);
    }

    /*
     * Return only alphabetic and numeric characters
     */
    public function ruleAlphaNum($value)
    {
        return preg_replace('/[^\pL\pM\pN\s]/u', '', $value);
    }

    /*
     * Return only alphabetic, numeric, underscore and dash characters
     */
    public function ruleAlphaNumDash($value)
    {
        return preg_replace('/[^\pL\pM\pN\s_-]/u', '', $value);
    }

    /*
     * Perform string replacement.
     */
    public function ruleReplace($value, $search, $replace)
    {
        return str_replace($search, $replace, $value);
    }
}


text:
namespace SharePoint.Scanning.Framework
{
    /// <summary>
    /// Base class for scan results
    /// </summary>
    public class Scan
    {
        public string SiteURL { get; set; }
        public string SiteColUrl { get; set; }
    }
}


text:
zarkov
======

Zarkov is a Lightweight Map-Reduce Framework

Reference
======

1、http://blog.pythonisito.com/2011/07/zarkov-is-lightweight-map-reduce.html
2、http://blog.pythonisito.com/2011/07/zarkov-is-event-logger.html
3、http://www.slideshare.net/rick446/realtime-analytics-using-mongodb-python-gevent-and-zeromq

Author
======

Rick Copeland,
http://www.slideshare.net/rick446?utm_campaign=profiletracking&utm_medium=sssite&utm_source=ssslideview


text:
package com.team2052.frckrawler.database;

import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;

import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.team2052.frckrawler.R;
import com.team2052.frckrawler.bluetooth.RobotComment;
import com.team2052.frckrawler.comparators.MatchNumberComparator;
import com.team2052.frckrawler.comparators.RobotTeamNumberComparator;
import com.team2052.frckrawler.database.metric.MetricHelper;
import com.team2052.frckrawler.db.DaoMaster;
import com.team2052.frckrawler.db.DaoSession;
import com.team2052.frckrawler.db.Event;
import com.team2052.frckrawler.db.EventDao;
import com.team2052.frckrawler.db.Game;
import com.team2052.frckrawler.db.GameDao;
import com.team2052.frckrawler.db.Match;
import com.team2052.frckrawler.db.MatchComment;
import com.team2052.frckrawler.db.MatchCommentDao;
import com.team2052.frckrawler.db.MatchDao;
import com.team2052.frckrawler.db.MatchData;
import com.team2052.frckrawler.db.MatchDataDao;
import com.team2052.frckrawler.db.Metric;
import com.team2052.frckrawler.db.MetricDao;
import com.team2052.frckrawler.db.PitData;
import com.team2052.frckrawler.db.PitDataDao;
import com.team2052.frckrawler.db.Robot;
import com.team2052.frckrawler.db.RobotDao;
import com.team2052.frckrawler.db.RobotEvent;
import com.team2052.frckrawler.db.RobotEventDao;
import com.team2052.frckrawler.db.Team;
import com.team2052.frckrawler.db.TeamDao;
import com.team2052.frckrawler.db.User;
import com.team2052.frckrawler.db.UserDao;
import com.team2052.frckrawler.tba.JSON;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Singleton;

import de.greenrobot.dao.query.QueryBuilder;
import rx.Observable;

/**
 * Used to keep a clean database
 * There is no CASCADE ON DELETE function with greenDAO, so we have to configure it manually.
 *
 * @author Adam
 * @since 10/7/2014
 */
@Singleton
public class  DBManager {
    private static DBManager instance;
    private final Games mGames;
    private final Events mEvents;
    private final Robots mRobots;
    private final Metrics mMetrics;
    private final RobotEvents mRobotEvents;
    private final MatchComments mMatchComments;
    private final MatchDatas mMatchDatas;
    private final PitDatas mPitDatas;
    private final Matches mMatches;
    private final Teams mTeams;
    private final Users mUsers;

    private final MatchDataDao matchDataDao;
    private final PitDataDao pitDataDao;
    private final GameDao gameDao;
    private final MatchCommentDao matchCommentDao;
    private final RobotEventDao robotEventDao;
    private final MatchDao matchDao;
    private final MetricDao metricDao;
    private final UserDao userDao;
    private final RobotDao robotDao;
    private final DaoMaster daoMaster;
    private final EventDao eventDao;

    private Context context;
    private DaoSession daoSession;

    private TeamDao teamDao;

    private DBManager(Context context) {
        this.context = context;

        DaoMaster.OpenHelper helper = new DatabaseHelper(context, "frc-krawler-database-v3", null);

        SQLiteDatabase db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();

        //DAO's
        matchDataDao = daoSession.getMatchDataDao();
        pitDataDao = daoSession.getPitDataDao();
        matchCommentDao = daoSession.getMatchCommentDao();
        robotEventDao = daoSession.getRobotEventDao();
        matchDao = daoSession.getMatchDao();
        metricDao = daoSession.getMetricDao();
        teamDao = daoSession.getTeamDao();
        userDao = daoSession.getUserDao();
        gameDao = daoSession.getGameDao();
        eventDao = daoSession.getEventDao();
        robotDao = daoSession.getRobotDao();

        mGames = new Games();
        mEvents = new Events();
        mRobots = new Robots();
        mMetrics = new Metrics();
        mRobotEvents = new RobotEvents();
        mMatchComments = new MatchComments();
        mMatchDatas = new MatchDatas();
        mPitDatas = new PitDatas();
        mMatches = new Matches();
        mTeams = new Teams();
        mUsers = new Users();
    }

    public static synchronized DBManager getInstance(Context context) {
        if (instance == null) {
            instance = new DBManager(context);
        }
        return instance;
    }

    public void runInTx(Runnable runnable) {
        daoSession.runInTx(runnable);
    }

    public void deleteAll() {
        matchDataDao.deleteAll();
        pitDataDao.deleteAll();
        gameDao.deleteAll();
        matchCommentDao.deleteAll();
        robotEventDao.deleteAll();
        matchDao.deleteAll();
        metricDao.deleteAll();
        userDao.deleteAll();
        robotDao.deleteAll();
        eventDao.deleteAll();
    }

    public Games getGamesTable() {
        return mGames;
    }

    public Events getEventsTable() {
        return mEvents;
    }

    public Robots getRobotsTable() {
        return mRobots;
    }

    public Metrics getMetricsTable() {
        return mMetrics;
    }

    public RobotEvents getRobotEvents() {
        return mRobotEvents;
    }

    public MatchComments getMatchComments() {
        return mMatchComments;
    }

    public MatchDatas getMatchDataTable() {
        return mMatchDatas;
    }

    public PitDatas getPitDataTable() {
        return mPitDatas;
    }

    public Matches getMatchesTable() {
        return mMatches;
    }

    public Teams getTeamsTable() {
        return mTeams;
    }

    public Observable<Map<String, String>> teamInfo(long team_id) {
        return Observable.create(subscriber -> {
            Team team = getTeamsTable().load(team_id);
            Map<String, String> info = Maps.newLinkedHashMap();
            info.put("Nickname", team.getName());

            JsonObject data = JSON.getAsJsonObject(team.getData());

            if (data.has("rookie_year") && !data.get("rookie_year").isJsonNull()) {
                info.put("Rookie Year", data.get("rookie_year").getAsString());
            }

            if (data.has("long_name") && !data.get("long_name").isJsonNull()) {
                info.put("Name", data.get("long_name").getAsString());
            }
            subscriber.onNext(info);
            subscriber.onCompleted();
        });
    }

    public Users getUsersTable() {
        return mUsers;
    }

    public Observable<List<Event>> eventsByGame(long game_id) {
        return Observable.create(subscriber -> {
            subscriber.onStart();
            List<Event> events = getEventsTable().getQueryBuilder().where(EventDao.Properties.Game_id.eq(game_id)).list();
            subscriber.onNext(events);

            subscriber.onCompleted();
        });
    }

    public Observable<List<Event>> allEvents() {
        return Observable.create(subscriber -> {
            List<Event> events = getEventsTable().loadAll();
            subscriber.onNext(events);

            subscriber.onCompleted();
        });
    }

    public Observable<List<Event>> robotAtEvents(long robot_id) {
        return Observable.create(subscriber -> {
            List<Event> events = new ArrayList<>();
            Robot load = getRobotsTable().load(robot_id);
            List<RobotEvent> robotEventList = load.getRobotEventList();
            for (int i = 0; i < robotEventList.size(); i++) {
                events.add(robotEventList.get(i).getEvent());
            }
            subscriber.onNext(events);
            subscriber.onCompleted();
        });
    }

    public Observable<List<Robot>> robotsWithTeam(long team_id) {
        return Observable.create(subscriber -> {
            List<Robot> robots = getRobotsTable().getQueryBuilder().where(RobotDao.Properties.Team_id.eq(team_id)).list();
            subscriber.onNext(robots);
            subscriber.onCompleted();
        });
    }

    public Observable<List<Robot>> robotsAtEvent(long event_id) {
        return Observable.create(subscriber -> {
            Event event = getEventsTable().load(event_id);
            List<RobotEvent> robotEvents = getEventsTable().getRobotEvents(event);
            List<Robot> robots = new ArrayList<>();
            for (int i = 0; i < robotEvents.size(); i++) {
                robots.add(robotEvents.get(i).getRobot());
            }
            Collections.sort(robots, new RobotTeamNumberComparator());
            subscriber.onNext(robots);

            subscriber.onCompleted();
        });
    }

    public Observable<List<Game>> allGames() {
        return Observable.create(subscriber -> {
            List<Game> games = getGamesTable().loadAll();
            subscriber.onNext(games);

            subscriber.onCompleted();
        });
    }

    public Observable<List<Metric>> metricsInGame(long game_id, Integer category) {
        return Observable.create(subscriber -> {
            QueryBuilder<Metric> where = getMetricsTable().getQueryBuilder().where(MetricDao.Properties.Game_id.eq(game_id));
            if (category != null)
                where.where(MetricDao.Properties.Category.eq(category));
            List<Metric> metrics = where.list();
            subscriber.onNext(metrics);
            subscriber.onCompleted();
        });
    }

    public Observable<List<Team>> allTeams() {
        return Observable.create(subscriber -> {
            List<Team> teams = getTeamsTable().getQueryBuilder().orderAsc(TeamDao.Properties.Number).list();
            subscriber.onNext(teams);
            subscriber.onCompleted();
        });
    }

    public Observable<List<Match>> matchesAtEvent(long event_id) {
        return Observable.create(subscriber -> {
            List<Match> matches = getMatchesTable().getQueryBuilder().where(MatchDao.Properties.Event_id.eq(event_id)).list();
            Collections.sort(matches, new MatchNumberComparator());
            subscriber.onNext(matches);
            subscriber.onCompleted();
        });
    }

    public Observable<? extends Map<String, String>> gameInfo(Game mGame) {
        return Observable.create(subscriber -> {
            Map<String, String> info = Maps.newLinkedHashMap();
            mGame.resetEventList();
            mGame.resetRobotList();
            Resources resources = context.getResources();
            info.put(resources.getString(R.string.game_info_num_of_event), Integer.toString(mGame.getEventList().size()));
            info.put(resources.getString(R.string.game_info_num_of_robots), Integer.toString(mGame.getRobotList().size()));
            info.put(resources.getString(R.string.game_info_num_of_match_metrics), Integer.toString(getMetricsTable().getNumberOfMetrics(mGame, MetricHelper.MATCH_PERF_METRICS)));
            info.put(resources.getString(R.string.game_info_num_of_pit_metrics), Integer.toString(getMetricsTable().getNumberOfMetrics(mGame, MetricHelper.ROBOT_METRICS)));

            subscriber.onNext(info);
            subscriber.onCompleted();
        });
    }

    public Observable<? extends Map<String, String>> eventInfo(Event event) {
        return Observable.create(subscriber -> {
            Map<String, String> info = Maps.newLinkedHashMap();
            Resources resources = context.getResources();
            info.put(resources.getString(R.string.event_info_num_of_teams), Integer.toString(getEventsTable().getTeamsAtEvent(event).size()));
            info.put(resources.getString(R.string.event_info_num_of_matches), Integer.toString(getEventsTable().getMatches(event).size()));
            info.put(resources.getString(R.string.event_info_num_of_pit_data), Integer.toString(getEventsTable().getPitData(event).size()));
            info.put(resources.getString(R.string.event_info_num_of_match_data), Integer.toString(getEventsTable().getMatchData(event).size()));
            subscriber.onNext(info);
            subscriber.onCompleted();
        });
    }

    public Observable<? extends Map<String, String>> metricInfo(long metricId) {
        return Observable.just(metricId)
                .map(metricDao::load)
                .map(metric -> {
                    Map<String, String> info = Maps.newLinkedHashMap();
                    info.put("Enabled",
                            CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, String.valueOf(metric.getEnabled())));

                    final JsonObject data = JSON.getAsJsonObject(metric.getData());
                    switch (metric.getType()) {
                        case MetricHelper.BOOLEAN:
                            break;
                        case MetricHelper.CHOOSER:
                        case MetricHelper.CHECK_BOX:
                            final String values = Joiner.on(", ").join(data.get("values").getAsJsonArray());
                            info.put("Comma Separated List", Strings.isNullOrEmpty(values) ? "No Values" : values);
                            break;
                        case MetricHelper.COUNTER:
                            info.put("Incrementation", data.get("inc").toString());
                        case MetricHelper.SLIDER:
                            info.put("Minimum", data.get("min").toString());
                            info.put("Maximum", data.get("max").toString());
                    }
                    return info;
                });
    }

    private interface Table<T> {
        T load(long id);

        void delete(T model);

        void delete(List<T> models);

        QueryBuilder<T> getQueryBuilder();
    }

    public class Games implements Table<Game> {
        @Override
        public Game load(long id) {
            return gameDao.load(id);
        }

        public List<Robot> getRobots(Game game) {
            game.resetRobotList();
            return game.getRobotList();
        }

        public List<Event> getEvents(Game game) {
            game.resetEventList();
            return game.getEventList();
        }

        public List<Metric> getMetrics(Game game) {
            game.resetMetricList();
            return game.getMetricList();
        }

        public void insert(Game game) {
            gameDao.insertOrReplace(game);
        }

        public List<Game> loadAll() {
            return gameDao.loadAll();
        }

        @Override
        public void delete(List<Game> games) {
            for (Game game : games) {
                delete(game);
            }
        }

        @Override
        public QueryBuilder<Game> getQueryBuilder() {
            return gameDao.queryBuilder();
        }

        @Override
        public void delete(Game game) {
            game.resetEventList();
            game.resetRobotList();
            game.resetMetricList();
            DBManager.this.getEventsTable().delete(game.getEventList());
            DBManager.this.getRobotsTable().delete(game.getRobotList());
            gameDao.delete(game);
        }
    }

    public class Events implements Table<Event> {

        public List<Event> loadAll() {
            return eventDao.loadAll();
        }

        public List<Robot> getRobots(Event event) {
            List<Robot> robots = new ArrayList<>();
            for (RobotEvent robotEvent : getRobotEvents(event)) {
                robots.add(DBManager.this.getRobotEvents().getRobot(robotEvent));
            }
            return robots;
        }

        public List<RobotEvent> getRobotEvents(Event event) {
            event.resetRobotEventList();
            return event.getRobotEventList();
        }

        public Game getGame(Event event) {
            return getGamesTable().load(event.getGame_id());
        }

        public List<Team> getTeamsAtEvent(Event event) {
            List<RobotEvent> robotEventList = event.getRobotEventList();
            List<Team> teams = Lists.newArrayList();
            for (RobotEvent robotEvent : robotEventList) {
                teams.add(DBManager.this.getRobotEvents().getTeam(robotEvent));
            }
            Collections.sort(teams, (lhs, rhs) -> Double.compare(lhs.getNumber(), rhs.getNumber()));
            return teams;
        }

        @Override
        public Event load(long id) {
            return eventDao.load(id);
        }

        public void insert(Event event) {
            eventDao.insertOrReplace(event);
        }

        public QueryBuilder<Event> query(String fms_id, Long game_id) {
            QueryBuilder<Event> queryBuilder = getQueryBuilder();
            if (fms_id != null)
                queryBuilder.where(EventDao.Properties.Fmsid.eq(fms_id));
            if (game_id != null)
                queryBuilder.where(EventDao.Properties.Game_id.eq(game_id));
            return queryBuilder;
        }

        public List<Match> getMatches(Event event) {
            event.resetMatchList();
            return event.getMatchList();
        }

        public List<MatchData> getMatchData(Event event) {
            event.resetMatchDataList();
            return event.getMatchDataList();
        }

        public List<PitData> getPitData(Event event) {
            event.resetPitDataList();
            return event.getPitDataList();
        }

        public List<MatchComment> getMatchComments(Event event) {
            event.resetMatchCommentList();
            return event.getMatchCommentList();
        }

        @Override
        public void delete(List<Event> events) {
            for (Event event : events) {
                delete(event);
            }
        }

        @Override
        public QueryBuilder<Event> getQueryBuilder() {
            return eventDao.queryBuilder();
        }

        @Override
        public void delete(Event model) {
            getMatchDataTable().delete(getMatchData(model));
            getPitDataTable().delete(getPitData(model));
            DBManager.this.getMatchComments().delete(getMatchComments(model));
            getMatchesTable().delete(getMatches(model));
            DBManager.this.getRobotEvents().delete(getRobotEvents(model));
            eventDao.delete(model);
        }

        public List<Event> getAllEvents() {
            return eventDao.loadAll();
        }
    }

    public class MatchComments implements Table<MatchComment> {
        public boolean insertMatchComment(MatchComment matchComment) {
            matchComment.setId(null);
            QueryBuilder<MatchComment> matchCommentQueryBuilder = matchCommentDao.queryBuilder();
            matchCommentQueryBuilder.where(MatchCommentDao.Properties.Event_id.eq(matchComment.getEvent_id()));
            matchCommentQueryBuilder.where(MatchCommentDao.Properties.Robot_id.eq(matchComment.getRobot_id()));
            matchCommentQueryBuilder.where(MatchCommentDao.Properties.Match_number.eq(matchComment.getMatch_number()));
            matchCommentQueryBuilder.where(MatchCommentDao.Properties.Match_type.eq(matchComment.getMatch_type()));
            long count = matchCommentQueryBuilder.count();
            if (count > 0) {
                MatchComment currentData = matchCommentQueryBuilder.unique();
                if (currentData.getLast_updated().getTime() <= System.currentTimeMillis()) {
                    currentData.setLast_updated(new Date());
                    currentData.setComment(matchComment.getComment());
                    matchCommentDao.update(currentData);
                }
                return false;
            } else {
                matchComment.setLast_updated(new Date());
                matchCommentDao.insert(matchComment);
                return true;
            }
        }

        public QueryBuilder<MatchComment> query(Long match_number, Integer game_type, Long robot_id, Long event_id) {
            QueryBuilder<MatchComment> queryBuilder = getQueryBuilder();
            if (match_number != null)
                queryBuilder.where(MatchCommentDao.Properties.Match_number.eq(match_number));
            if (game_type != null)
                queryBuilder.where(MatchCommentDao.Properties.Match_type.eq(game_type));
            if (robot_id != null)
                queryBuilder.where(MatchCommentDao.Properties.Robot_id.eq(robot_id));
            if (event_id != null)
                queryBuilder.where(MatchCommentDao.Properties.Event_id.eq(event_id));
            return queryBuilder;
        }

        public List<MatchComment> loadAll() {
            return matchCommentDao.loadAll();
        }

        @Override
        public MatchComment load(long id) {
            return matchCommentDao.load(id);
        }

        @Override
        public void delete(MatchComment matchComment) {
            matchCommentDao.delete(matchComment);
        }

        @Override
        public void delete(List<MatchComment> models) {
            for (MatchComment model : models) {
                delete(model);
            }
        }

        @Override
        public QueryBuilder<MatchComment> getQueryBuilder() {
            return matchCommentDao.queryBuilder();
        }
    }

    public class PitDatas implements Table<PitData> {
        public boolean insert(PitData pitData) {
            pitData.setId(null);
            QueryBuilder<PitData> pitDataQueryBuilder = pitDataDao.queryBuilder();
            pitDataQueryBuilder.where(PitDataDao.Properties.Robot_id.eq(pitData.getRobot_id()));
            pitDataQueryBuilder.where(PitDataDao.Properties.Metric_id.eq(pitData.getMetric_id()));
            long count = pitDataQueryBuilder.count();

            if (count > 0) {
                PitData unique = pitDataQueryBuilder.unique();
                if (unique.getLast_updated().getTime() <= System.currentTimeMillis()) {
                    unique.setLast_updated(new Date());
                    unique.setData(pitData.getData());
                    pitDataDao.update(unique);
                }
                return false;
            } else {
                pitData.setLast_updated(new Date());
                pitDataDao.insert(pitData);
                return true;
            }
        }

        public QueryBuilder<PitData> query(Long robot_id, Long metric_id, Long event_id, @Deprecated Long user_id) {
            QueryBuilder<PitData> queryBuilder = getQueryBuilder();
            if (robot_id != null)
                queryBuilder.where(PitDataDao.Properties.Robot_id.eq(robot_id));
            if (metric_id != null)
                queryBuilder.where(PitDataDao.Properties.Metric_id.eq(metric_id));
            if (event_id != null)
                queryBuilder.where(PitDataDao.Properties.Event_id.eq(event_id));
            if (user_id != null)
                queryBuilder.where(PitDataDao.Properties.User_id.eq(user_id));
            return queryBuilder;
        }

        public Metric getMetric(PitData pitData) {
            return getMetricsTable().load(pitData.getMetric_id());
        }

        public List<PitData> loadAll() {
            return pitDataDao.loadAll();
        }

        @Override
        public PitData load(long id) {
            return pitDataDao.load(id);
        }

        @Override
        public void delete(PitData model) {
            pitDataDao.delete(model);
        }

        @Override
        public void delete(List<PitData> models) {
            for (PitData data : models) {
                delete(data);
            }
        }

        @Override
        public QueryBuilder<PitData> getQueryBuilder() {
            return pitDataDao.queryBuilder();
        }

    }

    public class MatchDatas implements Table<MatchData> {
        public boolean insertMatchData(MatchData matchData) {
            matchData.setId(null);
            QueryBuilder<MatchData> matchDataQueryBuilder = matchDataDao.queryBuilder();
            matchDataQueryBuilder.where(MatchDataDao.Properties.Robot_id.eq(matchData.getRobot_id()));
            matchDataQueryBuilder.where(MatchDataDao.Properties.Metric_id.eq(matchData.getMetric_id()));
            matchDataQueryBuilder.where(MatchDataDao.Properties.Match_number.eq(matchData.getMatch_number()));
            matchDataQueryBuilder.where(MatchDataDao.Properties.Event_id.eq(matchData.getEvent_id()));
            matchDataQueryBuilder.where(MatchDataDao.Properties.Match_type.eq(matchData.getMatch_type()));
            long count = matchDataQueryBuilder.count();

            if (count > 0) {
                MatchData unique = matchDataQueryBuilder.unique();
                if (unique.getLast_updated().getTime() <= matchData.getLast_updated().getTime()) {
                    unique.setLast_updated(new Date());
                    unique.setData(matchData.getData());
                    matchDataDao.update(unique);
                }
                return false;
            } else {
                matchData.setLast_updated(new Date());
                matchDataDao.insert(matchData);
                return true;
            }
        }

        public QueryBuilder<MatchData> query(Long robotId, Long metricId, Long match_number, Integer match_type, Long eventId, Long userId) {
            QueryBuilder<MatchData> matchDataQueryBuilder = getQueryBuilder();
            if (robotId != null)
                matchDataQueryBuilder.where(MatchDataDao.Properties.Robot_id.eq(robotId));
            if (metricId != null)
                matchDataQueryBuilder.where(MatchDataDao.Properties.Metric_id.eq(metricId));
            if (match_number != null)
                matchDataQueryBuilder.where(MatchDataDao.Properties.Match_number.eq(match_number));
            if (match_type != null)
                matchDataQueryBuilder.where(MatchDataDao.Properties.Match_type.eq(match_type));
            if (eventId != null)
                matchDataQueryBuilder.where(MatchDataDao.Properties.Event_id.eq(eventId));
            if (userId != null)
                matchDataQueryBuilder.where(MatchDataDao.Properties.User_id.eq(userId));
            return matchDataQueryBuilder;
        }

        public Metric getMetric(MatchData matchData) {
            return getMetricsTable().load(matchData.getMetric_id());
        }

        public List<MatchData> loadAll() {
            return matchDataDao.loadAll();
        }

        @Override
        public MatchData load(long id) {
            return matchDataDao.load(id);
        }

        @Override
        public void delete(MatchData model) {
            matchDataDao.delete(model);
        }

        @Override
        public void delete(List<MatchData> models) {
            for (MatchData model : models) {
                delete(model);
            }
        }

        @Override
        public QueryBuilder<MatchData> getQueryBuilder() {
            return matchDataDao.queryBuilder();
        }

    }

    public class Metrics implements Table<Metric> {
        public int getNumberOfMetrics(Game game, int metric_category) {
            QueryBuilder<Metric> metricQueryBuilder = metricDao.queryBuilder();
            metricQueryBuilder.where(MetricDao.Properties.Game_id.eq(game.getId()));
            metricQueryBuilder.where(MetricDao.Properties.Category.eq(metric_category));

            return (int) metricQueryBuilder.count();
        }

        public QueryBuilder<Metric> query(@MetricHelper.MetricCategory Integer category, Integer type, Long game_id, Boolean enabled) {
            QueryBuilder<Metric> queryBuilder = getQueryBuilder();
            if (category != null)
                queryBuilder.where(MetricDao.Properties.Category.eq(category));
            if (type != null)
                queryBuilder.where(MetricDao.Properties.Type.eq(type));
            if (game_id != null)
                queryBuilder.where(MetricDao.Properties.Game_id.eq(game_id));
            if (enabled != null)
                queryBuilder.where(MetricDao.Properties.Enabled.eq(enabled));
            return queryBuilder;
        }

        public void insert(Metric metric) {
            metricDao.insertOrReplace(metric);
        }

        public List<MatchData> getMatchDataList(Metric metric) {
            metric.resetMatchDataList();
            return metric.getMatchDataList();
        }

        @Override
        public Metric load(long id) {
            return metricDao.load(id);
        }

        public List<PitData> getPitDataList(Metric metric) {
            metric.resetPitDataList();
            return metric.getPitDataList();
        }

        @Override
        public void delete(Metric metric) {
            metric.resetMatchDataList();
            metric.resetPitDataList();

            pitDataDao.deleteInTx(metric.getPitDataList());
            matchDataDao.deleteInTx(metric.getMatchDataList());
            metricDao.delete(metric);
        }

        @Override
        public void delete(List<Metric> models) {
            for (Metric model : models) {
                delete(model);
            }
        }

        @Override
        public QueryBuilder<Metric> getQueryBuilder() {
            return metricDao.queryBuilder();
        }
    }

    public class Robots implements Table<Robot> {
        public Game getGame(Robot mRobot) {
            return getGamesTable().load(mRobot.getGame_id());
        }

        public Team getTeam(Robot robot) {
            return teamDao.load(robot.getTeam_id());
        }

        public List<RobotComment> getRobotComments() {
            List<Robot> robots = robotDao.loadAll();
            List<RobotComment> robotComments = new ArrayList<>();

            for (Robot robot : robots) {
                robotComments.add(getRobotComment(robot));
            }

            return robotComments;
        }

        public RobotComment getRobotComment(Robot robot) {
            return new RobotComment(robot.getId(), robot.getComments());
        }

        public QueryBuilder<Robot> query(@Nullable Long team_number, @Nullable Long game_id) {
            QueryBuilder<Robot> robotQueryBuilder = getRobotsTable().getQueryBuilder();
            if (team_number != null)
                robotQueryBuilder.where(RobotDao.Properties.Team_id.eq(team_number));
            if (game_id != null)
                robotQueryBuilder.where(RobotDao.Properties.Game_id.eq(game_id));
            return robotQueryBuilder;
        }

        @Override
        public void delete(List<Robot> robots) {
            for (Robot robot : robots) {
                delete(robot);
            }
        }

        public void insert(Robot robot) {
            robotDao.insertOrReplace(robot);
        }

        public void update(Robot robot) {
            robotDao.update(robot);
        }

        public List<RobotEvent> getRobotEvents(Robot robot) {
            robot.resetRobotEventList();
            return robot.getRobotEventList();
        }

        @Override
        public QueryBuilder<Robot> getQueryBuilder() {
            return robotDao.queryBuilder();
        }

        @Override
        public Robot load(long id) {
            return robotDao.load(id);
        }

        @Override
        public void delete(Robot robot) {
            robotDao.delete(robot);
        }

    }

    public class RobotEvents implements Table<RobotEvent> {
        public Team getTeam(RobotEvent robotEvent) {
            return teamDao.load(getRobot(robotEvent).getTeam_id());
        }

        public Robot getRobot(RobotEvent robotEvent) {
            return getRobotsTable().load(robotEvent.getRobot_id());
        }

        public void insert(RobotEvent robotEvent) {
            robotEventDao.insert(robotEvent);
        }

        @Override
        public RobotEvent load(long id) {
            return robotEventDao.load(id);
        }

        @Override
        public void delete(RobotEvent model) {
            robotEventDao.delete(model);
        }

        @Override
        public void delete(List<RobotEvent> models) {
            for (RobotEvent model : models) {
                delete(model);
            }
        }

        @Override
        public QueryBuilder<RobotEvent> getQueryBuilder() {
            return robotEventDao.queryBuilder();
        }

    }

    public class Matches implements Table<Match> {
        public List<Team> getTeams(Match match) {
            JsonObject alliances = JSON.getAsJsonObject(match.getData()).get("alliances").getAsJsonObject();
            List<Team> teams = new ArrayList<>();
            JsonArray red = alliances.get("red").getAsJsonObject().get("teams").getAsJsonArray();
            JsonArray blue = alliances.get("blue").getAsJsonObject().get("teams").getAsJsonArray();
            teams.add(getTeamsTable().load(Long.parseLong(red.get(0).getAsString().replace("frc", ""))));
            teams.add(getTeamsTable().load(Long.parseLong(red.get(1).getAsString().replace("frc", ""))));
            teams.add(getTeamsTable().load(Long.parseLong(red.get(2).getAsString().replace("frc", ""))));
            teams.add(getTeamsTable().load(Long.parseLong(blue.get(0).getAsString().replace("frc", ""))));
            teams.add(getTeamsTable().load(Long.parseLong(blue.get(1).getAsString().replace("frc", ""))));
            teams.add(getTeamsTable().load(Long.parseLong(blue.get(2).getAsString().replace("frc", ""))));
            return teams;
        }

        public void insert(Match match) {
            matchDao.insertOrReplace(match);
        }

        public QueryBuilder<Match> query(Integer match_number, String key, Long event_id, String type) {
            QueryBuilder<Match> queryBuilder = getQueryBuilder();
            if (match_number != null)
                queryBuilder.where(MatchDao.Properties.Match_number.eq(match_number));
            if (key != null)
                queryBuilder.where(MatchDao.Properties.Match_key.eq(key));
            if (event_id != null)
                queryBuilder.where(MatchDao.Properties.Event_id.eq(event_id));
            if (type != null)
                queryBuilder.where(MatchDao.Properties.Event_id.eq(type));
            return queryBuilder;
        }

        @Override
        public Match load(long id) {
            return matchDao.load(id);
        }

        @Override
        public void delete(Match match) {
            matchDao.delete(match);
        }

        @Override
        public void delete(List<Match> models) {
            for (Match model : models) {
                delete(model);
            }
        }

        @Override
        public QueryBuilder<Match> getQueryBuilder() {
            return matchDao.queryBuilder();
        }

    }

    public class Teams implements Table<Team> {
        /**
         * Inserts team and Robot, and Robot Event
         *
         * @param team
         */
        public void insertNew(Team team, Event event) {
            boolean team_added = teamDao.load(team.getNumber()) != null;
            if (team_added) {
                team = teamDao.load(team.getNumber());
            } else {
                daoSession.insert(team);
            }

            //Check robot
            QueryBuilder<Robot> robotQueryBuilder = getRobotsTable().getQueryBuilder();
            robotQueryBuilder.where(RobotDao.Properties.Game_id.eq(event.getGame_id()));
            robotQueryBuilder.where(RobotDao.Properties.Team_id.eq(team.getNumber()));
            Robot robot = robotQueryBuilder.unique();
            boolean robot_added = robot != null;

            if (!robot_added) {
                robot = new Robot(null, team.getNumber(), event.getGame_id(), null, "", new Date());
                daoSession.insert(robot);
            }

            QueryBuilder<RobotEvent> robotEventQueryBuilder = getRobotEvents().getQueryBuilder();
            robotEventQueryBuilder.where(RobotEventDao.Properties.Event_id.eq(event.getId()));
            robotEventQueryBuilder.where(RobotEventDao.Properties.Robot_id.eq(robot.getId()));
            RobotEvent robotEvent = robotEventQueryBuilder.unique();
            boolean robot_event_exists = robotEvent != null;

            if (!robot_event_exists) {
                robotEvent = new RobotEvent(null, robot.getId(), event.getId(), null);
                daoSession.insert(robotEvent);
            }
        }

        @Deprecated
        /**
         * Please do not use this unless you really need to
         */
        public void insert(Team team) {
            teamDao.insertOrReplace(team);
        }

        @Override
        public Team load(long id) {
            return teamDao.load(id);
        }

        @Override
        public void delete(Team model) {
            teamDao.delete(model);
        }

        @Override
        public void delete(List<Team> models) {
            for (Team model : models) {
                delete(model);
            }
        }

        @Override
        public QueryBuilder<Team> getQueryBuilder() {
            return teamDao.queryBuilder();
        }
    }

    public class Users implements Table<User> {

        public List<User> loadAll() {
            return userDao.loadAll();
        }

        public void insert(User user) {
            userDao.insertOrReplace(user);
        }

        @Override
        public User load(long id) {
            return userDao.load(id);
        }

        @Override
        public void delete(User model) {
            userDao.delete(model);
        }

        @Override
        public void delete(List<User> models) {
            for (User model : models) {
                delete(model);
            }
        }

        @Override
        public QueryBuilder<User> getQueryBuilder() {
            return userDao.queryBuilder();
        }
    }
}


text:
module Ari
  class BridgeMerged < Event

    attr_reader :bridge, :bridge_from

    def bridge=(val)
      @bridge ||= Bridge.new(val)
    end

    def bridge_from=(val)
      @bridge_from ||= Bridge.new(val)
    end

  end
end


text:
<!DOCTYPE html>

<?php
include_once 'config.php';
$connected = "";
if (isset($_SESSION['nom'])){
  $connected = "
Connecter en tant ".$_SESSION['nom']."

Deconnexion
";
}
 ?>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
  <title>[DEV] SIX.DAVE</title>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/sweetalert.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

[DEV] SIX.DAVE V.2

        <?php echo $connected; ?>

Annuaire

Login

        <?php echo $connected; ?>

Annuaire

Login

      menu


text:
Contact Us

                        Full contact info and directions to the lab:
                        click here

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Website" id="website">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, user-scalable=no, maximum-scale=1.0"/>
    <title>邀请管理 - {wc:$webname}触屏版</title>
    <meta content="yes" name="apple-mobile-web-app-capable" />
    <meta content="black" name="apple-mobile-web-app-status-bar-style" />
    <meta content="telephone=no" name="format-detection" />
    <link href="{G_TEMPLATES_MOBILE_CSS}/comm.css?v=130715" rel="stylesheet" type="text/css" /><link href="{G_TEMPLATES_MOBILE_CSS}/member.css?v=130726" rel="stylesheet" type="text/css" />

	        <s></s>返回

邀请管理

                <s></s>{wc:$member['yungoudj']}

                {wc:fun:get_user_name($member['uid'])}({wc:$member['mobile']})

可用福分 {wc:$member['score']}

经验值 {wc:$member['jingyan']}

余额 ¥{wc:$member['money']}
                        去充值

邀请好友

邀请明细

佣金明细

申请提现

提现记录

{wc:templates "mobile/index","footer"}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

namespace SmoothGL.Graphics
{
    /// <summary>
    /// Represents a query which can be used to measure the time required for a number of graphics operations.
    /// </summary>
    public class TimeQuery : Query
    {
        public TimeQuery()
             : base(QueryTarget.TimeElapsed) { }

        /// <summary>
        /// Gets the required time for all graphics operations between <see cref="Query.Begin"/> and <see cref="Query.End"/>, measured in nanoseconds.
        /// This value is available when the query has finished.
        /// </summary>
        public int ElapsedTime
        {
            get
            {
                return Result;
            }
        }

        /// <summary>
        /// Gets the time since the start of the application, measured in nanoseconds.
        /// </summary>
        public static long Timestamp
        {
            get
            {
                long timestamp;
                GL.GetInteger64(GetPName.Timestamp, out timestamp);
                return timestamp;
            }
        }
    }
}


text:
<?php //-->

namespace Cradle\Http\Dispatcher;

use Cradle\Http\HttpDispatcher;

/**
 * Designed for the HttpHandler we are parting this out
 * to lessen the confusion
 *
 * @package  Cradle
 * @category Http
 * @author   Christian Blanquera <cblanquera@openovate.com>
 * @standard PSR-2
 */
trait DispatcherTrait
{
    /**
     * @var HttpDispatcher|null $dispatcher Response object to use
     */
    protected $dispatcher = null;

    /**
     * Returns a response object
     *
     * @return DispatcherInterface
     */
    public function getDispatcher(): DispatcherInterface
    {
        if (is_null($this->dispatcher)) {
            $this->setDispatcher($this->resolve(HttpDispatcher::class));
        }

        return $this->dispatcher;
    }

    /**
     * Sets the dispatcher to use
     *
     * @param DispatcherInterface $dispatcher
     *
     * @return DispatcherTrait
     */
    public function setDispatcher(DispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;

        return $this;
    }
}


text:
package example.service;

import example.repo.Customer285Repository;

import org.springframework.stereotype.Service;

@Service
public class Customer285Service {
	public Customer285Service(Customer285Repository repo) {}
}


text:
package com.rolfje.anonimatron.anonymizer;

import com.rolfje.anonimatron.synonyms.Synonym;

import java.sql.Date;
import java.util.Map;

/**
 * Provides functionality for consitently anonymizing a piece of data.
 *

 * Implementations of this interface must make sure that anonymization is done
 * in a reproducable manner. That is, if A transforms into B, it has to
 * consistently do so on each and every call.
 *

 * By doing this, anonimatron can guarantee that data is transformed
 * consistently accross all tables of the database, and referential constraints
 * can be re-enforced after anonymization.
 */
public interface Anonymizer {

    /**
     * @return The ID or name of this anonymizer, as used in the XML
     * configuration file. This is generally something along the lines
     * of "LASTNAME" or "UNEVENNUMBER". Please see the output of the
     * -configexample command line option when running Anonimatron.
     */
    String getType();

    /**
     * Anonymizes the given data into a non-tracable, non-reversible synonym,
     * and does it consistently, so that A always translates to B.
     *
     * @param from       the data to be anonymized, usually passed in as a
     *                   {@link String}, {@link Integer}, {@link Date} or other classes
     *                   which can be stored in a single JDBC database column.
     * @param size       the optional maximum size of the generated value
     * @param shortlived indicates that the generated synonym must have the
     *                   {@link Synonym#isShortLived()} boolean set
     * @return a {@link Synonym}
     */
    Synonym anonymize(Object from, int size, boolean shortlived);

    /**
     * Anonymizes the given data into a non-tracable, non-reversible synonym
     * with the provided parameters, and does it consistently, so that A
     * always translates to B.
     * @param from       the data to be anonymized, usually passed in as a
     *                   {@link String}, {@link Integer}, {@link java.sql.Date} or other classes
     *                   which can be stored in a single JDBC database column.
     * @param size       the optional maximum size of the generated value
     * @param shortlived indicates that the generated synonym must have the
     *                   {@link Synonym#isShortLived()} boolean set
     * @param parameters the parameters to be used by the anonymizer
     * @return a {@link Synonym}
     */
    default Synonym anonymize(Object from, int size, boolean shortlived, Map<String, String> parameters) {
        return anonymize(from, size, shortlived);
    }

}


text:
package com.thehen101.csgoexternal.util.serialisation;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.thehen101.csgoexternal.memory.Netvar;

public class NetvarDeserialiser implements JsonDeserializer<Netvar> {
	@Override
	public Netvar deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
		JsonObject jobject = json.getAsJsonObject();
		Netvar netvar = Netvar.valueOf(jobject.get("name").getAsString());
		netvar.setOffset(jobject.get("offset").getAsInt());
		return netvar;
	}
}


text:
/************************************************************************
 * Included Files
 ************************************************************************/

#include <nuttx/config.h>

#include <assert.h>

#include <nuttx/mqueue.h>
#include <nuttx/sched.h>

#include "mqueue/mqueue.h"

/************************************************************************
 * Pre-processor Definitions
 ************************************************************************/

/************************************************************************
 * Private Type Declarations
 ************************************************************************/

/************************************************************************
 * Public Variables
 ************************************************************************/

/************************************************************************
 * Private Variables
 ************************************************************************/

/************************************************************************
 * Private Functions
 ************************************************************************/

/************************************************************************
 * Public Functions
 ************************************************************************/

/************************************************************************
 * Name: mq_recover
 *
 * Description:
 *   This function is called when a task is deleted via task_deleted or
 *   via pthread_cancel. I checks if the task was waiting for a message
 *   queue event and adjusts counts appropriately.
 *
 * Inputs:
 *   tcb - The TCB of the terminated task or thread
 *
 * Return Value:
 *   None.
 *
 * Assumptions:
 *   This function is called from task deletion logic in a safe context.
 *
 ************************************************************************/

void mq_recover(FAR struct tcb_s *tcb)
{
  /* If were were waiting for a timed message queue event, then the
   * timer was canceled and deleted in task_recover() before this
   * function was called.
   */

  /* Was the task waiting for a message queue to become non-empty? */

  if (tcb->task_state == TSTATE_WAIT_MQNOTEMPTY)
    {
      /* Decrement the count of waiters */

      DEBUGASSERT(tcb->msgwaitq && tcb->msgwaitq->nwaitnotempty > 0);
      tcb->msgwaitq->nwaitnotempty--;
    }

  /* Was the task waiting for a message queue to become non-full? */

  else if (tcb->task_state == TSTATE_WAIT_MQNOTFULL)
    {
      /* Decrement the count of waiters */

      DEBUGASSERT(tcb->msgwaitq && tcb->msgwaitq->nwaitnotfull > 0);
      tcb->msgwaitq->nwaitnotfull--;
    }
}


text:
#include <utility>
#include "frontends/lean/token_set.h"

namespace lean {
token_set add_command_token(token_set const & s, char const * token) {
    return insert(s, token, token_info(token));
}
token_set add_command_token(token_set const & s, char const * token, char const * val) {
    return insert(s, token, token_info(val));
}
token_set add_token(token_set const & s, char const * token, unsigned prec) {
    return insert(s, token, token_info(token, prec));
}
token_set add_token(token_set const & s, char const * token, char const * val, unsigned prec) {
    return insert(s, token, token_info(val, prec));
}
token_set merge(token_set const & s1, token_set const & s2) {
    return merge(s1, s2);
}
token_set const * find(token_set const & s, char c) {
    return s.find(c);
}
token_info const * value_of(token_set const & s) {
    return s.value();
}
static char const * g_lambda_unicode = "\u03BB";
static char const * g_pi_unicode     = "\u03A0";
static char const * g_forall_unicode = "\u2200";
static char const * g_arrow_unicode  = "\u2192";

// Auxiliary class for creating the initial token set
class init_token_set_fn {
public:
    token_set m_token_set;
    init_token_set_fn() {
            char const * builtin[] = {"fun", "Pi", "let", "in", "have", "show", "by", "from", "(", ")", "{", "}",
                                      ".{", "Type", "...", ",", ".", ":", "calc", ":=", "--", "(*", "(--", "->",
                                      "proof", "qed", "private", nullptr};

            char const * commands[] = {"theorem", "axiom", "variable", "definition", "evaluate", "check",
                                       "print", "variables", "end", "namespace", "section", "import",
                                       "abbreviation", "inductive", "record", "structure", "module", nullptr};

            std::pair<char const *, char const *> aliases[] =
                {{g_lambda_unicode, "fun"}, {"forall", "Pi"}, {g_forall_unicode, "Pi"}, {g_pi_unicode, "Pi"},
                 {g_arrow_unicode, "->"}, {nullptr, nullptr}};

            std::pair<char const *, char const *> cmd_aliases[] =
                {{"parameter", "variable"}, {"parameters", "variables"}, {"lemma", "theorem"},
                 {"hypothesis", "axiom"}, {"conjecture", "axiom"}, {"corollary", "theorem"},
                 {nullptr, nullptr}};

            auto it = builtin;
            while (*it) {
                m_token_set = add_token(m_token_set, *it);
                it++;
            }

            it = commands;
            while (*it) {
                m_token_set = add_command_token(m_token_set, *it);
                ++it;
            }

            auto it2 = aliases;
            while (it2->first) {
                m_token_set = add_token(m_token_set, it2->first, it2->second);
                it2++;
            }

            it2 = cmd_aliases;
            while (it2->first) {
                m_token_set = add_command_token(m_token_set, it2->first, it2->second);
                ++it2;
            }
    }
};
static init_token_set_fn g_init;
token_set mk_default_token_set() { return g_init.m_token_set; }
}


text:
swoole_buffer: default contruct buffer
--SKIPIF--
<?php require __DIR__ . "/../inc/skipif.inc"; ?>
--INI--
assert.active=1
assert.warning=1
assert.bail=0
assert.quiet_eval=0

--FILE--
<?php
$buffer = new swoole_buffer();

assert($buffer instanceof swoole_buffer);

echo "capacity:" . $buffer->capacity . "\n";
echo "length:" . $buffer->length . "\n";

$ret = $buffer->read(0, 10);
assert($ret == false);

 ?>

--EXPECT--
capacity:128
length:0


text:
<?php

namespace MegaCastingBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * TypeMedia
 *
 * @ORM\Table("TypeMedia")
 * @ORM\Entity(repositoryClass="MegaCastingBundle\Repository\TypeMediaRepository")
 */
class TypeMedia
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="libelle", type="string", length=255)
     */
    private $libelle;

    /**
     * @ORM\OneToMany(targetEntity="Multimedia", mappedBy="typeMedia", cascade={"persist"}, orphanRemoval=false)
     * @ORM\JoinColumn(nullable=true)
     */
    private $multimedias;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set libelle
     *
     * @param string $libelle
     * @return TypeMedia
     */
    public function setLibelle($libelle)
    {
        $this->libelle = $libelle;

        return $this;
    }

    /**
     * Get libelle
     *
     * @return string
     */
    public function getLibelle()
    {
        return $this->libelle;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->medias = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add multimedias
     *
     * @param \MegaCastingBundle\Entity\Multimedia $multimedias
     * @return TypeMedia
     */
    public function addMultimedia(\MegaCastingBundle\Entity\Multimedia $multimedias)
    {
        $this->multimedias[] = $multimedias;

        return $this;
    }

    /**
     * Remove medias
     *
     * @param \MegaCastingBundle\Entity\Multimedias $multimedias
     */
    public function removeMultimedia(\MegaCastingBundle\Entity\Media $multimedias)
    {
        $this->multimedias->removeElement($multimedias);
    }

    /**
     * Get $Multimedias
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMultimedias()
    {
        return $this->$multimedias;
    }

    /**
     * Get multimedia
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMultimedia()
    {
        return $this->multimedia;
    }
}