text:
void UT_Init( const char *appName,
              size_t dynamicMem,
              size_t staticMem,
              void (*registerVars)( void ),
              void (*init)( void ),
              void (*done)( void ) );

void UT_Loop( void(*frame)( void ), int inputContext );

void UT_RunApp( const char *appName,
                void (*registerVars)( void ),
                void (*init)( void ),
                void (*frame)( void ),
                void (*done)( void ),
                int inputContext );


text:
package com.github.kaiwinter.androidremotenotifications.json;

import android.util.Log;

import com.github.kaiwinter.androidremotenotifications.RemoteNotifications;
import com.github.kaiwinter.androidremotenotifications.model.UserNotification;
import com.github.kaiwinter.androidremotenotifications.model.buttonaction.ButtonAction;
import com.github.kaiwinter.androidremotenotifications.model.buttonaction.impl.ExitAppButtonAction;
import com.github.kaiwinter.androidremotenotifications.model.buttonaction.impl.OpenStoreButtonAction;
import com.github.kaiwinter.androidremotenotifications.model.buttonaction.impl.OpenUrlButtonAction;
import com.github.kaiwinter.androidremotenotifications.model.impl.AlertDialogNotification;
import com.github.kaiwinter.androidremotenotifications.model.impl.PersistentNotification;
import com.github.kaiwinter.androidremotenotifications.model.impl.ToastNotification;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.typeadapters.RuntimeTypeAdapterFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Utility class for marshalling and unmarshalling JSON and Notification objects.
 */
public final class UnMarshaller {

    /**
     * Creates a JSON string from a Set of {@link PersistentNotification}s.
     *
     * @param notifications the notifications
     * @return the JSON string
     */
    public static String getJsonFromPersistentNotifications(Set<PersistentNotification> notifications) {
        Type listType = new TypeToken<Set<PersistentNotification>>() {
        }.getType();
        return createGson().toJson(notifications, listType);
    }

    /**
     * Creates a JSON string from a Set of {@link UserNotification}s.
     *
     * @param notifications the notifications
     * @return the JSON string
     */
    public static String getJsonFromNotifications(Set<UserNotification> notifications) {
        Type listType = new TypeToken<Set<UserNotification>>() {
        }.getType();
        return createGson().toJson(notifications, listType);
    }

