text:
import cv2
import numpy as np
import opensfm.transformations as tf
from opensfm import align
from opensfm import types

def points_errors(reference, candidate):
    common_points = set(reference.points.keys()).intersection(
        set(candidate.points.keys())
    )

    return np.array(
        [
            reference.points[p].coordinates - candidate.points[p].coordinates
            for p in common_points
        ]
    )

def completeness_errors(reference, candidate):
    return (
        float(len(candidate.shots)) / float(len(reference.shots)),
        float(len(candidate.points)) / float(len(reference.points)),
    )

def gps_errors(candidate):
    errors = []
    for shot in candidate.shots.values():
        pose1 = shot.metadata.gps_position.value
        pose2 = shot.pose.get_origin()
        errors.append(pose1 - pose2)
    return np.array(errors)

def position_errors(reference, candidate):
    common_shots = set(reference.shots.keys()).intersection(set(candidate.shots.keys()))
    errors = []
    for s in common_shots:
        pose1 = reference.shots[s].pose.get_origin()
        pose2 = candidate.shots[s].pose.get_origin()
        errors.append(pose1 - pose2)
    return np.array(errors)

def rotation_errors(reference, candidate):
    common_shots = set(reference.shots.keys()).intersection(set(candidate.shots.keys()))
    errors = []
    for s in common_shots:
        pose1 = reference.shots[s].pose.get_rotation_matrix()
        pose2 = candidate.shots[s].pose.get_rotation_matrix()
        difference = np.transpose(pose1).dot(pose2)
        rodrigues = cv2.Rodrigues(difference)[0].ravel()
        angle = np.linalg.norm(rodrigues)
        errors.append(angle)
    return np.array(errors)

def find_alignment(points0, points1):
    """Compute similarity transform between point sets.

    Returns (s, A, b) such that ``points1 = s * A * points0 + b``
    """
    v0, v1 = [], []
    for p0, p1 in zip(points0, points1):
        if p0 is not None and p1 is not None:
            v0.append(p0)
            v1.append(p1)
    v0 = np.array(v0).T
    v1 = np.array(v1).T
    M = tf.affine_matrix_from_points(v0, v1, shear=False)
    s = np.linalg.det(M[:3, :3]) ** (1.0 / 3.0)
    A = M[:3, :3] / s
    b = M[:3, 3]
    return s, A, b

def aligned_to_reference(reference, reconstruction):
    """Align a reconstruction to a reference."""
    coords1, coords2 = [], []
    for point1 in reconstruction.points.values():
        point2 = reference.points.get(point1.id)
        if point2 is not None:
            coords1.append(point1.coordinates)
            coords2.append(point2.coordinates)

    if len(coords1) == 0 or len(coords2) == 0:
        for shot1 in reconstruction.shots.values():
            shot2 = reference.shots.get(shot1.id)
            if shot2 is not None:
                coords1.append(shot1.pose.get_origin())
                coords2.append(shot2.pose.get_origin())

    s, A, b = find_alignment(coords1, coords2)
    aligned = _copy_reconstruction(reconstruction)
    align.apply_similarity(aligned, s, A, b)
    return aligned

def _copy_reconstruction(reconstruction):
    copy = types.Reconstruction()
    for camera in reconstruction.cameras.values():
        copy.add_camera(camera)
    for shot in reconstruction.shots.values():
        copy.add_shot(shot)
    for point in reconstruction.points.values():
        copy.add_point(point)
    return copy

def rmse(errors):
    return np.sqrt(np.mean(errors ** 2))


text:
`1.0.29`
--------

- **Fix:** error in Discuss menu on first usage

`1.0.28`
--------

**Fix:** debrand_bytes now accepts bytes and str types
**Fix:** fixed "OdooBot has a request" item in notifications
**Fix:** included mail_channel fixes

`1.0.27`
--------

**Fix:** error on res.config form opening

`1.0.26`
--------

- FIX: developer mode was availabile via dropdown menu for non-admins

`1.0.25`
--------

- FIX: error in Planner

`1.0.24`
--------

- FIX: Save\Create button didn't react in ``Point of Sale`` records

`1.0.23`
--------

- FIX: Debranding problems after introducing new features

`1.0.22`
--------

- FIX: method create didn't work via xmlrpc (e.g. on using Mail Composer)

`1.0.21`
--------

- FIX: In some cases, default parameters were used instead of custom ones

`1.0.20`
--------

- FIX: Hiding a custom logo
- FIX: Error when creating second empty database
- FIX: Remove official videos in planner
- FIX: Replace "Odoo" in 'install aplication' mails
- FIX: Remove Enterprise radio-buttons in Settings

`1.0.19`
--------

- FIX: Page title was empty even when it doesn't contain references to odoo

`1.0.18`
--------

- FIX: Replace icons for android and apple devices with custom url

`1.0.17`
--------

- FIX: Do not reset config values to default ones after upgrade or reinstall the module

`1.0.16`
--------

- FIX: Removed odoo.com link from left bottom of the page

`1.0.15`
--------

- FIX: Updating Title didn't work on *Optimize SEO* website tool

`1.0.14`
--------

- FIX: Compatibility with Timesheet Grid View module

`1.0.13`
--------

- IMP: Add "Developer mode" link to the top right-hand User Menu

`1.0.12`
--------

- FIX: Forbid to disable odoo.com binding for enterprise due to terms of Odoo Enterprise Subscription Agreement

`1.0.11`
--------

- FIX desktop notifications: replace odoo icon company log and debrand text

`1.0.10`
--------

- FIX: Reconsile button didn't work
- FIX: Updated title was not set

`1.0.9`
-------

- FIX: don't hide whole section in Settings if it not all fields are enterprise

`1.0.8`
-------

- IMP: 11. Disables server requests to odoo.com (publisher_warranty_url) - optional

`1.0.7`
-------

- FIX: bug with fields on User form in Odoo Enterprise

`1.0.6`
-------

- FIX: bug with replacing the word "odoo" in JS functions
- FIX: replace title and favicon in Odoo Enterprise

`1.0.5`
-------

- ADD: Replaces "Odoo" in all backend qweb templates (e.g. FAQ in import tool)

`1.0.4`
-------

- ADD: hide Enterprise features in Settings

`1.0.3`
-------

- ADD: support Enterprise release
- ADD: 16. Deletes "Odoo" in a request message for permission desktop notifications
- ADD: 17. [ENTERPRISE] Deletes odoo logo in application switcher

`1.0.2`
-------

- ADD: debrand Planner
- FIX: updates for recent odoo 9.0

`1.0.1`
-------

- FIX: updates for recent odoo 9.0
- REF: compatible with other Dashboard modules

`1.0.0`
-------

- init version

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tony\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity (repositoryClass="Tony\MainBundle\Entity\Repository\CompanyRepository")
 * @ORM\Table(name="company")
 * @ORM\HasLifecycleCallbacks
 */

class Company
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $name;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="string", length=20)
     */
    protected $image;

    /**
     * @ORM\Column(type="string")
     */
    protected $url;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updated;

    /**
     * @ORM\Column(name="user_social_link_token", type="string", length=36)
     */
    protected $userSocialLinkToken;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Company
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Company
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Company
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set url
     *
     * @param string $url
     * @return Company
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

    /**
     * Get url
     *
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     * @return Company
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param \DateTime $updated
     * @return Company
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

    /**
     * Get updated
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Set userSocialLinkToken
     *
     * @param string $userSocialLinkToken
     * @return Company
     */
    public function setUserSocialLinkToken($userSocialLinkToken)
    {
        $this->userSocialLinkToken = $userSocialLinkToken;

        return $this;
    }

    /**
     * Get userSocialLinkToken
     *
     * @return string
     */
    public function getUserSocialLinkToken()
    {
        return $this->userSocialLinkToken;
    }
}


