text:
<component name="ArtifactManager">
  <artifact type="jar" name="Sprocket:jar">
    <output-path>$PROJECT_DIR$/build/artifacts</output-path>
    <root id="archive" name="Sprocket.jar">
      <element id="directory" name="META-INF">
        <element id="file-copy" path="$PROJECT_DIR$/src/META-INF/MANIFEST.MF" />
      </element>
      <element id="module-output" name="Sprocket" />
      <element id="extracted-dir" path="$PROJECT_DIR$/lib/antlr-3.4.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$SCALA_HOME$/lib/scala-library.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$SCALA_HOME$/lib/scala-reflect.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$SCALA_HOME$/lib/scala-parser-combinators_2.11-1.0.1.jar" path-in-jar="/" />
      <element id="extracted-dir" path="$SCALA_HOME$/lib/scala-xml_2.11-1.0.1.jar" path-in-jar="/" />
      <element id="library" level="project" name="BouncyCastle" />
    </root>
  </artifact>
</component>


text:
package nate.util;

import java.util.Set;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

public class Graph {
  Graph() { }

  /**
   * @param matrix Adjacency matrix of the graph.
   * @return A set of indices to all vertices in the largest connected component.
   */
  public static Set<Integer> largestConnectedComponent(boolean[][] matrix) {
    int size = 1;
    boolean[] visited = new boolean[matrix.length];
    Set<Integer> largestComponent = null;

    for( int i = 0; i < visited.length; i++ ) {
      if( !visited[i] ) {
	Set<Integer> component = new HashSet();
	component.add(i);

	// Traverse neighbors of i.
	Queue<Integer> queue = new LinkedList();
	queue.add(i);

	while( !queue.isEmpty() ) {
	  Integer parent = queue.remove();
	  visited[parent] = true;
	  for( int j = 0; j < matrix.length; j++ ) {
	    if( matrix[parent][j] && !visited[j] ) {
	      queue.add(j);
	      component.add(j);
	    }
	  }
	}

	// See if it is a larger component.
	if( largestComponent == null || component.size() > largestComponent.size() )
	  largestComponent = component;
      }
    }

    return largestComponent;
  }

}

redpajama_set_name: RedPajamaGithub


text:
module Jisota
  class ParamParser
    attr_reader :params, :args

    def initialize(params, args)
      @params = params
      @args = args
    end

    def parse
      params_work_list = params.dup
      Hash.new.tap do |result|
        init_splat_params(result)
        add_unnamed_args(result, params_work_list)
        add_named_args(result)
        handle_remaining_params(result, params_work_list)
      end
    end

    private

    def init_splat_params(result)
      params.select(&:splat?).each do |param|
        result[param.name] = []
      end
    end

    def add_unnamed_args(result, params_work_list)
      param = nil
      unnamed_args.each do |arg|
        param = params_work_list.shift unless param && param.splat?
        raise ParameterError, "No parameter for unnamed argument #{arg}" unless param
        if param.splat?
          result[param.name] << arg
        else
          result[param.name] = arg
        end
      end
    end

    def add_named_args(result)
      named_args.each do |key, value|
        param = params.select { |p| p.name == key }.first
        raise ParameterError, "No parameter with name #{key.inspect}" unless param
        if result.has_key?(key)
          if param.splat?
            raise ParameterError, "Splat parameter #{key.inspect} only accepts unnamed arguments"
          else
            raise ParameterError, "Parameter #{key.inspect} already set with an unnamed argument"
          end
        end
        result[key] = value
      end
    end

    def unnamed_args
      args.dup.tap do |result|
        result.pop if named_args?
      end
    end

    def named_args
      named_args? ? args.last : {}
    end

    def named_args?
      args.last.is_a?(Hash)
    end

    def handle_remaining_params(result, params_work_list)
      params_work_list.each do |param|
        unless result.has_key?(param.name)
          if param.required? && !param.default?
            raise ParameterError, "Parameter #{param.name.inspect} is required"
          end
          result[param.name] = param.default? ? param.default : nil
        end
      end
    end
  end
end


text:
require 'spec_helper'

describe Github::GitData::Tags do

  it { described_class::VALID_TAG_PARAM_NAMES.should_not be_nil }

end # Github::GitData::Tags


text:
package ozone.securitysample.authentication.ldap;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import javax.naming.ldap.LdapName;

import org.hamcrest.core.IsInstanceOf;
import org.junit.Before;
import org.junit.Test;
import org.springframework.ldap.core.DirContextAdapter;

import ozone.securitysample.authentication.ldap.LdapAuthorityGroup;
import ozone.securitysample.authentication.ldap.LdapAuthorityGroupContextMapper;

public class LdapAuthorityGroupContextMapperTest {

	private LdapAuthorityGroupContextMapper ldapAuthorityGroupContextMapper;

	@Before
	public void setUp() throws Exception {
		ldapAuthorityGroupContextMapper = new LdapAuthorityGroupContextMapper();
	}

	/**
	 * Test mapping functionality, ensure the proper fields get mapped.
	 * @throws Exception
	 */
	@Test
	public void testContextMapper() throws Exception {

		DirContextAdapter contextAdapter = mock(DirContextAdapter.class);
		when(contextAdapter.getDn()).thenReturn(new LdapName("cn=user,ou=groups,o=OWF,st=Maryland,c=us"));
		when(contextAdapter.getStringAttribute("cn")).thenReturn("user");
		when(contextAdapter.getStringAttributes("member")).thenReturn(new String[]{ "cn=jsmith,ou=OWF,o=OWFDevelopment,l=Columbia,st=Maryland,c=US",
				                                                                    "cn=jdoe,ou=OWF,o=OWFDevelopment,l=Columbia,st=Maryland,c=US"
				                                                                  });

		Object oLdapAuthorityGroup = ldapAuthorityGroupContextMapper.mapFromContext(contextAdapter);

		assertTrue(new IsInstanceOf(LdapAuthorityGroup.class).matches(oLdapAuthorityGroup));
		LdapAuthorityGroup ldapAuthorityGroup = (LdapAuthorityGroup)oLdapAuthorityGroup;

		assertEquals("cn=user,ou=groups,o=OWF,st=Maryland,c=us",ldapAuthorityGroup.getDn());
		assertEquals("user",ldapAuthorityGroup.getCn());
		assertEquals(2,ldapAuthorityGroup.getMembers().length);
	}

	/**
	 * Test with null object.
	 * @throws Exception
	 */
	@Test
	public void testContextMapperWithNullObject() throws Exception {

		Object oLdapAuthorityGroup = ldapAuthorityGroupContextMapper.mapFromContext(null);
		assertNull(oLdapAuthorityGroup);
	}

	/**
	 * Test with non-DirContextAdaper object.
	 * @throws Exception
	 */
	@Test
	public void testContextMapperWithDifferentObject() throws Exception {

		Object oLdapAuthorityGroup = ldapAuthorityGroupContextMapper.mapFromContext(new Object());
		assertNull(oLdapAuthorityGroup);
	}
}


text:
class PartsController < ApplicationController
  PARENT_PLACEHOLDER = "Title of existing or new parent page"
  URL_PLACEHOLDER = "URL of part to add"

  def new
    @page = Page.new
    @title = "New parent page"
  end

  def edit
    @page = Page.find(params[:id])
    case params[:add]
    when "title"
      @title = "Edit title for #{@page.title}"
      render "title"
    when "part"
      @title = "Add part to #{@page.title}"
      @hint = URL_PLACEHOLDER
      render "part"
    when "parent"
      @title = "Add parent to #{@page.title}"
      @hint = PARENT_PLACEHOLDER
      render "parent"
    else
      raise "missing or bad params[:add] (#{params[:add]})"
    end
  end

  def create
    @page = Page.find(params[:page_id])
    @count = 0
    if params[:title]
      @page.update_attribute(:title, params[:title])
    elsif params[:add_url]
      url = params[:add_url] unless params[:add_url] == URL_PLACEHOLDER
      @page.add_part(url)
      flash[:notice] = "Part added"
      flash[:alert] = "Now Edit Raw HTML" if @page.first_part_ff?
      @count = @page.parts.size > Page::LIMIT ? @page.parts.size - Page::LIMIT : 0
    elsif params[:add_parent]
      @parent = @page.add_parent(params[:add_parent])
      #Rails.logger.debug "added #{@parent.inspect}"
      case @parent
      when Array
         flash[:alert] = "More than one page with that title"
         @possibles = @parent
         render 'choose' and return
      when "content"
         flash[:alert] = "Parent with that title has content"
      when Page
         flash[:notice] = "Page added to this parent"
         @count = @page.position > Page::LIMIT ? @page.position - Page::LIMIT : 0
         @page = @parent
      end
    elsif params[:parent_id]
      position = @page.add_parent_with_id(params[:parent_id])
      flash[:notice] = "Page added to this parent"
      @count = position > Page::LIMIT ? position - Page::LIMIT : 0
      @page = Page.find(params[:parent_id])
    else
      raise "missing or bad params (#{request.query_parameters})"
    end
    render 'pages/show' and return
  end
end


text:
namespace http = boost::network::http;

struct handler;
typedef http::server<handler> http_server;

struct handler {
    void operator() (http_server::request const &request,
                     http_server::response &response) {
        response = http_server::response::stock_reply(
            http_server::response::ok, "Hello, world!");
    }

    void log(http_server::string_type const &info) {
        std::cerr << "ERROR: " << info << '\n';
    }
};

int main(int arg, char * argv[]) {
    handler handler_;
    http_server::options options(handler_);
    http_server server_(
        options.address("0.0.0.0")
               .port("8000"));
    server_.run();
}


text:
<?php

class ShippingRateModel extends AppModel {
    public $name = 'ShippingRate';

    public $hasMany = array(
        'PostalCodeShippingRate'
    );

}


text:
/* md4.c */
extern void mdfour(unsigned char *out, unsigned char *in, int n);
/* smbdes.c */
extern void E_P16(unsigned char *p14, unsigned char *p16);
extern void E_P24(unsigned char *p21, const unsigned char *c8,
		  unsigned char *p24);


text:
package org.pantsbuild.zinc.bootstrapper

import org.pantsbuild.buck.util.zip.ZipScrubber
import java.io.File
import xsbti.compile.{
  ClasspathOptionsUtil,
  ScalaInstance => XScalaInstance
}
import sbt.internal.inc.{AnalyzingCompiler, RawCompiler}
import sbt.util.Logger

object BootstrapperUtils {
  val CompilerInterfaceId = "compiler-interface"
  val JavaClassVersion = System.getProperty("java.class.version")

  def compilerInterface(output: File, compilerBridgeSrc: File, compilerInterface: File, scalaInstance: XScalaInstance, log: Logger): Unit = {
    def compile(targetJar: File): Unit =
      AnalyzingCompiler.compileSources(
        Seq(compilerBridgeSrc),
        targetJar,
        Seq(compilerInterface),
        CompilerInterfaceId,
        new RawCompiler(scalaInstance, ClasspathOptionsUtil.auto, log),
        log
      )

    val dir = output.getParentFile
    dir.mkdirs()
    val tempJar = File.createTempFile("interface-", ".jar.tmp", dir)
    try {
      compile(tempJar)
      ZipScrubber.scrubZip(tempJar.toPath)
      tempJar.renameTo(output)
    } finally {
      tempJar.delete()
    }
  }
}


text:
var observable = require('data/observable');
var ObservableArray = require('data/observable-array').ObservableArray;
var fetchModule = require('fetch');
var config = require('../config');

function handleErrors(response) {
  if (!response.ok) {
    console.log(JSON.stringify(response));
    throw Error(response.statusText);
  }
  return response;
}

exports.empty = function () {
  while (feedItems.length) {
    feedItems.pop();
  }
};

