text:
using System.Collections.Generic;
using System.Linq;
using NBitcoin;
using Stratis.Bitcoin.Utilities;
using Stratis.Features.FederatedPeg.Interfaces;
using Stratis.Features.FederatedPeg.Models;

namespace Stratis.Features.FederatedPeg
{
    /// <summary>
    /// This class determines which federated member to select as the next leader based on a change in block height.
    /// </summary>
    public interface ILeaderProvider
    {
        /// <summary>Public key of the current leader.</summary>
        PubKey CurrentLeaderKey { get; }

        void Update(BlockTipModel blockTipModel);
    }

    /// <summary>
    /// This class determines which federated member to select as the next leader based on a change in block height.
    /// <para>
    /// Each federated member is selected in a round robin fashion.
    /// </para>
    /// <remarks>
    /// On construction the provider will order the federated members' public keys - which live in <see cref="IFederationGatewaySettings"/> - before it determines the next leader.
    /// </remarks>
    /// </summary>
    public class LeaderProvider : ILeaderProvider
    {
        /// <summary>
        /// Ordered list of federated members' public keys.
        /// </summary>
        private readonly IReadOnlyList<string> orderedFederationPublicKeys;

        public LeaderProvider(IFederationGatewaySettings federationGatewaySettings)
        {
            this.orderedFederationPublicKeys = federationGatewaySettings.FederationPublicKeys.
                Select(k => k.ToString()).
                OrderBy(j => j).
                ToList().
                AsReadOnly();

            this.CurrentLeaderKey = new PubKey(this.orderedFederationPublicKeys.First());
        }

        public PubKey CurrentLeaderKey { get; private set; }

        public void Update(BlockTipModel blockTipModel)
        {
            Guard.NotNull(blockTipModel, nameof(blockTipModel));

            this.CurrentLeaderKey = new PubKey(this.orderedFederationPublicKeys[blockTipModel.Height % this.orderedFederationPublicKeys.Count]);
        }
    }
}


text:
We welcome contributions from the community and are pleased to have them. Please follow this guide when logging issues or making code changes.

Make sure you have Ruby 2.0 installed. Copy and paste the following commands in your projects directory.

    git clone https://github.com/lob/lob-ruby.git
    cd lob-ruby
    bundle install

## Contributing Instructions

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Make sure the tests pass
6. Open up coverage/index.html in your browser and add tests if required
7. Create new Pull Request

redpajama_set_name: RedPajamaGithub


text:
      {{ site.title }}

        Articles
        About

      {% if site.show_social_icons %}
        {% include social_links.html %}
      {% endif %}


text:
static const unsigned int bytes_to_receive = 1<<20;
static unsigned char buf[8192];

static double time_diff(struct timespec &t_end, struct timespec &t_start) {
    double diff = t_end.tv_sec - t_start.tv_sec;
    diff += 1.e-9 * (t_end.tv_nsec - t_start.tv_nsec);
    return diff;
}

int main() {
    JTAGATLANTIC *atlantic = jtagatlantic_open(NULL, -1, -1, "counterperf");
    if(!atlantic) {
        show_err();
        return 1;
    }
    show_info(atlantic);

    struct timespec t_start, t_end;
    clock_gettime(CLOCK_MONOTONIC, &t_start);

    unsigned int bytes_received = 0;
    while(bytes_received < bytes_to_receive) {
        int ret = jtagatlantic_read(atlantic, (char*)buf, sizeof(buf));
        assert(ret >= 0);
        assert((unsigned int)ret <= sizeof(buf));
        if(ret == 0)
            usleep(100000);
        for(int i = 1; i < ret; i++)
            assert(buf[i] == ((buf[i-1] + 1) & 0xFF));
        bytes_received += ret;
    }

    clock_gettime(CLOCK_MONOTONIC, &t_end);

    double t_diff = time_diff(t_end, t_start);
    double datarate = 8. * bytes_received / t_diff;
    printf("time spent = %.3f s\n", t_diff);
    printf("received = %.3e bits\n", 8. * bytes_received);
    printf("data rate = %.3e bit/s\n", datarate);

    jtagatlantic_close(atlantic);
    return 0;
}


text:
import { factory } from '../../../utils/factory.js'
import { DimensionError } from '../../../error/DimensionError.js'

const name = 'algorithm07'
const dependencies = ['typed', 'DenseMatrix']

export const createAlgorithm07 = /* #__PURE__ */ factory(name, dependencies, ({ typed, DenseMatrix }) => {
  /**
   * Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij).
   * Callback function invoked MxN times.
   *
   * C(i,j) = f(Aij, Bij)
   *
   * @param {Matrix}   a                 The SparseMatrix instance (A)
   * @param {Matrix}   b                 The SparseMatrix instance (B)
   * @param {Function} callback          The f(Aij,Bij) operation to invoke
   *
   * @return {Matrix}                    DenseMatrix (C)
   *
   * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
   */
  return function algorithm07 (a, b, callback) {
    // sparse matrix arrays
    const asize = a._size
    const adt = a._datatype
    // sparse matrix arrays
    const bsize = b._size
    const bdt = b._datatype

    // validate dimensions
    if (asize.length !== bsize.length) { throw new DimensionError(asize.length, bsize.length) }

    // check rows & columns
    if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) { throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')') }

    // rows & columns
    const rows = asize[0]
    const columns = asize[1]

    // datatype
    let dt
    // zero value
    let zero = 0
    // callback signature to use
    let cf = callback

    // process data types
    if (typeof adt === 'string' && adt === bdt) {
      // datatype
      dt = adt
      // convert 0 to the same datatype
      zero = typed.convert(0, dt)
      // callback
      cf = typed.find(callback, [dt, dt])
    }

    // vars
    let i, j

    // result arrays
    const cdata = []
    // initialize c
    for (i = 0; i < rows; i++) { cdata[i] = [] }

    // workspaces
    const xa = []
    const xb = []
    // marks indicating we have a value in x for a given column
    const wa = []
    const wb = []

    // loop columns
    for (j = 0; j < columns; j++) {
      // columns mark
      const mark = j + 1
      // scatter the values of A(:,j) into workspace
      _scatter(a, j, wa, xa, mark)
      // scatter the values of B(:,j) into workspace
      _scatter(b, j, wb, xb, mark)
      // loop rows
      for (i = 0; i < rows; i++) {
        // matrix values @ i,j
        const va = wa[i] === mark ? xa[i] : zero
        const vb = wb[i] === mark ? xb[i] : zero
        // invoke callback
        cdata[i][j] = cf(va, vb)
      }
    }

    // return dense matrix
    return new DenseMatrix({
      data: cdata,
      size: [rows, columns],
      datatype: dt
    })
  }

  function _scatter (m, j, w, x, mark) {
    // a arrays
    const values = m._values
    const index = m._index
    const ptr = m._ptr
    // loop values in column j
    for (let k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) {
      // row
      const i = index[k]
      // update workspace
      w[i] = mark
      x[i] = values[k]
    }
  }
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2013 Evolveum
  ~
  ~ 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.
  -->

<!-- Connector broken by design. This is used to make sure that midPoint works well
     even if there is a broken connector in the repository. -->

<connector oid="cccccccc-76e0-59e2-ffff-ffffffffffff"
		  xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
          xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		  xsi:schemaLocation="http://midpoint.evolveum.com/xml/ns/public/common/common-3 ../../../../../../infra/schema/src/main/resources/xml/ns/public/common/common-3.xsd
							  http://www.w3.org/2001/XMLSchema ../../../../../../infra/schema/src/test/resources/standard/XMLSchema.xsd">

	<name>ICF Broken Connector</name>
	<framework>http://midpoint.evolveum.com/xml/ns/public/connector/icf-1</framework>
	<connectorType>this.connector.type.does.not.Exist</connectorType>
	<connectorVersion>1.1.0.0-e1</connectorVersion>
	<connectorBundle>non.existent.connector.bundle</connectorBundle>
	<namespace>http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/non.existent.connector.bundle</namespace>
	<schema>
		<!-- This is fake -->
	</schema>
</connector>


text:
<?php

namespace ChatLaraVue;

use Illuminate\Database\Eloquent\Collection;

class ChatRepository {

	public function getChats($you) {
		$users = User::all();
	    $filtered = $users->reject(function ($item) {
	        $user = auth()->user();
	        return $item->id == $user->id;
	    });
	    $users = $filtered->all();

	    $chats = new Collection();

	    foreach ($users as $user) {
	        $other = User::find($user->id);

	        $messages = $this->getMessages($you, $other);
	       	$this->setMessageYou($messages, $you);

	        $chat = new Chat();
	        $chat->messages = $messages;
	        $chat->id = $other->id;
	        $chats->add($chat);
	    }

	    return $chats;
	}

	public function getChat($you, $other) {
		$messages = $this->getMessages($you, $other);
	    $this->setMessageYou($messages, $you);

	    $chat = new Chat();
	    $chat->messages = $messages;
	    $chat->id = $other->id;

	    return $chat;
	}

	public function updateChat($you, $other) {
		$messages = $this->getMessages($you, $other);

		foreach($messages as $message) {
	        if ($message->receiver_id == $you->id) {
	            $message->read = true;
	            $message->save();
	        }
	    }
	}

	private function setMessageYou($messages, $you) {
		foreach($messages as $message) {
	        if ($message->sender_id == $you->id) {
	        	$message->you = true;
	        } else {
	        	$message->you = false;
	        }
	    }
	}

	private function getMessages($you, $other) {
		return Message::where('sender_id', $you->id)
                        ->where('receiver_id', $other->id)
                        ->orWhere('sender_id', $other->id)
                        ->where('receiver_id', $you->id)
                        ->get();
	}

}


text:
[instagram-private-api](../README.md) / sticker-builder

# Module: sticker-builder

## Table of contents

### Classes

- [AttachmentSticker](../classes/sticker_builder/AttachmentSticker.md)
- [ChatSticker](../classes/sticker_builder/ChatSticker.md)
- [CountdownSticker](../classes/sticker_builder/CountdownSticker.md)
- [HashtagSticker](../classes/sticker_builder/HashtagSticker.md)
- [InstaSticker](../classes/sticker_builder/InstaSticker.md)
- [LocationSticker](../classes/sticker_builder/LocationSticker.md)
- [MentionSticker](../classes/sticker_builder/MentionSticker.md)
- [PollSticker](../classes/sticker_builder/PollSticker.md)
- [QuestionSticker](../classes/sticker_builder/QuestionSticker.md)
- [QuizSticker](../classes/sticker_builder/QuizSticker.md)
- [SliderSticker](../classes/sticker_builder/SliderSticker.md)
- [StickerBuilder](../classes/sticker_builder/StickerBuilder.md)

### Interfaces

- [PollStickerTallie](../interfaces/sticker_builder/PollStickerTallie.md)

### Type aliases