text:
;(function (_) {
    var _list_system = {};
    /**
     * List manager
     * @module LIST
     * @memberOf MaDnh
     * @type {{}}
     */
    _.M.LIST = _.M.defineObject({

        /**
         * Trigger on list is changed
         * @param {string} type
         */
        triggerListSystemChange: function (type) {
            if (!_.isUndefined(type)) {
                _.M.EVENT.trigger('madnh_list_' + type + '_change');
            }
            _.M.EVENT.trigger('madnh_list_change');
        },

        /**
         * Add list type
         * @param {string} type
         */
        addType: function (type) {
            _list_system[type] = {};

            _.M.EVENT.trigger('madnh_list_add_type', type);
            this.triggerListSystemChange();
        },

        /**
         * Get list types as array
         * @return {string[]}
         */
        types: function () {
            return _.keys(_list_system);
        },

        /**
         * Check if a list type is exists
         * @param {string} type
         */
        hasType: function (type) {
            return _.has(_list_system, type);
        },

        /**
         * Remove list type
         * @param {string} type
         * @returns {boolean}
         */
        removeType: function (type) {
            if (this.hasType(type)) {
                delete _list_system[type];

                _.M.EVENT.trigger('madnh_list_remove_type', type);
                this.triggerListSystemChange();
                return true;
            }
            return false;
        },

        /**
         * Reset type by remove all it's items
         * @param {string} type
         * @returns {boolean}
         */
        resetType: function (type) {
            if (this.hasType(type)) {
                _list_system[type] = {};
                _.M.EVENT.trigger('madnh_list_reset_type', type);
                this.triggerListSystemChange(type);
                return true;
            }
            return false;
        },

        /**
         * Get detail of list type
         * @param {string} type
         * @returns {boolean}
         */
        getType: function (type) {
            if (this.hasType(type)) {
                return _.clone(_list_system[type]);
            }
            return false;
        },

        /**
         * Check if a list type is empty
         * @param {string} type
         * @returns {boolean}
         */
        isEmptyType: function (type) {
            if (!_.isUndefined(type)) {
                if (this.hasType(type)) {
                    return _.isEmpty(this.getType(type));
                }
                return true;
            }
            return _.isEmpty(_list_system);
        },

        /**
         * Get items name of a list
         * @param {string} type
         * @returns {(string[] | boolean)} Array of items name or False when list type not found
         */
        items: function (type) {
            if (this.hasType(type)) {
                return _.keys(_list_system[type]);
            }
            return false;
        },

        /**
         * Check if list type has item
         * @param {string} type
         * @param {string} item_name
         * @returns {boolean}
         */
        hasItem: function (type, item_name) {
            return this.hasType(type) && _.has(_list_system[type], item_name);
        },

        /**
         * Add item
         * @param {string} type Item's type
         * @param {string} name Item's name
         * @param {*} data
         * @param {boolean} [override=true] Override existed item
         * @returns {boolean}
         */
        addItem: function (type, name, data, override) {
            if (_.isUndefined(override)) {
                override = true;
            }
            if (!this.hasType(type)) {
                this.addType(type);
            }
            if (!(_.isString(name) || _.M.isNumeric(name)) || (name + '').length == 0) {
                name = _.M.nextID('madnh_list_item', true);
            }
            if (override || !this.hasItem(type, name)) {
                _list_system[type][name] = data;

                _.M.EVENT.trigger('madnh_list_' + type + '_add', {
                    name: name,
                    data: data
                });
                this.triggerListSystemChange(type);
                return true;
            }
            return false;
        },
        /**
         * Get data of item
         * @param {string} type List type
         * @param {string} name Item's name
         * @returns {*}
         */
        getItem: function (type, name) {
            if (this.hasItem(type, name)) {
                return _.clone(_list_system[type][name]);
            }
            return undefined;
        },

        /**
         * Remove item from list
         * @param {string} type List type
         * @param {(string|function|Array)} name Item's name
         * @returns {boolean}
         */
        removeKeys: function (type, name) {
            var result = false;
            if (this.hasType(type)) {
                name = _.castArray(name);
                var old = _.clone(_list_system[type]), removed;

                _list_system[type] = _.omit(_list_system[type], name);
                removed = _.pick(old, _.difference(_.keys(old), _.keys(_list_system[type])));
                if (!_.isEmpty(removed)) {
                    _.M.EVENT.trigger('madnh_list_remove_item', removed);
                    this.triggerListSystemChange(type);
                    result = true;
                }
            }

            return result;
        },

        /**
         * Toggle exists status of item
         * @param {string} type
         * @param {string} item
         * @param {*} data
         * @param {boolean} [status = undefined] Exists status of item. If undefined or null will all/remove base on
         *     exists status of item. If true will add item if item is non exists. If false will remove item
         */
        toggleItem: function (type, item, data, status) {
            if (_.isUndefined(status) || _.isNull(status)) {
                if (this.hasItem(type, item)) {
                    this.removeKeys(type, item);
                } else {
                    this.addItem(type, item, data, false);
                }
            } else {
                if (status) {
                    this.addItem(type, item, data, false);
                } else {
                    this.removeKeys(type, item);
                }
            }
        },

        /**
         * Remove item type base on it's data
         * @param {string} type
         * @param {*} data
         * @returns {(*|boolean)}
         */
        removeByData: function (type, data) {
            return this.removeKeys(type, function (item_data) {
                return item_data === data;
            });
        },

        /**
         * Check if item is exists in type
         * @param {string} type
         * @param {string} item
         * @param {*} [data] If special then check by data, instead of item name
         * @returns {boolean}
         */
        isInType: function (type, item, data) {
            if (this.hasType(type) && !_.isUndefined(item)) {
                if (!_.isNull(item)) {
                    return _.has(_list_system[type], item);
                }
                return _.contains(_list_system[type], data);
            }
            return false;
        },

        /**
         * Find item in type
         * @param {string} type
         * @param {function} callback
         * @param {*} not_found_value
         * @returns {*}
         */
        findInType: function (type, callback, not_found_value) {
            if (this.hasType(type)) {
                return _.find(_list_system[type], callback);
            }
            return not_found_value;
        },

        /**
         * Filter items in type
         * @param {string} type
         * @param {function} callback
         * @returns {Array}
         */
        filterInType: function (type, callback) {
            if (this.hasType(type)) {
                return _.filter(_list_system[type], callback);
            }
            return [];
        },
        /**
         *
         * @param type
         * @param properties
         * @returns {Array}
         */
        whereInType: function (type, properties) {
            if (this.hasType(type)) {
                return _.where(_list_system[type], properties);
            }
            return [];
        },

        /**
         *
         * @param type
         * @param properties
         * @returns {Array}
         */
        findWhereInType: function (type, properties) {
            if (this.hasType(type)) {
                return _.findWhere(_list_system[type], properties);
            }
            return [];
        }
    });

})(_);


text:
/* PR c++/37647 */
/* { dg-do compile } */

struct A
{
  A() { void A(); } /* { dg-error "return type specification for constructor invalid|non-class scope" } */
};


text:
package org.elasticsearch.index.mapper;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.lucene.all.AllEntries;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.mapper.object.RootObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class ParseContext {

    private final DocumentMapper docMapper;

    private final DocumentMapperParser docMapperParser;

    private final ContentPath path;

    private XContentParser parser;

    private Document document;

    private List<Document> documents = new ArrayList<Document>();

    private Analyzer analyzer;

    private final String index;

    @Nullable
    private final Settings indexSettings;

    private SourceToParse sourceToParse;
    private BytesReference source;

    private String id;

    private DocumentMapper.ParseListener listener;

    private String uid;

    private StringBuilder stringBuilder = new StringBuilder();

    private Map<String, String> ignoredValues = new HashMap<String, String>();

    private boolean mappingsModified = false;

    private boolean externalValueSet;

    private Object externalValue;

    private AllEntries allEntries = new AllEntries();

    private float docBoost = 1.0f;

    public ParseContext(String index, @Nullable Settings indexSettings, DocumentMapperParser docMapperParser, DocumentMapper docMapper, ContentPath path) {
        this.index = index;
        this.indexSettings = indexSettings;
        this.docMapper = docMapper;
        this.docMapperParser = docMapperParser;
        this.path = path;
    }

    public void reset(XContentParser parser, Document document, SourceToParse source, DocumentMapper.ParseListener listener) {
        this.parser = parser;
        this.document = document;
        if (document != null) {
            this.documents = new ArrayList<Document>();
            this.documents.add(document);
        } else {
            this.documents = null;
        }
        this.analyzer = null;
        this.uid = null;
        this.id = null;
        this.sourceToParse = source;
        this.source = source == null ? null : sourceToParse.source();
        this.path.reset();
        this.mappingsModified = false;
        this.listener = listener == null ? DocumentMapper.ParseListener.EMPTY : listener;
        this.allEntries = new AllEntries();
        this.ignoredValues.clear();
        this.docBoost = 1.0f;
    }

    public boolean flyweight() {
        return sourceToParse.flyweight();
    }

    public DocumentMapperParser docMapperParser() {
        return this.docMapperParser;
    }

    public boolean mappingsModified() {
        return this.mappingsModified;
    }

    public void setMappingsModified() {
        this.mappingsModified = true;
    }

    public String index() {
        return this.index;
    }

    @Nullable
    public Settings indexSettings() {
        return this.indexSettings;
    }

    public String type() {
        return sourceToParse.type();
    }

    public SourceToParse sourceToParse() {
        return this.sourceToParse;
    }

    public BytesReference source() {
        return source;
    }

    // only should be used by SourceFieldMapper to update with a compressed source
    public void source(BytesReference source) {
        this.source = source;
    }

    public ContentPath path() {
        return this.path;
    }

    public XContentParser parser() {
        return this.parser;
    }

    public DocumentMapper.ParseListener listener() {
        return this.listener;
    }

    public Document rootDoc() {
        return documents.get(0);
    }

    public List<Document> docs() {
        return this.documents;
    }

    public Document doc() {
        return this.document;
    }

    public void addDoc(Document doc) {
        this.documents.add(doc);
    }

    public Document switchDoc(Document doc) {
        Document prev = this.document;
        this.document = doc;
        return prev;
    }

    public RootObjectMapper root() {
        return docMapper.root();
    }

    public DocumentMapper docMapper() {
        return this.docMapper;
    }

    public AnalysisService analysisService() {
        return docMapperParser.analysisService;
    }

    public String id() {
        return id;
    }

    public void ignoredValue(String indexName, String value) {
        ignoredValues.put(indexName, value);
    }

    public String ignoredValue(String indexName) {
        return ignoredValues.get(indexName);
    }

    /**
     * Really, just the id mapper should set this.
     */
    public void id(String id) {
        this.id = id;
    }

    public String uid() {
        return this.uid;
    }

    /**
     * Really, just the uid mapper should set this.
     */
    public void uid(String uid) {
        this.uid = uid;
    }

    public boolean includeInAll(Boolean includeInAll, FieldMapper mapper) {
        return includeInAll(includeInAll, mapper.indexed());
    }

    /**
     * Is all included or not. Will always disable it if {@link org.elasticsearch.index.mapper.internal.AllFieldMapper#enabled()}
     * is <tt>false</tt>. If its enabled, then will return <tt>true</tt> only if the specific flag is <tt>null</tt> or
     * its actual value (so, if not set, defaults to "true") and the field is indexed.
     */
    private boolean includeInAll(Boolean specificIncludeInAll, boolean indexed) {
        if (!docMapper.allFieldMapper().enabled()) {
            return false;
        }
        // not explicitly set
        if (specificIncludeInAll == null) {
            return indexed;
        }
        return specificIncludeInAll;
    }

    public AllEntries allEntries() {
        return this.allEntries;
    }

    public Analyzer analyzer() {
        return this.analyzer;
    }

    public void analyzer(Analyzer analyzer) {
        this.analyzer = analyzer;
    }

    public void externalValue(Object externalValue) {
        this.externalValueSet = true;
        this.externalValue = externalValue;
    }

    public boolean externalValueSet() {
        return this.externalValueSet;
    }

    public Object externalValue() {
        externalValueSet = false;
        return externalValue;
    }

    public float docBoost() {
        return this.docBoost;
    }

    public void docBoost(float docBoost) {
        this.docBoost = docBoost;
    }

    /**
     * A string builder that can be used to construct complex names for example.
     * Its better to reuse the.
     */
    public StringBuilder stringBuilder() {
        stringBuilder.setLength(0);
        return this.stringBuilder;
    }
}