exports.load = function name(params) {
  console.log('CALLING LOAD');
  if (feedItems.length > 0) {
    return;
  }
  console.log('https://query.yahooapis.com/v1/public/yql?q=select%20title%2Clink%2Cdescription%20from%20rss%20where%20url%3D%22' + encodeURIComponent(config.rssURL) + '%22&format=json&diagnostics=true');

  return fetch('https://query.yahooapis.com/v1/public/yql?q=select%20title%2Clink%2Cdescription%20from%20rss%20where%20url%3D%22' + encodeURIComponent(config.rssURL) + '%22&format=json&diagnostics=true', {})
    .then(handleErrors)
    .then(function (response) {
      return response.json();
    }).then(function (data) {
      data.query.results.item.forEach(function (feedItem) {
        feedItems.push({
            title: feedItem.title,
            link: feedItem.link,
            description: feedItem.description
          }
        );

      });
    });

}

var feedItems = new ObservableArray();
exports.feedItems = feedItems;
var viewModel = new observable.Observable();
exports.viewModel = viewModel;


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

<TITLE>
IvyAuthenticator
</TITLE>

<META NAME="date" CONTENT="2013-01-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.ivy.util.url

Class IvyAuthenticator

java.lang.Object
  java.net.Authenticator
      org.apache.ivy.util.url.IvyAuthenticator

public final class IvyAuthenticator
extends java.net.Authenticator

Nested Class Summary

Nested classes/interfaces inherited from class java.net.Authenticator

java.net.Authenticator.RequestorType

Method Summary

protected  java.net.PasswordAuthentication
getPasswordAuthentication()

static void
install()

          Installs an <tt>IvyAuthenticator</tt> as default <tt>Authenticator</tt>.

Methods inherited from class java.net.Authenticator

getRequestingHost, getRequestingPort, getRequestingPrompt, getRequestingProtocol, getRequestingScheme, getRequestingSite, getRequestingURL, getRequestorType, requestPasswordAuthentication, requestPasswordAuthentication, requestPasswordAuthentication, setDefault

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

install

public static void install()

Installs an <tt>IvyAuthenticator</tt> as default <tt>Authenticator</tt>.
 Call this method before opening HTTP(S) connections to enable Ivy
 authentication.

getPasswordAuthentication

protected java.net.PasswordAuthentication getPasswordAuthentication()

Overrides:
getPasswordAuthentication in class java.net.Authenticator

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
from setuptools import setup
from codecs import open
import yakstack

with open('README.rst', encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='yakstack',
    version=yakstack.VERSION,

    description='A command-line utility to help you stack your yaks.',
    long_description=long_description,
    keywords=['yak stack', 'yak frame', 'cli', 'tasks'],

    url='https://github.com/gilmoreorless/yakstack',

    author='Gilmore Davidson',
    author_email='gilmoreorless@gmail.com',

    license='MIT',

    classifiers=[
        'Development Status :: 5 - Production/Stable',

        'Environment :: Console',
        'Intended Audience :: Developers',
        'Topic :: Utilities',

        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
    ],

    py_modules=['yakstack'],
    entry_points={
        'console_scripts': [
            'yakstack=yakstack:main'
        ]
    }

)


text:
MockMediaRouterActionController::MockMediaRouterActionController(
    Profile* profile)
    : MediaRouterActionController(
          profile,
          media_router::MediaRouterFactory::GetApiForBrowserContext(profile)) {}

MockMediaRouterActionController::~MockMediaRouterActionController() = default;


text:
man: git-ls-files
update: 2022-01-05
---

# Usage

Show information about files in the index and the working tree.

```shell
git ls-files OPTIONS FILE
```

| Option | Description |
| --- | --- |
| `--error-unmatch` | If any FILE does not appear in the index, treat this as an error (return 1). |

# Example

Check if a file is being tracked by git.

```shell
git ls-files --error-unmatch src/file.txt
```


text:
package org.usfirst.frc2811.RecycleRush.commands;

import edu.wpi.first.wpilibj.command.Command;

import org.usfirst.frc2811.RecycleRush.Robot;

/**
 * Moves the Bident a specific velocity.
 * NOTE: Only for use in testing. If the robot is homed, bidentMonitor will override this.
Use Up/DownManual instead.
 */
