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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.apache.commons.math3.optim.BaseMultiStartMultivariateOptimizer (Apache Commons Math 3.5 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.apache.commons.math3.optim.BaseMultiStartMultivariateOptimizer

Packages that use BaseMultiStartMultivariateOptimizer

Package
Description

org.apache.commons.math3.optim.nonlinear.scalar

Algorithms for optimizing a scalar function.

org.apache.commons.math3.optim.nonlinear.vector

Algorithms for optimizing a vector function.

Uses of BaseMultiStartMultivariateOptimizer in org.apache.commons.math3.optim.nonlinear.scalar

Subclasses of BaseMultiStartMultivariateOptimizer in org.apache.commons.math3.optim.nonlinear.scalar

Modifier and Type
Class and Description

class
MultiStartMultivariateOptimizer

Multi-start optimizer.

Uses of BaseMultiStartMultivariateOptimizer in org.apache.commons.math3.optim.nonlinear.vector

Subclasses of BaseMultiStartMultivariateOptimizer in org.apache.commons.math3.optim.nonlinear.vector

Modifier and Type
Class and Description

class
MultiStartMultivariateVectorOptimizer

Deprecated.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Copyright © 2003–2015 The Apache Software Foundation. All rights reserved.


text:
package goanna

import (
	"github.com/gorilla/mux"
	"log"
	"net/url"
)

// Router is a global router used for routing requests
var Router *mux.Router

// UrlBase is the base url used for creating absolute urls
var UrlBase url.URL

func init() {
	ClearRouter()
	UrlBase.Scheme = "http"
	UrlBase.Host = "localhost"
}

// ClearRouter clears the global router
func ClearRouter() {
	Router = mux.NewRouter()
}

// UrlFor returns the relative URL for the route name
func UrlFor(name string, args ...string) *url.URL {
	r := Router.Get(name)
	if r == nil {
		log.Panicf("UrlFor: No such route '%s'\n", name)
	}
	u, err := r.URL(args...)
	if err != nil {
		log.Panicln("UrlFor: " + err.Error())
	}
	return u
}

// UrlFor returns the avsolute URL for the route name.
// UrlBase is used for the URL Host and Scheme
func AbsoluteUrlFor(name string, args ...string) *url.URL {
	u := UrlFor(name, args...)
	u.Host = UrlBase.Host
	u.Scheme = UrlBase.Scheme
	return u
}

redpajama_set_name: RedPajamaGithub


text:
package org.drools.workbench.screens.guided.rule.client.editor;

import java.util.HashMap;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwtmockito.GwtMock;
import com.google.gwtmockito.GwtMockitoTestRunner;
import com.google.gwtmockito.WithClassesToStub;
import org.assertj.core.api.Assertions;
import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint;
import org.drools.workbench.models.datamodel.rule.CompositeFieldConstraint;
import org.drools.workbench.models.datamodel.rule.SingleFieldConstraint;
import org.drools.workbench.screens.guided.rule.client.widget.EnumDropDown;
import org.guvnor.common.services.workingset.client.WorkingSetManager;
import org.gwtbootstrap3.client.ui.TextBox;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.soup.project.datamodel.oracle.DataType;
import org.kie.workbench.common.services.shared.preferences.ApplicationPreferences;
import org.kie.workbench.common.widgets.client.datamodel.AsyncPackageDataModelOracle;
import org.kie.workbench.common.widgets.client.widget.LiteralTextBox;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;

import static org.junit.Assert.assertTrue;
import static org.kie.workbench.common.services.shared.preferences.ApplicationPreferences.DATE_FORMAT;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@WithClassesToStub(AddConstraintButton.class)
@RunWith(GwtMockitoTestRunner.class)
public class ConstraintValueEditorTest {

    @Mock
    private AsyncPackageDataModelOracle oracle;

    @Mock
    private SingleFieldConstraint constraint;

    @Mock
    private WorkingSetManager wsManager;

    @GwtMock
    private RuleModeller ruleModeller;

    @Mock
    private TemplateKeyTextBox templateKeyTextBox;

    @Before
    public void setup() {
        HashMap<String, String> map = new HashMap<>();
        map.put(DATE_FORMAT,
                "dd MMM yyyy");
        ApplicationPreferences.setUp(map);

        when(ruleModeller.getDataModelOracle()).thenReturn(oracle);
        when(oracle.getFieldType(any(),
                                 any())).thenReturn(DataType.TYPE_STRING);
        when(constraint.getConstraintValueType()).thenReturn(SingleFieldConstraint.TYPE_LITERAL);
    }

    @Test
    public void correctWidgetForStringField() {
        ConstraintValueEditor editor = createEditor(constraint);
        assertTrue(editor.getConstraintWidget() instanceof LiteralTextBox);
    }

    @Test
    public void correctWidgetForStringFieldValueInList() {
        when(constraint.getOperator()).thenReturn("in");
        ConstraintValueEditor editor = createEditor(constraint);
        assertTrue(editor.getConstraintWidget() instanceof LiteralTextBox);
    }

    @Test
    public void correctWidgetForStringFieldValueNotInList() {
        when(constraint.getOperator()).thenReturn("not in");
        ConstraintValueEditor editor = createEditor(constraint);
        assertTrue(editor.getConstraintWidget() instanceof LiteralTextBox);
    }

    @Test
    public void defaultTextBoxHasHandlersAttachedInCorrectOrder() {
        final TextBox defaultTextBox = mock(TextBox.class);
        final ConstraintValueEditor editor = spy(createEditor(constraint));
        final InOrder inOrder = inOrder(editor);

        doReturn(defaultTextBox).when(editor).getDefaultTextBox(any(String.class));

        editor.getNewTextBox(DataType.TYPE_STRING);

        inOrder.verify(editor).setUpTextBoxStyleAndHandlers(eq(defaultTextBox),
                                                            any());
        verify(defaultTextBox,
               times(1)).setText(any(String.class));
        inOrder.verify(editor).attachDisplayLengthHandler(eq(defaultTextBox));
    }

    @Test
    public void templateKeyEditorHasHandlersAttachedInCorrectOrder() {
        final ConstraintValueEditor editor = spy(createEditor(constraint));

        final InOrder inOrder = inOrder(editor);

        editor.templateKeyEditor();

        inOrder.verify(editor).setUpTextBoxStyleAndHandlers(eq(templateKeyTextBox),
                                                            any());
        verify(templateKeyTextBox,
               times(1)).setValue(any(String.class),
                                  any(Boolean.class));
        inOrder.verify(editor).attachDisplayLengthHandler(eq(templateKeyTextBox));
    }

    @Test
    public void testGetDrowpDown() {
        final String factType = "Car";
        final String factField = "color";
        final SingleFieldConstraint singleFieldConstraint = new SingleFieldConstraint() {{
            setFactType(factType);
            setFieldName(factField);
        }};
        final ConstraintValueEditor editor = spy(createEditor(singleFieldConstraint));

        // reset oracle due to calls in ConstraintValueEditor constructor
        reset(oracle);
        editor.initDropDownData();

        verify(oracle).getEnums(eq(factType), eq(factField), anyMap());
    }

    @Test
    public void testInitDropDown_BooleanFieldType() {
        final String factType = "Car";
        final String factField = "cheap";

        // reset oracle due to calls in @Before method
        reset(oracle);

        when(oracle.getFieldType(factType, factField)).thenReturn(DataType.TYPE_BOOLEAN);

        final SingleFieldConstraint singleFieldConstraint = new SingleFieldConstraint() {{
            setFactType(factType);
            setFieldName(factField);
            setConstraintValueType(TYPE_LITERAL);
        }};
        final ConstraintValueEditor editor = spy(createEditor(singleFieldConstraint));

        // EnumDropDown should be created because no enumeration loaded and field is Boolean type
        editor.initDropDownData();
        editor.refresh();
        Assertions.assertThat(editor.getConstraintWidget()).isInstanceOf(EnumDropDown.class);
    }

    @Test
    public void testInitializationOrder() {
        // DROOLS-2662 and DROOLS-2781
        // Create the dropdown before constraint value editor helper.
        final SingleFieldConstraint singleFieldConstraint = mock(SingleFieldConstraint.class);
        final ConstraintValueEditor editor = spy(createEditor(singleFieldConstraint));

        editor.init();

        final InOrder inOrder = Mockito.inOrder(editor);
        inOrder.verify(editor).initDropDownData();
        inOrder.verify(editor).constructConstraintValueEditorHelper();
        inOrder.verify(editor).refresh();
    }

    private ConstraintValueEditor createEditor(final BaseSingleFieldConstraint baseConstraint) {
        final ConstraintValueEditor editor = new ConstraintValueEditor(baseConstraint,
                                                                       mock(CompositeFieldConstraint.class),
                                                                       ruleModeller,
                                                                       mock(EventBus.class),
                                                                       false) {
            @Override
            void setBoxSize(final TextBox box) {
                //do nothing - avoid calling JavaScriptObject.cast()
            }

            @Override
            Widget wrap(Widget widget) {
                return widget;
            }

            @Override
            WorkingSetManager getWorkingSetManager() {
                return wsManager;
            }

            @Override
            TemplateKeyTextBox getTemplateKeyTextBox() {
                return templateKeyTextBox;
            }
        };

        editor.init();

        return editor;
    }
}


text:
using System;
using System.Collections.Generic;

public class BinaryHeap<T> where T : IComparable<T>
{
    private List<T> heap;

    public BinaryHeap()
    {
        this.heap = new List<T>();
    }

    public int Count
    {
        get
        {
            return this.heap.Count;
        }
    }

    public void Insert(T item)
    {
        this.heap.Add(item);
        this.HeapifyUp(this.heap.Count - 1);
    }

    private void HeapifyUp(int ItemIndex)
    {
        var parrentIndex = (ItemIndex - 1) / 2;

        var compare = this.heap[parrentIndex].CompareTo(this.heap[ItemIndex]);

        if (compare < 0)
        {
            Swap(parrentIndex, ItemIndex);
            ItemIndex = parrentIndex;
            this.HeapifyUp(ItemIndex);
        }
    }

    private void Swap(int parrentIndex, int itemIndex)
    {
        var temp = this.heap[parrentIndex];
        this.heap[parrentIndex] = this.heap[itemIndex];
        this.heap[itemIndex] = temp;
    }

    public T Peek()
    {
        return this.heap[0];
    }

    public T Pull()
    {
        if (this.Count == 0)
        {
            throw new InvalidOperationException();
        }

        var element = this.heap[0];

        Swap(0, this.Count - 1);

        this.heap.RemoveAt(this.Count - 1);

        this.HeapifyDown(0);

        return element;
    }

    private void HeapifyDown(int itemIndex)
    {
        if (this.Count / 2 > itemIndex)
        {
            var childIndex = (2 * itemIndex) + 1;

            if ((childIndex + 1) < this.Count - 1 &&
                this.heap[childIndex].CompareTo(this.heap[childIndex + 1]) < 0)
            {
                childIndex++;
            }

            var compare = this.heap[itemIndex].CompareTo(this.heap[childIndex]);

            if (compare < 0)
            {
                Swap(itemIndex, childIndex);

                itemIndex = childIndex;

                this.HeapifyDown(itemIndex);
            }
        }
    }
}


text:
package org.team619.crossout.program.ui;

import org.team619.crossout.program.LifeCycle;

import java.awt.*;
import java.awt.image.BufferedImage;

public interface UI extends LifeCycle {

    void draw(BufferedImage image);

    Robot getRobot();

    void press(int keyCode, int delay);

    void release(int keyCode, int delay);

    void move(int x, int y);

}


text:
django-components
=================

    An encapsulated thing that is meant to be reused across the site in many
    different views. Product reviews box, little stats widgets, etc. It's meant to
    be like a mini-version of a view that you can embed in another page.

    Benefits: easy to reuse code, change things in only one place to change
    them everywhere, cache components automatically, turn caching on and off
    without changing the template. All client side code (js, css, html) for one
    component is in one place. No mucking around with manual cache key
    generating.

    In your template, add:

        {% components_maker %}
        {% reviewscomponent subscriber %}

    Ta da.

    To build a new component, simply inherit Component and:
        - Override fetch_data to return the context for your component template
        - Override options to pass in any variables you need, like user ids.
        This is in Classytags format.
        - Declare name as the template file to use.
        - Optionally override any other (cache key, rendering) function for
        more complex behavior

    Overridables:
        - cached=True: enable / disable cache.
        - cache_duration=60*60*24: cache time in seconds.
        - tag_name=classname.lower(): name of the template tag
        - template_name: Name of the template to use
        - cache_vary_on: List of attribute names to get the value of when
        generating a cache key. Defaults to detecting the template tag
        arguments and using those.
        - sekizai_blocks: Dictionary of blockname -> content to inject js /
        css / etc into the template.

    TODO: maybe have post_render also cache subcontext data
    TODO: look into disabling offline compression to get compression to play
    nice with components/sekizai https://github.com/ojii/django-sekizai/issues/4


text:
package seedu.taskitty.commons.util;

import seedu.taskitty.model.task.Task;

//@@author A0139052L
/**
 * Helper functions for handling tasks related items.
 *
 */
public class TaskUtil {

    /**
     * Returns the specified index in the {@code command} IF a valid category
     * character was given. else return the default index
     */
    public static int getCategoryIndex(char category) {

        char lowerCaseCategory = Character.toLowerCase(category);
        switch (lowerCaseCategory) {

        case (Task.TODO_CATEGORY_CHAR):
            return Task.TODO_CATEGORY_INDEX;

        case (Task.DEADLINE_CATEGORY_CHAR):
            return Task.DEADLINE_CATEGORY_INDEX;

        case (Task.EVENT_CATEGORY_CHAR):
            return Task.EVENT_CATEGORY_INDEX;

        default:
            return getDefaultCategoryIndex();

        }
    }

    /**
     * Returns the default category index for when the user does not give any
     */
    public static int getDefaultCategoryIndex() {
        return Task.DEFAULT_CATEGORY_INDEX;
    }

}


text:
module Toggl
  module Api
    module Tag

      #  *name*: The name of the tag (string, required, unique in workspace)
      #  *wid*:  workspace ID, where the tag will be used (integer, required)

      def create_tag(name,wid)
        post "/tags", {"tag" => {"name" => name,"wid" =>wid}}
      end

      #tag wid can't be changed.
      #only name can be updated
      def update_tag_name(tag_id, name)
        put "/tags/#{tag_id}", {"tag" => {"name" => name}}
      end

      def delete_tag(tag_id)
        delete "/tags/#{tag_id}"
      end

    end
  end
end


text:
> Riprende job che sono stati sospesi (e.g. usando `Ctrl + Z`) mettendoli in esecuzione in background.

- Riprendi il job sospeso più recentemente ed eseguilo in background:

`bg`

- Riprendi uno specifico job (usa `jobs -l` per trovare l'ID) ed eseguilo in background:

`bg {{id_job}}`


text:
#ifndef __TBB_task_scheduler_observer_H
#define __TBB_task_scheduler_observer_H

#include "atomic.h"
#if __TBB_TASK_ARENA
#include "task_arena.h"
#endif //__TBB_TASK_ARENA

#if __TBB_SCHEDULER_OBSERVER

namespace tbb {
namespace interface6 {
class task_scheduler_observer;
}
namespace internal {

class observer_proxy;
class observer_list;

class task_scheduler_observer_v3 {
    friend class observer_proxy;
    friend class observer_list;
    friend class interface6::task_scheduler_observer;

    //! Pointer to the proxy holding this observer.
    /** Observers are proxied by the scheduler to maintain persistent lists of them. **/
    observer_proxy* my_proxy;

    //! Counter preventing the observer from being destroyed while in use by the scheduler.
    /** Valid only when observation is on. **/
    atomic<intptr_t> my_busy_count;

public:
    //! Enable or disable observation
    /** For local observers the method can be used only when the current thread
        has the task scheduler initialized or is attached to an arena.

        Repeated calls with the same state are no-ops. **/
    void __TBB_EXPORTED_METHOD observe( bool state=true );

    //! Returns true if observation is enabled, false otherwise.
    bool is_observing() const {return my_proxy!=NULL;}

    //! Construct observer with observation disabled.
    task_scheduler_observer_v3() : my_proxy(NULL) { my_busy_count.store<relaxed>(0); }

    //! Entry notification
    /** Invoked from inside observe(true) call and whenever a worker enters the arena
        this observer is associated with. If a thread is already in the arena when
        the observer is activated, the entry notification is called before it
        executes the first stolen task.

        Obsolete semantics. For global observers it is called by a thread before
        the first steal since observation became enabled. **/
    virtual void on_scheduler_entry( bool /*is_worker*/ ) {}

    //! Exit notification
    /** Invoked from inside observe(false) call and whenever a worker leaves the
        arena this observer is associated with.

        Obsolete semantics. For global observers it is called by a thread before
        the first steal since observation became enabled. **/
    virtual void on_scheduler_exit( bool /*is_worker*/ ) {}

    //! Destructor automatically switches observation off if it is enabled.
    virtual ~task_scheduler_observer_v3() { if(my_proxy) observe(false);}
};

} // namespace internal

#if TBB_PREVIEW_LOCAL_OBSERVER
namespace interface6 {
class task_scheduler_observer : public internal::task_scheduler_observer_v3 {
    friend class internal::task_scheduler_observer_v3;
    friend class internal::observer_proxy;
    friend class internal::observer_list;

    /** Negative numbers with the largest absolute value to minimize probability
        of coincidence in case of a bug in busy count usage. **/
    // TODO: take more high bits for version number
    static const intptr_t v6_trait = (intptr_t)((~(uintptr_t)0 >> 1) + 1);

    //! contains task_arena pointer or tag indicating local or global semantics of the observer
    intptr_t my_context_tag;
    enum { global_tag = 0, implicit_tag = 1 };

public:
    //! Construct local or global observer in inactive state (observation disabled).
    /** For a local observer entry/exit notifications are invoked whenever a worker
        thread joins/leaves the arena of the observer's owner thread. If a thread is
        already in the arena when the observer is activated, the entry notification is
        called before it executes the first stolen task. **/
    /** TODO: Obsolete.
        Global observer semantics is obsolete as it violates master thread isolation
        guarantees and is not composable. Thus the current default behavior of the
        constructor is obsolete too and will be changed in one of the future versions
        of the library. **/
    task_scheduler_observer( bool local = false ) {
        my_busy_count.store<relaxed>(v6_trait);
        my_context_tag = local? implicit_tag : global_tag;
    }

#if __TBB_TASK_ARENA
    //! Construct local observer for a given arena in inactive state (observation disabled).
    /** entry/exit notifications are invoked whenever a thread joins/leaves arena.
        If a thread is already in the arena when the observer is activated, the entry notification
        is called before it executes the first stolen task. **/
    task_scheduler_observer( task_arena & a) {
        my_busy_count.store<relaxed>(v6_trait);
        my_context_tag = (intptr_t)&a;
    }
#endif //__TBB_TASK_ARENA

    //! The callback can be invoked in a worker thread before it leaves an arena.
    /** If it returns false, the thread remains in the arena. Will not be called for masters
        or if the worker leaves arena due to rebalancing or priority changes, etc.
        NOTE: The preview library must be linked for this method to take effect **/
    virtual bool on_scheduler_leaving() { return true; }

    //! Destructor additionally protects concurrent on_scheduler_leaving notification
    // It is recommended to disable observation before destructor of a derived class starts,
    // otherwise it can lead to concurrent notification callback on partly destroyed object
    virtual ~task_scheduler_observer() { if(my_proxy) observe(false); }
};

} //namespace interface6
using interface6::task_scheduler_observer;
#else /*TBB_PREVIEW_LOCAL_OBSERVER*/
typedef tbb::internal::task_scheduler_observer_v3 task_scheduler_observer;
#endif /*TBB_PREVIEW_LOCAL_OBSERVER*/

} // namespace tbb

#endif /* __TBB_SCHEDULER_OBSERVER */

#endif /* __TBB_task_scheduler_observer_H */


text:
package yo

import (
	"net/http"
	"net/url"
)

// YoAll sends a Yo to all of your subscribers. The API token is issued by Yo
// for a specific account and is required.
func (c *Client) YoAll(apiToken string) (*http.Response, error) {
	u := "yoall/"
	body := url.Values{"api_token": {apiToken}}
	req, err := c.NewRequestForm(u, body)
	if err != nil {
		return nil, err
	}

	resp, err := c.Do(req, nil)
	if err != nil {
		return nil, err
	}

	return resp, nil
}


text:
class Noncopyable
{
protected:
    Noncopyable() = default;
    ~Noncopyable() = default;

private:
    Noncopyable(const Noncopyable&) = delete;
    Noncopyable& operator=(const Noncopyable&) = delete;
};

#endif


text:
//////////////////////////////////////////////////////////
// QCADesigner                                          //
// Copyright 2002 Konrad Walus                          //
// All Rights Reserved                                  //
// Author: Konrad Walus                                 //
// Email: qcadesigner@gmail.com                         //
// WEB: http://qcadesigner.ca/                          //
//////////////////////////////////////////////////////////
//******************************************************//
//*********** PLEASE DO NOT REFORMAT THIS CODE *********//
//******************************************************//
// If your editor wraps long lines disable it or don't  //
// save the core files that way. Any independent files  //
// you generate format as you wish.                     //
//////////////////////////////////////////////////////////
// Please use complete names in variables and fucntions //
// This will reduce ramp up time for new people trying  //
// to contribute to the project.                        //
//////////////////////////////////////////////////////////
// This file was contributed by Gabriel Schulhof        //
// (schulhof@atips.ca).                                 //
//////////////////////////////////////////////////////////
// Contents:                                            //
//                                                      //
// Header for a set of function responsible for         //
// creating QCADUndoEntry objects and hooking up the    //
// appropriate callbacks. It is essentially a set of    //
// convenience functions for the Undo/Redo system.      //
//                                                      //
//////////////////////////////////////////////////////////

#ifndef _SELECTION_UNDO_H_
#define _SELECTION_UNDO_H_

#ifdef UNDO_REDO

#include <gdk/gdk.h>
#include "design.h"
#include "selection_renderer.h"
#include "exp_array.h"

void push_undo_selection_move      (DESIGN *design, SELECTION_RENDERER *sr, GdkWindow *dst, double dxOffset, double dyOffset) ;
void push_undo_selection_transform (DESIGN *design, SELECTION_RENDERER *sr, GdkWindow *dst, double mtxFore[2][2], double mtxBack[2][2]) ;
void push_undo_selection_altered   (DESIGN *design, SELECTION_RENDERER *sr, GdkWindow *dst, EXP_ARRAY *objs, gboolean bAdded) ;
void push_undo_selection_existence (DESIGN *design, SELECTION_RENDERER *sr, GdkWindow *dst, EXP_ARRAY *objs, gboolean bCreated) ;
void push_undo_selection_clock     (DESIGN *design, SELECTION_RENDERER *sr, GdkWindow *dst, EXP_ARRAY *objs, int clock_new, gboolean bRelative) ;
void push_undo_selection_state     (DESIGN *design, SELECTION_RENDERER *sr, GdkWindow *dst, EXP_ARRAY *objs, char *state, GValue *value) ;
void track_undo_object_update      (DESIGN *design, SELECTION_RENDERER *sr, GdkWindow *dst, QCADUndoEntry *entry) ;

#endif /* def UNDO_REDO */
#endif /* _SELECTION_UNDO_H_ */


text:
namespace Microsoft.Azure.CognitiveServices.Language.SpellCheck.Models
{
    using System.Linq;

    public partial class Answer : Response
    {
        /// <summary>
        /// Initializes a new instance of the Answer class.
        /// </summary>
        public Answer()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Answer class.
        /// </summary>
        /// <param name="id">A String identifier.</param>
        public Answer(string id = default(string))
            : base(id)
        {
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

    }
}


text:
module Ahoy
  module Helper
    def amp_event(name, properties = {})
      url = Ahoy::Engine.routes.url_helpers.events_url(
        url_options.slice(:host, :port, :protocol).merge(
          name: name,
          properties: properties,
          screen_width: "SCREEN_WIDTH",
          screen_height: "SCREEN_HEIGHT",
          platform: "Web",
          landing_page: "AMPDOC_URL",
          referrer: "DOCUMENT_REFERRER",
          random: "RANDOM"
        )
      )
      url = "#{url}&visit_token=${clientId(ahoy_visit)}&visitor_token=${clientId(ahoy_visitor)}"

      content_tag "amp-analytics" do
        content_tag "script", type: "application/json" do
          json_escape({
            requests: {
              pageview: url
            },
            triggers: {
              trackPageview: {
                on: "visible",
                request: "pageview"
              }
            },
            transport: {
              beacon: true,
              xhrpost: true,
              image: false
            }
          }.to_json).html_safe
        end
      end
    end
  end
end


text:
#pragma once

#include <notifyCategoryProxy.h>

NotifyCategoryDecl(rppanda_interval, EXPORT_CLASS, EXPORT_TEMPL);


text:
__An open source Ruby on Rails content management system for Rails 3.__

More information at [http://refinerycms.com](http://refinerycms.com)

[![Build Status](https://secure.travis-ci.org/refinery/refinerycms.png)](http://travis-ci.org/refinery/refinerycms)

## Requirements

* [Bundler](http://gembundler.com)
* [ImageMagick](http://www.imagemagick.org/script/install-source.php)
  * Mac OS X users should use [homebrew's](https://github.com/mxcl/homebrew/wiki/installation) `brew install imagemagick` or the [magick-installer](https://github.com/maddox/magick-installer).

## How to

* __[Install Refinery CMS](http://refinerycms.com/download)__
* [Install Refinery CMS on Heroku](http://refinerycms.com/guides/heroku)
* [Contribute to Refinery CMS](http://refinerycms.com/guides/contributing-to-refinery)

## Getting Started

If you're new to Refinery, start with this guide:

* __[Getting Started](http://refinerycms.com/guides/getting-started)__

## What's it good at?

__Refinery is great for sites where the client needs to be able to update their website themselves__ without being bombarded with anything too complicated.

Unlike other content managers, Refinery is truly __aimed at the end user__ making it easy for them to pick up and make changes themselves.

### For developers

* Easily customise the look to suit the business.
* __Extend with custom extensions__ to do anything Refinery doesn't do out of the box.
* Sticks to __"the Rails way"__ as much as possible; we don't force you to learn new templating languages.
* Uses [jQuery](http://jquery.com/) for fast and concise Javascript.

![Refinery Dashboard](http://refinerycms.com/system/images/0000/0576/dashboard.png)

Wanna see Refinery for yourself? [Try the demo](http://demo.refinerycms.com/refinery)

## Help and Documentation

* [Getting Started](http://refinerycms.com/guides/getting-started)
* [Guides](http://refinerycms.com/guides)
* [Google Group Discussion](http://group.refinerycms.org)
* [IRC Channel](http://refinerycms.com/guides/how-to-get-help#irc-channel)
* [GitHub repository](https://github.com/refinery/refinerycms)
* [Developer/API documentation](http://api.refinerycms.org)
* [Twitter Account](http://twitter.com/refinerycms)

## Features

### Pages

* Easily edit and manage pages with a [WYSIWYG visual editor](http://www.wymeditor.org/).
* Manage your site's structure.

### Images & Files

* Easily upload and insert images.
* Upload and link to resources such as PDF documents.
* Uses the popular [Dragonfly](https://github.com/markevans/dragonfly).
* Supports storage on Amazon S3.

### Dashboard

* Get an overview of what has been updated recently and see recent inquiries.

### Authentication & Users

* Manage who can access Refinery.
* Control which extensions each user has access to.
* Uses the popular [Devise](https://github.com/plataformatec/devise).

### Custom Extensions

Extend Refinery easily by running the Refinery extension generator.
For help run the command without any options:

    rails generate refinery:engine

### Popular Extensions

* [Blog](https://github.com/refinery/refinerycms-blog) - A simple blogging extension that supports posts, categories and comments with optional moderation support.
* [Portfolio](https://github.com/refinery/refinerycms-portfolio) - manage groups of images like an image gallery.
* [News](https://github.com/refinery/refinerycms-news) - post and manage news items.
* [Inquiries](https://github.com/refinery/refinerycms-inquiries) - simple contact form that notifies you and customer when an inquiry is made.

[Full extension list here](http://refinerycms.com/engines)

### Example Site Showcase

[List here (add your link when you're done)](https://github.com/refinery/refinerycms/wiki/Example-Site-Showcase)

## License

Refinery is released under the MIT license. See the [license.md file](license.md#readme) for details.

### Credits

Many of the icons used in Refinery CMS are from the wonderful [Silk library by Mark James](http://www.famfamfam.com/lab/icons/silk/).


text:
import { DebugElement } from '@angular/core';

/** Button events to pass to `DebugElement.triggerEventHandler` for RouterLink event handler */
export const ButtonClickEvents = {
   left:  { button: 0 },
   right: { button: 2 }
};

/** Simulate element click. Defaults to mouse left-button click event. */
export function click(el: DebugElement | HTMLElement, eventObj: any = ButtonClickEvents.left): void {
  if (el instanceof HTMLElement) {
    el.click();
  } else {
    el.triggerEventHandler('click', eventObj);
  }
}


text:
package org.jmock.test.unit.internal;

import org.hamcrest.Matcher;
import org.jmock.internal.ReturnDefaultValueAction;
import org.junit.Test;

import javax.xml.ws.handler.LogicalMessageContext;
import java.beans.beancontext.BeanContext;
import java.beans.beancontext.BeanContextServices;
import java.util.*;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.jmock.test.unit.internal.ReturnDefaultValueActionTests.invocationReturning;

/**
 * @author Steve Freeman 2013 http://www.jmock.org
 *         https://github.com/jmock-developers/jmock-library/issues/9
 */
public class ReturnDefaultCollectionTests {
    public static final Matcher<Object> IS_PROXY_CLASS = hasProperty("canonicalName", containsString("Proxy"));
    private final ReturnDefaultValueAction action = new ReturnDefaultValueAction();

    @SuppressWarnings("unchecked")
    @Test public void
    returnsANewInstanceForEachCall() throws Throwable {
        final ArrayList<Object> firstInstance = returnedArrayList();
        firstInstance.add(new Object());

        assertThat(returnedArrayList(), is(empty()));
    }

    @Test public void
    returnsNewInstanceOfIterableClasses() throws Throwable {
        returnsInstanceForType(ArrayList.class, ArrayList.class);
        returnsInstanceForType(PriorityQueue.class, PriorityQueue.class);
    }

    @Test public void
    returnsNewInstanceOfMapClasses() throws Throwable {
        returnsInstanceForType(HashMap.class, HashMap.class);
        returnsInstanceForType(Properties.class, Properties.class);
    }

    @Test public void
    returnsNewInstanceConformingToCollectionInterface() throws Throwable {
        returnsInstanceForType(List.class, LinkedList.class);
        returnsInstanceForType(Set.class, TreeSet.class);
        returnsInstanceForType(NavigableSet.class, TreeSet.class);
        returnsInstanceForType(SortedSet.class, TreeSet.class);
        returnsInstanceForType(Queue.class, LinkedList.class);
        returnsInstanceForType(Deque.class, LinkedList.class);
    }

    // https://github.com/jmock-developers/jmock-library/issues/46
    @Test public void
    imposterisesBeanContextTypesToAvoidMissingTypesInAndroid() throws Throwable {
        assertThat(action.invoke(invocationReturning(BeanContext.class)).getClass(), IS_PROXY_CLASS);
        assertThat(action.invoke(invocationReturning(BeanContextServices.class)).getClass(), IS_PROXY_CLASS);
    }

    @Test public void
    returnsNewInstanceConformingToMapType() throws Throwable {
        returnsInstanceForType(Map.class, TreeMap.class);
        returnsInstanceForType(SortedMap.class, TreeMap.class);
        returnsInstanceForType(NavigableMap.class, TreeMap.class);
    }

    @Test public void
    imposterisesUnsupportedMapTypes() throws Throwable {
        assertThat(action.invoke(invocationReturning(LogicalMessageContext.class)).getClass(), IS_PROXY_CLASS);
    }

    private void returnsInstanceForType(Class<?> declaredType, Class<?> expectedType) throws Throwable {
        assertThat(
                action.invoke(invocationReturning(declaredType)),
                instanceOf(expectedType));
    }

    @SuppressWarnings("unchecked")
    private ArrayList<Object> returnedArrayList() throws Throwable {
        return (ArrayList<Object>) action.invoke(invocationReturning(ArrayList.class));
    }

}


text:
APA102 LED Strip library using JSUPM_APA102 module

This library is not released yet.


text:
/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */

/*** Copyright (c), The Regents of the University of California            ***
 *** For more information please refer to files in the COPYRIGHT directory ***/
/* dataObjCreate.h
 */

#ifndef DATA_OBJ_CREATE_HPP
#define DATA_OBJ_CREATE_HPP

/* This is a high level type API call */

#include "rods.hpp"
#include "rcMisc.hpp"
#include "procApiRequest.hpp"
#include "apiNumber.hpp"
#include "initServer.hpp"
#include "dataObjInpOut.hpp"
#include "fileCreate.hpp"

#if defined(RODS_SERVER)
#define RS_DATA_OBJ_CREATE rsDataObjCreate
/* prototype for the server handler */
int
rsDataObjCreate( rsComm_t *rsComm, dataObjInp_t *dataObjInp );
int
_rsDataObjCreate( rsComm_t *rsComm, dataObjInp_t *dataObjInp );
int
specCollSubCreate( rsComm_t *rsComm, dataObjInp_t *dataObjInp );
int
_rsDataObjCreateWithRescInfo( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
                              rescInfo_t *rescInfo, char *rescGroupName );
int
dataObjCreateAndReg( rsComm_t *rsComm, int l1descInx );
int
dataCreate( rsComm_t *rsComm, int l1descInx );
int
l3Create( rsComm_t *rsComm, int l1descInx );
int
l3CreateByObjInfo( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
                   dataObjInfo_t *dataObjInfo );
int
getRescGrpForCreate( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
                     rescGrpInfo_t **myRescGrpInfo );
#else
#define RS_DATA_OBJ_CREATE NULL
#endif

/* prototype for the client call */
/* rcDataObjCreate - Create a iRODS data object.
 * Input -
 *   rcComm_t *conn - The client connection handle.
 *   dataObjInp_t *dataObjInp - generic dataObj input. Relevant items are:
 *      objPath - the path of the data object.
 *      rescName - the input resource (optional)
 *      dataType - the data type of the object (optional).
 *      filePath - the physical file path (optional).
 *      numThreads - number of threads to use. NO_THREADING = no threading.
 *      createMode - the file mode (optional)
 *      openFlag - O_WRONLY, O_RDONLY , etc
 *      condInput - condition input (optional).
 *          DATA_TYPE_KW - "value" = the data type of the object
 *          FORCE_FLAG_KW - overwrite an existing data object
 *          REG_CHKSUM_KW - compute the checksum value
 *          VERIFY_CHKSUM_KW - compute and verify the checksum on the data.
 *          FILE_PATH_KW - "value" = the physical path of the
 *              destination file.
 *          REPL_NUM_KW  - "value" = The replica number of the copy to
 *              overwrite.
 *          DEST_RESC_NAME_KW - "value" = The destination Resource.
 *
 * OutPut -
 *   int l1descInx - an integer descriptor.
 */

extern "C" {

    int
    rcDataObjCreate( rcComm_t *conn, dataObjInp_t *dataObjInp );

}

#endif  /* DATA_OBJ_CREATE_H */


text:
package main

import (
	_ "github.com/icattlecoder/godaemon"
	"log"
	"net/http"
)

func main() {

	mux := http.NewServeMux()
	mux.HandleFunc("/index", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte("hello, golang!\n"))
	})
	log.Fatalln(http.ListenAndServe(":7070", mux))
}


text:
package com.indoqa.boot.actuate.resources;

import static java.lang.Boolean.FALSE;

import javax.inject.Inject;

import com.indoqa.boot.json.resources.AbstractJsonResourcesBase;
import com.indoqa.boot.spark.SparkAdminService;
import org.springframework.core.env.Environment;

import spark.Route;
import spark.Service;
import spark.Spark;

public abstract class AbstractAdminResources extends AbstractJsonResourcesBase {

    protected static final String CONTENT_TYPE_HTML = "text/html; charset=utf-8";
    private static final String PROPERTY_ADMIN_ENABLED_VIA_DEFAULT_SERVICE = "admin.enabled-via-default-service";
    private static final String ADMIN_BASE_PATH = "/admin";

    @Inject
    private SparkAdminService sparkAdminService;

    @Inject
    private Environment environment;

    protected static String resolveAdminPath(String path) {
        return new StringBuilder(ADMIN_BASE_PATH).append(path).toString();
    }

    protected void getActuator(String path, Route route) {
        if (this.isAdminServiceAvailable()) {
            this.sparkAdminService.instance().get(path, CONTENT_TYPE_JSON, route, this.getTransformer());
        }

        else if (this.isEnabledViaDefaultService()) {
            this.get(resolveAdminPath(path), route);
        }
    }

    protected void headActuator(String path, Route route) {
        if (this.isAdminServiceAvailable()) {
            this.sparkAdminService.instance().head(path, route);
        }

        else if (this.isEnabledViaDefaultService()) {
            this.head(resolveAdminPath(path), route);
        }
    }

    protected void putActuator(String path, Route route) {
        if (this.isAdminServiceAvailable()) {
            this.sparkAdminService.instance().put(path, CONTENT_TYPE_JSON, route, this.getTransformer());
        }

        else if (this.isEnabledViaDefaultService()) {
            this.put(resolveAdminPath(path), route);
        }
    }

    protected void getActuatorHtml(String path, Route route) {
        if (this.isAdminServiceAvailable()) {
            this.getSparkAdminService().get(path, CONTENT_TYPE_HTML, route);
        }

        else if (this.isEnabledViaDefaultService()) {
            Spark.get(resolveAdminPath(path), CONTENT_TYPE_HTML, route);
        }
    }

    protected void putActuatorHtml(String path, Route route) {
        if (this.isAdminServiceAvailable()) {
            this.sparkAdminService.instance().put(path, CONTENT_TYPE_HTML, route, this.getTransformer());
        }

        else if (this.isEnabledViaDefaultService()) {
            Spark.put(resolveAdminPath(path), CONTENT_TYPE_HTML, route);
        }
    }

    protected Service getSparkAdminService() {
        return this.sparkAdminService.instance();
    }

    protected boolean isAdminServiceAvailable() {
        return this.sparkAdminService.isAvailable();
    }

    protected Boolean isEnabledViaDefaultService() {
        return this.environment.getProperty(PROPERTY_ADMIN_ENABLED_VIA_DEFAULT_SERVICE, Boolean.class, FALSE);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:id="@+id/calibrate" android:titleCondensed="Calib"
		android:title="Calibrate"></item>
	<item android:id="@+id/patternsize" android:titleCondensed="Size"
		android:title="@string/patternsize" android:icon="@drawable/patternicon"></item>

<item android:id="@+id/settings" android:title="Settings" android:icon="@android:drawable/ic_menu_preferences"></item>
<item android:id="@+id/help" android:title="Help" android:icon="@android:drawable/ic_menu_help"></item>
</menu>


text:
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Runtime configuration or what are the strings I can pull?</title>
<link rel="stylesheet" href="../../../style/style.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.74.0">
<link rel="home" href="../../index.html" title="Boost Test Library">
<link rel="up" href="../user-guide.html" title="Unit Test Framework: User's guide">
<link rel="prev" href="test-output/test-progress.html" title="Test progress display">
<link rel="next" href="runtime-config/run-by-name.html" title="Running specific test units selected by their name">

 > The Unit Test Framework > User's guide
      >
      Runtime configuration

Runtime configuration  or what are the strings I can pull?

  The <acronym class="acronym">UTF</acronym> supports multiple parameters that affect test module execution. To set the parameter's value you can
  either use a runtime configuration subsystem interface from within the test module initialization function or you can
  specify the value at runtime during test module invocation.

  The <acronym class="acronym">UTF</acronym> provides two ways to set a parameter at runtime: by specifying a command line argument and by setting an
  environment variable. The command line argument always overrides the corresponding environment variable.

  During test module initialization the <acronym class="acronym">UTF</acronym> parses the command line and excludes all parameters that belong to it and
  their values from the argument list. The rest of command line is forwarded to the test module initialization function
  supplied by you. The command line argument format expected by the <acronym class="acronym">UTF</acronym> is:

  --<command line argument name>=<argument_value>.

  The command line argument name is case sensitive. It is required to match exactly the name in parameter specification.
  There should not be any spaces between '=' and either command line argument name or argument value.

  The corresponding environment variable name is also case sensitive and is required to exactly match the name in the
  parameter specification.

  All information about supported parameters is summarized below in the reference section.

Copyright © 2001-2007 Gennadiy Rozental


text:
export { NgbModal, NgbModalOptions } from './modal';
export { NgbModalRef } from './modal-ref';
export { ModalDismissReasons } from './modal-dismiss-reasons';
export declare class NgbModalModule {
}


text:
package com.helger.commons.csv;

/**
 Copyright 2005 Bytecode Pty Ltd.

 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.
 */

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.junit.Before;
import org.junit.Test;

import com.helger.commons.collection.impl.ICommonsList;

public final class IntegrationFuncTest
{
  private File m_aTempFile;

  @Before
  public void setUp () throws IOException
  {
    m_aTempFile = File.createTempFile ("csvWriterTest", ".csv");
    m_aTempFile.deleteOnExit ();
  }

  /**
   * Test the full cycle of write-read
   *
   * @throws IOException
   *         never
   */
  @Test
  public void testWriteRead () throws IOException
  {
    final String [] [] data = new String [] [] { { "hello, a test", "one nested \" test" }, { "\"\"", "test", null, "8" } };
    final Charset aCharset = StandardCharsets.UTF_8;

    try (final CSVWriter writer = new CSVWriter (new OutputStreamWriter (new FileOutputStream (m_aTempFile), aCharset)))
    {
      for (final String [] aData : data)
        writer.writeNext (aData);
    }

    try (final CSVReader reader = new CSVReader (new InputStreamReader (new FileInputStream (m_aTempFile), aCharset)))
    {
      int row = 0;
      while (true)
      {
        final ICommonsList <String> line = reader.readNext ();
        if (line == null)
          break;

        assertEquals (line.size (), data[row].length);

        for (int col = 0; col < line.size (); col++)
        {
          if (data[row][col] == null)
            assertEquals ("", line.get (col));
          else
            assertEquals (data[row][col], line.get (col));
        }
        row++;
      }
    }
  }
}


text:
#define DEBUG //make sure the Contract calls actually do something

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.Contracts;

public static class MonitorIsHeldTest
{
    static int s_result = 100;

    static int Main()
    {
        try
        {
            RunNullTest();
            RunTest(new object(), "object without SyncBlk");
            RunTest(CreateObjectWithSyncBlk(), "object with SyncBlk");

            Console.WriteLine(s_result == 100 ? "Success!" : "FAILED!");
            return s_result;
        }
        catch (Exception e)
        {
            Console.WriteLine("Unhandled exception!");
            Console.WriteLine(e);
            return 999;
        }
    }

    static object CreateObjectWithSyncBlk()
    {
        // force an object to have a SyncBlk, to exercise the IsEntered code that
        // deals with these
        object o = new object();
        o.GetHashCode();
        return o;
    }

    static void RunNullTest()
    {
        try
        {
            Monitor.IsEntered(null);
        }
        catch (ArgumentNullException)
        {
            // expected
            return;
        }

        // no exception
        Console.WriteLine("Monitor.IsEntered(null) did not throw ArgumentNullException");
        s_result = 101;
    }

    static void RunTest(object obj, string caseName)
    {
        // lock not held by anyone
        if (Monitor.IsEntered(obj))
        {
            Console.WriteLine("{0}: lock should be initially unheld, but IsEntered == true", caseName);
            s_result = 102;
        }

        // lock held by this thread
        lock (obj)
        {
            if (!Monitor.IsEntered(obj))
            {
                Console.WriteLine("{0}: lock should be held by this thread, but IsEntered == false", caseName);
                s_result = 103;
            }

            // do it the way the user would
            Contract.Assert(Monitor.IsEntered(obj));
        }

        // now it's released
        if (Monitor.IsEntered(obj))
        {
            Console.WriteLine("{0}: lock should have been released, but IsEntered == true", caseName);
            s_result = 104;
        }

        // do it the way the user would
        Contract.Assert(!Monitor.IsEntered(obj));

        // Make another thread hold the lock
        ManualResetEventSlim lockHeldEvent = new ManualResetEventSlim();
        ManualResetEventSlim releaseLockEvent = new ManualResetEventSlim();

        Task otherThread = Task.Factory.StartNew(() =>
            {
                lock (obj)
                {
                    Contract.Assert(Monitor.IsEntered(obj));
                    lockHeldEvent.Set();
                    releaseLockEvent.Wait();
                }
            });

        lockHeldEvent.Wait();

        // lock is held by other thread, so we should get "false"
        if (Monitor.IsEntered(obj))
        {
            Console.WriteLine("{0}: lock should be held by other thread, but IsEntered == true", caseName);
            s_result = 105;
        }

        releaseLockEvent.Set();
        otherThread.Wait();

        // lock is held by neither thread, so we should still get "false"
        if (Monitor.IsEntered(obj))
        {
            Console.WriteLine("{0}: lock should not be held by any thread, but IsEntered == true", caseName);
            s_result = 106;
        }

    }
}


text:
module Graphics.Rendering.OpenGL.Raw.NV.TessellationProgram5 (
  -- * Enums
  gl_MAX_PROGRAM_PATCH_ATTRIBS_NV,
  gl_TESS_CONTROL_PROGRAM_NV,
  gl_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV,
  gl_TESS_EVALUATION_PROGRAM_NV,
  gl_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV
) where

import Graphics.Rendering.OpenGL.Raw.Tokens


text: sap.ui.define(['jquery.sap.global','sap/ui/core/Renderer','sap/ui/layout/form/ResponsiveLayoutRenderer'],function(q,R,a){"use strict";var b=R.extend(a);return b;},true);


text:
<?php

require __dir__ . '/lib/bootstrap.php';

$loader = new LoadManager($_db, MOD_DIR);
$loader->load();


text:
// BZip2Encoder.cpp

#include "StdAfx.h"

#include "../../../C/Alloc.h"
#include "../../../C/BwtSort.h"
#include "../../../C/HuffEnc.h"

#include "BZip2Crc.h"
#include "BZip2Encoder.h"
#include "Mtf8.h"

namespace NCompress {
namespace NBZip2 {

const unsigned kMaxHuffmanLenForEncoding = 16; // it must be < kMaxHuffmanLen = 20

static const UInt32 kBufferSize = (1 << 17);
static const unsigned kNumHuffPasses = 4;

bool CThreadInfo::Alloc()
{
  if (m_BlockSorterIndex == 0)
  {
    m_BlockSorterIndex = (UInt32 *)::BigAlloc(BLOCK_SORT_BUF_SIZE(kBlockSizeMax) * sizeof(UInt32));
    if (m_BlockSorterIndex == 0)
      return false;
  }

  if (m_Block == 0)
  {
    m_Block = (Byte *)::MidAlloc(kBlockSizeMax * 5 + kBlockSizeMax / 10 + (20 << 10));
    if (m_Block == 0)
      return false;
    m_MtfArray = m_Block + kBlockSizeMax;
    m_TempArray = m_MtfArray + kBlockSizeMax * 2 + 2;
  }
  return true;
}

void CThreadInfo::Free()
{
  ::BigFree(m_BlockSorterIndex);
  m_BlockSorterIndex = 0;
  ::MidFree(m_Block);
  m_Block = 0;
}

#ifndef _7ZIP_ST

static THREAD_FUNC_DECL MFThread(void *threadCoderInfo)
{
  return ((CThreadInfo *)threadCoderInfo)->ThreadFunc();
}

#define RINOK_THREAD(x) { WRes __result_ = (x); if (__result_ != 0) return __result_; }

HRESULT CThreadInfo::Create()
{
  RINOK_THREAD(StreamWasFinishedEvent.Create());
  RINOK_THREAD(WaitingWasStartedEvent.Create());
  RINOK_THREAD(CanWriteEvent.Create());
  RINOK_THREAD(Thread.Create(MFThread, this));
  return S_OK;
}

void CThreadInfo::FinishStream(bool needLeave)
{
  Encoder->StreamWasFinished = true;
  StreamWasFinishedEvent.Set();
  if (needLeave)
    Encoder->CS.Leave();
  Encoder->CanStartWaitingEvent.Lock();
  WaitingWasStartedEvent.Set();
}

DWORD CThreadInfo::ThreadFunc()
{
  for (;;)
  {
    Encoder->CanProcessEvent.Lock();
    Encoder->CS.Enter();
    if (Encoder->CloseThreads)
    {
      Encoder->CS.Leave();
      return 0;
    }
    if (Encoder->StreamWasFinished)
    {
      FinishStream(true);
      continue;
    }
    HRESULT res = S_OK;
    bool needLeave = true;
    try
    {
      UInt32 blockSize = Encoder->ReadRleBlock(m_Block);
      m_PackSize = Encoder->m_InStream.GetProcessedSize();
      m_BlockIndex = Encoder->NextBlockIndex;
      if (++Encoder->NextBlockIndex == Encoder->NumThreads)
        Encoder->NextBlockIndex = 0;
      if (blockSize == 0)
      {
        FinishStream(true);
        continue;
      }
      Encoder->CS.Leave();
      needLeave = false;
      res = EncodeBlock3(blockSize);
    }
    catch(const CInBufferException &e)  { res = e.ErrorCode; }
    catch(const COutBufferException &e) { res = e.ErrorCode; }
    catch(...) { res = E_FAIL; }
    if (res != S_OK)
    {
      Encoder->Result = res;
      FinishStream(needLeave);
      continue;
    }
  }
}

#endif

void CEncProps::Normalize(int level)
{
  if (level < 0) level = 5;
  if (level > 9) level = 9;

  if (NumPasses == (UInt32)(Int32)-1)
    NumPasses = (level >= 9 ? 7 : (level >= 7 ? 2 : 1));
  if (NumPasses < 1) NumPasses = 1;
  if (NumPasses > kNumPassesMax) NumPasses = kNumPassesMax;

  if (BlockSizeMult == (UInt32)(Int32)-1)
    BlockSizeMult = (level >= 5 ? 9 : (level >= 1 ? level * 2 - 1: 1));
  if (BlockSizeMult < kBlockSizeMultMin) BlockSizeMult = kBlockSizeMultMin;
  if (BlockSizeMult > kBlockSizeMultMax) BlockSizeMult = kBlockSizeMultMax;
}

CEncoder::CEncoder()
{
  _props.Normalize(-1);

  #ifndef _7ZIP_ST
  ThreadsInfo = 0;
  m_NumThreadsPrev = 0;
  NumThreads = 1;
  #endif
}

#ifndef _7ZIP_ST
CEncoder::~CEncoder()
{
  Free();
}

HRESULT CEncoder::Create()
{
  RINOK_THREAD(CanProcessEvent.CreateIfNotCreated());
  RINOK_THREAD(CanStartWaitingEvent.CreateIfNotCreated());
  if (ThreadsInfo != 0 && m_NumThreadsPrev == NumThreads)
    return S_OK;
  try
  {
    Free();
    MtMode = (NumThreads > 1);
    m_NumThreadsPrev = NumThreads;
    ThreadsInfo = new CThreadInfo[NumThreads];
    if (ThreadsInfo == 0)
      return E_OUTOFMEMORY;
  }
  catch(...) { return E_OUTOFMEMORY; }
  for (UInt32 t = 0; t < NumThreads; t++)
  {
    CThreadInfo &ti = ThreadsInfo[t];
    ti.Encoder = this;
    if (MtMode)
    {
      HRESULT res = ti.Create();
      if (res != S_OK)
      {
        NumThreads = t;
        Free();
        return res;
      }
    }
  }
  return S_OK;
}

void CEncoder::Free()
{
  if (!ThreadsInfo)
    return;
  CloseThreads = true;
  CanProcessEvent.Set();
  for (UInt32 t = 0; t < NumThreads; t++)
  {
    CThreadInfo &ti = ThreadsInfo[t];
    if (MtMode)
      ti.Thread.Wait();
    ti.Free();
  }
  delete []ThreadsInfo;
  ThreadsInfo = 0;
}
#endif

UInt32 CEncoder::ReadRleBlock(Byte *buffer)
{
  UInt32 i = 0;
  Byte prevByte;
  if (m_InStream.ReadByte(prevByte))
  {
    UInt32 blockSize = _props.BlockSizeMult * kBlockSizeStep - 1;
    unsigned numReps = 1;
    buffer[i++] = prevByte;
    while (i < blockSize) // "- 1" to support RLE
    {
      Byte b;
      if (!m_InStream.ReadByte(b))
        break;
      if (b != prevByte)
      {
        if (numReps >= kRleModeRepSize)
          buffer[i++] = (Byte)(numReps - kRleModeRepSize);
        buffer[i++] = b;
        numReps = 1;
        prevByte = b;
        continue;
      }
      numReps++;
      if (numReps <= kRleModeRepSize)
        buffer[i++] = b;
      else if (numReps == kRleModeRepSize + 255)
      {
        buffer[i++] = (Byte)(numReps - kRleModeRepSize);
        numReps = 0;
      }
    }
    // it's to support original BZip2 decoder
    if (numReps >= kRleModeRepSize)
      buffer[i++] = (Byte)(numReps - kRleModeRepSize);
  }
  return i;
}

void CThreadInfo::WriteBits2(UInt32 value, unsigned numBits) { m_OutStreamCurrent->WriteBits(value, numBits); }
void CThreadInfo::WriteByte2(Byte b) { WriteBits2(b, 8); }
void CThreadInfo::WriteBit2(Byte v) { WriteBits2(v, 1); }
void CThreadInfo::WriteCrc2(UInt32 v)
{
  for (unsigned i = 0; i < 4; i++)
    WriteByte2(((Byte)(v >> (24 - i * 8))));
}

void CEncoder::WriteBits(UInt32 value, unsigned numBits) { m_OutStream.WriteBits(value, numBits); }
void CEncoder::WriteByte(Byte b) { WriteBits(b, 8); }
// void CEncoder::WriteBit(Byte v) { WriteBits(v, 1); }
void CEncoder::WriteCrc(UInt32 v)
{
  for (unsigned i = 0; i < 4; i++)
    WriteByte(((Byte)(v >> (24 - i * 8))));
}

// blockSize > 0
void CThreadInfo::EncodeBlock(const Byte *block, UInt32 blockSize)
{
  WriteBit2(0); // Randomised = false

  {
    UInt32 origPtr = BlockSort(m_BlockSorterIndex, block, blockSize);
    // if (m_BlockSorterIndex[origPtr] != 0) throw 1;
    m_BlockSorterIndex[origPtr] = blockSize;
    WriteBits2(origPtr, kNumOrigBits);
  }

  CMtf8Encoder mtf;
  unsigned numInUse = 0;
  {
    Byte inUse[256];
    Byte inUse16[16];
    UInt32 i;
    for (i = 0; i < 256; i++)
      inUse[i] = 0;
    for (i = 0; i < 16; i++)
      inUse16[i] = 0;
    for (i = 0; i < blockSize; i++)
      inUse[block[i]] = 1;
    for (i = 0; i < 256; i++)
      if (inUse[i])
      {
        inUse16[i >> 4] = 1;
        mtf.Buf[numInUse++] = (Byte)i;
      }
    for (i = 0; i < 16; i++)
      WriteBit2(inUse16[i]);
    for (i = 0; i < 256; i++)
      if (inUse16[i >> 4])
        WriteBit2(inUse[i]);
  }
  unsigned alphaSize = numInUse + 2;

  Byte *mtfs = m_MtfArray;
  UInt32 mtfArraySize = 0;
  UInt32 symbolCounts[kMaxAlphaSize];
  {
    for (unsigned i = 0; i < kMaxAlphaSize; i++)
      symbolCounts[i] = 0;
  }

  {
    UInt32 rleSize = 0;
    UInt32 i = 0;
    const UInt32 *bsIndex = m_BlockSorterIndex;
    block--;
    do
    {
      unsigned pos = mtf.FindAndMove(block[bsIndex[i]]);
      if (pos == 0)
        rleSize++;
      else
      {
        while (rleSize != 0)
        {
          rleSize--;
          mtfs[mtfArraySize++] = (Byte)(rleSize & 1);
          symbolCounts[rleSize & 1]++;
          rleSize >>= 1;
        }
        if (pos >= 0xFE)
        {
          mtfs[mtfArraySize++] = 0xFF;
          mtfs[mtfArraySize++] = (Byte)(pos - 0xFE);
        }
        else
          mtfs[mtfArraySize++] = (Byte)(pos + 1);
        symbolCounts[pos + 1]++;
      }
    }
    while (++i < blockSize);

    while (rleSize != 0)
    {
      rleSize--;
      mtfs[mtfArraySize++] = (Byte)(rleSize & 1);
      symbolCounts[rleSize & 1]++;
      rleSize >>= 1;
    }

    if (alphaSize < 256)
      mtfs[mtfArraySize++] = (Byte)(alphaSize - 1);
    else
    {
      mtfs[mtfArraySize++] = 0xFF;
      mtfs[mtfArraySize++] = (Byte)(alphaSize - 256);
    }
    symbolCounts[alphaSize - 1]++;
  }

  UInt32 numSymbols = 0;
  {
    for (unsigned i = 0; i < kMaxAlphaSize; i++)
      numSymbols += symbolCounts[i];
  }

  unsigned bestNumTables = kNumTablesMin;
  UInt32 bestPrice = 0xFFFFFFFF;
  UInt32 startPos = m_OutStreamCurrent->GetPos();
  Byte startCurByte = m_OutStreamCurrent->GetCurByte();
  for (unsigned nt = kNumTablesMin; nt <= kNumTablesMax + 1; nt++)
  {
    unsigned numTables;

    if (m_OptimizeNumTables)
    {
      m_OutStreamCurrent->SetPos(startPos);
      m_OutStreamCurrent->SetCurState((startPos & 7), startCurByte);
      if (nt <= kNumTablesMax)
        numTables = nt;
      else
        numTables = bestNumTables;
    }
    else
    {
      if (numSymbols < 200)  numTables = 2;
      else if (numSymbols < 600) numTables = 3;
      else if (numSymbols < 1200) numTables = 4;
      else if (numSymbols < 2400) numTables = 5;
      else numTables = 6;
    }

    WriteBits2(numTables, kNumTablesBits);

    UInt32 numSelectors = (numSymbols + kGroupSize - 1) / kGroupSize;
    WriteBits2(numSelectors, kNumSelectorsBits);

    {
      UInt32 remFreq = numSymbols;
      unsigned gs = 0;
      unsigned t = numTables;
      do
      {
        UInt32 tFreq = remFreq / t;
        unsigned ge = gs;
        UInt32 aFreq = 0;
        while (aFreq < tFreq) //  && ge < alphaSize)
          aFreq += symbolCounts[ge++];

        if (ge > gs + 1 && t != numTables && t != 1 && (((numTables - t) & 1) == 1))
          aFreq -= symbolCounts[--ge];

        Byte *lens = Lens[t - 1];
        unsigned i = 0;
        do
          lens[i] = (Byte)((i >= gs && i < ge) ? 0 : 1);
        while (++i < alphaSize);
        gs = ge;
        remFreq -= aFreq;
      }
      while (--t != 0);
    }

    for (unsigned pass = 0; pass < kNumHuffPasses; pass++)
    {
      {
        unsigned t = 0;
        do
          memset(Freqs[t], 0, sizeof(Freqs[t]));
        while (++t < numTables);
      }

      {
        UInt32 mtfPos = 0;
        UInt32 g = 0;
        do
        {
          UInt32 symbols[kGroupSize];
          unsigned i = 0;
          do
          {
            UInt32 symbol = mtfs[mtfPos++];
            if (symbol >= 0xFF)
              symbol += mtfs[mtfPos++];
            symbols[i] = symbol;
          }
          while (++i < kGroupSize && mtfPos < mtfArraySize);

          UInt32 bestPrice2 = 0xFFFFFFFF;
          unsigned t = 0;
          do
          {
            const Byte *lens = Lens[t];
            UInt32 price = 0;
            unsigned j = 0;
            do
              price += lens[symbols[j]];
            while (++j < i);
            if (price < bestPrice2)
            {
              m_Selectors[g] = (Byte)t;
              bestPrice2 = price;
            }
          }
          while (++t < numTables);
          UInt32 *freqs = Freqs[m_Selectors[g++]];
          unsigned j = 0;
          do
            freqs[symbols[j]]++;
          while (++j < i);
        }
        while (mtfPos < mtfArraySize);
      }

      unsigned t = 0;
      do
      {
        UInt32 *freqs = Freqs[t];
        unsigned i = 0;
        do
          if (freqs[i] == 0)
            freqs[i] = 1;
        while (++i < alphaSize);
        Huffman_Generate(freqs, Codes[t], Lens[t], kMaxAlphaSize, kMaxHuffmanLenForEncoding);
      }
      while (++t < numTables);
    }

    {
      Byte mtfSel[kNumTablesMax];
      {
        unsigned t = 0;
        do
          mtfSel[t] = (Byte)t;
        while (++t < numTables);
      }

      UInt32 i = 0;
      do
      {
        Byte sel = m_Selectors[i];
        unsigned pos;
        for (pos = 0; mtfSel[pos] != sel; pos++)
          WriteBit2(1);
        WriteBit2(0);
        for (; pos > 0; pos--)
          mtfSel[pos] = mtfSel[pos - 1];
        mtfSel[0] = sel;
      }
      while (++i < numSelectors);
    }

    {
      unsigned t = 0;
      do
      {
        const Byte *lens = Lens[t];
        UInt32 len = lens[0];
        WriteBits2(len, kNumLevelsBits);
        unsigned i = 0;
        do
        {
          UInt32 level = lens[i];
          while (len != level)
          {
            WriteBit2(1);
            if (len < level)
            {
              WriteBit2(0);
              len++;
            }
            else
            {
              WriteBit2(1);
              len--;
            }
          }
          WriteBit2(0);
        }
        while (++i < alphaSize);
      }
      while (++t < numTables);
    }

    {
      UInt32 groupSize = 0;
      UInt32 groupIndex = 0;
      const Byte *lens = 0;
      const UInt32 *codes = 0;
      UInt32 mtfPos = 0;
      do
      {
        UInt32 symbol = mtfs[mtfPos++];
        if (symbol >= 0xFF)
          symbol += mtfs[mtfPos++];
        if (groupSize == 0)
        {
          groupSize = kGroupSize;
          unsigned t = m_Selectors[groupIndex++];
          lens = Lens[t];
          codes = Codes[t];
        }
        groupSize--;
        m_OutStreamCurrent->WriteBits(codes[symbol], lens[symbol]);
      }
      while (mtfPos < mtfArraySize);
    }

    if (!m_OptimizeNumTables)
      break;
    UInt32 price = m_OutStreamCurrent->GetPos() - startPos;
    if (price <= bestPrice)
    {
      if (nt == kNumTablesMax)
        break;
      bestPrice = price;
      bestNumTables = nt;
    }
  }
}

// blockSize > 0
UInt32 CThreadInfo::EncodeBlockWithHeaders(const Byte *block, UInt32 blockSize)
{
  WriteByte2(kBlockSig0);
  WriteByte2(kBlockSig1);
  WriteByte2(kBlockSig2);
  WriteByte2(kBlockSig3);
  WriteByte2(kBlockSig4);
  WriteByte2(kBlockSig5);

  CBZip2Crc crc;
  unsigned numReps = 0;
  Byte prevByte = block[0];
  UInt32 i = 0;
  do
  {
    Byte b = block[i];
    if (numReps == kRleModeRepSize)
    {
      for (; b > 0; b--)
        crc.UpdateByte(prevByte);
      numReps = 0;
      continue;
    }
    if (prevByte == b)
      numReps++;
    else
    {
      numReps = 1;
      prevByte = b;
    }
    crc.UpdateByte(b);
  }
  while (++i < blockSize);
  UInt32 crcRes = crc.GetDigest();
  WriteCrc2(crcRes);
  EncodeBlock(block, blockSize);
  return crcRes;
}

void CThreadInfo::EncodeBlock2(const Byte *block, UInt32 blockSize, UInt32 numPasses)
{
  UInt32 numCrcs = m_NumCrcs;
  bool needCompare = false;

  UInt32 startBytePos = m_OutStreamCurrent->GetBytePos();
  UInt32 startPos = m_OutStreamCurrent->GetPos();
  Byte startCurByte = m_OutStreamCurrent->GetCurByte();
  Byte endCurByte = 0;
  UInt32 endPos = 0;
  if (numPasses > 1 && blockSize >= (1 << 10))
  {
    UInt32 blockSize0 = blockSize / 2;
    for (;(block[blockSize0] == block[blockSize0 - 1] ||
          block[blockSize0 - 1] == block[blockSize0 - 2]) &&
          blockSize0 < blockSize; blockSize0++);
    if (blockSize0 < blockSize)
    {
      EncodeBlock2(block, blockSize0, numPasses - 1);
      EncodeBlock2(block + blockSize0, blockSize - blockSize0, numPasses - 1);
      endPos = m_OutStreamCurrent->GetPos();
      endCurByte = m_OutStreamCurrent->GetCurByte();
      if ((endPos & 7) > 0)
        WriteBits2(0, 8 - (endPos & 7));
      m_OutStreamCurrent->SetCurState((startPos & 7), startCurByte);
      needCompare = true;
    }
  }

  UInt32 startBytePos2 = m_OutStreamCurrent->GetBytePos();
  UInt32 startPos2 = m_OutStreamCurrent->GetPos();
  UInt32 crcVal = EncodeBlockWithHeaders(block, blockSize);
  UInt32 endPos2 = m_OutStreamCurrent->GetPos();

  if (needCompare)
  {
    UInt32 size2 = endPos2 - startPos2;
    if (size2 < endPos - startPos)
    {
      UInt32 numBytes = m_OutStreamCurrent->GetBytePos() - startBytePos2;
      Byte *buffer = m_OutStreamCurrent->GetStream();
      for (UInt32 i = 0; i < numBytes; i++)
        buffer[startBytePos + i] = buffer[startBytePos2 + i];
      m_OutStreamCurrent->SetPos(startPos + endPos2 - startPos2);
      m_NumCrcs = numCrcs;
      m_CRCs[m_NumCrcs++] = crcVal;
    }
    else
    {
      m_OutStreamCurrent->SetPos(endPos);
      m_OutStreamCurrent->SetCurState((endPos & 7), endCurByte);
    }
  }
  else
  {
    m_NumCrcs = numCrcs;
    m_CRCs[m_NumCrcs++] = crcVal;
  }
}

HRESULT CThreadInfo::EncodeBlock3(UInt32 blockSize)
{
  CMsbfEncoderTemp outStreamTemp;
  outStreamTemp.SetStream(m_TempArray);
  outStreamTemp.Init();
  m_OutStreamCurrent = &outStreamTemp;

  m_NumCrcs = 0;

  EncodeBlock2(m_Block, blockSize, Encoder->_props.NumPasses);

  #ifndef _7ZIP_ST
  if (Encoder->MtMode)
    Encoder->ThreadsInfo[m_BlockIndex].CanWriteEvent.Lock();
  #endif
  for (UInt32 i = 0; i < m_NumCrcs; i++)
    Encoder->CombinedCrc.Update(m_CRCs[i]);
  Encoder->WriteBytes(m_TempArray, outStreamTemp.GetPos(), outStreamTemp.GetCurByte());
  HRESULT res = S_OK;
  #ifndef _7ZIP_ST
  if (Encoder->MtMode)
  {
    UInt32 blockIndex = m_BlockIndex + 1;
    if (blockIndex == Encoder->NumThreads)
      blockIndex = 0;

    if (Encoder->Progress)
    {
      UInt64 unpackSize = Encoder->m_OutStream.GetProcessedSize();
      res = Encoder->Progress->SetRatioInfo(&m_PackSize, &unpackSize);
    }

    Encoder->ThreadsInfo[blockIndex].CanWriteEvent.Set();
  }
  #endif
  return res;
}

void CEncoder::WriteBytes(const Byte *data, UInt32 sizeInBits, Byte lastByte)
{
  UInt32 bytesSize = (sizeInBits >> 3);
  for (UInt32 i = 0; i < bytesSize; i++)
    m_OutStream.WriteBits(data[i], 8);
  WriteBits(lastByte, (sizeInBits & 7));
}

HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
    const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)
{
  #ifndef _7ZIP_ST
  Progress = progress;
  RINOK(Create());
  for (UInt32 t = 0; t < NumThreads; t++)
  #endif
  {
    #ifndef _7ZIP_ST
    CThreadInfo &ti = ThreadsInfo[t];
    if (MtMode)
    {
      RINOK(ti.StreamWasFinishedEvent.Reset());
      RINOK(ti.WaitingWasStartedEvent.Reset());
      RINOK(ti.CanWriteEvent.Reset());
    }
    #else
    CThreadInfo &ti = ThreadsInfo;
    ti.Encoder = this;
    #endif

    ti.m_OptimizeNumTables = _props.DoOptimizeNumTables();

    if (!ti.Alloc())
      return E_OUTOFMEMORY;
  }

  if (!m_InStream.Create(kBufferSize))
    return E_OUTOFMEMORY;
  if (!m_OutStream.Create(kBufferSize))
    return E_OUTOFMEMORY;

  m_InStream.SetStream(inStream);
  m_InStream.Init();

  m_OutStream.SetStream(outStream);
  m_OutStream.Init();

  CombinedCrc.Init();
  #ifndef _7ZIP_ST
  NextBlockIndex = 0;
  StreamWasFinished = false;
  CloseThreads = false;
  CanStartWaitingEvent.Reset();
  #endif

  WriteByte(kArSig0);
  WriteByte(kArSig1);
  WriteByte(kArSig2);
  WriteByte((Byte)(kArSig3 + _props.BlockSizeMult));

  #ifndef _7ZIP_ST

  if (MtMode)
  {
    ThreadsInfo[0].CanWriteEvent.Set();
    Result = S_OK;
    CanProcessEvent.Set();
    UInt32 t;
    for (t = 0; t < NumThreads; t++)
      ThreadsInfo[t].StreamWasFinishedEvent.Lock();
    CanProcessEvent.Reset();
    CanStartWaitingEvent.Set();
    for (t = 0; t < NumThreads; t++)
      ThreadsInfo[t].WaitingWasStartedEvent.Lock();
    CanStartWaitingEvent.Reset();
    RINOK(Result);
  }
  else
  #endif
  {
    for (;;)
    {
      CThreadInfo &ti =
      #ifndef _7ZIP_ST
      ThreadsInfo[0];
      #else
      ThreadsInfo;
      #endif
      UInt32 blockSize = ReadRleBlock(ti.m_Block);
      if (blockSize == 0)
        break;
      RINOK(ti.EncodeBlock3(blockSize));
      if (progress)
      {
        UInt64 packSize = m_InStream.GetProcessedSize();
        UInt64 unpackSize = m_OutStream.GetProcessedSize();
        RINOK(progress->SetRatioInfo(&packSize, &unpackSize));
      }
    }
  }
  WriteByte(kFinSig0);
  WriteByte(kFinSig1);
  WriteByte(kFinSig2);
  WriteByte(kFinSig3);
  WriteByte(kFinSig4);
  WriteByte(kFinSig5);

  WriteCrc(CombinedCrc.GetDigest());
  return Flush();
}

STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
    const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)
{
  try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
  catch(const CInBufferException &e) { return e.ErrorCode; }
  catch(const COutBufferException &e) { return e.ErrorCode; }
  catch(...) { return S_FALSE; }
}

HRESULT CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *coderProps, UInt32 numProps)
{
  int level = -1;
  CEncProps props;
  for (UInt32 i = 0; i < numProps; i++)
  {
    const PROPVARIANT &prop = coderProps[i];
    PROPID propID = propIDs[i];
    if (propID >= NCoderPropID::kReduceSize)
      continue;
    if (prop.vt != VT_UI4)
      return E_INVALIDARG;
    UInt32 v = (UInt32)prop.ulVal;
    switch (propID)
    {
      case NCoderPropID::kNumPasses: props.NumPasses = v; break;
      case NCoderPropID::kDictionarySize: props.BlockSizeMult = v / kBlockSizeStep; break;
      case NCoderPropID::kLevel: level = v; break;
      case NCoderPropID::kNumThreads:
      {
        #ifndef _7ZIP_ST
        SetNumberOfThreads(v);
        #endif
        break;
      }
      default: return E_INVALIDARG;
    }
  }
  props.Normalize(level);
  _props = props;
  return S_OK;
}

#ifndef _7ZIP_ST
STDMETHODIMP CEncoder::SetNumberOfThreads(UInt32 numThreads)
{
  const UInt32 kNumThreadsMax = 64;
  if (numThreads < 1) numThreads = 1;
  if (numThreads > kNumThreadsMax) numThreads = kNumThreadsMax;
  NumThreads = numThreads;
  return S_OK;
}
#endif

}}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" id="com.analytics.google" version="1.2.2">
  <engines>
    <engine name="cordova" version=">=3.0.0" />
  </engines>
  <name>Google Analytics Plugin</name>
  <description>Phonegap, Cordova, Intel XDK Google Analytics plugin for iOS/Android with full support for views, events, timings, ecommerce and social. Supports userId and campaign url.</description>
  <author email="info@appfeel.com" href="https://github.com/appfeel/admob-google-cordova">AppFeel</author>
  <license>MIT</license>
  <keywords>analytics,google,metrics,event,screen,ecommerce,ua,universal analytics,universal,referral,download,install,track,tracking</keywords>
  <repo>https://github.com/appfeel/analytics-google.git</repo>
  <issue>https://github.com/appfeel/analytics-google/issues</issue>

  <hook type="after_prepare" src="hooks/after_prepare/999-admobPluginNotice.js" />

  <js-module src="www/analytics.js" name="GAPlugin">
    <merges target="analytics" />
  </js-module>

  <platform name="android">
    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="GAPlugin">
        <param name="android-package" value="com.appfeel.cordova.analytics.CPGoogleAnalytics" />
      </feature>
    </config-file>
    <config-file target="AndroidManifest.xml" parent="/*">
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    </config-file>
    <config-file target="AndroidManifest.xml" parent="/manifest/application">
      <service android:name="com.google.analytics.tracking.android.CampaignTrackingService" />
      <receiver android:name="com.google.analytics.tracking.android.CampaignTrackingReceiver" android:exported="true">
        <intent-filter>
          <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
      </receiver>
    </config-file>
    <source-file src="src/android/CPGoogleAnalytics.java" target-dir="src/com/appfeel/cordova/analytics" />
    <dependency id="com.google.play.services" />
  </platform>

  <platform name="ios">
    <config-file target="config.xml" parent="/*">
      <feature name="GAPlugin">
        <param name="ios-package" value="CDVGoogleAnalytics" />
      </feature>
    </config-file>

    <header-file src="src/ios/CDVGoogleAnalytics.h" />
    <source-file src="src/ios/CDVGoogleAnalytics.m" />

    <header-file src="src/ios/GAI.h" />
    <header-file src="src/ios/GAIDictionaryBuilder.h" />
    <header-file src="src/ios/GAIEcommerceFields.h" />
    <header-file src="src/ios/GAIEcommerceProduct.h" />
    <header-file src="src/ios/GAIEcommerceProductAction.h" />
    <header-file src="src/ios/GAIEcommercePromotion.h" />
    <header-file src="src/ios/GAIFields.h" />
    <header-file src="src/ios/GAILogger.h" />
    <header-file src="src/ios/GAITrackedViewController.h" />
    <header-file src="src/ios/GAITracker.h" />

    <source-file src="src/ios/libGoogleAnalyticsServices.a" framework="true" />

    <framework src="SystemConfiguration.framework" />
    <framework src="CoreData.framework" />
    <framework src="libz.dylib" />
    <framework src="libsqlite3.0.dylib" />
  </platform>
</plugin>


text:
@class GWSquare;

@interface GWSquareButton : UIButton
@property (nonatomic, strong) GWSquare *square;
@end


text:
class AuthorizationBuilder
  attr_reader :omnihash, :user, :authorization
  attr_accessor :auth_attribures

  def initialize omnihash, user = nil
    @omnihash = omnihash
    @user     = user
    @auth_attribures = {}
    @authorization = {}
    omniauth_unfold
  end

  def create_authorization
    @authorization = User::Authorization.create auth_attribures
  end

  def self.set_with_omniauth! omniauth_token, user
    authorization = User::Authorization.find_by_token(omniauth_token)

    if authorization
      user.authorizations << authorization

      user.email    = authorization.email if user.email.blank?
      user.username = authorization.username if user.username.blank?

      user.build_profile do |profile|
        profile.fio         = authorization.fio
        profile.first_name  = authorization.first_name
        profile.last_name   = authorization.last_name
        profile.middle_name = authorization.middle_name
        profile.birth_date  = authorization.birth_date
        profile.gender      = authorization.gender
      end
    end
  end

private

  def omniauth_unfold
    auth_attribures[:uid]       = omnihash['uid']
    auth_attribures[:provider]  = omnihash['provider']
    auth_attribures[:data]      = get_extra_data

    get_omniauth_credentials

    auth_attribures[:primary]   = true
    connect_to_user if user.present?
  end

  def get_extra_data
    data = omnihash['info'].merge(omnihash['extra']['raw_info']).delete_if do |key, value|
      value.is_a?(Hashie::Mash) or value.is_a?(Array)
    end
    data[:username] = data[:nickname]
    data
  end

  def get_omniauth_credentials
    if omnihash['credentials'].present?
      auth_attribures[:token]   = omnihash['credentials']['token']
      auth_attribures[:secret]  = omnihash['credentials']['secret']
    end
  end

  def connect_to_user
    auth_attribures[:primary] = false if user.authorizations.blank?
    auth_attribures[:user_id] = user.id
  end
end


text:
package com.colobu.fastjson;

import java.util.Map;

import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
 * Config FastJson.
 * @author smallnest
 *
 */
public class FastJsonConfig {
	public SerializeConfig serializeConfig;
	public ParserConfig parserConfig;
	public SerializerFeature[] serializerFeatures;
	public Feature[] features;
	public Map<Class<?>, SerializeFilter> serializeFilters;

	public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures) {
		this(serializeConfig, serializerFeatures, null, new ParserConfig(), null);
	}

	public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures, Map<Class<?>, SerializeFilter> serializeFilters) {
		this(serializeConfig, serializerFeatures, serializeFilters, new ParserConfig(), null);
	}

	public FastJsonConfig(ParserConfig parserConfig, Feature[] features) {
		this(new SerializeConfig(), null, null, parserConfig, features);
	}

	public FastJsonConfig(SerializeConfig serializeConfig, SerializerFeature[] serializerFeatures, Map<Class<?>, SerializeFilter> serializeFilters, ParserConfig parserConfig, Feature[] features) {
		this.serializeConfig = serializeConfig;
		this.parserConfig = parserConfig;
		this.serializerFeatures = serializerFeatures;
		this.features = features;
		this.serializeFilters = serializeFilters;
	}

}


text:
* Add Multi- versus MonoMarshaller and let a Client's marshaller and unmarshaller be set to either (not just a MultiMarshaller as now)
* Update Narcolepsy and Orderly-Common to use Jackson ASL not LGPL
* Deal with deprecated setDateformat etc in Narcolepsy


text:
import { Inject, Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { tokenNotExpired } from 'angular2-jwt';

@Injectable()
export class BackendRequestClass {

    private result: Object = null;

    constructor(private http: Http) {

    }

    public getResult() {
        return this.result;
    }

    public load() {

        let headers = new Headers({ 'Content-Type': 'application/json' });
        headers.append('Authorization', 'Bearer '+ localStorage.getItem("token"));
        if(tokenNotExpired("token")){
            return new Promise((resolve, reject) => {
               this.http.get(window.location.protocol + "//" + window.location.hostname + ":10000/api/me/", {headers:headers}).map( res => res.json() ).catch((error: any):any => {
                   reject(false);
                   return Observable.throw(error.json().error || 'Server error');
               }).subscribe( (callResult) => {
                   this.result = callResult;
                   resolve(true);
               });
           });
        } else {
        return Promise.resolve("not logged in");}
    }
}


text:
namespace MongoFramework.Infrastructure.Mapping
{
	public interface IEntityIndex
	{
		IEntityProperty Property { get; }
		string IndexName { get; }
		bool IsUnique { get; }
		IndexSortOrder SortOrder { get; }
		int IndexPriority { get; }
		IndexType IndexType { get; }
		bool IsTenantExclusive { get; set; }
	}
}


text:
var mandrill = require('mandrill-api/mandrill');
mandrill_client = new mandrill.Mandrill('MAV-UzITtA_aLmknKBpz-A');

DEFAULT_MESSAGE = {
    "html": "
Travel with miles!
",
    "subject": "TRAVEL WITH MILES RESULTS FOUND WITH ",
    "from_email": "gonzalo.docarmo@gmail.com",
    "from_name": "Miles Check Script",
    "to": [{
            "email": "gonzalo.docarmo@gmail.com",
            "name": "Gonzalo",
            "type": "to"
        }
        // ,
        // {
        // "email": "santiagoesteva@gmail.com",
        // "name": "Santiago",
        // "type": "to"
        // }
    ],
    "important": true,
    "preserve_recipients": true,
    "view_content_link": false
};

function sendEmail(airline, results, depDate, returnDate) {

    var message = DEFAULT_MESSAGE;
    message.subaccount = airline + "-miles";

	message.subject = message.subject + airline.toUpperCase();

	// message body **********************************************
	message.html += "
Departure date: " + depDate + "
";
	if(typeof returnDate != 'undefined'){
		message.html += "
Return date: " + returnDate + "
";
	}
	message.html += "
" + results.toString().replace(/,/g, '
') + "
";
	// message body **********************************************

    return mandrill_client.messages.send({
        "message": message,
        "async": false,
        "ip_pool": null,
        "send_at": null
    }, function(result) {
        console.log(result);
        /*
        [{
                "email": "recipient.email@example.com",
                "status": "sent",
                "reject_reason": "hard-bounce",
                "_id": "abc123abc123abc123abc123abc123"
            }]
        */
    }, function(e) {
        // Mandrill returns the error as an object with name and message keys
        console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
        // A mandrill error occurred: Unknown_Subaccount - No subaccount exists with the id 'customer-123'
    });
}

module.exports.notify = sendEmail;


text:
<?php
require_once 'config.php';
require_once 'websun/websun.php';

// проверяем константы и устанавливаем их, если они не определены в файле config.php
// paths
defined("LFME_ROOT_PATH")       or define( "LFME_ROOT_PATH", '/leafletmaps' );
defined("LFME_TEMPLATES_PATH")  or define( "LFME_TEMPLATES_PATH" , '$/leafletmaps/templates' );
defined("LFME_INDEX_TITLE")     or define( "LFME_INDEX_TITLE" , "Каталог карт для ролевых игр на движке Leaflet");
// viewport
defined("LFME_VIEWPORT_WIDTH")  or define( "LFME_VIEWPORT_WIDTH", 800);
defined("LFME_VIEWPORT_HEIGHT") or define( "LFME_VIEWPORT_HEIGHT", 600);
// version
defined("LFME_VERSION")         or define( "LFME_VERSION", "0.2.2");

/* =====================================================================
* Функции, используемые в проекте. В этом файле описаны только для того,
* чтобы не плодить кучу ненужных мелких файлов.
** ===================================================================== */

/**
 * Instant redirect to URL
 * @param $url
 */
function redirect($url)
{
    if (headers_sent() === false) header('Location: '.$url);
    die();
}

/**
 * Equivalent for isset( array[ key ] ) ? array[ key ] : default ;
 * at PHP 7 will be useless, use
 * z = $array[ $key ] ?? $default;
 *
 * @param $array    - массив, в котором ищем значение
 * @param $key      - ключ
 * @param $default  - значение по умолчанию
 */
function at($array, $key, $default)
{
    return isset($array[$key]) ? $array[$key] : $default;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>arquillian-container-chameleon-parent</artifactId>
    <groupId>org.arquillian.container</groupId>
    <version>1.0.0.Final-SNAPSHOT</version>
    <relativePath>../../pom.xml</relativePath>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>arquillian-chameleon-file-deployment-ftest</artifactId>

  <name>Arquillian Chameleon File Deployment Functional Test</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.arquillian.container</groupId>
      <artifactId>arquillian-chameleon-file-deployment</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.arquillian.container</groupId>
      <artifactId>arquillian-chameleon-junit-container-starter</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>4.1.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!-- This artifact shouldn't be deployed to maven repository -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
var request = require('supertest'),
    should = require('should'),
    app = require('../../app.js'),
    neo4jtest = require('../../config/neo4jtest.js'),
    url = '/api/v1';

describe('User API', function() {
  var username = 'newuser';
  var password = 'yolo';
  before(function(done){
    neo4jtest.initialize(function(){
      done();
    });
  });
  after(function(done){
    neo4jtest.clear(function(){
      done();
    });
  });
  describe('POST /users/signup', function() {
    it('should return a new user for unique username', function(done) {
      request(app)
        .post(url + '/users/signup')
        .send({ username: username, password: password})
        .expect(201)
        .end(function(err, res) {
          var data = JSON.parse(res.text);
          (data.username).should.be.exactly(username);
          (data.neoId).should.be.above(0);
          data.should.have.property('objectId');
          data.should.have.property('token');
          done();
        });
    });
    it('should return an error message if the username is taken', function(done) {
      request(app)
        .post(url + '/users/signup')
        .send({ username: username, password: password})
        .end(function(err, res) {
          var data = JSON.parse(res.text);
          (data.message).should.be.exactly('username newuser already taken');
          done();
        });
    });
  });
  describe('POST /users/login', function() {
    it('should return a logged in user for existing user', function(done) {
      request(app)
        .post(url + '/users/login')
        .send({ username: username, password: password})
        .expect(200)
        .end(function(err, res) {
          var data = JSON.parse(res.text);
          (data.username).should.be.exactly(username);
          (data.neoId).should.be.above(0);
          data.should.have.property('objectId');
          data.should.have.property('token');
          done();
        });
    });
    it('should return an error when an invalid password is entered', function(done) {
      request(app)
        .post(url + '/users/login')
        .send({ username: username, password: password + 'wrong'})
        .expect(200)
        .end(function(err, res) {
          var data = JSON.parse(res.text);
          (data.message).should.be.exactly('invalid login parameters');
          done();
        });
    });
    it('should return an error when an unregistered user tries to log in', function(done) {
      request(app)
        .post(url + '/users/login')
        .send({ username: username + 'unregistered', password: password})
        .expect(200)
        .end(function(err, res) {
          var data = JSON.parse(res.text);
          (data.message).should.be.exactly('invalid login parameters');
          done();
        });
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/containerEpisodeImage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorBackgroundDim"
    android:foreground="?attr/custom_list_selector"
    tools:ignore="Overdraw">

    <ImageView
        android:id="@+id/imageViewEpisode"
        android:layout_width="match_parent"
        android:layout_height="@dimen/imagecontainer_height"
        android:layout_gravity="center_vertical"
        android:contentDescription="@string/description_image"
        android:scaleType="centerCrop" />

</FrameLayout>


text:
import {
  observable,
  batchStart,
  batchEnd,
  observe,
  unobserve,
  ObserveFn,
} from "alo";
import { StoreInterface, SubscribableInterface } from "alo/store";
import { RedomComponent } from "redom";

export abstract class Observer {
  _subscriptions: { [key: string]: ReturnType<typeof observe> } = {};
  _observeFunctions: ObserveFn[] = [];
  _mounted = false;
  _started = false;

  observe(fn: ObserveFn) {
    const length = this._observeFunctions.push(fn);
    const idx = length - 1;

    if (this._mounted) {
      this._startSubscription(fn, idx);
    }

    return () => {
      this._observeFunctions.splice(idx, 1);
      if (!this._subscriptions[idx]) {
        return;
      }

      unobserve(this._subscriptions[idx]);
      delete this._subscriptions[idx];
    };
  }
  _startSubscription = (fn, idx) => {
    this._subscriptions[idx] = observe(fn);
  };
  startSubscriptions() {
    if (this._started) {
      this.clearSubscriptions();
    }
    this._started = true;
    this._observeFunctions.forEach(this._startSubscription);
  }
  clearSubscriptions() {
    for (const fn of Object.values(this._subscriptions)) {
      if (!fn) continue;
      unobserve(fn);
    }
    this._started = false;
    this._subscriptions = {};
  }
  onmount() {
    this._mounted = true;
    this.startSubscriptions();
  }
  onunmount() {
    this._mounted = false;
    this.clearSubscriptions();
  }
}

export abstract class ObserverListItem<
  I = any,
  C = any,
  ID = any
> extends Observer {
  state = observable({
    index: null as any,
    item: (null as unknown) as I,
    items: (null as unknown) as I[],
    context: (null as unknown) as C,
    initData: (null as unknown) as ID,
  });

  init = true;

  constructor(initData) {
    super();
    this.state.initData = initData;
  }

  update(item, index, items, context) {
    const prevBatch = batchStart();
    this.state.item = item;
    this.state.index = index;
    this.state.items = items;
    this.state.context = context;
    batchEnd(prevBatch);

    if (this.init && this["oninit"]) this["oninit"]();
    this.init = false;
  }
}

export class ConnectedComponent<
  S extends StoreInterface = any,
  T extends RedomComponent = any
> {
  el;
  _mounted = false;
  _component: T;
  _subscription?: ReturnType<
    SubscribableInterface<StoreInterface>["subscribe"]
  >;
  _store;
  _id;
  _filterUpdate;
  constructor({
    store,
    component,
    filterUpdate,
    id,
  }: {
    id?: any;
    store: S;
    component: T;
    // TODO: Implement
    filterUpdate?: (options: { store: S }) => boolean | void;
  }) {
    this._store = store;
    this._id = id;
    this._filterUpdate = filterUpdate;
    this._component = component;
    this.el = component["el"];
  }
  update(options = {}) {
    if (!this._component.update) {
      return;
    }

    (this._component.update as any)(options);
  }
  _storeListener = (store) => {
    if (!this._component.update) {
      return;
    }

    const updateOptions: any = {
      connectId: this._id,
      mounted: this._mounted,
      action: store.getAction(),
    };

    if (this._filterUpdate && !this._filterUpdate(updateOptions)) {
      return;
    }

    requestAnimationFrame(() => {
      (this._component.update as any)(updateOptions);
    });
  };
  onmount() {
    this._mounted = true;
    this._subscription = this._store.subscribe(this._storeListener, true);
    this._mounted = false;

    if (this._component.onmount) {
      this._component.onmount();
    }
  }
  onremount() {
    if (this._component.onremount) {
      this._component.onremount();
    }
  }
  onunmount() {
    if (this._subscription) {
      this._subscription();
      this._subscription = undefined;
    }

    if (this._component.onunmount) {
      this._component.onunmount();
    }
  }
  getChild() {
    return this._component;
  }
}


text:
webservice-framework
====================


text: Programs in C,C++