- [StickerConfig](sticker_builder.md#stickerconfig)
- [StickerOptions](sticker_builder.md#stickeroptions)

## Type aliases

### StickerConfig

Ƭ **StickerConfig**: `any` & { `story_sticker_ids`: `string`  }

#### Defined in

[src/sticker-builder/sticker-builder.ts:20](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/sticker-builder/sticker-builder.ts#L20)

___

### StickerOptions

Ƭ **StickerOptions**<`T`\>: `Diff`<`T`, [`InstaSticker`](../classes/sticker_builder/InstaSticker.md)\> & `Partial`<[`InstaSticker`](../classes/sticker_builder/InstaSticker.md)\>

#### Type parameters

| Name | Type |
| :------ | :------ |
| `T` | extends [`InstaSticker`](../classes/sticker_builder/InstaSticker.md) |

#### Defined in

[src/sticker-builder/sticker-builder.ts:18](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/sticker-builder/sticker-builder.ts#L18)


text:
Google Classroom API . courses . topics

Instance Methods

  close()

Close httplib2 connections.

  create(courseId, body=None, x__xgafv=None)

Creates a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course, create a topic in the requested course, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist.

  delete(courseId, id, x__xgafv=None)

Deletes a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not allowed to delete the requested topic or for access errors. * `FAILED_PRECONDITION` if the requested topic has already been deleted. * `NOT_FOUND` if no course or topic exists with the requested ID.

  get(courseId, id, x__xgafv=None)

Returns a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or topic, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or topic does not exist.

  list(courseId, pageSize=None, pageToken=None, x__xgafv=None)

Returns the list of topics that the requester is permitted to view. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist.

  list_next()

Retrieves the next page of results.

  patch(courseId, id, body=None, updateMask=None, x__xgafv=None)

Updates one or more fields of a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting developer project did not create the corresponding topic or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or topic does not exist

Method Details

    close()

Close httplib2 connections.

    create(courseId, body=None, x__xgafv=None)

Creates a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course, create a topic in the requested course, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist.

Args:
  courseId: string, Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. (required)
  body: object, The request body.
    The object takes the form of:

{ # Topic created by a teacher for the course
  "courseId": "A String", # Identifier of the course. Read-only.
  "name": "A String", # The name of the topic, generated by the user. Leading and trailing whitespaces, if any, are trimmed. Also, multiple consecutive whitespaces are collapsed into one inside the name. The result must be a non-empty string. Topic names are case sensitive, and must be no longer than 100 characters.
  "topicId": "A String", # Unique identifier for the topic. Read-only.
  "updateTime": "A String", # The time the topic was last updated by the system. Read-only.
}

  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # Topic created by a teacher for the course
  "courseId": "A String", # Identifier of the course. Read-only.
  "name": "A String", # The name of the topic, generated by the user. Leading and trailing whitespaces, if any, are trimmed. Also, multiple consecutive whitespaces are collapsed into one inside the name. The result must be a non-empty string. Topic names are case sensitive, and must be no longer than 100 characters.
  "topicId": "A String", # Unique identifier for the topic. Read-only.
  "updateTime": "A String", # The time the topic was last updated by the system. Read-only.
}

    delete(courseId, id, x__xgafv=None)

Deletes a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not allowed to delete the requested topic or for access errors. * `FAILED_PRECONDITION` if the requested topic has already been deleted. * `NOT_FOUND` if no course or topic exists with the requested ID.

Args:
  courseId: string, Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. (required)
  id: string, Identifier of the topic to delete. (required)
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
}

    get(courseId, id, x__xgafv=None)

Returns a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or topic, or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or topic does not exist.

Args:
  courseId: string, Identifier of the course. (required)
  id: string, Identifier of the topic. (required)
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # Topic created by a teacher for the course
  "courseId": "A String", # Identifier of the course. Read-only.
  "name": "A String", # The name of the topic, generated by the user. Leading and trailing whitespaces, if any, are trimmed. Also, multiple consecutive whitespaces are collapsed into one inside the name. The result must be a non-empty string. Topic names are case sensitive, and must be no longer than 100 characters.
  "topicId": "A String", # Unique identifier for the topic. Read-only.
  "updateTime": "A String", # The time the topic was last updated by the system. Read-only.
}

    list(courseId, pageSize=None, pageToken=None, x__xgafv=None)

Returns the list of topics that the requester is permitted to view. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course does not exist.

Args:
  courseId: string, Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. (required)
  pageSize: integer, Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results.
  pageToken: string, nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token.
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # Response when listing topics.
  "nextPageToken": "A String", # Token identifying the next page of results to return. If empty, no further results are available.
  "topic": [ # Topic items that match the request.
    { # Topic created by a teacher for the course
      "courseId": "A String", # Identifier of the course. Read-only.
      "name": "A String", # The name of the topic, generated by the user. Leading and trailing whitespaces, if any, are trimmed. Also, multiple consecutive whitespaces are collapsed into one inside the name. The result must be a non-empty string. Topic names are case sensitive, and must be no longer than 100 characters.
      "topicId": "A String", # Unique identifier for the topic. Read-only.
      "updateTime": "A String", # The time the topic was last updated by the system. Read-only.
    },
  ],
}

    list_next()

Retrieves the next page of results.

        Args:
          previous_request: The request for the previous page. (required)
          previous_response: The response from the request for the previous page. (required)

        Returns:
          A request object that you can call 'execute()' on to request the next
          page. Returns None if there are no more items in the collection.

    patch(courseId, id, body=None, updateMask=None, x__xgafv=None)

Updates one or more fields of a topic. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting developer project did not create the corresponding topic or for access errors. * `INVALID_ARGUMENT` if the request is malformed. * `NOT_FOUND` if the requested course or topic does not exist

Args:
  courseId: string, Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. (required)
  id: string, Identifier of the topic. (required)
  body: object, The request body.
    The object takes the form of:

{ # Topic created by a teacher for the course
  "courseId": "A String", # Identifier of the course. Read-only.
  "name": "A String", # The name of the topic, generated by the user. Leading and trailing whitespaces, if any, are trimmed. Also, multiple consecutive whitespaces are collapsed into one inside the name. The result must be a non-empty string. Topic names are case sensitive, and must be no longer than 100 characters.
  "topicId": "A String", # Unique identifier for the topic. Read-only.
  "updateTime": "A String", # The time the topic was last updated by the system. Read-only.
}

  updateMask: string, Mask that identifies which fields on the topic to update. This field is required to do an update. The update fails if invalid fields are specified. If a field supports empty values, it can be cleared by specifying it in the update mask and not in the Topic object. If a field that does not support empty values is included in the update mask and not set in the Topic object, an `INVALID_ARGUMENT` error is returned. The following fields may be specified: * `name`
  x__xgafv: string, V1 error format.
    Allowed values
      1 - v1 error format
      2 - v2 error format

Returns:
  An object of the form:

    { # Topic created by a teacher for the course
  "courseId": "A String", # Identifier of the course. Read-only.
  "name": "A String", # The name of the topic, generated by the user. Leading and trailing whitespaces, if any, are trimmed. Also, multiple consecutive whitespaces are collapsed into one inside the name. The result must be a non-empty string. Topic names are case sensitive, and must be no longer than 100 characters.
  "topicId": "A String", # Unique identifier for the topic. Read-only.
  "updateTime": "A String", # The time the topic was last updated by the system. Read-only.
}


text:
extern "Java"
{
  namespace gnu
  {
    namespace java
    {
      namespace nio
      {
        namespace charset
        {
            class UTF_8$Decoder;
        }
      }
    }
  }
  namespace java
  {
    namespace nio
    {
        class ByteBuffer;
        class CharBuffer;
      namespace charset
      {
          class Charset;
          class CoderResult;
      }
    }
  }
}

class gnu::java::nio::charset::UTF_8$Decoder : public ::java::nio::charset::CharsetDecoder
{

public: // actually package-private
  UTF_8$Decoder(::java::nio::charset::Charset *);
public: // actually protected
  ::java::nio::charset::CoderResult * decodeLoop(::java::nio::ByteBuffer *, ::java::nio::CharBuffer *);
private:
  static jboolean isContinuation(jbyte);
public:
  static ::java::lang::Class class$;
};

#endif // __gnu_java_nio_charset_UTF_8$Decoder__


text:
package com.github.andrewoma.dexx.collection.internal.adapter;

import com.github.andrewoma.dexx.collection.Pair;
import com.github.andrewoma.dexx.collection.SortedMap;
import org.jetbrains.annotations.NotNull;

import java.util.Comparator;
import java.util.NoSuchElementException;

/**
 *
 */
public class SortedMapAdapter<K, V> extends MapAdapter<K, V> implements java.util.SortedMap<K, V> {
    private SortedMap<K, V> map;

    public SortedMapAdapter(SortedMap<K, V> map) {
        super(map);
        this.map = map;
    }

    @SuppressWarnings("NullableProblems") // JetBrains annotation doesn't match the spec
    @Override
    public Comparator<? super K> comparator() {
        return map.comparator();
    }

    @NotNull
    @Override
    public java.util.SortedMap<K, V> subMap(@NotNull K fromKey, @NotNull K toKey) {
        return new SortedMapAdapter<K, V>(map.range(fromKey, true, toKey, false));
    }

    @NotNull
    @Override
    public java.util.SortedMap<K, V> headMap(@NotNull K toKey) {
        return new SortedMapAdapter<K, V>(map.to(toKey, false));
    }

    @NotNull
    @Override
    public java.util.SortedMap<K, V> tailMap(@NotNull K fromKey) {
        return new SortedMapAdapter<K, V>(map.from(fromKey, true));
    }

    @Override
    public K firstKey() {
        Pair<K, V> first = map.first();
        if (first == null) throw new NoSuchElementException("Empty map");
        return first.component1();
    }

