text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

package test.fixtures.includes;

import static com.facebook.swift.service.SwiftConstants.STICKY_HASH_KEY;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.thrift.protocol.*;
import org.apache.thrift.ClientPushMetadata;
import org.apache.thrift.InteractionCreate;
import org.apache.thrift.InteractionTerminate;
import com.facebook.thrift.client.ResponseWrapper;
import com.facebook.thrift.client.RpcOptions;
import com.facebook.thrift.util.Readers;

public class MyServiceReactiveClient
  implements MyService.Reactive {
  private static final AtomicLong _interactionCounter = new AtomicLong(0);

  protected final org.apache.thrift.ProtocolId _protocolId;
  protected final reactor.core.publisher.Mono<? extends com.facebook.thrift.client.RpcClient> _rpcClient;
  protected final Map<String, String> _headers;
  protected final Map<String, String> _persistentHeaders;
  protected final Set<Long> _activeInteractions;

  private static final TField _query_S_FIELD_DESC = new TField("s", TType.STRUCT, (short)1);
  private static final TField _query_I_FIELD_DESC = new TField("i", TType.STRUCT, (short)2);
  private static final java.util.Map<Short, com.facebook.thrift.payload.Reader> _query_EXCEPTION_READERS = java.util.Collections.emptyMap();
  private static final TField _hasArgDocs_S_FIELD_DESC = new TField("s", TType.STRUCT, (short)1);
  private static final TField _hasArgDocs_I_FIELD_DESC = new TField("i", TType.STRUCT, (short)2);
  private static final java.util.Map<Short, com.facebook.thrift.payload.Reader> _hasArgDocs_EXCEPTION_READERS = java.util.Collections.emptyMap();

  static {
  }

  public MyServiceReactiveClient(org.apache.thrift.ProtocolId _protocolId, reactor.core.publisher.Mono<? extends com.facebook.thrift.client.RpcClient> _rpcClient) {

    this._protocolId = _protocolId;
    this._rpcClient = _rpcClient;
    this._headers = java.util.Collections.emptyMap();
    this._persistentHeaders = java.util.Collections.emptyMap();
    this._activeInteractions = ConcurrentHashMap.newKeySet();
  }

  public MyServiceReactiveClient(org.apache.thrift.ProtocolId _protocolId, reactor.core.publisher.Mono<? extends com.facebook.thrift.client.RpcClient> _rpcClient, Map<String, String> _headers, Map<String, String> _persistentHeaders) {
    this(_protocolId, _rpcClient, _headers, _persistentHeaders, new AtomicLong(), ConcurrentHashMap.newKeySet());
  }

  public MyServiceReactiveClient(org.apache.thrift.ProtocolId _protocolId, reactor.core.publisher.Mono<? extends com.facebook.thrift.client.RpcClient> _rpcClient, Map<String, String> _headers, Map<String, String> _persistentHeaders, AtomicLong interactionCounter, Set<Long> activeInteractions) {

    this._protocolId = _protocolId;
    this._rpcClient = _rpcClient;
    this._headers = _headers;
    this._persistentHeaders = _persistentHeaders;
    this._activeInteractions = activeInteractions;
  }

  @java.lang.Override
  public void dispose() {}

  private com.facebook.thrift.payload.Writer _createqueryWriter(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i) {
    return oprot -> {
      try {
        {
          oprot.writeFieldBegin(_query_S_FIELD_DESC);

          test.fixtures.includes.MyStruct _iter0 = s;

          _iter0.write0(oprot);
          oprot.writeFieldEnd();
        }

        {
          oprot.writeFieldBegin(_query_I_FIELD_DESC);

          test.fixtures.includes.includes.Included _iter0 = i;

          _iter0.write0(oprot);
          oprot.writeFieldEnd();
        }

      } catch (Throwable _e) {
        com.facebook.thrift.util.NettyUtil.releaseIfByteBufTProtocol(oprot);
        throw reactor.core.Exceptions.propagate(_e);
      }
    };
  }

  private static final com.facebook.thrift.payload.Reader _query_READER = Readers.voidReader();

  @java.lang.Override
  public reactor.core.publisher.Mono<com.facebook.thrift.client.ResponseWrapper<Void>> queryWrapper(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i,  final com.facebook.thrift.client.RpcOptions rpcOptions) {
    return _rpcClient
      .flatMap(_rpc -> {
        org.apache.thrift.RequestRpcMetadata _metadata = new org.apache.thrift.RequestRpcMetadata.Builder()
                .setName("query")
                .setKind(org.apache.thrift.RpcKind.SINGLE_REQUEST_SINGLE_RESPONSE)
                .setOtherMetadata(getHeaders(rpcOptions))
                .setProtocol(_protocolId)
                .build();

            com.facebook.thrift.payload.ClientRequestPayload<Void> _crp =
                com.facebook.thrift.payload.ClientRequestPayload.create(
                    "MyService",
                    _createqueryWriter(s, i),
                    _query_READER,
                    _query_EXCEPTION_READERS,
                    _metadata,
                    java.util.Collections.emptyMap());

            return _rpc
                .singleRequestSingleResponse(_crp, rpcOptions).doOnNext(_p -> {if(_p.getException() != null) throw com.facebook.thrift.util.ExceptionUtil.propagate(_p);});
      });
  }

  @java.lang.Override
  public reactor.core.publisher.Mono<Void> query(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i,  final com.facebook.thrift.client.RpcOptions rpcOptions) {
    return queryWrapper(s, i,  rpcOptions).then();
  }

  @java.lang.Override
  public reactor.core.publisher.Mono<Void> query(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i) {
    return query(s, i,  com.facebook.thrift.client.RpcOptions.EMPTY);
  }

  private com.facebook.thrift.payload.Writer _createhasArgDocsWriter(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i) {
    return oprot -> {
      try {
        {
          oprot.writeFieldBegin(_hasArgDocs_S_FIELD_DESC);

          test.fixtures.includes.MyStruct _iter0 = s;

          _iter0.write0(oprot);
          oprot.writeFieldEnd();
        }

        {
          oprot.writeFieldBegin(_hasArgDocs_I_FIELD_DESC);

          test.fixtures.includes.includes.Included _iter0 = i;

          _iter0.write0(oprot);
          oprot.writeFieldEnd();
        }

      } catch (Throwable _e) {
        com.facebook.thrift.util.NettyUtil.releaseIfByteBufTProtocol(oprot);
        throw reactor.core.Exceptions.propagate(_e);
      }
    };
  }

  private static final com.facebook.thrift.payload.Reader _hasArgDocs_READER = Readers.voidReader();

  @java.lang.Override
  public reactor.core.publisher.Mono<com.facebook.thrift.client.ResponseWrapper<Void>> hasArgDocsWrapper(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i,  final com.facebook.thrift.client.RpcOptions rpcOptions) {
    return _rpcClient
      .flatMap(_rpc -> {
        org.apache.thrift.RequestRpcMetadata _metadata = new org.apache.thrift.RequestRpcMetadata.Builder()
                .setName("has_arg_docs")
                .setKind(org.apache.thrift.RpcKind.SINGLE_REQUEST_SINGLE_RESPONSE)
                .setOtherMetadata(getHeaders(rpcOptions))
                .setProtocol(_protocolId)
                .build();

            com.facebook.thrift.payload.ClientRequestPayload<Void> _crp =
                com.facebook.thrift.payload.ClientRequestPayload.create(
                    "MyService",
                    _createhasArgDocsWriter(s, i),
                    _hasArgDocs_READER,
                    _hasArgDocs_EXCEPTION_READERS,
                    _metadata,
                    java.util.Collections.emptyMap());

            return _rpc
                .singleRequestSingleResponse(_crp, rpcOptions).doOnNext(_p -> {if(_p.getException() != null) throw com.facebook.thrift.util.ExceptionUtil.propagate(_p);});
      });
  }

  @java.lang.Override
  public reactor.core.publisher.Mono<Void> hasArgDocs(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i,  final com.facebook.thrift.client.RpcOptions rpcOptions) {
    return hasArgDocsWrapper(s, i,  rpcOptions).then();
  }

  @java.lang.Override
  public reactor.core.publisher.Mono<Void> hasArgDocs(final test.fixtures.includes.MyStruct s, final test.fixtures.includes.includes.Included i) {
    return hasArgDocs(s, i,  com.facebook.thrift.client.RpcOptions.EMPTY);
  }

  private Map<String, String> getHeaders(com.facebook.thrift.client.RpcOptions rpcOptions) {
      Map<String, String> headers = new HashMap<>();
      if (rpcOptions.getRequestHeaders() != null && !rpcOptions.getRequestHeaders().isEmpty()) {
          headers.putAll(rpcOptions.getRequestHeaders());
      }
      if (_headers != null && !_headers.isEmpty()) {
          headers.putAll(_headers);
      }
      if (_persistentHeaders != null && !_persistentHeaders.isEmpty()) {
          headers.putAll(_persistentHeaders);
      }
      return headers;
  }
}


text:
function os::golang::verify_go_version() {
	os::util::ensure::system_binary_exists 'go'

	local go_version
	go_version=($(go version))
	if [[ "${go_version[2]}" != go1.6* ]]; then
		os::log::info "Detected go version: ${go_version[*]}."
		if [[ -z "${PERMISSIVE_GO:-}" ]]; then
			os::log::error "Please install Go version 1.6 or use PERMISSIVE_GO=y to bypass this check."
			return 1
		else
			os::log::warn "Detected golang version doesn't match preferred Go version for Origin."
			os::log::warn "This version mismatch could lead to differences in execution between this run and the Origin CI systems."
			return 0
		fi
	fi
}
readonly -f os::golang::verify_go_version

redpajama_set_name: RedPajamaGithub


text:
In the functional API, given some input tensor(s) and output tensor(s), you can instantiate a `Model` via:

```python
from keras.models import Model
from keras.layers import Input, Dense

a = Input(shape=(32,))
b = Dense(32)(a)
model = Model(inputs=a, outputs=b)
```

This model will include all layers required in the computation of `b` given `a`.

In the case of multi-input or multi-output models, you can use lists as well:

```python
model = Model(inputs=[a1, a2], outputs=[b1, b3, b3])
```

For a detailed introduction of what `Model` can do, read [this guide to the Keras functional API](/getting-started/functional-api-guide).

## Useful attributes of Model

- `model.layers` is a flattened list of the layers comprising the model graph.
- `model.inputs` is the list of input tensors.
- `model.outputs` is the list of output tensors.

## Methods

{{autogenerated}}


text:
from google.analytics import admin_v1alpha

def sample_delete_google_ads_link():
    # Create a client
    client = admin_v1alpha.AnalyticsAdminServiceClient()

    # Initialize request argument(s)
    request = admin_v1alpha.DeleteGoogleAdsLinkRequest(
        name="name_value",
    )

    # Make the request
    client.delete_google_ads_link(request=request)

# [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteGoogleAdsLink_sync]


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Taxon 32(4): 575 (1983)