    /**
     * Creates a Set of {@link UserNotification}s from JSON string which is queried from the given URL.
     *
     * @param url the URL which is parsed as JSON
     * @return Set of {@link UserNotification}s
     * @throws IOException if reading the JSON from the URL fails
     */
    public static Set<UserNotification> getNotificationsFromJson(URL url) throws IOException {

        Reader reader = null;
        try {
            reader = new InputStreamReader(url.openStream());

            Type listType = new TypeToken<Set<UserNotification>>() {
            }.getType();
            Set<UserNotification> notifications = createGson().fromJson(reader, listType);
            if (notifications == null) {
                notifications = new HashSet<>();
            }
            return notifications;
        } catch (JsonSyntaxException | JsonIOException e) {
            Log.e(RemoteNotifications.TAG, e.getMessage() + ": " + url);
            return Collections.emptySet();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    /**
     * Creates a Set of {@link PersistentNotification}s from a JSON string.
     *
     * @param json the JSON string.
     * @return Set of {@link PersistentNotification}
     */
    public static Set<PersistentNotification> getPersistentNotificationsFromJson(String json) {
        Type listType = new TypeToken<Set<PersistentNotification>>() {
        }.getType();
        Set<PersistentNotification> notifications = createGson().fromJson(json, listType);
        if (notifications == null) {
            notifications = new HashSet<>();
        }
        return notifications;
    }

    private static Gson createGson() {
        RuntimeTypeAdapterFactory<UserNotification> runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
                .of(UserNotification.class, "type")
                .registerSubtype(AlertDialogNotification.class, "AlertDialogNotification")
                .registerSubtype(ToastNotification.class, "ToastNotification");

        RuntimeTypeAdapterFactory<ButtonAction> runtimeTypeAdapterButtonFactory = RuntimeTypeAdapterFactory
                .of(ButtonAction.class, "type")
                .registerSubtype(OpenUrlButtonAction.class, "OpenUrlButtonAction")
                .registerSubtype(ExitAppButtonAction.class, "ExitAppButtonAction")
                .registerSubtype(OpenStoreButtonAction.class, "OpenStoreButtonAction");

        return new GsonBuilder()
                .registerTypeAdapterFactory(runtimeTypeAdapterFactory)
                .registerTypeAdapterFactory(runtimeTypeAdapterButtonFactory)
                .create();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<!--

-->
<integrations>
    <integration name="TestIntegration1">
        <email>test-integration1@example.com</email>
        <endpoint_url>http://example.com/endpoint1</endpoint_url>
        <identity_link_url>http://www.example.com/identity1</identity_link_url>
    </integration>
    <integration name="TestIntegration2">
        <email>test-integration2@example.com</email>
    </integration>
</integrations>


text:
package com.innova4b.empresaReparto.persistent;

public abstract class Vehiculo {

	private Integer idVehiculo;

	protected String matricula;
	protected int numeroPlazas;

	//METODOS ABSTRACTOS
	public abstract Integer getNumeroPlazas();

	public String getMatricula() {
		return matricula;
	}
	public void setMatricula(String matricula) {
		this.matricula = matricula;
	}
	public void setNumeroPlazas(Integer numeroPlazas) {
		this.numeroPlazas = numeroPlazas;
	}

	public Integer getIdVehiculo() {
		return idVehiculo;
	}

	public void setIdVehiculo(Integer idVehiculo) {
		this.idVehiculo = idVehiculo;
	}

}


text:
package jsprit.core.problem.cost;

import jsprit.core.problem.Location;
import jsprit.core.problem.driver.Driver;
import jsprit.core.problem.vehicle.Vehicle;

public interface BackwardTransportTime {

	public double getBackwardTransportTime(Location from, Location to, double arrivalTime, Driver driver, Vehicle vehicle);

}


text:
..
..
.. 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.
..

.. _to-api-v1-logs-newcount:

*****************
``logs/newcount``
*****************

``GET``
=======
Gets the number of new changes made to the Traffic Control system - "new" being defined as the last time the client requested either :ref:`to-api-v1-logs` or :ref:`to-api-v1-logs-days-days`.

.. note:: This endpoint's functionality is implemented by the :ref:`to-api-v1-logs` and :ref:`to-api-v1-logs-days-days` endpoints' responses setting cookies for the client to use when requesting _this_ endpoint. Take care that your client respects cookies!

:Auth. Required: Yes
:Roles Required: None
:Response Type:  Object

Request Structure
-----------------
No parameters available

Response Structure
------------------
:newLogcount: The integer number of new changes

.. code-block:: http
	:caption: Response Example

	HTTP/1.1 200 OK
	Access-Control-Allow-Credentials: true
	Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
	Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
	Access-Control-Allow-Origin: *
	Cache-Control: no-cache, no-store, max-age=0, must-revalidate
	Content-Type: application/json
	Date: Thu, 15 Nov 2018 15:17:35 GMT
	Server: Mojolicious (Perl)
	Set-Cookie: mojolicious=...; Path=/; Expires=Mon, 18 Nov 2019 17:40:54 GMT; Max-Age=3600; HttpOnly
	Vary: Accept-Encoding
	Whole-Content-Sha512: Ugdqe8GXKSOExphwbDX/Gli+2vBpubttbpfYMbJaCP7adox3MzmVRi2RxTDL5kwPewrcL1CO88zGITskhOsc9g==
	Content-Length: 30

	{ "response": {
		"newLogcount": 4
	}}


text:
package org.jadira.usertype.moneyandcurrency.joda;

import org.hibernate.usertype.ParameterizedType;
import org.jadira.usertype.moneyandcurrency.joda.columnmapper.LongColumnBigMoneyMajorMapper;
import org.jadira.usertype.spi.shared.IntegratorConfiguredType;
import org.joda.money.BigMoney;

/**
 * Maps {@link BigMoney} to and from a Long column using the Major amount for storage.
 * For example $100.34 will be stored as $100. Fractional parts will not be retained.
 */
public class PersistentBigMoneyMajorAmount extends AbstractSingleColumnMoneyUserType<BigMoney, Long, LongColumnBigMoneyMajorMapper> implements ParameterizedType, IntegratorConfiguredType {

	private static final long serialVersionUID = 8215107222490480211L;
}


text:
/**
 *
 */
package org.javaeightstudies.javalambda.testcomparator.functiontest;

/**
 * @author niranjanb
 *
 */
@FunctionalInterface
public interface ShortToByteFunction {

	byte applyAsByte(short s);
}


text:
AUTO_COMMIT=${AUTO_COMMIT:-""}
FUNNY_COMMIT=${FUNNY_COMMIT:-""}

os="$(uname)"

next_change() {
  x=$(cat .change-count)
  echo $((x+1)) | tee .change-count
}

watch() {
  if [[ "$os" = "Linux" ]]; then
    # to install: apt-get install inotify-tools
    inotifywait --quiet --recursive --monitor --event modify --format "%w%f" "$@"
  elif [[ "$os" = "Darwin" ]]; then
    # to install: brew install fswatch
    fswatch -o "$@"
  else
    echo "Unknown OS $os"
    exit 1
  fi
}

notify() {
  if [[ "$os" = "Linux" ]]; then
    notify-send "$@"
  elif [[ "$os" = "Darwin" ]]; then
    # to install: brew install terminal-notifier
    if [[ "$1" == --expire-time=* ]]; then
      shift
    fi
    echo terminal-notifier -message "$@"
    terminal-notifier -message "$@"
  else
    echo "Unknown OS $os"
    exit 1
  fi
}

commit_message() {
  ! [[ -z "$FUNNY_COMMIT" ]] && echo -n " " && curl http://whatthecommit.com/index.txt
}

watch lib spec \
  | while read change; do
    rspec --fail-fast > .watch.out
    res=$?
    committed=

    if [[ $res -eq 0 ]]; then
      ! [[ -z "$AUTO_COMMIT" ]] && git add . && git commit -m "[GREEN] Change $(next_change)$(commit_message)" && committed="(committed)"
      notify --expire-time=1000 "SUCCESS $committed"
    else
      failure=$(cat .watch.out | grep 'Failure\|expected:\|got:\|Error in')
      cat .watch.out
      ! [[ -z "$AUTO_COMMIT" ]] && git add . && git commit -m "[RED] Change $(next_change)$(commit_message)" && committed="(committed)"
      notify --expire-time=3000 "FAILURE:$failure $committed"
    fi
done


text:
rule:
  aip: 162
  name: [core, '0162', rollback-request-name-reference]
  summary: |
    Rollback requests should annotate the `name` field with `google.api.resource_reference`.
permalink: /162/rollback-request-name-reference
redirect_from:
  - /0162/rollback-request-name-reference
---

# Rollback requests: Name resource reference

This rule enforces that all `Rollback` requests have
`google.api.resource_reference` on their `string name` field, as mandated in
[AIP-162][].

## Details

This rule looks at the `name` field of any message matching `Rollback*Request`
and complains if it does not have a `google.api.resource_reference` annotation.

## Examples

**Incorrect** code for this rule:

```proto
// Incorrect.
message RollbackBookRequest {
  // The `google.api.resource_reference` annotation should also be included.
  string name = 1 [(google.api.field_behavior) = REQUIRED];

  string revision_id = 2 [(google.api.field_behavior) = REQUIRED];
}
```

**Correct** code for this rule:

```proto
// Correct.
message RollbackBookRequest {
  string name = 1 [
    (google.api.field_behavior) = REQUIRED,
    (google.api.resource_reference).type = "library.googleapis.com/Book"
  ];

  string revision_id = 2 [(google.api.field_behavior) = REQUIRED];
}
```

## Disabling

If you need to violate this rule, use a leading comment above the field.
Remember to also include an [aip.dev/not-precedent][] comment explaining why.

```proto
message RollbackBookRequest {
  // (-- api-linter: core::0162::rollback-request-name-reference=disabled
  //     aip.dev/not-precedent: We need to do this because reasons. --)
  string name = 1 [(google.api.field_behavior) = REQUIRED];

  string revision_id = 2 [(google.api.field_behavior) = REQUIRED];
}
```

If you need to violate this rule for an entire file, place the comment at the
top of the file.

[aip-162]: https://aip.dev/162
[aip.dev/not-precedent]: https://aip.dev/not-precedent


text:
Shindo.tests("Fog::Compute[:digitalocean] | region model", ['digitalocean', 'compute']) do

  service = Fog::Compute[:digitalocean]
  region  = service.regions.first

  tests('The region model should') do
    tests('have the action') do
      test('reload') { region.respond_to? 'reload' }
    end
    tests('have attributes') do
      model_attribute_hash = region.attributes
      attributes = [
        :id,
        :name,
      ]
      tests("The region model should respond to") do
        attributes.each do |attribute|
          test("#{attribute}") { region.respond_to? attribute }
        end
      end
      tests("The attributes hash should have key") do
        attributes.each do |attribute|
          test("#{attribute}") { model_attribute_hash.has_key? attribute }
        end
      end
    end
  end

end


text:
// Type definitions for Jest 20.0.5
// Project: http://facebook.github.io/jest/
// Definitions by: Asana <https://asana.com>, Ivo Stratev <https://github.com/NoHomey>, jwbay <https://github.com/jwbay>, Alexey Svetliakov <https://github.com/asvetliakov>, Alex Jover Morales <https://github.com/alexjoverm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1

declare var beforeAll: jest.Lifecycle;
declare var beforeEach: jest.Lifecycle;
declare var afterAll: jest.Lifecycle;
declare var afterEach: jest.Lifecycle;
declare var describe: jest.Describe;
declare var fdescribe: jest.Describe;
declare var xdescribe: jest.Describe;
declare var it: jest.It;
declare var fit: jest.It;
declare var xit: jest.It;
declare var test: jest.It;
declare var xtest: jest.It;

declare const expect: jest.Expect;

interface NodeRequire {
    /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */
    requireActual(moduleName: string): any;
    /** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */
    requireMock(moduleName: string): any;
}

declare namespace jest {
    /** Provides a way to add Jasmine-compatible matchers into your Jest context. */
    function addMatchers(matchers: jasmine.CustomMatcherFactories): typeof jest;
    /** Disables automatic mocking in the module loader. */
    function autoMockOff(): typeof jest;
    /** Enables automatic mocking in the module loader. */
    function autoMockOn(): typeof jest;
    /**
     * @deprecated use resetAllMocks instead
     */
    function clearAllMocks(): typeof jest;
    /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */
    function resetAllMocks(): typeof jest;
    /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */
    function clearAllTimers(): typeof jest;
    /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */
    function deepUnmock(moduleName: string): typeof jest;
    /** Disables automatic mocking in the module loader. */
    function disableAutomock(): typeof jest;
    /** Mocks a module with an auto-mocked version when it is being required. */
    function doMock(moduleName: string): typeof jest;
    /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */
    function dontMock(moduleName: string): typeof jest;
    /** Enables automatic mocking in the module loader. */
    function enableAutomock(): typeof jest;
    /** Creates a mock function. Optionally takes a mock implementation. */
    function fn<T extends {}>(implementation: (...args: any[]) => T): Mock<T>;
    function fn<T>(implementation?: Function): Mock<T>;
    /** Use the automatic mocking system to generate a mocked version of the given module. */
    function genMockFromModule<T>(moduleName: string): T;
    /** Returns whether the given function is a mock function. */
    function isMockFunction(fn: any): fn is Mock<any>;
    /** Mocks a module with an auto-mocked version when it is being required. */
    function mock(moduleName: string, factory?: any, options?: MockOptions): typeof jest;
    /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */
    function resetModuleRegistry(): typeof jest;
    /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */
    function resetModules(): typeof jest;
    /** Exhausts tasks queued by setImmediate(). */
    function runAllImmediates(): typeof jest;
    /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */
    function runAllTicks(): typeof jest;
    /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */
    function runAllTimers(): typeof jest;
    /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point).
     * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */
    function runOnlyPendingTimers(): typeof jest;
    /** Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */
    function runTimersToTime(msToRun: number): typeof jest;
    /** Explicitly supplies the mock object that the module system should return for the specified module. */
    function setMock<T>(moduleName: string, moduleExports: T): typeof jest;
    /** Creates a mock function similar to jest.fn but also tracks calls to object[methodName] */
    function spyOn<T extends {}, M extends keyof T>(object: T, method: M): SpyInstance<T[M]>;
    /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */
    function unmock(moduleName: string): typeof jest;
    /** Instructs Jest to use fake versions of the standard timer functions. */
    function useFakeTimers(): typeof jest;
    /** Instructs Jest to use the real versions of the standard timer functions. */
    function useRealTimers(): typeof jest;

    interface MockOptions {
        virtual?: boolean;
    }

    interface EmptyFunction {
        (): void;
    }

    interface DoneCallback {
        (...args: any[]): any
        fail(error?: string | { message: string }): any;
    }

    interface ProvidesCallback {
        (cb: DoneCallback): any;
    }

    interface Lifecycle {
        (fn: ProvidesCallback): any;
    }

    /** Creates a test closure */
    interface It {
        /**
         * Creates a test closure.
         *
         * @param {string} name The name of your test
         * @param {fn?} ProvidesCallback The function for your test
         */
        (name: string, fn?: ProvidesCallback): void;
        /** Only runs this test in the current file. */
        only: It;
        skip: It;
        concurrent: It;
    }

    interface Describe {
        (name: string, fn: EmptyFunction): void
        only: Describe;
        skip: Describe;
    }

    interface MatcherUtils {
        readonly isNot: boolean;
        utils: {
            readonly EXPECTED_COLOR: string;
            readonly RECEIVED_COLOR: string;
            ensureActualIsNumber(actual: any, matcherName?: string): void;
            ensureExpectedIsNumber(actual: any, matcherName?: string): void;
            ensureNoExpected(actual: any, matcherName?: string): void;
            ensureNumbers(actual: any, expected: any, matcherName?: string): void;
            /** get the type of a value with handling of edge cases like `typeof []` and `typeof null` */
            getType(value: any): string;
            matcherHint(matcherName: string, received?: string, expected?: string, options?: { secondArgument?: string, isDirectExpectCall?: boolean }): string;
            pluralize(word: string, count: number): string;
            printExpected(value: any): string;
            printReceived(value: any): string;
            printWithType(name: string, received: any, print: (value: any) => string): string;
            stringify(object: {}, maxDepth?: number): string;
        }
    }

    interface ExpectExtendMap {
        [key: string]: (this: MatcherUtils, received: any, actual: any) => { message: () => string, pass: boolean };
    }

    interface SnapshotSerializerOptions {
        callToJSON?: boolean;
        edgeSpacing?: string;
        spacing?: string;
        escapeRegex?: boolean;
        highlight?: boolean;
        indent?: number;
        maxDepth?: number;
        min?: boolean;
        plugins?: Array<SnapshotSerializerPlugin>
        printFunctionName?: boolean;
        theme?: SnapshotSerializerOptionsTheme;

        // see https://github.com/facebook/jest/blob/e56103cf142d2e87542ddfb6bd892bcee262c0e6/types/PrettyFormat.js
    }
    interface SnapshotSerializerOptionsTheme {
        comment?: string;
        content?: string;
        prop?: string;
        tag?: string;
        value?: string;
    }
    interface SnapshotSerializerColor {
        close: string;
        open: string;
    }
    interface SnapshotSerializerColors {
        comment: SnapshotSerializerColor;
        content: SnapshotSerializerColor;
        prop: SnapshotSerializerColor;
        tag: SnapshotSerializerColor;
        value: SnapshotSerializerColor;
    }
    interface SnapshotSerializerPlugin {
        print(val:any, serialize:((val:any) => string), indent:((str:string) => string), opts:SnapshotSerializerOptions, colors: SnapshotSerializerColors) : string;
        test(val:any) : boolean;
    }

    /** The `expect` function is used every time you want to test a value. You will rarely call `expect` by itself. */
    interface Expect {
        /**
         * The `expect` function is used every time you want to test a value. You will rarely call `expect` by itself.
         *
         * @param {any} actual The value to apply matchers against.
        */
        (actual: any): Matchers<void>;
        anything(): any;
        /** Matches anything that was created with the given constructor. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. */
        any(classType: any): any;
        /** Matches any array made up entirely of elements in the provided array. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.  */
        arrayContaining(arr: any[]): any;
        /** Verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. */
        assertions(num: number): void;
        /** Verifies that at least one assertion is called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. */
        hasAssertions(): void;
        /** You can use `expect.extend` to add your own matchers to Jest. */
        extend(obj: ExpectExtendMap): void;
        /** Adds a module to format application-specific data structures for serialization. */
        addSnapshotSerializer(serializer: SnapshotSerializerPlugin) : void;
        /** Matches any object that recursively matches the provided keys. This is often handy in conjunction with other asymmetric matchers. */
        objectContaining(obj: {}): any;
        /** Matches any string that contains the exact provided string */
        stringMatching(str: string | RegExp): any;
    }

    interface Matchers<R> {
        /** If you know how to test something, `.not` lets you test its opposite. */
        not: Matchers<R>;
        /** Use resolves to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails. */
        resolves: Matchers<Promise<R>>;
        /** Unwraps the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails. */
        rejects: Matchers<Promise<R>>;
        lastCalledWith(...args: any[]): R;
        /** Checks that a value is what you expect. It uses `===` to check strict equality. Don't use `toBe` with floating-point numbers. */
        toBe(expected: any): R;
        /** Ensures that a mock function is called. */
        toBeCalled(): R;
        /** Ensure that a mock function is called with specific arguments. */
        toBeCalledWith(...args: any[]): R;
        /** Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. */
        toBeCloseTo(expected: number, delta?: number): R;
        /** Ensure that a variable is not undefined. */
        toBeDefined(): R;
        /** When you don't care what a value is, you just want to ensure a value is false in a boolean context. */
        toBeFalsy(): R;
        /** For comparing floating point numbers. */
        toBeGreaterThan(expected: number): R;
        /** For comparing floating point numbers. */
        toBeGreaterThanOrEqual(expected: number): R;
        /** Ensure that an object is an instance of a class. This matcher uses `instanceof` underneath. */
        toBeInstanceOf(expected: any): R
        /** For comparing floating point numbers. */
        toBeLessThan(expected: number): R;
        /** For comparing floating point numbers. */
        toBeLessThanOrEqual(expected: number): R;
        /** This is the same as `.toBe(null)` but the error messages are a bit nicer. So use `.toBeNull()` when you want to check that something is null. */
        toBeNull(): R;
        /** Use when you don't care what a value is, you just want to ensure a value is true in a boolean context. In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. */
        toBeTruthy(): R;
        /** Used to check that a variable is undefined. */
        toBeUndefined(): R;
        /** Used to check that a variable is NaN. */
        toBeNaN(): R;
        /** Used when you want to check that an item is in a list. For testing the items in the list, this uses `===`, a strict equality check. */
        toContain(expected: any): R;
        /** Used when you want to check that an item is in a list. For testing the items in the list, this  matcher recursively checks the equality of all fields, rather than checking for object identity. */
        toContainEqual(expected: any): R;
        /** Used when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity. */
        toEqual(expected: any): R;
        /** Ensures that a mock function is called. */
        toHaveBeenCalled(): R;
        /** Ensures that a mock function is called an exact number of times. */
        toHaveBeenCalledTimes(expected: number): R;
        /** Ensure that a mock function is called with specific arguments. */
        toHaveBeenCalledWith(...params: any[]): R;
        /** If you have a mock function, you can use `.toHaveBeenLastCalledWith` to test what arguments it was last called with. */
        toHaveBeenLastCalledWith(...params: any[]): R;
        /** Used to check that an object has a `.length` property and it is set to a certain numeric value. */
        toHaveLength(expected: number): R;
        toHaveProperty(propertyPath: string, value?: any): R;
        /** Check that a string matches a regular expression. */
        toMatch(expected: string | RegExp): R;
        /** Used to check that a JavaScript object matches a subset of the properties of an objec */
        toMatchObject(expected: {}): R;
        /** This ensures that a value matches the most recent snapshot. Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */
        toMatchSnapshot(snapshotName?: string): R;
        /** Used to test that a function throws when it is called. */
        toThrow(error?: string | Constructable | RegExp): R;
        /** If you want to test that a specific error is thrown inside a function. */
        toThrowError(error?: string | Constructable | RegExp): R;
        /** Used to test that a function throws a error matching the most recent snapshot when it is called. */
        toThrowErrorMatchingSnapshot(): R;
    }

    interface Constructable {
        new (...args: any[]): any
    }

    interface Mock<T> extends Function, MockInstance<T> {
        new (): T;
        (...args: any[]): any;
    }

    interface SpyInstance<T> extends MockInstance<T> {
        mockRestore(): void;
    }

    /**
     * Wrap module with mock definitions
     * @example
     *  jest.mock("../api");
     *  import { Api } from "../api";
     *
     *  const myApi: jest.Mocked<Api> = new Api() as any;
     *  myApi.myApiMethod.mockImplementation(() => "test");
     */
    type Mocked<T> = {
        [P in keyof T]: T[P] & MockInstance<T[P]>;
    } & T;

    interface MockInstance<T> {
        mock: MockContext<T>;
        mockClear(): void;
        mockReset(): void;
        mockImplementation(fn: Function): Mock<T>;
        mockImplementationOnce(fn: Function): Mock<T>;
        mockReturnThis(): Mock<T>;
        mockReturnValue(value: any): Mock<T>;
        mockReturnValueOnce(value: any): Mock<T>;
    }

    interface MockContext<T> {
        calls: any[][];
        instances: T[];
    }
}

//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected.
//Relevant parts of Jasmine's API are below so they can be changed and removed over time.
//This file can't reference jasmine.d.ts since the globals aren't compatible.

declare function spyOn(object: any, method: string): jasmine.Spy;
/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */
declare function pending(reason?: string): void;
/** Fails a test when called within one. */
declare function fail(error?: any): void;
declare namespace jasmine {
    var DEFAULT_TIMEOUT_INTERVAL: number;
    var clock: () => Clock;
    function any(aclass: any): Any;
    function anything(): Any;
    function arrayContaining(sample: any[]): ArrayContaining;
    function objectContaining(sample: any): ObjectContaining;
    function createSpy(name: string, originalFn?: Function): Spy;
    function createSpyObj(baseName: string, methodNames: any[]): any;
    function createSpyObj<T>(baseName: string, methodNames: any[]): T;
    function pp(value: any): string;
    function addCustomEqualityTester(equalityTester: CustomEqualityTester): void;
    function addMatchers(matchers: CustomMatcherFactories): void;
    function stringMatching(value: string | RegExp): Any;

    interface Clock {
        install(): void;
        uninstall(): void;
        /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */
        tick(ms: number): void;
        mockDate(date?: Date): void;
    }

    interface Any {
        new (expectedClass: any): any;
        jasmineMatches(other: any): boolean;
        jasmineToString(): string;
    }

    interface ArrayContaining {
        new (sample: any[]): any;
        asymmetricMatch(other: any): boolean;
        jasmineToString(): string;
    }

    interface ObjectContaining {
        new (sample: any): any;
        jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean;
        jasmineToString(): string;
    }

    interface Spy {
        (...params: any[]): any;
        identity: string;
        and: SpyAnd;
        calls: Calls;
        mostRecentCall: { args: any[]; };
        argsForCall: any[];
        wasCalled: boolean;
    }

    interface SpyAnd {
        /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */
        callThrough(): Spy;
        /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */
        returnValue(val: any): Spy;
        /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */
        returnValues(...values: any[]): Spy;
        /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */
        callFake(fn: Function): Spy;
        /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */
        throwError(msg: string): Spy;
        /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */
        stub(): Spy;
    }

    interface Calls {
        /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */
        any(): boolean;
        /** By chaining the spy with calls.count(), will return the number of times the spy was called */
        count(): number;
        /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */
        argsFor(index: number): any[];
        /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */
        allArgs(): any[];
        /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */
        all(): CallInfo[];
        /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */
        mostRecent(): CallInfo;
        /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */
        first(): CallInfo;
        /** By chaining the spy with calls.reset(), will clears all tracking for a spy */
        reset(): void;
    }

    interface CallInfo {
        /** The context (the this) for the call */
        object: any;
        /** All arguments passed to the call */
        args: any[];
        /** The return value of the call */
        returnValue: any;
    }

    interface CustomMatcherFactories {
        [index: string]: CustomMatcherFactory;
    }

    interface CustomMatcherFactory {
        (util: MatchersUtil, customEqualityTesters: Array<CustomEqualityTester>): CustomMatcher;
    }

    interface MatchersUtil {
        equals(a: any, b: any, customTesters?: Array<CustomEqualityTester>): boolean;
        contains<T>(haystack: ArrayLike<T> | string, needle: any, customTesters?: Array<CustomEqualityTester>): boolean;
        buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array<any>): string;
    }

    interface CustomEqualityTester {
        (first: any, second: any): boolean;
    }

    interface CustomMatcher {
        compare<T>(actual: T, expected: T): CustomMatcherResult;
        compare(actual: any, expected: any): CustomMatcherResult;
    }

    interface CustomMatcherResult {
        pass: boolean;
        message: string | (() => string);
    }

    interface ArrayLike<T> {
        length: number;
        [n: number]: T;
    }
}


text:
package net.tridentsdk;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.concurrent.CountDownLatch;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

public class ImplTest {
    @Test
    public void testSetGet() {
        Impl.setImpl(null);
        assertNull(Impl.get());
    }

    @Test(expected = RuntimeException.class)
    public void testError() throws NoSuchFieldException, IllegalAccessException {
        // hack
        Field field = Impl.class.getDeclaredField("IMPL_LATCH");
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        field.setAccessible(true);
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, new CountDownLatch(1));

        Thread current = Thread.currentThread();
        new Thread(() -> {
            try {
                Thread.sleep(1000L);
                current.interrupt();
            } catch (InterruptedException e) {
                fail("This is not supposed to happen");
            }
        }).start();

        Impl.get();
    }
}


text:
{% load staticfiles %}

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

<title>{{title}} — Evangelos Sariyanidi</title>

<link rel="stylesheet" href="{% static "css/fonts/stylesheet.css" %}" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="{% static "css/style.css" %}" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="{% static "css/colorbox.css" %}" type="text/css" charset="utf-8" />

/index

/blog

/projects

/publications

/resources

/code_snippets

/about