    @Override
    public K lastKey() {
        Pair<K, V> last = map.last();
        if (last == null) throw new NoSuchElementException("Empty map");
        return last.component1();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2017 Evolveum
  ~
  ~ 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.
  -->

<!--

This file is an example of Password Policy definition.

-->

<objects xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3">

	<valuePolicy oid="81818181-76e0-59e2-8888-3d4f02d3fffd" xsi:type="c:ValuePolicyType" version="0" xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<name>Alphanumeric Password Policy</name>
	<description>Alphanumeric Password policy requires at least one lowercase letter and at least one digit in the password, no special characters are allowed.</description>
	<lifetime>
		<expiration>999</expiration>
		<warnBeforeExpiration>9</warnBeforeExpiration>
		<lockAfterExpiration>0</lockAfterExpiration>
		<minPasswordAge>0</minPasswordAge>
		<passwordHistoryLength>0</passwordHistoryLength>
	</lifetime>
	<stringPolicy>
		<description>String validation policy</description>
		<limitations>
			<minLength>4</minLength>
			<maxLength>32</maxLength>
			<minUniqueChars>3</minUniqueChars>
			<!-- not implemented yet
			 <checkAgainstDictionary>true</checkAgainstDictionary>
			 -->
			<checkPattern />
			<limit>
				<description>Lowercase alphanumeric characters</description>
				<minOccurs>1</minOccurs>
				<mustBeFirst>false</mustBeFirst>
				<characterClass>
					<value>abcdefghijklmnopqrstuvwxyz</value>
				</characterClass>
			</limit>
			<limit>
				<description>Uppercase alphanumeric characters</description>
				<minOccurs>0</minOccurs>
				<mustBeFirst>false</mustBeFirst>
				<characterClass>
					<value>ABCDEFGHIJKLMNOPQRSTUVWXYZ</value>
				</characterClass>
			</limit>
			<limit>
				<description>Numeric characters</description>
				<minOccurs>1</minOccurs>
				<mustBeFirst>false</mustBeFirst>
				<characterClass>
					<value>1234567890</value>
				</characterClass>
			</limit>
		</limitations>
	</stringPolicy>
</valuePolicy>

</objects>


text:
package org.openehealth.ipf.platform.camel.ihe.fhir.core.custom;

import lombok.Getter;
import lombok.Setter;
import org.apache.camel.CamelContext;
import org.openehealth.ipf.commons.ihe.fhir.FhirInteractionId;
import org.openehealth.ipf.commons.ihe.fhir.FhirTransactionConfiguration;
import org.openehealth.ipf.commons.ihe.fhir.audit.FhirAuditDataset;
import org.openehealth.ipf.platform.camel.ihe.fhir.core.FhirComponent;
import org.openehealth.ipf.platform.camel.ihe.fhir.core.FhirEndpoint;
import org.openehealth.ipf.platform.camel.ihe.fhir.core.FhirEndpointConfiguration;

/**
 * @author Christian Ohr
 * @since 3.1
 */
public class CustomFhirComponent<AuditDatasetType extends FhirAuditDataset> extends FhirComponent<AuditDatasetType>
        implements FhirInteractionId<AuditDatasetType> {

    @Getter @Setter
    private String name;
    @Getter @Setter
    private String description;
    @Getter @Setter
    private boolean query;
    @Getter @Setter
    private FhirTransactionConfiguration<AuditDatasetType> fhirTransactionConfiguration;

    public CustomFhirComponent() {
        super(null);
        setFhirInteractionId(this);
    }

    public CustomFhirComponent(CamelContext context) {
        super(context, null);
        setFhirInteractionId(this);
    }

    public CustomFhirComponent(FhirTransactionConfiguration<AuditDatasetType> fhirTransactionConfiguration) {
        this();
        this.fhirTransactionConfiguration = fhirTransactionConfiguration;
    }

    @Override
    protected FhirEndpoint<?, ?> doCreateEndpoint(String uri, FhirEndpointConfiguration<AuditDatasetType> config) {
        return new CustomFhirEndpoint(uri, this, config);
    }

}


text:
CERTS_FOLDER=/etc/haproxy/certs.d
mkdir -p $CERTS_FOLDER

function sync_certs {
  aws s3 sync --delete s3://$S3_YODA_BUCKET/certs.d $CERTS_FOLDER
      #This is not perfect, but certs are typically not added that frequently
      if [ "$1" == "true" ] || [ "$(find $CERTS_FOLDER -type f -mmin -6  | wc -l)" -gt 0 ];  then
         echo "Change detected (force: $1). Reloading haproxy..."
         /usr/sbin/haproxy-reload.sh
      fi
}

if [ "$SYNC_CERTS" == "true" ]; then
  sync_certs true # Force sync for first run
  while [ 1 ]
  do
      #Make sure to update --mmin flag if the sleep time changes.
      sleep 300s
      sync_certs false
  done

else
  echo "Skipping SYNC_CERTS. In order to enable this feature set environment variable SYNC_CERTS to true"
  #Sleep forever
  sleep infinity
fi


text:
package com.dwarfartisan.parsec;

import java.io.EOFException;
import java.util.List;

/**
 * Created by Mars Liu on 2016-01-08.
 */
public class UInt extends Parsec<String, Character> {
    private Parsec<List<Character>, Character> parser = new Many1<Character, Character>(new Digit());
    @Override
    public String parse(State<Character> s) throws EOFException, ParsecException {
        List<Character> buffer = parser.parse(s);
        StringBuilder sb = new StringBuilder();
        for (Character ch : buffer){
            sb.append(ch);
        }
        return sb.toString();
    }
}


text:
/*	This file contains functions called from the main loop.
 *
 *	This file is from the DE2 demonstration project with a few exceptions.
 *	The code has been modified in the following ways:
 *		- Class requests for HID have been added (will be called from DeviceRequest_Handler function)
 *		- Removed some of the Vendor requests that are not handled
 *		- config_endpoints function modified to set endpoints and hardware to desired settings
 *		- Some function names changed to be more descriptive of function
 */

#include <stdio.h>
#include "BasicTyp.h"
#include "mainloop.h"
#include "usb.h"
#include "Hal4D13.h"
#include "chap_9.h"
#include "HID.h"
#include "usb_irq.h"

/* Global Variables */
extern D13FLAGS bD13flags;
extern CONTROL_XFER ControlData;

//*************************************************************************
// USB protocol function pointer arrays
//*************************************************************************

#define MAX_STANDARD_REQUEST    0x0D
code void (*StandardDeviceRequest[])(void) =
{
	Chap9_GetStatus,
	Chap9_ClearFeature,
	Chap9_StallEP0,
	Chap9_SetFeature,
	Chap9_StallEP0,
	Chap9_SetAddress,
	Chap9_GetDescriptor,
	Chap9_StallEP0,
	Chap9_GetConfiguration,
	Chap9_SetConfiguration,
	Chap9_GetInterface,
	Chap9_SetInterface,
	Chap9_StallEP0
};

code CHAR * _NAME_USB_REQUEST_DIRECTION[] =
		{ "Host_to_device", "Device_to_host" };

code CHAR * _NAME_USB_REQUEST_RECIPIENT[] = { "Device", "Interface",
		"Endpoint(0)", "Other" };

code CHAR * _NAME_USB_REQUEST_TYPE[] = { "Standard", "Class", "Vendor",
		"Reserved" };

code CHAR * _NAME_USB_STANDARD_REQUEST[] = { "GET_STATUS", "CLEAR_FEATURE",
		"RESERVED", "SET_FEATURE", "RESERVED", "SET_ADDRESS", "GET_DESCRIPTOR",
		"SET_DESCRIPTOR", "GET_CONFIGURATION", "SET_CONFIGURATION",
		"GET_INTERFACE", "SET_INTERFACE", "SYNC_FRAME" };

//*************************************************************************
// Class device requests
//*************************************************************************

#define MAX_CLASS_REQUEST    0x0B
code void (*ClassDeviceRequest[])(void) =
{
	ML_Reserved,
	HID_Get_Report,
	HID_Get_Idle,
	HID_Get_Protocol,
	ML_Reserved,
	ML_Reserved,
	ML_Reserved,
	ML_Reserved,
	ML_Reserved,
	HID_Set_Report,
	HID_Set_Idle,
	HID_Set_Protocol
};

code CHAR * _NAME_USB_CLASS_REQUEST[] = { "ML_Reserved", "Get_Report",
		"Get_Idle", "Get_Protocol", "ML_Reserved", "ML_Reserved", "ML_Reserved",
		"ML_Reserved", "ML_Reserved", "Set_Report", "Set_Idle", "Set_Protocol" };

//*************************************************************************
// Vendor Device Request
//*************************************************************************

#define MAX_VENDOR_REQUEST    0x00

code void (*VendorDeviceRequest[])(void) =
{
		ML_Reserved
};

code CHAR * _NAME_USB_VENDOR_REQUEST[] =
		{ "Iso mode enable", "Philips D13bus handler", "RESERVED", "RESERVED",
				"RESERVED", "RESERVED", "RESERVED", "RESERVED", "RESERVED",
				"RESERVED", "RESERVED", "RESERVED", "read Firmware version ",
				"RESERVED", "RESERVED", "RESERVED", };

void SetupToken_Handler(void) {
	unsigned short j;
	RaiseIRQL();
	bD13flags.bits.At_IRQL1 = 1;
	ControlData.Abort = FALSE;

	ControlData.wLength = 0;
	ControlData.wCount = 0;

	j = Hal4D13_ReadEndpointWOClearBuffer(EPINDEX4EP0_CONTROL_OUT, &ControlData.DeviceRequest, sizeof(ControlData.DeviceRequest));

	if (j == sizeof(DEVICE_REQUEST)) {
		/* //For debugging prints components of packet
		 printf("ControlData.DeviceRequest_size:%ld\n", sizeof(ControlData.DeviceRequest));
		 printf("ControlData.DeviceRequest.bmRequestType:0x%X\n",ControlData.DeviceRequest.bmRequestType);   //1BYTE
		 printf("ControlData.DeviceRequest.bRequest:0x%X\n",ControlData.DeviceRequest.bRequest);//1BYTE
		 printf("ControlData.DeviceRequest.wValue:0x%X\n",ControlData.DeviceRequest.wValue); //2BYTE
		 printf("ControlData.DeviceRequest.wIndex:0x%X\n",ControlData.DeviceRequest.wIndex); //2BYTE
		 printf("ControlData.DeviceRequest.wLength:0x%X\n",ControlData.DeviceRequest.wLength);//2BYTE
		 */
		bD13flags.bits.At_IRQL1 = 0;
		LowerIRQL();
		ControlData.wLength = ControlData.DeviceRequest.wLength;
		ControlData.wCount = 0;

		if (ControlData.DeviceRequest.bmRequestType
				& (UCHAR) USB_ENDPOINT_DIRECTION_MASK) {
			/* get command */
			RaiseIRQL();
			ML_AcknowledgeSETUP();
			if ((ControlData.DeviceRequest.bRequest == 0)
					& (ControlData.DeviceRequest.bmRequestType == 0xc0))
				bD13flags.bits.DCP_state = USBFSM4DCP_HANDSHAKE;
			else
				bD13flags.bits.DCP_state = USBFSM4DCP_REQUESTPROC;

			LowerIRQL();
		} else {
			/* set command */
			if (ControlData.DeviceRequest.wLength == 0) {
				/* Set command  without Data stage*/
				RaiseIRQL();
				ML_AcknowledgeSETUP();
				bD13flags.bits.DCP_state = USBFSM4DCP_REQUESTPROC;
				LowerIRQL();
			} else {
				/*
				 // Set command  with Data stage
				 // get Data Buffer
				 */
				if (ControlData.DeviceRequest.wLength <= MAX_CONTROLDATA_SIZE) {
					/* set command with OUT token */
					RaiseIRQL();
					bD13flags.bits.DCP_state = USBFSM4DCP_DATAOUT;
					LowerIRQL();
					ML_AcknowledgeSETUP();
				} else {
					RaiseIRQL();
					ML_AcknowledgeSETUP();
					Hal4D13_StallEP0InControlWrite();
					bD13flags.bits.DCP_state = USBFSM4DCP_STALL;
					printf(
							"bD13flags.bits.DCP_state = x%hx\n Unknow set up command\n",
							bD13flags.bits.DCP_state);
					LowerIRQL();
				}
			}
		}
	} else {
		printf("wrong setup command\n");
		bD13flags.bits.At_IRQL1 = 0;
		LowerIRQL();
		Chap9_StallEP0();
	}
}

void DeviceRequest_Handler(void) {
	UCHAR type, req;

	type = ControlData.DeviceRequest.bmRequestType & USB_REQUEST_TYPE_MASK;
	req = ControlData.DeviceRequest.bRequest & USB_REQUEST_MASK;

	if ((type == USB_STANDARD_REQUEST) && (req < MAX_STANDARD_REQUEST)) {
		(*StandardDeviceRequest[req])();
	} else if ((type == USB_CLASS_REQUEST) && (req < MAX_CLASS_REQUEST)) {
		(*ClassDeviceRequest[req])();
	} else if ((type == USB_VENDOR_REQUEST) && (req < MAX_VENDOR_REQUEST)) //Never used
		(*VendorDeviceRequest[req])();
	else {
		Chap9_StallEP0();
	}
}

void help_devreq(UCHAR type, UCHAR req) {
	UCHAR typ = type;
	typ >>= 5;

	if (type == USB_STANDARD_REQUEST) {
		printf("Request Type = %s, Request = %s.\n",
				_NAME_USB_REQUEST_TYPE[typ], _NAME_USB_STANDARD_REQUEST[req]);
	} else if (type == USB_CLASS_REQUEST) {
		printf("Request Type = %s, Request = %s.\n",
				_NAME_USB_REQUEST_TYPE[typ], _NAME_USB_CLASS_REQUEST[req]);
	} else {
		if (bD13flags.bits.verbose)
			printf("Request Type = %s, bRequest = 0x%x.\n",
					_NAME_USB_REQUEST_TYPE[typ], req);
	}
}

void disconnect_USB_controller(void) {
	printf("disconnect\n");
	Hal4D13_SetDevConfig(
			D13REG_DEVCNFG_NOLAZYCLOCK | D13REG_DEVCNFG_PWROFF
					| D13REG_DEVCNFG_CLOCKRUNNING);
	Hal4D13_SetMode(D13REG_MODE_INT_EN);
}

void connect_USB_controller(void) {
	RaiseIRQL(); //Disconnect irq
	printf("connect_USB\n");
	bD13flags.value = 0; /* reset event flags*/
	bD13flags.bits.DCP_state = USBFSM4DCP_IDLE;
	config_endpoints();

	LowerIRQL();

	Hal4D13_SetMode(D13REG_MODE_SOFTCONNECT
				| D13REG_MODE_DMA16
				//| D13REG_MODE_OFFGOODLNK
				//| D13REG_MODE_DBG
				| D13REG_MODE_INT_EN
				//| D13REG_MODE_SUSPND
	);
}

void config_endpoints(void) {
    /*Control Endpoint*/
	//printf("CONFIG\n");
    Hal4D13_SetEndpointConfig(D13REG_EPCNFG_FIFO_EN|D13REG_EPCNFG_NONISOSZ_64,EPINDEX4EP0_CONTROL_OUT);
    Hal4D13_SetEndpointConfig(D13REG_EPCNFG_FIFO_EN|D13REG_EPCNFG_IN_EN|D13REG_EPCNFG_NONISOSZ_64,EPINDEX4EP0_CONTROL_IN);

    // ENDP01 : HID Keyboard IN
    Hal4D13_SetEndpointConfig(D13REG_EPCNFG_FIFO_EN| ENDPOINT_DIR_IN | D13REG_EPCNFG_DBLBUF_EN | ENDPOINT_NOT_ISO | D13REG_EPCNFG_NONISOSZ_8, EPINDEX4EP01);

    /*DISABLED*/
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN| */ D13REG_EPCNFG_DBLBUF_EN| D13REG_EPCNFG_IN_EN|D13REG_EPCNFG_NONISOSZ_8,EPINDEX4EP02);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_NONISOSZ_64,EPINDEX4EP03);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_IN_EN|D13REG_EPCNFG_NONISOSZ_64,EPINDEX4EP04);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_512|D13REG_EPCNFG_ISO_EN,EPINDEX4EP05);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_512|D13REG_EPCNFG_ISO_EN|D13REG_EPCNFG_IN_EN,EPINDEX4EP06);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_16|D13REG_EPCNFG_ISO_EN,EPINDEX4EP07);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_IN_EN|D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_16|D13REG_EPCNFG_ISO_EN,EPINDEX4EP08);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_16|D13REG_EPCNFG_ISO_EN,EPINDEX4EP09);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_IN_EN|D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_16|D13REG_EPCNFG_ISO_EN,EPINDEX4EP0A);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_64|D13REG_EPCNFG_ISO_EN,EPINDEX4EP0B);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_IN_EN|D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_64|D13REG_EPCNFG_ISO_EN,EPINDEX4EP0C);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_64|D13REG_EPCNFG_ISO_EN,EPINDEX4EP0D);
    Hal4D13_SetEndpointConfig(/*D13REG_EPCNFG_FIFO_EN|*/D13REG_EPCNFG_IN_EN|D13REG_EPCNFG_DBLBUF_EN|D13REG_EPCNFG_ISOSZ_64|D13REG_EPCNFG_ISO_EN,EPINDEX4EP0E);
    /*DISABLED*/

    /*Set interrupt configuration*/
    Hal4D13_SetIntEnable(
    					 D13REG_INTSRC_EP0OUT
                        |D13REG_INTSRC_EP0IN
                        |D13REG_INTSRC_EP01
//                      |D13REG_INTSRC_EP02
//                      |D13REG_INTSRC_EP03
//               		|D13REG_INTSRC_EP04
//			            |D13REG_INTSRC_EP05
//			            |D13REG_INTSRC_EP06
                        |D13REG_INTSRC_SUSPEND
                        |D13REG_INTSRC_RESUME
                        |D13REG_INTSRC_BUSRESET
    );

    /*Set Hardware Configuration*/
    Hal4D13_SetDevConfig(D13REG_DEVCNFG_NOLAZYCLOCK
                        |D13REG_DEVCNFG_CLOCKDIV_120M
                        |D13REG_DEVCNFG_DMARQPOL
//            			|D13REG_DEVCNFG_EXPULLUP
);

}