text:
<!DOCTYPE html>

  <title="Machine Learning Learning Useful Links List"></title>
        <meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="Styles/story/assets/css/main.css" />

About this project

List of Machine learning terms/keywords and useful links


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="7dp"
    android:clickable="true"
    android:foreground="?attr/selectableItemBackground"
    app:cardCornerRadius="3dp"
    app:cardElevation="1dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/editable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_margin="5dp"
            android:padding="5dp"
            android:background="@drawable/capsule_grey"
            android:textSize="9sp"
            android:text="@string/editable"
            android:visibility="gone"
            tools:visibility="visible"
            tools:ignore="SmallSp" />

        <LinearLayout
            android:id="@+id/info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="10dp">

            <ImageView
                android:id="@+id/avatar"
                android:layout_width="45dp"
                android:layout_height="45dp"
                app:srcCompat="@drawable/ic_avatar"
                android:contentDescription="@null" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginStart="5dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="2dp"
                    tools:text="Name"
                    android:textColor="@android:color/black" />

                <TextView
                    android:id="@+id/position"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="2dp"
                    tools:text="Designation"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/contactPanel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/info"
            android:gravity="center"
            android:background="#eeeeee"
            android:orientation="horizontal" />

        <TextView
            android:id="@+id/showProfile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/contactPanel"
            android:padding="16dp"
            android:background="@color/tw__composer_light_gray"
            android:foreground="?selectableItemBackground"
            android:text="@string/show_profile"
            android:visibility="gone"
            tools:visibility="visible" />
    </RelativeLayout>

</android.support.v7.widget.CardView>


text:
namespace tracing {

// static
void TracedProcess::ResetTracedProcessReceiver() {
#if !defined(OS_NACL) && !defined(OS_IOS)
  tracing::TracedProcessImpl::GetInstance()->ResetTracedProcessReceiver();
#endif
}

// static
void TracedProcess::OnTracedProcessRequest(
    mojo::PendingReceiver<mojom::TracedProcess> receiver) {
#if !defined(OS_NACL) && !defined(OS_IOS)
  tracing::TracedProcessImpl::GetInstance()->OnTracedProcessRequest(
      std::move(receiver));
#endif
}

}  // namespace tracing


text:
import React, {Component} from 'react';
import {Provider} from 'react-redux';
import {store} from './store';
import {DEBUG, RDEBUG} from './Constants';
import RootPage from './RootPage'
import SplashScreen from './SplashScreen';
global.LOG = (msg) => {
    if (DEBUG) console.log(msg);
}

global.RLOG = (msg) => {
    if (DEBUG && RDEBUG) console.log(msg);
}
class App extends Component {
    constructor(props) {
        super(props);

        this._unmount = false;
        this.state = {
            isShowSplash: true,
        }
    }

    componentWillUnmount() {
        this._unmount = true;
    }

    render() {
        if (this.state.isShowSplash) {
            return <SplashScreen onAnimEnd={() => !this._unmount && this.setState({isShowSplash: false})}/>
        } else {
            return (
                <Provider store={store}>
                    <RootPage />
                </Provider>
            )
        }
    }
}

export default App;


text:
Tungus
======