	{% block content %}{% endblock %}
	{% block footer %}

			created by e. sariyanidi. coded using python django
				— source code available in resources.

visual components designed using Inkscape

	{% endblock %}


text:
GH-797: Disabled $preserveGlobalState does not load bootstrap.php.
--FILE--
<?php declare(strict_types=1);
$_SERVER['argv'][] = '--do-not-cache-result';
$_SERVER['argv'][] = '--no-configuration';
$_SERVER['argv'][]  = '--process-isolation';
$_SERVER['argv'][]  = '--bootstrap';
$_SERVER['argv'][]  = __DIR__ . '/797/bootstrap797.php';
$_SERVER['argv'][]  = __DIR__ . '/797/Issue797Test.php';

require __DIR__ . '/../../../bootstrap.php';
PHPUnit\TextUI\Command::main();
--EXPECTF--
PHPUnit %s by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: %s, Memory: %s

OK (1 test, 1 assertion)


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Usnea arabum Dill. ex Ach.

### Remarks
null


text:
using MbDotNet.Models.Imposters;

namespace MbDotNet.Interfaces
{
    internal interface IRequestProxy
    {
        void DeleteAllImposters();
        void DeleteImposter(int port);
        void CreateImposter(Imposter imposter);
        RetrievedImposter GetImposter(int port);
    }
}


text:
<?php

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

class MigrationWerxeLaravelSeoCreateSeoTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('seo', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->morphs('entity');
            $table->string('title');
            $table->string('description')->nullable();
            $table->string('keywords')->nullable();
            $table->boolean('noindex')->default(0);
            $table->text('meta')->nullable();

            $table->engine = 'InnoDB';
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('seo');
    }
}