void reconnect_USB_controller(void) {
	disconnect_USB_controller();
	connect_USB_controller();
}

void change_suspend_state(void) {
	printf("SUSPEND CHANGE \n");
}

void ML_AcknowledgeSETUP(void) {

	if (Hal4D13_IsSetupPktInvalid() || ControlData.Abort) {
		return;
	}

	Hal4D13_AcknowledgeSETUP();
	Hal4D13_ClearBuffer(EPINDEX4EP0_CONTROL_OUT);
}

void ML_Reserved(void) {
	Hal4D13_ClearBuffer(EPINDEX4EP0_CONTROL_OUT);
	printf("Reserved\n");
}

unsigned short CHECK_CHIP_ID(void) {
	unsigned short CHIP_ID;
	unsigned char LOW_ID, HIGH_ID;

	CHIP_ID = Hal4D13_ReadChipID();
	LOW_ID = (unsigned char) CHIP_ID;
	HIGH_ID = (unsigned char) (CHIP_ID >> 8);

	switch (HIGH_ID) {
	case 0x61: {

		printf("               CHIP ID =0x%04x\n\n", CHIP_ID);
		CHIP_ID = 0x1161;
		return CHIP_ID;
		break;
	}

	case 0x36: {
		printf("               CHIP ID =0x%04x\n\n", CHIP_ID);
		CHIP_ID = 0x1362;
		return CHIP_ID;
		break;
	}

	default: {
		printf("               UNKNOWN CHIP ID =0x%04x\n\n", CHIP_ID);
		return CHIP_ID;
		break;
	}

	}

}


text:
'use strict';

angular.module('giv2givApp')
  .controller('EndowmentDetailsCtrl', function ($scope, $routeParams, $location, endowment) {

  	$scope.url = $location.absUrl();

  	console.log($routeParams.id);

  	$scope.endowment = endowment.get({id: $routeParams.id});

  	$scope.debug = $scope.endowment;

  });


text:
require 'rails_helper'

RSpec.describe Adjustment do
  it_should_behave_like 'an adjustment'
end


text:
describe port(8070) do
  it { should be_listening }
end

describe command 'curl -X POST -H "Http-Remote-User: dmlb2001" -H "Content-Type: application/json" localhost:8070/eventmatch -d"{\"name\": \"MyMatch\", \"jsonpath\": \"$.data\", \"target_url\": \"http://api.example.com/recieve\"}"' do
  its(:stdout) { should include 'uuid' }
end


text:
'use strict';

module.exports = function (client) {

    client.disco.addFeature('http://jabber.org/protocol/geoloc');
    client.disco.addFeature('http://jabber.org/protocol/geoloc+notify');

    client.on('pubsub:event', function (msg) {
        if (!msg.event.updated) {
            return;
        }
        if (msg.event.updated.node !== 'http://jabber.org/protocol/geoloc') {
            return;
        }

        client.emit('geoloc', {
            jid: msg.from,
            geoloc: msg.event.updated.published[0].geoloc
        });
    });

    client.publishGeoLoc = function (data, cb) {
        return this.publish('', 'http://jabber.org/protocol/geoloc', {
            geoloc: data
        }, cb);
    };
};


text:
use driver::session::Session;
use metadata::csearch::each_lang_item;
use middle::ty;
use syntax::ast;
use syntax::ast_util::local_def;
use syntax::attr::AttrMetaMethods;
use syntax::parse::token::InternedString;
use syntax::visit::Visitor;
use syntax::visit;

use collections::HashMap;
use std::iter::Enumerate;
use std::slice;

// The actual lang items defined come at the end of this file in one handy table.
// So you probably just want to nip down to the end.
macro_rules! lets_do_this {
    (
        $( $variant:ident, $name:expr, $method:ident; )*
    ) => {

#[deriving(FromPrimitive)]
pub enum LangItem {
    $($variant),*
}

pub struct LanguageItems {
    items: Vec<Option<ast::DefId>> ,
}

impl LanguageItems {
    pub fn new() -> LanguageItems {
        fn foo(_: LangItem) -> Option<ast::DefId> { None }

        LanguageItems {
            items: vec!($(foo($variant)),*)
        }
    }

    pub fn items<'a>(&'a self) -> Enumerate<slice::Items<'a, Option<ast::DefId>>> {
        self.items.iter().enumerate()
    }

    pub fn item_name(index: uint) -> &'static str {
        let item: Option<LangItem> = FromPrimitive::from_uint(index);
        match item {
            $( Some($variant) => $name, )*
            None => "???"
        }
    }

    pub fn require(&self, it: LangItem) -> Result<ast::DefId, ~str> {
        match self.items.get(it as uint) {
            &Some(id) => Ok(id),
            &None => {
                Err(format!("requires `{}` lang_item",
                            LanguageItems::item_name(it as uint)))
            }
        }
    }

    pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
        if Some(id) == self.send_trait() {
            Some(ty::BoundSend)
        } else if Some(id) == self.sized_trait() {
            Some(ty::BoundSized)
        } else if Some(id) == self.copy_trait() {
            Some(ty::BoundCopy)
        } else if Some(id) == self.share_trait() {
            Some(ty::BoundShare)
        } else {
            None
        }
    }

    $(
        pub fn $method(&self) -> Option<ast::DefId> {
            *self.items.get($variant as uint)
        }
    )*
}