public class BidentSetVelocity extends Command {
	private double tickVelocity;
    public BidentSetVelocity(double velocityInTicks) {
        // Use requires() here to declare subsystem dependencies
        //Do nothing, just update
    	tickVelocity=velocityInTicks;
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	System.out.println("Bident::SetVelocity:: Set to " + tickVelocity);

    	Robot.bident.setTickVelocity(tickVelocity);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return true;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
package org.littleshoot.proxy;

import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.server.Server;
import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;

@SuppressWarnings({"resource", "unused"})
@FixMethodOrder(MethodSorters.JVM)
@Slf4j
public class ThrottlingTest {

  private static final long THROTTLED_READ_BYTES_PER_SECOND = 25000L;
  private static final long THROTTLED_WRITE_BYTES_PER_SECOND = 25000L;

  // throttling is not guaranteed to be exact, so allow some variation in the amount of time the call takes. since we want
  // these tests to take just a few seconds, allow significant variation. even with this large variation, if throttling
  // is broken it should take much less time than expected.
  private static final double ALLOWABLE_VARIATION = 0.40;

  private Server writeWebServer;
  private Server readWebServer;

  private byte[] largeData;

  private int msToWriteThrottled;
  private int msToReadThrottled;

  // time to allow for an unthrottled local request
  private static final int UNTRHOTTLED_REQUEST_TIME_MS = 1000;

  private int writeWebServerPort;
  private int readWebServerPort;

  @Before
  public void setUp() throws Exception {

    // Set up some large data
    largeData = new byte[100000];
    for (int i = 0; i < largeData.length; i++) {
      largeData[i] = 1 % 256;
    }

    msToWriteThrottled = largeData.length * 1000 / (int) THROTTLED_WRITE_BYTES_PER_SECOND;
    msToReadThrottled = largeData.length * 1000 / (int) THROTTLED_READ_BYTES_PER_SECOND;

    writeWebServer = TestUtils.startWebServer(false);
    writeWebServerPort = TestUtils.findLocalHttpPort(writeWebServer);

    readWebServer = TestUtils.startWebServerWithResponse(false, largeData);
    readWebServerPort = TestUtils.findLocalHttpPort(readWebServer);
  }

  @After
  public void tearDown() throws Exception {
    try {
      if (writeWebServer != null) {
        writeWebServer.stop();
      }
    } finally {
      if (readWebServer != null) {
        readWebServer.stop();
      }
    }
  }

  @Test
  public void aWarmUpTest() throws IOException {
    // a "warm-up" test so the first test's results are not skewed due to classloading, etc. guaranteed to run
    // first with the @FixMethodOrder(MethodSorters.NAME_ASCENDING) annotation on the class.

    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
        .withPort(0)
        .withThrottling(0, THROTTLED_WRITE_BYTES_PER_SECOND)
        .start();

    int proxyPort = proxyServer.getListenAddress().getPort();

    HttpGet request = createHttpGet();
    DefaultHttpClient httpClient = createHttpClient(proxyPort);

    EntityUtils.consumeQuietly(httpClient.execute(new HttpHost("127.0.0.1", writeWebServerPort), request).getEntity());

    EntityUtils.consumeQuietly(httpClient.execute(new HttpHost("127.0.0.1", readWebServerPort), request).getEntity());
  }

  @Test
  public void testThrottledWrite() throws Exception {
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
        .withPort(0)
        .withThrottling(0, THROTTLED_WRITE_BYTES_PER_SECOND)
        .start();

    int proxyPort = proxyServer.getListenAddress().getPort();

    final HttpPost request = createHttpPost();

    DefaultHttpClient httpClient = createHttpClient(proxyPort);

    long start = System.currentTimeMillis();
    final org.apache.http.HttpResponse response = httpClient.execute(
        new HttpHost("127.0.0.1",
            writeWebServerPort), request);
    long finish = System.currentTimeMillis();

    assertEquals("Received " + largeData.length + " bytes\n",
        EntityUtils.toString(response.getEntity()));

    assertThat(
        "Expected throttled write to complete in approximately " + msToWriteThrottled + "ms" + " but took " + (finish
                                                                                - start)
        + "ms",
        (double) (finish - start), both(greaterThan(msToWriteThrottled * (1 - ALLOWABLE_VARIATION))).and(
            lessThan(msToWriteThrottled * (1 + ALLOWABLE_VARIATION))));

    proxyServer.abort();
  }

  @Test
  public void testUnthrottledWrite() throws Exception {
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
        .withPort(0)
        .start();

    int proxyPort = proxyServer.getListenAddress().getPort();

    final HttpPost request = createHttpPost();

    DefaultHttpClient httpClient = createHttpClient(proxyPort);

    long start = System.currentTimeMillis();
    final org.apache.http.HttpResponse response = httpClient.execute(
        new HttpHost("127.0.0.1",
            writeWebServerPort), request);
    long finish = System.currentTimeMillis();

    assertEquals("Received " + largeData.length + " bytes\n",
        EntityUtils.toString(response.getEntity()));

    assertThat(
        "Unthrottled write took " + (finish - start) + "ms, but expected to complete in " + UNTRHOTTLED_REQUEST_TIME_MS
        + "ms",
        finish - start, lessThan((long) UNTRHOTTLED_REQUEST_TIME_MS));

    proxyServer.abort();
  }

  @Ignore("This starts failing with netty 4.1.53")
  public void testThrottledRead() throws Exception {
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
        .withPort(0)
        .withThrottling(THROTTLED_READ_BYTES_PER_SECOND, 0)
        .start();

    int proxyPort = proxyServer.getListenAddress().getPort();

    final HttpGet request = createHttpGet();

    DefaultHttpClient httpClient = createHttpClient(proxyPort);

    long start = System.currentTimeMillis();
    log.info("httpClient.execute");
    final org.apache.http.HttpResponse response = httpClient.execute(
        new HttpHost("127.0.0.1",
            readWebServerPort), request);
    byte[] readContent = new byte[100000];

    log.info("To read: " + readContent.length);
    int bytesRead = 0;
    while (bytesRead < largeData.length) {
      int read = response.getEntity().getContent()
          .read(readContent, bytesRead, largeData.length - bytesRead);
      log.info("Read " + read + " bytes");
      bytesRead += read;
    }

    long finish = System.currentTimeMillis();

    final double elapsed = finish - start;
    assertThat(
        "Expected throttled read to complete in approximately " + msToReadThrottled + "ms" + " but took " + elapsed
        + "ms",
        elapsed, both(greaterThan(msToReadThrottled * (1 - ALLOWABLE_VARIATION)))
            .and(lessThan(msToReadThrottled * (1 + ALLOWABLE_VARIATION))));

    proxyServer.abort();
  }

  @Test
  public void testUnthrottledRead() throws Exception {
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
        .withPort(0)
        .start();

    int proxyPort = proxyServer.getListenAddress().getPort();

    final HttpGet request = createHttpGet();

    DefaultHttpClient httpClient = createHttpClient(proxyPort);

    long start = System.currentTimeMillis();
    final org.apache.http.HttpResponse response = httpClient.execute(
        new HttpHost("127.0.0.1",
            readWebServerPort), request);

    byte[] readContent = new byte[100000];
    int bytesRead = 0;
    while (bytesRead < largeData.length) {
      int read = response.getEntity().getContent().read(readContent, bytesRead, largeData.length - bytesRead);
      bytesRead += read;
    }

    long finish = System.currentTimeMillis();

    assertThat(
        "Unthrottled read took " + (finish - start) + "ms, but expected to complete in " + UNTRHOTTLED_REQUEST_TIME_MS
        + "ms",
        finish - start, lessThan((long) UNTRHOTTLED_REQUEST_TIME_MS));

    proxyServer.abort();
  }

  @Ignore("This starts failing with netty 4.1.53")
  public void testChangeThrottling() throws IOException {
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
        .withPort(0)
        .withThrottling(THROTTLED_READ_BYTES_PER_SECOND, 0)
        .start();

    int proxyPort = proxyServer.getListenAddress().getPort();

    final HttpGet request = createHttpGet();

    DefaultHttpClient httpClient = createHttpClient(proxyPort);

    long firstStart = System.currentTimeMillis();
    org.apache.http.HttpResponse response = httpClient.execute(
        new HttpHost("127.0.0.1",
            readWebServerPort), request);
    byte[] readContent = new byte[100000];

    int bytesRead = 0;
    while (bytesRead < largeData.length) {
      int read = response.getEntity().getContent().read(readContent, bytesRead, largeData.length - bytesRead);
      bytesRead += read;
    }

    long firstFinish = System.currentTimeMillis();

    HttpClientUtils.closeQuietly(response);

    proxyServer.setThrottle(THROTTLED_READ_BYTES_PER_SECOND * 2, 0);

    long secondStart = System.currentTimeMillis();
    response = httpClient.execute(
        new HttpHost("127.0.0.1",
            readWebServerPort), request);
    readContent = new byte[100000];

    bytesRead = 0;
    while (bytesRead < largeData.length) {
      int read = response.getEntity().getContent().read(readContent, bytesRead, largeData.length - bytesRead);
      bytesRead += read;
    }

    long secondFinish = System.currentTimeMillis();

    HttpClientUtils.closeQuietly(response);

    assertThat("Expected second read to take approximately half as long as first throttled read. First read took " + (
            firstFinish - firstStart) + "ms" + " but second read took " + (secondFinish - secondStart) + "ms",
        (double) (firstFinish - firstStart) / 2,
        both(greaterThan((secondFinish - secondStart) * (1 - ALLOWABLE_VARIATION)))
            .and(lessThan((secondFinish - secondStart) * (1 + ALLOWABLE_VARIATION))));

    proxyServer.abort();
  }

  @Ignore("This starts failing with netty 4.1.53")
  public void testDisableThrottling() throws IOException {
    HttpProxyServer proxyServer = DefaultHttpProxyServer.bootstrap()
        .withPort(0)
        .withThrottling(THROTTLED_READ_BYTES_PER_SECOND, 0)
        .start();

    int proxyPort = proxyServer.getListenAddress().getPort();

    final HttpGet request = createHttpGet();

    DefaultHttpClient httpClient = createHttpClient(proxyPort);

    long firstStart = System.currentTimeMillis();
    org.apache.http.HttpResponse response = httpClient.execute(
        new HttpHost("127.0.0.1",
            readWebServerPort), request);
    byte[] readContent = new byte[100000];

    int bytesRead = 0;
    while (bytesRead < largeData.length) {
      int read = response.getEntity().getContent().read(readContent, bytesRead, largeData.length - bytesRead);
      bytesRead += read;
    }

    long firstFinish = System.currentTimeMillis();

    HttpClientUtils.closeQuietly(response);

    proxyServer.setThrottle(0, 0);

    long secondStart = System.currentTimeMillis();
    response = httpClient.execute(
        new HttpHost("127.0.0.1",
            readWebServerPort), request);
    readContent = new byte[100000];

    bytesRead = 0;
    while (bytesRead < largeData.length) {
      int read = response.getEntity().getContent().read(readContent, bytesRead, largeData.length - bytesRead);
      bytesRead += read;
    }

    long secondFinish = System.currentTimeMillis();

    HttpClientUtils.closeQuietly(response);

    assertThat("Expected second read to complete within " + UNTRHOTTLED_REQUEST_TIME_MS
               + "ms, without throttling. First read took "
               + (firstFinish - firstStart) + "ms" + ". Second read took " + (secondFinish - secondStart) + "ms",
        secondFinish - secondStart, lessThan((long) UNTRHOTTLED_REQUEST_TIME_MS));

    proxyServer.abort();

  }

  private HttpGet createHttpGet() {
    final HttpGet request = new HttpGet("/");
    request.getParams().setParameter(
        CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    return request;
  }

  private HttpPost createHttpPost() {
    final HttpPost request = new HttpPost("/");
    request.getParams().setParameter(
        CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    final ByteArrayEntity entity = new ByteArrayEntity(largeData);
    entity.setChunked(true);
    request.setEntity(entity);
    return request;
  }

  private DefaultHttpClient createHttpClient(int proxyPort) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    final HttpHost proxy = new HttpHost("127.0.0.1", proxyPort, "http");
    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
        proxy);
    return httpClient;
  }
}


text:
/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('emotions');

// Plucin static class
var TinyMCE_EmotionsPlugin = {
	getInfo : function() {
		return {
			longname : 'Emotions',
			author : 'Moxiecode Systems AB',
			authorurl : 'http://tinymce.moxiecode.com',
			infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_emotions.html',
			version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
		};
	},

	/**
	 * Returns the HTML contents of the emotions control.
	 */
	getControlHTML : function(cn) {
		switch (cn) {
			case "emotions":
				return tinyMCE.getButtonHTML(cn, 'lang_emotions_desc', '{$pluginurl}/images/emotions.gif', 'mceEmotion');
		}

		return "";
	},

	/**
	 * Executes the mceEmotion command.
	 */
	execCommand : function(editor_id, element, command, user_interface, value) {
		// Handle commands
		switch (command) {
			case "mceEmotion":
				var template = new Array();

				template['file'] = '../../plugins/emotions/emotions.htm'; // Relative to theme
				template['width'] = 160;
				template['height'] = 160;

				// Language specific width and height addons
				template['width'] += tinyMCE.getLang('lang_emotions_delta_width', 0);
				template['height'] += tinyMCE.getLang('lang_emotions_delta_height', 0);

				tinyMCE.openWindow(template, {editor_id : editor_id, inline : "yes"});

				return true;
		}

		// Pass to next handler in chain
		return false;
	}
};

// Register plugin
tinyMCE.addPlugin('emotions', TinyMCE_EmotionsPlugin);


text:
"use strict";

exports.__esModule = true;
exports.default = _default;

var _loose = _interopRequireDefault(require("./loose"));

var _vanilla = _interopRequireDefault(require("./vanilla"));

var _helperAnnotateAsPure = _interopRequireDefault(require("@babel/helper-annotate-as-pure"));

var _helperFunctionName = _interopRequireDefault(require("@babel/helper-function-name"));

var _core = require("@babel/core");

var _globals = _interopRequireDefault(require("globals"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var getBuiltinClasses = function getBuiltinClasses(category) {
  return Object.keys(_globals.default[category]).filter(function (name) {
    return /^[A-Z]/.test(name);
  });
};

var builtinClasses = new Set(getBuiltinClasses("builtin").concat(getBuiltinClasses("browser")));

function _default(api, options) {
  var loose = options.loose;
  var Constructor = loose ? _loose.default : _vanilla.default;
  var VISITED = Symbol();
  return {
    visitor: {
      ExportDefaultDeclaration: function ExportDefaultDeclaration(path) {
        if (!path.get("declaration").isClassDeclaration()) return;
        var node = path.node;
        var ref = node.declaration.id || path.scope.generateUidIdentifier("class");
        node.declaration.id = ref;
        path.replaceWith(node.declaration);
        path.insertAfter(_core.types.exportNamedDeclaration(null, [_core.types.exportSpecifier(_core.types.cloneNode(ref), _core.types.identifier("default"))]));
      },
      ClassDeclaration: function ClassDeclaration(path) {
        var node = path.node;
        var ref = node.id || path.scope.generateUidIdentifier("class");
        path.replaceWith(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(ref, _core.types.toExpression(node))]));
      },
      ClassExpression: function ClassExpression(path, state) {
        var node = path.node;
        if (node[VISITED]) return;
        var inferred = (0, _helperFunctionName.default)(path);

        if (inferred && inferred !== node) {
          path.replaceWith(inferred);
          return;
        }

        node[VISITED] = true;
        path.replaceWith(new Constructor(path, state.file, builtinClasses).run());

        if (path.isCallExpression()) {
          (0, _helperAnnotateAsPure.default)(path);

          if (path.get("callee").isArrowFunctionExpression()) {
            path.get("callee").arrowFunctionToExpression();
          }
        }
      }
    }
  };
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit1df3992ac0427d9008a0056fdbd40d64::getLoader();


text:
package rapcap.hadoop.mr1.lzo;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.util.LineReader;

import com.hadoop.compression.lzo.LzoCodec;

public class LzoLineRecordReader implements RecordReader<LongWritable, Text> {
  private CompressionCodecFactory codecFactory = null;
  private long start;
  private long pos;
  private final long end;
  private final LineReader in;
  private final FSDataInputStream fileIn;

  LzoLineRecordReader(Configuration conf, FileSplit split) throws IOException {
    start = split.getStart();
    end = start + split.getLength();
    final Path file = split.getPath();

    FileSystem fs = file.getFileSystem(conf);
    codecFactory = new CompressionCodecFactory(conf);
//    final CompressionCodec codec = codecFactory.getCodec(file);
    CompressionCodec codec = new LzoCodec();
    if (codec == null) {
      throw new IOException("No LZO codec found, cannot run.");
    }

    // Open the file and seek to the next split.
    fileIn = fs.open(file);
    // Create input stream and read the file header.
    in = new LineReader(codec.createInputStream(fileIn), conf);
    if (start != 0) {
      fileIn.seek(start);

      // Read and ignore the first line.
      in.readLine(new Text());
      start = fileIn.getPos();
    }

    pos = start;
  }

  public LongWritable createKey() {
    return new LongWritable();
  }

  public Text createValue() {
    return new Text();
  }

  public boolean next(LongWritable key, Text value) throws IOException {
    // Since the LZOP codec reads everything in LZO blocks, we can't stop if pos == end.
    // Instead, wait for the next block to be read in when pos will be > end.
    while (pos <= end) {
      key.set(pos);

      int newSize = in.readLine(value);
      if (newSize == 0) {
        return false;
      }
      pos = fileIn.getPos();
      return true;
    }
    return false;
  }

  public float getProgress() throws IOException {
    if (start == end) {
      return 0.0f;
    } else {
      return Math.min(1.0f, (pos - start)/ (float)(end - start));
    }
  }

  public synchronized long getPos() throws IOException {
    return pos;
  }

  public synchronized void close() throws IOException {
    if (in != null) {
      in.close();
    }
  }
}


text:
using System.IO;
using System.Windows.Forms;
using UnitTests.Fixtures;
using Utilities.Media;
using Xunit;

namespace UnitTests.Media.Image.ExtensionMethods
{
    public class ScreenshotExtensions :TestingDirectoryFixture
    {
        public void SetFixture(TestingDirectoryFixture data)
        {
        }

        [Fact]
        public void TakeScreenShot()
        {
            Assert.NotNull(Screen.AllScreens.TakeScreenShot(@".\Testing\1.bmp"));
            Assert.True(new FileInfo(@".\Testing\1.bmp").Exists);
            Assert.NotNull(Screen.PrimaryScreen.TakeScreenShot(@".\Testing\2.bmp"));
            Assert.True(new FileInfo(@".\Testing\2.bmp").Exists);
        }
    }
}


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

<TITLE>
Uses of Class org.apache.fop.area.Page (Apache FOP 1.0 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 1.0

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.fop.area.Page

Packages that use Page

org.apache.fop.area
FOP's area tree.

org.apache.fop.render
Generic renderer interface.

Uses of Page in org.apache.fop.area

Methods in org.apache.fop.area that return Page

 Page
PageViewport.getPage()

          Get the page reference area with the contents.

Methods in org.apache.fop.area with parameters of type Page

 void
PageViewport.setPage(Page page)

          Sets the page object for this PageViewport.

Uses of Page in org.apache.fop.render

Methods in org.apache.fop.render with parameters of type Page

protected  void
AbstractRenderer.renderPageAreas(Page page)

          Renders page areas.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 1.0

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
'use strict';

import angular from 'angular';
import 'firebase';
import 'angularfire';
import 'angular-material';
import 'angular-loading-bar';
import 'angular-animate';
import 'angular-messages';
import 'angular-route';
import {spfShared} from 'singpath-core';

export const singpath = angular.module('spf', [
  'angular-loading-bar',
  'firebase',
  'ngAnimate',
  'ngMessages',
  'ngRoute',
  'ngMaterial',
  spfShared.name
]);


text:
package org.diirt.datasource.expression;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.diirt.datasource.PVDirector;
import org.diirt.datasource.QueueCollector;
import org.diirt.datasource.ReadRecipeBuilder;

/**
 * A read expression for a key/value map.
 *

 * This expression returns a map where the key is the name of the child
 * expression and the value is the value returned by the child expression.
 * The map is dynamic: the child expressions can be added and removed
 * while the reader is active.
 *

 * There is currently no way to retrieve the individual errors for each
 * element of the map. If the value is a VType, the connection can be
 * retrieved by looking at the alarm.
 *
 * @param <T> the type for the values in the map
 * @author carcassi
 */
public class ReadMap<T> extends DesiredRateExpressionImpl<Map<String, T>> {

    private final Object lock = new Object();
    private final Map<String, DesiredRateExpression<T>> expressions = new HashMap<>();
    private PVDirector<?> director;

    /**
     * Creates a new group.
     */
    public ReadMap() {
        super(new DesiredRateExpressionListImpl<Object>(), new MapOfReadFunction<T>(new QueueCollector<MapUpdate<T>>(1000)), "map");
    }

    MapOfReadFunction<T> getMapOfFunction() {
        return (MapOfReadFunction<T>) getFunction();
    }

    /**
     * Removes all the expressions currently in the map.
     *
     * @return this expression
     */
    public ReadMap<T> clear() {
        synchronized(lock) {
            getMapOfFunction().getMapUpdateCollector().writeValue(MapUpdate.<T>clear());
            if (director != null) {
                for (DesiredRateExpression<T> desiredRateExpression : expressions.values()) {
                    director.disconnectReadExpression(desiredRateExpression);
                }
            }
            expressions.clear();
            return this;
        }
    }

    /**
     * Returns the number of expressions in the group.
     *
     * @return number of expressions in the group
     */
    public int size() {
        synchronized(lock) {
            return expressions.size();
        }
    }

    /**
     * Adds the expression to the map.
     *
     * @param expression the expression to be added
     * @return this expression
     */
    public ReadMap<T> add(DesiredRateExpression<T> expression) {
        synchronized(lock) {
            if (expression.getName() == null) {
                throw new NullPointerException("Expression has a null name");
            }
            if (expressions.containsKey(expression.getName())) {
                throw new IllegalArgumentException("MapExpression already contain an expression named '" + expression.getName() + "'");
            }

            getMapOfFunction().getMapUpdateCollector().writeValue(MapUpdate.addReadFunction(expression.getName(), expression.getFunction()));
            expressions.put(expression.getName(), expression);
            if (director != null) {
                director.connectReadExpression(expression);
            }
            return this;
        }
    }

    /**
     * Adds the expressions to the map.
     *
     * @param expressions the new list of expressions
     * @return this expression
     */
    public ReadMap<T> add(DesiredRateExpressionList<T> expressions) {
        synchronized(lock) {
            for (DesiredRateExpression<T> desiredRateExpression : expressions.getDesiredRateExpressions()) {
                add(desiredRateExpression);
            }
            return this;
        }
    }

    /**
     * Removes the expression with the given name.
     *
     * @param name the name of the expression to remove
     * @return this expression
     */
    public ReadMap<T> remove(String name) {
        synchronized(lock) {
            if (!expressions.containsKey(name)) {
                throw new IllegalArgumentException("MapExpression does not contain an expression named '" + name + "'");
            }

            getMapOfFunction().getMapUpdateCollector().writeValue(MapUpdate.<T>removeFunction(name));
            DesiredRateExpression<T> expression = expressions.remove(name);
            if (director != null) {
                director.disconnectReadExpression(expression);
            }
            return this;
        }
    }

    /**
     * Removes the expressions from the map.
     *
     * @param names the names of the expressions to remove
     * @return this expression
     */
    public ReadMap<T> remove(Collection<String> names) {
        synchronized(lock) {
            for (String name : names) {
                remove(name);
            }
            return this;
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void fillReadRecipe(PVDirector director, ReadRecipeBuilder builder) {
        synchronized(lock) {
            this.director = director;
            for (Map.Entry<String, DesiredRateExpression<T>> entry : expressions.entrySet()) {
                DesiredRateExpression<T> readExpression = entry.getValue();
                director.connectReadExpression(readExpression);
            }
        }
    }

}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>last_insert_id (::PostgreSQL)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/jdbc_adapter/jdbc_postgre.rb, line 326
    def last_insert_id(table, sequence_name)
      Integer(select_value("SELECT currval('#{sequence_name}')"))
    end


text:
from collections import namedtuple
from functools import update_wrapper
from threading import Lock

_CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])

def lru_cache(maxsize=100, typed=False):
    """Least-recently-used cache decorator.

    If *maxsize* is set to None, the LRU features are disabled and the cache
    can grow without bound.

    If *typed* is True, arguments of different types will be cached separately.
    For example, f(3.0) and f(3) will be treated as distinct calls with
    distinct results.

    Arguments to the cached function must be hashable.

    View the cache statistics named tuple (hits, misses, maxsize, currsize) with
    f.cache_info().  Clear the cache and statistics with f.cache_clear().
    Access the underlying function with f.__wrapped__.

    See:  http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used

    """

    # Users should only access the lru_cache through its public API:
    #       cache_info, cache_clear, and f.__wrapped__
    # The internals of the lru_cache are encapsulated for thread safety and
    # to allow the implementation to change (including a possible C version).

    def decorating_function(user_function):

        cache = dict()
        stats = [0, 0]                  # make statistics updateable non-locally
        HITS, MISSES = 0, 1             # names for the stats fields
        kwd_mark = (object(),)          # separate positional and keyword args
        cache_get = cache.get           # bound method to lookup key or return None
        _len = len                      # localize the global len() function
        lock = Lock()                   # because linkedlist updates aren't threadsafe
        root = []                       # root of the circular doubly linked list
        nonlocal_root = [root]                  # make updateable non-locally
        root[:] = [root, root, None, None]      # initialize by pointing to self
        PREV, NEXT, KEY, RESULT = 0, 1, 2, 3    # names for the link fields

        def make_key(args, kwds, typed, tuple=tuple, sorted=sorted, type=type):
            # helper function to build a cache key from positional and keyword args
            key = args
            if kwds:
                sorted_items = tuple(sorted(kwds.items()))
                key += kwd_mark + sorted_items
            if typed:
                key += tuple(type(v) for v in args)
                if kwds:
                    key += tuple(type(v) for k, v in sorted_items)
            return key

        if maxsize == 0:

            def wrapper(*args, **kwds):
                # no caching, just do a statistics update after a successful call
                result = user_function(*args, **kwds)
                stats[MISSES] += 1
                return result

        elif maxsize is None:

            def wrapper(*args, **kwds):
                # simple caching without ordering or size limit
                key = make_key(args, kwds, typed) if kwds or typed else args
                result = cache_get(key, root)   # root used here as a unique not-found sentinel
                if result is not root:
                    stats[HITS] += 1
                    return result
                result = user_function(*args, **kwds)
                cache[key] = result
                stats[MISSES] += 1
                return result

        else:

            def wrapper(*args, **kwds):
                # size limited caching that tracks accesses by recency
                key = make_key(args, kwds, typed) if kwds or typed else args
                with lock:
                    link = cache_get(key)
                    if link is not None:
                        # record recent use of the key by moving it to the front of the list
                        root, = nonlocal_root
                        link_prev, link_next, key, result = link
                        link_prev[NEXT] = link_next
                        link_next[PREV] = link_prev
                        last = root[PREV]
                        last[NEXT] = root[PREV] = link
                        link[PREV] = last
                        link[NEXT] = root
                        stats[HITS] += 1
                        return result
                result = user_function(*args, **kwds)
                with lock:
                    root = nonlocal_root[0]
                    if _len(cache) < maxsize:
                        # put result in a new link at the front of the list
                        last = root[PREV]
                        link = [last, root, key, result]
                        cache[key] = last[NEXT] = root[PREV] = link
                    else:
                        # use root to store the new key and result
                        root[KEY] = key
                        root[RESULT] = result
                        cache[key] = root
                        # empty the oldest link and make it the new root
                        root = nonlocal_root[0] = root[NEXT]
                        del cache[root[KEY]]
                        root[KEY] = None
                        root[RESULT] = None
                    stats[MISSES] += 1
                return result

        def cache_info():
            """Report cache statistics"""
            with lock:
                return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache))

        def cache_clear():
            """Clear the cache and cache statistics"""
            with lock:
                cache.clear()
                root = nonlocal_root[0]
                root[:] = [root, root, None, None]
                stats[:] = [0, 0]

        wrapper.__wrapped__ = user_function
        wrapper.cache_info = cache_info
        wrapper.cache_clear = cache_clear
        return update_wrapper(wrapper, user_function)

    return decorating_function


text:
<?php

namespace App\Statistic;

use Doctrine\ORM\Query;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Person;
use App\Statistic\PersonStatistics;

/**
 * App\Statistic\StatisticService
 *
 * @author naitsirch
 */
class StatisticService
{
    private $doctrine;
    private $statistics;

    public function __construct(ManagerRegistry $doctrine)
    {
        $this->doctrine = $doctrine;
    }

    /**
     * Returns the statistics about our members.
     * @return PersonStatistics
     */
    public function getPersonStatistics()
    {
        if (!$this->statistics) {
            $repo = $this->doctrine->getRepository(Person::class);
            $qb = $repo->createQueryBuilder('person'); /* @var $qb \Doctrine\ORM\QueryBuilder */
            $qb->select('person');

            $now = new \DateTime();
            $ageSum = 0;
            $total = 0;
            $femaleTotal = 0;
            $atLeast65YearsOld = 0;
            $atMost25YearsOld = 0;
            $numberPerYearOfBirth = [];
            $numberPerAge = [];

            foreach ($qb->getQuery()->iterate(null, Query::HYDRATE_ARRAY) as $person) {
                $age = $person[0]['dob']->diff($now); /* @var $age \DateInterval */
                $ageSum += $age->y + ($age->m / 12);
                $total++;
                if (Person::GENDER_FEMALE === $person[0]['gender']) {
                    $femaleTotal++;
                }
                if ($age->y >= 65) {
                    $atLeast65YearsOld++;
                } else if ($age->y < 26) {
                    $atMost25YearsOld++;
                }

                $numberPerAge[$age->y] = 1 + (isset($numberPerAge[$age->y]) ? $numberPerAge[$age->y] : 0);

                $yearOfBirth = $person[0]['dob']->format('Y');
                $numberPerYearOfBirth[$yearOfBirth] = 1 + (isset($numberPerYearOfBirth[$yearOfBirth]) ? $numberPerYearOfBirth[$yearOfBirth] : 0);
            }

            ksort($numberPerYearOfBirth, SORT_NUMERIC);
            ksort($numberPerAge, SORT_NUMERIC);

            $this->statistics = new PersonStatistics(
                $total,             // total number of members
                $femaleTotal,       // number of female members
                $atLeast65YearsOld,
                $atMost25YearsOld,
                $ageSum / $total,    // average age
                $numberPerYearOfBirth,
                $numberPerAge
            );
        }
        return $this->statistics;
    }
}


text:
import sys, os
import argparse
import subprocess
import time
import shutil
import tempfile

OKAY = 0

def Print(*objects, **kwargs):
    sep = kwargs.get('sep', ' ')
    end = kwargs.get('end', '\n')
    out = kwargs.get('file', sys.stderr)
    t = time.strftime('[%F %R:%S] ', time.localtime())
    out.write(t + sep.join(objects) + end)
    os.write(TEMP_LOG_FD, t + sep.join(objects) + end)

def init_args(args):
    # Init argparse
    parser = argparse.ArgumentParser()

    parser.add_argument('initial', nargs='?', help='initial device ROM image, ensure that can boot to home and download mode')
    parser.add_argument('test', nargs='*', help='to-be-test device ROM images, ensure those updates can boot to home and download mode')
    parser.add_argument('-c', metavar='command', default=None, help='Fastboot commands')
    parser.add_argument('-s', metavar='serialno', default=None, help='Device\'s serial number')
    parser.add_argument('--title', '-t', default='The test', help='Test title string')
    parser.add_argument('--fastboot-path', '-f', metavar='PATH', default=None, help='Google fastboot tool path')
    parser.add_argument('--htc-fastboot-path', '-F', metavar='PATH', default=None, help='HTC fastboot tool path')
    parser.add_argument('--adb-path', '-a', metavar='PATH', default=None, help='Google adb tool path')

    return parser.parse_args(args)

G_FASTBOOT = 'fastboot'
H_FASTBOOT = 'htc_fastboot'
G_ADB = 'adb'
X_PARAMS = []
LOG_PATH = None
TEMP_LOG_FD = None
TEMP_LOG_PATH = None

def init_logger():
    global LOG_PATH, TEMP_LOG_FD, TEMP_LOG_PATH
    LOG_PATH = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime()) + '_dlz_test.txt'
    TEMP_LOG_FD, TEMP_LOG_PATH = tempfile.mkstemp()

def finalized_logger():
    global LOG_PATH, TEMP_LOG_PATH
    os.close(TEMP_LOG_FD)
    shutil.move(TEMP_LOG_PATH, LOG_PATH)

def setup_tools(google, htc, adb, sn):
    global G_FASTBOOT, H_FASTBOOT
    if google: G_FASTBOOT = google
    if htc: H_FASTBOOT = htc
    if adb: G_ADB = adb
    if sn: X_PARAMS += sn

def assert_process(title, func, *args):
    Print('>>> ' + title)
    assert func(*args) == OKAY, 'Failed: ' + title
    Print('<<< Passed: ' + title)

def _run(command):
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    log = ''
    while True:
        l = p.stdout.readline()
        if l:
            log += l
            Print(l, end='')
        else:
            break
    out, err = p.communicate()
    if out:
        Print(out, end='')
    return (log, p.returncode)

def _reboot_with_params(tool, params, **kwargs):
    command = [tool]
    command.extend(X_PARAMS)
    command.extend(params)
    timeout = kwargs.get('timeout', 2)
    log, ret = _run(command)
    if ret == OKAY:
        time.sleep(timeout)
    return ret

def _a_reboot_download():
    return _reboot_with_params(G_ADB, ['reboot', 'oem-e0'], timeout=5)

def _f_reboot_download():
    return _reboot_with_params(H_FASTBOOT, ['oem', 'reboot-download'])

def _reboot_download():
    ret = OKAY
    if _a_reboot_download() != OKAY:
        ret = _f_reboot_download()
    return ret

def _f_reboot_os():
    return _reboot_with_params(H_FASTBOOT, ['reboot'])

def _do_flash(partition, rom):
    command = [H_FASTBOOT]
    command.extend(X_PARAMS)
    command.extend(['-d', 'flash', partition, rom])