[![Build Status](https://travis-ci.org/sergeyksv/tungus.png?branch=master)](https://travis-ci.org/sergeyksv/tungus)
[![Deps Status](https://david-dm.org/sergeyksv/tungus.png)](https://david-dm.org/sergeyksv/tungus)
[![Dev deps Status](https://david-dm.org/sergeyksv/tungus/dev-status.png)](https://david-dm.org/sergeyksv/tungus)

This module implements mongoose.js driver API and allows to use mongoose with [TingoDB](http://www.tingodb.com).

TingoDB is embedded Node.js database that is compatible with MongoDB on API level.

So far this module is on its early stage with only basic functionality.

To use this module you have to install both tungus and mongoose.

	npm install tungus
	npm install mongoose

Then in your code you should include once tungus module prior to include of mongoose.
This rewrites global.MONGOOSE_DRIVER_PATH variable to point it to tungus.

	require('tungus')
	require('mongoose')

Next to that you can keep using mongoose as usual except now it will accept different connection string:

	mongoose.connect('tingodb:///some/local/folder')

Optionally you can set tingodb options using ```TUNGUS_DB_OPTIONS``` global variable. For example this way it is possible to switch to BSON.ObjectID ids which is default for mongodb.

```
global.TUNGUS_DB_OPTIONS =  { nativeObjectID: true, searchInArray: true };
```

Full example:

	var tungus = require('tungus');
	var mongoose = require('mongoose')
	var Schema = mongoose.Schema;

	console.log('Running mongoose version %s', mongoose.version);

	/**
	 * Console schema
	 */

	var consoleSchema = Schema({
		name: String
	  , manufacturer: String
	  , released: Date
	})
	var Console = mongoose.model('Console', consoleSchema);

	/**
	 * Game schema
	 */

	var gameSchema = Schema({
		name: String
	  , developer: String
	  , released: Date
	  , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }]
	})
	var Game = mongoose.model('Game', gameSchema);

	/**
	 * Connect to the local tingo db file
	 */

	mongoose.connect('tingodb://'+__dirname+'/data', function (err) {
	  // if we failed to connect, abort
	  if (err) throw err;

	  // we connected ok
	  createData();
	})

	/**
	 * Data generation
	 */

	function createData () {
	  Console.create({
		  name: 'Nintendo 64'
		, manufacturer: 'Nintendo'
		, released: 'September 29, 1996'
	  }, function (err, nintendo64) {
		if (err) return done(err);

		Game.create({
			name: 'Legend of Zelda: Ocarina of Time'
		  , developer: 'Nintendo'
		  , released: new Date('November 21, 1998')
		  , consoles: [nintendo64]
		}, function (err) {
		  if (err) return done(err);
		  example();
		})
	  })
	}

	/**
	 * Population
	 */

	function example () {
	  Game
	  .findOne({ name: /^Legend of Zelda/ })
	  .populate('consoles')
	  .exec(function (err, ocinara) {
		if (err) return done(err);
		console.log(ocinara);

		console.log(
			'"%s" was released for the %s on %s'
		  , ocinara.name
		  , ocinara.consoles[0].name
		  , ocinara.released.toLocaleDateString());

		done();
	  })
	}

	function done (err) {
	  if (err) console.error(err);
	  Console.remove(function () {
		Game.remove(function () {
		  mongoose.disconnect();
		})
	  })
	}

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/sergeyksv/tungus/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
[![githalytics.com alpha](https://cruel-carlota.pagodabox.com/b6cbaf6c8ba3c422361664a9df97ec80 "githalytics.com")](http://githalytics.com/sergeyksv/tungus)


text:
package com.mobimvp.privacybox.ui;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;

public class BaseActivity extends Activity {
	private ActionBar actionBar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		actionBar=getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowHomeEnabled(false);
	}

	public ActionBar getPrivacyActionBar(){
		 return actionBar;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Smaps HTML Table</title>
    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
    <link href="bootstrap-sortable.css" rel="stylesheet">

Proc text parser

        <form role="form" id="parserChoice">

        </form>

        <form role="form">
          <textarea class="form-control" rows="6" id="smapsText" style="width:100%;"></textarea>
        </form>
        <button type="submit" id="parseBtn" class="btn btn-primary">Parse Text</button>


text:
package com.google.javascript.jscomp;

import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.StaticTypedRef;
import com.google.javascript.rhino.jstype.StaticTypedSlot;

/**
 * {@link AbstractVar} subclass for use with {@link TypedScope}.
 *
 * <p>Note that this class inherits its {@link #equals} and {@link #hashCode} implementations from
 * {@link ScopedName}, which does not include any type information. This is necessary because {@code
 * Var}-keyed maps are used across multiple top scopes, but it comes with the caveat that if {@code
 * TypedVar} instances are stored in a set, the type information is at risk of disappearing if an
 * untyped (or differently typed) var is added for the same symbol.
 */
public class TypedVar extends AbstractVar<TypedScope, TypedVar>
    implements StaticTypedSlot, StaticTypedRef {

  private JSType type;
  // The next two fields and the associated methods are only used by
  // TypeInference.java. Maybe there is a way to avoid having them in all typed variable instances.
  private boolean markedEscaped = false;
  private boolean markedAssignedExactlyOnce = false;

  /**
   * Whether the variable's type has been inferred or is declared. An inferred
   * type may change over time (as more code is discovered), whereas a
   * declared type is a static contract that must be matched.
   */
  private final boolean typeInferred;

  TypedVar(boolean inferred, String name, Node nameNode, JSType type,
      TypedScope scope, int index, CompilerInput input) {
    super(name, nameNode, scope, index, input);
    this.type = type;
    this.typeInferred = inferred;
  }

  /**
   * Gets this variable's type. To know whether this type has been inferred,
   * see {@code #isTypeInferred()}.
   */
  @Override
  public JSType getType() {
    return type;
  }

  void setType(JSType type) {
    this.type = type;
  }

  void resolveType(ErrorReporter errorReporter) {
    if (type != null) {
      this.type = type.resolve(errorReporter);
    }
  }

  /**
   * Returns whether this variable's type is inferred. To get the variable's
   * type, see {@link #getType()}.
   */
  @Override
  public boolean isTypeInferred() {
    return typeInferred;
  }

  public String getInputName() {
    if (input == null) {
      return "<non-file>";
    }
    return input.getName();
  }

  @Override
  public String toString() {
    return "Var " + name + "{" + type + "}";
  }

  void markEscaped() {
    markedEscaped = true;
  }

  boolean isMarkedEscaped() {
    return markedEscaped;
  }

  void markAssignedExactlyOnce() {
    markedAssignedExactlyOnce = true;
  }

  boolean isMarkedAssignedExactlyOnce() {
    return markedAssignedExactlyOnce;
  }
}


text:
/**
 * oauth2js (https://github.com/ni-c/oauth2js)
 *
 * @file app.js
 * @brief OAuth application
 * @author Willi Thiel (ni-c@ni-c.de)
 *
 */

/**
 * RequireJS
 * @see http://requirejs.org/docs/node.html
 */
var requirejs = require('requirejs');
requirejs.config({
  nodeRequire: require
});

/**
 * Express
 * @see http://expressjs.com/guide.html
 */
requirejs([ 'http', 'connect', 'path', 'express', 'node-conf', 'mongodb', './routes/oauth', './routes/user' ], function(http, connect, path, express, conf, mongodb, oauth, user) {

  var node_env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development';
  var config = conf.load(node_env);

  // Check for configuration
  if (!config.ports || !config.mongo || !config.mongo.host || !config.mongo.name || !config.mongo.port || !config.secret || !config.oauth) {
    console.log('\u001b[31mMissing configuration file \u001b[33mconfig/' + node_env + '.json\u001b[31m. Create configuration file or start with `NODE_ENV=production node app.js` to use another configuration file.\033[0m');
    return;
  }
  console.log('\u001b[32mUsing configuration \u001b[33mconfig/' + node_env + '.json\u001b[32m...\033[0m');

  var app = express();
  var cookieParser = express.cookieParser(config.secret);
  var sessionStore = new connect.middleware.session.MemoryStore();

  // Initialize database
  var db = new mongodb.Db(config.mongo.name, new mongodb.Server(config.mongo.host, parseInt(config.mongo.port), config.mongo.user, {
    native_parser: false,
    auto_reconnect: true,
    safe: true
  }));

  // Open database
  db.open(function(err, db) {
    if (err) {
      throw new Error(err);
    }

    app.configure(function() {
      app.set('ports', config.ports);
      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.set('db', db);
      app.set('oauth', config.oauth);
      app.use(express.favicon());
      app.use(express.logger('dev'));
      app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(cookieParser);
      app.use(express.session({
        store: sessionStore,
        key: 'oauth2js'
      }));
      app.use(app.router);
    });

    app.configure('development', function() {
      app.use(express.errorHandler());
    });

    // Define OAuth routes
    app.post('/token', oauth.token);
    app.get('/authorize', oauth.authorize);
    app.get('/verify', oauth.verify);

    // Define User routes
    app.get('/', user.index);
    app.get('/login', user.login);
    app.post('/login', user.performlogin);
    app.get('/logout', user.logout);

    // 404 Not found
    app.all('*', function(req, res) {
      res.send(404, "
I'm sorry Dave, i'm afraid i can't do that.
");
    });

    // Start server
    app.get('ports').forEach(function(port) {
      http.createServer(app).listen(port, function() {
        console.log('\u001b[32mExpress server listening on port \u001b[33m' + port + '\033[0m');
      });
    });
  });
});


text:
package org.factcast.core.subscription;

import static org.factcast.core.TestHelper.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;

import org.factcast.core.Fact;
import org.factcast.core.subscription.observer.GenericObserver;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class SubscriptionImplTest {

    @Mock
    private GenericObserver<Fact> observer;

    @InjectMocks
    private SubscriptionImpl<Fact> uut;

    @SuppressWarnings("unchecked")
    @BeforeEach
    void setUp() {
        obs = mock(GenericObserver.class);
    }

    @Test
    void testClose() throws Exception {
        expect(TimeoutException.class, () -> uut.awaitCatchup(10));
        expect(TimeoutException.class, () -> uut.awaitComplete(10));
        uut.close();
        expect(SubscriptionCancelledException.class, () -> uut.awaitCatchup(10));
        expect(SubscriptionCancelledException.class, () -> uut.awaitComplete(10));
    }

    @Test
    void testAwaitCatchup() {
        expect(TimeoutException.class, () -> uut.awaitCatchup(10));
        expect(TimeoutException.class, () -> uut.awaitComplete(10));
        uut.notifyCatchup();
        uut.awaitCatchup();
        expect(TimeoutException.class, () -> uut.awaitComplete(10));
    }

    @Test
    void testAwaitComplete() {
        expect(TimeoutException.class, () -> uut.awaitCatchup(10));
        expect(TimeoutException.class, () -> uut.awaitComplete(10));
        uut.notifyComplete();
        uut.awaitCatchup();
        uut.awaitComplete();
    }

    @SuppressWarnings("resource")
    @Test
    void testNullConst() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            new SubscriptionImpl<>(null);
        });
    }

    @Test
    void testNotifyElementNull() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            uut.notifyElement(null);
        });
    }

    @Test
    void testNotifyErrorNull() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            uut.notifyError(null);
        });
    }

    @Test
    void testOnClose() throws Exception {
        CountDownLatch l = new CountDownLatch(1);
        uut.onClose(l::countDown);
        uut.close();
        l.await();
    }

    private GenericObserver<Integer> obs;

    @Test
    void testOnNull() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            SubscriptionImpl.on(null);
        });
    }

    @Test
    void testOn() {
        SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs);
        verify(obs, never()).onNext(any());
        on.notifyElement(1);
        verify(obs).onNext(1);
        verify(obs, never()).onCatchup();
        on.notifyCatchup();
        verify(obs).onCatchup();
        verify(obs, never()).onComplete();
        on.notifyComplete();
        verify(obs).onComplete();
        // subsequent calls will be ignored, as this subscription was completed.
        // creating a new one...
    }

    @Test
    void testOnError() {
        SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs);
        verify(obs, never()).onError(any());
        on.notifyError(new Throwable("ignore me"));
        verify(obs).onError(any());
    }

    @Test
    void testOnErrorCloses() {
        SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs);
        on.notifyError(new Throwable("ignore me"));
        on.notifyElement(1);
        on.notifyCatchup();
        on.notifyComplete();
        verify(obs, never()).onComplete();
        verify(obs, never()).onCatchup();
        verify(obs, never()).onNext(anyInt());
    }

    @Test
    void testOnCompleteCloses() {
        SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs);
        on.notifyComplete();
        on.notifyElement(1);
        on.notifyCatchup();
        on.notifyError(new Throwable("ignore me"));
        verify(obs, never()).onError(any());
        verify(obs, never()).onCatchup();
        verify(obs, never()).onNext(anyInt());
    }

    @Test
    void testOnCatchupDoesNotClose() {
        SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs);
        on.notifyCatchup();
        on.notifyElement(1);
        on.notifyError(new Throwable("ignore me"));
        verify(obs).onError(any());
        verify(obs).onCatchup();
        verify(obs).onNext(anyInt());
    }

    @Test
    void testOnErrorCompletesFutureCatchup() {
        Assertions.assertThrows(SubscriptionCancelledException.class, () -> {
            SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs);
            verify(obs, never()).onError(any());
            on.notifyError(new Throwable("ignore me"));
            verify(obs).onError(any());
            on.awaitCatchup();
        });
    }

    @Test
    void testOnErrorCompletesFutureComplete() {
        Assertions.assertThrows(SubscriptionCancelledException.class, () -> {
            SubscriptionImpl<Integer> on = SubscriptionImpl.on(obs);
            verify(obs, never()).onError(any());
            on.notifyError(new Throwable("ignore me"));
            verify(obs).onError(any());
            on.awaitComplete();
        });
    }

    @Test
    void testAwaitCatchupLong() throws Exception {
        Assertions.assertTimeout(Duration.ofMillis(100), () -> {
            uut.notifyCatchup();
            uut.awaitCatchup(100000);
        });
    }

    @Test
    void testAwaitCompleteLong() throws Exception {
        Assertions.assertTimeout(Duration.ofMillis(100), () -> {
            uut.notifyComplete();
            uut.awaitComplete(100000);
        });
    }

    @Test
    public void testCloseThrowsException() throws Exception {
        uut = spy(uut);
        doThrow(RuntimeException.class).when(uut).close();

        // this must return without exceptions
        uut.notifyComplete();
    }
}


text:
require "spec_helper"

describe VIPS::TIFFWriter do
  before :all do
    @image = simg 'wagon.v'
    @writer = VIPS::TIFFWriter.new @image
    @path = tmp('wagon.tiff').to_s
  end

  it "should write a tiff file" do
    @writer.write(@path)

    im = VIPS::Image.tiff @path
    im.x_size.should == @image.x_size
    im.y_size.should == @image.y_size
  end

  it "should write tiff files in all available compression formats" do
    VIPS::TIFFWriter::FORMAT.each do |f|
      @writer.format = f
      @writer.write(@path)

      im = VIPS::Image.tiff @path
      im.x_size.should == @image.x_size
      im.y_size.should == @image.y_size
    end
  end

  it "should write an identical file when using no compression" do
    @writer.compression = :none
    @writer.write @path

    im = VIPS::Image.tiff @path
    im.should match_image(@image)
  end

  it "should write tiff files with different jpeg compression levels" do
    @writer.compression = :jpeg

    @writer.quality = 10
    @writer.write(@path)
    size1 = File.size @path

    @writer.quality = 90
    @writer.write(@path)
    size2 = File.size @path

    size1.should < size2 / 2
  end

  it "should store the internal resolution" do
    im = @image.shrink 2, 2
    x_res = im.x_res
    y_res = im.y_res

    im.tiff @path
    im2 = VIPS::Image.tiff @path

    im2.x_res.should == x_res
    im2.y_res.should == y_res
  end

  it "should allow setting a custom resolution" do
    @writer.resolution = [0.123, 0.456]
    @writer.write @path

    im = VIPS::Image.tiff @path

    # tiff images are stored at a resolution at 1/10 of vips resolution
    im.x_res.should approximate(0.123 / 10)
    im.y_res.should approximate(0.456 / 10)
  end

  it "should create a tiff writer from an image" do
    @writer.class.should == VIPS::TIFFWriter
    @writer.image.should == @image
  end

  it "should accept options as a has when creating from an image" do
    writer = @image.tiff(nil, :compression => :lzw, :layout => :tile,
      :tile_size => [37, 55])
    writer.compression.should == :lzw
    writer.layout.should == :tile
    writer.tile_size.should == [37, 55]
  end