struct LanguageItemCollector<'a> {
    items: LanguageItems,

    session: &'a Session,

    item_refs: HashMap<&'static str, uint>,
}

impl<'a> Visitor<()> for LanguageItemCollector<'a> {
    fn visit_item(&mut self, item: &ast::Item, _: ()) {
        match extract(item.attrs.as_slice()) {
            Some(value) => {
                let item_index = self.item_refs.find_equiv(&value).map(|x| *x);

                match item_index {
                    Some(item_index) => {
                        self.collect_item(item_index, local_def(item.id))
                    }
                    None => {}
                }
            }
            None => {}
        }

        visit::walk_item(self, item, ());
    }
}

impl<'a> LanguageItemCollector<'a> {
    pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
        let mut item_refs = HashMap::new();

        $( item_refs.insert($name, $variant as uint); )*

        LanguageItemCollector {
            session: session,
            items: LanguageItems::new(),
            item_refs: item_refs
        }
    }

    pub fn collect_item(&mut self, item_index: uint, item_def_id: ast::DefId) {
        // Check for duplicates.
        match self.items.items.get(item_index) {
            &Some(original_def_id) if original_def_id != item_def_id => {
                self.session.err(format!("duplicate entry for `{}`",
                                      LanguageItems::item_name(item_index)));
            }
            &Some(_) | &None => {
                // OK.
            }
        }

        // Matched.
        *self.items.items.get_mut(item_index) = Some(item_def_id);
    }

    pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
        visit::walk_crate(self, krate, ());
    }

    pub fn collect_external_language_items(&mut self) {
        let crate_store = &self.session.cstore;
        crate_store.iter_crate_data(|crate_number, _crate_metadata| {
            each_lang_item(crate_store, crate_number, |node_id, item_index| {
                let def_id = ast::DefId { krate: crate_number, node: node_id };
                self.collect_item(item_index, def_id);
                true
            });
        })
    }

    pub fn collect(&mut self, krate: &ast::Crate) {
        self.collect_local_language_items(krate);
        self.collect_external_language_items();
    }
}

pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
    for attribute in attrs.iter() {
        match attribute.name_str_pair() {
            Some((ref key, ref value)) if key.equiv(&("lang")) => {
                return Some((*value).clone());
            }
            Some(..) | None => {}
        }
    }

    return None;
}

pub fn collect_language_items(krate: &ast::Crate,
                              session: &Session) -> @LanguageItems {
    let mut collector = LanguageItemCollector::new(session);
    collector.collect(krate);
    let LanguageItemCollector { items, .. } = collector;
    session.abort_if_errors();
    @items
}

// End of the macro
    }
}

lets_do_this! {
//  Variant name,                    Name,                      Method name;
    SendTraitLangItem,               "send",                    send_trait;
    SizedTraitLangItem,              "sized",                   sized_trait;
    CopyTraitLangItem,               "copy",                    copy_trait;
    ShareTraitLangItem,              "share",                   share_trait;

    DropTraitLangItem,               "drop",                    drop_trait;

    AddTraitLangItem,                "add",                     add_trait;
    SubTraitLangItem,                "sub",                     sub_trait;
    MulTraitLangItem,                "mul",                     mul_trait;
    DivTraitLangItem,                "div",                     div_trait;
    RemTraitLangItem,                "rem",                     rem_trait;
    NegTraitLangItem,                "neg",                     neg_trait;
    NotTraitLangItem,                "not",                     not_trait;
    BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
    BitAndTraitLangItem,             "bitand",                  bitand_trait;
    BitOrTraitLangItem,              "bitor",                   bitor_trait;
    ShlTraitLangItem,                "shl",                     shl_trait;
    ShrTraitLangItem,                "shr",                     shr_trait;
    IndexTraitLangItem,              "index",                   index_trait;

    UnsafeTypeLangItem,              "unsafe",                  unsafe_type;

    DerefTraitLangItem,              "deref",                   deref_trait;
    DerefMutTraitLangItem,           "deref_mut",               deref_mut_trait;

    EqTraitLangItem,                 "eq",                      eq_trait;
    OrdTraitLangItem,                "ord",                     ord_trait;

    StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
    UniqStrEqFnLangItem,             "uniq_str_eq",             uniq_str_eq_fn;
    FailFnLangItem,                  "fail_",                   fail_fn;
    FailBoundsCheckFnLangItem,       "fail_bounds_check",       fail_bounds_check_fn;
    ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
    ClosureExchangeMallocFnLangItem, "closure_exchange_malloc", closure_exchange_malloc_fn;
    ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
    MallocFnLangItem,                "malloc",                  malloc_fn;
    FreeFnLangItem,                  "free",                    free_fn;
    StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;

    StartFnLangItem,                 "start",                   start_fn;

    TyDescStructLangItem,            "ty_desc",                 ty_desc;
    TyVisitorTraitLangItem,          "ty_visitor",              ty_visitor;
    OpaqueStructLangItem,            "opaque",                  opaque;

    TypeIdLangItem,                  "type_id",                 type_id;

    EhPersonalityLangItem,           "eh_personality",          eh_personality_fn;

    ManagedHeapLangItem,             "managed_heap",            managed_heap;
    ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
    GcLangItem,                      "gc",                      gc;

    CovariantTypeItem,               "covariant_type",          covariant_type;
    ContravariantTypeItem,           "contravariant_type",      contravariant_type;
    InvariantTypeItem,               "invariant_type",          invariant_type;

    CovariantLifetimeItem,           "covariant_lifetime",      covariant_lifetime;
    ContravariantLifetimeItem,       "contravariant_lifetime",  contravariant_lifetime;
    InvariantLifetimeItem,           "invariant_lifetime",      invariant_lifetime;

    NoSendItem,                      "no_send_bound",           no_send_bound;
    NoCopyItem,                      "no_copy_bound",           no_copy_bound;
    NoShareItem,                     "no_share_bound",          no_share_bound;
    ManagedItem,                     "managed_bound",           managed_bound;
}


text:
<?php

namespace SVG\Nodes\Structures;

use SVG\Nodes\SVGNodeContainer;
use SVG\Rasterization\SVGRasterizer;

/**
 * Represents the SVG tag 'metadata'.
 */
class SVGMetadata extends SVGNodeContainer
{
    const TAG_NAME = 'metadata';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @inheritdoc
     */
    public function rasterize(SVGRasterizer $rasterizer)
    {
        // Nothing to rasterize.
    }
}


text:
package com.jfixby.scarabei.red.android.display;

import android.view.Display;
import android.view.Surface;

public class AndroidDisplay {
	public enum ROTATION {
		ROTATION_0, ROTATION_90, ROTATION_180, ROTATION_270

	}

	ROTATION rotation = null;
	private final Display shitDisplay;

	public AndroidDisplay (final Display shitDisplay) {
		this.shitDisplay = shitDisplay;
		final int oldVlue = this.shitDisplay.getRotation();
		if (Surface.ROTATION_0 == oldVlue) {
			this.rotation = ROTATION.ROTATION_0;
		}
		if (Surface.ROTATION_90 == oldVlue) {
			this.rotation = ROTATION.ROTATION_90;
		}
		if (Surface.ROTATION_180 == oldVlue) {
			this.rotation = ROTATION.ROTATION_180;
		}
		if (Surface.ROTATION_270 == oldVlue) {
			this.rotation = ROTATION.ROTATION_270;
		}
	}

	@Override
	public String toString () {
		return "Display [" + this.rotation + "]";
	}

	public ROTATION getRotation () {
		return this.rotation;
	}

}


text:
#region Copyright

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Wosad.General
{

    public partial class AxialForceTypeSelectionView: UserControl
    {
        public AxialForceTypeSelectionView()
        {
            InitializeComponent();
        }
    }
}


text:
Software License Agreement
==========================