    log, ret = _run(command)
    if 'hboot pre-update!' in log:
        Print('Automatically restart fastboot for preupdating ...');
        time.sleep(10)
        return _do_flash(partition, rom)
    return ret

def _do_command(cmds):
    command = [G_FASTBOOT]
    command.extend(X_PARAMS)
    command.extend(cmds)

    log, ret = _run(command)
    return ret

def _wait_for_boot():
    command = [G_ADB]
    command.extend(X_PARAMS)
    command.extend(['wait-for-device', 'logcat', '-d', 'ActivityManager:I'])

    log, ret = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
    if 'android.intent.action.BOOT_COMPLETED' in log:
        return OKAY
    else:
        time.sleep(2)
    return _wait_for_boot()

def get_partition_name(rom):
    if rom.endswith('zip'):
        return 'zip'
    return os.path.split(os.path.splitext(rom)[0])[1]

#Tests
def update(title, rom, partition, **kwargs):
    reboot = kwargs.get('reboot', False)
    reboot_download = kwargs.get('reboot_download', False)

    Print('### ' + title)

    assert_process('Flash %s %s' % (partition, rom), _do_flash, partition, rom)

    if reboot:
        assert_process('Reboot to OS', _f_reboot_os)
        assert_process('Waiting boot completed...', _wait_for_boot)
    if reboot_download:
        assert_process('Reboot to HTC DLM', _reboot_download)