end


text:
from __future__ import absolute_import
from proteus import *
from proteus.default_n import *
from .ls_consrv_vortex_3d_p import *
from .vortex import *

timeIntegrator = ForwardIntegrator
timeIntegration = NoIntegration
stepController = MCorr.Newton_controller#need a tricked up controller that can fix the VOF model's initial conditions

if cDegree_ls==0:
    if useHex:
        if pDegree_ls==1:
            femSpaces = {0:C0_AffineLinearOnCubeWithNodalBasis}
        elif pDegree_ls==2:
            femSpaces = {0:C0_AffineLagrangeOnCubeWithNodalBasis}
        elementQuadrature = CubeGaussQuadrature(nd,vortex_quad_order)
        elementBoundaryQuadrature = CubeGaussQuadrature(nd-1,vortex_quad_order)
    else:
        if pDegree_ls==1:
            femSpaces = {0:C0_AffineLinearOnSimplexWithNodalBasis}
        elif pDegree_ls==2:
            femSpaces = {0:C0_AffineQuadraticOnSimplexWithNodalBasis}
        elementQuadrature = SimplexGaussQuadrature(nd,vortex_quad_order)
        elementBoundaryQuadrature = SimplexGaussQuadrature(nd-1,vortex_quad_order)
    if parallel or LevelModelType in [MCorr.LevelModel]:#,MCorrElement.LevelModel]:
        numericalFluxType = DoNothing#Diffusion_IIPG_exterior
elif cDegree_ls==-1:
    if pDegree_ls==0:
        femSpaces = {0:DG_AffineP0_OnSimplexWithMonomialBasis}
    elif pDegree_ls==1:
        femSpaces = {0:DG_AffineP1_OnSimplexWithMonomialBasis}
    elif pDegree_ls==2:
        femSpaces = {0:DG_AffineP2_OnSimplexWithMonomialBasis}
    numericalFluxType = Advection_DiagonalUpwind_Diffusion_SIPG

# elementQuadrature = SimplexLobattoQuadrature(nd,1)

# elementBoundaryQuadrature = SimplexLobattoQuadrature(nd-1,1)

subgridError = None

massLumping = False

shockCapturing = None

multilevelNonlinearSolver  = NLNI

if correctionType == 'dg':
    levelNonlinearSolver = MCorr.ElementNewton
elif correctionType == 'dgp0':
    levelNonlinearSolver = MCorr.ElementConstantNewton
elif correctionType == 'global':
    levelNonlinearSolver = MCorr.GlobalConstantNewton
elif correctionType == 'none':
    levelNonlinearSolver = MCorr.DummyNewton
else:
    levelNonlinearSolver = Newton
    nonlinearSolverNorm = MCorr.conservationNorm
nonlinearSmoother = NLGaussSeidel

fullNewtonFlag = True

tolFac = 0.0

nl_atol_res = atolConservation

maxNonlinearIts = 100

matrix = SparseMatrix

if parallel:
    multilevelLinearSolver = PETSc
    levelLinearSolver = PETSc
    linear_solver_options_prefix = 'mcorr_'
    linearSolverConvergenceTest = 'r-true'
else:
    multilevelLinearSolver = LU

    levelLinearSolver = LU

linTolFac = 1.0e-6

conservativeFlux = {}
if checkMass:
    auxiliaryVariables = [AuxiliaryVariables.ConservationHistoryMC("vortex3d"+repr(lRefinement)+"p"+repr(pDegree_ls))]


text:
package de.aice.act.http;

import de.aice.act.Act;
import de.aice.act.ActException;

/**
 * Stage.
 *
 * @author Eléna Ihde-Simon (elena.ihde-simon@posteo.de)
 * @version $Id$
 */
public interface Stage {

	/**
	 * Start until exit.
	 *
	 * @param exit exit.
	 * @throws Exception if something goes wrong.
	 */
	void start(Exit exit) throws Exception;

	/**
	 * Basic stage without exception handling.
	 *
	 * @param act Act to call.
	 * @return basicStage Stage.
	 * @throws ActException if something goes wrong.
	 */
	static Stage basicStage(final Act act) throws ActException {
		return new StageBasic(BackStage.basic(act));
	}

	/**
	 * Stage with exception handling.
	 *
	 * @param act Act to call.
	 * @return Safe Stage.
	 */
	static Stage safeStage(final Act act) {
		return new StageBasic(BackStage.safe(act));
	}

}


text:
package net.i2p.data;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;

import junit.framework.TestCase;

/**
 * basic unit tests for the DataHelper
 *
 */
public class DataHelperTest extends TestCase{

    /**
     * Test to/from/read/writeLong with every 1, 2, and 4 byte value, as
     * well as some 8 byte values.
     */
    public void testLong() throws Exception{
        for (int i = 0; i <= 0xFF; i+=4)
            checkLong(1, i);
        for (long i = 0; i <= 0xFFFF; i+=16)
            checkLong(2, i);
        for (long i = 0; i <= 0xFFFFFF; i +=128)
            checkLong(3, i);
        for (long i = 0; i <= 0xFFFFFFFFl; i+=512)
            checkLong(4, i);
        // i know, doesnt test (2^63)-(2^64-1)
        for (long i = Long.MAX_VALUE - 0xFFFFFFl; i < Long.MAX_VALUE; i++)
            checkLong(8, i);
    }
    private static void checkLong(int numBytes, long value) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(numBytes);
        DataHelper.writeLong(baos, numBytes, value);
        byte written[] = baos.toByteArray();
        byte extract[] = DataHelper.toLong(numBytes, value);
        assertTrue(extract.length == numBytes);
        assertTrue(DataHelper.eq(written, extract));
        byte extract2[] = new byte[numBytes];
        DataHelper.toLong(extract2, 0, numBytes, value);
        assertTrue(DataHelper.eq(extract, extract2));

        long read = DataHelper.fromLong(extract, 0, numBytes);
        assertTrue(read == value);