**CKEditor 4 Export to PDF plugin** (https://ckeditor.com/ckeditor-4/)<br>
Copyright (c) 2003-2022, [CKSource](http://cksource.com) Holding sp. z o.o. All rights reserved.

CKEditor 4 Export to PDF plugin is licensed under a commercial license and is protected by copyright law.
For more details about available licensing options please contact us at sales@cksource.com.

Sources of Intellectual Property Included in CKEditor 4 export to PDF
---------------------------------------------------------------------

Where not otherwise indicated, all CKEditor 4 Export to PDF plugin content is authored by CKSource engineers and consists of CKSource-owned intellectual property.

Trademarks
----------

**CKEditor** is a trademark of [CKSource](http://cksource.com) Holding sp. z o.o. All other brand and product names are trademarks, registered trademarks or service marks of their respective holders.


text:
package com.github.richie.test_tool;

import java.util.Collection;

public class CompositeTestCase<TC extends TestCase> implements TestCase {
	private final Collection<TC> children;

	public CompositeTestCase(Collection<TC> children) {
		this.children = children;
	}

	@Override
	public void test() throws Exception {
		for (final TestCase tc : children) {
			tc.test();
		}
	}
}


text:
/**
 * Created by Alvaro on 24/09/2016.
 */

import {Component} from '@angular/core';
import * as fs from "fs";
import {remote} from 'electron';
import {
    DomSanitizationService,
    SafeUrl
} from '@angular/platform-browser';
import {Observable} from "rxjs";
import {FileSet} from "./files/FileSet";

let dialog = remote.dialog;

@Component({
    selector: 'app',
    templateUrl: 'app.component.html'
})

export class AppComponent {

    /**
     * The image currently been shown.
     */
    currentImg: Observable<SafeUrl>;

    /**
     * The fileset we're working on.
     * @type {FileSet}
     */
    fileSet: FileSet = new FileSet();

    /**
     * The name of the action to be applied to the current image.
     * @type {string}
     */
    currentImageAction: string = '';

    constructor(private sanitization: DomSanitizationService) {
        this.currentImg = Observable.of<SafeUrl>('assets/images/No_image_available.svg');
    }

    /**
     *
Shows a dialog for opening the directory to be processed.

     *
After a directory is selected, it will be analyzed and all images will be loaded to be organized.

     */
    openDir() {
        new Promise((resolve, reject) => {
            dialog.showOpenDialog({defaultPath: 'C:\\', properties: ['openDirectory']}, (fileNames) => {
                this.fileSet.dirPath = fileNames[0];
                fs.readdir(this.fileSet.dirPath, (e, f) => {
                    this.fileSet.loadFiles(e, f);

                    // end the promise
                    resolve();
                });
            })
        }).then(() => this.setSanitizedCurrentImage());
    }

    /**
     * Sets the currently shown image sanitazing its URL so Angular doesn't complain.
     */
    setSanitizedCurrentImage() {
        let currentPath = this.fileSet.getCurrentImagePath();
        this.currentImg = Observable.of(this.sanitization.bypassSecurityTrustUrl(currentPath));
    }

    /**
     *
Shows the next picture of the fileset (as long as it holds at least one image).

     *
If the last image was selected, no changes will be done.

     */
    nextImage() {
        this.fileSet.nextImage();
        this.setSanitizedCurrentImage();
        this.currentImageAction = this.fileSet.getCurrentImageAction();
    }

    /**
     *
Shows the previous picture of the fileset (as long as it holds at least one image).

     *
If the first image was selected, no changes will be done.

     */
    prevImage() {
        this.fileSet.prevImage();
        this.setSanitizedCurrentImage();
        this.currentImageAction = this.fileSet.getCurrentImageAction();
    }

    /**
     *
Marks the current image to be kept.

     */
    keepImage() {
        this.fileSet.keepImage();
        this.nextImage();
    }

    /**
     *
Marks the current image to be kept.

     */
    retouchImage() {
        this.fileSet.retouchImage();
        this.nextImage();
    }

    /**
     *
Marks the current image to be kept.

     */
    privateImage() {
        this.fileSet.privateImage();
        this.nextImage();
    }

    /**
     *
Marks the current image to be kept.

     */
    deleteImage() {
        this.fileSet.deleteImage();
        this.nextImage();
    }

    /**
     *
Executes all the images' actions.

     */
    organize() {
        this.fileSet.organize();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="co.edu.unab.mgads.atenea" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppThemeOrangeLight" >
        <activity
            android:name=".Splash"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login"
            android:label="@string/title_activity_login" >
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
        </activity>
        <activity
            android:name=".view.DetailNewsActivity"
            android:label="@string/title_activity_detail_news" >
        </activity>
    </application>

</manifest>


text:
import "core-js/stable";
import "regenerator-runtime/runtime";

export { default as Button } from './components/Button';
export { default as Input } from './components/Input';
export { default as Select } from './components/Select';


text:
import { User } from './user'

export interface UserAuth {
  username: string
  password: string
}

export interface AuthResponse {
  access_token: string
  expires_in: number
  iat: number
  iss: string
  jti: string
  token_type: string
}

export interface AuthData {
  token: string
  user: User
}


text:
namespace arc {

namespace {

// A class which handles the asynchronous ARC runtime callback to figure out if
// an app can handle a certain resolution or not.
// After LaunchAndRelease() got called, the object will destroy itself once
// done.
class LaunchAppWithoutSize {
 public:
  LaunchAppWithoutSize(content::BrowserContext* context,
                       const std::string& app_id,
                       bool landscape_mode) :
      context_(context), app_id_(app_id), landscape_mode_(landscape_mode) {}

  // This will launch the request and after the return the creator does not
  // need to delete the object anymore.
  bool LaunchAndRelease() {
    landscape_ = landscape_mode_ ?
        gfx::Rect(0, 0, NEXUS7_WIDTH, NEXUS7_HEIGHT) :
        gfx::Rect(0, 0, NEXUS5_WIDTH, NEXUS5_HEIGHT);
    if (!ash::Shell::HasInstance()) {
      // Skip this if there is no Ash shell.
      LaunchAppWithRect(context_, app_id_, landscape_);
      delete this;
      return true;
    }
    // TODO(skuhne): Change CanHandleResolution into a call which returns
    // capability flags like [PHONE/TABLET]_[LANDSCAPE/PORTRAIT] and which
    // might also return the used DP->PIX conversion constant to do better
    // size calculations.
    bool result = CanHandleResolution(context_, app_id_, landscape_,
        base::Bind(&LaunchAppWithoutSize::Callback, base::Unretained(this)));
    if (!result)
      delete this;
    return result;
  }

 private:
  // Default sizes to use.
  static const int NEXUS7_WIDTH = 960;
  static const int NEXUS7_HEIGHT = 600;
  static const int NEXUS5_WIDTH = 410;
  static const int NEXUS5_HEIGHT = 690;

  content::BrowserContext* context_;
  const std::string app_id_;
  const bool landscape_mode_;
  gfx::Rect landscape_;

  // The callback handler which gets called from the CanHandleResolution
  // function.
  void Callback(bool can_handle) {
    gfx::Size target_size = can_handle ? landscape_.size() :
        gfx::Size(NEXUS5_WIDTH, NEXUS5_HEIGHT);
    LaunchAppWithRect(context_, app_id_, getTargetRect(target_size));
    // Now that we are done, we can delete ourselves.
    delete this;
  }

  // Find a proper size and position for a given rectangle on the screen.
  // TODO(skuhne): This needs more consideration, but it is lacking
  // WindowPositioner functionality since we do not have an Aura::Window yet.
  gfx::Rect getTargetRect(const gfx::Size& size) {
    // Make sure that the window will fit into our workspace.
    // Note that Arc++ will always be on the primary screen (for now).
    // Note that Android's coordinate system is only valid inside the working
    // area. We can therefore ignore the provided left / top offsets.
    aura::Window* root = ash::Shell::GetPrimaryRootWindow();
    gfx::Rect work_area =
        display::Screen::GetScreen()->GetDisplayNearestWindow(root).work_area();

    gfx::Rect result(size);

    // We do not adjust sizes to fit the window into the work area here.
    // The reason is that the used DP<->pix transformation is different on
    // ChromeOS and ARC dependent on the device and zoom factor being used.
    // As such the real size cannot be determined here (yet). However - ARC
    // will adjust the bounds to not exceed the visible screen later.

   // ChromeOS does not give us much logic at this time, so we emulate what
    // WindowPositioner::GetDefaultWindowBounds does for now.
    // Note: Android's positioning will not overlap the shelf - as such we can
    // ignore the given workspace inset.
    // TODO(skuhne): Replace this with some more useful logic from the
    // WindowPositioner.
    result.set_x((work_area.width() - result.width()) / 2);
    result.set_y((work_area.height() - result.height()) / 2);
    return result;
  }

  DISALLOW_COPY_AND_ASSIGN(LaunchAppWithoutSize);
};

}  // namespace

const char kPlayStoreAppId[] = "gpkmicpkkebkmabiaedjognfppcchdfa";

bool LaunchAppWithRect(content::BrowserContext* context,
                       const std::string& app_id,
                       const gfx::Rect& target_rect) {
  ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context);
  CHECK(prefs);

  std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = prefs->GetApp(app_id);
  if (!app_info) {
    VLOG(2) << "Cannot launch unavailable app: " << app_id << ".";
    return false;
  }

  if (!app_info->ready) {
    VLOG(2) << "Cannot launch not-ready app: " << app_id << ".";
    return false;
  }

  arc::ArcBridgeService* bridge_service = arc::ArcBridgeService::Get();
  if (!bridge_service) {
    VLOG(2) << "Request to launch app when bridge service is not ready: "
            << app_id << ".";
    return false;
  }
  arc::mojom::AppInstance* app_instance = bridge_service->app_instance();
  if (!app_instance) {
    VLOG(2) << "Request to launch app when bridge service is not ready: "
            << app_id << ".";
    return false;
  }

  arc::mojom::ScreenRectPtr rect = arc::mojom::ScreenRect::New();
  rect->left = target_rect.x();
  rect->right = target_rect.right();
  rect->top = target_rect.y();
  rect->bottom = target_rect.bottom();

  app_instance->LaunchApp(app_info->package_name, app_info->activity,
                          std::move(rect));
  prefs->SetLastLaunchTime(app_id, base::Time::Now());

  return true;
}

bool LaunchApp(content::BrowserContext* context, const std::string& app_id) {
  return LaunchApp(context, app_id, true);
}

bool LaunchApp(content::BrowserContext* context,
               const std::string& app_id,
               bool landscape_layout) {
  return (new LaunchAppWithoutSize(context, app_id, landscape_layout))->
      LaunchAndRelease();
}

bool CanHandleResolution(content::BrowserContext* context,
    const std::string& app_id,
    const gfx::Rect& rect,
    const CanHandleResolutionCallback& callback) {
  ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context);
  std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = prefs->GetApp(app_id);
  if (!app_info) {
    VLOG(2) << "Cannot test resolution capability of unavailable app:" << app_id
            << ".";
    return false;
  }

  arc::ArcBridgeService* bridge_service = arc::ArcBridgeService::Get();
  arc::mojom::AppInstance* app_instance =
      bridge_service ? bridge_service->app_instance() : nullptr;
  if (!app_instance) {
    VLOG(2) << "Request to get resolution capability when bridge service is "
            << "not ready: " << app_id << ".";
    return false;
  }

  if (bridge_service->app_version() < 1) {
    VLOG(2)
        << "CanHandleResolution() not supported by ARC app instance version "
        << bridge_service->app_version();
    return false;
  }

  arc::mojom::ScreenRectPtr screen_rect = arc::mojom::ScreenRect::New();
  screen_rect->left = rect.x();
  screen_rect->right = rect.right();
  screen_rect->top = rect.y();
  screen_rect->bottom = rect.bottom();

  app_instance->CanHandleResolution(app_info->package_name, app_info->activity,
                                    std::move(screen_rect),
                                    callback);
  return true;
}

void UninstallPackage(const std::string& package_name) {
  VLOG(2) << "Uninstalling " << package_name;
  arc::ArcBridgeService* bridge_service = arc::ArcBridgeService::Get();
  if (!bridge_service) {
    VLOG(2) << "Request to uninstall package when bridge service is not ready: "
            << package_name << ".";
    return;
  }
  arc::mojom::AppInstance* app_instance = bridge_service->app_instance();
  if (!app_instance) {
    VLOG(2) << "Request to uninstall package when bridge service is not ready: "
            << package_name << ".";
    return;
  }

  if (bridge_service->app_version() < 2) {
    LOG(ERROR) << "Request to uninstall package when version "
               << bridge_service->app_version() << " does not support it";
    return;
  }
  app_instance->UninstallPackage(package_name);
}

}  // namespace arc


text:
typedef void (^VWWPermissionsManagerEmptyBlock)(void);

@interface VWWPermissionsManager ()
@property (nonatomic, strong) NSArray *permissions;
@property (nonatomic, strong) VWWPermissionsManagerResultsBlock resultsBlock;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) VWWPermissionsViewController *permissionsViewController;
@property (nonatomic) BOOL required;
@end

@implementation VWWPermissionsManager

#pragma mark Public methods

+(void)requirePermissions:(NSArray*)permissions
                    title:(NSString*)title
       fromViewController:(UIViewController*)viewController
             resultsBlock:(VWWPermissionsManagerResultsBlock)resultsBlock {
    VWWPermissionsManager *permissionsManager = [[self alloc]init];
    [permissionsManager displayPermissions:permissions
                                  required:YES title:title
                        fromViewController:viewController
                              resultsBlock:resultsBlock];
}

+(void)optionPermissions:(NSArray*)permissions
                   title:(NSString*)title
      fromViewController:(UIViewController*)viewController
            resultsBlock:(VWWPermissionsManagerResultsBlock)resultsBlock {
    VWWPermissionsManager *permissionsManager = [[self alloc]init];
    [permissionsManager displayPermissions:permissions required:NO title:title fromViewController:viewController resultsBlock:resultsBlock];
}

+(void)readPermissions:(NSArray*)permissions resultsBlock:(VWWPermissionsManagerResultsBlock)resultsBlock{
    VWWPermissionsManager *permissionsManager = [[self alloc]init];
    [permissionsManager readPermissions:permissions resultsBlock:resultsBlock];
}

#pragma mark Private methods

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserverForName:VWWPermissionNotificationsPromptAction object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
            dispatch_async(dispatch_get_main_queue(), ^{
                VWWPermission *permission = note.userInfo[VWWPermissionNotificationsPermissionKey];
                [permission presentSystemPromtWithCompletionBlock:^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [permission updatePermissionStatus];

                        if(permission.status == VWWPermissionStatusDenied){
                            [self.permissionsViewController displayDeniedAlertForPermission:permission];
                        }

                        [self checkAllPermissionsSatisfied];
                    });
                }];
            });
        }];

        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self readPermissions];
            });
        }];

    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(BOOL)checkAllPermissionsSatisfied{
    if(self.required){
        for(VWWPermission *permission in self.permissions) {
            if(permission.status != VWWPermissionStatusAuthorized){
                [self.permissionsViewController setCloseButtonTitle:nil];
                return NO;
            }
        }
        [self.permissionsViewController setCloseButtonTitle:@"Done"];
        return YES;

    } else {
        [self.permissionsViewController setCloseButtonTitle:@"Done"];
        for(VWWPermission *permission in self.permissions) {
            if(permission.status != VWWPermissionStatusAuthorized){
                return NO;
            }
        }
        return YES;
    }
}