text:
package com.twitter.hraven;

import java.util.HashSet;
import java.util.Set;

import org.codehaus.jackson.map.annotate.JsonSerialize;

import com.twitter.hraven.datasource.ProcessingException;

/**
 * Represents summary information about a hadoop application
 *
 * cluster, user, application name identify this app via {@linkplain AppKey}
 *
 * Used to represent collective statistics of an app
 * either over a period of time or any other summary reporting
 *
 * An actual instance of an app run is represented by {@linkplain Flow}
 */
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class AppSummary {

  /** the key that uniquely identifies this hadoop application */
  private AppKey appKey;

  /** number of runs in this summary */
  private long numberRuns;

  /** run id of the first time this app ran in this summary */
  private long firstRunId;

  /** run id of the last time this app ran in this summary */
  private long lastRunId;

  /** how many hadoop jobs in this summary */
  private long jobCount;

  /** Number of map tasks in this summary */
  private long totalMaps;

  /** Number of reduce tasks in this summary */
  private long totalReduces;

  /** total cost of this app in this summary */
  private double cost;

  /** map slot millis it has taken up */
  private long mapSlotMillis;

  /** reduce slot millis it has taken up */
  private long reduceSlotMillis;

  /** mega byte millis it has taken up */
  private long mbMillis;

  /** the queue(s) this app ran in, in the context of this summary*/
  private Set<String> queues;

  public AppSummary(AppKey key) {
    this.appKey = key;
    this.queues = new HashSet<String>();
  }

  public AppKey getKey() {
    return appKey;
  }

  public void setKey(AppKey key) {
    this.appKey = key;
  }

  public double getCost() {
    return cost;
  }

  public void setCost(double cost) {
    this.cost = cost;
  }

  public long getMbMillis() {
    return mbMillis;
  }

  public void setMbMillis(long mbMillis) {
    this.mbMillis = mbMillis;
  }

  public Set<String> getQueue() {
    return queues;
  }

  public void setQueue(Set<String> queue) {
    this.queues = queue;
  }

  public void addQueue(String aQueue) {
    if (this.queues != null) {
      this.queues.add(aQueue);
    } else {
      throw new ProcessingException("Could not add pool to list of queue for this app "
          + this.appKey);
    }
  }

  public long getNumberRuns() {
    return numberRuns;
  }

  public void setNumberRuns(long numberRuns) {
    this.numberRuns = numberRuns;
  }

  public long getJobCount() {
    return jobCount;
  }

  public void setJobCount(long jobCount) {
    this.jobCount = jobCount;
  }

  public long getMapSlotMillis() {
    return mapSlotMillis;
  }

  public void setMapSlotMillis(long mapSlotMillis) {
    this.mapSlotMillis = mapSlotMillis;
  }

  public long getReduceSlotMillis() {
    return reduceSlotMillis;
  }

  public void setReduceSlotMillis(long reduceSlotMillis) {
    this.reduceSlotMillis = reduceSlotMillis;
  }

  public long getTotalMaps() {
    return totalMaps;
  }

  public void setTotalMaps(long totalMaps) {
    this.totalMaps = totalMaps;
  }

  public long getTotalReduces() {
    return totalReduces;
  }

  public void setTotalReduces(long totalReduces) {
    this.totalReduces = totalReduces;
  }

  public long getFirstRunId() {
    return firstRunId;
  }

  public void setFirstRunId(long firstRunId) {
    this.firstRunId = firstRunId;
  }

  public long getLastRunId() {
    return lastRunId;
  }

  public void setLastRunId(long lastRunId) {
    this.lastRunId = lastRunId;
  }

  /**
   * adds a flow (a run of the app) of the app summary
   * @param flow
   */
  public void addFlow(Flow flow) {

    // add the flow stats to this app summary
    this.numberRuns++;
    this.jobCount += flow.getJobCount();
    this.mapSlotMillis += flow.getMapSlotMillis();
    this.reduceSlotMillis += flow.getReduceSlotMillis();
    this.totalMaps += flow.getTotalMaps();
    this.totalReduces += flow.getTotalReduces();
    this.mbMillis += flow.getMegabyteMillis();

    // add the queue of this flow to the set of queues in this app summary
    this.queues.add(flow.getQueue());

    /**  TODO add jobcost once job cost has been added to job details and flow */

    // store the latest timestamp seen for this app summary
    // since these are epoch timestamps, a bigger number means more recent
    if ((this.lastRunId == 0L) || (this.lastRunId < flow.getRunId())) {
      this.lastRunId = flow.getRunId();
    }

    // store the oldest seen timestamp seen for this app summary
    // since these are epoch timestamps, a smaller number means older run
    if ((this.firstRunId == 0L) || (this.firstRunId > flow.getRunId())) {
      this.firstRunId = flow.getRunId();
    }

  }

}