    return OKAY

def main(args):
    Opts = init_args(args)

    setup_tools(Opts.fastboot_path, Opts.htc_fastboot_path, Opts.s, Opts.adb_path)

    init_logger()

    Print("*** Reboot Device")
    _reboot_download()

    if Opts.c:
        _do_command(Opts.c.split(' '))

    if Opts.initial:
        update(Opts.title, Opts.initial, get_partition_name(Opts.initial), reboot=True, reboot_download=True)

    if Opts.test and len(Opts.test) > 0:
        for rom in Opts.test[0:-1]:
            update(Opts.title, rom, get_partition_name(rom), reboot=False, reboot_download=False)
        rom = Opts.test[-1]
        update(Opts.title, rom, get_partition_name(rom), reboot=True, reboot_download=True)

    finalized_logger();

if __name__ == '__main__':
    main(sys.argv[1:])


text:
from __future__ import absolute_import
import os
import json
import ui
import scene
from PIL import Image

def get_asset_folder():
	try:
		p = os.path.dirname(scene.get_image_path('emj:Airplane'))[:-10]
	except:
		p = os.path.dirname(scene.get_image_path('Airplane'))+'/'
	return p

def get_collection_info(asset_type=''):
	folder = get_asset_folder()
	try:
		with open(folder+os.listdir(folder)[0], 'rt', encoding='utf-8') as f:
			return [asset for asset in json.loads(str(f.read()))['collections'] if asset['type'] == asset_type]
	except ValueError:
		return os.listdir(folder)

class AssetPicker (ui.View):
	def __init__(self, source, selected_cb, name='', dark_cells=False, object_type='none', parent=None, theme_manager= None):
		w, h = ui.get_screen_size()
		self.frame = (0, 0, w, h)
		self.name = name
		self.source = source
		self.dark_cells = dark_cells
		self.parent = parent
		self.object_type = object_type
		self.picked_asset = None
		self.selected_cb = selected_cb
		self.theme_manager = theme_manager
		self.create_table_view()

	def is_main(self):
		return all([1 if isinstance(i, dict) else 0 for i in self.source])

	def create_table_view(self):
		table_view = ui.TableView()
		table_view.name = 'tableview'
		table_view.flex = 'WH'
		table_view.width = self.width
		table_view.height = self.height
		table_view.delegate = self
		table_view.data_source = self
		table_view.background_color = self.theme_manager.main_background_colour

		self.add_subview(table_view)

	def tableview_number_of_rows(self, tableview, section):
		return len(self.source)

	def tableview_cell_for_row(self, tableview, section, row):
		cell = ui.TableViewCell('subtitle')
		cell.accessory_type = 'disclosure_indicator'
		if self.is_main():
			text = self.source[row]['title']
			cell.text_label.text = text
			if 'copyright' in self.source[row]:
				cell.detail_text_label.text = self.source[row]['copyright']
		else:
			cell.text_label.text = self.source[row]
			tableview.row_height = 48
			cell.image_view.image = ui.Image.named(self.source[row])
			if self.dark_cells:
				cell.image_view.background_color = 'black'
		cell.text_label.text_color = self.theme_manager.main_text_colour
		cell.detail_text_label.text_color = self.theme_manager.main_text_colour
		cell.background_color = self.theme_manager.main_background_colour
		return cell

	def tableview_did_select(self, tableview, section, row):
		if not self.is_main():
			if self.parent:
				pass
				# do something with asset
			# example:
			self.selected_cb(self.source[row])
			self.navigation_view.pop_view()
			return
		path = os.path.join(get_asset_folder(), self.source[row]['path'])
		if not os.path.isdir(path):
			with open(path, 'r') as f:
				source = eval(f.read())
		else:
			source = sorted(list(set([path.split('/')[-1]+':'+(i.split('@')[0] if '@' in i else i.split('.')[0]) for i in os.listdir(path)])))
		dark_cells = 1 if 'darkBackground' in self.source[row] else 0
		self.navigation_view.push_view(AssetPicker(source, name=self.source[row]['title'], dark_cells=dark_cells, object_type=self.object_type, parent=self.parent, selected_cb=self.selected_cb, theme_manager = self.theme_manager))

def get_view(selected_cb, parent=None, object_type='none', theme_manager=None):
	source = get_collection_info(asset_type='image')
	main_view = AssetPicker(source, name='Assets', object_type=object_type, parent=parent, selected_cb=selected_cb, theme_manager=theme_manager)
	main_view.background_color = theme_manager.main_background_colour
	return main_view

if __name__ == '__main__':
	v= get_view(None)
	v.present()


text:
<layout:VerticalLayout id="notSuspendedLayout"
	xmlns:layout="sap.ui.layout"
	width="100%"
	xmlns="sap.m"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:core="sap.ui.core"
	xmlns:f="sap.ui.layout.form"
	xmlns:f2="sap.f"
	xmlns:mdc="sap.ui.mdc"
	xmlns:table="sap.ui.mdc"

	xmlns:vhfb="sap.ui.mdc.filterbar.vh"
	xmlns:mdcv="sap.ui.mdc.valuehelp"
	xmlns:mdcvc="sap.ui.mdc.valuehelp.content"
	xmlns:mdcf="sap.ui.mdc.field"
	xmlns:mdct="sap.ui.mdc.table"
	xmlns:ui="sap.ui"
	xmlns:uit="sap.ui.table"
	xmlns:variants="sap.ui.fl.variants"
	xmlns:types="sap.ui.v4demo.types"
	xmlns:demo="sap.ui.v4demo.controls">

	<Title class="sapUiSmallMarginBottom" level="H3" text="Simple Scenario" />