-(void)readPermissions{
    [self.permissions enumerateObjectsUsingBlock:^(VWWPermission *permission, NSUInteger idx, BOOL *stop) {
        [permission updatePermissionStatus];
    }];
}

-(void)showPermissionsViewControllerFromViewController:(UIViewController*)viewController{
    NSBundle* resourcesBundle = [NSBundle bundleForClass:[VWWPermissionsManager class]];
    self.permissionsViewController = [[resourcesBundle loadNibNamed:VWWPermissionsViewControllerIdentifier owner:self options:nil] firstObject];
    self.permissionsViewController.permissions = self.permissions;
    self.permissionsViewController.titleText = self.title;
    __weak VWWPermissionsManager *welf = self;
    [self.permissionsViewController setCompletionBlock:^{
        if(welf.resultsBlock){
            welf.resultsBlock(welf.permissions);
        }
    }];
    UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:self.permissionsViewController];
    [viewController presentViewController:nc animated:YES completion:NULL];
}

-(void)displayPermissions:(NSArray*)permissions
                 required:(BOOL)required
                    title:(NSString*)title
       fromViewController:(UIViewController*)viewController
             resultsBlock:(VWWPermissionsManagerResultsBlock)resultsBlock{

    _permissions = [permissions copy];
    _required = required;
    _title = title;
    _resultsBlock = resultsBlock;

    [self readPermissions];
    if([self checkAllPermissionsSatisfied] == YES){
        // Return if all permissions are all authorized
        return resultsBlock(self.permissions);
    } else {
        [self showPermissionsViewControllerFromViewController:viewController];
        [self checkAllPermissionsSatisfied];
    }
}

-(void)readPermissions:(NSArray*)permissions resultsBlock:(VWWPermissionsManagerResultsBlock)resultsBlock{
    _permissions = permissions;
    [self readPermissions];
    resultsBlock(_permissions);
}

@end


text:
<?php

$lang["suppliers_account_number"] = "Btw nummer";
$lang["suppliers_basic_information"] = "Informatie Leverancier";
$lang["suppliers_cannot_be_deleted"] = "De geselecteeerde leveranciers konden niet worden verwijderd. Eén of meerdere leveranciers hebben ordergegevens in de database zitten.";
$lang["suppliers_company_name"] = "Bedrijfsnaam";
$lang["suppliers_company_name_required"] = "Bedrijfsnaam moet ingevuld worden";
$lang["suppliers_confirm_delete"] = "Bent u zeker dat u de geselecteerde leveranciers wil verwijderen?";
$lang["suppliers_error_adding_updating"] = "Fout bij het toevoegen/aanpassen van een leverancier";
$lang["suppliers_new"] = "N. Leverancier";
$lang["suppliers_none_selected"] = "U hebt geen leveranciers geselecteerd";
$lang["suppliers_one_or_multiple"] = "leverancier(s) verwijderd";
$lang["suppliers_successful_adding"] = "Leverancier succesvol toegevoegd";
$lang["suppliers_successful_deleted"] = "Er werd(en)";
$lang["suppliers_successful_updating"] = "Wijzigingen leveranciersgegevens bewaard";
$lang["suppliers_supplier"] = "Leverancier";
$lang["suppliers_update"] = "Bewerk Leverancier";


text:
<?php
/*
Section: phpmyadmin
Language: Serbian
*/

$translations = array(
    'h1' => 'phpMyAdmin',
);
?>


text:
package org.apache.sling.launchpad.webapp.integrationtest.servlets.resolution;

import java.util.Collections;

import org.apache.commons.httpclient.NameValuePair;

/**
 * Test that a servlet registered at a particular path is still executed when a
 * node at that path also exists.
 */
public class PathsServletWithNodeTest extends ResolutionTestBase {

    private final static String NODE_SERVLET_URL = HTTP_BASE_URL + "/testing/PathsServletNodeServlet";

    private final static String TEST_URL = HTTP_BASE_URL + "/testing/PathsServlet/foo";

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        assertPostStatus(NODE_SERVLET_URL, 201, Collections.singletonList(new NameValuePair("action", "create")),
                "Unable to create node at " + TEST_PATH);
    }

    public void testGetCorrectPath() throws Exception {
        assertServlet(getContent(TEST_URL, CONTENT_TYPE_PLAIN), PATHS_SERVLET_SUFFIX);
    }

    @Override
    protected void tearDown() throws Exception {
        assertPostStatus(NODE_SERVLET_URL, 204, Collections.singletonList(new NameValuePair("action", "delete")),
                "Unable to delete node at " + TEST_PATH);
        super.tearDown();
    }

}


text:
__author__ = 'Ruslan Spivak <ruslan.spivak@gmail.com>'

import time

from cynic.handlers.base import BaseHandler

SLEEP_TIME = 24 * 60 * 60 # sleep for 24 hours

class NoResponse(BaseHandler):
    """Doesn't send any response at all.

    Sleeps for SLEEP_TIME (default is 24 hours) and exits
    """

    LOGGER_NAME = __name__

    def handle(self):
        self.logger.info(
            'Sleeping for the next 24 hours. No response will be sent.')
        time.sleep(SLEEP_TIME)


text:
#if !defined(_WAV_FILE_H_)
#define _WAV_FILE_H_

#include "file_system.h"

//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------

//! @brief Macro to build a four-char code in little-endian format.
#define FOUR_CHAR_CODE(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))

namespace slab {

/*!
 * @brief Decodes a .wav file.
 */
class WaveFile : public fs::File
{
public:
    enum wave_error : uint32_t
    {
        kParseError = 100,
    };

    //! @brief Stream of a wav file's audio data.
    //!
    //! This class is really just a simple wrapper to make calculations of the audio
    //! data size and file offset easier.
    class AudioDataStream : public Stream
    {
    public:
        AudioDataStream() : Stream(), _file(nullptr) {}
        AudioDataStream(WaveFile * wave) : Stream(), _file(wave) {}
        AudioDataStream(const AudioDataStream& other)=default;
        AudioDataStream& operator = (const AudioDataStream& other)=default;

        virtual error_t read(uint32_t count, void * data, uint32_t * actualCount) override;
        virtual error_t write(uint32_t count, const void * data, uint32_t * actualCount) override { return fs::kGenericError; }
        virtual error_t seek(uint32_t offset) override;

        virtual uint32_t get_size() const override;
        virtual uint32_t get_offset() const override;

        uint32_t get_frames() const;

    protected:
        WaveFile * _file;
    };

    WaveFile();
    WaveFile(const char * path);
    virtual ~WaveFile() {}

    WaveFile& operator = (const WaveFile& other);

    bool is_valid() const { return _dataSize > 0; }

    //! @brief Parse file to read format and find data.
    error_t parse();

    AudioDataStream get_audio_data() { return AudioDataStream(this); }

    uint32_t get_sample_rate() const { return _format.dwSamplesPerSec; }
    uint32_t get_sample_size() const { return _format.wBitsPerSample; }
    uint32_t get_channels() const { return _format.wChannels; }
    uint32_t get_frame_size() const { return _format.wBlockAlign; }

protected:
    friend class AudioDataStream;

    //! @brief Four-char codes used in WAV files.
    enum ChunkIDs : uint32_t
    {
        kRIFFGroupID = FOUR_CHAR_CODE('R', 'I', 'F', 'F'),
        kWaveFormatID = FOUR_CHAR_CODE('W', 'A', 'V', 'E'),
        kFormatChunkID = FOUR_CHAR_CODE('f', 'm', 't', ' '),
        kDataChunkID = FOUR_CHAR_CODE('d', 'a', 't', 'a'),
    };

    //! @brief Header for every chunk.
    struct ChunkHeader {
        uint32_t chunkID;
        int32_t chunkSize;
    };

    //! @brief Wave file header.
    struct RIFFFileHeader {
        uint32_t groupID;
        uint32_t fileSize;
        uint32_t formatID;
    };

    //! @brief Values for wFormatTag in the format chunk.
    enum : int16_t
    {
        kUncompressedWaveFormat = 1,
    };

    //! @brief Structure for the 'fmt ' chunk.
    //!
    //! The actual structure in the file is prefixed with the ChunkHeader. The header is missing
    //! from this struct definition because it is read separately while searching for the format
    //! chunk.
    //!
    //! Additional fields may follow those defined here, depending upon wFormatTag. The actual size
    //! of the chunk is specified in the chunk header.
    struct FormatChunk {
        // ChunkHeader header;
        int16_t wFormatTag;
        uint16_t wChannels;
        uint32_t dwSamplesPerSec;
        uint32_t dwAvgBytesPerSec;
        uint16_t wBlockAlign;
        uint16_t wBitsPerSample;
    };

    FormatChunk _format;    //!< The file's audio format header.
    uint32_t _dataOffset;   //!< Byte offset of the start of the audio data.
    uint32_t _dataSize;     //!< Byte count of the audio data chunk.

    //! @brief Search for a chunk from the current position.
    bool find_chunk(uint32_t chunkID, ChunkHeader * header);
};

} // namespace slab

#endif // _WAV_FILE_H_
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web.Configuration;
/// <summary>
/// This class is connecting the application to the database,
/// mainly used in the business logic classes.
/// </summary>
public static class Connect
{
    public static int QueriesCount;
    /// <summary>
    ///  Return's Result For The SQL Query(DataTable Object)
    /// </summary>
    public static DataTable GetData(string SqlQuery, string TableName)
    {
        OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["eduDB_Connection"].ConnectionString);
        OleDbCommand command = new OleDbCommand(SqlQuery, con);
        con.Open();
        OleDbDataAdapter adp = new OleDbDataAdapter(command);
        DataSet ds = new DataSet();