text:
//
//  SqueakUIViewCALayer.h
//  SqueakPureObjc
//
//  Created by John M McIntosh on 10-09-09.
//  Copyright 2010 Corporate Smalltalk Consulting Ltd. All rights reserved.

//

#import <UIKit/UIKit.h>
#import "SqueakUIView.h"

@interface SqueakUIViewCALayer : SqueakUIView {
	CALayer *myLayer[4][4];
	BOOL	dirty[4][4];
	CGRect	frameForQuartz[4][4];
	CGFloat dividedWidth;
	CGFloat dividedHeight;
}

@end


text:
namespace testinator
{
  //------------------------------------------------------------------------------
  enum RunFlags : uint32_t
  {
    RF_NONE = 0,

    // ALPHA_ORDER means run tests in alphabetical order (default is random
    // order).
    RF_ALPHA_ORDER = 1 << 0,
  };

  //------------------------------------------------------------------------------
  struct RunParams
  {
    uint32_t m_flags = RF_NONE;
    size_t m_numPropertyChecks = 100;
    unsigned long m_randomSeed = 0;
  };

  //------------------------------------------------------------------------------
  struct Result
  {
    std::string m_suiteName;
    std::string m_testName;
    bool m_success;
  };

  using Results = std::vector<Result>;

  //------------------------------------------------------------------------------
  class TestRegistry;

  class Test
  {
  public:
    Test(TestRegistry& reg, const std::string& name,
         const std::string& suiteName = std::string());
    Test(const std::string& name, const std::string& suiteName = std::string());
    virtual ~Test();

    virtual bool Setup(const RunParams&) { return true; }
    virtual bool Run() { return true; }
    bool RunWithBranches();

    Result RunWrapper(const Outputter* outputter)
    {
      Result r;
      m_op = outputter;
      r.m_success = RunWithBranches() && m_success;
      return r;
    }

    const std::string& GetName() const { return m_name; }
    bool skipped() const { return m_skipped; }

  protected:
    bool m_success = true;
    bool m_skipped = false;
    const std::string m_name;
    TestRegistry& m_registry;
    const Outputter* m_op;
  };
}