	<mdc:FilterBar id="FB0" p13nMode="Value" liveMode="false" delegate="{name: 'delegates/odata/v4/FilterBarDelegate', payload: {collectionName: 'Books'}}">
		<mdc:dependents>
			<mdc:ValueHelp
				id="FB0-FH1-10"
				delegate="{name: 'sap/ui/v4demo/delegate/ValueHelp.delegate', payload: {}}">
				<mdc:dialog>
					<mdcv:Dialog title="MDC Table with ui.Table">
						<mdcvc:MDCTable id="mdcTableContent1" keyPath="ID" descriptionPath="name" filterFields="$search" group="group1" title="Default Search Template" forceBind="true">
							<mdc:Table autoBindOnInit="false"
								id="mdcTable1"
								width="100%"
								height="100%"
								headerVisible="true"
								selectionMode="{= ${settings>/maxConditions} === -1 ? 'Multi' : 'Single'}"
								p13nMode="Column,Sort"
								delegate="{name: 'sap/ui/v4demo/delegate/GridTable.delegate', payload: {collectionName: 'Authors'}}"
								threshold="50">
								<mdc:type>
									<mdc:table.GridTableType rowCountMode="Auto"/>
								</mdc:type>
								<mdc:columns>
									<mdc:table.Column id="mdcTable1_col_ID" header="ID" dataProperty="ID">
										<Text text="{ID}" />
									</mdc:table.Column>
									<mdc:table.Column id="mdcTable1_col_name" header="Name" dataProperty="name">
										<Text text="{name}" />
									</mdc:table.Column>
									<mdc:table.Column id="mdcTable1_col_dateOfBirth" header="Date of birth" dataProperty="dateOfBirth">
										<Text text="{dateOfBirth}" />
									</mdc:table.Column>
								</mdc:columns>
							</mdc:Table>
						</mdcvc:MDCTable>

					</mdcv:Dialog>
				</mdc:dialog>
			</mdc:ValueHelp>
		</mdc:dependents>
		<mdc:filterItems>

			<mdc:FilterField delegate="{name: 'delegates/odata/v4/FieldBaseDelegate', payload: {}}"
				id="FB0-FF1-10"
				label="TestField"
				conditions="{$filters>/conditions/author_ID}"
				dataType="Edm.Int32"
				required="false"
				fieldHelp="FB0-FH1-10"
				display="DescriptionValue"
				maxConditions="{settings>/maxConditions}" />
		</mdc:filterItems>
	</mdc:FilterBar>

</layout:VerticalLayout>


text:
using std::string;

namespace kudu {

typedef SliceMap<int>::type MySliceMap;

TEST(SliceTest, TestSliceMap) {
  MySliceMap my_map;
  Slice a("a");
  Slice b("b");
  Slice c("c");

  // Insertion is deliberately out-of-order; the map should restore order.
  InsertOrDie(&my_map, c, 3);
  InsertOrDie(&my_map, a, 1);
  InsertOrDie(&my_map, b, 2);

  int expectedValue = 0;
  for (const MySliceMap::value_type& pair : my_map) {
    int data = 'a' + expectedValue++;
    ASSERT_EQ(Slice(reinterpret_cast<uint8_t*>(&data), 1), pair.first);
    ASSERT_EQ(expectedValue, pair.second);
  }

  expectedValue = 0;
  for (auto iter = my_map.begin(); iter != my_map.end(); iter++) {
    int data = 'a' + expectedValue++;
    ASSERT_EQ(Slice(reinterpret_cast<uint8_t*>(&data), 1), iter->first);
    ASSERT_EQ(expectedValue, iter->second);
  }
}

} // namespace kudu


text:
title: Scenes
layout: usermanual-page.hbs
position: 9
---

Scenes contain the Entity hierarchy which lists the order and structure of all Entities in your scene. They are edited using the PlayCanvas Editor.


text:
from __future__ import print_function
import pysb.bng
import numpy
import sympy
import re
import ctypes
import csv
import scipy.interpolate
from pysundials import cvode

# These set of functions set up the system for annealing runs
# and provide the runner function as input to annealing

def annlinit(model, abstol=1.0e-3, reltol=1.0e-3, nsteps = 1000, itermaxstep = None):
    '''
    must be run to set up the environment for annealing with pysundials
    '''
    # Generate equations
    pysb.bng.generate_equations(model)
    # Get the size of the ODE array
    odesize = len(model.odes)

    # init the arrays we need
    yzero = numpy.zeros(odesize)  #initial values for yzero

    # assign the initial conditions
    for cplxptrn, ic_param in model.initial_conditions:
        speci = model.get_species_index(cplxptrn)
        yzero[speci] = ic_param.value

    # initialize y with the yzero values
    y = cvode.NVector(yzero)

    # make a dict of ydot functions. notice the functions are in this namespace.
    # replace the kxxxx constants with elements from the params array
    rhs_exprs = []
    for i in range(0,odesize):
        # first get the function string from sympy, replace the the "sN" with y[N]
        tempstring = re.sub(r's(\d+)', lambda m: 'y[%s]'%(int(m.group(1))), str(model.odes[i]))
        # now replace the constants with 'p' array names; cycle through the whole list
        #for j in range(0, numparams):
        #    tempstring = re.sub('(?<![A-Za-z0-9_])%s(?![A-Za-z0-9_])'%(model.parameters[j].name),'p[%d]'%(j), tempstring)
        for j, parameter in enumerate(model.parameters):
            tempstring = re.sub('(?<![A-Za-z0-9_])%s(?![A-Za-z0-9_])' % parameter.name, 'p[%d]' % j, tempstring)
        # make a list of compiled rhs expressions which will be run by the integrator
        # use the ydots to build the function for analysis
        # (second arg is the "filename", useful for exception/debug output)
        rhs_exprs.append(compile(tempstring, '<ydot[%s]>' % i, 'eval'))

    # Create the structure to hold the parameters when calling the function
    # This results in a generic "p" array
    numparams = len(model.parameters)
    class UserData(ctypes.Structure):
        _fields_ = [('p', cvode.realtype*numparams)] # parameters
    PUserData = ctypes.POINTER(UserData)
    data = UserData()

    #paramlist for annealing feeder function
    #paramlist = []
    #for i in range(0, numparams):
    #    # notice: p[i] ~ model.parameters[i].name ~ model.parameters[i].value
    #    data.p[i] = model.parameters[i].value
    #    paramlist.append(model.parameters[i].value)
    #paramarray = numpy.asarray(paramlist)

    data.p[:] = [p.value for p in model.parameters]
    paramarray = numpy.array([p.value for p in model.parameters])

    # if no sensitivity analysis is needed allocate the "p" array as a
    # pointer array that can be called by sundials "f" as needed
    def f(t, y, ydot, f_data):
        data = ctypes.cast(f_data, PUserData).contents
        rhs_locals = {'y': y, 'p': data.p}
        for i in range(0,len(model.odes)):
            ydot[i] = eval(rhs_exprs[i], rhs_locals)
        return 0

    # CVODE STUFF
    # initialize the cvode memory object, use BDF and Newton for stiff
    cvode_mem = cvode.CVodeCreate(cvode.CV_BDF, cvode.CV_NEWTON)
    # allocate the cvode memory as needed, pass the function and the init ys
    cvode.CVodeMalloc(cvode_mem, f, 0.0, y, cvode.CV_SS, reltol, abstol)
    # point the parameters to the correct array
    # if the params are changed later this does not need to be reassigned (???)
    cvode.CVodeSetFdata(cvode_mem, ctypes.pointer(data))
    # link integrator with linear solver
    cvode.CVDense(cvode_mem, odesize)
    #stepsize
    if itermaxstep != None:
        cvode.CVodeSetMaxStep(cvode_mem, itermaxstep)

    #list of outputs
    xout = numpy.zeros(nsteps)
    yout = numpy.zeros([nsteps, odesize])

    #initialize the arrays
    #print("Initial parameter values:", y)
    xout[0] = 0.0 #CHANGE IF NEEDED
    #first step in yout
    for i in range(0, odesize):
        yout[0][i] = y[i]

    # f: the function called by cvodes calls that returns dy
    # rhs_exprs: the python expression for the right hand side (list of strings)
    # y: a CVode NVector object with the initial values for all species
    # odesize: the number of odes
    # data: a ctypes data structure (for Sundials) containing the parameter values (floats)
    # xout: the numpy array where the time values will be put
    # yout: the numpy array where the integrated timeseries will be put
    # nsteps: the number of time steps
    # cvode_mem: cvode memory object defining the step method
    # yzero: a numpy array of the initial conditions
    # paramarray: a numpy array containing the parameter values (floats). (same contents as data, but different datatype)
    # reltol: integrator relative tolerance (float)
    # abstol: integrator absolute tolerance (float)
    return [f, rhs_exprs, y, odesize, data, xout, yout, nsteps, cvode_mem, yzero, reltol, abstol], paramarray

# reltol of 1.0e-3, relative error of ~1%. abstol of 1.0e-3, enough for values that oscillate in the hundreds to thousands
def annlodesolve(model, tfinal, envlist, params, tinit = 0.0, ic=True):
    '''
    the ODE equation solver tailored to work with the annealing algorithm
    model: the model object
    envlist: the list returned from annlinit
    params: the list of parameters that are being optimized with annealing
    tinit: initial time
    reltol: relative tolerance
    abstol: absolute tolerance
    ic: reinitialize initial conditions to a value in params
    '''
    (f, rhs_exprs, y, odesize, data, xout, yout, nsteps, cvode_mem, yzero, reltol, abstol) = envlist

    #set the initial values and params in each run
    #all parameters are used in annealing.
    for i in range(len(params)):
        data.p[i] = params[i]

    # update yzero if initial conditions are being modified as part of the parameters
    # did it this way b/c yzero and data.p may not always want to be modified at the same time
    # FIXME: this is not the best way to do this.
    # the params list should NOT contain the initial conditions if they are not
    # to be used in the annealing... so this is a hack based on the fact that the
    # initial conditions are contained as part of the model.parameters list.
    # FIXME
    #
    if ic is True:
        for cplxptrn, ic_param in model.initial_conditions:
            speci = model.get_species_index(cplxptrn)
            yzero[speci] = ic_param.value

    #reset initial concentrations
    y = cvode.NVector(yzero)

    # Reinitialize the memory allocations, DOES NOT REALLOCATE
    cvode.CVodeReInit(cvode_mem, f, 0.0, y, cvode.CV_SS, reltol, abstol)

    tadd = tfinal/nsteps

    t = cvode.realtype(tinit)
    tout = tinit + tadd

    #print("Beginning integration")
    #print("TINIT:", tinit, "TFINAL:", tfinal, "TADD:", tadd, "ODESIZE:", odesize)
    #print("Integrating Parameters:\n", params)
    #print("y0:", yzero)

    for step in range(1, nsteps):
        ret = cvode.CVode(cvode_mem, tout, y, ctypes.byref(t), cvode.CV_NORMAL)
        if ret !=0:
            print("CVODE ERROR %i"%(ret))
            break

        xout[step]= tout
        for i in range(0, odesize):
            yout[step][i] = y[i]

        # increase the time counter
        tout += tadd
    #print("Integration finished")

    #now deal with observables
    yobs = numpy.zeros([len(model.observables), nsteps])

    #sum up the correct entities
    for i, obs in enumerate(model.observables):
        coeffs = obs.coefficients
        specs  = obs.species
        yobs[i] = (yout[:, specs] * coeffs).sum(1)

    #merge the x and y arrays for easy analysis
    xyobs = numpy.vstack((xout, yobs))

    return (xyobs,xout,yout, yobs)

def compare_data(xparray, simarray, xspairlist, vardata=False):
    """Compares two arrays of different size and returns the X^2 between them.
    Uses the X axis as the unit to re-grid both arrays.
    xparray: experimental data
    xparrayaxis: which axis of xparray to use for simulation
    simarray: simulation data
    simarrayaxis: which axis of simarray to use for simulation
    """
    # this expects arrays of the form array([time, measurement1, measurement2, ...])
    # the time is assumed to be roughly the same for both and the
    # shortest time will be taken as reference to regrid the data
    # the regridding is done using a b-spline interpolation
    # xparrayvar shuold be the variances at every time point
    #
    # FIXME FIXME FIXME FIXME
    # This prob should figure out the overlap of the two arrays and
    # get a spline of the overlap. For now just assume the simarray domain
    # is bigger than the xparray. FIXME FIXME FIXME FIXME
    #
    #rngmin = max(xparray[0].min(), simarray[0].min())
    #rngmax = min(xparray[0].max(), simarray[0].max())
    #rngmin = round(rngmin, -1)
    #rngmax = round(rngmax, -1)
    #print("Time overlap range:", rngmin,"to", rngmax)

