text:
"""
Utils.
"""
import copy
import warnings
from collections import OrderedDict
import inspect

import inflection
from django.conf import settings
from django.utils import encoding
from django.utils import six
from django.utils.module_loading import import_string as import_class_from_dotted_path
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import APIException
from rest_framework import exceptions

try:
    from rest_framework.serializers import ManyRelatedField
except ImportError:
    ManyRelatedField = type(None)

try:
    from rest_framework_nested.relations import HyperlinkedRouterField
except ImportError:
    HyperlinkedRouterField = type(None)

def get_resource_name(context):
    """
    Return the name of a resource.
    """
    view = context.get('view')

    # Sanity check to make sure we have a view.
    if not view:
        raise APIException(_('Could not find view.'))

    # Check to see if there is a status code and return early
    # with the resource_name value of `errors`.
    try:
        code = str(view.response.status_code)
    except (AttributeError, ValueError):
        pass
    else:
        if code.startswith('4') or code.startswith('5'):
            return 'errors'

    try:
        resource_name = getattr(view, 'resource_name')
    except AttributeError:
        try:
            serializer = view.get_serializer_class()
            return get_resource_type_from_serializer(serializer)
        except AttributeError:
            try:
                resource_name = get_resource_type_from_model(view.model)
            except AttributeError:
                resource_name = view.__class__.__name__

            if not isinstance(resource_name, six.string_types):
                # The resource name is not a string - return as is
                return resource_name

            # the name was calculated automatically from the view > pluralize and format
            resource_name = format_resource_type(resource_name)

    return resource_name

def get_serializer_fields(serializer):
    fields = None
    if hasattr(serializer, 'child'):
        fields = getattr(serializer.child, 'fields')
        meta = getattr(serializer.child, 'Meta', None)
    if hasattr(serializer, 'fields'):
        fields = getattr(serializer, 'fields')
        meta = getattr(serializer, 'Meta', None)

    if fields is not None:
        meta_fields = getattr(meta, 'meta_fields', {})
        for field in meta_fields:
            try:
                fields.pop(field)
            except KeyError:
                pass
        return fields

def format_keys(obj, format_type=None):
    """
    Takes either a dict or list and returns it with camelized keys only if
    JSON_API_FORMAT_KEYS is set.

    :format_type: Either 'dasherize', 'camelize' or 'underscore'
    """
    if format_type is None:
        format_type = getattr(settings, 'JSON_API_FORMAT_KEYS', False)

    if format_type in ('dasherize', 'camelize', 'underscore', 'capitalize'):

        if isinstance(obj, dict):
            formatted = OrderedDict()
            for key, value in obj.items():
                if format_type == 'dasherize':
                    # inflection can't dasherize camelCase
                    key = inflection.underscore(key)
                    formatted[inflection.dasherize(key)] \
                        = format_keys(value, format_type)
                elif format_type == 'camelize':
                    formatted[inflection.camelize(key, False)] \
                        = format_keys(value, format_type)
                elif format_type == 'capitalize':
                    formatted[inflection.camelize(key)] \
                        = format_keys(value, format_type)
                elif format_type == 'underscore':
                    formatted[inflection.underscore(key)] \
                        = format_keys(value, format_type)
            return formatted
        if isinstance(obj, list):
            return [format_keys(item, format_type) for item in obj]
        else:
            return obj
    else:
        return obj

def format_value(value, format_type=None):
    if format_type is None:
        format_type = getattr(settings, 'JSON_API_FORMAT_KEYS', False)
    if format_type == 'dasherize':
        # inflection can't dasherize camelCase
        value = inflection.underscore(value)
        value = inflection.dasherize(value)
    elif format_type == 'camelize':
        value = inflection.camelize(value, False)
    elif format_type == 'capitalize':
        value = inflection.camelize(value)
    elif format_type == 'underscore':
        value = inflection.underscore(value)
    return value

def format_relation_name(value, format_type=None):
    warnings.warn("The 'format_relation_name' function has been renamed 'format_resource_type' and the settings are now 'JSON_API_FORMAT_TYPES' and 'JSON_API_PLURALIZE_TYPES'")
    if format_type is None:
        format_type = getattr(settings, 'JSON_API_FORMAT_RELATION_KEYS', None)
    pluralize = getattr(settings, 'JSON_API_PLURALIZE_RELATION_TYPE', None)
    return format_resource_type(value, format_type, pluralize)

def format_resource_type(value, format_type=None, pluralize=None):
    if format_type is None:
        format_type = getattr(settings, 'JSON_API_FORMAT_TYPES', False)

    if pluralize is None:
        pluralize = getattr(settings, 'JSON_API_PLURALIZE_TYPES', False)

    if format_type:
        # format_type will never be None here so we can use format_value
        value = format_value(value, format_type)

    return inflection.pluralize(value) if pluralize else value

def get_related_resource_type(relation):
    if hasattr(relation, '_meta'):
        relation_model = relation._meta.model
    elif hasattr(relation, 'model'):
        # the model type was explicitly passed as a kwarg to ResourceRelatedField
        relation_model = relation.model
    elif hasattr(relation, 'get_queryset') and relation.get_queryset() is not None:
        relation_model = relation.get_queryset().model
    else:
        parent_serializer = relation.parent
        if hasattr(parent_serializer, 'Meta'):
            parent_model = parent_serializer.Meta.model
        else:
            parent_model = parent_serializer.parent.Meta.model

        if relation.source:
            if relation.source != '*':
                parent_model_relation = getattr(parent_model, relation.source)
            else:
                parent_model_relation = getattr(parent_model, relation.field_name)
        else:
            parent_model_relation = getattr(parent_model, parent_serializer.field_name)

        if hasattr(parent_model_relation, 'related'):
            try:
                relation_model = parent_model_relation.related.related_model
            except AttributeError:
                # Django 1.7
                relation_model = parent_model_relation.related.model
        elif hasattr(parent_model_relation, 'field'):
            try:
                relation_model = parent_model_relation.field.remote_field.model
            except AttributeError:
                relation_model = parent_model_relation.field.related.model
        else:
            return get_related_resource_type(parent_model_relation)
    return get_resource_type_from_model(relation_model)

def get_instance_or_manager_resource_type(resource_instance_or_manager):
    if hasattr(resource_instance_or_manager, 'model'):
        return get_resource_type_from_manager(resource_instance_or_manager)
    if hasattr(resource_instance_or_manager, '_meta'):
        return get_resource_type_from_instance(resource_instance_or_manager)
    pass

def get_resource_type_from_model(model):
    json_api_meta = getattr(model, 'JSONAPIMeta', None)
    return getattr(
        json_api_meta,
        'resource_name',
        format_resource_type(model.__name__))

def get_resource_type_from_queryset(qs):
    return get_resource_type_from_model(qs.model)

def get_resource_type_from_instance(instance):
    return get_resource_type_from_model(instance._meta.model)

def get_resource_type_from_manager(manager):
    return get_resource_type_from_model(manager.model)

def get_resource_type_from_serializer(serializer):
    if hasattr(serializer.Meta, 'resource_name'):
        return serializer.Meta.resource_name
    else:
        return get_resource_type_from_model(serializer.Meta.model)

def get_default_included_resources_from_serializer(serializer):
    try:
        return list(serializer.JSONAPIMeta.included_resources)
    except AttributeError:
        return []

def get_included_serializers(serializer):
    included_serializers = copy.copy(getattr(serializer, 'included_serializers', dict()))

    for name, value in six.iteritems(included_serializers):
        if not isinstance(value, type):
            if value == 'self':
                included_serializers[name] = serializer if isinstance(serializer, type) else serializer.__class__
            else:
                included_serializers[name] = import_class_from_dotted_path(value)

    return included_serializers

class Hyperlink(six.text_type):
    """
    A string like object that additionally has an associated name.
    We use this for hyperlinked URLs that may render as a named link
    in some contexts, or render as a plain URL in others.

    Comes from Django REST framework 3.2
    https://github.com/tomchristie/django-rest-framework
    """

    def __new__(self, url, name):
        ret = six.text_type.__new__(self, url)
        ret.name = name
        return ret

    is_hyperlink = True

def format_drf_errors(response, context, exc):
    errors = []
    # handle generic errors. ValidationError('test') in a view for example
    if isinstance(response.data, list):
        for message in response.data:
            errors.append({
                'detail': message,
                'source': {
                    'pointer': '/data',
                },
                'status': encoding.force_text(response.status_code),
            })
    # handle all errors thrown from serializers
    else:
        for field, error in response.data.items():
            field = format_value(field)
            pointer = '/data/attributes/{}'.format(field)
            # see if they passed a dictionary to ValidationError manually
            if isinstance(error, dict):
                errors.append(error)
            elif isinstance(error, six.string_types):
                classes = inspect.getmembers(exceptions, inspect.isclass)
                # DRF sets the `field` to 'detail' for its own exceptions
                if isinstance(exc, tuple(x[1] for x in classes)):
                    pointer = '/data'
                errors.append({
                    'detail': error,
                    'source': {
                        'pointer': pointer,
                    },
                    'status': encoding.force_text(response.status_code),
                })
            elif isinstance(error, list):
                for message in error:
                    errors.append({
                        'detail': message,
                        'source': {
                            'pointer': pointer,
                        },
                        'status': encoding.force_text(response.status_code),
                    })
            else:
                errors.append({
                    'detail': error,
                    'source': {
                        'pointer': pointer,
                    },
                    'status': encoding.force_text(response.status_code),
                })

    context['view'].resource_name = 'errors'
    response.data = errors

    return response

def format_errors(data):
    if len(data) > 1 and isinstance(data, list):
        data.sort(key=lambda x: x.get('source', {}).get('pointer', ''))
    return {'errors': data}