//------------------------------------------------------------------------------
#define DEF_TEST(NAME, SUITE)                             \
  class SUITE##NAME : public testinator::Test             \
  {                                                       \
  public:                                                 \
    SUITE##NAME()                                         \
      : testinator::Test(#NAME, #SUITE) {}                \
    virtual bool Run() override;                          \
  } s_##SUITE##NAME##_Test;                               \
  bool SUITE##NAME::Run()

//------------------------------------------------------------------------------
#include "branch.h"
#include "test_registry.h"

namespace testinator
{
  //------------------------------------------------------------------------------
  inline Results RunAllTests(const RunParams& params = RunParams(),
                             const Outputter* outputter = nullptr)
  {
    return GetTestRegistry().RunAllTests(params, outputter);
  }

  inline Results RunSuite(const std::string& suiteName,
                          const RunParams& params = RunParams(),
                          const Outputter* outputter = nullptr)
  {
    return GetTestRegistry().RunSuite(suiteName, params, outputter);
  }

  inline Results RunTest(const std::string& testName,
                         const RunParams& params = RunParams(),
                         const Outputter* outputter = nullptr)
  {
    return GetTestRegistry().RunTest(testName, params, outputter);
  }

  //------------------------------------------------------------------------------
  inline Test::Test(TestRegistry& r, const std::string& n, const std::string& s)
    : m_name(n)
    , m_registry(r)
  {
    m_registry.Register(this, n, s);
  }

  inline Test::Test(const std::string& n, const std::string& s)
    : Test(GetTestRegistry(), n, s)
  {
  }

  inline Test::~Test()
  {
    m_registry.Unregister(this);
  }
}


text:
package org.apache.nutch.net.urlnormalizer.basic;

import java.net.URL;
import java.net.MalformedURLException;

// Commons Logging imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

// Nutch imports
import org.apache.nutch.net.URLNormalizer;
import org.apache.nutch.util.LogUtil;

import org.apache.hadoop.conf.Configuration;
import org.apache.oro.text.regex.*;

/** Converts URLs to a normal form . */
public class BasicURLNormalizer implements URLNormalizer {
    public static final Log LOG = LogFactory.getLog(BasicURLNormalizer.class);

    private Perl5Compiler compiler = new Perl5Compiler();
    private ThreadLocal matchers = new ThreadLocal() {
        protected synchronized Object initialValue() {
          return new Perl5Matcher();
        }
      };
    private Rule relativePathRule = null;
    private Rule leadingRelativePathRule = null;
    private Rule adjacentSlashRule = null;

    private Configuration conf;

    public BasicURLNormalizer() {
      try {
        // this pattern tries to find spots like "/xx/../" in the url, which
        // could be replaced by "/" xx consists of chars, different then "/"
        // (slash) and needs to have at least one char different from "."
        relativePathRule = new Rule();
        relativePathRule.pattern = (Perl5Pattern)
          compiler.compile("(/[^/]*[^/.]{1}[^/]*/\\.\\./)",
                           Perl5Compiler.READ_ONLY_MASK);
        relativePathRule.substitution = new Perl5Substitution("/");

        // this pattern tries to find spots like leading "/../" in the url,
        // which could be replaced by "/"
        leadingRelativePathRule = new Rule();
        leadingRelativePathRule.pattern = (Perl5Pattern)
          compiler.compile("^(/\\.\\./)+", Perl5Compiler.READ_ONLY_MASK);
        leadingRelativePathRule.substitution = new Perl5Substitution("/");

        // this pattern tries to find spots like "xx//yy" in the url,
        // which could be replaced by a "/"
        adjacentSlashRule = new Rule();
        adjacentSlashRule.pattern = (Perl5Pattern)
          compiler.compile("/{2,}", Perl5Compiler.READ_ONLY_MASK);
        adjacentSlashRule.substitution = new Perl5Substitution("/");

      } catch (MalformedPatternException e) {
        e.printStackTrace(LogUtil.getWarnStream(LOG));
        throw new RuntimeException(e);
      }
    }

    public String normalize(String urlString, String scope)
            throws MalformedURLException {
        if ("".equals(urlString))                     // permit empty
            return urlString;

        urlString = urlString.trim();                 // remove extra spaces

        URL url = new URL(urlString);

        String protocol = url.getProtocol();
        String host = url.getHost();
        int port = url.getPort();
        String file = url.getFile();

        boolean changed = false;

        if (!urlString.startsWith(protocol))        // protocol was lowercased
            changed = true;

        if ("http".equals(protocol) || "ftp".equals(protocol)) {

            if (host != null) {
                String newHost = host.toLowerCase();    // lowercase host
                if (!host.equals(newHost)) {
                    host = newHost;
                    changed = true;
                }
            }

            if (port == url.getDefaultPort()) {       // uses default port
                port = -1;                              // so don't specify it
                changed = true;
            }

            if (file == null || "".equals(file)) {    // add a slash
                file = "/";
                changed = true;
            }

            if (url.getRef() != null) {                 // remove the ref
                changed = true;
            }

            // check for unnecessary use of "/../"
            String file2 = substituteUnnecessaryRelativePaths(file);

            if (!file.equals(file2)) {
                changed = true;
                file = file2;
            }

        }

        if (changed)
            urlString = new URL(protocol, host, port, file).toString();

        return urlString;
    }

    private String substituteUnnecessaryRelativePaths(String file) {
        String fileWorkCopy = file;
        int oldLen = file.length();
        int newLen = oldLen - 1;

        // All substitutions will be done step by step, to ensure that certain
        // constellations will be normalized, too
        //
        // For example: "/aa/bb/../../cc/../foo.html will be normalized in the
        // following manner:
        //   "/aa/bb/../../cc/../foo.html"
        //   "/aa/../cc/../foo.html"
        //   "/cc/../foo.html"
        //   "/foo.html"
        //
        // The normalization also takes care of leading "/../", which will be
        // replaced by "/", because this is a rather a sign of bad webserver
        // configuration than of a wanted link.  For example, urls like
        // "http://www.foo.com/../" should return a http 404 error instead of
        // redirecting to "http://www.foo.com".
        //
        Perl5Matcher matcher = (Perl5Matcher)matchers.get();

        while (oldLen != newLen) {
            // substitue first occurence of "/xx/../" by "/"
            oldLen = fileWorkCopy.length();
            fileWorkCopy = Util.substitute
              (matcher, relativePathRule.pattern,
               relativePathRule.substitution, fileWorkCopy, 1);

            // remove leading "/../"
            fileWorkCopy = Util.substitute
              (matcher, leadingRelativePathRule.pattern,
               leadingRelativePathRule.substitution, fileWorkCopy, 1);

            // collapse adjacent slashes with "/"
            fileWorkCopy = Util.substitute
            (matcher, adjacentSlashRule.pattern,
              adjacentSlashRule.substitution, fileWorkCopy, 1);

            newLen = fileWorkCopy.length();
        }

        return fileWorkCopy;
    }

    /**
     * Class which holds a compiled pattern and its corresponding substition
     * string.
     */
    private static class Rule {
        public Perl5Pattern pattern;
        public Perl5Substitution substitution;
    }

  public void setConf(Configuration conf) {
    this.conf = conf;
  }

  public Configuration getConf() {
    return this.conf;
  }

}


text:
package it.unibz.inf.data_pumper.columns_cluster;

interface IntervalKeyDecorator extends IntervalKey {

}


text:
{% extends 'base.html' %}
{% load staticfiles %}
{% load i18n %}

{% block title %}{{ result.name }}{% endblock %}

{% block head %}
  <link href="{% static 'css/articles.css' %}" rel="stylesheet">

{% endblock head %}

{% block main %}

{% trans 'Results' %}

{% trans 'Result Details' %}

{{ result }}

{% endblock main %}


text: from .episode import Episode


text:
export * from "./common";
export * from "./openspec2";
export * from "./openspec3";


text:
function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

function formatParams( params ){
    return "?" + Object
        .keys(params)
        .map(function(key){
            return key+"="+encodeURIComponent(params[key])
        })
        .join("&")
}

function show_display(type='image',page=1){
    var http = new XMLHttpRequest();
    http.open('GET','/display'+formatParams({type:type,page:page}), true);
    http.onreadystatechange = function(){
        if(this.readyState === 4 && this.status === 200){
            display_data(this.response)
        }
    }
    http.send();
}

function create_pagination(pageList,type){
    //TODO page number updated display on pagination bar
    var ul = document.createElement('ul');
    ul.setAttribute('class','pagination');
    if(type==='image' && $( "#img_pagination" ).length<=0){
        ul.setAttribute('id','img_pagination');
        document.getElementById('img_content').appendChild(ul);
    }
    else if(type==='text' && $( "#text_pagination" ).length<=0){
        ul.setAttribute('id','text_pagination');
        document.getElementById('text_content').appendChild(ul);
    }
    for (var page=0; page<pageList.length; page++){
        var li = document.createElement('li');
        var a = document.createElement('a');
        a.innerHTML = pageList[page];
        if(type==='image'){
            a.setAttribute('href','#img_content/'+pageList[page]);
            a.setAttribute('onclick',"return directPage('image',"+pageList[page]+")");
        }else{
            a.setAttribute('href','#text_content/'+pageList[page]);
            a.setAttribute('onclick',"return directPage('text',"+pageList[page]+")");
        }
        li.appendChild(a);
        ul.appendChild(li);
    }
}

function directPage(type,page){
    if(type==='image'){
        show_display('image',page)
    }else{
        show_display('text',page)
    }
}

function create_editButton(type,id){
    var editButton = document.createElement('a');
    editButton.innerHTML = 'Edit';
    editButton.classList.add('btn','btn-link');
    if(type==='image'){
        editButton.setAttribute('href','/edit?img_id='+id);
    }else if(type==='text'){
        editButton.setAttribute('href','/edit?text_id='+id);
    }
    return editButton;
}

function create_deleteButton(id){
    var deleteButton = document.createElement('a');
    deleteButton.innerHTML = 'Delete';
    deleteButton.classList.add('btn','btn-link');
    deleteButton.setAttribute('href','/delete?target_id='+id);
    deleteButton.setAttribute('onclick','return deleteConfirm()');
    return deleteButton
}

function insert_imgs(imgs,data_types,page,type){
    var img_table = document.getElementById('img_table')
    while(img_table.rows.length > 1){
        img_table.deleteRow(-1);
    }
    var count = imgs.length
    var perPage = 8
    var totalPage = Math.ceil(count/perPage)
    var start = (page-1)*perPage
    var end = page*perPage
    for(let obj of imgs.slice(start,end)){
        var row = img_table.insertRow();
        for (let type of data_types){
            if(type[0] === obj['type_id']){
                var target_type = type
            }
        }
        var preview_img = document.createElement('img');
        preview_img.setAttribute('src',obj['img_url']);
        preview_img.setAttribute('width','240');
        preview_img.setAttribute('height','180');

        var editButton = create_editButton(type='image',obj['img_id']);
        var deleteButton = create_deleteButton(obj['img_id']);

        row.insertCell().innerHTML = obj['img_id'];
        row.insertCell().innerHTML = target_type[1];
        row.insertCell().innerHTML = obj['img_upload_time'];
        row.insertCell().innerHTML = obj['img_start_date'];
        row.insertCell().innerHTML = obj['img_end_date'];
        row.insertCell().innerHTML = obj['img_start_time'];
        row.insertCell().innerHTML = obj['img_end_time'];
        row.insertCell().innerHTML = obj['img_display_count'];
        row.insertCell().innerHTML = obj['img_display_time'];
        row.insertCell().appendChild(preview_img);
        var editCell = row.insertCell();
        editCell.appendChild(editButton);
        editCell.appendChild(deleteButton);
    }
    var pageList=[]
    if(Number(page)>=3){
        if(Number(page)<=totalPage-2){
            pageList.push(Number(page)-2,Number(page)-1,Number(page),Number(page)+1,Number(page)+2);
        }
        else if(Number(page)===totalPage-1){
            pageList.push(Number(page)-3,Number(page)-2,Number(page)-1,Number(page),Number(page)+1);
        }
        else{
            pageList.push(Number(page)-4,Number(page)-3,Number(page)-2,Number(page)-1,Number(page));
        }
    }else{
        if(totalPage<=5){
            for(let i=page;i<=totalPage;i++){
                pageList.push(i);
            }
        }else{
            for(let i=page;i<=5;i++){
                pageList.push(i);
            }
        }
    }
    create_pagination(pageList,type);
}

function insert_texts(texts,data_types,page,type){
    text_table = document.getElementById('text_table');
    while(text_table.rows.length > 1){
        text_table.deleteRow(-1);
    }
    var count = texts.length
    var perPage = 8;
    var totalPage = Math.ceil(count/perPage)
    var start = (page-1)*perPage
    var end = page*perPage
    for(let text of texts.slice(start,end)){
        var row = text_table.insertRow();
        for (let type of data_types){
            if(type[0] === text[1]){
                var target_type = type
            }
        }

        var editButton = create_editButton(type='text',text[0]);
        var deleteButton = create_deleteButton(text[0]);

        row.insertCell().innerHTML = text[0];
        if (typeof target_type != 'undefined'){
            row.insertCell().innerHTML = target_type[1];
        }else{
            row.insertCell().innerHTML = '';
        }
        row.insertCell().innerHTML = text[2];
        row.insertCell().innerHTML = text[3];
        row.insertCell().innerHTML = text[4];
        row.insertCell().innerHTML = text[5];
        row.insertCell().innerHTML = text[6];
        row.insertCell().innerHTML = text[7];
        row.insertCell().innerHTML = text[8];
        var editCell = row.insertCell();
        editCell.appendChild(editButton);
        editCell.appendChild(deleteButton);
    }
    var pageList=[]
    if(Number(page)>=3){
        if(page<=totalPage-2){
            pageList.push(Number(page)-2,Number(page)-1,Number(page),Number(page)+1,Number(page)+2);
        }
        else if(page===totalPage-1){
            pageList.push(Number(page)-3,Number(page)-2,Number(page)-1,Number(page),Number(page)+1);
        }
        else{
            pageList.push(Number(page)-4,Number(page)-3,Number(page)-2,Number(page)-1,Number(page));
        }
    }else{
        if(totalPage<=5){
            for(let i=page;i<=totalPage;i++){
                pageList.push(i);
            }
        }else{
            for(let i=page;i<=5;i++){
                pageList.push(i);
            }
        }
    }
    create_pagination(pageList,type);
}

function display_data(response){
    response = JSON.parse(response)
    if(response.type === 'image'){
        insert_imgs(response.data,response.data_types,response.page,response.type)
    }else if(response.type === 'text'){
        insert_texts(response.data,response.data_types,response.page,response.type)
    }
}


text:
using System.Collections.Generic;

namespace MQTTnet.Packets
{
    public sealed class MqttPubRelPacketProperties
    {
        public string ReasonString { get; set; }

        public List<MqttUserProperty> UserProperties { get; set; }
    }
}


text:
/**
 * @fileoverview Prevent direct mutation of this.state
 * @author David Petersen
 * @author Nicolas Fernandez <@burabure>
 */
'use strict';

const Components = require('../util/Components');

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

module.exports = {
  meta: {
    docs: {
      description: 'Prevent direct mutation of this.state',
      category: 'Possible Errors',
      recommended: true
    }
  },

  create: Components.detect((context, components, utils) => {
    /**
     * Checks if the component is valid
     * @param {Object} component The component to process
     * @returns {Boolean} True if the component is valid, false if not.
     */
    function isValid(component) {
      return Boolean(component && !component.mutateSetState);
    }

    /**
     * Reports undeclared proptypes for a given component
     * @param {Object} component The component to process
     */
    function reportMutations(component) {
      let mutation;
      for (let i = 0, j = component.mutations.length; i < j; i++) {
        mutation = component.mutations[i];
        context.report({
          node: mutation,
          message: 'Do not mutate state directly. Use setState().'
        });
      }
    }

    // --------------------------------------------------------------------------
    // Public
    // --------------------------------------------------------------------------
    let inConstructor = false;
    let inCallExpression = false;

    return {
      MethodDefinition(node) {
        if (node.kind === 'constructor') {
          inConstructor = true;
        }
      },

      CallExpression: function() {
        inCallExpression = true;
      },

      AssignmentExpression(node) {
        let item;
        if ((inConstructor && !inCallExpression) || !node.left || !node.left.object) {
          return;
        }
        item = node.left;
        while (item.object && item.object.property) {
          item = item.object;
        }
        if (
          item.object.type === 'ThisExpression' &&
          item.property.name === 'state'
        ) {
          const component = components.get(utils.getParentComponent());
          const mutations = (component && component.mutations) || [];
          mutations.push(node.left.object);
          components.set(node, {
            mutateSetState: true,
            mutations
          });
        }
      },

      'CallExpression:exit': function() {
        inCallExpression = false;
      },

      'MethodDefinition:exit': function (node) {
        if (node.kind === 'constructor') {
          inConstructor = false;
        }
      },

      'Program:exit': function () {
        const list = components.list();

        Object.keys(list).forEach(key => {
          if (!isValid(list[key])) {
            reportMutations(list[key]);
          }
        });
      }
    };
  })
};


text:
using System;
using System.Reactive.Linq;

namespace LanguageExt
{
    public static class TryOptionRxExtensions
    {
        public static IObservable<A> ToObservable<A>(this TryOption<A> ma) =>
            ma.Match(
                Some: Observable.Return,
                None: () => Observable.Empty<A>(),
                Fail: e => Observable.Empty<A>());

        public static IObservable<R> MatchObservable<A, R>(this TryOption<A> ma, Func<A, IObservable<R>> Some, Func<R> Fail) =>
            ma.Match(
                Some: Some,
                Fail: () => Observable.Return(Fail()));

        public static IObservable<R> MatchObservable<A, R>(this TryOption<A> ma, Func<A, IObservable<R>> Some, Func<R> None, Func<Exception, R> Fail) =>
            ma.Match(
                Some: Some,
                None: () => Observable.Return(None()),
                Fail: e => Observable.Return(Fail(e)));

        public static IObservable<R> MatchObservable<A, R>(this TryOption<A> ma, Func<A, IObservable<R>> Some, Func<IObservable<R>> Fail) =>
            ma.Match(
                Some: Some,
                Fail: Fail);

        public static IObservable<R> MatchObservable<A, R>(this TryOption<A> ma, Func<A, IObservable<R>> Some, Func<IObservable<R>> None, Func<Exception, IObservable<R>> Fail) =>
            ma.Match(
                Some: Some,
                None: None,
                Fail: Fail);

        public static IObservable<R> MatchObservable<A, R>(this TryOption<A> ma, Func<A, R> Some, Func<IObservable<R>> Fail) =>
            ma.Match(
                Some: x => Observable.Return(Some(x)),
                Fail: Fail);

        public static IObservable<R> MatchObservable<A, R>(this TryOption<A> ma, Func<A, R> Some, Func<IObservable<R>> None, Func<Exception, IObservable<R>> Fail) =>
            ma.Match(
                Some: x => Observable.Return(Some(x)),
                None: None,
                Fail: Fail);

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, R> Some, Func<R> Fail) =>
            self.Select(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(Some, Fail, _ => Fail());
            });

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, IObservable<R>> Some, Func<R> Fail) =>
            from tt in self.SelectMany(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(Some, () => Observable.Return(Fail()), _ => Observable.Return(Fail()));
            })
            select tt;

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, IObservable<R>> Some, Func<IObservable<R>> Fail) =>
            from tt in self.SelectMany(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(Some, Fail, _ => Fail());
            })
            select tt;

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, R> Some, Func<IObservable<R>> Fail) =>
            from tt in self.SelectMany(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(x => Observable.Return(Some(x)), Fail, _ => Fail());
            })
            select tt;

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, R> Some, Func<R> None, Func<Exception, R> Fail) =>
            self.Select(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(Some, None, Fail);
            });

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, IObservable<R>> Some, Func<R> None, Func<Exception, R> Fail) =>
            from tt in self.SelectMany(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(Some, () => Observable.Return(None()), e => Observable.Return(Fail(e)));
            })
            select tt;

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, IObservable<R>> Some, Func<IObservable<R>> None, Func<Exception, IObservable<R>> Fail) =>
            from tt in self.SelectMany(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(Some, None, Fail);
            })
            select tt;

        public static IObservable<R> MatchObservable<T, R>(this IObservable<TryOption<T>> self, Func<T, R> Some, Func<IObservable<R>> None, Func<Exception, IObservable<R>> Fail) =>
            from tt in self.SelectMany(trySelf =>
            {
                var res = trySelf.Try();
                return res.Match(x => Observable.Return(Some(x)), None, Fail);
            })
            select tt;

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>statsmodels.tools.eval_measures.aic_sigma — statsmodels v0.10.2 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.tools.eval_measures.aicc" href="statsmodels.tools.eval_measures.aicc.html" />
    <link rel="prev" title="statsmodels.tools.eval_measures.aic" href="statsmodels.tools.eval_measures.aic.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Tools |