#### Original name
Hysterium foliicola Fr., 1823

### Remarks
null


text:
#pragma once

typedef struct _OVS_SWITCH_INFO OVS_SWITCH_INFO;

NET_BUFFER_LIST* CloneNblFragment(_In_ const OVS_SWITCH_INFO* pSwitchInfo, _In_ NET_BUFFER_LIST* pNbl, _In_ ULONG maxNbLength);
NET_BUFFER_LIST* CloneNblNormal(_In_ const OVS_SWITCH_INFO* pSwitchInfo, _In_ NET_BUFFER_LIST* pNbl);
NET_BUFFER_LIST* DuplicateNbl(_In_ const OVS_SWITCH_INFO* pSwitchInfo, _In_ NET_BUFFER_LIST* pNbl);
VOID FreeDuplicateNbl(_In_ const OVS_SWITCH_INFO* pSwitchInfo, _In_ NET_BUFFER_LIST* pNbl);

VOID* ReadNb_Alloc(_In_ NET_BUFFER* net_buffer);
VOID* GetNbBufferData(_In_ NET_BUFFER* pNb, _Out_ void** pAllocBuffer);
VOID* GetNbBufferData_OfSize(_In_ NET_BUFFER* pNb, ULONG size, _Out_ void** pAllocBuffer);

VOID FreeClonedNblFragment(_In_ NET_BUFFER_LIST* pNbl, _In_ ULONG dataOffsetDelta);
VOID FreeClonedNblNormal(_In_ NET_BUFFER_LIST* pNbl);

ULONG CountNbs(_In_ NET_BUFFER_LIST* pNbl);
ULONG CountNbls(_In_ NET_BUFFER_LIST* pNbl);

BOOLEAN VerifyNetBuffer(VOID* buffer, ULONG length);
BOOLEAN VerifyProtocolHeader(BYTE* buffer, ULONG* pLength, UINT16* pEthType);

NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO* GetChecksumOffloadInfo(_In_ NET_BUFFER_LIST* pNbl);

VOID DbgPrintNblInfo(NET_BUFFER_LIST* pNbl);

#ifdef DBG
VOID DbgPrintMdl(MDL* pMdl);
VOID DbgPrintNb(NET_BUFFER* pNb, LPCSTR msg);
VOID DbgPrintNbl(NET_BUFFER_LIST* pNbl, LPCSTR msg);
VOID DbgPrintNblList(NET_BUFFER_LIST* pNbl);
VOID DbgPrintNblCount(NET_BUFFER_LIST* pNbl);
VOID DbgPrintNbCount(NET_BUFFER_LIST* pNbl);

#else
#define DbgPrintMdl(pMdl)
#define DbgPrintNb(pNb, msg)
#define DbgPrintNbl(pNbl, msg)
#define DbgPrintNblList(pNbl)
#define DbgPrintNblCount(pNbl)
#define DbgPrintNbCount(pNbl)
#endif


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddThreadsColumnToServersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('servers', function (Blueprint $table) {
            $table->string('threads')->nullable()->after('cpu');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('servers', function (Blueprint $table) {
            $table->dropColumn('threads');
        });
    }
}


text:
export interface AssetTypeInterface {
    readonly id: string;
    readonly projectId: string;
    readonly description: string;
    readonly createdAt: string;
    readonly updatedAt: string;
}


text:
package org.kie.server.services.taskassigning.planning.data;

import java.util.Map;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public abstract class AbstractAttributeMapValueLabelValueExtractorTest<M extends Map<String, ?>, T, E extends AbstractAttributeMapValueLabelValueExtractor<M, T>>
        extends AbstractLabelValueExtractorTest<T, E> {

    protected abstract String getExpectedAttributeName();

    @Test
    public void getAttributeName() {
        assertThat(valueExtractor.getAttributeName()).isEqualTo(getExpectedAttributeName());
    }
}


text:
Contributions are welcome. If you discover bugs or issues, or have ideas for
improvements or new features, please file a report on the issue tracker for this
repository. Follow the guidelines below to make sure everything goes smoothly.

## Issue reporting

- Check that the issue has not already been reported
- Check that the issue has not already been fixed in the latest code
- Open an issue with a clear title
- Write as grammatically correct as you can in the description.

## Pull requests