    ipsimarray = numpy.zeros(xparray.shape[1])
    objout = 0

    for i in range(len(xspairlist)):
        # create a b-spline of the sim data and fit it to desired range

        #some error checking
        #print("xspairlist length:", len(xspairlist[i]))
        #print("xspairlist element type:", type(xspairlist[i]))
        #print("xspairlist[i] elements:", xspairlist[i][0], xspairlist[i][1])
        assert type(xspairlist[i]) is tuple
        assert len(xspairlist[i]) == 2

        xparrayaxis = xspairlist[i][0]
        simarrayaxis = xspairlist[i][1]

        tck = scipy.interpolate.splrep(simarray[0], simarray[simarrayaxis])
        ipsimarray = scipy.interpolate.splev(xparray[0], tck) #xp x-coordinate values to extract from y splines

        # we now have x and y axis for the points in the model array
        # calculate the objective function
        #                        1
        # obj(t, params) = -------------(S_sim(t,params)-S_exp(t))^2
        #                  2*sigma_exp^2

        diffarray = ipsimarray - xparray[xparrayaxis]
        diffsqarray = diffarray * diffarray

        if vardata is True:
            #print("using XP VAR",xparrayaxis+1)
            xparrayvar = xparray[xparrayaxis+1] # variance data provided in xparray in next column
        else:
        # assume a default variance
            xparrayvar = numpy.ones(xparray.shape[1])
            xparrayvar = xparray[xparrayaxis]*.25 #assume a coeff of variation of .25 = sigma/mean (from Chen, Gaudet...)
            # Remove any zeros in the variance array # FIXME
            for i in range(0, len(xparrayvar)):
                if (xparrayvar[i] == 0):
                    xparrayvar[i] = 1

        xparrayvar = xparrayvar*2.0
        #numpy.seterr(divide='ignore')
        objarray = diffsqarray / xparrayvar

        # check for inf in objarray, they creep up when there are near zero or zero values in xparrayvar
        for i in range(len(objarray)):
            if numpy.isinf(objarray[i]) or numpy.isnan(objarray[i]):
                #print("CORRECTING NAN OR INF. IN ARRAY")
                #print(objarray)
                objarray[i] = 1e-100 #zero enough

        objout += objarray.sum()
        #print("OBJOUT(%d,%d):%f  |\t\tOBJOUT(CUM):%f"%(xparrayaxis, simarrayaxis, objarray.sum(), objout))

    print("OBJOUT(total):", objout)
    return objout

def logparambounds(params, omag=1, useparams=[], usemag=None, initparams=[], initmag=None):
    ub = numpy.zeros(len(params))
    lb = numpy.zeros(len(params))
    # set upper/lower bounds for generic problem
    for i in range(len(params)):
        if i in useparams and i not in initparams:
            ub[i] = params[i] * pow(10,usemag)
            lb[i] = params[i] / pow(10,usemag)
        elif i in initparams:
            ub[i] = params[i] * pow(10,initmag)
            lb[i] = params[i] / pow(10,initmag)
        else:
            ub[i] = params[i] * pow(10, omag)
            lb[i] = params[i] / pow(10, omag)
    return lb, ub

def linparambounds(params, fact=.25, useparams=[], usefact=None):
    ub = numpy.zeros(len(params))
    lb = numpy.zeros(len(params))
    # set upper/lower bounds for generic problem
    for i in range(len(params)):
        if i in useparams:
            ub[i] = params[i] + (params[i] * fact)
            lb[i] = params[i] - (params[i] * fact)
        else:
            ub[i] = params[i] + (params[i] * usefact)
            lb[i] = params[i] - (params[i] * usefact)
    lb[numpy.where(lower<0.)] = 0.0 #make sure we don't go negative on parameters...
    return lb, ub

def mapprms(nums01, lb, ub, scaletype="log"):
    """given an upper bound(ub), lower bound(lb), and a sample between zero and one (zosample)
    return a set of parameters within the lb, ub range.
    nums01: array of numbers between zero and 1
    lb: array of lower bound for each parameter
    ub: arary of upper bound for each parameter
    """
    params = numpy.zeros_like(nums01)

    if scaletype == "log":
        params = lb*(ub/lb)**nums01 # map the [0..1] array to values sampled over their omags
    elif scaletype == "lin":
        params = (nums01*(ub-lb)) + lb

    return params

def writetofile(fout, simparms, simdata, temperature):
    imax, jmax = simdata.shape
    nparms = len(simparms)

    fout.write('# TEMPERATURE\n{0}\n'.format(temperature))
    fout.write('# PARAMETERS ({0})\n'.format(len(simparms)))
    for i in range(nparms):
        fout.write('{0}'.format(simparms[i]))
        if (i !=0 and i%5 == 0) or (i == nparms-1):
            fout.write('\n')
        else:
            fout.write(', ')

    fout.write('# SIMDATA ({0},{1})\n'.format(imax, jmax))
    for i in range(imax):
        fout.write('# {0}\n'.format(i))
        for j in range(jmax):
            fout.write('{0}'.format(simdata[i][j]))
            if (j != 0 and j%10 == 0) or (j == jmax-1):
                fout.write('\n')
            else:
                fout.write(', ')
    fout.write('#-------------------------------------------------------------------------------------------------\n')
    return

def tenninetycomp(outlistnorm, arglist, xpsamples=1.0):
    """ Determine Td and Ts. Td calculated at time when signal goes up to 10%.
        Ts calculated as signal(90%) - signal(10%). Then a chi-square is calculated.
        outlistnorm: the outlist from anneal_odesolve
        arglist: simaxis, Tdxp, varTdxp, Tsxp, varTsxp
        xpsamples
    """
    xarr = outlistnorm[0] #this assumes the first column of the array is time
    yarr = outlistnorm[arglist[0]] #the argument passed should be the axis
    Tdxp = arglist[1]
    varTdxp = arglist[2]
    Tsxp = arglist[3]
    varTsxp = arglist[4]

    # make a B-spine representation of the xarr and yarr
    tck = scipy.interpolate.splrep(xarr, yarr)
    t, c, k = tck
    tenpt = numpy.max(yarr) * .1 # the ten percent point in y-axis
    ntypt = numpy.max(yarr) * .9 # the 90 percent point in y-axis
    #lower the spline at the abcissa
    xten = scipy.interpolate.sproot((t, c-tenpt, k))[0]
    xnty = scipy.interpolate.sproot((t, c-ntypt, k))[0]

    #now compare w the input data, Td, and Ts
    Tdsim = xten #the Td is the point where the signal crosses 10%; should be the midpoint???
    Tssim = xnty - xten

    # calculate chi-sq as
    #
    #            1                           1
    # obj = ----------(Tdsim - Tdxp)^2 + --------(Tssim - Tsxp)^2
    #       2*var_Tdxp                   2*var_Td
    #

    obj = ((1./varTdxp) * (Tdsim - Tdxp)**2.) + ((1./varTsxp) * (Tssim - Tsxp)**2.)
    #obj *= xpsamples

    print("OBJOUT-10-90:(%g,%g):%g"%(Tdsim, Tssim, obj))

    return obj

def annealfxn(zoparams, time, model, envlist, xpdata, xspairlist, lb, ub, tn = [], scaletype="log", norm=True, vardata=False, fileobj=None):
    """Feeder function for scipy.optimize.anneal
    zoparams: the parameters in the range [0,1) to be sampled
    time: the time scale for the simulation
    model: a PySB model object
    envlist: an environment list for the sundials integrator
    xpdata: experimental data
    xspairlist: the pairlist of the correspondence of experimental and simulation outputs
    lb: lower bound for parameters
    ub: upper bound for parameters
    tn: list of values for ten-ninety fits
    scaletype: log, linear,etc to convert zoparams to real params b/w lb and ub. default "log"
    norm: normalization on. default true
    vardata: variance data available. default "false"
    fileobj: file object to write data output. default "None"

    """

    # convert of linear values from [0,1) to desired sampling distrib
    paramarr = mapprms(zoparams, lb, ub, scaletype="log")

    #debug
    #print("ZOPARAMS:\n", zoparams,"\n")
    #print(paramarr)

    # eliminate values outside the boundaries, i.e. those outside [0,1)
    if numpy.greater_equal(paramarr, lb).all() and numpy.less_equal(paramarr, ub).all():
        print("integrating... ")
        outlist = annlodesolve(model, time, envlist, paramarr)

        # normalized data needs a bit more tweaking before objfxn calculation
        if norm is True:
            print("Normalizing data")
            datamax = numpy.max(outlist[0], axis = 1)
            datamin = numpy.min(outlist[0], axis = 1)
            outlistnorm = ((outlist[0].T - datamin)/(datamax-datamin)).T
            # xpdata[0] should be time, get from original array
            outlistnorm[0] = outlist[0][0].copy()
            # xpdata here should be normalized
            objout = compare_data(xpdata, outlistnorm, xspairlist, vardata)
            if tn:
                tn = tenninetycomp(outlistnorm, tn, len(xpdata[0]))
                objout += tn
            print("NORM objout TOT:", objout)
        else:
            objout = compare_data(xpdata, outlist[0], xspairlist, vardata)
            if tn:
                tn = tenninetycomp(outlist[0], tn)
                objout += tn
            print("objout TOT:", objout)
    else:
        print("======> VALUE OUT OF BOUNDS NOTED")
        temp = numpy.where((numpy.logical_and(numpy.greater_equal(paramarr, lb), numpy.less_equal(paramarr, ub)) * 1) == 0)
        for i in temp:
            print("======>",i,"\n======", paramarr[i],"\n", zoparams[i],"\n")
        objout = 1.0e300 # the largest FP in python is 1.0e308, otherwise it is just Inf

    # save the params and temps for analysis

    # FIXME If a parameter is out of bounds, outlist and outlistnorm will be undefined and this will cause an error
    if fileobj:
        if norm:
            writetofile(fileobj, paramarr, outlistnorm, objout)
        else:
            writetofile(fileobj, paramarr, outlist, objout)

    return objout


text:
namespace LINQPadUtils.Fragments
{
    using LINQPadUtils.Markup;
    using LINQPadUtils.MetadataProviders;

    class PrimitiveTypeFragment : FragmentBase
    {
        public PrimitiveTypeFragment(TypeMetadataProviderBase metadata)
            : base(metadata)
        {
        }