statsmodels.tools.eval_measures.aic_sigma¶

statsmodels.tools.eval_measures.aic_sigma(sigma2, nobs, df_modelwc, islog=False)[source]¶

Akaike information criterion

Parameters

sigma2float

estimate of the residual variance or determinant of Sigma_hat in the
multivariate case. If islog is true, then it is assumed that sigma
is already log-ed, for example logdetSigma.

nobsint

number of observations

df_modelwcint

number of parameters including constant

Returns

aicfloat

information criterion

Notes

A constant has been dropped in comparison to the loglikelihood base
information criteria. The information criteria should be used to compare
only comparable models.

For example, AIC is defined in terms of the loglikelihood as

\(-2 llf + 2 k\)

in terms of \(\hat{\sigma}^2\)

\(log(\hat{\sigma}^2) + 2 k / n\)

in terms of the determinant of \(\hat{\Sigma}\)

\(log(\|\hat{\Sigma}\|) + 2 k / n\)

Note: In our definition we do not divide by n in the log-likelihood
version.

TODO: Latex math

reference for example lecture notes by Herman Bierens

References

http://en.wikipedia.org/wiki/Akaike_information_criterion

Previous topic

statsmodels.tools.eval_measures.aic

Next topic

statsmodels.tools.eval_measures.aicc

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

        © Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 2.2.1.


text:
from collections import defaultdict

class Sieve(object):

    def __init__(self, nmax):
        self.iscomp = defaultdict(bool)
        self.nmax = nmax
        for n in range(2, nmax):
            m = 2*n
            while m <= nmax:
                self.iscomp[m] = True
                m += n

    def isprime(self, n):
        if n < 2:
            return False
        else:
            return not self.iscomp[n]

    def find_all_primes(self, nmax):
        return [n for n in range(2, min(self.nmax, nmax)) if not self.iscomp[n]]

sieve = Sieve(100)

for i in range(0, 50):
    print i, sieve.isprime(i)

print sieve.find_all_primes(110)


text:
module Main where

import           Control.Exception
import           Control.Monad (unless, when)
import qualified Data.ByteString as S
import           Data.List (isInfixOf)
import           StackTest

main :: IO ()
main = do
    removeDirIgnore ".stack-work"
    removeFileIgnore "stack.yaml"
    stack [defaultResolverArg, "init"]
    stack ["build", ":alpha"]
    bracket
        (S.readFile alphaFile)
        (S.writeFile alphaFile)
        (const
             (do appendFile alphaFile "\n--"
                 stackCheckStderr
                     ["build", ":alpha"]
                     (rejectMessage
                          (unlines
                               ["Preprocessing executable 'beta' for foo-0..."]))))
  where
    alphaFile = "app/Alpha.hs"

expectMessage :: String -> String -> IO ()
expectMessage msg stderr =
    unless (msg `isInfixOf` stderr)
        (error $ "Expected in output: \n" ++ show msg)

rejectMessage :: String -> String -> IO ()
rejectMessage msg stderr =
    when (msg `isInfixOf` stderr)
            (error $ "Did not expect message here: \n" ++ show msg)


text:
using System;
using UnityEngine;

public class MineOreAction : GoapAction
{
	private bool mined = false;
	private IronRockComponent targetRock; // where we get the ore from

	private float startTime = 0;
	public float miningDuration = 2; // seconds

