text:
@interface RACCommandViewController : UIViewController

@end

redpajama_set_name: RedPajamaGithub


text:
package org.sfm.csv.impl;

import org.sfm.csv.CellValueReader;
import org.sfm.csv.ParsingContext;
import org.sfm.reflect.Instantiator;
import org.sfm.utils.ErrorHelper;

public class InstantiatorOnReader<S, T> implements CellValueReader<T> {
	private final Instantiator<S, T> instantiator;
	private final CellValueReader<S> innerReader;

	public InstantiatorOnReader(Instantiator<S, T> constructor,
								CellValueReader<S> innerReader) {
		this.instantiator = constructor;
		this.innerReader = innerReader;
	}

	@Override
	public T read(char[] chars, int offset, int length,
			ParsingContext parsingContext) {
		try {
			return instantiator.newInstance(innerReader.read(chars, offset, length, parsingContext));
		} catch (Exception e) {
            return ErrorHelper.rethrow(e);
		}
	}

    @Override
    public String toString() {
        return "ConstructorOnReader{" +
                "constructor=" + instantiator +
                ", innerReader=" + innerReader +
                '}';
    }
}


text:
export default socket => () => next => (action) => {
  action.payload = Object.assign(action.payload || {}, {
    socket
  });
  return next(action);
};


text:
import os
import sys

from setuptools import setup, find_packages

if sys.version_info < (2, 6):
    raise SystemExit("Python 2.6 or later is required.")

exec(open(os.path.join("marrow", "tags", "release.py")).read())

setup(
        name = "marrow.tags",
        version = version,

        description = "An object-based template and widget library wherein templates are interpreted by Python itself.",
        long_description = """\
For full documentation, see the README.textile file present in the package,
or view it online on the GitHub project page:

https://github.com/marrow/marrow.tags""",

        author = "Alice Bevan-McGregor",
        author_email = "alice+marrow@gothcandy.com",
        url = "https://github.com/marrow/marrow.tags",
        license = "MIT",

        install_requires = [
            'marrow.util < 2.0'
        ],

        test_suite = 'nose.collector',
        tests_require = ['nose', 'coverage'],

        classifiers = [
                "Development Status :: 1 - Planning",
                "Environment :: Console",
                "Intended Audience :: Developers",
                "License :: OSI Approved :: MIT License",
                "Operating System :: OS Independent",
                "Programming Language :: Python",
                "Topic :: Internet :: WWW/HTTP :: WSGI",
                "Topic :: Software Development :: Libraries :: Python Modules"
            ],

        packages = find_packages(exclude=['examples', 'tests']),
        zip_safe = True,
        include_package_data = True,
        package_data = {'': ['README.textile', 'LICENSE']},

        namespace_packages = ['marrow'],
    )