text:
namespace SerializationTests
{

using System;
using FlatBuffers;

public sealed class TestTable1 : Table {
  public static TestTable1 GetRootAsTestTable1(ByteBuffer _bb) { return GetRootAsTestTable1(_bb, new TestTable1()); }
  public static TestTable1 GetRootAsTestTable1(ByteBuffer _bb, TestTable1 obj) { return (obj.__init(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
  public TestTable1 __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; }

  public int IntProp { get { int o = __offset(4); return o != 0 ? bb.GetInt(o + bb_pos) : (int)0; } }
  public byte ByteProp { get { int o = __offset(6); return o != 0 ? bb.Get(o + bb_pos) : (byte)0; } }
  public short ShortProp { get { int o = __offset(8); return o != 0 ? bb.GetShort(o + bb_pos) : (short)0; } }

  public static Offset<TestTable1> CreateTestTable1(FlatBufferBuilder builder,
      int IntProp = 0,
      byte ByteProp = 0,
      short ShortProp = 0) {
    builder.StartObject(3);
    TestTable1.AddIntProp(builder, IntProp);
    TestTable1.AddShortProp(builder, ShortProp);
    TestTable1.AddByteProp(builder, ByteProp);
    return TestTable1.EndTestTable1(builder);
  }

  public static void StartTestTable1(FlatBufferBuilder builder) { builder.StartObject(3); }
  public static void AddIntProp(FlatBufferBuilder builder, int IntProp) { builder.AddInt(0, IntProp, 0); }
  public static void AddByteProp(FlatBufferBuilder builder, byte ByteProp) { builder.AddByte(1, ByteProp, 0); }
  public static void AddShortProp(FlatBufferBuilder builder, short ShortProp) { builder.AddShort(2, ShortProp, 0); }
  public static Offset<TestTable1> EndTestTable1(FlatBufferBuilder builder) {
    int o = builder.EndObject();
    return new Offset<TestTable1>(o);
  }
};

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser;

import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;

import org.chromium.base.CalledByNative;
import org.chromium.base.ThreadUtils;
import org.chromium.base.TraceEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

/**
 * This class is the Java counterpart to the C++ TtsPlatformImplAndroid class.
 * It implements the Android-native text-to-speech code to support the web
 * speech synthesis API.
 *
 * Threading model note: all calls from C++ must happen on the UI thread.
 * Callbacks from Android may happen on a different thread, so we always
 * use ThreadUtils.runOnUiThread when calling back to C++.
 */
class TtsPlatformImpl {
    private static class TtsVoice {
        private TtsVoice(String name, String language) {
            mName = name;
            mLanguage = language;
        }
        private final String mName;
        private final String mLanguage;
    }

    private static class PendingUtterance {
        private PendingUtterance(TtsPlatformImpl impl, int utteranceId, String text,
                String lang, float rate, float pitch, float volume) {
            mImpl = impl;
            mUtteranceId = utteranceId;
            mText = text;
            mLang = lang;
            mRate = rate;
            mPitch = pitch;
            mVolume = volume;
        }

        private void speak() {
            mImpl.speak(mUtteranceId, mText, mLang, mRate, mPitch, mVolume);
        }

        TtsPlatformImpl mImpl;
        int mUtteranceId;
        String mText;
        String mLang;
        float mRate;
        float mPitch;
        float mVolume;
    }

    private long mNativeTtsPlatformImplAndroid;
    protected final TextToSpeech mTextToSpeech;
    private boolean mInitialized;
    private ArrayList<TtsVoice> mVoices;
    private String mCurrentLanguage;
    private PendingUtterance mPendingUtterance;

    protected TtsPlatformImpl(long nativeTtsPlatformImplAndroid, Context context) {
        mInitialized = false;
        mNativeTtsPlatformImplAndroid = nativeTtsPlatformImplAndroid;
        mTextToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {
                    if (status == TextToSpeech.SUCCESS) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                initialize();
                            }
                        });
                    }
                }
            });
        addOnUtteranceProgressListener();
    }

    /**
     * Create a TtsPlatformImpl object, which is owned by TtsPlatformImplAndroid
     * on the C++ side.
     *
     * @param nativeTtsPlatformImplAndroid The C++ object that owns us.
     * @param context The app context.
     */
    @CalledByNative
    private static TtsPlatformImpl create(long nativeTtsPlatformImplAndroid,
                                          Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new LollipopTtsPlatformImpl(nativeTtsPlatformImplAndroid, context);
        } else {
            return new TtsPlatformImpl(nativeTtsPlatformImplAndroid, context);
        }
    }

    /**
     * Called when our C++ counterpoint is deleted. Clear the handle to our
     * native C++ object, ensuring it's never called.
     */
    @CalledByNative
    private void destroy() {
        mNativeTtsPlatformImplAndroid = 0;
    }

    /**
     * @return true if our TextToSpeech object is initialized and we've
     * finished scanning the list of voices.
     */
    @CalledByNative
    private boolean isInitialized() {
        return mInitialized;
    }

    /**
     * @return the number of voices.
     */
    @CalledByNative
    private int getVoiceCount() {
        assert mInitialized;
        return mVoices.size();
    }

    /**
     * @return the name of the voice at a given index.
     */
    @CalledByNative
    private String getVoiceName(int voiceIndex) {
        assert mInitialized;
        return mVoices.get(voiceIndex).mName;
    }

    /**
     * @return the language of the voice at a given index.
     */
    @CalledByNative
    private String getVoiceLanguage(int voiceIndex) {
        assert mInitialized;
        return mVoices.get(voiceIndex).mLanguage;
    }

    /**
     * Attempt to start speaking an utterance. If it returns true, will call back on
     * start and end.
     *
     * @param utteranceId A unique id for this utterance so that callbacks can be tied
     *     to a particular utterance.
     * @param text The text to speak.
     * @param lang The language code for the text (e.g., "en-US").
     * @param rate The speech rate, in the units expected by Android TextToSpeech.
     * @param pitch The speech pitch, in the units expected by Android TextToSpeech.
     * @param volume The speech volume, in the units expected by Android TextToSpeech.
     * @return true on success.
     */
    @CalledByNative
    private boolean speak(int utteranceId, String text, String lang,
                          float rate, float pitch, float volume) {
        if (!mInitialized) {
            mPendingUtterance = new PendingUtterance(this, utteranceId, text, lang, rate,
                    pitch, volume);
            return true;
        }
        if (mPendingUtterance != null) mPendingUtterance = null;

        if (!lang.equals(mCurrentLanguage)) {
            mTextToSpeech.setLanguage(new Locale(lang));
            mCurrentLanguage = lang;
        }

        mTextToSpeech.setSpeechRate(rate);
        mTextToSpeech.setPitch(pitch);

        int result = callSpeak(text, volume, utteranceId);
        return (result == TextToSpeech.SUCCESS);
    }

    /**
     * Stop the current utterance.
     */
    @CalledByNative
    private void stop() {
        if (mInitialized) mTextToSpeech.stop();
        if (mPendingUtterance != null) mPendingUtterance = null;
    }

    /**
     * Post a task to the UI thread to send the TTS "end" event.
     */
    protected void sendEndEventOnUiThread(final String utteranceId) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mNativeTtsPlatformImplAndroid != 0) {
                    nativeOnEndEvent(mNativeTtsPlatformImplAndroid, Integer.parseInt(utteranceId));
                }
            }
        });
    }

    /**
     * Post a task to the UI thread to send the TTS "error" event.
     */
    protected void sendErrorEventOnUiThread(final String utteranceId) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mNativeTtsPlatformImplAndroid != 0) {
                    nativeOnErrorEvent(mNativeTtsPlatformImplAndroid,
                            Integer.parseInt(utteranceId));
                }
            }
        });
    }

    /**
     * Post a task to the UI thread to send the TTS "start" event.
     */
    protected void sendStartEventOnUiThread(final String utteranceId) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mNativeTtsPlatformImplAndroid != 0) {
                    nativeOnStartEvent(mNativeTtsPlatformImplAndroid,
                            Integer.parseInt(utteranceId));
                }
            }
        });
    }

    /**
     * This is overridden by LollipopTtsPlatformImpl because the API changed.
     */
    @SuppressWarnings("deprecation")
    protected void addOnUtteranceProgressListener() {
        mTextToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onDone(final String utteranceId) {
                sendEndEventOnUiThread(utteranceId);
            }

            // This is deprecated in Lollipop and higher but we still need to catch it
            // on pre-Lollipop builds.
            @Override
            @SuppressWarnings("deprecation")
            public void onError(final String utteranceId) {
                sendErrorEventOnUiThread(utteranceId);
            }

            @Override
            public void onStart(final String utteranceId) {
                sendStartEventOnUiThread(utteranceId);
            }
        });
    }

    /**
     * This is overridden by LollipopTtsPlatformImpl because the API changed.
     */
    @SuppressWarnings("deprecation")
    protected int callSpeak(String text, float volume, int utteranceId) {
        HashMap<String, String> params = new HashMap<String, String>();
        if (volume != 1.0) {
            params.put(TextToSpeech.Engine.KEY_PARAM_VOLUME, Double.toString(volume));
        }
        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, Integer.toString(utteranceId));
        return mTextToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, params);
    }

    /**
     * Note: we enforce that this method is called on the UI thread, so
     * we can call nativeVoicesChanged directly.
     */
    private void initialize() {
        assert mNativeTtsPlatformImplAndroid != 0;

        TraceEvent.begin("TtsPlatformImpl:initialize");

        // Note: Android supports multiple speech engines, but querying the
        // metadata about all of them is expensive. So we deliberately only
        // support the default speech engine, and expose the different
        // supported languages for the default engine as different voices.
        String defaultEngineName = mTextToSpeech.getDefaultEngine();
        String engineLabel = defaultEngineName;
        for (TextToSpeech.EngineInfo info : mTextToSpeech.getEngines()) {
            if (info.name.equals(defaultEngineName)) engineLabel = info.label;
        }
        Locale[] locales = Locale.getAvailableLocales();
        mVoices = new ArrayList<TtsVoice>();
        for (int i = 0; i < locales.length; ++i) {
            if (!locales[i].getVariant().isEmpty()) continue;
            try {
                if (mTextToSpeech.isLanguageAvailable(locales[i]) > 0) {
                    String name = locales[i].getDisplayLanguage();
                    if (!locales[i].getCountry().isEmpty()) {
                        name += " " + locales[i].getDisplayCountry();
                    }
                    TtsVoice voice = new TtsVoice(name, locales[i].toString());
                    mVoices.add(voice);
                }
            } catch (java.util.MissingResourceException e) {
                // Just skip the locale if it's invalid.
            }
        }

        mInitialized = true;
        nativeVoicesChanged(mNativeTtsPlatformImplAndroid);

        if (mPendingUtterance != null) mPendingUtterance.speak();

        TraceEvent.end("TtsPlatformImpl:initialize");
    }

    private native void nativeVoicesChanged(long nativeTtsPlatformImplAndroid);
    private native void nativeOnEndEvent(long nativeTtsPlatformImplAndroid, int utteranceId);
    private native void nativeOnStartEvent(long nativeTtsPlatformImplAndroid, int utteranceId);
    private native void nativeOnErrorEvent(long nativeTtsPlatformImplAndroid, int utteranceId);
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('hs_modelinstance', '0002_auto_20150813_1345'),
        ('hs_modelinstance', '0002_auto_20150914_1902'),
    ]

    operations = [
    ]


text:
<?php

namespace Stuki\Form\Renderers;

use Stuki\Form;

class Insert extends Form {

    public function init() {

        // New renderer class input
        $alias = $this->createElement('text', 'alias');
        $alias->setLabel('Alias');
        $alias->addValidator('stringLength', false, array(1, 255));
        $alias->setDescription('An alias to display when selecting this renderer');
        $alias->setRequired(true);
        # FIXME:  add validator for regex not allowing leading \

        $alias->size = 35;
        $alias->maxlength = 255;
        $alias->tabindex = 1;

        $class = $this->createElement('text', 'class');
        $class->setLabel('Renderer');
        $class->addValidator('stringLength', false, array(1, 255));
        $class->setDescription('Enter the fully namespaced renderer class such as Stuki\Renderer\Date');
        # FIXME:  add validator for regex not allowing leading \

        $class->size = 35;
        $class->maxlength = 255;
        $class->tabindex = 2;

        $submit = $this->createElement('submit', 'submit');
        $submit->setLabel("Add");
        $submit->setIgnore(true);
        $submit->tabindex = 3;

        // Build the form
        $this->addElement($alias);
        $this->addElement($class);
        $this->addElement($submit);
    }
}