- Perform all changes on a topic branch for easier merging
- Follow the coding conventions already in use
- Add unit tests whenever possible
- Open a [pull request](https://help.github.com/articles/using-pull-requests)
  relating to a single issue.


text:
FROM sp_platform/spi_nodejs
RUN mkdir -p /proxy
ADD sp_proxy/ /proxy
WORKDIR /proxy
RUN /spaas/nodejs/bin/npm install
EXPOSE 8888
ENV SP_REGISTRY_HOST 172.17.0.5
ENTRYPOINT /spaas/nodejs/bin/node app.js


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Debugger - pyspider</title>

    <meta name="description" content="pyspider - debugger">
    <meta name="author" content="binux">

    <link href="{{ url_for('cdn', path='codemirror/3.22.0/codemirror.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('cdn', path='font-awesome/4.0.3/css/font-awesome.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('cdn', path='codemirror/3.22.0/addon/dialog/dialog.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('static', filename='debug.css') }}" rel="stylesheet">

pyspider > {{ project_name }}

        Quickstart

run

               < |>

              {#

                __callback__ > __url__

 #}

messages

follows

html

web

enable css selector helper

save


text:
<?php
require dirname(__FILE__) . '/../lib/bootstrap.php';
return Phortress\Cli::run();


text:
"""
Module for handling HDF5 data within qcodes.
Based on hdf5 datawrapper from qtlab originally by Reinier Heeres and
Wolfgang Pfaff.

Contains:
- a data class (HDF5Data) which is essentially a wrapper of a h5py data
  object, adapted for usage with qcodes
- name generators in the style of qtlab Data objects
- functions to create standard data sets
"""

import os
import time
import h5py
import numpy as np
import logging
from uncertainties import UFloat

# from pycqed.utilities.general import RepresentsInt

log = logging.getLogger(__name__)

class DateTimeGenerator:
    """
    Class to generate filenames / directories based on the date and time.
    """

    def __init__(self):
        pass

    def create_data_dir(
        self,
        datadir: str,
        name: str = None,
        ts=None,
        datesubdir: bool = True,
        timesubdir: bool = True,
    ):
        """
        Create and return a new data directory.

        Input:
            datadir (string): base directory
            name (string): optional name of measurement
            ts (time.localtime()): timestamp which will be used
                if timesubdir=True
            datesubdir (bool): whether to create a subdirectory for the date
            timesubdir (bool): whether to create a subdirectory for the time

        Output:
            The directory to place the new file in
        """

        path = datadir
        if ts is None:
            ts = time.localtime()
        if datesubdir:
            path = os.path.join(path, time.strftime("%Y%m%d", ts))
        if timesubdir:
            tsd = time.strftime("%H%M%S", ts)
            timestamp_verified = False
            counter = 0
            # Verify if timestamp is unique by seeing if the folder exists
            while not timestamp_verified:
                counter += 1
                try:
                    measdirs = [d for d in os.listdir(path) if d[:6] == tsd]
                    if len(measdirs) == 0:
                        timestamp_verified = True
                    else:
                        # if timestamp not unique, add one second
                        # This is quite a hack
                        ts = time.localtime((time.mktime(ts) + 1))
                        tsd = time.strftime("%H%M%S", ts)
                    if counter >= 3600:
                        raise Exception()
                except OSError as err:
                    if "cannot find the path specified" in str(err):
                        timestamp_verified = True
                    elif "No such file or directory" in str(err):
                        timestamp_verified = True
                    else:
                        raise err
            if name is not None:
                path = os.path.join(path, tsd + "_" + name)
            else:
                path = os.path.join(path, tsd)

        return path, tsd

    def new_filename(self, data_obj, folder):
        """Return a new filename, based on name and timestamp."""
        path, tstr = self.create_data_dir(
            folder, name=data_obj._name, ts=data_obj._localtime
        )
        filename = "%s_%s.hdf5" % (tstr, data_obj._name)
        return os.path.join(path, filename)

class Data(h5py.File):
    def __init__(self, name: str, datadir: str):
        """
        Creates an empty data set including the file, for which the currently
        set file name generator is used.

        kwargs:
            name (string) : base name of the file
            datadir (string) : A folder will be created within the datadir
                using the standard timestamp structure
        """
        self._name = name

        self._localtime = time.localtime()
        self._timestamp = time.asctime(self._localtime)
        self._timemark = time.strftime("%H%M%S", self._localtime)
        self._datemark = time.strftime("%Y%m%d", self._localtime)

        self.filepath = DateTimeGenerator().new_filename(self, folder=datadir)

        self.filepath = self.filepath.replace("%timemark", self._timemark)

        self.folder, self._filename = os.path.split(self.filepath)
        if not os.path.isdir(self.folder):
            os.makedirs(self.folder)
        super(Data, self).__init__(self.filepath, "a")
        self.flush()

def encode_to_utf8(s):
    """
    Required because h5py does not support python3 strings
    """
    # converts byte type to string because of h5py datasaving
    if isinstance(s, str):
        s = s.encode("utf-8")
    # If it is an array of value decodes individual entries
    elif isinstance(s, (np.ndarray, list, tuple)):
        s = [s.encode("utf-8") for s in s]
    return s

def write_dict_to_hdf5(
    data_dict: dict, entry_point, group_overwrite_level: int = np.inf
):
    """
    Args:
        data_dict (dict): dictionary to write to hdf5 file
        entry_point (hdf5 group.file) : location in the nested hdf5 structure
            where to write to.
    """
    for key, item in data_dict.items():
        # Basic types
        if isinstance(
            item, (str, float, int, bool, np.number, np.float_, np.int_, np.bool_)
        ):
            try:
                entry_point.attrs[key] = item
            except Exception as e:
                print(
                    "Exception occurred while writing"
                    " {}:{} of type {} at entry point {}".format(
                        key, item, type(item), entry_point
                    )
                )
                log.warning(e)
        elif isinstance(item, np.ndarray):
            entry_point.create_dataset(key, data=item)
        elif item is None:
            # as h5py does not support saving None as attribute
            # I create special string, note that this can create
            # unexpected behaviour if someone saves a string with this name
            entry_point.attrs[key] = "NoneType:__None__"

        elif isinstance(item, dict):
            # converting key to string is to make int dictionary keys work
            str_key = str(key)
            if str_key not in entry_point.keys():
                entry_point.create_group(str_key)
            elif group_overwrite_level < 1:
                log.debug("Overwriting hdf5 group: {}".format(str_key))
                del entry_point[str_key]
                entry_point.create_group(str_key)

            write_dict_to_hdf5(
                data_dict=item,
                entry_point=entry_point[str_key],
                group_overwrite_level=group_overwrite_level - 1,
            )

        elif isinstance(item, UFloat):
            str_key = str(key)
            if str_key not in entry_point.keys():
                entry_point.create_group(str_key)
            elif group_overwrite_level < 1:
                log.debug("Overwriting hdf5 group: {}".format(str_key))
                del entry_point[str_key]
                entry_point.create_group(str_key)

            new_item = {"nominal_value": item.nominal_value, "std_dev": item.std_dev}
            write_dict_to_hdf5(
                data_dict=new_item,
                entry_point=entry_point[str_key],
                group_overwrite_level=group_overwrite_level - 1,
            )

        elif isinstance(item, (list, tuple)):
            if len(item) > 0:
                elt_type = type(item[0])
                # Lists of a single type, are stored as an hdf5 dset
                if (
                    all(isinstance(x, elt_type) for x in item)
                    and not isinstance(item[0], dict)
                    and not isinstance(item, tuple)
                ):
                    if isinstance(item[0], (int, float, np.int32, np.int64)):
                        entry_point.create_dataset(key, data=np.array(item))
                        entry_point[key].attrs["list_type"] = "array"

                    # strings are saved as a special dtype hdf5 dataset
                    elif isinstance(item[0], str):
                        dt = h5py.special_dtype(vlen=str)
                        data = np.array(item)
                        data = data.reshape((-1, 1))
                        ds = entry_point.create_dataset(key, (len(data), 1), dtype=dt)
                        ds.attrs["list_type"] = "str"
                        ds[:] = data
                    else:
                        # For nested list we don't throw warning, it will be
                        # recovered in case of a snapshot
                        warn_msg = (
                            'List of type "{}" for "{}":"{}" not '
                            "supported, storing as string".format(elt_type, key, item)
                        )
                        if elt_type is list:
                            log.debug(warn_msg)
                        else:
                            log.warning(warn_msg)

                        entry_point.attrs[key] = str(item)
                # Storing of generic lists/tuples
                else:
                    if key not in entry_point.keys():
                        entry_point.create_group(key)
                    elif group_overwrite_level < 1:
                        log.debug("Overwriting hdf5 group: {}".format(key))
                        del entry_point[key]
                        entry_point.create_group(key)

                    # N.B. item is of type list
                    list_dct = {
                        "list_idx_{}".format(idx): entry
                        for idx, entry in enumerate(item)
                    }
                    group_attrs = entry_point[key].attrs
                    if isinstance(item, tuple):
                        group_attrs["list_type"] = "generic_tuple"
                    else:
                        group_attrs["list_type"] = "generic_list"
                    group_attrs["list_length"] = len(item)
                    write_dict_to_hdf5(
                        data_dict=list_dct,
                        entry_point=entry_point[key],
                        group_overwrite_level=group_overwrite_level - 1,
                    )
            else:
                # as h5py does not support saving None as attribute
                entry_point.attrs[key] = "NoneType:__emptylist__"

        else:
            log.warning(
                'Type "{}" for "{}" (key): "{}" (item) at location {} '
                "not supported, "
                "storing as string".format(type(item), key, item, entry_point)
            )
            entry_point.attrs[key] = str(item)

def read_dict_from_hdf5(data_dict: dict, h5_group):
    """
    Reads a dictionary from an hdf5 file or group that was written using the
    corresponding "write_dict_to_hdf5" function defined above.

    Args:
        data_dict (dict):
                dictionary to which to add entries being read out.
                This argument exists because it allows nested calls of this
                function to add the data to an existing data_dict.
        h5_group  (hdf5 group):
                hdf5 file or group from which to read.
    """
    # if 'list_type' not in h5_group.attrs:
    for key, item in h5_group.items():
        if RepresentsInt(key):
            key = int(key)
        if isinstance(item, h5py.Group):
            data_dict[key] = {}
            data_dict[key] = read_dict_from_hdf5(data_dict[key], item)
        else:  # item either a group or a dataset
            if "list_type" not in item.attrs:
                data_dict[key] = item[()]  # changed deprecated item.value => item[()]
            elif item.attrs["list_type"] == "str":
                # lists of strings needs some special care, see also
                # the writing part in the writing function above.
                list_of_str = [
                    x[0] for x in item[()]
                ]  # changed deprecated item.value => item[()]
                data_dict[key] = list_of_str
            elif item.attrs["list_type"] == "array":
                data_dict[key] = list(
                    item[()]
                )  # changed deprecated item.value => item[()]
            else:
                data_dict[key] = list(
                    item[()]
                )  # changed deprecated item.value => item[()]
    for key, item in h5_group.attrs.items():
        if isinstance(item, str):
            # Extracts "None" as an exception as h5py does not support
            # storing None, nested if statement to avoid elementwise
            # comparison warning
            if item == "NoneType:__None__":
                item = None
            elif item == "NoneType:__emptylist__":
                item = []
        data_dict[key] = item

    if "list_type" in h5_group.attrs:
        if (
            h5_group.attrs["list_type"] == "generic_list"
            or h5_group.attrs["list_type"] == "generic_tuple"
        ):
            list_dict = data_dict
            data_list = []
            for i in range(list_dict["list_length"]):
                data_list.append(list_dict["list_idx_{}".format(i)])

            if h5_group.attrs["list_type"] == "generic_tuple":
                return tuple(data_list)
            else:
                return data_list
        else:
            raise NotImplementedError(
                'cannot read "list_type":"{}"'.format(h5_group.attrs["list_type"])
            )
    return data_dict

def extract_pars_from_datafile(filepath: str, param_spec: dict) -> dict:
    """
    Extract parameters from an hdf5 datafile.

    Args:
        filepath (str)
            tilepath of the hfd5 datafile.

        param_spec (dict)
            specification of parameters to extract.
                key: name used to store the extracted entry
                value: tuple consiting of "/" separated parameter path
                    and attribute/dataset specificiation.
                    The attribute/dataset specification is
                    "attr:attribute_name", "dset", "attr:all_attr", or "group"
                    "group" allows to recursively extract all the tree in
                    the group

            example param_spec
                param_spec = {
                    'T1': ('Analysis/Fitted Params F|1>/tau', 'attr:value'),
                    'uT1': ('Analysis/Fitted Params F|1>/tau', 'attr:stderr'),
                    'data': ('Experimental Data/Data', 'dset'),
                    'timestamp': ('MC settings/begintime', 'dset'),
                    'qois': ('Analysis/quantities_of_interest', 'group')}
        convert_str_arrays (bool):
            allows to automatically make the string array usable in python
            e.g. extracting the `value_names` of a measurement

    Return:
        param_dict (dict)
            dictionary containing the extracted parameters.
    """
    param_dict = {}
    f = h5py.File(filepath, "r")
    with h5py.File(filepath, "r") as f:
        for par_name, par_spec in param_spec.items():
            entry = f[par_spec[0]]
            if par_spec[1].startswith("dset"):
                param_dict[par_name] = entry[()]  # deprecated syntax: entry.value
            elif par_spec[1].startswith("attr:all_attr"):
                param_dict[par_name] = dict()
                for attribute_name in entry.attrs.keys():
                    param_dict[par_name][attribute_name] = entry.attrs[attribute_name]
            elif par_spec[1].startswith("attr"):
                param_dict[par_name] = entry.attrs[par_spec[1][5:]]
            elif par_spec[1].startswith("group"):
                # This should allow to retrieve the entire tree under a certain
                # as a dictionary
                new_dict = dict()
                param_dict[par_name] = read_dict_from_hdf5(new_dict, h5_group=entry)
            else:
                raise ValueError(
                    "Parameter spec `{}` not recognized".format(par_spec[1])
                )

    return param_dict

def RepresentsInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


text:
package com.intellij.ui;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.function.Consumer;

public interface JBAccountInfoService {

  final class JBAData {
    @NotNull
    public final String id;
    @Nullable
    public final String loginName;
    @Nullable
    public final String email;

    public JBAData(@NotNull String userId, @Nullable String loginName, @Nullable String email) {
      this.id = userId;
      this.loginName = loginName;
      this.email = email;
    }
  }

  @Nullable
  JBAccountInfoService.JBAData getUserData();

  void invokeJBALogin(@Nullable Consumer<String> userIdConsumer, @Nullable Runnable onFailure);

  @Nullable
  static JBAccountInfoService getInstance() {
    try {
      return ServiceLoader.load(JBAccountInfoService.class).findFirst().orElse(null);
    }
    catch (ServiceConfigurationError ignored) {
      return null;
    }
  }
}


text:
<?php
require_once("HTML/QuickForm/input.php");
/**
*For this class to work, prototype and scriptaculous (see http://script.aculo.us) must be included.
*in blueCMS, call to method getJsIncludes() will return
*
*
*
*
*
*Your setup may vary...
*/
class HTML_QuickForm_Sorter extends HTML_QuickForm_input
{
     var $_html = '';
    /**
    * Class constructor
    *
    * @param     string    $elementName    (optional)Input field name attribute
    * @param     string    $elementLabel   (optional)Input field label
    * @param     mixed     $attributes       (optional) array
    * @return    void
    */
    function HTML_QuickForm_Sorter($elementName=null, $elementLabel=null, $attributes=null)
    {
        HTML_QuickForm_input::HTML_QuickForm_input($elementName, $elementLabel, $attributes);
        $this->_persistantFreeze = true;
    }
    function getJsIncludes($dir = '')
    {
        if(empty($dir))
            $dir = BLUECMS_WEBROOT . 'bluecms/jsapps/scriptaculous/';
        $js='

        ';
        return($js);
    }
    function toHTML()
    {
        return($this->_html);
    }

    /**
    *Function called by quickform.
    *$values is array of form (key1=>value1, key2=>value2...) where keyX is integer and array reflects current order
    */
    function setValue($values)
    {
        if(is_array($values))
        {
            if(! defined('HTML_QUICKFORM_SORTER_JS'))
            {
                define('HTML_QUICKFORM_SORTER_JS', true);
                $js =<<<JS

JS;
            $this->_html .= $js;
        }
        $html = &$this->_html;
        $name = $this->_attributes['name'];
        $this->_html .= '<input type="hidden" name="' . $name . '" value="' . implode(",",array_keys($values)) . '">';
        $this->_html .= '
\n";
        foreach($values as $k => $v)
        {
            $this->_html .= '
' . $v . "
\n";
        }
        $this->_html .="
\n";
        $this->_html .= '';

        }
    }
}
?>


text:
package capnslog

import (
	"errors"
	"strings"
	"sync"
)

// LogLevel is the set of all log levels.
type LogLevel int8

const (
	// CRITICAL is the lowest log level; only errors which will end the program will be propagated.
	CRITICAL LogLevel = -1
	// ERROR is for errors that are not fatal but lead to troubling behavior.
	ERROR = 0
	// WARNING is for errors which are not fatal and not errors, but are unusual. Often sourced from misconfigurations.
	WARNING = 1
	// NOTICE is for normal but significant conditions.
	NOTICE = 2
	// INFO is a log level for common, everyday log updates.
	INFO = 3
	// DEBUG is the default hidden level for more verbose updates about internal processes.
	DEBUG = 4
	// TRACE is for (potentially) call by call tracing of programs.
	TRACE = 5
)

// Char returns a single-character representation of the log level.
func (l LogLevel) Char() string {
	switch l {
	case CRITICAL:
		return "C"
	case ERROR:
		return "E"
	case WARNING:
		return "W"
	case NOTICE:
		return "N"
	case INFO:
		return "I"
	case DEBUG:
		return "D"
	case TRACE:
		return "T"
	default:
		panic("Unhandled loglevel")
	}
}

// ParseLevel translates some potential loglevel strings into their corresponding levels.
func ParseLevel(s string) (LogLevel, error) {
	switch s {
	case "CRITICAL", "C":
		return CRITICAL, nil
	case "ERROR", "0", "E":
		return ERROR, nil
	case "WARNING", "1", "W":
		return WARNING, nil
	case "NOTICE", "2", "N":
		return NOTICE, nil
	case "INFO", "3", "I":
		return INFO, nil
	case "DEBUG", "4", "D":
		return DEBUG, nil
	case "TRACE", "5", "T":
		return TRACE, nil
	}
	return CRITICAL, errors.New("couldn't parse log level " + s)
}

type RepoLogger map[string]*PackageLogger

// LogEntry is the generic interface for things which can be logged.
// Implementing the single method LogString() on your objects allows you to
// format them for logs/debugging as necessary.
type LogEntry interface {
	LogString() string
}

type loggerStruct struct {
	sync.Mutex
	repoMap   map[string]RepoLogger
	formatter Formatter
}

// logger is the global logger
var logger = new(loggerStruct)

// SetGlobalLogLevel sets the log level for all packages in all repositories
// registered with capnslog.
func SetGlobalLogLevel(l LogLevel) {
	logger.Lock()
	defer logger.Unlock()
	for _, r := range logger.repoMap {
		r.setRepoLogLevelInternal(l)
	}
}

// GetRepoLogger may return the handle to the repository's set of packages' loggers.
func GetRepoLogger(repo string) (RepoLogger, error) {
	logger.Lock()
	defer logger.Unlock()
	r, ok := logger.repoMap[repo]
	if !ok {
		return nil, errors.New("no packages registered for repo " + repo)
	}
	return r, nil
}

// MustRepoLogger returns the handle to the repository's packages' loggers.
func MustRepoLogger(repo string) RepoLogger {
	r, err := GetRepoLogger(repo)
	if err != nil {
		panic(err)
	}
	return r
}

// SetRepoLogLevel sets the log level for all packages in the repository.
func (r RepoLogger) SetRepoLogLevel(l LogLevel) {
	logger.Lock()
	defer logger.Unlock()
	r.setRepoLogLevelInternal(l)
}

func (r RepoLogger) setRepoLogLevelInternal(l LogLevel) {
	for _, v := range r {
		v.level = l
	}
}

// ParseLogLevelConfig parses a comma-separated string of "package=loglevel", in
// order, and returns a map of the results, for use in SetLogLevel.
func (r RepoLogger) ParseLogLevelConfig(conf string) (map[string]LogLevel, error) {
	setlist := strings.Split(conf, ",")
	out := make(map[string]LogLevel)
	for _, setstring := range setlist {
		setting := strings.Split(setstring, "=")
		if len(setting) != 2 {
			return nil, errors.New("oddly structured `pkg=level` option: " + setstring)
		}
		l, err := ParseLevel(setting[1])
		if err != nil {
			return nil, err
		}
		out[setting[0]] = l
	}
	return out, nil
}

// SetLogLevel takes a map of package names within a repository to their desired
// loglevel, and sets the levels appropriately. Unknown packages are ignored.
// "*" is a special package name that corresponds to all packages, and will be
// processed first.
func (r RepoLogger) SetLogLevel(m map[string]LogLevel) {
	logger.Lock()
	defer logger.Unlock()
	if l, ok := m["*"]; ok {
		r.setRepoLogLevelInternal(l)
	}
	for k, v := range m {
		l, ok := r[k]
		if !ok {
			continue
		}
		l.level = v
	}
}

// SetFormatter sets the formatting function for all logs.
func SetFormatter(f Formatter) {
	logger.Lock()
	defer logger.Unlock()
	logger.formatter = f
}

// NewPackageLogger creates a package logger object.
// This should be defined as a global var in your package, referencing your repo.
func NewPackageLogger(repo string, pkg string) (p *PackageLogger) {
	logger.Lock()
	defer logger.Unlock()
	if logger.repoMap == nil {
		logger.repoMap = make(map[string]RepoLogger)
	}
	r, rok := logger.repoMap[repo]
	if !rok {
		logger.repoMap[repo] = make(RepoLogger)
		r = logger.repoMap[repo]
	}
	p, pok := r[pkg]
	if !pok {
		r[pkg] = &PackageLogger{
			pkg:   pkg,
			level: INFO,
		}
		p = r[pkg]
	}
	return
}

type BaseLogEntry string

func (b BaseLogEntry) LogString() string {
	return string(b)
}


text:
/**
	_moon.ContextualPopupDecorator_ is a control that activates a
	[moon.ContextualPopup](#moon.ContextualPopup). It loosely couples the popup
	with an activating control, which may be a button or any other control that
	fires an _onActivate_ event. The decorator surrounds both the activating
	control and the contextual popup.

	When the control is activated, the popup shows itself in the correct position
	relative to the activator.

		{kind: "moon.ContextualPopupDecorator", components: [
			{content: "Show Popup"},
			{kind: "moon.ContextualPopup",
				components: [
					{content:"Sample component in popup"}
				]
			}
		]}
*/
enyo.kind({
	name: "moon.ContextualPopupDecorator",
	//* @protected
	defaultKind: "moon.ContextualPopupButton",
	// selection on ios prevents tap events, so avoid.
	classes: "moon-contextual-popup-decorator",
	handlers: {
		onActivate: "activated",
		onHide: "popupHidden"
	},
	activated: function(inSender, inEvent) {
		// Don't process activate events that came from inside this decorator
		if (inEvent.sentFromPopup && inEvent.sentFromPopup.isDescendantOf(this)) {
			return;
		}

		this.requestHidePopup();
		if (inEvent.originator.active) {
			this.popupActive = true;
			this.activator = inEvent.originator;
			this.activator.addClass("active");
			this.requestShowPopup();
		}
	},
	popupHidden: function() {
		this.popupActive = false;
		if (this.activator) {
			this.activator.setActive(false);
			this.activator.removeClass("active");
			this.activator.removeClass("pressed");
		}
	},
	requestShowPopup: function() {
		this.waterfallDown("onRequestShowPopup", {activator: this.activator});
	},
	requestHidePopup: function() {
		this.waterfallDown("onRequestHidePopup");
	}
});


text:
grunt-styleguide

0.1.0

lazy styleguide

test/fixtures/_imported.scss

test/fixtures/compile.scss

Button

Your standard form button.

:hover
is-hover
Highlights when hovering.

:disabled
is-disabled
Dims the button when disabled.

.primary
primary
Indicates button is the primary action.

.smaller
smaller
A smaller button

			<button>This is a button</button>

			<button>This is a button</button>


text:
package nl.cwi.pr.runtime.examples.thesis.chess;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import nl.cwi.pr.runtime.api.InputPort;
import nl.cwi.pr.runtime.api.OutputPort;

public class Engine {
	private final InputPort inputPort;
	private final OutputPort outputPort;
	private final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
	private final BufferedReader reader;
	private final BufferedWriter writer;
	private final int moveTime = new Random().nextInt(3000);

	public Engine(InputPort inputPort, OutputPort outputPort) {
		this.inputPort = inputPort;
		this.outputPort = outputPort;

		String os = System.getProperty("os.name").toLowerCase();
		final String stockfish;
		if (os.contains("win"))
			stockfish = "stockfish-6-win-32.exe";
		else if (os.contains("mac"))
			stockfish = "stockfish-6-osx-64";
		else
			stockfish = "stockfish-6-linux-64";

		String path = "src/main/java"
				+ File.separator
				+ getClass().getPackage().getName()
						.replace('.', File.separatorChar) + File.separator
				+ stockfish;

		Process process = null;
		try {
			process = Runtime.getRuntime().exec(path);
			System.out.println("Running " + path + "...");
		} catch (IOException e) {
			System.out.println("Failed to run " + path);
			e.printStackTrace();
			throw new Error();
		}

		this.reader = new BufferedReader(new InputStreamReader(
				process.getInputStream()));
		this.writer = new BufferedWriter(new OutputStreamWriter(
				process.getOutputStream()));

		new Thread() {
			@Override
			public void run() {
				String line;
				StringBuilder builder = new StringBuilder();

				try {
					while ((line = reader.readLine()) != null) {
						builder.append(line + "\n");

						if (line.startsWith("uciok")
								|| line.startsWith("bestmove")) {

							queue.put(builder.toString());
							builder = new StringBuilder();
						}
					}
				}

				catch (IOException | InterruptedException e) {
					e.printStackTrace();
					throw new Error();
				}
			}
		}.start();

		try {
			writer.write("uci\n");
			writer.flush();
			queue.take();
		}

		catch (IOException | InterruptedException e) {
			e.printStackTrace();
			throw new Error();
		}
	}

	public void run() {
		while (true) {
			String moves = (String) inputPort.getUninterruptibly();
			String result = "";

			try {
				writer.write("ucinewgame\n");
				writer.write("position startpos moves " + moves + "\n");
				writer.write("go movetime " + moveTime + "\n");
				writer.flush();
				result = queue.take();
			}

			catch (IOException | InterruptedException e) {
				e.printStackTrace();
				throw new Error();
			}

			outputPort.putUninterruptibly(result);
		}

	}
}


text:
import Workload from 'ui/models/workload';

const ReplicationController = Workload.extend({
});

export default ReplicationController;


text:
package org.samovich.technologies.basics.collections.interfaces.map;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author Valery Samovich
 * @see
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Description {
    private int id;
    private String description;
}


text:
package com.helger.photon.security.object.tenant;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.time.Clock;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;

import com.helger.dao.DAOException;
import com.helger.photon.app.mock.PhotonAppWebTestRule;
import com.helger.photon.security.CSecurity;
import com.helger.photon.security.login.ELoginResult;
import com.helger.photon.security.login.LoggedInUserManager;
import com.helger.photon.security.mgr.PhotonSecurityManager;
import com.helger.tenancy.tenant.ITenant;

/**
 * Test class for class {@link TenantManager}
 *
 * @author Philip Helger
 */
public final class TenantManagerTest
{
  @Rule
  public final TestRule m_aRule = new PhotonAppWebTestRule ();

  @Test
  public void testAny () throws DAOException
  {
    PhotonSecurityManager.getUserMgr ().createDefaultsForTest ();

    final TenantManager aMgr = new TenantManager ("dummy-tenant.xml");

    // Login required for deletion
    final LoggedInUserManager aLUM = LoggedInUserManager.getInstance ();
    assertEquals (ELoginResult.SUCCESS, aLUM.loginUser (CSecurity.USER_ADMINISTRATOR_LOGIN, CSecurity.USER_ADMINISTRATOR_PASSWORD));
    try
    {
      final String sTenantID = Long.toString (Clock.systemUTC ().millis ());
      final ITenant aTenant = aMgr.createTenant (sTenantID, "Name1");
      assertNotNull (aTenant);
      try
      {
        assertNull (aMgr.createTenant (sTenantID, "Was anderes"));
      }
      finally
      {
        aMgr.deleteTenant (sTenantID);
      }
    }
    finally
    {
      aLUM.logoutCurrentUser ();
    }
  }
}


text:
layout: post
title: Shopping Cart
category: [Short Stories]
---

Found on the web

> The shopping cart is the ultimate litmus test for whether a person is capable of self-governing.
>
> To return the shopping cart is an easy, convenient task and one which we all recognize as the correct , appropriate thing to do. To return the shopping cart is objectively right. There are no situations other than dire emergencies in which a person is not able to return their cart. Simultaneously, it is not illegal to abandon your shopping cart. Therefore the shopping cart presents itself as the apex example of whether a person will do what is right without being forced to do it. No one will punish you for not returning the shopping cart, no one will fine you or kill you for not returning the shopping cart. You must return the shopping cart out of the goodness of your own heart. You must return the shopping cart because it is the right thing to do. Because it is correct.
>
> A person who is unable to do this is no better than an animal, an absolute savage who can only be made to do what is right by threatening them with a law and the force that stands behind it.
>
> The Shopping Cart is what determines whether a person is a good or bad member of society.


text:
"""
Common utilities for OpenStack
"""
import sys
import binascii
import os
import datetime

from libcloud.utils.py3 import httplib
from libcloud.utils.iso8601 import parse_date

from libcloud.common.base import ConnectionUserAndKey, Response
from libcloud.compute.types import (LibcloudError, InvalidCredsError,
                                    MalformedResponseError)

try:
    import simplejson as json
except ImportError:
    import json

AUTH_API_VERSION = '1.1'

# Auth versions which contain token expiration information.
AUTH_VERSIONS_WITH_EXPIRES = [
    '1.1',
    '2.0',
    '2.0_apikey',
    '2.0_password'
]

# How many seconds to substract from the auth token expiration time before
# testing if the token is still valid.
# The time is subtracted to account for the HTTP request latency and prevent
# user from getting "InvalidCredsError" if token is about to expire.
AUTH_TOKEN_EXPIRES_GRACE_SECONDS = 5

__all__ = [
    'OpenStackBaseConnection',
    'OpenStackAuthConnection',
    'OpenStackServiceCatalog',
    'OpenStackDriverMixin',
    "OpenStackBaseConnection",
    "OpenStackAuthConnection",

    'AUTH_TOKEN_EXPIRES_GRACE_SECONDS'
]

# @TODO: Refactor for re-use by other openstack drivers
class OpenStackAuthResponse(Response):
    def success(self):
        return True

    def parse_body(self):
        if not self.body:
            return None

        if 'content-type' in self.headers:
            key = 'content-type'
        elif 'Content-Type' in self.headers:
            key = 'Content-Type'
        else:
            raise LibcloudError('Missing content-type header',
                                driver=OpenStackAuthConnection)

        content_type = self.headers[key]
        if content_type.find(';') != -1:
            content_type = content_type.split(';')[0]

        if content_type == 'application/json':
            try:
                data = json.loads(self.body)
            except:
                raise MalformedResponseError('Failed to parse JSON',
                                             body=self.body,
                                             driver=OpenStackAuthConnection)
        elif content_type == 'text/plain':
            data = self.body
        else:
            data = self.body

        return data

class OpenStackAuthConnection(ConnectionUserAndKey):

    responseCls = OpenStackAuthResponse
    name = 'OpenStack Auth'
    timeout = None

    def __init__(self, parent_conn, auth_url, auth_version, user_id, key,
                 tenant_name=None, timeout=None):
        self.parent_conn = parent_conn
        # enable tests to use the same mock connection classes.
        self.conn_classes = parent_conn.conn_classes

        super(OpenStackAuthConnection, self).__init__(
            user_id, key, url=auth_url, timeout=timeout)

        self.auth_version = auth_version
        self.auth_url = auth_url
        self.driver = self.parent_conn.driver
        self.tenant_name = tenant_name
        self.timeout = timeout

        self.urls = {}
        self.auth_token = None
        self.auth_token_expires = None
        self.auth_user_info = None

    def morph_action_hook(self, action):
        return action

    def add_default_headers(self, headers):
        headers['Accept'] = 'application/json'
        headers['Content-Type'] = 'application/json; charset=UTF-8'
        return headers

    def authenticate(self, force=False):
        """
        Authenticate against the keystone api.

        @param force: Forcefully update the token even if it's already cached
                      and still valid.
        @type force: C{bool}
        """
        if not force and self.auth_version in AUTH_VERSIONS_WITH_EXPIRES \
           and self._is_token_valid():
            # If token is still valid, there is no need to re-authenticate
            return self

        if self.auth_version == "1.0":
            return self.authenticate_1_0()
        elif self.auth_version == "1.1":
            return self.authenticate_1_1()
        elif self.auth_version == "2.0" or self.auth_version == "2.0_apikey":
            return self.authenticate_2_0_with_apikey()
        elif self.auth_version == "2.0_password":
            return self.authenticate_2_0_with_password()
        else:
            raise LibcloudError('Unsupported Auth Version requested')

    def authenticate_1_0(self):
        resp = self.request("/v1.0",
                    headers={
                        'X-Auth-User': self.user_id,
                        'X-Auth-Key': self.key,
                    },
                    method='GET')

        if resp.status == httplib.UNAUTHORIZED:
            # HTTP UNAUTHORIZED (401): auth failed
            raise InvalidCredsError()
        elif resp.status != httplib.NO_CONTENT:
            raise MalformedResponseError('Malformed response',
                    body='code: %s body:%s headers:%s' % (resp.status,
                                                          resp.body,
                                                          resp.headers),
                    driver=self.driver)
        else:
            headers = resp.headers
            # emulate the auth 1.1 URL list
            self.urls = {}
            self.urls['cloudServers'] = \
                [{'publicURL': headers.get('x-server-management-url', None)}]
            self.urls['cloudFilesCDN'] = \
                [{'publicURL': headers.get('x-cdn-management-url', None)}]
            self.urls['cloudFiles'] = \
                [{'publicURL': headers.get('x-storage-url', None)}]
            self.auth_token = headers.get('x-auth-token', None)
            self.auth_user_info = None

            if not self.auth_token:
                raise MalformedResponseError('Missing X-Auth-Token in \
                                              response headers')

        return self

    def authenticate_1_1(self):
        reqbody = json.dumps({'credentials': {'username': self.user_id,
                                              'key': self.key}})
        resp = self.request("/v1.1/auth",
                    data=reqbody,
                    headers={},
                    method='POST')

        if resp.status == httplib.UNAUTHORIZED:
            # HTTP UNAUTHORIZED (401): auth failed
            raise InvalidCredsError()
        elif resp.status != httplib.OK:
            raise MalformedResponseError('Malformed response',
                    body='code: %s body:%s' % (resp.status, resp.body),
                    driver=self.driver)
        else:
            try:
                body = json.loads(resp.body)
            except Exception:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Failed to parse JSON', e)

            try:
                expires = body['auth']['token']['expires']

                self.auth_token = body['auth']['token']['id']
                self.auth_token_expires = parse_date(expires)
                self.urls = body['auth']['serviceCatalog']
                self.auth_user_info = None
            except KeyError:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Auth JSON response is \
                                             missing required elements', e)

        return self

    def authenticate_2_0_with_apikey(self):
        # API Key based authentication uses the RAX-KSKEY extension.
        # http://s.apache.org/oAi
        data = {'auth':
                {'RAX-KSKEY:apiKeyCredentials':
                 {'username': self.user_id, 'apiKey': self.key}}}
        if self.tenant_name:
            data['auth']['tenantName'] = self.tenant_name
        reqbody = json.dumps(data)
        return self.authenticate_2_0_with_body(reqbody)

    def authenticate_2_0_with_password(self):
        # Password based authentication is the only 'core' authentication
        # method in Keystone at this time.
        # 'keystone' - http://s.apache.org/e8h
        data = {'auth': \
                {'passwordCredentials': \
                 {'username': self.user_id, 'password': self.key}}}
        if self.tenant_name:
            data['auth']['tenantName'] = self.tenant_name
        reqbody = json.dumps(data)
        return self.authenticate_2_0_with_body(reqbody)

    def authenticate_2_0_with_body(self, reqbody):
        resp = self.request('/v2.0/tokens',
                    data=reqbody,
                    headers={'Content-Type': 'application/json'},
                    method='POST')
        if resp.status == httplib.UNAUTHORIZED:
            raise InvalidCredsError()
        elif resp.status not in [httplib.OK,
                                 httplib.NON_AUTHORITATIVE_INFORMATION]:
            raise MalformedResponseError('Malformed response',
                    body='code: %s body: %s' % (resp.status, resp.body),
                    driver=self.driver)
        else:
            try:
                body = json.loads(resp.body)
            except Exception:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Failed to parse JSON', e)

            try:
                access = body['access']
                expires = access['token']['expires']

                self.auth_token = access['token']['id']
                self.auth_token_expires = parse_date(expires)
                self.urls = access['serviceCatalog']
                self.auth_user_info = access.get('user', {})
            except KeyError:
                e = sys.exc_info()[1]
                raise MalformedResponseError('Auth JSON response is \
                                             missing required elements', e)

        return self

    def _is_token_valid(self):
        """
        Return True if the current taken is already cached and hasn't expired
        yet.

        @rtype: C{bool}
        """
        if not self.auth_token:
            return False

        if not self.auth_token_expires:
            return False

        expires = self.auth_token_expires - \
                datetime.timedelta(seconds=AUTH_TOKEN_EXPIRES_GRACE_SECONDS)

        time_tuple_expires = expires.utctimetuple()
        time_tuple_now = datetime.datetime.utcnow().utctimetuple()

        # TODO: Subtract some reasonable grace time period
        if time_tuple_now < time_tuple_expires:
            return True

        return False

class OpenStackServiceCatalog(object):
    """
    http://docs.openstack.org/api/openstack-identity-service/2.0/content/

    This class should be instanciated with the contents of the
    'serviceCatalog' in the auth response. This will do the work of figuring
    out which services actually exist in the catalog as well as split them up
    by type, name, and region if available
    """

    _auth_version = None
    _service_catalog = None

    def __init__(self, service_catalog, ex_force_auth_version=None):
        self._auth_version = ex_force_auth_version or AUTH_API_VERSION
        self._service_catalog = {}

        # Check this way because there are a couple of different 2.0_*
        # auth types.
        if '2.0' in self._auth_version:
            self._parse_auth_v2(service_catalog)
        elif ('1.1' in self._auth_version) or ('1.0' in self._auth_version):
            self._parse_auth_v1(service_catalog)
        else:
            raise LibcloudError('auth version "%s" not supported'
                                % (self._auth_version))

    def get_catalog(self):
        return self._service_catalog

    def get_public_urls(self, service_type=None, name=None):
        endpoints = self.get_endpoints(service_type=service_type,
                                       name=name)

        result = []
        for endpoint in endpoints:
            if 'publicURL' in endpoint:
                result.append(endpoint['publicURL'])

        return result

    def get_endpoints(self, service_type=None, name=None):
        eps = []

        if '2.0' in self._auth_version:
            endpoints = self._service_catalog.get(service_type, {}) \
                                             .get(name, {})
        elif ('1.1' in self._auth_version) or ('1.0' in self._auth_version):
            endpoints = self._service_catalog.get(name, {})

        for regionName, values in endpoints.items():
            eps.append(values[0])

        return eps

    def get_endpoint(self, service_type=None, name=None, region=None):
        if '2.0' in self._auth_version:
            endpoint = self._service_catalog.get(service_type, {}) \
                                            .get(name, {}).get(region, [])
        elif ('1.1' in self._auth_version) or ('1.0' in self._auth_version):
            endpoint = self._service_catalog.get(name, {}).get(region, [])

        # ideally an endpoint either isn't found or only one match is found.
        if len(endpoint) == 1:
            return endpoint[0]
        else:
            return {}

    def _parse_auth_v1(self, service_catalog):
        for service, endpoints in service_catalog.items():

            self._service_catalog[service] = {}

            for endpoint in endpoints:
                region = endpoint.get('region')

                if region not in self._service_catalog[service]:
                    self._service_catalog[service][region] = []

                self._service_catalog[service][region].append(endpoint)

    def _parse_auth_v2(self, service_catalog):
        for service in service_catalog:
            service_type = service['type']
            service_name = service.get('name', None)

            if service_type not in self._service_catalog:
                self._service_catalog[service_type] = {}

            if service_name not in self._service_catalog[service_type]:
                self._service_catalog[service_type][service_name] = {}

            for endpoint in service.get('endpoints', []):
                region = endpoint.get('region', None)

                catalog = self._service_catalog[service_type][service_name]
                if region not in catalog:
                    catalog[region] = []

                catalog[region].append(endpoint)

class OpenStackBaseConnection(ConnectionUserAndKey):

    """
    Base class for OpenStack connections.

    @param user_id: User name to use when authenticating
    @type user_id: C{string}

    @param key: Secret to use when authenticating.
    @type key: C{string}

    @param secure: Use HTTPS?  (True by default.)
    @type secure: C{bool}

    @param ex_force_base_url: Base URL for connection requests.  If
    not specified, this will be determined by authenticating.
    @type ex_force_base_url: C{string}

    @param ex_force_auth_url: Base URL for authentication requests.
    @type ex_force_auth_url: C{string}

    @param ex_force_auth_version: Authentication version to use.  If
    not specified, defaults to AUTH_API_VERSION.
    @type ex_force_auth_version: C{string}

    @param ex_force_auth_token: Authentication token to use for
    connection requests.  If specified, the connection will not attempt
    to authenticate, and the value of ex_force_base_url will be used to
    determine the base request URL.  If ex_force_auth_token is passed in,
    ex_force_base_url must also be provided.
    @type ex_force_auth_token: C{string}

    @param ex_tenant_name: When authenticating, provide this tenant
    name to the identity service.  A scoped token will be returned.
    Some cloud providers require the tenant name to be provided at
    authentication time.  Others will use a default tenant if none
    is provided.
    @type ex_tenant_name: C{string}

    @param ex_force_service_type: Service type to use when selecting an
    service.  If not specified, a provider specific default will be used.
    @type ex_force_service_type: C{string}

    @param ex_force_service_name: Service name to use when selecting an
    service.  If not specified, a provider specific default will be used.
    @type ex_force_service_name: C{string}

    @param ex_force_service_region: Region to use when selecting an
    service.  If not specified, a provider specific default will be used.
    @type ex_force_service_region: C{string}

    @param ex_auth_connection: OpenStackAuthConnection instance to use for
    making HTTP requests. If not specified, a new one is instantiated.
    @type ex_auth_connection: C{OpenStackAuthConnection}
    """

    auth_url = None
    auth_token = None
    auth_token_expires = None
    auth_user_info = None
    service_catalog = None
    service_type = None
    service_name = None
    service_region = None
    _auth_version = None

    def __init__(self, user_id, key, secure=True,
                 host=None, port=None, timeout=None,
                 ex_force_base_url=None,
                 ex_force_auth_url=None,
                 ex_force_auth_version=None,
                 ex_force_auth_token=None,
                 ex_tenant_name=None,
                 ex_force_service_type=None,
                 ex_force_service_name=None,
                 ex_force_service_region=None,
                 ex_auth_connection=None):

        self._ex_force_base_url = ex_force_base_url
        self._ex_force_auth_url = ex_force_auth_url
        self._auth_version = self._auth_version or ex_force_auth_version
        self._ex_tenant_name = ex_tenant_name
        self._ex_force_service_type = ex_force_service_type
        self._ex_force_service_name = ex_force_service_name
        self._ex_force_service_region = ex_force_service_region

        self._auth_connection = ex_auth_connection

        if ex_force_auth_token:
            self.auth_token = ex_force_auth_token

        if ex_force_auth_token and not ex_force_base_url:
            raise LibcloudError(
                'Must also provide ex_force_base_url when specifying '
                'ex_force_auth_token.')

        if not self._auth_version:
            self._auth_version = AUTH_API_VERSION

        super(OpenStackBaseConnection, self).__init__(
            user_id, key, secure=secure, timeout=timeout)

    def get_service_catalog(self):
        if self.service_catalog is None:
            self._populate_hosts_and_request_paths()

        return self.service_catalog

    def get_endpoint(self):
        """
        Selects the endpoint to use based on provider specific values,
        or overrides passed in by the user when setting up the driver.

        @returns: url of the relevant endpoint for the driver
        """
        service_type = self.service_type
        service_name = self.service_name
        service_region = self.service_region
        if self._ex_force_service_type:
            service_type = self._ex_force_service_type
        if self._ex_force_service_name:
            service_name = self._ex_force_service_name
        if self._ex_force_service_region:
            service_region = self._ex_force_service_region

        ep = self.service_catalog.get_endpoint(service_type=service_type,
                                               name=service_name,
                                               region=service_region)
        if 'publicURL' in ep:
            return ep['publicURL']

        raise LibcloudError('Could not find specified endpoint')

    def get_auth_connection_instance(self):
        """
        Return an OpenStackAuthConnection instance for this connection.
        """
        auth_url = self.auth_url

        if self._ex_force_auth_url is not None:
            auth_url = self._ex_force_auth_url

        if auth_url is None:
            raise LibcloudError('OpenStack instance must ' +
                                'have auth_url set')

        if not self._auth_connection:
            self._auth_connection = OpenStackAuthConnection(self, auth_url,
                                                            self._auth_version,
                                                            self.user_id,
                                                            self.key,
                                                            tenant_name=self._ex_tenant_name,
                                                            timeout=self.timeout)

        return self._auth_connection

    def add_default_headers(self, headers):
        headers['X-Auth-Token'] = self.auth_token
        headers['Accept'] = self.accept_format
        return headers

    def morph_action_hook(self, action):
        self._populate_hosts_and_request_paths()
        return super(OpenStackBaseConnection, self).morph_action_hook(action)

    def request(self, **kwargs):
        return super(OpenStackBaseConnection, self).request(**kwargs)

    def _populate_hosts_and_request_paths(self):
        """
        OpenStack uses a separate host for API calls which is only provided
        after an initial authentication request.
        """

        if not self.auth_token:
            auth_connection = self.get_auth_connection_instance()

            # may throw InvalidCreds, etc
            auth_connection.authenticate()

            self.auth_token = auth_connection.auth_token
            self.auth_token_expires = auth_connection.auth_token_expires
            self.auth_user_info = auth_connection.auth_user_info

            # pull out and parse the service catalog
            self.service_catalog = OpenStackServiceCatalog(auth_connection.urls,
                    ex_force_auth_version=self._auth_version)

        # Set up connection info
        url = self._ex_force_base_url or self.get_endpoint()
        (self.host, self.port, self.secure, self.request_path) = \
                self._tuple_from_url(url)

    def _add_cache_busting_to_params(self, params):
        cache_busting_number = binascii.hexlify(os.urandom(8))

        if isinstance(params, dict):
            params['cache-busting'] = cache_busting_number
        else:
            params.append(('cache-busting', cache_busting_number))

class OpenStackDriverMixin(object):

    # Extenstion arguments which are passed to the connection class.
    EXTENSTION_ARGUMENTS = [
        'ex_force_base_url',
        'ex_force_auth_token',
        'ex_force_auth_url',
        'ex_force_auth_version',
        'ex_tenant_name',
        'ex_force_service_type',
        'ex_force_service_name',
        'ex_force_service_region',
        'ex_auth_connection'
    ]

    def __init__(self, *args, **kwargs):
        pairs = self._get_argument_pairs()
        for argument_name, attribute_name in pairs:
            value = kwargs.get(argument_name, None)

            if value is None:
                continue

            setattr(self, attribute_name, value)

    def openstack_connection_kwargs(self):
        """
        @rtype: C{dict}
        """
        result = {}

        pairs = self._get_argument_pairs()
        for argument_name, attribute_name in pairs:
            value = getattr(self, attribute_name, None)

            if not value:
                continue

            result[argument_name] = value

        return result

    def _get_argument_pairs(self):
        result = []
        for argument_name in self.EXTENSTION_ARGUMENTS:
            attribute_name = '_%s' % (argument_name)
            result.append([argument_name, attribute_name])

        return result


text:
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Dashboard.TestDoubles
{
    public class FakeStartup<T> where T : new()
    {
        private readonly T _innerStartup;
        private readonly MethodInfo _configureMethod;
        private readonly MethodInfo _configureServicesMethod;

        public FakeStartup()
        {
            _innerStartup = new T();
            _configureMethod = typeof(T).GetMethod("Configure");
            _configureServicesMethod = typeof(T).GetMethod("ConfigureServices");
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddApplicationPart(typeof(T).GetTypeInfo().Assembly)
                .AddControllersAsServices();
            _configureServicesMethod.Invoke(_innerStartup, new object[]{services});
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var parameters = _configureMethod.GetParameters();
            if (parameters.Length == 3)
                _configureMethod.Invoke(_innerStartup, new object[] {app, env, loggerFactory});
            else if (parameters.Length == 2)
                _configureMethod.Invoke(_innerStartup, new object[] {app, env});
            else
                _configureMethod.Invoke(_innerStartup, new object[] {app});
        }
    }
}


text:
import { equals } from "../fp";
export = equals;


text:
var webpack = require('webpack');
var config = require('./webpack.config.client');
var _ = require('lodash');
var devProps = require('./devProps');
var RunInMeteorPlugin = require('webpack-meteor-tools/lib/RunInMeteorPlugin');
var dirs = require('../dirs');

var config = module.exports = _.assign(_.clone(config), {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?' + devProps.baseUrl,
    'webpack/hot/only-dev-server',
  ].concat(config.entry),
  output: _.assign(_.clone(config.output), {
    publicPath: devProps.baseUrl + '/assets/',
    pathinfo: true,
  }),
  plugins: (config.plugins || []).concat([
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new RunInMeteorPlugin({
      mode: 'development',
      target: 'client',
      meteor: dirs.meteor,
      key: 'client',
    }),
  ]),
  devServer: {
    publicPath: devProps.baseUrl + '/assets/',
    host: devProps.host,
    hot: true,
    historyApiFallback: true,
    contentBase: devProps.contentBase,
    port: devProps.webpackPort,
    // proxy: {
      // '/sockjs/*': {
      //   ws: true,
      //   target: 'ws://localhost:3000/sockjs',
      // },
      // '*': 'http://localhost:3000',
    // }
  }
});


text:
var clone = require('gulp-clone'),
  gutil = require('gulp-util'),
  inject = require('gulp-multinject'),
  _ = require('lodash'),
  filter = require('gulp-filter');

var self = module.exports = {
  __module: {
    properties: {
      log: '../log',
      util: "../../util"
    },
    provides: {"assetmanager/build/transforms/define_transforms": {before: "./dest"}}
  },

  define_transforms: function(definitions) {
    var streams = [];
    _.each(definitions.resources, function(resourcesDescriptor, type) {
      if(resourcesDescriptor.options.doNotInject) {
        return;
      }

      _.each(resourcesDescriptor.namespaces, function(resourceLists, namespace) {
        var filterStream = filter(resourcesDescriptor.options.injectFilter);
        var toInject = [];

        if(resourceLists.urls) {
          Array.prototype.push.apply(toInject, resourceLists.urls);
        }

        if(resourceLists.files) {
          Array.prototype.push.apply(toInject, resourceLists.files);
        }

        if(_.isEmpty(toInject)) {
          return;
        }

        var ns = type+":"+namespace;

        self.log.debug({
          files: toInject,
          namespace: ns,
          options: resourcesDescriptor.options.injectOptions
        }, "gulp-multinject configuration");

        streams.push(
          filterStream,
          self.util.logStream("Processing file", null, "gulp-multinject " + ns),
          inject(toInject, ns, resourcesDescriptor.options.injectOptions),
          filterStream.restore()
        );
      });
    });

    Array.prototype.push.apply(definitions.streams.views, streams);
    return definitions;
  }
};


text:
import { faMinus } from "@fortawesome/free-solid-svg-icons/faMinus"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome/index.js"
import { EntityName } from "@ourworldindata/core-table"
import {
    ComparisonLineConfig,
    Grapher,
    ScatterPointLabelStrategy,
} from "@ourworldindata/grapher"
import { debounce, excludeUndefined } from "@ourworldindata/utils"
import { action, computed, observable } from "mobx"
import { observer } from "mobx-react"
import React from "react"
import { NumberField, Section, SelectField, Toggle } from "./Forms.js"

@observer
export class EditorScatterTab extends React.Component<{ grapher: Grapher }> {
    @observable comparisonLine: ComparisonLineConfig = { yEquals: undefined }

    constructor(props: { grapher: Grapher }) {
        super(props)
    }

    @action.bound onToggleHideTimeline(value: boolean) {
        this.props.grapher.hideTimeline = value || undefined
    }

    @action.bound onToggleHideLinesOutsideTolerance(value: boolean) {
        this.props.grapher.hideLinesOutsideTolerance = value || undefined
    }

    @action.bound onXOverrideYear(value: number | undefined) {
        this.props.grapher.xOverrideTime = value
    }

    @computed private get excludedEntityNames(): EntityName[] {
        const { excludedEntities, inputTable } = this.props.grapher
        const { entityIdToNameMap } = inputTable
        const excludedEntityIds = excludedEntities ?? []
        return excludeUndefined(
            excludedEntityIds.map((entityId) => entityIdToNameMap.get(entityId))
        )
    }

    @computed private get excludedEntityChoices() {
        const { inputTable } = this.props.grapher
        return inputTable.availableEntityNames
            .filter(
                (entityName) => !this.excludedEntityNames.includes(entityName)
            )
            .sort()
    }

    @action.bound onExcludeEntity(entity: string) {
        const { grapher } = this.props
        if (grapher.excludedEntities === undefined) {
            grapher.excludedEntities = []
        }

        const entityId = grapher.table.entityNameToIdMap.get(entity)!
        if (grapher.excludedEntities.indexOf(entityId) === -1)
            grapher.excludedEntities.push(entityId)
    }

    @action.bound onUnexcludeEntity(entity: string) {
        const { grapher } = this.props
        if (!grapher.excludedEntities) return

        const entityId = grapher.table.entityNameToIdMap.get(entity)
        grapher.excludedEntities = grapher.excludedEntities.filter(
            (e) => e !== entityId
        )
    }

    @action.bound onToggleConnection(value: boolean) {
        const { grapher } = this.props
        grapher.hideConnectedScatterLines = value
    }

    @action.bound onChangeScatterPointLabelStrategy(value: string) {
        this.props.grapher.scatterPointLabelStrategy =
            value as ScatterPointLabelStrategy
    }

    render() {
        const { excludedEntityChoices } = this
        const { grapher } = this.props

        return (

                    <Toggle
                        label="Hide timeline"
                        value={!!grapher.hideTimeline}
                        onValue={this.onToggleHideTimeline}
                    />
                    <Toggle
                        label="Hide entities without data for full time span (within tolerance)"
                        value={!!grapher.hideLinesOutsideTolerance}
                        onValue={this.onToggleHideLinesOutsideTolerance}
                    />
                    <Toggle
                        label="Hide connected scatter lines"
                        value={!!grapher.hideConnectedScatterLines}
                        onValue={this.onToggleConnection}
                    />
                    <NumberField
                        label="Override X axis target year"
                        value={grapher.xOverrideTime}
                        onValue={debounce(this.onXOverrideYear, 300)}
                        allowNegative
                    />

                    <SelectField
                        value={grapher.scatterPointLabelStrategy}
                        onValue={this.onChangeScatterPointLabelStrategy}
                        options={Object.keys(ScatterPointLabelStrategy).map(
                            (entry) => ({ value: entry })
                        )}
                    />

                    <Toggle
                        label="Exclude entities that do not belong in any color group"
                        value={!!grapher.matchingEntitiesOnly}
                        onValue={action(
                            (value: boolean) =>
                                (grapher.matchingEntitiesOnly =
                                    value || undefined)
                        )}
                    />
                    <SelectField
                        label="Exclude individual entities"
                        placeholder="Select an entity to exclude"
                        value={undefined}
                        onValue={(v) => v && this.onExcludeEntity(v)}
                        options={excludedEntityChoices.map((entry) => ({
                            value: entry,
                        }))}
                    />
                    {this.excludedEntityNames && (

                            {this.excludedEntityNames.map((entity) => (

                                            this.onUnexcludeEntity(entity)
                                        }
                                    >
                                        <FontAwesomeIcon icon={faMinus} />

                                    {entity}

                            ))}

                    )}

        )
    }
}