text:
"""Neural network operations commonly shared by the architectures."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools
import tensorflow as tf

class NormActivation(tf.keras.layers.Layer):
  """Combined Normalization and Activation layers."""

  def __init__(self,
               momentum=0.997,
               epsilon=1e-4,
               trainable=True,
               init_zero=False,
               use_activation=True,
               activation='relu',
               fused=True,
               name=None):
    """A class to construct layers for a batch normalization followed by a ReLU.

    Args:
      momentum: momentum for the moving average.
      epsilon: small float added to variance to avoid dividing by zero.
      trainable: `bool`, if True also add variables to the graph collection
        GraphKeys.TRAINABLE_VARIABLES. If False, freeze batch normalization
        layer.
      init_zero: `bool` if True, initializes scale parameter of batch
          normalization with 0. If False, initialize it with 1.
      fused: `bool` fused option in batch normalziation.
      use_actiation: `bool`, whether to add the optional activation layer after
        the batch normalization layer.
      activation: 'string', the type of the activation layer. Currently support
        `relu` and `swish`.
      name: `str` name for the operation.
    """
    super(NormActivation, self).__init__(trainable=trainable)
    if init_zero:
      gamma_initializer = tf.keras.initializers.Zeros()
    else:
      gamma_initializer = tf.keras.initializers.Ones()
    self._normalization_op = tf.keras.layers.BatchNormalization(
        momentum=momentum,
        epsilon=epsilon,
        center=True,
        scale=True,
        trainable=trainable,
        fused=fused,
        gamma_initializer=gamma_initializer,
        name=name)
    self._use_activation = use_activation
    if activation == 'relu':
      self._activation_op = tf.nn.relu
    elif activation == 'swish':
      self._activation_op = tf.nn.swish
    else:
      raise ValueError('Unsupported activation `{}`.'.format(activation))

  def __call__(self, inputs, is_training=None):
    """Builds the normalization layer followed by an optional activation layer.

    Args:
      inputs: `Tensor` of shape `[batch, channels, ...]`.
      is_training: `boolean`, if True if model is in training mode.

    Returns:
      A normalized `Tensor` with the same `data_format`.
    """
    # We will need to keep training=None by default, so that it can be inherit
    # from keras.Model.training
    if is_training and self.trainable:
      is_training = True
    inputs = self._normalization_op(inputs, training=is_training)

    if self._use_activation:
      inputs = self._activation_op(inputs)
    return inputs

def norm_activation_builder(momentum=0.997,
                            epsilon=1e-4,
                            trainable=True,
                            activation='relu',
                            **kwargs):
  return functools.partial(
      NormActivation,
      momentum=momentum,
      epsilon=epsilon,
      trainable=trainable,
      activation=activation,
      **kwargs)


text:
import { connectRouter } from "connected-react-router";
import { History } from "history";
import { downloadActions } from "readium-desktop/common/redux/actions";
import { dialogReducer } from "readium-desktop/common/redux/reducers/dialog";
import { i18nReducer } from "readium-desktop/common/redux/reducers/i18n";
import { keyboardReducer } from "readium-desktop/common/redux/reducers/keyboard";
import { toastReducer } from "readium-desktop/common/redux/reducers/toast";
import { apiReducer } from "readium-desktop/renderer/common/redux/reducers/api";
import { loadReducer } from "readium-desktop/renderer/common/redux/reducers/load";
import { winReducer } from "readium-desktop/renderer/common/redux/reducers/win";
import { historyReducer } from "readium-desktop/renderer/library/redux/reducers/history";
import {
    opdsBreadcrumbReducer, opdsHeaderLinkReducer, opdsSearchLinkReducer,
} from "readium-desktop/renderer/library/redux/reducers/opds";
import { IRouterLocationState } from "readium-desktop/renderer/library/routing";
import { priorityQueueReducer } from "readium-desktop/utils/redux-reducers/pqueue.reducer";
import { combineReducers } from "redux";

import { ILibraryRootState } from "../states";

export const rootReducer = (history: History<IRouterLocationState>) => {
    return combineReducers<ILibraryRootState>({
        i18n: i18nReducer,
        opds: combineReducers({
            browser: combineReducers({
                breadcrumb: opdsBreadcrumbReducer,
                header: opdsHeaderLinkReducer,
                search: opdsSearchLinkReducer,
            }),
        }),
        win: winReducer,
        // net: netReducer,
        // update: updateReducer,
        api: apiReducer,
        dialog: dialogReducer,
        router: connectRouter<IRouterLocationState>(history),
        toast: toastReducer,
        download: priorityQueueReducer
            <
                downloadActions.progress.TAction,
                downloadActions.done.TAction,
                downloadActions.progress.Payload,
                number
            >(
                {
                    push: {
                        type: downloadActions.progress.ID,
                        selector: (action) =>
                            [action.payload, action.payload.id],
                    },
                    pop: {
                        type: downloadActions.done.ID,
                        selector: (action) => [undefined, action.payload.id],
                    },
                    sortFct: (a, b) => b[1] - a[1],
                },
            ),
        history: historyReducer,
        keyboard: keyboardReducer,
        load: loadReducer,
    });
};


text:
$pluginVersion = "1"

#Setting this to true will alert you when there is a communication problem while posting plugin data to server
$heartbeat="true"
$displayName = "MailServerStatusCheck" #Name of this plugin

#pop server configurations
$popEnabled = 1 # value 1-pop enabled ; value 0 - pop disabled
$popServer = "popserver"
$popPort = "popport"

#imap server configurations
$imapEnabled = 0 # value 1-imap enabled ; value 0 - imap disabled
$imapServer = "imapserver"
$imapPort = "imapport"

#credentials
$userName = "user@domain.com"
$password = "password"

$imapStatus  = 0
$popStatus = 0
$msg = ""

$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path

if($popEnabled)
{
#pop
	try
	{
	$dependencypath = $directorypath + '\OpenPop.dll'
	[Reflection.Assembly]::LoadFile($dependencypath) | Out-Null

		$pop = new-object OpenPop.Pop3.Pop3Client
		$pop.Connect($popServer, $popPort, 1);
		$pop.Authenticate($userName,$password,"UsernameAndPassword");
		$popStatus = 1;
		$msg = "Successfully connected to the mail server via POP"
	}
	catch
	{
		$msg = "failed to connect to the mail server via POP"
	}
	$data = "{""popStatus"":""$popStatus""}"
}
ElseIf($imapEnabled)
{
	#imap
	$dependencypath = $directorypath + '\S22Imap\S22.Imap.dll'
	[Reflection.Assembly]::LoadFile($dependencypath) | Out-Null

	try
	{
		$imap = new-object S22.Imap.ImapClient($imapServer,$imapPort,$userName,$password,"Login",1)
		$imapStatus = 1;
		$msg = "Successfully connected to the mail server via IMAP"
	}
	catch
	{
		$msg = "failed to connect to the mail server via IMAP"
	}
	$data = "{""imapStatus"":""$imapStatus""}"
}

$toReturn = "{ `"version`" : `"$pluginVersion`",`"heartbeat`" : `"$heartbeat`",`"displayName`" : `"$displayName`",`"msg`" : `"$msg`",`"data`" : $data }"
Write-Host $toReturn


text:
import logging
from tornado.web import HTTPError
from tornado.web import asynchronous
from handler import BaseHandler
from lib.route import route
from tornado.ioloop import IOLoop
import time
import os
import subprocess
import tornado.iostream

@route(r'/tools/tail', name='tools_tail') #
class TailHandler(BaseHandler):
    @asynchronous
    def get(self):
        file_path = "tail.txt"
        self.file = open(file_path, "r")
        self.pos = self.file.tell()
        def _read_file():
            line = self.file.read()
            last_pos = self.file.tell()
            if not line:
                self.file.close()
                self.file = open(file_path, 'r')
                self.file.seek(last_pos)
                pass
            else:
                self.write(line)
                self.flush()
            IOLoop.instance().add_timeout(time.time() + 1, _read_file)
        _read_file()

@route(r'/tools/tail1', name='tools_tail1') #
class Tail1Handler(BaseHandler):
    @asynchronous
    def get(self):
        print "GOT REQUEST"
        self.p = subprocess.Popen(
            ["tail", "-f", "tail.txt", "-n+1"],
            stdout=subprocess.PIPE)

        self.write("<pre>")
        self.write("Hello, world\n")
        self.flush()

        self.stream = tornado.iostream.PipeIOStream(self.p.stdout.fileno())
        self.stream.read_until("\n", self.line_from_nettail)

    def on_connection_close(self, *args, **kwargs):
        """Clean up the nettail process when the connection is closed.
        """
        print "CONNECTION CLOSED!!!!"
        self.p.terminate()
        tornado.web.RequestHandler.on_connection_close(self, *args, **kwargs)

    def line_from_nettail(self, data):
        self.write(data)
        self.flush()
        self.stream.read_until("\n", self.line_from_nettail)


text:
module Query
  # Query's for Locations where Observation meets specified conditions
  class LocationWithObservations < Query::LocationBase
    include Query::Initializers::ContentFilters
    include Query::Initializers::Names

    def parameter_declarations
      super.merge(
        old_by?: :string,
        date?: [:date],
        locations?: [:string],
        projects?: [:string],
        species_lists?: [:string],
        herbaria?: [:string],
        confidence?: [:float],
        is_collection_location?: :boolean,
        has_location?: :boolean,
        has_name?: :boolean,
        has_comments?: { boolean: [true] },
        has_sequences?: { boolean: [true] },
        has_notes?: :boolean,
        has_notes_fields?: [:string],
        notes_has?: :string,
        comments_has?: :string
      ).merge(content_filter_parameter_declarations(Observation)).
        merge(names_parameter_declarations).
        merge(consensus_parameter_declarations)
    end

    def initialize_flavor
      add_join(:observations)
      add_owner_and_time_stamp_conditions("observations")
      add_date_condition("observations.when", params[:date])
      initialize_name_parameters
      add_where_condition(:observations, params[:locations])
      initialize_association_parameters
      add_range_condition("observations.vote_cache", params[:confidence])
      initialize_boolean_parameters
      initialize_search_parameters
      initialize_content_filters(Observation)
      super
    end

    def initialize_association_parameters
      add_id_condition(
        "observations_projects.project_id",
        lookup_projects_by_name(params[:projects]),
        :observations, :observations_projects
      )
      add_id_condition(
        "observations_species_lists.species_list_id",
        lookup_species_lists_by_name(params[:species_lists]),
        :observations, :observations_species_lists
      )
      add_id_condition(
        "herbarium_records.herbarium_id",
        lookup_herbaria_by_name(params[:herbaria]),
        :observations, :herbarium_records_observations, :herbarium_records
      )
    end

    def initialize_boolean_parameters
      initialize_is_collection_location_parameter
      initialize_has_location_parameter
      initialize_has_name_parameter
      initialize_has_notes_parameter
      add_has_notes_fields_condition(params[:has_notes_fields])
      add_join(:observations, :comments) if params[:has_comments]
      add_join(:observations, :sequences) if params[:has_sequences]
    end

    def initialize_is_collection_location_parameter
      add_boolean_condition(
        "observations.is_collection_location IS TRUE",
        "observations.is_collection_location IS FALSE",
        params[:is_collection_location]
      )
    end

    def initialize_has_location_parameter
      add_boolean_condition(
        "observations.location_id IS NOT NULL",
        "observations.location_id IS NULL",
        params[:has_location]
      )
    end

    def initialize_has_name_parameter
      genus = Name.ranks[:Genus]
      group = Name.ranks[:Group]
      add_boolean_condition(
        "names.rank <= #{genus} or names.rank = #{group}",
        "names.rank > #{genus} and names.rank < #{group}",
        params[:has_name],
        :observations, :names
      )
    end

    def initialize_has_notes_parameter
      add_boolean_condition(
        "observations.notes != #{escape(Observation.no_notes_persisted)}",
        "observations.notes  = #{escape(Observation.no_notes_persisted)}",
        params[:has_notes]
      )
    end

    def initialize_search_parameters
      add_search_condition(
        "observations.notes",
        params[:notes_has]
      )
      add_search_condition(
        "CONCAT(comments.summary,COALESCE(comments.comment,''))",
        params[:comments_has],
        :observations, :comments
      )
    end

    def coerce_into_observation_query
      Query.lookup(:Observation, :all, params_with_old_by_restored)
    end
  end
end


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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.

=cut

=pod

=head1 NAME

Bio::EnsEMBL::Compara::RunnableDB::LoadAllGenomeDBs

=head1 DESCRIPTION

Loads all the core databases and stores the species as GenomeDB objects.

=cut

package Bio::EnsEMBL::Compara::RunnableDB::LoadAllGenomeDBs;

use strict;

use base ('Bio::EnsEMBL::Compara::RunnableDB::LoadOneGenomeDB');

my $suffix_separator = '__cut_here__';

sub fetch_input {
    my $self = shift @_;
    $self->param('all_core_dbas', $self->get_all_core_dbas);
}

sub run {
    my $self = shift @_;

    my @genome_dbs;
    foreach my $core_dba (@{$self->param('all_core_dbas')}) {
        next unless $core_dba->assembly_name;
        push @genome_dbs, $self->create_genome_db($core_dba);
    }
    $self->param('genome_dbs', \@genome_dbs);
}

sub write_output {
    my $self = shift;

    foreach my $genome_db (@{$self->param('genome_dbs')}) {
        $self->store_and_dataflow_genome_db($genome_db, 2);
    }
}

sub get_all_core_dbas {
    my $self = shift;

    my $registry_conf_file = $self->param('registry_conf_file');
    my $registry_dbs = $self->param('registry_dbs') || [];
    my $registry_files = $self->param('registry_files') || [];
    $registry_dbs || $registry_files || die "'registry_dbs' or 'registry_files' become obligatory parameter";

    my @core_dba_list = ();

    if ($registry_conf_file) {
        Bio::EnsEMBL::Registry->load_all( $registry_conf_file );
        push @core_dba_list, @{Bio::EnsEMBL::Registry->get_all_DBAdaptors(-GROUP => 'core')};
    }

    for(my $r_ind=0; $r_ind<scalar(@$registry_dbs); $r_ind++) {
        Bio::EnsEMBL::Registry->load_registry_from_db( %{ $registry_dbs->[$r_ind] }, -species_suffix => $suffix_separator.$r_ind, -db_version => $self->param('db_version') );
        push @core_dba_list, @{Bio::EnsEMBL::Registry->get_all_DBAdaptors(-GROUP => 'core')};
    }

    for(my $r_ind=0; $r_ind<scalar(@$registry_files); $r_ind++) {

        my $reg_content = Bio::EnsEMBL::Compara::GenomeMF->all_from_file( $registry_files->[$r_ind] );
        push @core_dba_list, @$reg_content;
    }

    return \@core_dba_list;
}

1;


text:
package org.mellowtech.core.sort;

import org.mellowtech.core.codec.BCodec;

import java.util.Comparator;

/**
 * @author msvens
 *
 */
public class BComparatorArray<A> implements Comparator<Integer>{

  private final BCodec<A> template;
  private final byte buffer[];

  public BComparatorArray(BCodec<A> template, byte[] buffer){
    this.template = template;
    this.buffer = buffer;
  }

  @Override
  public int compare(Integer o1, Integer o2) {
    return template.byteCompare(o1, o2, buffer);
  }

}


text:
package raptor.engine.uci;

public class UCIBestMove {
	protected UCIMove bestMove;
	protected UCIMove ponderMove;

	public UCIMove getBestMove() {
		return bestMove;
	}

	public UCIMove getPonderMove() {
		return ponderMove;
	}

	public void setBestMove(UCIMove bestMove) {
		this.bestMove = bestMove;
	}

	public void setPonderMove(UCIMove ponderMove) {
		this.ponderMove = ponderMove;
	}
}


text:
*A call that returns a BLOB, for the providen blob_id*

* **URL**

  `blobstore.site.tld/<string:bsid>/`

* **Method:**
  `GET`

*  **URL Params**

   **Required:**

   `bsid = [string]` - *file id in blobstore*

* **Success Response:**

  *Actually, there is no JSON response. If a request was handleded sucessfully, the device recieves the blob.*

* **Error Response:**

  *In a case of a bad `blobstore_id` parameter, that doesn't exist in the databse,
  the recieved error code is as follows:*
  * **Code:** 404 NOT FOUND

    **Content:** `{"message":"not found"}`

* **Sample Call:**

  *Although you could call this endpoint like it was a REST API, and save the recieved bytes in a file, this endpoint should be embeded in html, for example - image sources.*

  ```html
  <img class="AlbumCover" src="blobstore.site.tld/591ddfadf1b4fa8188ec5d60/" />
  ```

---

### 2. AddBlob
**REQUIRES ADMIN AUTHENTIFICATION VIA TOKEN**

*A call that saves a blob into the database.*

* **URL**

  `blobstore.site.tld/add/`

* **Method:**
  `POST`

*  **Data Params**

   **Required:**

   `admin_access_token = [string]`

   `file = [file]`

   `mimetype = [string]`

* **Success Response:**
   ```json
  {"bsid": "<blobstore_id>"}
  ```

* **Error Response:**

  *In a case of a bad `admin_access_token` parameter, this error occurs*
  * **Code:** 403 NOT AUTHORISED

    **Content:** `{"message": "not allowed"}`

* **Sample Call:**

*Adding a mp3 file to the blobstore*

```python
import requests

r = requests.post(
	"http://localhost:8889/add/",
	params={"admin_access_token":"token","mimetype":"audio/mpeg"},
	files={"file":open("data.mp3", "rb")}
		)
```
---

### 3. DeleteBlob
**REQUIRES ADMIN AUTHENTIFICATION VIA TOKEN**

*A call that deletes a blob from the database.*

* **URL**

  `blobstore.site.tld/delete/`

* **Method:**
  `GET`

*  **Data Params**

   **Required:**

   `admin_access_token = [string]`

   `bsid = [string]` - *id of the file in the blobstore*

* **Success Response:**
   ```json
  {"message": "attempted deletion, not guaranteed (default)"}
  ```

* **Error Response:**

  *In a case of a bad `admin_access_token` parameter, this error occurs*
  * **Code:** 403 NOT AUTHORISED

    **Content:** `{"message": "not allowed"}`

* **Sample Call:**

*Adding a mp3 file to the blobstore*

```python
import requests

r2 = requests.get("http://localhost:8889/delete/",
	params={"admin_access_token":"jamtest", "bsid":"591ddfadf1b4fa8188ec5d60"}
		)
```

---


text:
package com.reactnativenavigation.presentation;

import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;

import com.reactnativenavigation.parse.Options;
import com.reactnativenavigation.parse.SideMenuRootOptions;

public class SideMenuPresenter {

    private DrawerLayout sideMenu;

    public void bindView(DrawerLayout sideMenu) {
        this.sideMenu = sideMenu;
    }

    public boolean handleBack() {
        if (sideMenu.isDrawerOpen(Gravity.LEFT)) {
            sideMenu.closeDrawer(Gravity.LEFT);
            return true;
        }
        if (sideMenu.isDrawerOpen(Gravity.RIGHT)) {
            sideMenu.closeDrawer(Gravity.RIGHT);
            return true;
        }
        return false;
    }

    public void mergeOptions(SideMenuRootOptions options) {
        mergeLockMode(options);
        mergeVisibility(options);
    }

    public void mergeChildOptions(SideMenuRootOptions options) {
        mergeLockMode(options);
        mergeVisibility(options);
    }

    public void applyChildOptions(Options options) {
        applyLockMode(options.sideMenuRootOptions);
        mergeVisibility(options.sideMenuRootOptions);
    }

    private void applyLockMode(SideMenuRootOptions options) {
        int leftLockMode = options.left.enabled.isTrueOrUndefined() ? DrawerLayout.LOCK_MODE_UNLOCKED : DrawerLayout.LOCK_MODE_LOCKED_CLOSED;
        sideMenu.setDrawerLockMode(leftLockMode, Gravity.LEFT);

        int rightLockMode = options.right.enabled.isTrueOrUndefined() ? DrawerLayout.LOCK_MODE_UNLOCKED : DrawerLayout.LOCK_MODE_LOCKED_CLOSED;
        sideMenu.setDrawerLockMode(rightLockMode, Gravity.RIGHT);
    }

    private void mergeVisibility(SideMenuRootOptions options) {
        if (options.left.visible.isTrue()) {
            sideMenu.openDrawer(Gravity.LEFT, options.left.animate.get(true));
        } else if (options.left.visible.isFalse()) {
            sideMenu.closeDrawer(Gravity.LEFT, options.left.animate.get(true));
        }

        if (options.right.visible.isTrue()) {
            sideMenu.openDrawer(Gravity.RIGHT, options.right.animate.get(true));
        } else if (options.right.visible.isFalse()) {
            sideMenu.closeDrawer(Gravity.RIGHT, options.right.animate.get(true));
        }
    }

    private void mergeLockMode(SideMenuRootOptions options) {
        if (options.left.enabled.isFalse()) {
            sideMenu.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
        } else if (options.left.enabled.isTrue()) {
            sideMenu.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
        }

        if (options.right.enabled.isFalse()) {
            sideMenu.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
        } else if (options.right.enabled.isTrue()) {
            sideMenu.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
        }
    }
}


text:
{% extends "gui_app/base.html" %}
{% block title %}
{% endblock %}

{% block headerscript %}
{% endblock %}

{% block nav %}
    {% include "gui_app/includes/nav_menu.html" %}
{% endblock %}

{% block content %}
    消えました。
{% endblock %}

{% block bodyscript %}
{% endblock %}


text:
package org.usfirst.frc2876.Steamworks2017.commands;

import org.usfirst.frc2876.Steamworks2017.Robot;

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

/**
 *
 */
public class InverseDrive extends Command {

    public InverseDrive() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    	requires(Robot.driveTrain);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
//    	Robot.driveTrain.toggleInverseDrive();
    }

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

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

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

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


text:
"""Module to handle installing requirements."""
import asyncio
from functools import partial
import logging
import os
import sys
from typing import Any, Dict, List, Optional
from urllib.parse import urlparse

import pkg_resources

import homeassistant.util.package as pkg_util
from homeassistant.core import HomeAssistant

DATA_PIP_LOCK = 'pip_lock'
DATA_PKG_CACHE = 'pkg_cache'
CONSTRAINT_FILE = 'package_constraints.txt'
_LOGGER = logging.getLogger(__name__)

async def async_process_requirements(hass: HomeAssistant, name: str,
                                     requirements: List[str]) -> bool:
    """Install the requirements for a component or platform.

    This method is a coroutine.
    """
    pip_lock = hass.data.get(DATA_PIP_LOCK)
    if pip_lock is None:
        pip_lock = hass.data[DATA_PIP_LOCK] = asyncio.Lock(loop=hass.loop)

    pkg_cache = hass.data.get(DATA_PKG_CACHE)
    if pkg_cache is None:
        pkg_cache = hass.data[DATA_PKG_CACHE] = PackageLoadable(hass)

    pip_install = partial(pkg_util.install_package,
                          **pip_kwargs(hass.config.config_dir))

    async with pip_lock:
        for req in requirements:
            if await pkg_cache.loadable(req):
                continue

            ret = await hass.async_add_executor_job(pip_install, req)

            if not ret:
                _LOGGER.error("Not initializing %s because could not install "
                              "requirement %s", name, req)
                return False

    return True

def pip_kwargs(config_dir: Optional[str]) -> Dict[str, Any]:
    """Return keyword arguments for PIP install."""
    kwargs = {
        'constraints': os.path.join(os.path.dirname(__file__), CONSTRAINT_FILE)
    }
    if not (config_dir is None or pkg_util.is_virtual_env()):
        kwargs['target'] = os.path.join(config_dir, 'deps')
    return kwargs

class PackageLoadable:
    """Class to check if a package is loadable, with built-in cache."""

    def __init__(self, hass: HomeAssistant) -> None:
        """Initialize the PackageLoadable class."""
        self.dist_cache = {}  # type: Dict[str, pkg_resources.Distribution]
        self.hass = hass

    async def loadable(self, package: str) -> bool:
        """Check if a package is what will be loaded when we import it.

        Returns True when the requirement is met.
        Returns False when the package is not installed or doesn't meet req.
        """
        dist_cache = self.dist_cache

        try:
            req = pkg_resources.Requirement.parse(package)
        except ValueError:
            # This is a zip file. We no longer use this in Home Assistant,
            # leaving it in for custom components.
            req = pkg_resources.Requirement.parse(urlparse(package).fragment)

        req_proj_name = req.project_name.lower()
        dist = dist_cache.get(req_proj_name)

        if dist is not None:
            return dist in req

        for path in sys.path:
            # We read the whole mount point as we're already here
            # Caching it on first call makes subsequent calls a lot faster.
            await self.hass.async_add_executor_job(self._fill_cache, path)

            dist = dist_cache.get(req_proj_name)
            if dist is not None:
                return dist in req

        return False

    def _fill_cache(self, path: str) -> None:
        """Add packages from a path to the cache."""
        dist_cache = self.dist_cache
        for dist in pkg_resources.find_distributions(path):
            dist_cache.setdefault(dist.project_name.lower(), dist)


text:
<?php

namespace luya\news\admin;

use luya\admin\components\AdminMenuBuilder;

/**
 * News Admin Module.
 *
 * @author Basil Suter <basil@nadar.io>
 */
final class Module extends \luya\admin\base\Module
{
    public $apis = [
        'api-news-article' => 'luya\news\admin\apis\ArticleController',
        'api-news-tag' => 'luya\news\admin\apis\TagController',
        'api-news-cat' => 'luya\news\admin\apis\CatController',
    ];

    /**
     * @inheritdoc
     */
    public function getMenu()
    {
        return (new AdminMenuBuilder($this))
            ->node('news', 'local_library')
                ->group('news_administrate')
                    ->itemApi('article', 'newsadmin/article/index', 'edit', 'api-news-article')
                    ->itemApi('cat', 'newsadmin/cat/index', 'bookmark_border', 'api-news-cat');
    }

    public static function onLoad()
    {
        self::registerTranslation('newsadmin', '@newsadmin/messages', [
            'newsadmin' => 'newsadmin.php',
        ]);
    }

    /**
     * Translat news messages.
     *
     * @param string $message
     * @param array $params
     * @return string
     */
    public static function t($message, array $params = [])
    {
        return parent::baseT('newsadmin', $message, $params);
    }
}


text:
Curviation runs on [node.js >= v0.10](https://nodejs.org/).
You need to install node on the machine that will run the Curviation server.

## Installation

__Clone the repository__

    git clone https://github.com/Elao/Curviation.git
    cd Curviation

__Install dependencies__

    npm install
    bower install

__Build the game__

    gulp

## Launch server

    node bin/Curviation.js

## Play

Go to [http://localhost:8080/](http://localhost:8080/)
Join a room, choose a player name and play!


text:
<BroadcastMonitor>
  <updated>2015-08-06T21:50:13</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime></startTime>
    <itemId></itemId>
    <titleId></titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName></titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode></CategoryCode>
    <CategoryName></CategoryName>
    <itemDuration></itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-06T21:50:12</startTime>
    <itemId>1000080577:0</itemId>
    <titleId>216138975</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>Mark Ronson over Amy hoe de Daptones You Know I'm No Good maakten (NPR Fresh Air)</titleName>
    <artistName>AUDIOLINK</artistName>
    <albumName></albumName>
    <CategoryCode>751</CategoryCode>
    <CategoryName>INVOER</CategoryName>
    <itemDuration>55</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
using System;

namespace _15.Fast_Prime_Checker
{
    class Program
    {
        static void Main(string[] args)
        {
            int N = int.Parse(Console.ReadLine());
            for (int numbers = 2; numbers <= N; numbers++)
            {
                bool isTrue = PrimeCheck(numbers);
                Console.WriteLine($"{numbers} -> {isTrue}");
            }

        }

        static bool PrimeCheck(int numbers)
        {
            bool isTrue = true;
            for (int divide = 2; divide <= Math.Sqrt(numbers); divide++)
            {
                if (numbers % divide == 0)
                {
                    isTrue = false;
                    break;
                }
            }
            return isTrue;
        }
    }
}


text:
class BooksController < ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy]

  # GET /books
  # GET /books.json
  def index
    @books = Book.all
  end

  # GET /books/1
  # GET /books/1.json
  def show
  end

  # GET /books/new
  def new
    @book = Book.new
  end

  # GET /books/1/edit
  def edit
  end

  # POST /books
  # POST /books.json
  def create
    @book = Book.new(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
        format.json { render action: 'show', status: :created, location: @book }
      else
        format.html { render action: 'new' }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /books/1
  # PATCH/PUT /books/1.json
  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1
  # DELETE /books/1.json
  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:title, :author=>[])
    end
end


text:
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import time
import uuid

import pytest
from mock import patch

pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))  # noqa
sys.path.insert(0, pkg_root)  # noqa

import toil
from toil import resolveEntryPoint
from toil.common import Config, Toil
from toil.job import Job
from toil.lib.bioio import system
from toil.test import (ToilTest,
                       integrative,
                       needs_aws_ec2,
                       needs_cwl,
                       needs_docker,
                       needs_rsync3,
                       slow,
                       travis_test,
                       get_temp_file)
from toil.test.sort.sortTest import makeFileToSort
from toil.utils.toilStats import getStats, processData
from toil.utils.toilStatus import ToilStatus
from toil.version import python

logger = logging.getLogger(__name__)

class UtilsTest(ToilTest):
    """
    Tests the utilities that toil ships with, e.g. stats and status, in conjunction with restart
    functionality.
    """

    def setUp(self):
        super(UtilsTest, self).setUp()
        self.tempDir = self._createTempDir()
        self.tempFile = get_temp_file(rootDir=self.tempDir)
        self.outputFile = 'someSortedStuff.txt'
        self.toilDir = os.path.join(self.tempDir, "jobstore")
        self.assertFalse(os.path.exists(self.toilDir))
        self.lines = 1000
        self.lineLen = 10
        self.N = 1000
        makeFileToSort(self.tempFile, self.lines, self.lineLen)
        # First make our own sorted version
        with open(self.tempFile, 'r') as fileHandle:
            self.correctSort = fileHandle.readlines()
            self.correctSort.sort()

        self.sort_workflow_cmd = [
            python,
            '-m',
            'toil.test.sort.sort',
            f'file:{self.toilDir}',
            '--clean=never',
            '--numLines=1',
            '--lineLength=1'
        ]

        self.restart_sort_workflow_cmd = [
            python,
            '-m',
            'toil.test.sort.restart_sort',
            f'file:{self.toilDir}'
        ]

    def tearDown(self):
        if os.path.exists(self.tempDir):
            shutil.rmtree(self.tempDir)
        if os.path.exists(self.toilDir):
            shutil.rmtree(self.toilDir)

        for f in ['fileToSort.txt', 'sortedFile.txt', 'output.txt']:
            if os.path.exists(f):
                os.remove(f)

        ToilTest.tearDown(self)

    @property
    def toilMain(self):
        return resolveEntryPoint('toil')

    @property
    def cleanCommand(self):
        return [self.toilMain, 'clean', self.toilDir]

    @property
    def statsCommand(self):
        return [self.toilMain, 'stats', self.toilDir, '--pretty']

    def statusCommand(self, failIfNotComplete=False):
        commandTokens = [self.toilMain, 'status', self.toilDir]
        if failIfNotComplete:
            commandTokens.append('--failIfNotComplete')
        return commandTokens

    @needs_rsync3
    @pytest.mark.timeout(1200)
    @needs_aws_ec2
    @integrative
    @slow
    def testAWSProvisionerUtils(self):
        """
        Runs a number of the cluster utilities in sequence.

        Launches a cluster with custom tags.
        Verifies the tags exist.
        ssh's into the cluster.
        Does some weird string comparisons.
        Makes certain that TOIL_WORKDIR is set as expected in the ssh'ed cluster.
        Rsyncs a file and verifies it exists on the leader.
        Destroys the cluster.

        :return:
        """
        # TODO: Run these for the other clouds.
        clusterName = f'cluster-utils-test{uuid.uuid4()}'
        keyName = os.getenv('TOIL_AWS_KEYNAME').strip() or 'id_rsa'

        try:
            from toil.provisioners.aws.awsProvisioner import AWSProvisioner
            aws_provisioner = AWSProvisioner.__module__
            logger.debug(f"Found AWSProvisioner: {aws_provisioner}.")

            # launch master with an assortment of custom tags
            system([self.toilMain, 'launch-cluster', '--clusterType', 'mesos',
                    '-t', 'key1=value1', '-t', 'key2=value2', '--tag', 'key3=value3',
                    '--leaderNodeType=t2.medium', '--keyPairName=' + keyName, clusterName,
                    '--provisioner=aws', '--zone=us-west-2a', '--logLevel=DEBUG'])

            from toil.provisioners import cluster_factory
            cluster = toil.provisioners.cluster_factory(provisioner='aws', zone='us-west-2a', clusterName=clusterName)
            leader = cluster.getLeader()

            # check that the leader carries the appropriate tags
            tags = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'Name': clusterName, 'Owner': keyName}
            for key in tags:
                self.assertEqual(leader.tags.get(key), tags[key])
        finally:
            system([self.toilMain, 'destroy-cluster', '--zone=us-west-2a', '--provisioner=aws', clusterName])

    @slow
    def testUtilsSort(self):
        """
        Tests the status and stats commands of the toil command line utility using the
        sort example with the --restart flag.
        """
        # Get the sort command to run
        toilCommand = [sys.executable,
                       '-m', toil.test.sort.sort.__name__,
                       self.toilDir,
                       '--logLevel=DEBUG',
                       '--fileToSort', self.tempFile,
                       '--outputFile', self.outputFile,
                       '--N', str(self.N),
                       '--stats',
                       '--retryCount=2',
                       '--badWorker=0.5',
                       '--badWorkerFailInterval=0.05']
        # Try restarting it to check that a JobStoreException is thrown
        self.assertRaises(subprocess.CalledProcessError, system, toilCommand + ['--restart'])
        # Check that trying to run it in restart mode does not create the jobStore
        self.assertFalse(os.path.exists(self.toilDir))

        # Status command
        # Run the script for the first time
        try:
            system(toilCommand)
            finished = True
        except subprocess.CalledProcessError:  # This happens when the script fails due to having unfinished jobs
            system(self.statusCommand())
            self.assertRaises(subprocess.CalledProcessError, system, self.statusCommand(failIfNotComplete=True))
            finished = False
        self.assertTrue(os.path.exists(self.toilDir))

        # Try running it without restart and check an exception is thrown
        self.assertRaises(subprocess.CalledProcessError, system, toilCommand)

        # Now restart it until done
        totalTrys = 1
        while not finished:
            try:
                system(toilCommand + ['--restart'])
                finished = True
            except subprocess.CalledProcessError:  # This happens when the script fails due to having unfinished jobs
                system(self.statusCommand())
                self.assertRaises(subprocess.CalledProcessError, system, self.statusCommand(failIfNotComplete=True))
                if totalTrys > 16:
                    self.fail()  # Exceeded a reasonable number of restarts
                totalTrys += 1

        # Check the toil status command does not issue an exception
        system(self.statusCommand())

        # Check we can run 'toil stats'
        system(self.statsCommand)

        # Check the file is properly sorted
        with open(self.outputFile, 'r') as fileHandle:
            l2 = fileHandle.readlines()
            self.assertEqual(self.correctSort, l2)

        # Delete output file before next step
        os.remove(self.outputFile)

        # Check we can run 'toil clean'
        system(self.cleanCommand)

    @slow
    def testUtilsStatsSort(self):
        """
        Tests the stats commands on a complete run of the stats test.
        """
        # Get the sort command to run
        toilCommand = [sys.executable,
                       '-m', toil.test.sort.sort.__name__,
                       self.toilDir,
                       '--logLevel=DEBUG',
                       '--fileToSort', self.tempFile,
                       '--outputFile', self.outputFile,
                       '--N', str(self.N),
                       '--stats',
                       '--retryCount=99',
                       '--badWorker=0.5',
                       '--badWorkerFailInterval=0.01']

        # Run the script for the first time
        system(toilCommand)
        self.assertTrue(os.path.exists(self.toilDir))

        # Check we can run 'toil stats'
        system(self.statsCommand)

        # Check the file is properly sorted
        with open(self.outputFile, 'r') as fileHandle:
            l2 = fileHandle.readlines()
            self.assertEqual(self.correctSort, l2)

        # Delete output file
        os.remove(self.outputFile)

    @travis_test
    def testUnicodeSupport(self):
        options = Job.Runner.getDefaultOptions(self._getTestJobStorePath())
        options.clean = 'always'
        options.logLevel = 'debug'
        Job.Runner.startToil(Job.wrapFn(printUnicodeCharacter), options)

    @slow
    def testMultipleJobsPerWorkerStats(self):
        """
        Tests case where multiple jobs are run on 1 worker to ensure that all jobs report back their data
        """
        options = Job.Runner.getDefaultOptions(self._getTestJobStorePath())
        options.clean = 'never'
        options.stats = True
        Job.Runner.startToil(RunTwoJobsPerWorker(), options)
        config = Config()
        config.setOptions(options)
        jobStore = Toil.resumeJobStore(config.jobStore)
        stats = getStats(jobStore)
        collatedStats = processData(jobStore.config, stats)
        self.assertTrue(len(collatedStats.job_types) == 2, "Some jobs are not represented in the stats.")

    def check_status(self, status, status_fn, seconds=10):
        i = 0.0
        while status_fn(self.toilDir) != status:
            time.sleep(0.5)
            i += 0.5
            if i > seconds:
                s = status_fn(self.toilDir)
                self.assertEqual(s, status, 'Status took longer than 10 seconds to fetch:  %s' % s)

    @travis_test
    def testGetPIDStatus(self):
        """Test that ToilStatus.getPIDStatus() behaves as expected."""
        wf = subprocess.Popen(self.sort_workflow_cmd)
        self.check_status('RUNNING', status_fn=ToilStatus.getPIDStatus)
        wf.wait()
        self.check_status('COMPLETED', status_fn=ToilStatus.getPIDStatus)

        # TODO: we need to reach into the FileJobStore's files and
        # delete this shared file. We assume we know its internal layout.
        os.remove(os.path.join(self.toilDir, 'files/shared/pid.log'))
        self.check_status('QUEUED', status_fn=ToilStatus.getPIDStatus)

    @travis_test
    def testGetStatusFailedToilWF(self):
        """
        Test that ToilStatus.getStatus() behaves as expected with a failing Toil workflow.
        While this workflow could be called by importing and evoking its main function, doing so would remove the
        opportunity to test the 'RUNNING' functionality of getStatus().
        """
        # --badWorker is set to force failure.
        wf = subprocess.Popen(self.sort_workflow_cmd + ['--badWorker=1'])
        self.check_status('RUNNING', status_fn=ToilStatus.getStatus)
        wf.wait()
        self.check_status('ERROR', status_fn=ToilStatus.getStatus)

    @needs_cwl
    @needs_docker
    def testGetStatusFailedCWLWF(self):
        """Test that ToilStatus.getStatus() behaves as expected with a failing CWL workflow."""
        # --badWorker is set to force failure.
        cmd = ['toil-cwl-runner', '--jobStore', self.toilDir, '--clean=never', '--badWorker=1',
               'src/toil/test/cwl/sorttool.cwl', '--reverse', '--input', 'src/toil/test/cwl/whale.txt']
        wf = subprocess.Popen(cmd)
        self.check_status('RUNNING', status_fn=ToilStatus.getStatus)
        wf.wait()
        self.check_status('ERROR', status_fn=ToilStatus.getStatus)

    @needs_cwl
    @needs_docker
    def testGetStatusSuccessfulCWLWF(self):
        """Test that ToilStatus.getStatus() behaves as expected with a successful CWL workflow."""
        cmd = ['toil-cwl-runner', '--jobStore', self.toilDir, '--clean=never',
               'src/toil/test/cwl/sorttool.cwl', '--reverse', '--input', 'src/toil/test/cwl/whale.txt']
        wf = subprocess.Popen(cmd)
        self.check_status('RUNNING', status_fn=ToilStatus.getStatus)
        wf.wait()
        self.check_status('COMPLETED', status_fn=ToilStatus.getStatus)

    @needs_cwl
    @patch('builtins.print')
    def testPrintJobLog(self, mock_print):
        """Test that ToilStatus.printJobLog() reads the log from a failed command without error."""
        # Run a workflow that will always fail
        cmd = ['toil-cwl-runner', '--jobStore', self.toilDir, '--clean=never',
               'src/toil/test/cwl/alwaysfails.cwl', '--message', 'Testing']
        wf = subprocess.Popen(cmd)
        wf.wait()
        # print log and check output
        status = ToilStatus(self.toilDir)
        status.printJobLog()

        # Make sure it printed some kind of complaint about the missing command.
        args, kwargs = mock_print.call_args
        self.assertIn('invalidcommand', args[0])

    def testRestartAttribute(self):
        """
        Test that the job store is only destroyed when we observe a succcessful workflow run.
        The following simulates a failing workflow that attempts to resume without restart().
        In this case, the job store should not be destroyed until restart() is called.
        """
        # Run a workflow that will always fail
        cmd = self.restart_sort_workflow_cmd + ['--badWorker=1']
        subprocess.run(cmd)

        restart_cmd = self.restart_sort_workflow_cmd + ['--badWorker=0', '--restart']
        subprocess.run(restart_cmd)

        # Check the job store exists after restart attempt
        self.assertTrue(os.path.exists(self.toilDir))

        successful_cmd = [python, '-m', 'toil.test.sort.sort', 'file:' + self.toilDir,
                                  '--restart']
        subprocess.run(successful_cmd)

        # Check the job store is destroyed after calling restart()
        self.assertFalse(os.path.exists(self.toilDir))

def printUnicodeCharacter():
    # We want to get a unicode character to stdout but we can't print it directly because of
    # Python encoding issues. To work around this we print in a separate Python process. See
    # http://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python
    subprocess.check_call([sys.executable, '-c', "print('\\xc3\\xbc')"])

class RunTwoJobsPerWorker(Job):
    """
    Runs child job with same resources as self in an attempt to chain the jobs on the same worker
    """
    def __init__(self):
        Job.__init__(self)

    def run(self, fileStore):
        self.addChildFn(printUnicodeCharacter)


text: Data gets put here.


text:
import os

from setuptools import setup, find_packages

def read(fname):
    with open(os.path.join(os.path.dirname(__file__), fname)) as fn:
        return fn.read()

with open('requirements.txt') as f:
    required = f.read().splitlines()

with open('test-requirements.txt') as f:
    required_for_tests = f.read().splitlines()

setup(
    name='steel_pigs',
    version='0.1',
    packages=find_packages(exclude=["tests", "*.tests", "tests.*", "*.tests.*"]),
    url='https://github.com/virtdevninja/steel_pigs',
    license='License :: OSI Approved :: Apache Software License',
    author='Michael Rice',
    author_email='michael@michaelrice.org',
    description='Powerful iPXE Generation Service',
    long_description=read('README.rst'),
    platforms=['Windows', 'Linux', 'Solaris', 'Mac OS-X', 'Unix'],
    test_suite='tests',
    tests_require=required_for_tests,
    package_data={
        'static': 'steel_pigs/static/*',
        'templates': 'steel_pigs/templates/*'
    },
    zip_safe=False,
    include_package_data=True,
    setup_requires=[required_for_tests]
)


text:
/**
  __          _      _         _
 / _|        | |    (_)       (_)
| |_ __ _  __| | ___ _ _ __    _ ___
|  _/ _` |/ _` |/ _ \ | '_ \  | / __|
| || (_| | (_| |  __/ | | | |_| \__ \
|_| \__,_|\__,_|\___|_|_| |_(_) |___/
                             _/ |
                            |__/

Filename: fadein.js
Description: A jQuery extension that fades in objects
once they appear within the active browser view.
Author: Zach Alam
Example: http://everbranded.com/
*/

// ----------------------------------------------------------------

// CONFIGURATION VARIABLES

// default delay: the default amount of time to wait in milliseconds
// before the fading in of an element begins.
var default_delay = 0;

// default speed: the default amount of time in milliseconds that
// elapses during the fade in animation.
var default_speed = 600;

// ----------------------------------------------------------------

// verify the DOM is completely loaded.
$(document).ready(function() {

	// function that defines the fading in of an element.
	function element_fade(element)
	{
		// check if a "delay" exists.
		var obj_delay = default_delay;
		if($(element).attr("data-delay")) obj_delay = $(element).attr("data-delay");

		// check if a "speed" exists.
		var obj_speed = default_speed;
		if($(element).attr("data-speed")) obj_speed = $(element).attr("data-speed");

		// animate the fading in of object.
		$(element).delay(obj_delay).animate({'opacity':'1'}, obj_speed);
	}

	// function that defines the fading in of a element (when scrolled).
	function element_fade_scroll(element)
	{
		// calculate the halfway to the bottom of the object.
		var object_bottom = $(element).offset().top + ($(element).outerHeight()/2);

		// calculate the bottom of the window.
		var window_bottom = $(window).scrollTop() + $(window).height();

		// check if the bottom of the window is now higher than the bottom
		// of the object to fade in.
		if(window_bottom > object_bottom)
		{
			// animate the fadein.
			element_fade(element);
		}
	}

	// --------------------------------------------------------------

	// when the page initially loads, make all fadein objects invisible.
	$(".fadein").each(function() {

		// this opacity should be set in the CSS but
		// is set here again for redundancy.
		$(this).css("opacity","0");

		// check to see if this element has a "always" attribute,
		// if so we'll fade the object in regardless of its position.
		if($(this).attr("data-always")) element_fade(this);

		// fade in any elements that are in the active view
		element_fade_scroll(this);

	}); // end $(".fadein").each();

	// after the page is loaded, check that a scroll action has happened.
	$(window).scroll(function() {

		// look through all fadein classes.
		$(".fadein").each(function() {

			element_fade_scroll(this);

		}); // end $(".fadein").each();

	}); // end $(window).scroll();

}); // end $(document).ready();


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 11-jun-2015 19:38:58 by Hibernate Tools 4.3.1 -->
<hibernate-mapping package="modelo.dominio.dto">
 <class name="modelo.dominio.dto.Departments" table="DEPARTMENTS">
  <comment>Departments table that shows details of departments where employees work. Contains 27 rows; references with locations, employees, and job_history
        tables.</comment>
  <id name="departmentId" type="short">
   <column name="DEPARTMENT_ID" precision="4" scale="0"/>
   <generator class="assigned"/>
  </id>
  <many-to-one class="modelo.dominio.dto.Locations" fetch="select" name="locations">
   <column name="LOCATION_ID" precision="4" scale="0">
    <comment>Location id where a department is located. Foreign key to location_id column of locations table.</comment>
   </column>
  </many-to-one>
  <many-to-one class="modelo.dominio.dto.Employees" fetch="select" name="employees">
   <column name="MANAGER_ID" precision="6" scale="0">
    <comment>Manager_id of a department. Foreign key to employee_id column of employees table. The manager_id column of the employee table references this
                column.</comment>
   </column>
  </many-to-one>
  <property generated="never" lazy="false" name="departmentName" type="string">
   <column length="30" name="DEPARTMENT_NAME" not-null="true">
    <comment>A not null column that shows name of a department. Administration, Marketing, Purchasing, Human Resources, Shipping, IT, Executive, Public Relations,
                Sales, Finance, and Accounting.</comment>
   </column>
  </property>
  <set fetch="select" inverse="true" lazy="true" name="employeeses"
   sort="unsorted" table="EMPLOYEES">
   <key>
    <column name="DEPARTMENT_ID" precision="4" scale="0">
     <comment>Department id where employee works; foreign key to department_id column of the departments table</comment>
    </column>
   </key>
   <one-to-many class="modelo.dominio.dto.Employees"/>
  </set>
  <set fetch="select" inverse="true" lazy="true" name="jobHistories"
   sort="unsorted" table="JOB_HISTORY">
   <key>
    <column name="DEPARTMENT_ID" precision="4" scale="0">
     <comment>Department id in which the employee worked in the past; foreign key to deparment_id column in the departments table</comment>
    </column>
   </key>
   <one-to-many class="modelo.dominio.dto.JobHistory"/>
  </set>
 </class>
</hibernate-mapping>


text:
_[www.codever.land/bookmarks/t/relational-database](https://www.codever.land/bookmarks/t/relational-database)_
---
#### [postgrest](https://github.com/begriffs/postgrest)
_https://github.com/begriffs/postgrest_

Serve a fully RESTful API directly from an existing PostgreSQL database.
* **tags**: [rest](../tagged/rest.md), [server](../tagged/server.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/begriffs/postgrest)**
---
#### [MySQL HTTP plugin](http://blog.ulf-wendel.de/2014/mysql-5-7-http-plugin-mysql/)
_http://blog.ulf-wendel.de/2014/mysql-5-7-http-plugin-mysql/_

Simple REST-like / CRUD server for any MySQL database.
* **tags**: [rest](../tagged/rest.md), [server](../tagged/server.md), [relational-database](../tagged/relational-database.md)
---
#### [pREST](https://github.com/prest/prest)
_https://github.com/prest/prest_

A fully RESTful API from any existing PostgreSQL database written in Go.
* **tags**: [rest](../tagged/rest.md), [server](../tagged/server.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/prest/prest)**
---
#### [avatica](https://github.com/apache/calcite-avatica-go)
_https://github.com/apache/calcite-avatica-go_

Apache Avatica/Phoenix SQL driver for database/sql.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/apache/calcite-avatica-go)**
---
#### [bgc](https://github.com/viant/bgc)
_https://github.com/viant/bgc_

Datastore Connectivity for BigQuery for go.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/viant/bgc)**
---
#### [firebirdsql](https://github.com/nakagami/firebirdsql)
_https://github.com/nakagami/firebirdsql_

Firebird RDBMS SQL driver for Go.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/nakagami/firebirdsql)**
---
#### [go-adodb](https://github.com/mattn/go-adodb)
_https://github.com/mattn/go-adodb_

Microsoft ActiveX Object DataBase driver for go that uses database/sql.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/mattn/go-adodb)**
---
#### [go-mssqldb](https://github.com/denisenkom/go-mssqldb)
_https://github.com/denisenkom/go-mssqldb_

Microsoft MSSQL driver for Go.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/denisenkom/go-mssqldb)**
---
#### [go-oci8](https://github.com/mattn/go-oci8)
_https://github.com/mattn/go-oci8_

Oracle driver for go that uses database/sql.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/mattn/go-oci8)**
---
#### [go-sql-driver/mysql](https://github.com/go-sql-driver/mysql)
_https://github.com/go-sql-driver/mysql_

MySQL driver for Go.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/go-sql-driver/mysql)**
---
#### [go-sqlite3](https://github.com/mattn/go-sqlite3)
_https://github.com/mattn/go-sqlite3_

SQLite3 driver for go that uses database/sql.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/mattn/go-sqlite3)**
---
#### [gofreetds](https://github.com/minus5/gofreetds)
_https://github.com/minus5/gofreetds_

Microsoft MSSQL driver. Go wrapper over [FreeTDS](http://www.freetds.org).
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/minus5/gofreetds)**
---
#### [goracle](https://github.com/go-goracle/goracle)
_https://github.com/go-goracle/goracle_

Oracle driver for Go, using the ODPI-C driver.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/go-goracle/goracle)**
---
#### [pgx](https://github.com/jackc/pgx)
_https://github.com/jackc/pgx_

PostgreSQL driver supporting features beyond those exposed by database/sql.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/jackc/pgx)**
---
#### [pq](https://github.com/lib/pq)
_https://github.com/lib/pq_

Pure Go Postgres driver for database/sql.
* **tags**: [go](../tagged/go.md), [database-drivers](../tagged/database-drivers.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/lib/pq)**
---
#### [Django Models](https://docs.djangoproject.com/en/dev/topics/db/models/)
_https://docs.djangoproject.com/en/dev/topics/db/models/_

A part of Django.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
---
#### [SQLAlchemy](https://www.sqlalchemy.org/)
_https://www.sqlalchemy.org/_

The Python SQL Toolkit and Object Relational Mapper.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
---
#### [awesome-sqlalchemy](https://github.com/dahlia/awesome-sqlalchemy)
_https://github.com/dahlia/awesome-sqlalchemy_

A curated list of awesome tools for SQLAlchemy. Contribute to dahlia/awesome-sqlalchemy development by creating an account on GitHub.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/dahlia/awesome-sqlalchemy)**
---
#### [dataset](https://github.com/pudo/dataset)
_https://github.com/pudo/dataset_

Store Python dicts in a database - works with SQLite, MySQL, and PostgreSQL.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/pudo/dataset)**
---
#### [orator](https://github.com/sdispater/orator)
_https://github.com/sdispater/orator_

The Orator ORM provides a simple yet beautiful ActiveRecord implementation.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/sdispater/orator)**
---
#### [peewee](https://github.com/coleifer/peewee)
_https://github.com/coleifer/peewee_

A small, expressive ORM.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/coleifer/peewee)**
---
#### [pony](https://github.com/ponyorm/pony/)
_https://github.com/ponyorm/pony/_

ORM that provides a generator-oriented interface to SQL.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/ponyorm/pony/)**
---
#### [pydal](https://github.com/web2py/pydal/)
_https://github.com/web2py/pydal/_

A pure Python Database Abstraction Layer.
* **tags**: [python](../tagged/python.md), [orm](../tagged/orm.md), [relational-database](../tagged/relational-database.md)
* :octocat: **[source code](https://github.com/web2py/pydal/)**
---


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery

Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
    ''' <summary>
    ''' Recommends the "While" keyword at the start of a statement. "While" as a part of a Do statement is handled in
    ''' the UntilAndWhileKeywordRecommender.
    ''' </summary>
    Friend Class WhileLoopKeywordRecommender
        Inherits AbstractKeywordRecommender

        Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
            If context.IsMultiLineStatementContext Then
                Return SpecializedCollections.SingletonEnumerable(New RecommendedKeyword("While", VBFeaturesResources.WhileKeywordToolTip))
            End If

            ' Are we after Exit or Continue?
            If context.FollowsEndOfStatement Then
                Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
            End If

            Dim targetToken = context.TargetToken
            If targetToken.IsKind(SyntaxKind.ExitKeyword, SyntaxKind.ContinueKeyword) AndAlso
               context.IsInStatementBlockOfKind(SyntaxKind.WhileBlock) AndAlso
               Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then

                Return SpecializedCollections.SingletonEnumerable(
                            New RecommendedKeyword("While",
                                                   If(targetToken.IsKind(SyntaxKind.ExitKeyword),
                                                                    VBFeaturesResources.ExitWhileKeywordToolTip,
                                                                    VBFeaturesResources.ContinueWhileKeywordToolTip)))
            End If

            Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
        End Function
    End Class
End Namespace


text:
import * as helpers from './helpers'

export default class OSClass {
  family: string;
  major: string;
  minor: string;
  patch: string;
  patchMinor: string;
  constructor(family: string | undefined = undefined, major: string | undefined = undefined, minor: string | undefined = undefined, patch: string | undefined = undefined, patchMinor: string | undefined = undefined) {
    this.family = family ? family.trim() : 'Other';
    this.major = major ? major.trim() : '';
    this.minor = minor ? minor.trim() : '';
    this.patch = patch ? patch.trim() : '';
    this.patchMinor = patchMinor ? patchMinor.trim() : '';
  }
  toVersionString = function () {
    let output = helpers.versionString(this.major, this.minor, this.patch, this.patchmMinor);
    return output || '';
  };

  toString = function () {
    let suffix = this.toVersionString();
    if (suffix) { suffix = ' ' + suffix; }
    return this.family + suffix;
  };

  static _makeParsers(obj) {
    var regexp = new RegExp(obj.regex, obj.regex_flag);
    var famRep = obj.os_replacement;
    var majorRep = obj.os_v1_replacement;
    var minorRep = obj.os_v2_replacement;
    var patchRep = obj.os_v3_replacement;
    var patchMinorRep = obj.os_v4_replacement;

    function parser(str) {
      let m = str.match(regexp);
      if (!m) { return ''; }

      let family = famRep ? m[0].replace(regexp, famRep) : m[1];
      let major = majorRep ? m[0].replace(regexp, majorRep) : m[2];
      let minor = minorRep ? m[0].replace(regexp, minorRep) : m[3];
      let patch = patchRep ? m[0].replace(regexp, patchRep) : m[4];
      let patchMinor = patchMinorRep ? m[0].replace(regexp, patchMinorRep) : m[5];

      return new OSClass(family, major, minor, patch, patchMinor);
    }

    return parser;
  }

  static makeParser(regexes) {
    var parsers = regexes.map(OSClass._makeParsers)

    function parser(str) {
      let obj;

      if (typeof str === 'string') {
        for (let i = 0, length = parsers.length; i < length; i++) {
          obj = parsers[i](str);
          if (obj) { return obj; }
        }
      }

      return obj || new OSClass();
    }

    return parser;
  }
}


text:
cd /root/ca
openssl genrsa -des3 \
      -out intermediate/private/www.example.com.key.pem 2048
chmod 400 intermediate/private/www.example.com.key.pem
openssl req -config intermediate/openssl.cnf \
      -key intermediate/private/www.example.com.key.pem \
      -new -sha256 -out intermediate/csr/www.example.com.csr.pem
openssl req -in intermediate/csr/www.example.com.csr.pem -text -noout

# sign the csr
# if the certificate is going to be used on a server, use the server_cert extension. if the certificate is going to be used for user authentication, use the usr_cert extension.
#
openssl ca -config intermediate/openssl.cnf \
      -extensions server_cert -days 375 -notext -md sha256 \
      -in intermediate/csr/www.example.com.csr.pem \
      -out intermediate/certs/www.example.com.cert.pem
chmod 444 intermediate/certs/www.example.com.cert.pem

# verify the certificate
openssl x509 -noout -text -in /root/ca/intermediate/certs/www.example.com.cert.pem


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include "arrow/util/compression_brotli.h"

#include <cstddef>
#include <cstdint>
#include <sstream>

#include <brotli/decode.h>
#include <brotli/encode.h>
#include <brotli/types.h>

#include "arrow/status.h"
#include "arrow/util/logging.h"
#include "arrow/util/macros.h"

namespace arrow {
namespace util {

// Brotli compression quality is max (11) by default, which is slow.
// We use 8 as a default as it is the best trade-off for Parquet workload.
constexpr int kBrotliDefaultCompressionLevel = 8;

// ----------------------------------------------------------------------
// Brotli decompressor implementation

class BrotliDecompressor : public Decompressor {
 public:
  BrotliDecompressor() {}

  ~BrotliDecompressor() override {
    if (state_ != nullptr) {
      BrotliDecoderDestroyInstance(state_);
    }
  }

  Status Init() {
    state_ = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
    if (state_ == nullptr) {
      return BrotliError("Brotli init failed");
    }
    return Status::OK();
  }

  Status Decompress(int64_t input_len, const uint8_t* input, int64_t output_len,
                    uint8_t* output, int64_t* bytes_read, int64_t* bytes_written,
                    bool* need_more_output) override {
    auto avail_in = static_cast<size_t>(input_len);
    auto avail_out = static_cast<size_t>(output_len);
    BrotliDecoderResult ret;

    ret = BrotliDecoderDecompressStream(state_, &avail_in, &input, &avail_out, &output,
                                        nullptr /* total_out */);
    if (ret == BROTLI_DECODER_RESULT_ERROR) {
      return BrotliError(BrotliDecoderGetErrorCode(state_), "Brotli decompress failed: ");
    }
    *need_more_output = (ret == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT);
    *bytes_read = static_cast<int64_t>(input_len - avail_in);
    *bytes_written = static_cast<int64_t>(output_len - avail_out);
    return Status::OK();
  }

  bool IsFinished() override { return BrotliDecoderIsFinished(state_); }

 protected:
  Status BrotliError(const char* msg) { return Status::IOError(msg); }

  Status BrotliError(BrotliDecoderErrorCode code, const char* prefix_msg) {
    return Status::IOError(prefix_msg, BrotliDecoderErrorString(code));
  }

  BrotliDecoderState* state_ = nullptr;
};

// ----------------------------------------------------------------------
// Brotli compressor implementation

class BrotliCompressor : public Compressor {
 public:
  BrotliCompressor() {}

  ~BrotliCompressor() override {
    if (state_ != nullptr) {
      BrotliEncoderDestroyInstance(state_);
    }
  }

  Status Init() {
    state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
    if (state_ == nullptr) {
      return BrotliError("Brotli init failed");
    }
    if (!BrotliEncoderSetParameter(state_, BROTLI_PARAM_QUALITY,
                                   kBrotliDefaultCompressionLevel)) {
      return BrotliError("Brotli set compression level failed");
    }
    return Status::OK();
  }

  Status Compress(int64_t input_len, const uint8_t* input, int64_t output_len,
                  uint8_t* output, int64_t* bytes_read, int64_t* bytes_written) override;

  Status Flush(int64_t output_len, uint8_t* output, int64_t* bytes_written,
               bool* should_retry) override;

  Status End(int64_t output_len, uint8_t* output, int64_t* bytes_written,
             bool* should_retry) override;

 protected:
  Status BrotliError(const char* msg) { return Status::IOError(msg); }

  BrotliEncoderState* state_ = nullptr;
};

Status BrotliCompressor::Compress(int64_t input_len, const uint8_t* input,
                                  int64_t output_len, uint8_t* output,
                                  int64_t* bytes_read, int64_t* bytes_written) {
  auto avail_in = static_cast<size_t>(input_len);
  auto avail_out = static_cast<size_t>(output_len);
  BROTLI_BOOL ret;

  ret = BrotliEncoderCompressStream(state_, BROTLI_OPERATION_PROCESS, &avail_in, &input,
                                    &avail_out, &output, nullptr /* total_out */);
  if (!ret) {
    return BrotliError("Brotli compress failed");
  }
  *bytes_read = static_cast<int64_t>(input_len - avail_in);
  *bytes_written = static_cast<int64_t>(output_len - avail_out);
  return Status::OK();
}

Status BrotliCompressor::Flush(int64_t output_len, uint8_t* output,
                               int64_t* bytes_written, bool* should_retry) {
  size_t avail_in = 0;
  const uint8_t* next_in = nullptr;
  auto avail_out = static_cast<size_t>(output_len);
  BROTLI_BOOL ret;

  ret = BrotliEncoderCompressStream(state_, BROTLI_OPERATION_FLUSH, &avail_in, &next_in,
                                    &avail_out, &output, nullptr /* total_out */);
  if (!ret) {
    return BrotliError("Brotli flush failed");
  }
  *bytes_written = static_cast<int64_t>(output_len - avail_out);
  *should_retry = !!BrotliEncoderHasMoreOutput(state_);
  return Status::OK();
}

Status BrotliCompressor::End(int64_t output_len, uint8_t* output, int64_t* bytes_written,
                             bool* should_retry) {
  size_t avail_in = 0;
  const uint8_t* next_in = nullptr;
  auto avail_out = static_cast<size_t>(output_len);
  BROTLI_BOOL ret;

  ret = BrotliEncoderCompressStream(state_, BROTLI_OPERATION_FINISH, &avail_in, &next_in,
                                    &avail_out, &output, nullptr /* total_out */);
  if (!ret) {
    return BrotliError("Brotli end failed");
  }
  *bytes_written = static_cast<int64_t>(output_len - avail_out);
  *should_retry = !!BrotliEncoderHasMoreOutput(state_);
  DCHECK_EQ(*should_retry, !BrotliEncoderIsFinished(state_));
  return Status::OK();
}

// ----------------------------------------------------------------------
// Brotli codec implementation

Status BrotliCodec::MakeCompressor(std::shared_ptr<Compressor>* out) {
  auto ptr = std::make_shared<BrotliCompressor>();
  RETURN_NOT_OK(ptr->Init());
  *out = ptr;
  return Status::OK();
}

Status BrotliCodec::MakeDecompressor(std::shared_ptr<Decompressor>* out) {
  auto ptr = std::make_shared<BrotliDecompressor>();
  RETURN_NOT_OK(ptr->Init());
  *out = ptr;
  return Status::OK();
}

Status BrotliCodec::Decompress(int64_t input_len, const uint8_t* input,
                               int64_t output_buffer_len, uint8_t* output_buffer) {
  return Decompress(input_len, input, output_buffer_len, output_buffer, nullptr);
}

Status BrotliCodec::Decompress(int64_t input_len, const uint8_t* input,
                               int64_t output_buffer_len, uint8_t* output_buffer,
                               int64_t* output_len) {
  std::size_t output_size = output_buffer_len;
  if (BrotliDecoderDecompress(input_len, input, &output_size, output_buffer) !=
      BROTLI_DECODER_RESULT_SUCCESS) {
    return Status::IOError("Corrupt brotli compressed data.");
  }
  if (output_len) {
    *output_len = output_size;
  }
  return Status::OK();
}

int64_t BrotliCodec::MaxCompressedLen(int64_t input_len,
                                      const uint8_t* ARROW_ARG_UNUSED(input)) {
  return BrotliEncoderMaxCompressedSize(input_len);
}

Status BrotliCodec::Compress(int64_t input_len, const uint8_t* input,
                             int64_t output_buffer_len, uint8_t* output_buffer,
                             int64_t* output_len) {
  std::size_t output_size = output_buffer_len;
  if (BrotliEncoderCompress(kBrotliDefaultCompressionLevel, BROTLI_DEFAULT_WINDOW,
                            BROTLI_DEFAULT_MODE, input_len, input, &output_size,
                            output_buffer) == BROTLI_FALSE) {
    return Status::IOError("Brotli compression failure.");
  }
  *output_len = output_size;
  return Status::OK();
}

}  // namespace util
}  // namespace arrow