text:
<!-- TITLE/ -->

# [Benjamin Lupton's](http://balupton.com) Utility Functions

<!-- /TITLE -->

<!-- BADGES/ -->

[![Build Status](http://img.shields.io/travis-ci/balupton/bal-util.png?branch=master)](http://travis-ci.org/balupton/bal-util "Check this project's build status on TravisCI")
[![NPM version](http://badge.fury.io/js/bal-util.png)](https://npmjs.org/package/bal-util "View this project on NPM")
[![Dependency Status](https://david-dm.org/balupton/bal-util.png?theme=shields.io)](https://david-dm.org/balupton/bal-util)
[![Development Dependency Status](https://david-dm.org/balupton/bal-util/dev-status.png?theme=shields.io)](https://david-dm.org/balupton/bal-util#info=devDependencies)<br/>
[![Gittip donate button](http://img.shields.io/gittip/balupton.png)](https://www.gittip.com/balupton/ "Donate weekly to this project using Gittip")
[![Flattr donate button](http://img.shields.io/flattr/donate.png?color=yellow)](http://flattr.com/thing/344188/balupton-on-Flattr "Donate monthly to this project using Flattr")
[![PayPayl donate button](http://img.shields.io/paypal/donate.png?color=yellow)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QB8GQPZAH84N6 "Donate once-off to this project using Paypal")
[![BitCoin donate button](http://img.shields.io/bitcoin/donate.png?color=yellow)](https://coinbase.com/checkouts/9ef59f5479eec1d97d63382c9ebcb93a "Donate once-off to this project using BitCoin")

<!-- /BADGES -->

<!-- DESCRIPTION/ -->

Common utility functions for Node.js used and maintained by Benjamin Lupton

<!-- /DESCRIPTION -->

<!-- INSTALL/ -->

## Install

### [Node](http://nodejs.org/)
- Use: `require('bal-util')`
- Install: `npm install --save bal-util`

### [Browserify](http://browserify.org/)
- Use: `require('bal-util')`
- Install: `npm install --save bal-util`
- CDN URL: `//wzrd.in/bundle/bal-util@2.4.1`

### [Ender](http://ender.jit.su/)
- Use: `require('bal-util')`
- Install: `ender add bal-util`

<!-- /INSTALL -->

## Usage
Best off looking at source, it's well documented, and there are plenty of tests

## Future
We're in the process of abstracting the pieces of bal-util out into their own modules. So far, we've done the following:

- [ambi](https://github.com/bevry/ambi) < `balUtilFlow.fireWithOptionalCallback`
- [binaryextensions](https://github.com/bevry/binaryextensions) < `balUtilPaths.binaryExtensions`
- [eachr](https://github.com/bevry/eachr) < `balUtilFlow.each`
- [event-emitter-grouped](https://github.com/bevry/event-emitter-grouped) < `balUtilEvents.EventEmitterEnhanced`
- [extendr](https://github.com/bevry/extendr) < `balUtilFlow.(extend|clone|etc)`
- [extract-opts](https://github.com/bevry/extract-opts) < `balUtilFlow.extractOptsAndCallback`
- [getsetdeep](https://github.com/bevry/getsetdeep) < `balUtilFlow.(get|set)Deep`
- [ignorefs](https://github.com/bevry/ignorefs) < `balUtilPaths.isIgnoredPath`
- [ignorepatterns](https://github.com/bevry/ignorepatterns/blob/master/HISTORY.md) < `balUtilPaths.ignoreCommonPatterns`
- [istextorbinary](https://github.com/bevry/istextorbinary) < `balUtilPaths.(isTextSync|isText|getEncodingSync|getEncoding)`
- [safecallback](https://github.com/bevry/safecallback) < `balUtilFlow.safeCallback`
- [safefs](https://github.com/bevry/safefs) < `balUtilPaths.(openFile|closeFile|etc)`
- [safeps](https://github.com/bevry/safeps) < `balUtilModules`
- [taskgroup](https://github.com/bevry/taskgroup) < `balUtilFlow.Group`
- [textextensions](https://github.com/bevry/textextensions) < `balUtilPaths.textExtensions`
- [typechecker](https://github.com/bevry/typechecker) < `balUtilTypes`

<!-- CONTRIBUTE/ -->

## Contribute

[Discover how you can contribute by heading on over to the `CONTRIBUTING.md` file.](https://github.com/balupton/bal-util/blob/master/CONTRIBUTING.md#files)

<!-- /CONTRIBUTE -->

<!-- HISTORY/ -->

## History
[Discover the change history by heading on over to the `HISTORY.md` file.](https://github.com/balupton/bal-util/blob/master/HISTORY.md#files)

<!-- /HISTORY -->

<!-- BACKERS/ -->

## Backers

### Maintainers

These amazing people are maintaining this project:

- Benjamin Lupton <b@lupton.cc> (https://github.com/balupton)

### Sponsors

No sponsors yet! Will you be the first?

[![Gittip donate button](http://img.shields.io/gittip/balupton.png)](https://www.gittip.com/balupton/ "Donate weekly to this project using Gittip")
[![Flattr donate button](http://img.shields.io/flattr/donate.png?color=yellow)](http://flattr.com/thing/344188/balupton-on-Flattr "Donate monthly to this project using Flattr")
[![PayPayl donate button](http://img.shields.io/paypal/donate.png?color=yellow)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QB8GQPZAH84N6 "Donate once-off to this project using Paypal")
[![BitCoin donate button](http://img.shields.io/bitcoin/donate.png?color=yellow)](https://coinbase.com/checkouts/9ef59f5479eec1d97d63382c9ebcb93a "Donate once-off to this project using BitCoin")

### Contributors

These amazing people have contributed code to this project:

- [Benjamin Lupton](https://github.com/balupton) <b@lupton.cc> — [view contributions](https://github.com/balupton/bal-util/commits?author=balupton)
- [Sean Fridman](https://github.com/sfrdmn) <fridman@mail.sfsu.edu> — [view contributions](https://github.com/balupton/bal-util/commits?author=sfrdmn)

[Become a contributor!](https://github.com/balupton/bal-util/blob/master/CONTRIBUTING.md#files)

<!-- /BACKERS -->

<!-- LICENSE/ -->

## License

Licensed under the incredibly [permissive](http://en.wikipedia.org/wiki/Permissive_free_software_licence) [MIT license](http://creativecommons.org/licenses/MIT/)

Copyright © 2011+ Benjamin Lupton <b@lupton.cc> (http://balupton.com)

<!-- /LICENSE -->


text:
package pl.polak.designpattern.command.impl;

import pl.polak.designpattern.command.FileReceiver;

import java.io.File;

/**
 * User: marcin
 * Date: 26.11.13
 * Time: 21:01
 */
public class UnixFileReceiver implements FileReceiver {

    @Override
    public void openFile(String fileName) {
        System.out.println("UNIX: Open file: " + fileName);
    }

    @Override
    public void closeFile() {
        System.out.println("UNIX: Closing file.");
    }
}


text:
'use strict';

/** @param {import('puppeteer').Browser} */
module.exports = async browser => {
  const page = await browser.newPage();
  await page.goto('http://localhost:52426/login');
};


text:
package org.apache.solr.update;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.common.cloud.CompositeIdRouter;
import org.apache.solr.common.cloud.DocRouter;
import org.apache.solr.common.cloud.PlainIdRouter;
import org.apache.solr.common.util.Hash;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.DirectoryFactory;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.common.collect.Lists;
import java.nio.charset.StandardCharsets;

public class SolrIndexSplitterTest extends SolrTestCaseJ4 {
  File indexDir1 = null, indexDir2 = null, indexDir3 = null;

  @BeforeClass
  public static void beforeClass() throws Exception {
    System.setProperty("enable.update.log", "false"); // schema12 doesn't support _version_
    initCore("solrconfig.xml", "schema12.xml");
  }

  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    clearIndex();
    assertU(commit());
    indexDir1 = createTempDir("_testSplit1");
    indexDir2 = createTempDir("_testSplit2");
    indexDir3 = createTempDir("_testSplit3");
  }

  @Test
  public void testSplitByPaths() throws Exception {
    LocalSolrQueryRequest request = null;
    try {
      // add two docs
      String id1 = "dorothy";
      assertU(adoc("id", id1));
      String id2 = "kansas";
      assertU(adoc("id", id2));
      assertU(commit());
      assertJQ(req("q", "*:*"), "/response/numFound==2");

      // find minHash/maxHash hash ranges
      List<DocRouter.Range> ranges = getRanges(id1, id2);

      request = lrf.makeRequest("q", "dummy");

      SplitIndexCommand command = new SplitIndexCommand(request,
          Lists.newArrayList(indexDir1.getAbsolutePath(), indexDir2.getAbsolutePath()), null, ranges, new PlainIdRouter(), null, null);
      new SolrIndexSplitter(command).split();

      Directory directory = h.getCore().getDirectoryFactory().get(indexDir1.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      DirectoryReader reader = DirectoryReader.open(directory);
      assertEquals("id:dorothy should be present in split index1", 1, reader.docFreq(new Term("id", "dorothy")));
      assertEquals("id:kansas should not be present in split index1", 0, reader.docFreq(new Term("id", "kansas")));
      assertEquals("split index1 should have only one document", 1, reader.numDocs());
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
      directory = h.getCore().getDirectoryFactory().get(indexDir2.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      reader = DirectoryReader.open(directory);
      assertEquals("id:dorothy should not be present in split index2", 0, reader.docFreq(new Term("id", "dorothy")));
      assertEquals("id:kansas should be present in split index2", 1, reader.docFreq(new Term("id", "kansas")));
      assertEquals("split index2 should have only one document", 1, reader.numDocs());
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
    } finally {
      if (request != null) request.close(); // decrefs the searcher
    }
  }

  // SOLR-5144
  public void testSplitDeletes() throws Exception {
    LocalSolrQueryRequest request = null;
    try {
      // add two docs
      String id1 = "dorothy";
      assertU(adoc("id", id1));
      String id2 = "kansas";
      assertU(adoc("id", id2));
      assertU(commit());
      assertJQ(req("q", "*:*"), "/response/numFound==2");
      assertU(delI(id2)); // delete id2
      assertU(commit());

      // find minHash/maxHash hash ranges
      List<DocRouter.Range> ranges = getRanges(id1, id2);

      request = lrf.makeRequest("q", "dummy");

      SplitIndexCommand command = new SplitIndexCommand(request,
          Lists.newArrayList(indexDir1.getAbsolutePath(), indexDir2.getAbsolutePath()), null, ranges, new PlainIdRouter(), null, null);
      new SolrIndexSplitter(command).split();

      Directory directory = h.getCore().getDirectoryFactory().get(indexDir1.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      DirectoryReader reader = DirectoryReader.open(directory);
      assertEquals("id:dorothy should be present in split index1", 1, reader.docFreq(new Term("id", "dorothy")));
      assertEquals("id:kansas should not be present in split index1", 0, reader.docFreq(new Term("id", "kansas")));
      assertEquals("split index1 should have only one document", 1, reader.numDocs());
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
      directory = h.getCore().getDirectoryFactory().get(indexDir2.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      reader = DirectoryReader.open(directory);
      assertEquals(0, reader.numDocs()); // should be empty
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
    } finally {
      if (request != null) request.close(); // decrefs the searcher
    }
  }

  @Test
  public void testSplitByCores() throws Exception {
    // add two docs
    String id1 = "dorothy";
    assertU(adoc("id", id1));
    String id2 = "kansas";
    assertU(adoc("id", id2));
    assertU(commit());
    assertJQ(req("q", "*:*"), "/response/numFound==2");
    List<DocRouter.Range> ranges = getRanges(id1, id2);

    SolrCore core1 = null, core2 = null;
    try {
      String instanceDir = h.getCore().getCoreDescriptor().getInstanceDir();

      CoreDescriptor dcore1 = buildCoreDescriptor(h.getCoreContainer(), "split1", instanceDir)
          .withDataDir(indexDir1.getAbsolutePath()).withSchema("schema12.xml").build();
      if (h.getCoreContainer().getZkController() != null) {
        h.getCoreContainer().preRegisterInZk(dcore1);
      }
      core1 = h.getCoreContainer().create(dcore1);
      h.getCoreContainer().register(core1, false);

      CoreDescriptor dcore2 = buildCoreDescriptor(h.getCoreContainer(), "split2", instanceDir)
          .withDataDir(indexDir2.getAbsolutePath()).withSchema("schema12.xml").build();
      if (h.getCoreContainer().getZkController() != null) {
        h.getCoreContainer().preRegisterInZk(dcore2);
      }
      core2 = h.getCoreContainer().create(dcore2);
      h.getCoreContainer().register(core2, false);

      LocalSolrQueryRequest request = null;
      try {
        request = lrf.makeRequest("q", "dummy");

        SplitIndexCommand command = new SplitIndexCommand(request, null, Lists.newArrayList(core1, core2), ranges, new PlainIdRouter(), null, null);
        new SolrIndexSplitter(command).split();
      } finally {
        if (request != null) request.close();
      }
      EmbeddedSolrServer server1 = new EmbeddedSolrServer(h.getCoreContainer(), "split1");
      EmbeddedSolrServer server2 = new EmbeddedSolrServer(h.getCoreContainer(), "split2");
      server1.commit(true, true);
      server2.commit(true, true);
      assertEquals("id:dorothy should be present in split index1", 1, server1.query(new SolrQuery("id:dorothy")).getResults().getNumFound());
      assertEquals("id:kansas should not be present in split index1", 0, server1.query(new SolrQuery("id:kansas")).getResults().getNumFound());
      assertEquals("id:dorothy should not be present in split index2", 0, server2.query(new SolrQuery("id:dorothy")).getResults().getNumFound());
      assertEquals("id:kansas should be present in split index2", 1, server2.query(new SolrQuery("id:kansas")).getResults().getNumFound());
    } finally {
      h.getCoreContainer().remove("split2");
      h.getCoreContainer().remove("split1");
      if (core2 != null) core2.close();
      if (core1 != null) core1.close();
    }
  }

  @Test
  public void testSplitAlternately() throws Exception {
    LocalSolrQueryRequest request = null;
    Directory directory = null;
    try {
      // add an even number of docs
      int max = (1 + random().nextInt(10)) * 3;
      log.info("Adding {} number of documents", max);
      for (int i = 0; i < max; i++) {
        assertU(adoc("id", String.valueOf(i)));
      }
      assertU(commit());

      request = lrf.makeRequest("q", "dummy");

      SplitIndexCommand command = new SplitIndexCommand(request,
          Lists.newArrayList(indexDir1.getAbsolutePath(), indexDir2.getAbsolutePath(), indexDir3.getAbsolutePath()), null, null, new PlainIdRouter(), null, null);
      new SolrIndexSplitter(command).split();

      directory = h.getCore().getDirectoryFactory().get(indexDir1.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      DirectoryReader reader = DirectoryReader.open(directory);
      assertEquals("split index1 has wrong number of documents", max / 3, reader.numDocs());
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
      directory = h.getCore().getDirectoryFactory().get(indexDir2.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      reader = DirectoryReader.open(directory);
      assertEquals("split index2 has wrong number of documents", max / 3, reader.numDocs());
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
      directory = h.getCore().getDirectoryFactory().get(indexDir3.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      reader = DirectoryReader.open(directory);
      assertEquals("split index3 has wrong number of documents", max / 3, reader.numDocs());
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
      directory = null;
    } finally {
      if (request != null) request.close(); // decrefs the searcher
      if (directory != null)  {
        // perhaps an assert failed, release the directory
        h.getCore().getDirectoryFactory().release(directory);
      }
    }
  }

  @Test
  public void testSplitByRouteKey() throws Exception  {
    File indexDir = createTempDir();

    CompositeIdRouter r1 = new CompositeIdRouter();
    String splitKey = "sea-line!";
    String key2 = "soul-raising!";

    // murmur2 has a collision on the above two keys
    assertEquals(r1.keyHashRange(splitKey), r1.keyHashRange(key2));

    /*
    More strings with collisions on murmur2 for future reference:
    "Drava" "dessert spoon"
    "Bighorn" "pleasure lover"
    "attributable to" "second edition"
    "sea-line" "soul-raising"
    "lift direction" "testimony meeting"
     */

    for (int i=0; i<10; i++)  {
      assertU(adoc("id", splitKey + i));
      assertU(adoc("id", key2 + i));
    }
    assertU(commit());
    assertJQ(req("q", "*:*"), "/response/numFound==20");

    DocRouter.Range splitKeyRange = r1.keyHashRange(splitKey);

    LocalSolrQueryRequest request = null;
    Directory directory = null;
    try {
      request = lrf.makeRequest("q", "dummy");
      SplitIndexCommand command = new SplitIndexCommand(request,
          Lists.newArrayList(indexDir.getAbsolutePath()), null, Lists.newArrayList(splitKeyRange), new CompositeIdRouter(), null, splitKey);
      new SolrIndexSplitter(command).split();
      directory = h.getCore().getDirectoryFactory().get(indexDir.getAbsolutePath(),
          DirectoryFactory.DirContext.DEFAULT, h.getCore().getSolrConfig().indexConfig.lockType);
      DirectoryReader reader = DirectoryReader.open(directory);
      assertEquals("split index has wrong number of documents", 10, reader.numDocs());
      reader.close();
      h.getCore().getDirectoryFactory().release(directory);
      directory = null;
    } finally {
      if (request != null)  {
        request.close();
      }
      if (directory != null)  {
        h.getCore().getDirectoryFactory().release(directory);
      }
    }
  }

  private List<DocRouter.Range> getRanges(String id1, String id2) throws UnsupportedEncodingException {
    // find minHash/maxHash hash ranges
    byte[] bytes = id1.getBytes(StandardCharsets.UTF_8);
    int minHash = Hash.murmurhash3_x86_32(bytes, 0, bytes.length, 0);
    bytes = id2.getBytes(StandardCharsets.UTF_8);
    int maxHash = Hash.murmurhash3_x86_32(bytes, 0, bytes.length, 0);

    if (minHash > maxHash)  {
      int temp = maxHash;
      maxHash = minHash;
      minHash = temp;
    }

    PlainIdRouter router = new PlainIdRouter();
    DocRouter.Range fullRange = new DocRouter.Range(minHash, maxHash);
    return router.partitionRange(2, fullRange);
  }
}


text:
package collide.shared.collect;

import elemental.js.util.JsArrayOf;
import elemental.js.util.JsArrayOfString;
import elemental.util.ArrayOf;
import elemental.util.ArrayOfString;
import elemental.util.impl.JreArrayOfString;
import xapi.log.X_Log;

import com.google.gwt.reflect.shared.GwtReflect;

import java.util.Iterator;

public class ArrayOfStringIterable implements Iterable<String> {

  ArrayOf<String> array;

  public ArrayOfStringIterable(ArrayOfString strings) {
    if (strings == null) {
      throw new NullPointerException("Strings array cannot be null");
    }
    if (strings instanceof JsArrayOfString) {
      array = ((JsArrayOfString) strings).<JsArrayOf<String>>cast();
    } else {
      try {
        array = GwtReflect.fieldGet(JreArrayOfString.class, "array", strings);
      } catch (Exception e) {
        X_Log.error("Could not get inner array field of "+strings.getClass(), e);
      }
    }
  }

  @Override
  public Iterator<String> iterator() {
    return new ArrayOfIterator<String>(array);
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 Copyright 2003 - 2011 The eFaps Team

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 Author:          The eFaps Team
 Revision:        $Rev$
 Last Changed:    $Date$
 Last Changed By: $Author$

-->

<datamodel-type  xmlns="http://www.efaps.org/xsd"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>dff29743-ed7d-4cca-83a4-2c140777a752</uuid>
    <file-application>eFapsApp-Archives</file-application>
    <file-revision>$Rev$</file-revision>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Archives_Object2ArchiveAbstract</name>
        <purpose abstract="true"/>
        <attribute>
            <name>Type</name>
            <type>Type</type>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>TYPEID</sqlcolumn>
        </attribute>
        <attribute>
            <name>OID</name>
            <type>OID</type>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>TYPEID,ID</sqlcolumn>
        </attribute>
        <attribute>
            <name>ID</name>
            <type>Long</type>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>ID</sqlcolumn>
        </attribute>
        <attribute>
            <name>ToLinkAbstract</name>
            <type>Link</type>
            <typelink>Archives_ArchiveAbstract</typelink>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>TOID</sqlcolumn>
        </attribute>
        <attribute>
            <name>Creator</name>
            <type>CreatorLink</type>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>CREATOR</sqlcolumn>
        </attribute>
        <attribute>
            <name>Created</name>
            <type>Created</type>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>CREATED</sqlcolumn>
        </attribute>
        <attribute>
            <name>Modifier</name>
            <type>ModifierLink</type>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>MODIFIER</sqlcolumn>
        </attribute>
        <attribute>
            <name>Modified</name>
            <type>Modified</type>
            <sqltable>Archives_Object2ArchiveAbstractSQLTable</sqltable>
            <sqlcolumn>MODIFIED</sqlcolumn>
        </attribute>
    </definition>
</datamodel-type>


text:
To build dependencies for the current arch+OS:

    make

To build for another arch/OS:

    make HOST=host-platform-triplet

For example:

    make HOST=x86_64-w64-mingw32 -j4

**Bitcoin Core's `configure` script by default will ignore the depends output.** In
order for it to pick up libraries, tools, and settings from the depends build,
you must set the `CONFIG_SITE` environment variable to point to a `config.site` settings file.
In the above example, a file named `depends/x86_64-w64-mingw32/share/config.site` will be
created. To use it during compilation:

    CONFIG_SITE=$PWD/depends/x86_64-w64-mingw32/share/config.site ./configure

The default install prefix when using `config.site` is `--prefix=depends/<host-platform-triplet>`,
so depends build outputs will be installed in that location.

Common `host-platform-triplet`s for cross compilation are:

- `i686-pc-linux-gnu` for Linux 32 bit
- `x86_64-pc-linux-gnu` for x86 Linux
- `x86_64-w64-mingw32` for Win64
- `x86_64-apple-darwin` for macOS
- `arm64-apple-darwin` for ARM macOS
- `arm-linux-gnueabihf` for Linux ARM 32 bit
- `aarch64-linux-gnu` for Linux ARM 64 bit
- `powerpc64-linux-gnu` for Linux POWER 64-bit (big endian)
- `powerpc64le-linux-gnu` for Linux POWER 64-bit (little endian)
- `riscv32-linux-gnu` for Linux RISC-V 32 bit
- `riscv64-linux-gnu` for Linux RISC-V 64 bit
- `s390x-linux-gnu` for Linux S390X
- `armv7a-linux-android` for Android ARM 32 bit
- `aarch64-linux-android` for Android ARM 64 bit
- `x86_64-linux-android` for Android x86 64 bit

The paths are automatically configured and no other options are needed unless targeting [Android](../doc/build-android.md).

### Install the required dependencies: Ubuntu & Debian

#### For macOS cross compilation

    sudo apt-get install curl bsdmainutils cmake libz-dev python3-setuptools libtinfo5 xorriso

Note: You must obtain the macOS SDK before proceeding with a cross-compile.
Under the depends directory, create a subdirectory named `SDKs`.
Then, place the extracted SDK under this new directory.
For more information, see [SDK Extraction](../contrib/macdeploy/README.md#sdk-extraction).

#### For Win64 cross compilation

- see [build-windows.md](../doc/build-windows.md#cross-compilation-for-ubuntu-and-windows-subsystem-for-linux)

#### For linux (including i386, ARM) cross compilation

Common linux dependencies:

    sudo apt-get install make automake cmake curl g++-multilib libtool binutils-gold bsdmainutils pkg-config python3 patch bison

For linux ARM cross compilation:

    sudo apt-get install g++-arm-linux-gnueabihf binutils-arm-linux-gnueabihf

For linux AARCH64 cross compilation:

    sudo apt-get install g++-aarch64-linux-gnu binutils-aarch64-linux-gnu

For linux POWER 64-bit cross compilation (there are no packages for 32-bit):

    sudo apt-get install g++-powerpc64-linux-gnu binutils-powerpc64-linux-gnu g++-powerpc64le-linux-gnu binutils-powerpc64le-linux-gnu

For linux RISC-V 64-bit cross compilation (there are no packages for 32-bit):

    sudo apt-get install g++-riscv64-linux-gnu binutils-riscv64-linux-gnu

For linux S390X cross compilation:

    sudo apt-get install g++-s390x-linux-gnu binutils-s390x-linux-gnu

### Dependency Options

The following can be set when running make: `make FOO=bar`

- `SOURCES_PATH`: Downloaded sources will be placed here
- `BASE_CACHE`: Built packages will be placed here
- `SDK_PATH`: Path where SDKs can be found (used by macOS)
- `FALLBACK_DOWNLOAD_PATH`: If a source file can't be fetched, try here before giving up
- `NO_QT`: Don't download/build/cache Qt and its dependencies
- `NO_QR`: Don't download/build/cache packages needed for enabling qrencode
- `NO_ZMQ`: Don't download/build/cache packages needed for enabling ZeroMQ
- `NO_WALLET`: Don't download/build/cache libs needed to enable the wallet
- `NO_BDB`: Don't download/build/cache BerkeleyDB
- `NO_SQLITE`: Don't download/build/cache SQLite
- `NO_UPNP`: Don't download/build/cache packages needed for enabling UPnP
- `NO_NATPMP`: Don't download/build/cache packages needed for enabling NAT-PMP</dd>
- `ALLOW_HOST_PACKAGES`: Packages that are missed in dependencies (due to `NO_*` option or
  build script logic) are searched for among the host system packages using
  `pkg-config`. It allows building with packages of other (newer) versions
- `MULTIPROCESS`: Build libmultiprocess (experimental, requires CMake)
- `DEBUG`: Disable some optimizations and enable more runtime checking
- `HOST_ID_SALT`: Optional salt to use when generating host package ids
- `BUILD_ID_SALT`: Optional salt to use when generating build package ids
- `FORCE_USE_SYSTEM_CLANG`: (EXPERTS ONLY) When cross-compiling for macOS, use Clang found in the
  system's `$PATH` rather than the default prebuilt release of Clang
  from llvm.org. Clang 8 or later is required.

If some packages are not built, for example `make NO_WALLET=1`, the appropriate
options will be passed to bitcoin's configure. In this case, `--disable-wallet`.

### Additional targets

    download: run 'make download' to fetch all sources without building them
    download-osx: run 'make download-osx' to fetch all sources needed for macOS builds
    download-win: run 'make download-win' to fetch all sources needed for win builds
    download-linux: run 'make download-linux' to fetch all sources needed for linux builds

### Other documentation

- [description.md](description.md): General description of the depends system
- [packages.md](packages.md): Steps for adding packages


text:
<?php

use Symfony\Component\Debug\Debug;

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || isset($_SERVER['REMOTE_ADDR']) && !in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1'), true)
) {
    header('HTTP/1.0 403 Forbidden');
    echo 'You are not allowed to access this file. Check '.basename(__FILE__).' for more information.';
    return;
}

require_once __DIR__.'/../vendor/autoload.php';

Debug::enable();

$app = require __DIR__.'/../src/app.php';
require __DIR__.'/../config/dev.php';
require __DIR__.'/../src/controllers.php';
$app->run();


text:
ActiveRecord::Schema.define(version: 20151117134636) do

  create_table "tweets", force: :cascade do |t|
    t.text     "content",    null: false
    t.text     "hashtags"
    t.text     "links"
    t.text     "mentions"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "tweets", ["user_id"], name: "index_tweets_on_user_id"

  create_table "user_sessions", force: :cascade do |t|
    t.string   "session_id", null: false
    t.text     "data"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "login",                         null: false
    t.string   "nicename",                      null: false
    t.string   "email",                         null: false
    t.string   "email_md5"
    t.string   "crypted_password",              null: false
    t.string   "password_salt",                 null: false
    t.string   "persistence_token",             null: false
    t.integer  "login_count",       default: 0, null: false
    t.datetime "last_request_at"
    t.datetime "last_login_at"
    t.datetime "current_login_at"
    t.string   "last_login_ip"
    t.string   "current_login_ip"
    t.datetime "created_at",                    null: false
    t.datetime "updated_at",                    null: false
  end

end


text:
<?php

namespace Concrete\Core\Updater\Migrations\Migrations;

use Concrete\Core\Updater\Migrations\AbstractMigration;
use Concrete\Core\Updater\Migrations\RepeatableMigrationInterface;
use Doctrine\DBAL\Schema\Schema;

class Version20150731000000 extends AbstractMigration implements RepeatableMigrationInterface
{
    /**
     * {@inheritdoc}
     *
     * @see \Doctrine\Migrations\AbstractMigration::getDescription()
     */
    public function getDescription(): string
    {
        return '5.7.5.2';
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Updater\Migrations\AbstractMigration::upgradeSchema()
     */
    public function upgradeSchema(Schema $schema)
    {
        try {
            $table = $schema->getTable('SystemDatabaseQueryLog');
            $table->addColumn('ID', 'integer', ['unsigned' => true, 'autoincrement' => true]);
            $table->setPrimaryKey(['ID']);
        } catch (\Exception $e) {
        }
    }

    /**
     * {@inheritdoc}
     *
     * @see \Concrete\Core\Updater\Migrations\AbstractMigration::upgradeDatabase()
     */
    public function upgradeDatabase()
    {
        $db = \Database::connection();
        $db->executeQuery('DELETE FROM FileSetFiles WHERE fID NOT IN (SELECT fID FROM Files)');
        $db->executeQuery('DELETE FROM FileSearchIndexAttributes WHERE fID NOT IN (SELECT fID FROM Files)');
        $db->executeQuery('DELETE FROM DownloadStatistics WHERE fID NOT IN (SELECT fID FROM Files)');
        $db->executeQuery('DELETE FROM FilePermissionAssignments WHERE fID NOT IN (SELECT fID FROM Files)');

        $this->refreshBlockType('page_list');
    }
}


text:
int main(int argc, char* argv[] ) {

	//Print Allocated Memory
	printf("Average memory which is allocated: %lu \n",get_total_alloc_mem_syscall_wrapper());

	//Print Free Memory
	printf("Average memory which is free: %lu \n", get_total_free_mem_syscall_wrapper());

	return 0;
}


text:
// Dependencies
const fs = require('fs');
const through = require('through2');
const path = require('path');
const md5 = require('md5');
const chalk = require('chalk');

const assetCache = {
  cacheFile: {},
  currentCache: {},
  cacheName: false,

  filter(cacheName) {
    // Set default cache if not specified
    assetCache.cacheName = cacheName || './.asset-cache';

    // Try to load an existing cache file
    try {
      assetCache.cacheFile = JSON.parse(fs.readFileSync(assetCache.cacheName));
    } catch (err) {
      assetCache.cacheFile = {};
    }

    /**
     * Update the current cache and filter out cached files
     * @param {object} file - A vinyl file
     * @param {string} encoding - Encoding
     * @param {function} cb - Callback
     */
    return through.obj(function (file, enc, cb) {
      if (file.isNull()) {
        return cb();
      }

      if (file.isStream()) {
        this.emit('error', new Error('Streaming not supported in gulp-asset-cache'));
        return cb();
      }

      if (file.isBuffer()) {
        const relativePath = path.relative(process.cwd(), `${path.dirname(file.path)}/${path.basename(file.path)}`);
        const hash = md5(relativePath + file.stat.size);

        // Update cache object
        assetCache.currentCache[relativePath] = hash;

        if (assetCache.cacheFile[relativePath] === assetCache.currentCache[relativePath]) {
          console.log(`gulp-asset-cache: ${chalk.green('✔')} ${relativePath} ${chalk.grey('(cached)')}`);
        } else {
          console.log(`gulp-asset-cache: ${chalk.red('✖')} ${relativePath} ${chalk.grey('(uncached)')}`);
          this.push(file);
        }
      }
      return cb();
    });
  },

  cache() {
    /**
     * Update the current with changed files
     * @param {object} file - A vinyl file
     * @param {string} encoding - Encoding
     * @param {function} cb - Callback
     */
    function transform(file, enc, cb) {
      const self = this;
      const relativePath = path.relative(process.cwd(), `${path.dirname(file.path)}/${path.basename(file.path)}`);

      fs.stat(file.path, function callback(err, stats) {
        if (err) this.emit('error', new Error(err));
        // Update Cache
        const hash = md5(relativePath + stats.size);
        assetCache.currentCache[relativePath] = hash;
        self.push(file);
        return cb();
      });
    }

    /**
     * Flush updated cache file to disk
     * @param {function} cb - Callback
     */
    function flush(cb) {
      fs.writeFile(assetCache.cacheName, JSON.stringify(assetCache.currentCache, null, 4), cb);
    }

    return through.obj(transform, flush);
  }
};

// Exports
module.exports = assetCache;


text:
import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, text_output

@click.command('repository_revisions')
@click.option(
    "--downloadable",
    help="Can the tool be downloaded",
    is_flag=True
)
@click.option(
    "--malicious",
    help="",
    is_flag=True
)
@click.option(
    "--tools_functionally_correct",
    help="",
    is_flag=True
)
@click.option(
    "--missing_test_components",
    help="",
    is_flag=True
)
@click.option(
    "--do_not_test",
    help="",
    is_flag=True
)
@click.option(
    "--includes_tools",
    help="",
    is_flag=True
)
@click.option(
    "--test_install_error",
    help="",
    is_flag=True
)
@click.option(
    "--skip_tool_test",
    help="",
    is_flag=True
)
@pass_context
@custom_exception
@text_output
def cli(ctx, downloadable="", malicious="", tools_functionally_correct="", missing_test_components="", do_not_test="", includes_tools="", test_install_error="", skip_tool_test=""):
    """Returns a (possibly filtered) list of dictionaries that include information about all repository revisions. The following parameters can be used to filter the list.

Output:

    Returns a (possibly filtered) list of dictionaries that include
          information about all repository revisions.
          For example::

            [{'changeset_revision': '6e26c5a48e9a',
              'do_not_test': False,
              'downloadable': True,
              'has_repository_dependencies': False,
              'id': '92250afff777a169',
              'includes_datatypes': False,
              'includes_tool_dependencies': False,
              'includes_tools': True,
              'includes_tools_for_display_in_tool_panel': True,
              'includes_workflows': False,
              'malicious': False,
              'missing_test_components': False,
              'repository_id': '78f2604ff5e65707',
              'test_install_error': False,
              'time_last_tested': None,
              'tools_functionally_correct': False,
              'url': '/api/repository_revisions/92250afff777a169'},
             {'changeset_revision': '15a54fa11ad7',
              'do_not_test': False,
              'downloadable': True,
              'has_repository_dependencies': False,
              'id': 'd3823c748ae2205d',
              'includes_datatypes': False,
              'includes_tool_dependencies': False,
              'includes_tools': True,
              'includes_tools_for_display_in_tool_panel': True,
              'includes_workflows': False,
              'malicious': False,
              'missing_test_components': False,
              'repository_id': 'f9662009da7bfce0',
              'test_install_error': False,
              'time_last_tested': None,
              'tools_functionally_correct': False,
              'url': '/api/repository_revisions/d3823c748ae2205d'}]
    """
    return ctx.ti.repositories.repository_revisions(downloadable=downloadable, malicious=malicious, tools_functionally_correct=tools_functionally_correct, missing_test_components=missing_test_components, do_not_test=do_not_test, includes_tools=includes_tools, test_install_error=test_install_error, skip_tool_test=skip_tool_test)


text:
public class EarthMonument : Monument
{
    private int earthAffinity;

    public EarthMonument(string name, int earthAffinity)
        : base(name)
    {
        this.earthAffinity = earthAffinity;
    }

    public int EarthAffinity
    {
        get { return this.earthAffinity; }
        set { this.earthAffinity = value; }
    }

    public override int GetAffinity() => this.EarthAffinity;

    public override string ToString() => $"{base.ToString()}, Earth Affinity: {this.EarthAffinity}";
}


text:
package com.amay077.android.gms.maps.google.v2;

import hu.akarnokd.reactive4java.base.Action1;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.amay077.android.collections.Lambda;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MarkerOverlay extends Overlay {
	private Map<String, Marker> _markers = new HashMap<String, Marker>();

	public void add(String id, MarkerOptions markerOptions) {
		Marker marker = _map.get().addMarker(markerOptions);
		_markers.put(id, marker);
	}

	@Override
	protected void onVisibleChanged(final boolean visible) {
		Lambda.iter(_markers.values(), new Action1<Marker>() {
			@Override
			public void invoke(Marker m) {
				m.setVisible(visible);
			}
		});
	}

	public void clear() {
		Lambda.iter(_markers.values(), new Action1<Marker>() {
			@Override
			public void invoke(Marker m) {
				m.remove();
			}
		});
		_markers.clear();
	}

	public Marker get(String id) {
		return _markers.get(id);
	}

	public Iterable<Marker> items() {
		return Collections.unmodifiableCollection(_markers.values());
	}

	public int size() {
		return _markers.size();
	}
}


text:
PyMOL4RNA
=========

## PyMOL4Spliceosome: all spliceosome structures in one PyMOL session

![](doc/pymol4spliceosome.png)

See releases for PyMOL sessions: https://github.com/mmagnus/PyMOL4Spliceosome

Quick ref:

	PyMOL>enable CWC15*
	PyMOL>disable CWC15*

You can also download sessions for single steps prepared by the Nagai lab: <https://www2.mrc-lmb.cam.ac.uk/groups/nagai/resources/>

Read more: https://pymolwiki.org/index.php/Enable

## Example: Color-coding for RNA Puzzles

To get:

![rna](doc/rna.png)

(install the plugin) and run:

	PyMOL>rp
	PyMOL>rp17

The source of the pdb: <http://www.rcsb.org/pdb/explore/explore.do?structureId=5K7C> see also `test_data/5k7c_clean.pdb`

## Install

See the docs, https://rna-tools.readthedocs.io/en/latest/pymol4rna.html#install

## One-time load of the functions
(less complicated than install, but you have to do it each time, it's better to properly install the package).

To load the functions of PyMOL4RNA.py, type `run <path to the file of PyMOL4RNA.py>` into the PyMOL console.

In my case, this will be [1]:

![rna](doc/run.png)

OK, now the functions are loaded into PyMOL. Unfortunately, you have to type run each time when you open and close PyMOL. If you want this to be loaded at the start of PyMOL see the Install section.

Now we can open a PDB file and color spliceosomal proteins. The way how it works at the moment is a bit hacky. The function `spl color` reads the name of the object (like in this case 5zwo) in your PyMOL session and based on that, the function colors the chains according to the rules encoded in the function.

At the moment, the following structure can be colored with the PyMOL4RNA: (1) complex B (5zwo), (2) complex Bact (5gm6), (3) complex C (5lj3), (4) C* (5mps), (5) complex P (6exn), and (6) ILS (5y88). To learn more about these structures, see the review (Zhang, & Zhao, 2019).

Chains and colors can be found here pyMoL_colors-EMX.xlsx.

![rna](doc/spl.png)

The structure ready to use with the function can be download from [here](https://www.dropbox.com/s/jz4qoqu6p8mfhof/spls.zip?dl=0).

    [1] run /Users/magnus/work-src/rna-tools/rna_tools/tools/PyMOL4RNA/PyMOL4RNA.py

Zhang, L., Vielle, A., Espinosa, S., & Zhao, R. (2019). RNAs in the spliceosome: Insight from cryoEM structures. Wiley Interdisciplinary Reviews: RNA, 10(3), e1523–11. http://doi.org/10.1002/wrna.1523


text:
'use strict';

const assert = require('./../../assert');
const common = require('./../../common');

let battle;

describe('Flower Gift', function () {
	afterEach(function () {
		battle.destroy();
	});

	it('should boost allies\' Attack and Special Defense stats', function () {
		battle = common.createBattle({gameType: 'doubles'}, [
			[{species: "Cherrim", ability: 'flowergift', moves: ['healbell']}, {species: "Snorlax", ability: 'immunity', moves: ['healbell']}],
			[{species: "Blissey", ability: 'serenegrace', moves: ['healbell']}, {species: "Blissey", ability: 'serenegrace', moves: ['healbell']}],
		]);

		let cherAtk = battle.p1.active[0].getStat('atk');
		let cherSpd = battle.p1.active[0].getStat('spd');
		let baseAtk = battle.p1.active[1].getStat('atk');
		let baseSpd = battle.p1.active[1].getStat('spd');

		// Set the weather to sun and re-check
		battle.field.setWeather('sunnyday', 'debug');
		assert.strictEqual(battle.p1.active[0].getStat('atk'), battle.modify(cherAtk, 1.5));
		assert.strictEqual(battle.p1.active[0].getStat('spd'), battle.modify(cherSpd, 1.5));
		assert.strictEqual(battle.p1.active[1].getStat('atk'), battle.modify(baseAtk, 1.5));
		assert.strictEqual(battle.p1.active[1].getStat('spd'), battle.modify(baseSpd, 1.5));
	});

	it('should still work if Cherrim transforms into something with Flower Gift without originally having it', function () {
		battle = common.createBattle({gameType: 'doubles'}, [
			[{species: "Cherrim", ability: 'serenegrace', moves: ['transform']}, {species: "Snorlax", ability: 'immunity', moves: ['healbell']}],
			[{species: "Blissey", ability: 'flowergift', moves: ['healbell']}, {species: "Blissey", ability: 'flowergift', moves: ['healbell']}],
		]);

		battle.makeChoices('move transform 1, move healbell', 'move healbell, move healbell');
		let cherAtk = battle.p1.active[0].getStat('atk');
		let cherSpd = battle.p1.active[0].getStat('spd');
		let baseAtk = battle.p1.active[1].getStat('atk');
		let baseSpd = battle.p1.active[1].getStat('spd');

		// Set the weather to sun and re-check
		battle.field.setWeather('sunnyday', 'debug');
		assert.strictEqual(battle.p1.active[0].getStat('atk'), battle.modify(cherAtk, 1.5));
		assert.strictEqual(battle.p1.active[0].getStat('spd'), battle.modify(cherSpd, 1.5));
		assert.strictEqual(battle.p1.active[1].getStat('atk'), battle.modify(baseAtk, 1.5));
		assert.strictEqual(battle.p1.active[1].getStat('spd'), battle.modify(baseSpd, 1.5));
	});
});


text:
San Jose, CA

June 2018

https://conferences.oreilly.com/velocity/vl-ca

---


text:
from google.cloud import retail_v2beta

def sample_delete_product():
    # Create a client
    client = retail_v2beta.ProductServiceClient()

    # Initialize request argument(s)
    request = retail_v2beta.DeleteProductRequest(
        name="name_value",
    )

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

# [END retail_v2beta_generated_ProductService_DeleteProduct_sync]


text:
var request = require('superagent');

var nodeBinaryParser = function (res, done) {
	res.setEncoding('binary');
	res.text = '';
	res.on('data', function (chunk) {
		res.text += chunk;
	});
	res.on('end', function () {
		done(null, new Buffer(res.text, 'binary'));
	});
};

var doGet = function (url, args) {
	return new Promise(function (resolve, reject) {
		request
			.get(url)
			.query(args)
			.buffer(true)
			.end(function (err, res) {
				if (err || !res) reject(err);
				resolve(res.body);
			});
	});
};

var doPost = function(url, args) {
	return new Promise(function (resolve, reject) {
		request
			.post(url)
			.type('form')
			.send(args)
			.end(function (err, res) {
				if (err || !res) reject(err);
				resolve(res.body);
			});
	});
};

var doDelete = function(url, args) {
	return new Promise(function (resolve, reject) {
		request
			.delete(url)
			.query(args)
			.end(function (err, res) {
				if (err) reject(err);
				resolve(res.body);
			});
	});
};

var doUpload = function(url, args) {
	return new Promise(function (resolve, reject) {
		request
			.post(url)
			.attach('file', args['file'])
			.end(function (err, res) {
				if (err) reject(err);
				resolve(res.body);
			});
	});
}

var doDownload = function(url, args) {
	return new Promise(function (resolve, reject) {
		request
			.get(url)
			.query(args)
			.buffer(true)
			.parse(nodeBinaryParser)
			.end(function (err, res) {
				if (err) reject(err);
				resolve(res.body);
			});
	});
}

module.exports = {
	doGet: doGet,
	doPost: doPost,
	doDelete: doDelete,
	doUpload: doUpload,
	doDownload: doDownload
};


text:
package com.microsoft.azure.management.resources.v2018_02_01.implementation;

import com.microsoft.azure.management.resources.v2018_02_01.ResourceManagementErrorWithDetails;
import com.microsoft.azure.management.resources.v2018_02_01.DeploymentPropertiesExtended;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Information from validate template deployment response.
 */
public class DeploymentValidateResultInner {
    /**
     * Validation error.
     */
    @JsonProperty(value = "error")
    private ResourceManagementErrorWithDetails error;

    /**
     * The template deployment properties.
     */
    @JsonProperty(value = "properties")
    private DeploymentPropertiesExtended properties;

    /**
     * Get validation error.
     *
     * @return the error value
     */
    public ResourceManagementErrorWithDetails error() {
        return this.error;
    }

    /**
     * Set validation error.
     *
     * @param error the error value to set
     * @return the DeploymentValidateResultInner object itself.
     */
    public DeploymentValidateResultInner withError(ResourceManagementErrorWithDetails error) {
        this.error = error;
        return this;
    }

    /**
     * Get the template deployment properties.
     *
     * @return the properties value
     */
    public DeploymentPropertiesExtended properties() {
        return this.properties;
    }

    /**
     * Set the template deployment properties.
     *
     * @param properties the properties value to set
     * @return the DeploymentValidateResultInner object itself.
     */
    public DeploymentValidateResultInner withProperties(DeploymentPropertiesExtended properties) {
        this.properties = properties;
        return this;
    }

}


text:
package org.codinjutsu.tools.mongo.runner;

import com.intellij.execution.configurations.*;
import com.intellij.openapi.project.Project;
import org.codinjutsu.tools.mongo.utils.GuiUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class MongoRunConfigurationType implements ConfigurationType {
    private final MongoFactory myConfigurationFactory;

    public MongoRunConfigurationType() {
        myConfigurationFactory = new MongoFactory(this);
    }

    @NotNull
    public String getDisplayName() {
        return "Mongo";
    }

    public String getConfigurationTypeDescription() {
        return "Mongo run configuration";
    }

    public Icon getIcon() {
        return GuiUtils.loadIcon("mongo_logo.png");
    }

    @NonNls
    @NotNull
    public String getId() {
        return "MongoRunConfigurationType";
    }

    @Override
    public boolean isDumbAware() {
        return true;
    }

    public MongoFactory[] getConfigurationFactories() {
        return new MongoFactory[]{myConfigurationFactory};
    }

    MongoFactory getFactory() {
        return myConfigurationFactory;
    }

    public static MongoRunConfigurationType getInstance() {
        return ConfigurationTypeUtil.findConfigurationType(MongoRunConfigurationType.class);
    }

    private static class MongoFactory extends ConfigurationFactory {
        MongoFactory(ConfigurationType type) {
            super(type);
        }

        @NotNull
        public RunConfiguration createTemplateConfiguration(@NotNull Project project) {
            return new MongoRunConfiguration(project, this);
        }
    }
}


text:
package jenkins;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import java.io.IOException;
import net.sf.json.JSONObject;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestPluginManager;
import org.xml.sax.SAXException;

/**
 * @author tom.fennelly@gmail.com
 */
public class I18nTest {

    @Rule
    public JenkinsRule jenkinsRule = new JenkinsRule();

    @Test
    public void test_baseName_unspecified() throws IOException, SAXException {
        JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle").getJSONObject();
        Assert.assertEquals("error", response.getString("status"));
        Assert.assertEquals("Mandatory parameter 'baseName' not specified.", response.getString("message"));
    }

    @Test
    public void test_baseName_unknown() throws IOException, SAXException {
        try {
            JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=com.acme.XyzWhatever").getJSONObject();
        } catch (FailingHttpStatusCodeException e) {
            Assert.assertNotNull(e);
            Assert.assertTrue(e.getMessage().contains("com.acme.XyzWhatever"));
        }
    }

    @Issue("JENKINS-35270")
    @Test
    public void test_baseName_plugin() throws Exception {
        ((TestPluginManager) jenkinsRule.jenkins.pluginManager).installDetachedPlugin("credentials");
        ((TestPluginManager) jenkinsRule.jenkins.pluginManager).installDetachedPlugin("ssh-credentials");
        ((TestPluginManager) jenkinsRule.jenkins.pluginManager).installDetachedPlugin("ssh-slaves");
        JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=hudson.plugins.sshslaves.Messages").getJSONObject();
        Assert.assertEquals(response.toString(), "ok", response.getString("status"));
        JSONObject data = response.getJSONObject("data");
        Assert.assertEquals("The launch timeout must be a number.", data.getString("SSHConnector.LaunchTimeoutMustBeANumber"));
    }

    @Test
    public void test_valid() throws IOException, SAXException {
        JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=hudson.logging.Messages&language=de").getJSONObject();
        Assert.assertEquals("ok", response.getString("status"));
        JSONObject data = response.getJSONObject("data");
        Assert.assertEquals("Initialisiere Log-Rekorder", data.getString("LogRecorderManager.init"));
    }

    @Issue("JENKINS-39034")
    @Test // variant testing
    public void test_valid_region_variant() throws IOException, SAXException {
        JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=jenkins.i18n.Messages&language=en_AU_variant").getJSONObject();
        Assert.assertEquals("ok", response.getString("status"));
        JSONObject data = response.getJSONObject("data");
        Assert.assertEquals("value_au_variant", data.getString("Key"));
    }

    @Issue("JENKINS-39034")
    @Test //country testing with delimiter '-' instead of '_'
    public void test_valid_region() throws IOException, SAXException {
        JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=jenkins.i18n.Messages&language=en-AU").getJSONObject();
        Assert.assertEquals("ok", response.getString("status"));
        JSONObject data = response.getJSONObject("data");
        Assert.assertEquals("value_au", data.getString("Key"));
    }

    @Issue("JENKINS-39034")
    @Test //fallthrough to default language if variant does not exit
    public void test_valid_fallback() throws IOException, SAXException {
        JSONObject response = jenkinsRule.getJSON("i18n/resourceBundle?baseName=jenkins.i18n.Messages&language=en_NZ_variant").getJSONObject();
        Assert.assertEquals("ok", response.getString("status"));
        JSONObject data = response.getJSONObject("data");
        Assert.assertEquals("value", data.getString("Key"));
    }

}


text:
The 1.0.0 release of the `google-cloud-talent` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage.

If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-talent/issues).

## Supported Python Versions

> **WARNING**: Breaking change
The 1.0.0 release requires Python 3.6+.

## Method Calls

> **WARNING**: Breaking change
Methods expect request objects. We provide a script that will convert most common use cases.
* Install the library with `libcst.`
```py
python3 -m pip install google-cloud-talent[libcst]
```

* The scripts `fixup_talent_v4beta1_keywords.py` shipped with the library. It expects
an input directory (with the code to convert) and an empty destination directory.

```sh
$ fixup_talent_v1_keywords.py --input-directory .samples/ --output-directory samples/
```

**Before:**
```py
from google.cloud import talent_v4beta1
client = talent_v4beta1.JobServiceClient()
parent = client.project_path('[PROJECT]')
# TODO: Initialize `jobs`:
jobs = []
response = client.batch_create_jobs(parent, jobs)
```

**After:**
```py
response = client.batch_create_jobs(request={"parent": "parent", "jobs": []})
```

### More Details

In `google-cloud-talent<1.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters.

**Before:**
```py
    def batch_create_jobs(
        self,
        parent,
        jobs,
        retry=google.api_core.gapic_v1.method.DEFAULT,
        timeout=google.api_core.gapic_v1.method.DEFAULT,
        metadata=None,
    ):
```

In the 1.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional.

Some methods have additional keyword only parameters. The available parameters depend on the [`google.api.method_signature` annotation] (https://github.com/googleapis/googleapis/blob/master/google/cloud/talent/v4beta1/job_service.proto#L73) specified by the API producer.

**After:**
```py
    def batch_create_jobs(
        self,
        request: job_service.BatchCreateJobsRequest = None,
        *,
        parent: str = None,
        jobs: Sequence[job.Job] = None,
        retry: retries.Retry = gapic_v1.method.DEFAULT,
        timeout: float = None,
        metadata: Sequence[Tuple[str, str]] = (),
    ) -> operation.Operation:
```

> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive.
> Passing both will result in an error.
Both of these calls are valid:
```py
response = client.batch_create_jobs(
    request={
        "parent": parent,
        "jobs": jobs,
    }
)
```

```py
response = client.batch_create_jobs(
    parent=parent,
    jobs=jobs,
)
```

This call is invalid because it mixes `request` with a keyword argument `jobs`. Executing this code will result in an error.

```py
response = client.batch_create_jobs(
    request={
        "parent": parent,
    },
    jobs=jobs
)
```

## v4beta1 -> v4

In addition, this release adds the v4 API surface, which has breaking changes from the v4beta1.
The `google.cloud.talent` import now resolves to `google.cloud.talent_v4`. To continue
to use the `v4beta1`, import from it explicitly.

The `v4` surface merges functionalty in the  `v3p1beta1` and `v4beta1`.

```py
from google.cloud import talent_v4beta1
```

### search_jobs

`search_jobs` returns `SearchJobsResponse`. Matching jobs are in `SearchJobsResponse.matching_jobs`.

**v4beta1:**
```py
from google.cloud import talent_v4beta1

client = talent_v4beta1.JobServiceClient()

#...
request = talent_v4beta1.SearchJobsRequest(
    parent=parent,
    request_metadata=request_metadata,
    job_query=job_query,
)
for response_item in client.search_jobs(request=request):
    # ...
```

**v4**
```py
from google.cloud import talent_v4

client = talent_v4.JobServiceClient()

#...
request = talent_v4.SearchJobsRequest(
    parent=parent,
    request_metadata=request_metadata,
    job_query=job_query,
)
for response_item in client.search_jobs(request=request).matching_jobs:
    # ...
```


text:
package net.wayfarerx.dreamsleeve.data

import org.scalatest._

/**
 * Test case for the document implementation.
 */
class DocumentSpec extends FlatSpec with Matchers {

  val generator = Hash.Generator()

  "A document" should "act as a hashable root fragment container" in {
    val e = Document("e", Table())
    val o = Document("o", Table(Value.Number(1) -> Value.String("1")))
    e == e shouldBe true
    e == o shouldBe false
    e == ("Hi": Any) shouldBe false
    e.toString shouldBe "Document(e,Table())"
    o.toString shouldBe "Document(o,Table(Number(1)=String(1)))"
    e.hash shouldBe generator.hash(Document.Header, "e", e.content.hash)
    o.hash shouldBe generator.hash(Document.Header, "o", o.content.hash)
    Document.unapply(o) shouldBe Some((o.title, o.content))
  }

}


text:
@interface OYTopViewController : UIViewController

@end


text:
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import classnames from 'classnames';
import { defineMessages, FormattedHTMLMessage, intlShape } from 'react-intl';
import DialogCloseButton from '../../widgets/DialogCloseButton';
import Dialog from '../../widgets/Dialog';
import WalletRecoveryInstructions from './WalletRecoveryInstructions';
import globalMessages from '../../../i18n/global-messages';
import styles from './WalletRecoveryPhraseDisplayDialog.scss';
import { WALLET_RECOVERY_PHRASE_WORD_COUNT } from '../../../config/cryptoConfig';
import LoadingSpinner from '../../widgets/LoadingSpinner';
import { MnemonicInput } from '../mnemonic-input';

const messages = defineMessages({
  backupInstructions: {
    id: 'wallet.backup.recovery.phrase.display.dialog.backup.instructions',
    defaultMessage:
      '!!!Please make sure you write down the {walletRecoveryPhraseWordCount} words of your wallet recovery phrase on a piece of paper in the exact order shown here.',
    description:
      'Instructions for backing up wallet recovery phrase on dialog that displays wallet recovery phrase.',
  },
  buttonLabelIHaveWrittenItDown: {
    id:
      'wallet.backup.recovery.phrase.display.dialog.button.label.iHaveWrittenItDown',
    defaultMessage: '!!!Yes, I have written down my wallet recovery phrase.',
    description:
      'Label for button "Yes, I have written down my wallet recovery phrase." on wallet backup dialog',
  },
});
type Props = {
  recoveryPhrase: string;
  onStartWalletBackup: (...args: Array<any>) => any;
  onCancelBackup: (...args: Array<any>) => any;
  isSubmitting: boolean;
};

@observer
class WalletRecoveryPhraseDisplayDialog extends Component<Props> {
  static contextTypes = {
    intl: intlShape.isRequired,
  };

  render() {
    const { intl } = this.context;
    const {
      recoveryPhrase,
      onStartWalletBackup,
      onCancelBackup,
      isSubmitting,
    } = this.props;
    const dialogClasses = classnames([
      styles.component,
      'WalletRecoveryPhraseDisplayDialog',
    ]);
    const buttonLabel = !isSubmitting ? (
      intl.formatMessage(messages.buttonLabelIHaveWrittenItDown)
    ) : (
      <LoadingSpinner />
    );
    const actions = [
      {
        label: buttonLabel,
        onClick: onStartWalletBackup,
        primary: true,
      },
    ];
    const mnemonicValues = recoveryPhrase.split(' ');
    return (
      <Dialog
        className={dialogClasses}
        title={intl.formatMessage(globalMessages.recoveryPhraseDialogTitle)}
        actions={actions}
        onClose={onCancelBackup}
        closeOnOverlayClick={false}
        closeButton={<DialogCloseButton onClose={onCancelBackup} />}
      >
        <WalletRecoveryInstructions
          instructionsText={
            <FormattedHTMLMessage
              {...messages.backupInstructions}
              values={{
                walletRecoveryPhraseWordCount: WALLET_RECOVERY_PHRASE_WORD_COUNT,
              }}
            />
          }
        />
        <MnemonicInput
          disabled
          value={mnemonicValues}
          wordCount={mnemonicValues.length}
        />
      </Dialog>
    );
  }
}

export default WalletRecoveryPhraseDisplayDialog;


text:
package org.pcj.internal.message;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import org.pcj.internal.message.accumulate.ValueAccumulateRequestMessage;
import org.pcj.internal.message.accumulate.ValueAccumulateResponseMessage;
import org.pcj.internal.message.alive.AbortMessage;
import org.pcj.internal.message.alive.AliveMessage;
import org.pcj.internal.message.at.AsyncAtRequestMessage;
import org.pcj.internal.message.at.AsyncAtResponseMessage;
import org.pcj.internal.message.barrier.GroupBarrierGoMessage;
import org.pcj.internal.message.barrier.GroupBarrierWaitingMessage;
import org.pcj.internal.message.broadcast.BroadcastBytesMessage;
import org.pcj.internal.message.broadcast.BroadcastResponseMessage;
import org.pcj.internal.message.broadcast.BroadcastRequestMessage;
import org.pcj.internal.message.bye.ByeCompletedMessage;
import org.pcj.internal.message.bye.ByeNotifyMessage;
import org.pcj.internal.message.collect.CollectRequestMessage;
import org.pcj.internal.message.collect.CollectResponseMessage;
import org.pcj.internal.message.collect.CollectValueMessage;
import org.pcj.internal.message.gather.GatherRequestMessage;
import org.pcj.internal.message.gather.GatherResponseMessage;
import org.pcj.internal.message.gather.GatherValueMessage;
import org.pcj.internal.message.get.ValueGetRequestMessage;
import org.pcj.internal.message.get.ValueGetResponseMessage;
import org.pcj.internal.message.hello.HelloBonjourMessage;
import org.pcj.internal.message.hello.HelloCompletedMessage;
import org.pcj.internal.message.hello.HelloGoMessage;
import org.pcj.internal.message.hello.HelloInformMessage;
import org.pcj.internal.message.hello.HelloMessage;
import org.pcj.internal.message.peerbarrier.PeerBarrierMessage;
import org.pcj.internal.message.put.ValuePutRequestMessage;
import org.pcj.internal.message.put.ValuePutResponseMessage;
import org.pcj.internal.message.reduce.ReduceRequestMessage;
import org.pcj.internal.message.reduce.ReduceResponseMessage;
import org.pcj.internal.message.reduce.ReduceValueMessage;
import org.pcj.internal.message.scatter.ScatterRequestMessage;
import org.pcj.internal.message.scatter.ScatterResponseMessage;
import org.pcj.internal.message.splitgroup.SplitGroupAnswerMessage;
import org.pcj.internal.message.splitgroup.SplitGroupGoMessage;
import org.pcj.internal.message.splitgroup.SplitGroupQueryMessage;
import org.pcj.internal.message.splitgroup.SplitGroupRequestMessage;
import org.pcj.internal.message.splitgroup.SplitGroupResponseMessage;
import org.pcj.internal.message.splitgroup.SplitGroupWaitingMessage;

/**
 * @author Marek Nowicki (faramir@mat.umk.pl)
 */
public enum MessageType {

    UNKNOWN(MessageUnknown::new),
    HELLO(HelloMessage::new),
    HELLO_INFORM(HelloInformMessage::new),
    HELLO_BONJOUR(HelloBonjourMessage::new),
    HELLO_COMPLETED(HelloCompletedMessage::new),
    HELLO_GO(HelloGoMessage::new),
    ALIVE(AliveMessage::new),
    ABORT(AbortMessage::new),
    BYE(ByeNotifyMessage::new),
    BYE_COMPLETED(ByeCompletedMessage::new),
    GROUP_BARRIER_WAITING(GroupBarrierWaitingMessage::new),
    GROUP_BARRIER_GO(GroupBarrierGoMessage::new),
    PEER_BARRIER(PeerBarrierMessage::new),
    SPLIT_GROUP_REQUEST(SplitGroupRequestMessage::new),
    SPLIT_GROUP_RESPONSE(SplitGroupResponseMessage::new),
    SPLIT_GROUP_QUERY(SplitGroupQueryMessage::new),
    SPLIT_GROUP_ANSWER(SplitGroupAnswerMessage::new),
    SPLIT_GROUP_WAITING(SplitGroupWaitingMessage::new),
    SPLIT_GROUP_GO(SplitGroupGoMessage::new),
    VALUE_GET_REQUEST(ValueGetRequestMessage::new),
    VALUE_GET_RESPONSE(ValueGetResponseMessage::new),
    VALUE_PUT_REQUEST(ValuePutRequestMessage::new),
    VALUE_PUT_RESPONSE(ValuePutResponseMessage::new),
    VALUE_ACCUMULATE_REQUEST(ValueAccumulateRequestMessage::new),
    VALUE_ACCUMULATE_RESPONSE(ValueAccumulateResponseMessage::new),
    BROADCAST_REQUEST(BroadcastRequestMessage::new),
    BROADCAST_BYTES(BroadcastBytesMessage::new),
    BROADCAST_RESPONSE(BroadcastResponseMessage::new),
    SCATTER_REQUEST(ScatterRequestMessage::new),
    SCATTER_RESPONSE(ScatterResponseMessage::new),
    GATHER_REQUEST(GatherRequestMessage::new),
    GATHER_VALUE(GatherValueMessage::new),
    GATHER_RESPONSE(GatherResponseMessage::new),
    REDUCE_REQUEST(ReduceRequestMessage::new),
    REDUCE_VALUE(ReduceValueMessage::new),
    REDUCE_RESPONSE(ReduceResponseMessage::new),
    COLLECT_REQUEST(CollectRequestMessage::new),
    COLLECT_VALUE(CollectValueMessage::new),
    COLLECT_RESPONSE(CollectResponseMessage::new),
    ASYNC_AT_REQUEST(AsyncAtRequestMessage::new),
    ASYNC_AT_RESPONSE(AsyncAtResponseMessage::new);
    /* **************************************************** */
    private static final Map<Byte, MessageType> map;

    static {
        map = new HashMap<>(values().length, 1.0f);
        for (MessageType type : values()) {
            map.put((byte) type.ordinal(), type);
        }
        if (map.size() != values().length) {
            throw new InstantiationError("At least two MessageType items have the same value");
        }
    }

    private final Supplier<? extends Message> constructor;

    MessageType(Supplier<? extends Message> constructor) {
        this.constructor = constructor;
    }

    /**
     * Creates Message object that is associated with id
     *
     * @return Message object
     */
    public final static Message createMessage(byte messageTypeId) {
        MessageType type = map.get(messageTypeId);
        Supplier<? extends Message> constructor = (type == null ? UNKNOWN.constructor : type.constructor);
        return constructor.get();
    }

    public final byte getId() {
        return (byte) ordinal();
    }
}


text:
<?php
/* ---  kontrola jadra  --- */
if (!defined('_core')) {
    exit;
}

/* ---  nastaveni a vlozeni skriptu pro upravu stranky  --- */
$type = 6;
require 'require/sub/content-editscript-init.php';
if ($continue) {
    $custom_settings = "<label><input type='checkbox' name='var1' value='1'" . _checkboxActivate($query['var1']) . " /> " . $_lang['admin.content.form.newwindow'] . "</label>";
    $custom_array = array(array("var1", true, 0, false));
}
require 'require/sub/content-editscript.php';