	public MineOreAction () {
		addPrecondition ("hasTool", true); // we need a tool to do this
		addPrecondition ("hasOre", false); // if we have ore we don't want more
		addEffect ("hasOre", true);
	}

	public override void reset ()
	{
		mined = false;
		targetRock = null;
		startTime = 0;
	}

	public override bool isDone ()
	{
		return mined;
	}

	public override bool requiresInRange ()
	{
		return true; // yes we need to be near a rock
	}

	public override bool checkProceduralPrecondition (GameObject agent)
	{
		// find the nearest rock that we can mine
		IronRockComponent[] rocks = FindObjectsOfType ( typeof(IronRockComponent) ) as IronRockComponent[];
		IronRockComponent closest = null;
		float closestDist = 0;

		foreach (IronRockComponent rock in rocks) {
			if (closest == null) {
				// first one, so choose it for now
				closest = rock;
				closestDist = (rock.gameObject.transform.position - agent.transform.position).magnitude;
			} else {
				// is this one closer than the last?
				float dist = (rock.gameObject.transform.position - agent.transform.position).magnitude;
				if (dist < closestDist) {
					// we found a closer one, use it
					closest = rock;
					closestDist = dist;
				}
			}
		}
		targetRock = closest;
		target = targetRock.gameObject;

		return closest != null;
	}

	public override bool perform (GameObject agent)
	{
		if (startTime == 0)
			startTime = Time.time;

		if (Time.time - startTime > miningDuration) {
			// finished mining
			BackpackComponent backpack = (BackpackComponent)agent.GetComponent(typeof(BackpackComponent));
			backpack.numOre += 2;
			mined = true;
			ToolComponent tool = backpack.tool.GetComponent(typeof(ToolComponent)) as ToolComponent;
			tool.use(0.5f);
			if (tool.destroyed()) {
				Destroy(backpack.tool);
				backpack.tool = null;
			}
		}
		return true;
	}

}


text:
class ActivityPolicy < ApplicationPolicy
  def create?
    user.admin?
  end

  def update?
    create?
  end

  def destroy?
    create?
  end

  class Scope < Scope
    def resolve
      scope
    end
  end
end


text:
<?php
	@session_start();
	if (!(isset($_SESSION['administrator'])||
		isset($_SESSION['contest_creator'])||
		isset($_SESSION['problem_editor']))){
		echo "Please Login First!";
		exit(1);
	}
	if(isset($OJ_LANG)){
		require_once("../lang/$OJ_LANG.php");
	}

	require_once("../include/db_info.inc.php");
	require_once("../include/const.inc.php");

	function send_post($url, $post_data, $timeout=3) {
		$postdata = http_build_query($post_data);
		$options = array(
			'http' => array(
				'method' => 'POST',
				'header' => 'Content-type:application/x-www-form-urlencoded',
				'content' => $postdata,
				'timeout' => $timeout
			)
		);
		$context = stream_context_create($options);
		$result = file_get_contents($url, false, $context);
		return $result;
	}

	$result=send_post("http://$OS_HOST/cloud_api", array("command"=>"launch_instance", "image"=>$_POST['image'], "flavor"=>$_POST['flavor'], "internet"=>"true", "name"=>$_POST['name']));
	echo $result;
?>


text:
#ifndef MODULES_DRIVERS_DELPHI_ESR_PROTOCOL_ESR_TRACKMOTIONPOWER_540_H_
#define MODULES_DRIVERS_DELPHI_ESR_PROTOCOL_ESR_TRACKMOTIONPOWER_540_H_

#include "modules/drivers/proto/delphi_esr.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"

namespace apollo {
namespace drivers {
namespace delphi_esr {

using apollo::drivers::DelphiESR;

class Esrtrackmotionpower540 :
public apollo::drivers::canbus::ProtocolData<DelphiESR> {
 public:
  static const int32_t ID;
  Esrtrackmotionpower540();
  void Parse(const std::uint8_t* bytes, int32_t length,
             DelphiESR* delphi_esr) const override;

 private:
  // config detail: {'name': 'CAN_TX_TRACK_ROLLING_COUNT_2', 'offset': 0.0,
  // 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'physical_range':
  // '[0|1]', 'bit': 4, 'type': 'bool', 'order': 'motorola', 'physical_unit':
  // ''}
  bool can_tx_track_rolling_count_2(const std::uint8_t* bytes,
                                    const int32_t length) const;
  int32_t can_tx_track_can_id_group(const std::uint8_t* bytes,
                                    int32_t length) const;
  bool can_tx_track_moving(const std::uint8_t* bytes, int32_t length,
                           int32_t index) const;
  bool can_tx_track_moving_fast(const std::uint8_t* bytes, int32_t length,
                                int32_t index) const;
  bool can_tx_track_moving_slow(const std::uint8_t* bytes, int32_t length,
                                int32_t index) const;
  int32_t can_tx_track_power(const std::uint8_t* bytes, int32_t length,
                             int32_t index) const;
};

}  // namespace delphi_esr
}  // namespace drivers
}  // namespace apollo

#endif  // MODULES_CANBUS_VEHICL_ESR_PROTOCOL_ESR_TRACKMOTIONPOWER_540_H_


text:
{% extends "base.html" %}
{% block title %}{{ page.title }} - {{ SITENAME }}{% endblock %}
{% block html_lang %}{{ page.lang }}{% endblock %}
{% block meta %}
    {% if page.author %}
        <meta name="author" content="{{ page.author }}" />
    {% else %}
        <meta name="author" content="{{ AUTHOR }}" />
    {% endif %}
    {% if page.summary %}
        <meta name="description" content="{{ page.summary|striptags|escape }}" />
    {% endif %}
{% endblock %}
{% block opengraph %}
    {% if OPEN_GRAPH_FB_APP_ID %}
        <meta property="fb:app_id" content="{{ OPEN_GRAPH_FB_APP_ID }}"/>
    {% endif %}
    <meta property="og:site_name" content="{{ SITENAME }}" />
    <meta property="og:type" content="article"/>
    <meta property="og:title" content="{{ page.title|striptags|escape }}"/>
    <meta property="og:url" content="{{ SITEURL }}/{{ page.url }}"/>
    <meta property="og:description" content="{{ page.summary|striptags|escape }}" />
    {% if page.og_image %}
        <meta property="og:image"
              content="{{ SITEURL }}/{{ page.og_image }}"/>
    {% elif OPEN_GRAPH_IMAGE %}
        <meta property="og:image"
              content="{{ SITEURL }}/{{ OPEN_GRAPH_IMAGE }}"/>
    {% endif %}
{% endblock %}

{% block canonical_rel %}
<link rel="canonical" href="{{ SITEURL }}/{{ page.url }}">
{% endblock %}

{% block breadcrumbs %}
    {% if DISPLAY_BREADCRUMBS %}

	  {% if page.url %}

{{ page.title }}

	  {% endif %}

    {% endif %}
{% endblock %}

{% block content %}

{{ page.title }}

          {% import 'includes/translations.html' as translations with context %}
          {{ translations.translations_for(page) }}
          {% if PDF_PROCESSOR %}

                  get the pdf

          {% endif %}

              {{ page.content }}
              {% if page.comments == 'enabled' %}
                  {% include 'includes/comments.html' %}
              {% endif %}

{% endblock %}


text:
<?php

namespace Solarium\Tests\QueryType\MoreLikeThis;

use Solarium\QueryType\MoreLikeThis\Query;
use Solarium\QueryType\MoreLikeThis\ResponseParser;

class ResponseParserTest extends \PHPUnit_Framework_TestCase
{
    public function testParse()
    {
        $data = array(
            'response' => array(
                'docs' => array(
                    array('fieldA' => 1, 'fieldB' => 'Test'),
                    array('fieldA' => 2, 'fieldB' => 'Test2')
                ),
                'numFound' => 503,
            ),
            'responseHeader' => array(
                'status' => 1,
                'QTime' => 13,
            ),
            'interestingTerms' => array(
                'key1', 'value1', 'key2', 'value2'
            ),
            'match' => array(
                'docs' => array(
                    array('fieldA' => 5, 'fieldB' => 'Test5'),
                ),
            ),
        );

        $query = new Query();
        $query->setInterestingTerms('details');
        $query->setMatchInclude(true);

        $resultStub = $this->getMock('Solarium\QueryType\MoreLikeThis\Result', array(), array(), '', false);
        $resultStub->expects($this->any())
             ->method('getData')
             ->will($this->returnValue($data));
        $resultStub->expects($this->any())
             ->method('getQuery')
             ->will($this->returnValue($query));

        $parser = new ResponseParser;
        $result = $parser->parse($resultStub);

        $this->assertEquals(array('key1' => 'value1', 'key2' => 'value2'), $result['interestingTerms']);
        $this->assertEquals(5, $result['match']->fieldA);
    }
}


text:
Dialog
******

.. highlight:: java

API
===

setCanceledOnTouchOutside
-------------------------

Sets whether this dialog is canceled when touched outside the window's bounds.
If setting to true, the dialog is set to be cancelable if not already set.

setCanceledOnTouchOutside_

.. _setCanceledOnTouchOutside: http://developer.android.com/reference/android/app/Dialog.html#setCanceledOnTouchOutside(boolean)