text:
require "fume/nav/nav_tag"

module Fume
  module Nav
    module HelperExt
      def fume_nav(*args, &block)
        attributes = {
          active_class: "active",
          inactive_class: nil,
          hide_if_empty: true
        }.merge(args.extract_options!)

        attributes[:current] = args.shift
        attributes[:helper] = self
        tag = NavTag.new(attributes)
        content = capture(tag, &block)

        return content if !tag.hide?
      end

    end
  end
end


text:
require('./style.css');
var loop = require('./test.js');
var util = require('./util.js');
var $ = require('jquery');

$('body').css('color', 'red');
$(document).ready(function(){
    $('.test-01').html('jquery works!');
});

//document.write('It works hahahah;');

//require.ensure('http://yyfinancesmall.bs2dl.yy.com/financeSearch.js', function() {
    //console.log('success')
//});

//加载股票数据
util.loader.load('http://yyfinancesmall.bs2dl.yy.com/financeSearch.js')
    .wait(function(){
        console.log(navSearchData);
    })

loop.loop();


text:
require 'uri'
require 'webrick/httpversion'
require 'webrick/httpstatus'
require 'webrick/httputils'
require 'webrick/cookie'

module WEBrick
  class HTTPRequest
    BODY_CONTAINABLE_METHODS = [ "POST", "PUT" ]

    # Request line
    attr_reader :request_line
    attr_reader :request_method, :unparsed_uri, :http_version

    # Request-URI
    attr_reader :request_uri, :path
    attr_accessor :script_name, :path_info, :query_string

    # Header and entity body
    attr_reader :raw_header, :header, :cookies
    attr_reader :accept, :accept_charset
    attr_reader :accept_encoding, :accept_language

    # Misc
    attr_accessor :user
    attr_reader :addr, :peeraddr
    attr_reader :attributes
    attr_reader :keep_alive
    attr_reader :request_time

    def initialize(config)
      @config = config
      @buffer_size = @config[:InputBufferSize]
      @logger = config[:Logger]

      @request_line = @request_method =
        @unparsed_uri = @http_version = nil

      @request_uri = @host = @port = @path = nil
      @script_name = @path_info = nil
      @query_string = nil
      @query = nil
      @form_data = nil

      @raw_header = Array.new
      @header = nil
      @cookies = []
      @accept = []
      @accept_charset = []
      @accept_encoding = []
      @accept_language = []
      @body = ""

      @addr = @peeraddr = nil
      @attributes = {}
      @user = nil
      @keep_alive = false
      @request_time = nil

      @remaining_size = nil
      @socket = nil

      @forwarded_proto = @forwarded_host = @forwarded_port =
        @forwarded_server = @forwarded_for = nil
    end

    def parse(socket=nil)
      @socket = socket
      begin
        @peeraddr = socket.respond_to?(:peeraddr) ? socket.peeraddr : []
        @addr = socket.respond_to?(:addr) ? socket.addr : []
      rescue Errno::ENOTCONN
        raise HTTPStatus::EOFError
      end

      read_request_line(socket)
      if @http_version.major > 0
        read_header(socket)
        @header['cookie'].each{|cookie|
          @cookies += Cookie::parse(cookie)
        }
        @accept = HTTPUtils.parse_qvalues(self['accept'])
        @accept_charset = HTTPUtils.parse_qvalues(self['accept-charset'])
        @accept_encoding = HTTPUtils.parse_qvalues(self['accept-encoding'])
        @accept_language = HTTPUtils.parse_qvalues(self['accept-language'])
      end
      return if @request_method == "CONNECT"
      return if @unparsed_uri == "*"

      begin
        setup_forwarded_info
        @request_uri = parse_uri(@unparsed_uri)
        @path = HTTPUtils::unescape(@request_uri.path)
        @path = HTTPUtils::normalize_path(@path)
        @host = @request_uri.host
        @port = @request_uri.port
        @query_string = @request_uri.query
        @script_name = ""
        @path_info = @path.dup
      rescue
        raise HTTPStatus::BadRequest, "bad URI `#{@unparsed_uri}'."
      end

      if /close/io =~ self["connection"]
        @keep_alive = false
      elsif /keep-alive/io =~ self["connection"]
        @keep_alive = true
      elsif @http_version < "1.1"
        @keep_alive = false
      else
        @keep_alive = true
      end
    end

    def body(&block)
      block ||= Proc.new{|chunk| @body << chunk }
      read_body(@socket, block)
      @body.empty? ? nil : @body
    end

    def query
      unless @query
        parse_query()
      end
      @query
    end

    def content_length
      return Integer(self['content-length'])
    end

    def content_type
      return self['content-type']
    end

    def [](header_name)
      if @header
        value = @header[header_name.downcase]
        value.empty? ? nil : value.join(", ")
      end
    end

    def each
      @header.each{|k, v|
        value = @header[k]
        yield(k, value.empty? ? nil : value.join(", "))
      }
    end

    def host
      return @forwarded_host || @host
    end

    def port
      return @forwarded_port || @port
    end

    def server_name
      return @forwarded_server || @config[:ServerName]
    end

    def remote_ip
      return self["client-ip"] || @forwarded_for || @peeraddr[3]
    end

    def ssl?
      return @request_uri.scheme == "https"
    end

    def keep_alive?
      @keep_alive
    end

    def to_s
      ret = @request_line.dup
      @raw_header.each{|line| ret << line }
      ret << CRLF
      ret << body if body
      ret
    end

    def fixup()
      begin
        body{|chunk| }   # read remaining body
      rescue HTTPStatus::Error => ex
        @logger.error("HTTPRequest#fixup: #{ex.class} occured.")
        @keep_alive = false
      rescue => ex
        @logger.error(ex)
        @keep_alive = false
      end
    end

    def meta_vars
      # This method provides the metavariables defined by the revision 3
      # of ``The WWW Common Gateway Interface Version 1.1''.
      # (http://Web.Golux.Com/coar/cgi/)

      meta = Hash.new

      cl = self["Content-Length"]
      ct = self["Content-Type"]
      meta["CONTENT_LENGTH"]    = cl if cl.to_i > 0
      meta["CONTENT_TYPE"]      = ct.dup if ct
      meta["GATEWAY_INTERFACE"] = "CGI/1.1"
      meta["PATH_INFO"]         = @path_info ? @path_info.dup : ""
     #meta["PATH_TRANSLATED"]   = nil      # no plan to be provided
      meta["QUERY_STRING"]      = @query_string ? @query_string.dup : ""
      meta["REMOTE_ADDR"]       = @peeraddr[3]
      meta["REMOTE_HOST"]       = @peeraddr[2]
     #meta["REMOTE_IDENT"]      = nil      # no plan to be provided
      meta["REMOTE_USER"]       = @user
      meta["REQUEST_METHOD"]    = @request_method.dup
      meta["REQUEST_URI"]       = @request_uri.to_s
      meta["SCRIPT_NAME"]       = @script_name.dup
      meta["SERVER_NAME"]       = @host
      meta["SERVER_PORT"]       = @port.to_s
      meta["SERVER_PROTOCOL"]   = "HTTP/" + @config[:HTTPVersion].to_s
      meta["SERVER_SOFTWARE"]   = @config[:ServerSoftware].dup

      self.each{|key, val|
        next if /^content-type$/i =~ key
        next if /^content-length$/i =~ key
        name = "HTTP_" + key
        name.gsub!(/-/o, "_")
        name.upcase!
        meta[name] = val
      }

      meta
    end

    private

    def read_request_line(socket)
      @request_line = read_line(socket, 1024) if socket
      if @request_line.bytesize >= 1024 and @request_line[-1, 1] != LF
        raise HTTPStatus::RequestURITooLarge
      end
      @request_time = Time.now
      raise HTTPStatus::EOFError unless @request_line
      if /^(\S+)\s+(\S+)(?:\s+HTTP\/(\d+\.\d+))?\r?\n/mo =~ @request_line
        @request_method = $1
        @unparsed_uri   = $2
        @http_version   = HTTPVersion.new($3 ? $3 : "0.9")
      else
        rl = @request_line.sub(/\x0d?\x0a\z/o, '')
        raise HTTPStatus::BadRequest, "bad Request-Line `#{rl}'."
      end
    end

    def read_header(socket)
      if socket
        while line = read_line(socket)
          break if /\A(#{CRLF}|#{LF})\z/om =~ line
          @raw_header << line
        end
      end
      @header = HTTPUtils::parse_header(@raw_header.join)
    end

    def parse_uri(str, scheme="http")
      if @config[:Escape8bitURI]
        str = HTTPUtils::escape8bit(str)
      end
      uri = URI::parse(str)
      return uri if uri.absolute?
      if @forwarded_host
        host, port = @forwarded_host, @forwarded_port
      elsif self["host"]
        pattern = /\A(#{URI::REGEXP::PATTERN::HOST})(?::(\d+))?\z/n
        host, port = *self['host'].scan(pattern)[0]
      elsif @addr.size > 0
        host, port = @addr[2], @addr[1]
      else
        host, port = @config[:ServerName], @config[:Port]
      end
      uri.scheme = @forwarded_proto || scheme
      uri.host = host
      uri.port = port ? port.to_i : nil
      return URI::parse(uri.to_s)
    end

    def read_body(socket, block)
      return unless socket
      if tc = self['transfer-encoding']
        case tc
        when /chunked/io then read_chunked(socket, block)
        else raise HTTPStatus::NotImplemented, "Transfer-Encoding: #{tc}."
        end
      elsif self['content-length'] || @remaining_size
        @remaining_size ||= self['content-length'].to_i
        while @remaining_size > 0
          sz = [@buffer_size, @remaining_size].min
          break unless buf = read_data(socket, sz)
          @remaining_size -= buf.bytesize
          block.call(buf)
        end
        if @remaining_size > 0 && @socket.eof?
          raise HTTPStatus::BadRequest, "invalid body size."
        end
      elsif BODY_CONTAINABLE_METHODS.member?(@request_method)
        raise HTTPStatus::LengthRequired
      end
      return @body
    end

    def read_chunk_size(socket)
      line = read_line(socket)
      if /^([0-9a-fA-F]+)(?:;(\S+))?/ =~ line
        chunk_size = $1.hex
        chunk_ext = $2
        [ chunk_size, chunk_ext ]
      else
        raise HTTPStatus::BadRequest, "bad chunk `#{line}'."
      end
    end

    def read_chunked(socket, block)
      chunk_size, = read_chunk_size(socket)
      while chunk_size > 0
        data = read_data(socket, chunk_size) # read chunk-data
        if data.nil? || data.bytesize != chunk_size
          raise BadRequest, "bad chunk data size."
        end
        read_line(socket)                    # skip CRLF
        block.call(data)
        chunk_size, = read_chunk_size(socket)
      end
      read_header(socket)                    # trailer + CRLF
      @header.delete("transfer-encoding")
      @remaining_size = 0
    end

    def _read_data(io, method, *arg)
      begin
        WEBrick::Utils.timeout(@config[:RequestTimeout]){
          return io.__send__(method, *arg)
        }
      rescue Errno::ECONNRESET
        return nil
      rescue TimeoutError
        raise HTTPStatus::RequestTimeout
      end
    end

    def read_line(io, size=4096)
      _read_data(io, :gets, LF, size)
    end

    def read_data(io, size)
      _read_data(io, :read, size)
    end

    def parse_query()
      begin
        if @request_method == "GET" || @request_method == "HEAD"
          @query = HTTPUtils::parse_query(@query_string)
        elsif self['content-type'] =~ /^application\/x-www-form-urlencoded/
          @query = HTTPUtils::parse_query(body)
        elsif self['content-type'] =~ /^multipart\/form-data; boundary=(.+)/
          boundary = HTTPUtils::dequote($1)
          @query = HTTPUtils::parse_form_data(body, boundary)
        else
          @query = Hash.new
        end
      rescue => ex
        raise HTTPStatus::BadRequest, ex.message
      end
    end

    PrivateNetworkRegexp = /
      ^unknown$|
      ^((::ffff:)?127.0.0.1|::1)$|
      ^(::ffff:)?(10|172\.(1[6-9]|2[0-9]|3[01])|192\.168)\.
    /ixo

    def setup_forwarded_info
      @forwarded_server = self["x-forwarded-server"]
      @forwarded_proto = self["x-forwarded-proto"]
      if host_port = self["x-forwarded-host"]
        @forwarded_host, tmp = host_port.split(":", 2)
        @forwarded_port = (tmp || (@forwarded_proto == "https" ? 443 : 80)).to_i
      end
      if addrs = self["x-forwarded-for"]
        addrs = addrs.split(",").collect(&:strip)
        addrs.reject!{|ip| PrivateNetworkRegexp =~ ip }
        @forwarded_for = addrs.first
      end
    end
  end
end


text:
"""A module with MySQL implementation of YARA-related database methods."""

from typing import Text

import MySQLdb

from grr_response_server.databases import db
from grr_response_server.databases import mysql_utils
from grr_response_server.rdfvalues import objects as rdf_objects

class MySQLDBYaraMixin(object):
  """A MySQL database mixin class with YARA-related methods."""

  @mysql_utils.WithTransaction()
  def WriteYaraSignatureReference(
      self,
      blob_id: rdf_objects.BlobID,
      username: Text,
      cursor: MySQLdb.cursors.Cursor,
  ) -> None:
    """Marks specified blob id as a YARA signature."""
    query = """
    INSERT IGNORE INTO yara_signature_references
    VALUES (%(blob_id)s, %(username_hash)s, NOW(6))
    """
    args = {
        "blob_id": blob_id.AsBytes(),
        "username_hash": mysql_utils.Hash(username),
    }

    try:
      cursor.execute(query, args)
    except MySQLdb.IntegrityError:
      raise db.UnknownGRRUserError(username=username)

  @mysql_utils.WithTransaction(readonly=True)
  def VerifyYaraSignatureReference(
      self,
      blob_id: rdf_objects.BlobID,
      cursor: MySQLdb.cursors.Cursor,
  ) -> bool:
    """Verifies whether specified blob is a YARA signature."""
    query = """
    SELECT 1
      FROM yara_signature_references
     WHERE blob_id = %(blob_id)s
    """
    cursor.execute(query, {"blob_id": blob_id.AsBytes()})

    return len(cursor.fetchall()) == 1