        adp.Fill(ds, TableName);
        con.Close();
        QueriesCount++;
        return ds.Tables[0];
    }
    /// <summary>
    ///  Return's Result For The SQL Query(DataSet Object)
    /// </summary>
    public static DataSet GetData(string SqlQuery, string TableName, bool WantFullDataSet)
    {
        OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["eduDB_Connection"].ConnectionString);
        OleDbCommand command = new OleDbCommand(SqlQuery, con);
        OleDbDataAdapter adp = new OleDbDataAdapter(command);
        DataSet ds = new DataSet();
        adp.Fill(ds, TableName);
        QueriesCount++;
        return ds;
    }
    /// <summary>
    /// Return's Object Result (It's Mainly For Mathmatical Use)
    /// </summary>
    public static object GetObject(string SqlQuery)
    {
        try
        {
            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["eduDB_Connection"].ConnectionString);
            OleDbCommand command = new OleDbCommand(SqlQuery, con);
            con.Open();
            object MyObj = command.ExecuteScalar();
            con.Close();
            QueriesCount++;
            return MyObj;
        }
        catch(Exception ex)
        {
            //Problem.Log(ex);
            return null;
        }
    }
    /// <summary>
    /// Executes The SqlQuery And Return's Boolean For Success Of The Query Execution
    /// </summary>
    public static bool InsertUpdateDelete(string SqlQuery)
    {
        try
        {
            OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["eduDB_Connection"].ConnectionString);
            OleDbCommand command = new OleDbCommand(SqlQuery, con);
            con.Open();
            command.ExecuteNonQuery();
            con.Close();
            QueriesCount++;
            return true;
        }
        catch (Exception ex)
        {
            //Problem.Log(ex);
        }
        return false;
    }
}


text:
function varargout=savejd(varargin)
%
%    savejd(rootname, obj, outputfile)
%       or
%    buffer=savejd(obj)
%    buffer=savejd(rootname, obj)
%    savejd(rootname, obj, opt)
%    savejd(rootname, obj, 'filename', outputfile, 'Param1',value1, 'Param2',value2,...)
%
%    Save a complex MATLAB/Octave data structure to a hierarchical
%    container data file including JSON, binary JSON
%    (BJData/UBJSON/MessagePack) and HDF5
%
%    author: Qianqian Fang (q.fang <at> neu.edu)
%
%    input:
%        rootname: the name of the root-object, when set to '', the root name
%           is ignored, however, when opt.ForceRootName is set to 1 (see help savejson),
%           the MATLAB variable name will be used as the root name.
%        obj: a MATLAB object (array, cell, cell array, struct, struct array,
%             class instance).
%        outputfile: the output file name to the hierarchical container file
%                *.json,.jnii,.jdt,.jmsh,.jnirs: JSON/JData based data files, see https://neurojson.org/jdata/draft2
%                *.bjd,.bnii,.jdb,.bmsh,.bnirs: binary JData (BJData) files, see https://neurojson.org/bjdata/draft2
%                *.ubj: UBJSON-encoded files, see http://ubjson.org
%                *.msgpack: MessagePack-encoded files, see http://msgpack.org
%                *.h5,.hdf5,.snirf: HDF5 files, see https://www.hdfgroup.org/
%        opt: (optional) for JSON/JData files, these are optional 'param',value pairs
%                supported by loadjson.m; for BJData/UBJSON/MessagePack files, these are
%                options supported by loadbj.m; for HDF5 files, these are options
%                supported by loadh5.m (part of EasyH5 toolbox, http://github.com/NeuroJSON/easyh5/)
%
%    output:
%        data: a structure (array) or cell (array) storing the hierarchical data
%              in the container data file
%        mmap: optional output storing the JSON/binary JSON memory-map table for fast
%              disk access. see help info for loadjson or loadbj for more details.
%
%    examples:
%        obj=struct('string','value','array',[1 2 3]);
%        savejd('obj', obj, 'datafile.json')
%        newobj=loadjd('datafile.json');
%
%    license:
%        BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%

if(nargin<1)
    error('you must provide file name');
end

opt=struct;

if(nargin>2)
    if(nargin==3 && ischar(varargin{3}))
        filename=varargin{3};
    else
        opt=varargin2struct(varargin{3:end});
        filename=jsonopt('filename','.json',opt);
    end
end
if(~exist('filename','var'))
    filename='.json';
end
if(regexpi(filename,'\.json$|\.jnii$\.jdt$\.jdat$|\.jmsh$|\.jnirs$'))
    [varargout{1:nargout}]=savejson(varargin{:});
elseif(regexpi(filename,'\.bjd$|\.bnii$\.jdb$\.jbat$|\.bmsh$|\.bnirs$'))
    [varargout{1:nargout}]=savebj(varargin{:});
elseif(regexpi(filename,'\.ubj$'))
    [varargout{1:nargout}]=saveubjson(varargin{:});
elseif(regexpi(filename,'\.msgpack$'))
    [varargout{1:nargout}]=savemsgpack(varargin{:});
elseif(regexpi(filename,'\.h5$|\.hdf5$|\.snirf$'))
    if(~exist('saveh5','file'))
        error('you must first install EasyH5 from http://github.com/NeuroJSON/easyh5/');
    end
    if(~isfield(opt,'rootname'))
        if(nargin>=3 && ischar(varargin{1}))
            opt.rootname=varargin{1};
        else
            opt.rootname=inputname(2);
        end
    end
    [varargout{1:nargout}]=saveh5(varargin{2},filename, opt);
else
    error('file suffix must be one of .json,.jnii,.jdt,.jmsh,.jnirs,.bjd,.bnii,.jdb,.bmsh,.bnirs,.ubj,.msgpack,.h5,.hdf5,.snirf');
end


text:
import re

from setuptools import find_packages, setup

# get metadata from mudule using a regexp
with open('rdmo/__init__.py') as f:
    metadata = dict(re.findall(r'__(.*)__ = [\']([^\']*)[\']', f.read()))

# get install_requires from requirements.txt
with open('requirements.txt') as f:
    install_requires = f.readlines()

setup(
    name=metadata['title'],
    version=metadata['version'],
    author=metadata['author'],
    author_email=metadata['email'],
    maintainer=metadata['author'],
    maintainer_email=metadata['email'],
    license=metadata['license'],
    url='https://github.com/rdmorganiser/rdmo',
    description=u'RDMO is a tool to support the systematic planning, organisation and implementation of the data management throughout the course of a research project.',
    long_description=open('README.md').read(),
    long_description_content_type='text/markdown',
    install_requires=install_requires,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Framework :: Django :: 2.2',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3.5'
    ],
    packages=find_packages(),
    include_package_data=True
)


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	PostProcessHistogramReduce.h: Post processing histogram reduce implementation.
=============================================================================*/

#pragma once

#include "RenderingCompositionGraph.h"
#include "PostProcessHistogram.h"

// derives from TRenderingCompositePassBase<InputCount, OutputCount>
class FRCPassPostProcessHistogramReduce : public TRenderingCompositePassBase<1, 1>
{
public:
	// interface FRenderingCompositePass ---------
	virtual void Process(FRenderingCompositePassContext& Context) override;
	virtual void Release() override { delete this; }
	virtual FPooledRenderTargetDesc ComputeOutputDesc(EPassOutputId InPassOutputId) const override;

	static const uint32 ThreadGroupSizeX = FRCPassPostProcessHistogram::HistogramTexelCount;
	static const uint32 ThreadGroupSizeY = 4;

private:

	static uint32 ComputeLoopSize(FIntPoint PixelExtent);
};


text:
package com.github.kennycyb.uifactory.ext.factory;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.kennycyb.uifactory.core.components.IComponent;
import com.github.kennycyb.uifactory.core.factory.ComponentContext;
import com.github.kennycyb.uifactory.core.factory.IAnnotationHandler;
import com.github.kennycyb.uifactory.core.factory.IComponentFactory;
import com.github.kennycyb.uifactory.core.factory.IUiFactory;
import com.github.kennycyb.uifactory.core.factory.impl.components.awt.ComponentFactory;

public class JxComponentFactory implements IComponentFactory {

	private static Logger LOGGER = LoggerFactory.getLogger(ComponentFactory.class);

	private final List<IAnnotationHandler<?>> mAnnotationHandlers = new ArrayList<>();

	protected void addAnnotationHandler(final IAnnotationHandler<?> handler) {
		mAnnotationHandlers.add(handler);
	}

	@Override
	public void createInstance(final IUiFactory factory, final ComponentContext context) throws Exception {
		Object instance = null;

		if (context.getParentContext() != null && context.getType().getDeclaringClass() != null && !Modifier.isStatic(context.getType().getModifiers())) {

			final Class<?> innerClass = context.getType();
			final Class<?> outerClass = context.getParentContext().getType();

			final Constructor<?> innerClassConstructor = innerClass.getDeclaredConstructor(outerClass);

			innerClassConstructor.setAccessible(true);

			instance = innerClassConstructor.newInstance(context.getParentContext().getComponent());
		} else {

			LOGGER.debug("{}|creating from {}", context.getId(), context.getType());

			instance = context.getType().newInstance();
		}

		context.setJxComponent(IComponent.class.cast(instance));

	}

	@Override
	public void initialize(final ComponentContext context) {
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--<color name="colorPrimary">#3F51B5</color>-->
    <!--<color name="colorPrimaryDark">#303F9F</color>-->
    <!--<color name="colorAccent">#FF4081</color>-->

    <color name="primary">@android:color/black</color>
    <color name="primary_dark">@color/grey_600</color>
    <color name="accent">@color/green_600</color>
</resources>


text:
#ifndef DATMANAGER_H
#define DATMANAGER_H

#include <framework/global.h>
#include <framework/core/declarations.h>
#include "thingtype.h"

//@bindsingleton g_thingsType
class ThingsType
{
public:

    enum Categories {
        Item = 0,
        Creature,
        Effect,
        Missile,
        LastCategory
    };

    bool load(const std::string& file);
    void unload();

    bool parseThingType(const FileStreamPtr& fin, ThingType& thingType);

    ThingType *getEmptyThingType() { return &m_emptyThingType; }
    ThingType *getThingType(uint16 id, Categories category);

    uint32 getSignature() { return m_signature; }
    bool isLoaded() { return m_loaded; }

    uint16 getFirstItemId() { return 100; }
    uint16 getMaxItemid() { return m_things[Item].size() + 99; }
    bool isValidItemId(int id) { return id >= getFirstItemId() && id <= getMaxItemid(); }

private:
    uint32 m_signature;
    stdext::boolean<false> m_loaded;
    ThingTypeList m_things[LastCategory];
    static ThingType m_emptyThingType;
};

extern ThingsType g_thingsType;

#endif