        public override string Render(int depthLimit, int currentDepth)
        {
            var source = base.Metadata.SourceObject;

            var sourceObjectType = base.Metadata.SourceObjectType;

            var value = ValueDisplay.GetDisplayValue(source, sourceObjectType);

            return HtmlTag.WrapValue("span", value).ToString();
        }
    }
}


text:
This is a sub package of [web3.js][repo]

This is the PromiEvent package is used to return a EventEmitter mixed with a Promise to allow multiple final states as well as chaining.
Please read the [documentation][docs] for more.

## Installation

### Node.js

```bash
npm install web3-core-promievent
```

### In the Browser

Build running the following in the [web3.js][repo] repository:

```bash
npm run-script build-all
```

Then include `dist/web3-core-promievent.js` in your html file.
This will expose the `Web3PromiEvent` object on the window object.

## Usage

```js
// in node.js
var Web3PromiEvent = require('web3-core-promievent');

var myFunc = function(){
    var promiEvent = Web3PromiEvent();

    setTimeout(function() {
        promiEvent.eventEmitter.emit('done', 'Hello!');
        promiEvent.resolve('Hello!');
    }, 10);

    return promiEvent.eventEmitter;
};

// and run it
myFunc()
.then(console.log);
.on('done', console.log);
```

[docs]: http://web3js.readthedocs.io/en/1.0/
[repo]: https://github.com/ethereum/web3.js


text:
SHELL := bash
REPO ?= imma/ubuntu
TAG ?= $(shell basename $(shell pwd))

build:
	docker build --no-cache -t $(REPO):$(TAG) .
	#rsync --progress -ia --blocking-io -e "docker run -i $(REPO):$(TAG)" env:/data/. data/.


text:
makeSafeFileName = function(name) {
  return name.replace(/\.\./g, '');
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: darksy
 * Date: 15/12/2015
 * Time: 11:49
 */

namespace MovieUser\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class RegistrationController extends AbstractActionController
{
    public function indexAction()
    {
        return parent::indexAction(); // TODO: Change the autogenerated stub
    }
}


text:
title: "No-op Mode"
sub_link: "python-library/no-op"
meta_title: "Introduction to no-op mode - Python Client References"
meta_description: "Polyaxon's Python library allows to turn off all API calls and silently pass through all function calls."
visibility: public
status: published
tags:
  - client
  - api
  - polyaxon
  - python
sidebar: "core"
---

## Overview

The no-op mode allows users to turn off all API calls and silently pass through all function calls. this behavior is generally useful if a user needs to debug or test
a script without the need to connect to a Polyaxon Cluster.

```bash
export POLYAXON_NO_OP=true
# Or
export POLYAXON_NO_OP="1"
```

or in Python

```python
import os

os.environ["POLYAXON_NO_OP"] = "true"
# Or
os.environ["POLYAXON_NO_OP"] = "1"
```

## Disabling Polyaxon clients without changing code

Since using the Polyaxon client and the tracking API requires code change, e.g.

```python
from polyaxon.client import ProjectClient, RunClient

project_client = ProjectClient()
run_client = RunClient()
...
# Using the client results in void calls
project_client.list_runs()
project_client.list_versions()
run_client.refresh_data()
run_client.log_inputs(...)
```

Users might need to run the same code outside of a Polyaxon context,
which will break since Polyaxon related operations perform API calls.

Users won't need to perform any change to their code,
they just need to set an environment variable `POLYAXON_NO_OP` to true/1, and the Polyaxon related code will be ignored.


text:
// .NAME vtkGenericEdgeTable - keep track of edges (defined by pair of integer id's)
// .SECTION Description
// vtkGenericEdgeTable is used to indicate the existance of and hold
// information about edges. Similar to vtkEdgeTable, this class is
// more sophisticated in that it uses reference counting to keep track
// of when information about an edge should be deleted.
//
// vtkGenericEdgeTable is a helper class used in the adaptor framework.  It
// is used during the tessellation process to hold information about the
// error metric on each edge. This avoids recomputing the error metric each
// time the same edge is visited.

#ifndef __vtkGenericEdgeTable_h
#define __vtkGenericEdgeTable_h

#include "vtkObject.h"

class vtkEdgeTableEdge;
class vtkEdgeTablePoints;

class VTK_FILTERING_EXPORT vtkGenericEdgeTable : public vtkObject
{
public:
  // Description:
  // Instantiate an empty edge table.
  static vtkGenericEdgeTable *New();

  // Description:
  // Standard VTK type and print macros.
  vtkTypeRevisionMacro(vtkGenericEdgeTable,vtkObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Split the edge with the indicated point id.
  void InsertEdge(vtkIdType e1, vtkIdType e2, vtkIdType cellId,
                  int ref, vtkIdType &ptId );

  // Description:
  // Insert an edge but do not split it.
  void InsertEdge(vtkIdType e1, vtkIdType e2, vtkIdType cellId, int ref = 1 );

  // Description:
  // Method to remove an edge from the table. The method returns the
  // current reference count.
  int RemoveEdge(vtkIdType e1, vtkIdType e2);

  // Description:
  // Method to determine whether an edge is in the table (0 or 1), or not (-1).
  // It returns whether the edge was split (1) or not (0),
  // and the point id exists.
  int CheckEdge(vtkIdType e1, vtkIdType e2, vtkIdType &ptId);

  // Description:
  // Method that increments the referencecount and returns it.
  int IncrementEdgeReferenceCount(vtkIdType e1, vtkIdType e2,
                                  vtkIdType cellId);

  // Description:
  // Return the edge reference count.
  int CheckEdgeReferenceCount(vtkIdType e1, vtkIdType e2);

  // Description:
  // To specify the starting point id. It will initialize LastPointId
  // This is very sensitive the start point should be cautiously chosen
  void Initialize(vtkIdType start);

  // Description:
  // Return the total number of components for the point-centered attributes.
  // \post positive_result: result>0
  int GetNumberOfComponents();

  // Description:
  // Set the total number of components for the point-centered attributes.
  // \pre positive_count: count>0
  void SetNumberOfComponents(int count);

  // Description:
  // Check if a point is already in the point table.
  int CheckPoint(vtkIdType ptId);

  // Description:
  // Check for the existence of a point and return its coordinate value.
  // \pre scalar_size: sizeof(scalar)==this->GetNumberOfComponents()
  int CheckPoint(vtkIdType ptId, double point[3], double *scalar);

  // Description:
  // Insert point associated with an edge.
  void InsertPoint(vtkIdType ptId, double point[3]);
  // \pre: sizeof(s)==GetNumberOfComponents()
  void InsertPointAndScalar(vtkIdType ptId, double pt[3], double *s);

  // Description:
  // Remove a point from the point table.
  void RemovePoint(vtkIdType ptId);

  // Description:
  // Increment the reference count for the indicated point.
  void IncrementPointReferenceCount(vtkIdType ptId );

  // Description:
  // For debugging purposes. It is particularly useful to dump the table
  // and check that nothing is left after a complete iteration. LoadFactor
  // should ideally be very low to be able to have a constant time access
  void DumpTable();
  void LoadFactor();

//BTX
class PointEntry
{
public:
  vtkIdType PointId;
  double Coord[3];
  double *Scalar;  // point data: all point-centered attributes at this point
  int numberOfComponents;

  int Reference;  //signed char

  // Description:
  // Constructor with a scalar field of `size' doubles.
  // \pre positive_number_of_components: size>0
  PointEntry(int size);

  ~PointEntry()
    {
      delete[] this->Scalar;
    }

  PointEntry(const PointEntry &other)
    {
    this->PointId  = other.PointId;

    memcpy(this->Coord,other.Coord,sizeof(double)*3);

    int c = other.numberOfComponents;
    this->numberOfComponents = c;
    this->Scalar = new double[c];
    memcpy(this->Scalar, other.Scalar, sizeof(double)*c);
    this->Reference = other.Reference;
    }

  void operator=(const PointEntry &other)
    {
    if(this != &other)
      {
      this->PointId  = other.PointId;

      memcpy(this->Coord, other.Coord, sizeof(double)*3);

      int c = other.numberOfComponents;

      if(this->numberOfComponents!=c)
        {
        delete[] this->Scalar;
        this->Scalar = new double[c];
        this->numberOfComponents = c;
        }
      memcpy(this->Scalar, other.Scalar, sizeof(double)*c);
      this->Reference = other.Reference;
      }
    }
};

class EdgeEntry
{
public:
  vtkIdType E1;
  vtkIdType E2;

  int Reference;  //signed char
  int ToSplit;  //signed char
  vtkIdType PtId;
  vtkIdType CellId; //CellId the edge refer to at a step in tesselation

  EdgeEntry()
    {
    this->Reference = 0;
    this->CellId = -1;
    }
  ~EdgeEntry() {}

  EdgeEntry(const EdgeEntry& copy)
    {
    this->E1 = copy.E1;
    this->E2 = copy.E2;

    this->Reference = copy.Reference;
    this->ToSplit = copy.ToSplit;
    this->PtId = copy.PtId;
    this->CellId = copy.CellId;
    }

  void operator=(const EdgeEntry& entry)
    {
    if(this == &entry)
      {
      return;
      }
    this->E1 = entry.E1;
    this->E2 = entry.E2;
    this->Reference = entry.Reference;
    this->ToSplit = entry.ToSplit;
    this->PtId = entry.PtId;
    this->CellId = entry.CellId;
    }
};
//ETX

protected:
  vtkGenericEdgeTable();
  ~vtkGenericEdgeTable();

  // Description:
  // Split the edge with the indicated point id.
  void InsertEdge(vtkIdType e1, vtkIdType e2, vtkIdType cellId,
                  int ref, int toSplit, vtkIdType &ptId );

  //Hash table that contiain entry based on edges:
  vtkEdgeTableEdge   *EdgeTable;

  //At end of process we should be able to retrieve points coord based on pointid
  vtkEdgeTablePoints *HashPoints;

  // Main hash functions
  //For edge table:
  vtkIdType HashFunction(vtkIdType e1, vtkIdType e2);

  //For point table:
  vtkIdType HashFunction(vtkIdType ptId);

  // Keep track of the last point id we inserted, increment it each time:
  vtkIdType LastPointId;

  vtkIdType NumberOfComponents;

private:
  vtkGenericEdgeTable(const vtkGenericEdgeTable&);  // Not implemented.
  void operator=(const vtkGenericEdgeTable&);  // Not implemented.

};

#endif


text:
'use strict';

const argv = require('yargs')
    .usage('Usage: $0 <command> [options]')
    .command('get', 'Run get benchmark')
    .command('set', 'Run set benchmark')
    .command('random', 'Run random op (get, set, delete) benchmark')
    .number('t')
    .describe('t', 'Total number of operations to run')
    .number('c')
    .describe('c', 'Concurrency level for operations')
    .number('s')
    .describe('s', 'Size of values to use (for ASCII strings)')
    .help('h')
    .argv;
const runBenchmark = require('./BenchmarkRunner');

const KEY = '00000000-0000-0000-0000-000000000000';
const VALUE_SIZE = argv.s || 1024;
const VAL = randomString(VALUE_SIZE);

const RANDOM_ENTRY_COUNT = 1000;
const RANDOM_GET_PERCENTAGE = 40;
const RANDOM_SET_PERCENTAGE = 40;

function randomString(len) {
    const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let res = '';
    for (let i = 0; i < len; i++) {
        const pos = Math.floor(Math.random() * charSet.length);
        res += charSet.substring(pos, pos + 1);
    }
    return res;
}

function randomOp(map) {
    const key = Math.random() * RANDOM_ENTRY_COUNT;
    const opType = Math.floor(Math.random() * 100);
    if (opType < RANDOM_GET_PERCENTAGE) {
        return map.get(key);
    } else if (opType < RANDOM_GET_PERCENTAGE + RANDOM_SET_PERCENTAGE) {
        return map.set(key, VAL);
    }
    return map.delete(key);
}

(async () => {
    try {
        const type = argv._[0];

        let prepareOp;
        let nextOp;
        switch (type) {
            case 'get':
                prepareOp = (map) => map.set(KEY, VAL);
                nextOp = (map) => map.get(KEY);
                break;
            case 'set':
                nextOp = (map) => map.set(KEY, VAL);
                break;
            case 'random':
                nextOp = (map) => randomOp(map);
                break;
            default:
                console.error(`Unknown command "${type}". Supported commands are "get", "set", "random".`);
                process.exit(1);
        }

        console.log('Benchmark type:', type);
        console.log('Value size:', VALUE_SIZE);
        await runBenchmark({
            prepareOp,
            nextOp,
            totalOps: argv.t || 1000000,
            concurrency: argv.c || 128
        });
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();