        ByteArrayInputStream bais = new ByteArrayInputStream(written);
        read = DataHelper.readLong(bais, numBytes);
        assertTrue(read == value);
        read = DataHelper.fromLong(written, 0, numBytes);
        assertTrue(read == value);

    }

    public void testDate() throws Exception{
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        cal.set(Calendar.YEAR, 1970);
        cal.set(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        checkDate(cal.getTime());

        cal.set(Calendar.SECOND, 1);
        checkDate(cal.getTime());

        cal.set(Calendar.YEAR, 1999);
        cal.set(Calendar.MONTH, 11);
        cal.set(Calendar.DAY_OF_MONTH, 31);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        checkDate(cal.getTime());

        cal.set(Calendar.YEAR, 2000);
        cal.set(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        checkDate(cal.getTime());

        cal.setTimeInMillis(System.currentTimeMillis());
        checkDate(cal.getTime());

        cal.set(Calendar.SECOND, cal.get(Calendar.SECOND)+10);
        checkDate(cal.getTime());

        cal.set(Calendar.YEAR, 1969);
        cal.set(Calendar.MONTH, 11);
        cal.set(Calendar.DAY_OF_MONTH, 31);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        boolean error = false;
        try{
            checkDate(cal.getTime());
        }catch(Exception e){
            error = true;
        }
        assertTrue(error);
    }

    private void checkDate(Date when) throws Exception{
        byte buf[] = new byte[DataHelper.DATE_LENGTH];
        DataHelper.toDate(buf, 0, when.getTime());
        byte tbuf[] = DataHelper.toDate(when);
        assertTrue(DataHelper.eq(tbuf, buf));
        Date time = DataHelper.fromDate(buf, 0);
        assertEquals(when.getTime(), time.getTime());
    }

    public void testCompress() throws Exception{
        Random r = new Random();
        for (int size = 0; size < 32*1024; size+=32){   // Original had size++, changed value because
                                                        // speed was a problem. -Comwiz
            byte data[] = new byte[size];
            r.nextBytes(data);
            byte compressed[] = DataHelper.compress(data);
            byte decompressed[] = DataHelper.decompress(compressed);
            assertTrue(DataHelper.eq(data, decompressed));

        }
    }

    public void testSkip() throws Exception {
        final int sz = 256;
        TestInputStream tis = new TestInputStream(sz);
        DataHelper.skip(tis, sz);
        try {
            DataHelper.skip(tis, 1);
            fail();
        } catch (IOException ioe) {}

        DataHelper.skip(tis, 0);

        try {
            DataHelper.skip(tis, -1);
            fail("skipped negative?");
        } catch (IllegalArgumentException expected) {}
    }

    private static class TestInputStream extends ByteArrayInputStream {
        private final Random r = new Random();

        public TestInputStream(int size) {
            super(new byte[size]);
            r.nextBytes(buf);
        }

        /** skip a little at a time, or sometimes zero */
        @Override
        public long skip(long n) {
            return super.skip(Math.min(n, r.nextInt(4)));
        }
    }
}


text: Graph link weight regression with a deep neural network


text:
import { LocalStorageCryptoStore } from 'matrix-js-sdk/src/crypto/store/localStorage-crypto-store';
import { IndexedDBStore } from "matrix-js-sdk/src/store/indexeddb";
import { IndexedDBCryptoStore } from "matrix-js-sdk/src/crypto/store/indexeddb-crypto-store";
import { logger } from "matrix-js-sdk/src/logger";

const localStorage = window.localStorage;

// just *accessing* indexedDB throws an exception in firefox with
// indexeddb disabled.
let indexedDB: IDBFactory;
try {
    indexedDB = window.indexedDB;
} catch (e) {}

// The JS SDK will add a prefix of "matrix-js-sdk:" to the sync store name.
const SYNC_STORE_NAME = "riot-web-sync";
const CRYPTO_STORE_NAME = "matrix-js-sdk:crypto";

function log(msg: string) {
    logger.log(`StorageManager: ${msg}`);
}

function error(msg: string, ...args: string[]) {
    logger.error(`StorageManager: ${msg}`, ...args);
}

export function tryPersistStorage() {
    if (navigator.storage && navigator.storage.persist) {
        navigator.storage.persist().then(persistent => {
            logger.log("StorageManager: Persistent?", persistent);
        });
    } else if (document.requestStorageAccess) { // Safari
        document.requestStorageAccess().then(
            () => logger.log("StorageManager: Persistent?", true),
            () => logger.log("StorageManager: Persistent?", false),
        );
    } else {
        logger.log("StorageManager: Persistence unsupported");
    }
}

export async function checkConsistency() {
    log("Checking storage consistency");
    log(`Local storage supported? ${!!localStorage}`);
    log(`IndexedDB supported? ${!!indexedDB}`);

    let dataInLocalStorage = false;
    let dataInCryptoStore = false;
    let cryptoInited = false;
    let healthy = true;

    if (localStorage) {
        dataInLocalStorage = localStorage.length > 0;
        log(`Local storage contains data? ${dataInLocalStorage}`);

        cryptoInited = !!localStorage.getItem("mx_crypto_initialised");
        log(`Crypto initialised? ${cryptoInited}`);
    } else {
        healthy = false;
        error("Local storage cannot be used on this browser");
    }

    if (indexedDB && localStorage) {
        const results = await checkSyncStore();
        if (!results.healthy) {
            healthy = false;
        }
    } else {
        healthy = false;
        error("Sync store cannot be used on this browser");
    }

    if (indexedDB) {
        const results = await checkCryptoStore();
        dataInCryptoStore = results.exists;
        if (!results.healthy) {
            healthy = false;
        }
    } else {
        healthy = false;
        error("Crypto store cannot be used on this browser");
    }

    if (dataInLocalStorage && cryptoInited && !dataInCryptoStore) {
        healthy = false;
        error(
            "Data exists in local storage and crypto is marked as initialised " +
            " but no data found in crypto store. " +
            "IndexedDB storage has likely been evicted by the browser!",
        );
    }

    if (healthy) {
        log("Storage consistency checks passed");
    } else {
        error("Storage consistency checks failed");
    }

    return {
        dataInLocalStorage,
        dataInCryptoStore,
        cryptoInited,
        healthy,
    };
}

async function checkSyncStore() {
    let exists = false;
    try {
        exists = await IndexedDBStore.exists(
            indexedDB, SYNC_STORE_NAME,
        );
        log(`Sync store using IndexedDB contains data? ${exists}`);
        return { exists, healthy: true };
    } catch (e) {
        error("Sync store using IndexedDB inaccessible", e);
    }
    log("Sync store using memory only");
    return { exists, healthy: false };
}

async function checkCryptoStore() {
    let exists = false;
    try {
        exists = await IndexedDBCryptoStore.exists(
            indexedDB, CRYPTO_STORE_NAME,
        );
        log(`Crypto store using IndexedDB contains data? ${exists}`);
        return { exists, healthy: true };
    } catch (e) {
        error("Crypto store using IndexedDB inaccessible", e);
    }
    try {
        exists = LocalStorageCryptoStore.exists(localStorage);
        log(`Crypto store using local storage contains data? ${exists}`);
        return { exists, healthy: true };
    } catch (e) {
        error("Crypto store using local storage inaccessible", e);
    }
    log("Crypto store using memory only");
    return { exists, healthy: false };
}

/**
 * Sets whether crypto has ever been successfully
 * initialised on this client.
 * StorageManager uses this to determine whether indexeddb
 * has been wiped by the browser: this flag is saved to localStorage
 * and if it is true and not crypto data is found, an error is
 * presented to the user.
 *
 * @param {boolean} cryptoInited True if crypto has been set up
 */
export function setCryptoInitialised(cryptoInited: boolean) {
    localStorage.setItem("mx_crypto_initialised", String(cryptoInited));
}

/* Simple wrapper functions around IndexedDB.
 */

let idb: IDBDatabase = null;

async function idbInit(): Promise<void> {
    if (!indexedDB) {
        throw new Error("IndexedDB not available");
    }
    idb = await new Promise((resolve, reject) => {
        const request = indexedDB.open("matrix-react-sdk", 1);
        request.onerror = reject;
        request.onsuccess = () => { resolve(request.result); };
        request.onupgradeneeded = () => {
            const db = request.result;
            db.createObjectStore("pickleKey");
            db.createObjectStore("account");
        };
    });
}

export async function idbLoad(
    table: string,
    key: string | string[],
): Promise<any> {
    if (!idb) {
        await idbInit();
    }
    return new Promise((resolve, reject) => {
        const txn = idb.transaction([table], "readonly");
        txn.onerror = reject;

        const objectStore = txn.objectStore(table);
        const request = objectStore.get(key);
        request.onerror = reject;
        request.onsuccess = (event) => { resolve(request.result); };
    });
}

export async function idbSave(
    table: string,
    key: string | string[],
    data: any,
): Promise<void> {
    if (!idb) {
        await idbInit();
    }
    return new Promise((resolve, reject) => {
        const txn = idb.transaction([table], "readwrite");
        txn.onerror = reject;

        const objectStore = txn.objectStore(table);
        const request = objectStore.put(data, key);
        request.onerror = reject;
        request.onsuccess = (event) => { resolve(); };
    });
}

export async function idbDelete(
    table: string,
    key: string | string[],
): Promise<void> {
    if (!idb) {
        await idbInit();
    }
    return new Promise((resolve, reject) => {
        const txn = idb.transaction([table], "readwrite");
        txn.onerror = reject;

        const objectStore = txn.objectStore(table);
        const request = objectStore.delete(key);
        request.onerror = reject;
        request.onsuccess = () => { resolve(); };
    });
}


text:
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from pendulum.tests.utils import VALID_PASSWORD, VALID_USER, ffd
from pendulum.models import Entry
from datetime import datetime, timedelta

class UpdateEntryTestCase(TestCase):
    """
    Make sure that the code for updating a closed entry works as expected.
    Rules for updating an entry:
    - Owned by user
    - Closed
    - Cannot start in the future
    - Cannot end in the future
    - Start must be before end
    """

    fixtures = ['activities', 'projects', 'users', 'entries']
    first_run = True

    def setUp(self):
        self.client = Client()

        if self.first_run:
            # try updating an entry before being logged in
            response = self.get_response(2)
            self.assertEquals(response.status_code, 302)

        # log in
        response = self.client.login(username=VALID_USER, password=VALID_PASSWORD)
        self.assertTrue(response)

        if self.first_run:
            # try updating an entry that doesn't exist
            response = self.get_response(1000)
            self.assertEquals(response.status_code, 302)

            self.first_run = False

    def get_response(self, id):
        """
        Retrieve the response of a GET request
        """
        return self.client.get(reverse('pendulum-update', args=[id]))

    def post_response(self, id, args):
        """
        Retrieve the response of a POST request with specified parameters
        """
        return self.client.post(reverse('pendulum-update', args=[id]), args)

    def testUpdateOtherUsersEntry(self):
        #--------------------------------------------------
        # 1. ENTRY THAT BELONGS TO OTHER USER
        id = 1
        now = datetime.now()

        # check to make sure that log entry isn't closed
        entry = Entry.objects.get(pk=id)
        self.assertFalse(entry.is_closed)

        # try to get the form to update it
        response = self.get_response(id)
        self.assertEquals(response.status_code, 302)

        # try to manually post information
        response = self.post_response(id, {'start_time': ffd(now + timedelta(hours=-5)),
                                           'end_time': ffd(now)})
        self.assertEquals(response.status_code, 302)

        again = Entry.objects.get(pk=id)
        self.assertEquals(entry.start_time, again.start_time)
        self.assertEquals(entry.end_time, again.end_time)

    def testUpdatePausedEntry(self):
        #--------------------------------------------------
        # 2. ENTRY THAT IS PAUSED
        id = 2
        now = datetime.now()

        # get a paused entry, and make sure it's paused
        entry = Entry.objects.get(pk=id)
        self.assertTrue(entry.is_paused)

        # try to get the form to update its information
        response = self.get_response(id)
        self.assertEquals(response.status_code, 302)

        # try to update it with no information specified
        response = self.post_response(id, {})
        self.assertEquals(response.status_code, 302)

        # try to update it with a little information specified
        response = self.post_response(id, {'project': 2,
                                           'comments': 'Updating the entry'})
        self.assertEquals(response.status_code, 302)

        # try to update it with all required information
        response = self.post_response(id, {'project': 1,
                                           'activity': 1,
                                           'start_time': ffd(now + timedelta(hours=-5)),
                                           'end_time': ffd(now)})
        self.assertEquals(response.status_code, 302)

        # pull back the entry, and make sure it hasn't changed
        again = Entry.objects.get(pk=id)
        self.assertEquals(entry.project, again.project)
        self.assertEquals(entry.activity, again.activity)
        self.assertEquals(entry.start_time, again.start_time)
        self.assertEquals(entry.end_time, again.end_time)
        self.assertEquals(entry.comments, again.comments)

    def testUpdateAlreadyClosedEntry(self):
        #--------------------------------------------------
        # 3. ENTRY THAT IS ALREADY CLOSED
        id = 3
        now = datetime.now()
        values = {'project': 2,
                  'activity': 2,
                  'start_time': ffd(now + timedelta(hours=-2)),
                  'end_time': ffd(now),
                  'comments': 'New comments'}

        # make sure the entry is already closed
        entry = Entry.objects.get(pk=id)
        self.assertTrue(entry.is_closed)
        self.assertFalse(entry.is_paused)

        # try to update the new entry with not enough information
        response = self.post_response(id, {})
        self.assertEquals(response.status_code, 200)

        # try various combinations of incomplete data
        response = self.post_response(id, {'project': values['project']})
        self.assertEquals(response.status_code, 200)

        response = self.post_response(id, {'project': values['project'],
                                           'activity': values['activity']})
        self.assertEquals(response.status_code, 200)

        response = self.post_response(id, {'project': values['project'],
                                           'activity': values['activity'],
                                           'start_time': values['start_time']})
        self.assertEquals(response.status_code, 200)

        response = self.post_response(id, {'activity': values['activity'],
                                           'start_time': values['start_time'],
                                           'end_time': values['end_time']})
        self.assertEquals(response.status_code, 200)

        #response = self.post_response(id, {'project': values['project'],
        #                                   'start_time': values['start_time'],
        #                                   'end_time': values['end_time']})
        #self.assertEquals(response.status_code, 200)

        response = self.post_response(id, {'project': values['project'],
                                           'activity': values['activity'],
                                           'end_time': values['end_time']})
        self.assertEquals(response.status_code, 200)

        # update the entry with new information
        response = self.post_response(id, values)
        self.assertEquals(response.status_code, 302)

        # make sure the information is just as I want it to be
        entry = Entry.objects.get(pk=id)
        self.assertEquals(entry.project.id, values['project'])
        self.assertEquals(entry.activity.id, values['activity'])
        self.assertEquals(ffd(entry.start_time), values['start_time'])
        self.assertEquals(ffd(entry.end_time), values['end_time'])
        self.assertEquals(entry.comments, values['comments'])

    def testUpdateOpenUnpausedEntry(self):
        #--------------------------------------------------
        # 4. ENTRY THAT IS OPEN AND NOT PAUSED
        id = 4
        now = datetime.now()

        # get an open entry, and make sure it's not paused
        entry = Entry.objects.get(pk=id)
        self.assertFalse(entry.is_closed)
        self.assertFalse(entry.is_paused)

        # try to get the form to update its information
        response = self.get_response(id)
        self.assertEquals(response.status_code, 302)

        # try to update it with no information specified
        response = self.post_response(id, {})
        self.assertEquals(response.status_code, 302)

        # try to update it with a little information specified
        response = self.post_response(id, {'project': 2,
                                           'comments': 'Updating the entry'})
        self.assertEquals(response.status_code, 302)

        # try to update it with all required information
        response = self.post_response(id, {'project': 1,
                                           'activity': 1,
                                           'start_time': ffd(now + timedelta(hours=-5)),
                                           'end_time': ffd(now)})
        self.assertEquals(response.status_code, 302)

        # pull back the entry, and make sure it hasn't changed
        again = Entry.objects.get(pk=id)
        self.assertEquals(entry.project, again.project)
        self.assertEquals(entry.activity, again.activity)
        self.assertEquals(entry.start_time, again.start_time)
        self.assertEquals(entry.end_time, again.end_time)
        self.assertEquals(entry.comments, again.comments)

        # now update it again, just to make sure
        values = {'project': 1,
                  'activity': 1,
                  'start_time': ffd(now + timedelta(hours=-2)),
                  'end_time': ffd(now + timedelta(hours=-1)),
                  'comments': 'New comments'}
        response = self.post_response(id, values)
        self.assertEquals(response.status_code, 302)

        # pull back the entry, and make sure it has changed
        again = Entry.objects.get(pk=id)
        self.assertNotEquals(again.project.id, values['project'])
        self.assertNotEquals(again.activity.id, values['activity'])
        self.assertNotEquals(again.start_time, values['start_time'])
        self.assertNotEquals(again.end_time, values['end_time'])
        self.assertNotEquals(again.comments, values['comments'])

    def testSetStartInFuture(self):
        """
        Try to update a good, closed entry to start and end in the future
        """
        id = 3
        now = datetime.now()
        values = {'project': 2,
                  'activity': 2,
                  'start_time': ffd(now + timedelta(hours=2)),
                  'end_time': ffd(now + timedelta(hours=5)),
                  'comments': 'New comments'}

        response = self.post_response(id, values)
        self.assertEquals(response.status_code, 200)

        # make sure the information is still as in the fixture
        entry = Entry.objects.get(pk=id)
        self.assertNotEquals(entry.project.id, values['project'])
        self.assertNotEquals(entry.activity.id, values['activity'])
        self.assertNotEquals(ffd(entry.start_time), values['start_time'])
        self.assertNotEquals(ffd(entry.end_time), values['end_time'])
        self.assertNotEquals(entry.comments, values['comments'])

    def testSetEndInFuture(self):
        """
        Try to update a good, closed entry to end in the future
        """
        id = 3
        now = datetime.now()
        values = {'project': 2,
                  'activity': 2,
                  'start_time': ffd(now + timedelta(hours=-2)),
                  'end_time': ffd(now + timedelta(hours=1)),
                  'comments': 'New comments'}

        response = self.post_response(id, values)
        self.assertEquals(response.status_code, 200)

        # make sure the information is still as in the fixture
        entry = Entry.objects.get(pk=id)
        self.assertNotEquals(entry.project.id, values['project'])
        self.assertNotEquals(entry.activity.id, values['activity'])
        self.assertNotEquals(ffd(entry.start_time), values['start_time'])
        self.assertNotEquals(ffd(entry.end_time), values['end_time'])
        self.assertNotEquals(entry.comments, values['comments'])

    def testSetStartAfterEnd(self):
        """
        Try to update a good, closed entry to start after it ends
        """
        id = 3
        now = datetime.now()
        values = {'project': 2,
                  'activity': 2,
                  'start_time': ffd(now + timedelta(hours=2)),
                  'end_time': ffd(now),
                  'comments': 'New comments'}

        response = self.post_response(id, values)
        self.assertEquals(response.status_code, 200)

        # make sure the information is still as in the fixture
        entry = Entry.objects.get(pk=id)
        self.assertNotEquals(entry.project.id, values['project'])
        self.assertNotEquals(entry.activity.id, values['activity'])
        self.assertNotEquals(ffd(entry.start_time), values['start_time'])
        self.assertNotEquals(ffd(entry.end_time), values['end_time'])
        self.assertNotEquals(entry.comments, values['comments'])


text:
require 'github_api'

user = ARGV[0]
token = ARGV[1]

def bad?(text)
  return false if text.nil?
  [
    "auth_token="
  ].any? do |bad_thing|
    text.include?(bad_thing)
  end ? text : nil
end

github = Github.new do |config|
  config.oauth_token = token
end

page = 1
begin

  repos = github.repos.list user: user, per_page: 5, page: page
  page += 1

  repos.each do |repo|
  puts '---' + repo.owner.login + '/' + repo.name
    begin
      ['open', 'closed'].each do |state|

        issues = github.issues.list user: user, repo: repo.name, per_page: 10000, state: state
        issues.each do |issue|

          text = nil

          text = bad?(issue.body)

          if issue.comments > 0
            comments = github.issues.comments.all user, repo.name, issue_id: issue.number
            comments.each do |comment|
              text = bad?(comment.body)
            end
          end

          puts "#{issue.html_url}: #{text}" if text

        end
      end
    rescue Github::Error::ServiceError => ex
      raise unless ex.message.include?("Issues are disabled for this repo")
    end
  end

end until repos.empty?


text:
set -e

# $1 is 0 for full release and 1 for incremental

if [ $1 -eq 0 ]; then
    # Run code for full release
    echo "Full release hook"
fi

if [ $1 -eq 1 ]; then
    # Run code for incremental release
    echo "Incremental release hook"
fi


text:
<?php

namespace Jhu\ZdtLoggerModule;

use Jhu\ZdtLoggerModule\ServiceFactory;
use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\ModuleManager\Feature\InitProviderInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\ModuleManager\ModuleManagerInterface;

/**
 * @since   0.1
 * @author  Jérémy Huet <jeremy.huet@gmail.com>
 * @link    https://github.com/jhuet/JhuZdtLoggerModule
 * @package Jhu\ZdtLoggerModule
 * @license MIT
 */
class Module implements
    AutoloaderProviderInterface,
    BootstrapListenerInterface,
    ConfigProviderInterface,
    ServiceProviderInterface,
    InitProviderInterface
{
    /**
     * {@inheritDoc}
     */
    public function init(ModuleManagerInterface $manager)
    {
        $events = $manager->getEventManager();
        // Initialize logger collector once the profiler is initialized itself
        $events->attach('profiler_init', function(EventInterface $e) use ($manager) {
            $manager->getEvent()->getParam('ServiceManager')->get('Jhu\ZdtLoggerModule\Collector');
        } );
    }

    /**
     * {@inheritDoc}
     */
    public function onBootstrap(EventInterface $e)
    {
        $application = $e->getParam('application');
        $config = $application->getServiceManager()->get('Config');

        // If the default logger is different and ZDT's toolbar is activated,
        // we initialize ours to add our functionalities
        if (
            $config['jhu']['zdt_logger']['logger'] != 'Zend\Log\Logger' &&
            $config['zenddevelopertools']['toolbar']['enabled'] == true
        ) {
            $application->getServiceManager()->get('jhu.zdt_logger');
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/../../../autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/../../../src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function getConfig()
    {
        return include __DIR__ . '/../../../config/module.config.php';
    }

    /**
     * {@inheritDoc}
     */
    public function getServiceConfig()
    {
        return array(
            'invokables' => array(
                'Jhu\ZdtLoggerModule\Writer'    => 'Jhu\ZdtLoggerModule\Writer\Stack',
                'Zend\Log\Logger'               => 'Zend\Log\Logger'
            ),

            'factories' => array(
                'Jhu\ZdtLoggerModule\Logger'    => new ServiceFactory\LoggerFactory(),
                'Jhu\ZdtLoggerModule\Collector' => new ServiceFactory\CollectorFactory(),
                'Jhu\ZdtLoggerModule\Options'   => new ServiceFactory\ModuleOptionsFactory(),
            ),

            'aliases' => array(
                'jhu.zdt_logger' => 'Jhu\ZdtLoggerModule\Logger',
            ),
        );
    }
}


text:
package br.com.senai.postocorreio.dao;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import br.com.senai.postocorreio.model.Cidade;

@Stateless
public class CidadeDAO {

    @PersistenceContext(unitName = "postocorreioPU")
    private EntityManager em;

    public void insere(Cidade cidade) {
        em.persist(cidade);
    }

    public void excluir(Long id) {
        em.remove(em.getReference(Cidade.class, id));
    }

    public Cidade buscar(Long id) {
        return em.find(Cidade.class, id);
    }

    public Cidade atualizar(Cidade cidade) {
        return em.merge(cidade);
    }

    public List<Cidade> lista() {
        TypedQuery<Cidade> q = em.createQuery("SELECT c "
                + "FROM Cidade c ORDER BY c.nome", Cidade.class);
        return q.getResultList();
    }

}


text:
'use strict';

/**
 * @ngdoc function
 * @name uiApp.controller:PropertiesCtrl
 * @description
 * # PropertiesCtrl
 * Controller of the uiApp
 */
angular.module('uiApp')
  .controller('PropertiesCtrl', ['PropertyService', 'ReplyErrorHandler', 'ConfirmModal', 'notifications','$scope','$filter', 'sharedProperty', function(PropertyService, ReplyErrorHandler, ConfirmModal, notifications, $scope, $filter, sharedProperty) {
    var orderBy = $filter('orderBy');
    $scope.propertylist = [];
    $scope.property = sharedProperty.property;
    $scope.formvisible = false;

    $scope.showForm = function(visible) {
        if(visible === true) {
            $scope.formvisible = true;
        } else {
            $scope.formvisible = false;
        }
    };

    $scope.loadProperties = function () {
        PropertyService.noid.get({},function(data) { //, status, headers, config
            $scope.propertylist = data;
        }, ReplyErrorHandler);
    };
    $scope.loadProperties();

    $scope.deleteProperty = function (id) {
        ConfirmModal.showModal({}, {headerText: 'Confirm', bodyText: 'Are you sure you want to delete this Property?'}).then(function () {//result
            PropertyService.id.delete({id: id},function() { //data, status, headers, config
                $scope.loadProperties();
                notifications.showSuccess('Property has been deleted.');
            }, ReplyErrorHandler);
        }, function() {notifications.showInfo('Delete canceled.');});
    };

    $scope.order = function(predicate, reverse) {
        $scope.propertylist = orderBy($scope.propertylist, predicate, reverse);
    };
    $scope.order('attribute', false);
}]);


text:
@interface HasItemTests : MatcherTestCase
@end

@implementation HasItemTests

- (void)testCopesWithNilsAndUnknownTypes
{
    id matcher = hasItem(equalTo(@"irrelevant"));

    assertNilSafe(matcher);
    assertUnknownTypeSafe(matcher);
}

- (void)testMatchesACollectionThatContainsAnElementForTheGivenMatcher
{
    id matcher = hasItem(equalTo(@1));

    assertMatches(@"list containing 1", matcher, (@[@1, @2, @3]));
}

- (void)testDoesNotMatchCollectionWithoutAnElementForGivenMatcher
{
    id matcher = hasItem([Mismatchable mismatchable:@"a"]);

    assertMismatchDescription(@"mismatches were: [mismatched: b, mismatched: c]", matcher, (@[@"b", @"c"]));
    assertMismatchDescription(@"was empty", matcher, @[]);
}

- (void)testDoesNotMatchNil
{
    assertDoesNotMatch(@"doesn't match nil", hasItem(equalTo(@1)), nil);
}

- (void)testProvidesConvenientShortcutForMatchingWithEqualTo
{
    assertMatches(@"list contains '1'", hasItem(@1), ([NSSet setWithObjects:@1, @2, @3, nil]));
    assertDoesNotMatch(@"list without '1'", hasItem(@1), ([NSSet setWithObjects:@2, @3, nil]));
}

- (void)testDoesNotMatchNonCollection
{
    assertMismatchDescription(@"was non-collection nil", hasItem(equalTo(@1)), nil);
}

- (void)testMatcherCreationRequiresNonNilArgument
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
    XCTAssertThrows(hasItem(nil), @"Should require non-nil argument");
#pragma clang diagnostic pop
}

- (void)testHasAReadableDescription
{
    assertDescription(@"a collection containing <1>", hasItem(@1));
}

- (void)testSuccessfulMatchDoesNotGenerateMismatchDescription
{
    assertNoMismatchDescription(hasItem(@1), ([NSSet setWithObjects:@1, @2, nil]));
}

- (void)testDescribeMismatch
{
    assertDescribeMismatch(@"was non-collection \"bad\"", hasItem(@1), @"bad");
}

- (void)testMatchesMultipleItemsInCollection
{
    id matcher1 = hasItems(equalTo(@1), equalTo(@2), equalTo(@3), nil);
    assertMatches(@"list containing all items", matcher1, (@[@1, @2, @3]));

    id matcher2 = hasItems(@1, @2, @3, nil);
    assertMatches(@"list containing all items (without matchers)", matcher2, (@[@1, @2, @3]));

    id matcher3 = hasItems(equalTo(@1), equalTo(@2), equalTo(@3), nil);
    assertMatches(@"list containing all items in any order", matcher3, (@[@3, @2, @1]));

    id matcher4 = hasItems(equalTo(@1), equalTo(@2), equalTo(@3), nil);
    assertMatches(@"list containing all items plus others", matcher4, (@[@5, @3, @2, @1, @4]));

    id matcher5 = hasItems(equalTo(@1), equalTo(@2), equalTo(@3), nil);
    assertDoesNotMatch(@"not match list unless it contains all items", matcher5, (@[@5, @3, @2, @4])); // '1' missing
}

- (void)testHasItems_ProvidesConvenientShortcutForMatchingWIthEqualTo
{
    assertMatches(@"list containing all items", hasItems(@1, @2, @3, nil), (@[ @1, @2, @3 ]));
}

- (void)testArrayVariant_ProvidesConvenientShortcutForMatchingWIthEqualTo
{
    assertMatches(@"list containing all items", hasItemsIn(@[@1, @2, @3]), (@[ @1, @2, @3 ]));
}

- (void)testReportsMismatchWithAReadableDescriptionForMultipleItems
{
    id matcher = hasItems(@3, @4, nil);

    assertMismatchDescription(@"instead of a collection containing <4>, mismatches were: [was <1>, was <2>, was <3>]",
            matcher, (@[@1, @2, @3]));
}

@end


text:
package uk.gov.dstl.baleen.annotators.regex;

import static org.junit.Assert.assertEquals;

import org.apache.uima.fit.util.JCasUtil;
import org.junit.Test;

import uk.gov.dstl.baleen.annotators.testing.AbstractAnnotatorTest;
import uk.gov.dstl.baleen.types.common.Vulnerability;

public class CveTest extends AbstractAnnotatorTest {

  public CveTest() {
    super(Cve.class);
  }

  @Test
  public void test() throws Exception {
    jCas.setDocumentText(
        "The second CVE to be issued, cve-1999-0002, describes a buffer overflow in NFS mountd.");
    processJCas();

    assertEquals(1, JCasUtil.select(jCas, Vulnerability.class).size());
    Vulnerability bw = JCasUtil.selectByIndex(jCas, Vulnerability.class, 0);
    assertEquals("cve-1999-0002", bw.getCoveredText());
  }
}


text:
/*
 * @lc app=leetcode id=1079 lang=java
 *
 * [1079] Letter Tile Possibilities
 *
 * https://leetcode.com/problems/letter-tile-possibilities/description/
 *
 * algorithms
 * Medium (75.65%)
 * Total Accepted:    40.7K
 * Total Submissions: 53.8K
 * Testcase Example:  '"AAB"'
 *
 * You have n  tiles, where each tile has one letter tiles[i] printed on it.
 *
 * Return the number of possible non-empty sequences of letters you can make
 * using the letters printed on those tiles.
 *
 *
 * Example 1:
 *
 *
 * Input: tiles = "AAB"
 * Output: 8
 * Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB",
 * "ABA", "BAA".
 *
 *
 * Example 2:
 *
 *
 * Input: tiles = "AAABBC"
 * Output: 188
 *
 *
 * Example 3:
 *
 *
 * Input: tiles = "V"
 * Output: 1
 *
 *
 *
 * Constraints:
 *
 *
 * 1 <= tiles.length <= 7
 * tiles consists of uppercase English letters.
 *
 *
 */
class Solution {
    Set<String> set = new HashSet<>();
    boolean[] visited;
    public int numTilePossibilities(String tiles) {
        StringBuilder sb = new StringBuilder();
        visited = new boolean[tiles.length()];
        dfs(tiles, sb, tiles.length());
        return set.size();
    }

    void dfs(String s, StringBuilder sb, int cur) {
        if (cur == 0) {
            return;
        }
        for (int i = 0; i < s.length(); i++)
            if (!visited[i]) {
                visited[i] = true;
                sb.append(s.charAt(i));
                set.add(sb.toString());
                dfs(s, sb, cur-1);
                sb.deleteCharAt(sb.length()-1);
                visited[i] = false;
            }
    }
}