text:
package com.netflix.loadbalancer;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Nullable;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.netflix.client.config.IClientConfig;

/**
 * A basic building block for server filtering logic which can be used in rules and server list filters.
 * The input object of the predicate is {@link PredicateKey}, which has Server and load balancer key
 * information. Therefore, it is possible to develop logic to filter servers by both Server and load balancer
 * key or either one of them.
 *
 * @author awang
 *
 */
public abstract class AbstractServerPredicate implements Predicate<PredicateKey> {

    protected IRule rule;
    private volatile LoadBalancerStats lbStats;

    private final Random random = new Random();

    private final AtomicInteger nextIndex = new AtomicInteger();

    private final Predicate<Server> serverOnlyPredicate =  new Predicate<Server>() {
        @Override
        public boolean apply(@Nullable Server input) {
            return AbstractServerPredicate.this.apply(new PredicateKey(input));
        }
    };

    public static AbstractServerPredicate alwaysTrue() {
        return new AbstractServerPredicate() {
            @Override
            public boolean apply(@Nullable PredicateKey input) {
                return true;
            }
        };
    }

    public AbstractServerPredicate() {

    }

    public AbstractServerPredicate(IRule rule) {
        this.rule = rule;
    }

    @Deprecated
    public AbstractServerPredicate(IRule rule, IClientConfig clientConfig) {
        this(rule);
    }

    @Deprecated
    public AbstractServerPredicate(LoadBalancerStats lbStats, IClientConfig clientConfig) {
        this(lbStats);
    }

    public AbstractServerPredicate(LoadBalancerStats lbStats) {
        this.lbStats = lbStats;
    }

    protected LoadBalancerStats getLBStats() {
        if (lbStats != null) {
            return lbStats;
        } else if (rule != null) {
            ILoadBalancer lb = rule.getLoadBalancer();
            if (lb instanceof AbstractLoadBalancer) {
                LoadBalancerStats stats =  ((AbstractLoadBalancer) lb).getLoadBalancerStats();
                setLoadBalancerStats(stats);
                return stats;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    public void setLoadBalancerStats(LoadBalancerStats stats) {
        this.lbStats = stats;
    }

    /**
     * Get the predicate to filter list of servers. The load balancer key is treated as null
     * as the input of this predicate.
     */
    public Predicate<Server> getServerOnlyPredicate() {
        return serverOnlyPredicate;
    }

    /**
     * Get servers filtered by this predicate from list of servers. Load balancer key
     * is presumed to be null.
     *
     * @see #getEligibleServers(List, Object)
     *
     */
    public List<Server> getEligibleServers(List<Server> servers) {
        return getEligibleServers(servers, null);
    }

    /**
     * Get servers filtered by this predicate from list of servers.
     */
    public List<Server> getEligibleServers(List<Server> servers, Object loadBalancerKey) {
        if (loadBalancerKey == null) {
            return ImmutableList.copyOf(Iterables.filter(servers, this.getServerOnlyPredicate()));
        } else {
            List<Server> results = Lists.newArrayList();
            for (Server server: servers) {
                if (this.apply(new PredicateKey(loadBalancerKey, server))) {
                    results.add(server);
                }
            }
            return results;
        }
    }

    /**
     * Referenced from RoundRobinRule
     * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
     *
     * @param modulo The modulo to bound the value of the counter.
     * @return The next value.
     */
    private int incrementAndGetModulo(int modulo) {
        for (;;) {
            int current = nextIndex.get();
            int next = (current + 1) % modulo;
            if (nextIndex.compareAndSet(current, next) && current < modulo)
                return current;
        }
    }

    /**
     * Choose a random server after the predicate filters a list of servers. Load balancer key
     * is presumed to be null.
     *
     */
    public Optional<Server> chooseRandomlyAfterFiltering(List<Server> servers) {
        List<Server> eligible = getEligibleServers(servers);
        if (eligible.size() == 0) {
            return Optional.absent();
        }
        return Optional.of(eligible.get(random.nextInt(eligible.size())));
    }

    /**
     * Choose a server in a round robin fashion after the predicate filters a list of servers. Load balancer key
     * is presumed to be null.
     */
    public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers) {
        List<Server> eligible = getEligibleServers(servers);
        if (eligible.size() == 0) {
            return Optional.absent();
        }
        return Optional.of(eligible.get(incrementAndGetModulo(eligible.size())));
    }

    /**
     * Choose a random server after the predicate filters list of servers given list of servers and
     * load balancer key.
     *
     */
    public Optional<Server> chooseRandomlyAfterFiltering(List<Server> servers, Object loadBalancerKey) {
        List<Server> eligible = getEligibleServers(servers, loadBalancerKey);
        if (eligible.size() == 0) {
            return Optional.absent();
        }
        return Optional.of(eligible.get(random.nextInt(eligible.size())));
    }

    /**
     * Choose a server in a round robin fashion after the predicate filters a given list of servers and load balancer key.
     */
    public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers, Object loadBalancerKey) {
        List<Server> eligible = getEligibleServers(servers, loadBalancerKey);
        if (eligible.size() == 0) {
            return Optional.absent();
        }
        return Optional.of(eligible.get(incrementAndGetModulo(eligible.size())));
    }

    /**
     * Create an instance from a predicate.
     */
    public static AbstractServerPredicate ofKeyPredicate(final Predicate<PredicateKey> p) {
        return new AbstractServerPredicate() {
            @Override
            @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP")
            public boolean apply(PredicateKey input) {
                return p.apply(input);
            }
        };
    }

    /**
     * Create an instance from a predicate.
     */
    public static AbstractServerPredicate ofServerPredicate(final Predicate<Server> p) {
        return new AbstractServerPredicate() {
            @Override
            @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP")
            public boolean apply(PredicateKey input) {
                return p.apply(input.getServer());
            }
        };
    }
}


text:
from geopy.point import Point
from geopy.location import Location
from geopy import geocoders

redpajama_set_name: RedPajamaGithub


text:
define([
	'jquery',
	'underscore',
	'backbone',
	'marionette',
	'text!templates/projects/info/members/invitations/project-invitations-list/project-invitations-list-item.tpl',
	'scripts/registry',
	'scripts/utilities/date-format',
	'scripts/models/projects/project-invitation',
	'scripts/views/dialogs/confirm-view',
	'scripts/views/dialogs/notify-view',
	'scripts/views/dialogs/error-view'
], function($, _, Backbone, Marionette, Template, Registry, DateFormat, ProjectInvitation, ConfirmView, NotifyView, ErrorView) {
	return Backbone.Marionette.ItemView.extend({

		//
		// attributes
		//

		tagName: 'tr',

		events: {
			'click .delete': 'onClickDelete'
		},

		//
		// rendering methods
		//

		template: function(data) {
			return _.template(Template, _.extend(data, {
				model: this.model,
				showDelete: this.options.showDelete
			}));
		},

		//
		// event handling methods
		//

		onClickDelete: function() {
			var self = this;

			// show confirm dialog
			//
			Registry.application.modal.show(
				new ConfirmView({
					title: "Delete Project Invitation",
					message: "Are you sure that you want to delete this invitation of " + this.model.get('invitee_name') + " to project " + self.options.project.get('full_name') + "?",

					// callbacks
					//
					accept: function() {
						var projectInvitation = new ProjectInvitation({
							'invitation_key': self.model.get('invitation_key')
						});

						// delete project invitation
						//
						self.model.destroy({
							url: projectInvitation.url(),

							// callbacks
							//
							success: function() {

								// show success notify
								//
								Registry.application.modal.show(
									new NotifyView({
										message: "This project invitation has successfully been deleted."
									})
								);
							},

							error: function() {

								// show error dialog
								//
								Registry.application.modal.show(
									new ErrorView({
										message: "Could not delete this project invitation."
									})
								);
							}
						});
					}
				})
			);
		}
	});
});


text:
/* */
module.exports = require('./reduce');


text:
namespace CGAL {

template <class Polygon>
struct Gps_default_traits
{};

template <class Kernel, class Container>
struct Gps_default_traits<CGAL::Polygon_2<Kernel, Container> >
{
  typedef Gps_segment_traits_2<Kernel,
                               Container,
                               Arr_segment_traits_2<Kernel> >    Traits;
};

template <class Kernel, class Container>
struct Gps_default_traits<CGAL::Polygon_with_holes_2<Kernel, Container> >
{
  typedef Gps_segment_traits_2<Kernel,
                               Container,
                               Arr_segment_traits_2<Kernel> >    Traits;
};

template <class Polygon>
struct Gps_default_traits<CGAL::General_polygon_with_holes_2<Polygon> >
{
  typedef typename Gps_default_traits<Polygon>::Traits Traits;
};

template <class Arr_traits>
struct Gps_default_traits<CGAL::General_polygon_2<Arr_traits> >
{
  typedef Gps_traits_2<Arr_traits>    Traits;
};

} //namespace CGAL

#endif


text:
CVR

Get code coverage reports from your LCOV, Cobertura, Jacoco, or Go Cover results.

                {{#if authed}}

Browse repos to view coverage or get a token to post coverage.

                {{else}}

                    Sign in with GitHub

                {{/if}}

        Use

curl

    curl -F coverage=@coverage.info "https://cvr.vokal.io/coverage?token=:TOKEN&commit=:COMMIT_HASH&coveragetype=:COVERAGE_TYPE&removepath=:REMOVE_PATH"

Details

                coverage (required)

                The coverage file contents posted in multipart format

                token (required unless providing owner and repo)

                The token provided with each repo, browse repos to get a token

                owner (required unless providing token)

                The owner of the repo

                repo (required unless providing token)

                The repo name

                commit (required)

                The git commit hash. In bash you can get this like COMMIT_HASH="$(git rev-parse HEAD)"

                coveragetype (optional, lcov|cobertura|jacoco|gocover, default is lcov)

                The type of coverage being sent

                removepath (optional)

                A file path segment that will be removed from paths in the coverage data. This makes it easier to
                map paths in coverage data to paths in the git repo.
                Line by line coverage will not be available if the coverage paths
                do not match the paths from the git project root.

                For example, if a path looks like /User/docs/build/file.js, use removepath=/User/docs/
                to map the path to build/file.js

                prependpath (optional)

                A file path segment that will be prepended to paths in the coverage data. This makes it easier to
                map paths in coverage data to paths in the git repo.
                Line by line coverage will not be available if the coverage paths
                do not match the paths from the git project root.

                For example, if a path looks like file.js, use prependpath=project/
                to map the path to project/file.js

                ispullrequest (optional)

                Pass a truthy value to force the commit_hash to show as a pull request.
                If you omit the value it will be retrieved from the GitHub API.
                This shows as a badge on the commit page.

Travis

This script can be used to work with Travis, passing the owner and repo instead of the token.
        Those values could also be hardcoded.

#!/bin/bash

# The location of the coverage file. Change this, depending on your Travis configuration, to point to the file.
COBERTURA_FILE="${TRAVIS_BUILD_DIR}/cobertura.xml"

if [[ "$TRAVIS_PULL_REQUEST" == "false" ]]; then
    # On a merge build, $TRAVIS_COMMIT is the merge commit
    LAST_COMMIT="${TRAVIS_COMMIT}"
else
    # For PRs, we have to do some more fiddling to get the proper commit hash ($TRAVIS_COMMIT is the hash of a merge
    # that Travis makes, not the hash of the last commit in the PR)
    LAST_COMMIT="${TRAVIS_COMMIT_RANGE##*...}"
fi

# Split the repo slug to get repo owner and name.
REPO_OWNER="${TRAVIS_REPO_SLUG%%/*}"
REPO_NAME="${TRAVIS_REPO_SLUG##*/}"

# Combine the git details into query parameters
GIT_PARAMS="owner=${REPO_OWNER}&repo=${REPO_NAME}&commit=${LAST_COMMIT}"

# Upload the PR coverage to the CVR server. Update the domain in this URL as appropriate.
curl \
    -F coverage=@"${COBERTURA_FILE}" \
    "https://cvr.vokal.io/coverage?coveragetype=cobertura&${GIT_PARAMS}"


text: Sanitized code samples of various projects I've done


text:
<?php
defined('IN_ADMIN') or exit('No permission resources.');
$show_dialog = $show_header = 1;
include $this->admin_tpl('header', 'admin');
?>

    <?php if(isset($big_menu)) echo ''.$big_menu[1].' ';?>
    <?php echo admin::submenu($_GET['menuid'],$big_menu); ?>|<a href="javascript:window.top.art.dialog({id:'setting',iframe:'?m=poster&c=space&a=setting', title:'<?php echo L('module_setting')?>', width:'540', height:'320'}, function(){var d = window.top.art.dialog({id:'setting'}).data.iframe;var form = d.document.getElementById('dosubmit');form.click();return false;}, function(){window.top.art.dialog({id:'setting'}).close()});void(0);"><?php echo L('module_setting')?>

<form name="myform" action="?m=poster&c=space&a=delete" method="post" id="myform">

            <input type="checkbox" value="" id="check_box" onclick="selectall('spaceid[]');">
			<?php echo L('boardtype')?>
			<?php echo L('ads_type')?>
			<?php echo L('size_format')?>
			<?php echo L('ads_num')?>
			<?php echo L('description')?>
			<?php echo L('operations_manage')?>

 <?php
if(is_array($infos)){
	foreach($infos as $info){
?>

	<input type="checkbox" name="spaceid[]" value="<?php echo $info['spaceid']?>">

	<?php echo $info['name']?>
	<?php echo $TYPES[$info['type']]?>
	<?php echo $info['width']?>*<?php echo $info['height']?>
	<?php echo $info['items']?>
	<?php echo $info['description']?>

	<a href="?m=poster&c=space&a=public_preview&spaceid=<?php echo $info['spaceid']?>" target="_blank"><?php echo L('preview')?> | <a href="javascript:call(<?php echo $info['spaceid']?>);void(0);"><?php echo L('get_code')?> | <a href='?m=poster&c=poster&a=init&spaceid=<?php echo $info['spaceid']?>&menuid=<?php echo $_GET['menuid']?>' ><?php echo L('ad_list')?> |
	<a href="###" onclick="edit(<?php echo $info['spaceid']?>, '<?php echo addslashes(new_html_special_chars($info['name']))?>')" title="<?php echo L('edit')?>" ><?php echo L('edit')?> |
	<a href='?m=poster&c=space&a=delete&spaceid=<?php echo $info['spaceid']?>' onClick="return confirm('<?php echo L('confirm', array('message' => addslashes(new_html_special_chars($info['name']))))?>')"><?php echo L('delete')?>
	| <a href="index.php?m=poster&c=poster&a=add&spaceid=<?php echo $info['spaceid']?>&menuid=<?php echo $_GET['menuid']?>&pc_hash=<?php echo $_SESSION['pc_hash']?>">添加广告

<?php
	}
}
?>

<?php echo L('selected_all')?>/<?php echo L('cancel')?>
		<input name="submit" type="submit" class="button" value="<?php echo L('remove_all_selected')?>" onClick="return confirm('<?php echo L('confirm', array('message' => L('selected')))?>')">

<?php echo $pages?>

</form>


text:
package ch.qos.logback.core.net.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * A {@link ServerListener} that accepts connections from remote receiver
 * component clients.
 *
 * @author Carl Harris
 */
class RemoteReceiverServerListener
    extends ServerSocketListener<RemoteReceiverClient> {

  /**
   * Constructs a new listener.
   * @param serverSocket server socket from which new client connections
   *    will be accepted
   */
  public RemoteReceiverServerListener(ServerSocket serverSocket) {
    super(serverSocket);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected RemoteReceiverClient createClient(String id, Socket socket)
      throws IOException {
    return new RemoteReceiverStreamClient(id, socket);
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer">

<title>
    Tags - Better Call Paper
</title>
<link href="/tags/index.xml" rel="alternate" type="application/rss+xml" title="Better Call Paper" />

<link rel="stylesheet" href="/css/main.min.3c9fa6b3264a9f8be4f27730f1d5f0ded496304d03812ed49d97703ffb28122a.css" integrity="sha256-PJ+msyZKn4vk8ncw8dXw3tSWME0DgS7UnZdwP/soEio=" crossorigin="anonymous" media="screen">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Didact+Gothic">

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Tags"/>
<meta name="twitter:description" content=""/>

<meta property="og:title" content="Tags" />
<meta property="og:description" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://paperhs.github.io/tags/" />

    <title>

        Tags

    </title>

Tags

            Better Call Paper

            ·
            writing

    ·


text:
package org.apache.jena.atlas.csv ;

import java.io.IOException ;
import java.io.InputStream ;
import java.io.Reader ;
import java.util.Iterator ;
import java.util.List ;
import java.util.function.Function;

import org.apache.commons.csv.CSVFormat ;
import org.apache.commons.csv.CSVRecord ;
import org.apache.jena.atlas.io.IO ;
import org.apache.jena.atlas.iterator.Iter ;

/**
 *  Wrapper for Commons CSV parser.
 */
public class CSVParser implements Iterable<List<String>>
{
    private final org.apache.commons.csv.CSVParser parser;
    private final Iterator<CSVRecord> iterator ;

    public static CSVParser create(String filename) {
        InputStream input = IO.openFile(filename) ;
        return create(input) ;
    }

    public static CSVParser create(InputStream input) {
        CSVParser parser = new CSVParser(IO.asBufferedUTF8(input)) ;
        return parser ;
    }

    /** Be careful about charsets */
    public static CSVParser create(Reader input) {
        CSVParser parser = new CSVParser(input) ;
        return parser ;
    }

    private CSVParser(Reader input) {
        try {
            this.parser = CSVFormat.RFC4180.parse(input);
            this.iterator = parser.iterator() ;
        } catch (IOException e) {
            throw new CSVParseException("Failed to create the CSV parser: " + e.getMessage(), e);
        }
    }

    private static Function<CSVRecord, List<String>> transform = rec -> recordToList(rec) ;

    @Override
    public Iterator<List<String>> iterator() {
        return Iter.map(iterator, transform) ;
    }

    public List<String> parse1() {
        if (iterator.hasNext())
             return recordToList(iterator.next()) ;
        return null;
    }

    private static List<String> recordToList(CSVRecord record) {
        return Iter.toList(record.iterator()) ;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<odoo>
	<data noupdate="0">
		<record id="group_lounge_user" model="res.groups">
            <field name="name">User</field>
            <field name="category_id" ref="point_of_lounge.module_category_point_of_lounge"/>
        </record>
	    <record id="group_lounge_manager" model="res.groups">
	        <field name="name">Manager</field>
	        <field name="category_id" ref="point_of_lounge.module_category_point_of_lounge"/>
	        <field name="implied_ids" eval="[(4, ref('group_lounge_user')), (4, ref('stock.group_stock_user'))]"/>
	        <field name="users" eval="[(4, ref('base.user_root'))]"/>
	    </record>
	</data>
	<data>
		<record id="point_of_lounge_session_group_lounge_user" model="ir.rule">
            <field name="name">user: modify own session only</field>
            <field name="model_id" ref="model_lounge_session"/>
            <field name="domain_force">[('user_id','=',user.id)]</field>
            <field name="groups" eval="[(4,ref('point_of_lounge.group_lounge_user'))]"/>
        </record>
	</data>
</odoo>


text:
layout: app
title: TryToFLAC User Manual
subtitle: Documentation
comments: false
product: TryToFLAC
current: docs
---

# MANUAL
## TryToFLAC
A FLAC audio converter for Mac

Version 4.0

 ### **Preface**:

>Do you think MP3 audio files cannot fit your desire for music?

>Do you enjoy high-quality audio file and better listening experience?

>Have you got into trouble when you put other audio formats into your player?

  If you answered "yes" to at least one of these questions, then TryToFLAC is definitely designed for you. If you are interested to know more about this product, and how the product can help you in your life, just read more below, and have a try, you can simply enjoy the excellent user experience by our company.

 ### **Introduction**:
FLAC, which stands for Free Lossless Audio Codec, an audio format similar to MP3, but lossless, meaning that audio is compressed in FLAC without any loss in quality. This is similar to how Zip works, except with FLAC you will get much better compression because it is designed specifically for audio, and you can play back compressed FLAC files in your favorite player just like you would an MP3 file, such as your home stereo, your car or your phones. This converter lets you also easily extract audio from video files in high quality.

TryToFLAC is an FLAC audio converter tool which aims to convert various audio formats to the FLAC format. The software is made for Mac users only (MacOSX 10.7 mac OS (64-bit) or newer is required). The software is so convenient that users can easily get the conversion result by simply clicking one button in it. Most audio formats in Internet can be intelligently recognized by TryToFLAC and transfered as FLAC format. The conversion process in our product is simple and efficient, users will be released from annoying ads, bundled softwares, plug-ins, even log in and registration. By simply enjoying the swift, comfortable operation of TryToFLAC, you are able to join our community and get our excellent after-sale services.

### **Installation**:
TryToFLAC runs on Mac only, MacOSX 10.7 mac OS (64-bit) or newer is required. A new version 4.0 is updated recently. Older version is also provided in Older Releases in [DOWNLOAD](./download.html).

There are three kinds of install package in DOWNLOAD page, you need to choose one suitable package, click it and wait for the downloading. Then choose a suitable folder to put the software in and click "open" to run it.

**The trial version** for users is also available in [DOWNLOAD](./download.html), and combined with the install package.

 You can click and download one of the files. when you open and run the software, a little window will pop up. If you choose to try out, click "continue" button, you can freely try this software three times. If you wanna to buy our product, then click "Buy" button to enter the online store.

![](./images/screens/trytoflac_trialversion_1440x900.png)

If you encounter any problems during or after installing TryToFLAC please refer to [Frequently Asked Questions (FAQ)](./faq.html) first.

### **User Guide**:
This section describes daily use guide to the TryToFLAC client. It instructs you how to use the software in details after the installation finished.
1. Firstly, you need to open the file and run it, the window of TryToFLAC will pop up in the desktop. As what have mentioned before, if you want to try out this software first, click "continue" to use the trial version, you have three chances to try it freely. If you satisfied with our product,and decided to pay for it, please click the "Buy" button or directly come to our home page and enter the [BUY ONLINE](./buy.html).

2. Secondly, in the BUY ONLINE page, there are two optional purchase link for you, that is, you can choose to buy from our **official App store** or the Apple App store. The good news is, we offer a **coupon code** below the purchase link for anyone who willing to buy from the Gmagon official App store.

![](./images/screens/trytoflac_onlinestore_800x500.png)

3. Thirdly, in the Gmagon Online Store, you need to put the product in your cart, fill the Billing Information, choose your payment information, and then finish the whole purchase process.

![](./images/screens/trytoflac_couponcode_800x500.png)

4. Finally, after you finished the purchasing process of the product, you can get the **active code** from us. When you run the software, a registered window will pop up, then you need to copy and paste the active code in the **license key** text box, then click "register" button to finish the License Activation.

![](./images/screens/trytoflac_lisencekey_1440x900.png)

Hope the TryToFLAC will help you enjoy a high-quality listening experience and make your life more convenient than ever. We'd like to receive and answer any question from you, if you are willing to communicate with us in  Support Center  and join our community. We will strive to provide the best services we can offer with our customers.


text:
using System;
using numl.Model;
using System.Linq;
using numl.Math.Functions;
using numl.Math.LinearAlgebra;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;

namespace numl.Supervised.NeuralNetwork
{
    /// A network.
    [XmlRoot("Network")]
    public class Network : IXmlSerializable
    {
        /// Gets or sets the in.
        /// <value>The in.</value>
        public Node[] In { get; set; }
        /// Gets or sets the out.
        /// <value>The out.</value>
        public Node[] Out { get; set; }
        /// Defaults.
        /// <param name="d">The Descriptor to process.</param>
        /// <param name="x">The Vector to process.</param>
        /// <param name="y">The Vector to process.</param>
        /// <param name="activation">The activation.</param>
        /// <returns>A Network.</returns>
        public static Network Default(Descriptor d, Matrix x, Vector y, IFunction activation)
        {
            Network nn = new Network();
            // set output to number of choices of available
            // 1 if only two choices
            int distinct = y.Distinct().Count();
            int output = distinct > 2 ? distinct : 1;
            // identity funciton for bias nodes
            IFunction ident = new Ident();

            // set number of hidden units to (Input + Hidden) * 2/3 as basic best guess.
            int hidden = (int)System.Math.Ceiling((decimal)(x.Cols + output) * 2m / 3m);

            // creating input nodes
            nn.In = new Node[x.Cols + 1];
            nn.In[0] = new Node { Label = "B0", Activation = ident };
            for (int i = 1; i < x.Cols + 1; i++)
                nn.In[i] = new Node { Label = d.ColumnAt(i - 1), Activation = ident };

            // creating hidden nodes
            Node[] h = new Node[hidden + 1];
            h[0] = new Node { Label = "B1", Activation = ident };
            for (int i = 1; i < hidden + 1; i++)
                h[i] = new Node { Label = String.Format("H{0}", i), Activation = activation };

            // creating output nodes
            nn.Out = new Node[output];
            for (int i = 0; i < output; i++)
                nn.Out[i] = new Node { Label = GetLabel(i, d), Activation = activation };

            // link input to hidden. Note: there are
            // no inputs to the hidden bias node
            for (int i = 1; i < h.Length; i++)
                for (int j = 0; j < nn.In.Length; j++)
                    Edge.Create(nn.In[j], h[i]);

            // link from hidden to output (full)
            for (int i = 0; i < nn.Out.Length; i++)
                for (int j = 0; j < h.Length; j++)
                    Edge.Create(h[j], nn.Out[i]);

            return nn;
        }
        /// Gets a label.
        /// <param name="n">The Node to process.</param>
        /// <param name="d">The Descriptor to process.</param>
        /// <returns>The label.</returns>
        private static string GetLabel(int n, Descriptor d)
        {
            if (d.Label.Type.IsEnum)
                return Enum.GetName(d.Label.Type, n);
            else if (d.Label is StringProperty && ((StringProperty)d.Label).AsEnum)
                return ((StringProperty)d.Label).Dictionary[n];
            else return d.Label.Name;
        }
        /// Forwards the given x coordinate.
        /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
        /// <param name="x">The Vector to process.</param>
        public void Forward(Vector x)
        {
            if (In.Length != x.Length + 1)
                throw new InvalidOperationException("Input nodes not aligned to input vector");

            // set input
            for (int i = 0; i < In.Length; i++)
                In[i].Input = In[i].Output = i == 0 ? 1 : x[i - 1];
            // evaluate
            for (int i = 0; i < Out.Length; i++)
                Out[i].Evaluate();
        }
        /// Backs.
        /// <param name="t">The double to process.</param>
        /// <param name="learningRate">The learning rate.</param>
        public void Back(double t, double learningRate)
        {
            // propagate error gradients
            for (int i = 0; i < In.Length; i++)
                In[i].Error(t);

            // reset weights
            for (int i = 0; i < Out.Length; i++)
                Out[i].Update(learningRate);
        }
        ///
        /// This method is reserved and should not be used. When implementing the IXmlSerializable
        /// interface, you should return null (Nothing in Visual Basic) from this method, and instead, if
        /// specifying a custom schema is required, apply the
        /// <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute" /> to the class.
        ///
        /// <returns>
        /// An <see cref="T:System.Xml.Schema.XmlSchema" /> that describes the XML representation of the
        /// object that is produced by the
        /// <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)" />
        /// method and consumed by the
        /// <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)" />
        /// method.
        /// </returns>
        public XmlSchema GetSchema()
        {
            return null;
        }
        /// Generates an object from its XML representation.
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader" /> stream from which the object is
        /// deserialized.</param>
        public void ReadXml(XmlReader reader)
        {
            XmlSerializer nSerializer = new XmlSerializer(typeof(Node));
            XmlSerializer eSerializer = new XmlSerializer(typeof(Edge));

            reader.MoveToContent();

            Dictionary<string, Node> nodes = new Dictionary<string, Node>();
            int length = 0;
            reader.ReadStartElement();
            length = int.Parse(reader.GetAttribute("Length"));
            reader.ReadStartElement("Nodes");
            for (int i = 0; i < length; i++)
            {
                var node = (Node)nSerializer.Deserialize(reader);
                nodes.Add(node.Id, node);
                reader.Read();
            }
            reader.ReadEndElement();

            length = int.Parse(reader.GetAttribute("Length"));
            reader.ReadStartElement("Edges");
            for (int i = 0; i < length; i++)
            {
                var edge = (Edge)eSerializer.Deserialize(reader);
                reader.Read();

                edge.Source = nodes[edge.SourceId];
                edge.Target = nodes[edge.TargetId];

                edge.Source.Out.Add(edge);
                edge.Target.In.Add(edge);
            }
            reader.ReadEndElement();

            length = int.Parse(reader.GetAttribute("Length"));
            reader.ReadStartElement("In");
            In = new Node[length];
            for (int i = 0; i < length; i++)
            {
                reader.MoveToContent();
                In[i] = nodes[reader.GetAttribute("Id")];
                reader.Read();

            }
            reader.ReadEndElement();

            length = int.Parse(reader.GetAttribute("Length"));
            reader.ReadStartElement("Out");
            Out = new Node[length];
            for (int i = 0; i < length; i++)
            {
                reader.MoveToContent();
                Out[i] = nodes[reader.GetAttribute("Id")];
                reader.Read();

            }
            reader.ReadEndElement();
        }
        /// Converts an object into its XML representation.
        /// <param name="writer">The <see cref="T:System.Xml.XmlWriter" /> stream to which the object is
        /// serialized.</param>
        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer nSerializer = new XmlSerializer(typeof(Node));
            XmlSerializer eSerializer = new XmlSerializer(typeof(Edge));

            var nodes = GetNodes().ToArray();
            writer.WriteStartElement("Nodes");
            writer.WriteAttributeString("Length", nodes.Length.ToString());
            foreach (var node in nodes)
                nSerializer.Serialize(writer, node);

            writer.WriteEndElement();

            var edges = GetEdges().ToArray();
            writer.WriteStartElement("Edges");
            writer.WriteAttributeString("Length", edges.Length.ToString());
            foreach (var edge in edges)
                eSerializer.Serialize(writer, edge);

            writer.WriteEndElement();

            writer.WriteStartElement("In");
            writer.WriteAttributeString("Length", In.Length.ToString());
            for (int i = 0; i < In.Length; i++)
            {
                writer.WriteStartElement("Node");
                writer.WriteAttributeString("Id", In[i].Id);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();

            writer.WriteStartElement("Out");
            writer.WriteAttributeString("Length", Out.Length.ToString());
            for (int i = 0; i < Out.Length; i++)
            {
                writer.WriteStartElement("Node");
                writer.WriteAttributeString("Id", Out[i].Id);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }

        /// The nodes.
        private HashSet<string> _nodes;
        /// Gets the nodes in this collection.
        /// <returns>
        /// An enumerator that allows foreach to be used to process the nodes in this collection.
        /// </returns>
        public IEnumerable<Node> GetNodes()
        {
            if (_nodes == null) _nodes = new HashSet<string>();
            else _nodes.Clear();

            foreach (var node in Out)
            {
                _nodes.Add(node.Id);
                yield return node;
                foreach (var n in GetNodes(node))
                {
                    if (!_nodes.Contains(n.Id))
                    {
                        _nodes.Add(n.Id);
                        yield return n;
                    }
                }
            }
        }
        /// Gets the nodes in this collection.
        /// <param name="n">The Node to process.</param>
        /// <returns>
        /// An enumerator that allows foreach to be used to process the nodes in this collection.
        /// </returns>
        private IEnumerable<Node> GetNodes(Node n)
        {
            foreach (var edge in n.In)
            {
                yield return edge.Source;
                foreach (var node in GetNodes(edge.Source))
                    yield return node;
            }
        }

        /// The edges.
        private HashSet<Tuple<string, string>> _edges;
        /// Gets the edges in this collection.
        /// <returns>
        /// An enumerator that allows foreach to be used to process the edges in this collection.
        /// </returns>
        public IEnumerable<Edge> GetEdges()
        {
            if (_edges == null) _edges = new HashSet<Tuple<string, string>>();
            else _edges.Clear();

            foreach (var node in Out)
            {
                foreach (var edge in GetEdges(node))
                {
                    var key = new Tuple<string, string>(edge.Source.Id, edge.Target.Id);
                    if (!_edges.Contains(key))
                    {
                        _edges.Add(key);
                        yield return edge;
                    }
                }
            }
        }
        /// Gets the edges in this collection.
        /// <param name="n">The Node to process.</param>
        /// <returns>
        /// An enumerator that allows foreach to be used to process the edges in this collection.
        /// </returns>
        private IEnumerable<Edge> GetEdges(Node n)
        {
            foreach (var edge in n.In)
            {
                yield return edge;
                foreach (var e in GetEdges(edge.Source))
                    yield return e;
            }
        }
    }
}


text:
package io.airlift.stats;

import org.weakref.jmx.Managed;

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

public class Distribution
{
    private final static double MAX_ERROR = 0.01;

    private final QuantileDigest digest;

    public Distribution()
    {
        digest = new QuantileDigest(MAX_ERROR);
    }

    public Distribution(double alpha)
    {
        digest = new QuantileDigest(MAX_ERROR, alpha);
    }

    public void add(long value)
    {
        digest.add(value);
    }

    @Managed
    public double getMaxError()
    {
        return digest.getConfidenceFactor();
    }

    @Managed
    public double getCount()
    {
        return digest.getCount();
    }

    @Managed
    public long getP50()
    {
        return digest.getQuantile(0.5);
    }

    @Managed
    public long getP75()
    {
        return digest.getQuantile(0.75);
    }

    @Managed
    public long getP90()
    {
        return digest.getQuantile(0.90);
    }

    @Managed
    public long getP95()
    {
        return digest.getQuantile(0.95);
    }

    @Managed
    public long getP99()
    {
        return digest.getQuantile(0.99);
    }

    @Managed
    public long getMin()
    {
        return digest.getMin();
    }

    @Managed
    public long getMax()
    {
        return digest.getMax();
    }

    @Managed
    public Map<Double, Long> getPercentiles()
    {
        List<Double> percentiles = new ArrayList<Double>(100);
        for (int i = 0; i < 100; ++i) {
            percentiles.add(i / 100.0);
        }

        List<Long> values = digest.getQuantiles(percentiles);

        Map<Double, Long> result = new LinkedHashMap<Double, Long>(values.size());
        for (int i = 0; i < percentiles.size(); ++i) {
            result.put(percentiles.get(i), values.get(i));
        }

        return result;
    }
}


text:
import { Tag } from "../interfaces/Tag";
import { useApiData } from "./useApiData";

export const useTags = () =>
  (useApiData<Tag[]>("/api/directory/tags") || []).sort((a: Tag, b: Tag) =>
    a.name.localeCompare(b.name)
  );


text:
package org.apache.hadoop.hbase.replication.regionserver;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.Cell.Type;
import org.apache.hadoop.hbase.CellBuilderFactory;
import org.apache.hadoop.hbase.CellBuilderType;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.ReplicationPeerNotFoundException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.Waiter;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ClusterConnection;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.regionserver.Region;
import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
import org.apache.hadoop.hbase.replication.ReplicationException;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
import org.apache.hadoop.hbase.testclassification.FlakeyTests;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSTableDescriptors;
import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
import org.apache.hadoop.hbase.wal.WAL.Entry;
import org.apache.hadoop.hbase.wal.WALEdit;
import org.apache.hadoop.hbase.wal.WALKeyImpl;
import org.apache.hadoop.hbase.zookeeper.ZKConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
import org.apache.hbase.thirdparty.com.google.common.util.concurrent.Uninterruptibles;

/**
 * Tests RegionReplicaReplicationEndpoint class by setting up region replicas and verifying async
 * wal replication replays the edits to the secondary region in various scenarios.
 */
@Category({ FlakeyTests.class, LargeTests.class })
public class TestRegionReplicaReplicationEndpoint {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestRegionReplicaReplicationEndpoint.class);

  private static final Logger LOG =
    LoggerFactory.getLogger(TestRegionReplicaReplicationEndpoint.class);

  private static final int NB_SERVERS = 2;

  private static final HBaseTestingUtility HTU = new HBaseTestingUtility();

  @Rule
  public TestName name = new TestName();

  @BeforeClass
  public static void beforeClass() throws Exception {
    Configuration conf = HTU.getConfiguration();
    conf.setFloat("hbase.regionserver.logroll.multiplier", 0.0003f);
    conf.setInt("replication.source.size.capacity", 10240);
    conf.setLong("replication.source.sleepforretries", 100);
    conf.setInt("hbase.regionserver.maxlogs", 10);
    conf.setLong("hbase.master.logcleaner.ttl", 10);
    conf.setInt("zookeeper.recovery.retry", 1);
    conf.setInt("zookeeper.recovery.retry.intervalmill", 10);
    conf.setBoolean(ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_CONF_KEY, true);
    conf.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);
    conf.setInt("replication.stats.thread.period.seconds", 5);
    conf.setBoolean("hbase.tests.use.shortcircuit.reads", false);
    conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5); // less number of retries is needed
    conf.setInt(HConstants.HBASE_CLIENT_SERVERSIDE_RETRIES_MULTIPLIER, 1);

    HTU.startMiniCluster(NB_SERVERS);
  }

  @AfterClass
  public static void afterClass() throws Exception {
    HTU.shutdownMiniCluster();
  }

  @Test
  public void testRegionReplicaReplicationPeerIsCreated() throws IOException, ReplicationException {
    // create a table with region replicas. Check whether the replication peer is created
    // and replication started.
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
      Admin admin = connection.getAdmin()) {
      String peerId = ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_PEER;

      ReplicationPeerConfig peerConfig = null;
      try {
        peerConfig = admin.getReplicationPeerConfig(peerId);
      } catch (ReplicationPeerNotFoundException e) {
        LOG.warn("Region replica replication peer id=" + peerId + " not exist", e);
      }

      try {
        peerConfig = admin.getReplicationPeerConfig(peerId);
      } catch (ReplicationPeerNotFoundException e) {
        LOG.warn("Region replica replication peer id=" + peerId + " not exist", e);
      }

      if (peerConfig != null) {
        admin.removeReplicationPeer(peerId);
        peerConfig = null;
      }

      HTableDescriptor htd =
        HTU.createTableDescriptor("testReplicationPeerIsCreated_no_region_replicas");
      createOrEnableTableWithRetries(htd, true);
      try {
        peerConfig = admin.getReplicationPeerConfig(peerId);
        fail("Should throw ReplicationException, because replication peer id=" + peerId
          + " not exist");
      } catch (ReplicationPeerNotFoundException e) {
      }
      assertNull(peerConfig);

      htd = HTU.createTableDescriptor("testReplicationPeerIsCreated");
      htd.setRegionReplication(2);
      createOrEnableTableWithRetries(htd, true);

      // assert peer configuration is correct
      peerConfig = admin.getReplicationPeerConfig(peerId);
      assertNotNull(peerConfig);
      assertEquals(peerConfig.getClusterKey(),
        ZKConfig.getZooKeeperClusterKey(HTU.getConfiguration()));
      assertEquals(RegionReplicaReplicationEndpoint.class.getName(),
        peerConfig.getReplicationEndpointImpl());
    }
  }

  @Test
  public void testRegionReplicaReplicationPeerIsCreatedForModifyTable() throws Exception {
    // modify a table by adding region replicas. Check whether the replication peer is created
    // and replication started.
    try (Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
      Admin admin = connection.getAdmin()) {
      String peerId = ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_PEER;
      ReplicationPeerConfig peerConfig = null;
      try {
        peerConfig = admin.getReplicationPeerConfig(peerId);
      } catch (ReplicationPeerNotFoundException e) {
        LOG.warn("Region replica replication peer id=" + peerId + " not exist", e);
      }

      if (peerConfig != null) {
        admin.removeReplicationPeer(peerId);
        peerConfig = null;
      }

      HTableDescriptor htd =
        HTU.createTableDescriptor("testRegionReplicaReplicationPeerIsCreatedForModifyTable");
      createOrEnableTableWithRetries(htd, true);

      // assert that replication peer is not created yet
      try {
        peerConfig = admin.getReplicationPeerConfig(peerId);
        fail("Should throw ReplicationException, because replication peer id=" + peerId
          + " not exist");
      } catch (ReplicationPeerNotFoundException e) {
      }
      assertNull(peerConfig);

      HTU.getAdmin().disableTable(htd.getTableName());
      htd.setRegionReplication(2);
      HTU.getAdmin().modifyTable(htd.getTableName(), htd);
      createOrEnableTableWithRetries(htd, false);

      // assert peer configuration is correct
      peerConfig = admin.getReplicationPeerConfig(peerId);
      assertNotNull(peerConfig);
      assertEquals(peerConfig.getClusterKey(),
        ZKConfig.getZooKeeperClusterKey(HTU.getConfiguration()));
      assertEquals(RegionReplicaReplicationEndpoint.class.getName(),
        peerConfig.getReplicationEndpointImpl());
      admin.close();
    }
  }

  public void testRegionReplicaReplication(int regionReplication) throws Exception {
    // test region replica replication. Create a table with single region, write some data
    // ensure that data is replicated to the secondary region
    TableName tableName =
      TableName.valueOf("testRegionReplicaReplicationWithReplicas_" + regionReplication);
    HTableDescriptor htd = HTU.createTableDescriptor(tableName.toString());
    htd.setRegionReplication(regionReplication);
    createOrEnableTableWithRetries(htd, true);
    TableName tableNameNoReplicas =
      TableName.valueOf("testRegionReplicaReplicationWithReplicas_NO_REPLICAS");
    HTU.deleteTableIfAny(tableNameNoReplicas);
    HTU.createTable(tableNameNoReplicas, HBaseTestingUtility.fam1);

    Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
    Table table = connection.getTable(tableName);
    Table tableNoReplicas = connection.getTable(tableNameNoReplicas);

    try {
      // load some data to the non-replicated table
      HTU.loadNumericRows(tableNoReplicas, HBaseTestingUtility.fam1, 6000, 7000);

      // load the data to the table
      HTU.loadNumericRows(table, HBaseTestingUtility.fam1, 0, 1000);

      verifyReplication(tableName, regionReplication, 0, 1000);

    } finally {
      table.close();
      tableNoReplicas.close();
      HTU.deleteTableIfAny(tableNameNoReplicas);
      connection.close();
    }
  }

  private void verifyReplication(TableName tableName, int regionReplication, final int startRow,
    final int endRow) throws Exception {
    verifyReplication(tableName, regionReplication, startRow, endRow, true);
  }

  private void verifyReplication(TableName tableName, int regionReplication, final int startRow,
    final int endRow, final boolean present) throws Exception {
    // find the regions
    final Region[] regions = new Region[regionReplication];

    for (int i = 0; i < NB_SERVERS; i++) {
      HRegionServer rs = HTU.getMiniHBaseCluster().getRegionServer(i);
      List<HRegion> onlineRegions = rs.getRegions(tableName);
      for (HRegion region : onlineRegions) {
        regions[region.getRegionInfo().getReplicaId()] = region;
      }
    }

    for (Region region : regions) {
      assertNotNull(region);
    }

    for (int i = 1; i < regionReplication; i++) {
      final Region region = regions[i];
      // wait until all the data is replicated to all secondary regions
      Waiter.waitFor(HTU.getConfiguration(), 90000, 1000, new Waiter.Predicate<Exception>() {
        @Override
        public boolean evaluate() throws Exception {
          LOG.info("verifying replication for region replica:" + region.getRegionInfo());
          try {
            HTU.verifyNumericRows(region, HBaseTestingUtility.fam1, startRow, endRow, present);
          } catch (Throwable ex) {
            LOG.warn("Verification from secondary region is not complete yet", ex);
            // still wait
            return false;
          }
          return true;
        }
      });
    }
  }

  @Test
  public void testRegionReplicaReplicationWith2Replicas() throws Exception {
    testRegionReplicaReplication(2);
  }

  @Test
  public void testRegionReplicaReplicationWith3Replicas() throws Exception {
    testRegionReplicaReplication(3);
  }

  @Test
  public void testRegionReplicaReplicationWith10Replicas() throws Exception {
    testRegionReplicaReplication(10);
  }

  @Test
  public void testRegionReplicaWithoutMemstoreReplication() throws Exception {
    int regionReplication = 3;
    final TableName tableName = TableName.valueOf(name.getMethodName());
    HTableDescriptor htd = HTU.createTableDescriptor(tableName);
    htd.setRegionReplication(regionReplication);
    htd.setRegionMemstoreReplication(false);
    createOrEnableTableWithRetries(htd, true);

    Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
    Table table = connection.getTable(tableName);
    try {
      // write data to the primary. The replicas should not receive the data
      final int STEP = 100;
      for (int i = 0; i < 3; ++i) {
        final int startRow = i * STEP;
        final int endRow = (i + 1) * STEP;
        LOG.info("Writing data from " + startRow + " to " + endRow);
        HTU.loadNumericRows(table, HBaseTestingUtility.fam1, startRow, endRow);
        verifyReplication(tableName, regionReplication, startRow, endRow, false);

        // Flush the table, now the data should show up in the replicas
        LOG.info("flushing table");
        HTU.flush(tableName);
        verifyReplication(tableName, regionReplication, 0, endRow, true);
      }
    } finally {
      table.close();
      connection.close();
    }
  }

  @Test
  public void testRegionReplicaReplicationForFlushAndCompaction() throws Exception {
    // Tests a table with region replication 3. Writes some data, and causes flushes and
    // compactions. Verifies that the data is readable from the replicas. Note that this
    // does not test whether the replicas actually pick up flushed files and apply compaction
    // to their stores
    int regionReplication = 3;
    final TableName tableName = TableName.valueOf(name.getMethodName());
    HTableDescriptor htd = HTU.createTableDescriptor(tableName);
    htd.setRegionReplication(regionReplication);
    createOrEnableTableWithRetries(htd, true);

    Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
    Table table = connection.getTable(tableName);
    try {
      // load the data to the table

      for (int i = 0; i < 6000; i += 1000) {
        LOG.info("Writing data from " + i + " to " + (i + 1000));
        HTU.loadNumericRows(table, HBaseTestingUtility.fam1, i, i + 1000);
        LOG.info("flushing table");
        HTU.flush(tableName);
        LOG.info("compacting table");
        HTU.compact(tableName, false);
      }

      verifyReplication(tableName, regionReplication, 0, 1000);
    } finally {
      table.close();
      connection.close();
    }
  }

  @Test
  public void testRegionReplicaReplicationIgnoresDisabledTables() throws Exception {
    testRegionReplicaReplicationIgnores(false, false);
  }

  @Test
  public void testRegionReplicaReplicationIgnoresDroppedTables() throws Exception {
    testRegionReplicaReplicationIgnores(true, false);
  }

  @Test
  public void testRegionReplicaReplicationIgnoresNonReplicatedTables() throws Exception {
    testRegionReplicaReplicationIgnores(false, true);
  }

  public void testRegionReplicaReplicationIgnores(boolean dropTable, boolean disableReplication)
    throws Exception {

    // tests having edits from a disabled or dropped table is handled correctly by skipping those
    // entries and further edits after the edits from dropped/disabled table can be replicated
    // without problems.
    final TableName tableName = TableName.valueOf(
      name.getMethodName() + "_drop_" + dropTable + "_disabledReplication_" + disableReplication);
    HTableDescriptor htd = HTU.createTableDescriptor(tableName);
    int regionReplication = 3;
    htd.setRegionReplication(regionReplication);
    HTU.deleteTableIfAny(tableName);

    createOrEnableTableWithRetries(htd, true);
    TableName toBeDisabledTable = TableName.valueOf(
      dropTable ? "droppedTable" : (disableReplication ? "disableReplication" : "disabledTable"));
    HTU.deleteTableIfAny(toBeDisabledTable);
    htd = HTU.createTableDescriptor(toBeDisabledTable.toString());
    htd.setRegionReplication(regionReplication);
    createOrEnableTableWithRetries(htd, true);

    // both tables are created, now pause replication
    HTU.getAdmin().disableReplicationPeer(ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_PEER);

    // now that the replication is disabled, write to the table to be dropped, then drop the table.

    Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
    Table table = connection.getTable(tableName);
    Table tableToBeDisabled = connection.getTable(toBeDisabledTable);

    HTU.loadNumericRows(tableToBeDisabled, HBaseTestingUtility.fam1, 6000, 7000);

    AtomicLong skippedEdits = new AtomicLong();
    RegionReplicaReplicationEndpoint.RegionReplicaOutputSink sink =
      mock(RegionReplicaReplicationEndpoint.RegionReplicaOutputSink.class);
    when(sink.getSkippedEditsCounter()).thenReturn(skippedEdits);
    FSTableDescriptors fstd =
      new FSTableDescriptors(FileSystem.get(HTU.getConfiguration()), HTU.getDefaultRootDirPath());
    RegionReplicaReplicationEndpoint.RegionReplicaSinkWriter sinkWriter =
      new RegionReplicaReplicationEndpoint.RegionReplicaSinkWriter(sink,
        (ClusterConnection) connection, Executors.newSingleThreadExecutor(), Integer.MAX_VALUE,
        fstd);
    RegionLocator rl = connection.getRegionLocator(toBeDisabledTable);
    HRegionLocation hrl = rl.getRegionLocation(HConstants.EMPTY_BYTE_ARRAY);
    byte[] encodedRegionName = hrl.getRegionInfo().getEncodedNameAsBytes();

    Cell cell = CellBuilderFactory.create(CellBuilderType.DEEP_COPY).setRow(Bytes.toBytes("A"))
      .setFamily(HTU.fam1).setValue(Bytes.toBytes("VAL")).setType(Type.Put).build();
    Entry entry =
      new Entry(new WALKeyImpl(encodedRegionName, toBeDisabledTable, 1), new WALEdit().add(cell));

    HTU.getAdmin().disableTable(toBeDisabledTable); // disable the table
    if (dropTable) {
      HTU.getAdmin().deleteTable(toBeDisabledTable);
    } else if (disableReplication) {
      htd.setRegionReplication(regionReplication - 2);
      HTU.getAdmin().modifyTable(toBeDisabledTable, htd);
      createOrEnableTableWithRetries(htd, false);
    }
    sinkWriter.append(toBeDisabledTable, encodedRegionName, HConstants.EMPTY_BYTE_ARRAY,
      Lists.newArrayList(entry, entry));

    assertEquals(2, skippedEdits.get());

    HRegionServer rs = HTU.getMiniHBaseCluster().getRegionServer(0);
    MetricsSource metrics = mock(MetricsSource.class);
    ReplicationEndpoint.Context ctx = new ReplicationEndpoint.Context(HTU.getConfiguration(),
      HTU.getConfiguration(), HTU.getTestFileSystem(),
      ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_PEER, UUID.fromString(rs.getClusterId()),
      rs.getReplicationSourceService().getReplicationManager().getReplicationPeers()
        .getPeer(ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_PEER),
      metrics, rs.getTableDescriptors(), rs);
    RegionReplicaReplicationEndpoint rrpe = new RegionReplicaReplicationEndpoint();
    rrpe.init(ctx);
    rrpe.start();
    ReplicationEndpoint.ReplicateContext repCtx = new ReplicationEndpoint.ReplicateContext();
    repCtx.setEntries(Lists.newArrayList(entry, entry));
    assertTrue(rrpe.replicate(repCtx));
    /*
     * Come back here. There is a difference on how counting is done here and in master branch.
     * St.Ack Mockito.verify(metrics, Mockito.times(1)). incrLogEditsFiltered(Mockito.eq(2L));
     */
    rrpe.stop();
    if (disableReplication) {
      // enable replication again so that we can verify replication
      HTU.getAdmin().disableTable(toBeDisabledTable); // disable the table
      htd.setRegionReplication(regionReplication);
      HTU.getAdmin().modifyTable(toBeDisabledTable, htd);
      createOrEnableTableWithRetries(htd, false);
    }

    try {
      // load some data to the to-be-dropped table

      // load the data to the table
      HTU.loadNumericRows(table, HBaseTestingUtility.fam1, 0, 1000);

      // now enable the replication
      HTU.getAdmin().enableReplicationPeer(ServerRegionReplicaUtil.REGION_REPLICA_REPLICATION_PEER);

      verifyReplication(tableName, regionReplication, 0, 1000);

    } finally {
      table.close();
      rl.close();
      tableToBeDisabled.close();
      HTU.deleteTableIfAny(toBeDisabledTable);
      connection.close();
    }
  }

  private void createOrEnableTableWithRetries(TableDescriptor htd, boolean createTableOperation) {
    // Helper function to run create/enable table operations with a retry feature
    boolean continueToRetry = true;
    int tries = 0;
    while (continueToRetry && tries < 50) {
      try {
        continueToRetry = false;
        if (createTableOperation) {
          HTU.getAdmin().createTable(htd);
        } else {
          HTU.getAdmin().enableTable(htd.getTableName());
        }
      } catch (IOException e) {
        if (e.getCause() instanceof ReplicationException) {
          continueToRetry = true;
          tries++;
          Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
        }
      }
    }
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.Editor.Mocks
{
    [ExcludeFromCodeCoverage]
    public sealed class ContentTypeRegistryServiceMock : IContentTypeRegistryService
    {
        private List<IContentType> _contentTypes = new List<IContentType>();

        public ContentTypeRegistryServiceMock(IEnumerable<string> contentTypeNames)
        {
            foreach(string name in contentTypeNames)
            {
                _contentTypes.Add(new ContentTypeMock(name));
            }
        }

        public IEnumerable<IContentType> ContentTypes
        {
            get { return _contentTypes; }
        }

        public IContentType UnknownContentType
        {
            get { return new ContentTypeMock("unknown"); }
        }

        public IContentType AddContentType(string typeName, IEnumerable<string> baseTypeNames)
        {
            throw new NotImplementedException();
        }

        public IContentType GetContentType(string typeName)
        {
            return _contentTypes.FirstOrDefault((IContentType ct) => { return ct.TypeName == typeName; });
        }

        public void RemoveContentType(string typeName)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package io.pravega.controller.server.eventProcessor.requesthandlers;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import io.pravega.client.stream.ReaderGroupConfig;
import io.pravega.client.stream.Stream;
import io.pravega.common.Exceptions;
import io.pravega.common.Timer;
import io.pravega.common.concurrent.Futures;
import io.pravega.common.tracing.TagLogger;
import io.pravega.controller.metrics.StreamMetrics;
import io.pravega.controller.retryable.RetryableException;
import io.pravega.controller.store.stream.OperationContext;
import io.pravega.controller.store.stream.StreamMetadataStore;
import io.pravega.controller.task.Stream.StreamMetadataTasks;
import io.pravega.controller.util.RetryHelper;
import io.pravega.shared.NameUtils;
import io.pravega.shared.controller.event.UpdateReaderGroupEvent;
import io.pravega.shared.protocol.netty.ConnectionFailedException;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Predicate;

/**
 * Request handler for executing a create operation for a ReaderGroup.
 */
public class UpdateReaderGroupTask implements ReaderGroupTask<UpdateReaderGroupEvent> {
    private static final TagLogger log = new TagLogger(LoggerFactory.getLogger(UpdateReaderGroupTask.class));
    private static final Predicate<Throwable> UPDATE_RETRY_PREDICATE = e -> {
        Throwable t = Exceptions.unwrap(e);
        return t instanceof RetryableException || t instanceof ConnectionFailedException;
    };
    private final StreamMetadataStore streamMetadataStore;
    private final StreamMetadataTasks streamMetadataTasks;
    private final ScheduledExecutorService executor;

    public UpdateReaderGroupTask(final StreamMetadataTasks streamMetaTasks,
                                 final StreamMetadataStore streamMetaStore,
                                 final ScheduledExecutorService executor) {
        Preconditions.checkNotNull(streamMetaStore);
        Preconditions.checkNotNull(streamMetaTasks);
        Preconditions.checkNotNull(executor);
        this.streamMetadataStore = streamMetaStore;
        this.streamMetadataTasks = streamMetaTasks;
        this.executor = executor;
    }

    @Override
    public CompletableFuture<Void> execute(final UpdateReaderGroupEvent request) {
        Timer timer = new Timer();
        String scope = request.getScope();
        String readerGroup = request.getRgName();
        long requestId = request.getRequestId();
        long generation = request.getGeneration();
        UUID readerGroupId = request.getReaderGroupId();
        boolean isTransition = request.isTransitionToFromSubscriber();
        ImmutableSet<String> streamsToBeUnsubscribed = request.getRemoveStreams();
        final OperationContext context = streamMetadataStore.createRGContext(scope, readerGroup, requestId);

        return RetryHelper.withRetriesAsync(() -> streamMetadataStore.getReaderGroupId(scope, readerGroup, context, executor)
                .thenCompose(id -> {
                if (!id.equals(readerGroupId)) {
                        log.warn(requestId, "Skipping processing of Reader Group update request {} as UUID did not match.", requestId);
                        return CompletableFuture.completedFuture(null);
                }
                return streamMetadataStore.getReaderGroupConfigRecord(scope, readerGroup, context, executor)
                       .thenCompose(rgConfigRecord -> {
                           if (rgConfigRecord.getObject().getGeneration() != generation) {
                               log.warn(requestId,
                                       "Skipping processing of Reader Group update request as generation did not match.");
                               return CompletableFuture.completedFuture(null);
                           }
                           if (rgConfigRecord.getObject().isUpdating()) {
                               if (isTransition) {
                                   // update Stream metadata tables, only if RG is a Subscriber
                                   Iterator<String> streamIter = rgConfigRecord.getObject()
                                                                               .getStartingStreamCuts().keySet().iterator();
                                   String scopedRGName = NameUtils.getScopedReaderGroupName(scope, readerGroup);
                                   Iterator<String> removeStreamsIter = streamsToBeUnsubscribed.stream().iterator();
                                   return Futures.loop(removeStreamsIter::hasNext, () -> {
                                       Stream stream = Stream.of(removeStreamsIter.next());
                                       return streamMetadataStore.deleteSubscriber(stream.getScope(),
                                               stream.getStreamName(), scopedRGName, rgConfigRecord.getObject().getGeneration(),
                                               context, executor);
                                   }, executor)
                                   .thenCompose(v -> {
                                       // updated config suggests this is a subscriber RG so addSubscriber
                                       if (!ReaderGroupConfig.StreamDataRetention.NONE
                                           .equals(ReaderGroupConfig.StreamDataRetention.values()
                                                  [rgConfigRecord.getObject().getRetentionTypeOrdinal()])) {
                                           return Futures.loop(streamIter::hasNext, () -> {
                                                  Stream stream = Stream.of(streamIter.next());
                                                  return streamMetadataStore.addSubscriber(stream.getScope(),
                                                         stream.getStreamName(), scopedRGName,
                                                          rgConfigRecord.getObject().getGeneration(),
                                                         context, executor);
                                           }, executor);
                                       }
                                       return CompletableFuture.completedFuture(null);
                                   })
                                   .thenCompose(v -> streamMetadataStore.completeRGConfigUpdate(scope, readerGroup, rgConfigRecord, context, executor))
                                           .thenAccept(v -> StreamMetrics.getInstance().controllerEventProcessorUpdateReaderGroupEvent(timer.getElapsed()));
                               }
                               // We get here for non-transition updates
                               return streamMetadataStore.completeRGConfigUpdate(scope, readerGroup, rgConfigRecord, context, executor)
                                       .thenAccept(v -> StreamMetrics.getInstance().controllerEventProcessorUpdateReaderGroupEvent(timer.getElapsed()));
                           }
                           return CompletableFuture.completedFuture(null);
                       });
        }), UPDATE_RETRY_PREDICATE, Integer.MAX_VALUE, executor);
    }

}


text:
import pytest
import random
from string import letters
from mmvdApp.utils import memoize

def unmemoizable_function(argument):
    L = list(letters)
    random.shuffle(L)
    return L

@pytest.mark.utils
@pytest.mark.memoization
@pytest.mark.regression
def test_memoization():
    memoized = memoize(unmemoizable_function)

    argument = random.randrange(10000)

    assert memoized(argument) != unmemoizable_function(argument)
    assert set(memoized(argument)) == set(letters)
    assert isinstance(memoized, memoize)
    assert memoized.__doc__ is unmemoizable_function.__doc__


text:
package org.jboss.weld.tests.beanDeployment.mixed;

import jakarta.ejb.Local;

@Local
public interface HoundLocal {

}


text:
package com.streamreduce;

/**
 * Exception that occurs when an attempt to store a payload via the Outbound Message Gateway fails.  Instances of this
 * Exception should signal failure and trigger some form of retry to the outbound storage, but should not terminate the
 * execution path of logic that triggered persisting to the Outbound Message Gateway.
 *
 */
public class OutboundStorageException extends NodeableException {

    @SuppressWarnings("unused")
    public OutboundStorageException(String s) {
        super("OutboundStorage Exception:" + s);
    }

    @SuppressWarnings("unused")
    public OutboundStorageException(String s, Throwable t) {
        super("OutboundStorage Exception:" + s,t);
    }
}


text:
class Tr8n::Notification < ActiveRecord::Base
  self.table_name = :tr8n_notifications
  attr_accessible :translator, :actor, :target, :object, :action, :viewed_at

  belongs_to :translator, :class_name => "Tr8n::Translator"

  belongs_to :actor, :class_name => "Tr8n::Translator", :foreign_key => :actor_id
  belongs_to :target, :class_name => "Tr8n::Translator", :foreign_key => :target_id
  belongs_to :object, :polymorphic => true

  def self.distribute(object)
    Tr8n::OfflineTask.schedule(self.name, :distribute_offline, {
                               :object_type => object.class.name,
                               :object_id => object.id
    })
  end

  def self.distribute_offline(opts)
    object = opts[:object_type].constantize.find_by_id(opts[:object_id])
    return unless object

    "#{object.class.name}Notification".constantize.distribute(object)
  end

  def self.key(object)
    object.class.name.underscore.split("/").last
  end

  def self.commenters(tkey, language)
    Tr8n::TranslationKeyComment.where("translation_key_id = ? and language_id = ?",
                                       tkey.id, language.id).all.collect{|f| f.translator}
  end

  def self.followers(obj)
    Tr8n::TranslatorFollowing.where("object_type = ? and object_id = ?",
                          obj.class.name, obj.id).all.collect{|f| f.translator}
  end

  def self.translators_for_translation(translation)
    tkey = translation.translation_key

    # find translators for all other translations of the key in this language
    tanslations = Tr8n::Translation.where("translation_key_id = ? and language_id = ?",
                                           tkey.id, translation.language.id).all
    translators = []
    tanslations.each do |t|
      translators << t.translator
    end
    translators
  end

  def key
    self.class.key(object)
  end

  def valid_notification?
    return false unless object
    true
  end

  def excerpt
    nil
  end

  def has_excerpt?
    not excerpt.nil?
  end

  def translation
    nil
  end

  def translation_key
    nil
  end

  def language
    nil
  end

  def tr(label, description = nil, tokens = {}, options = {})
    label.translate(description, tokens, options.merge(:source => "tr8n/notifications/#{key}"))
  end

  def title
    raise "#{self.class.name} must implement title method"
  end

end


text:
package me.theredheadhd.assaultzone.utilities;

import java.io.File;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

public class SettingsManager {

	private static SettingsManager instance = new SettingsManager();

	public static SettingsManager getInstance() {
		return instance;
	}

	private static FileConfiguration arenas;
	private static File afile;

	public void setup(Plugin p) {
		if(!(p.getDataFolder().exists())) p.getDataFolder().mkdir();

		afile = new File(p.getDataFolder(), "arenas.yml");

		if(!(afile.exists())) {
			try {
				afile.createNewFile();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}

		arenas = YamlConfiguration.loadConfiguration(afile);
	}

	public FileConfiguration getArenas() {
		return arenas;
	}

	public Object get(String id) {
		return getArenas().get("Arenas" + id);
	}

	public ConfigurationSection getArenaWorld(int id) {
		return getArenas().getConfigurationSection("Arenas" + "." + "" + id + ".world");
	}

	public void set(String path, Object value) {
		arenas.set(path, value);

		try {
			arenas.save(afile);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public void deleteArena(String id) {
		getArenas().getConfigurationSection("Arenas").set(id, null);

		try {
			arenas.save(afile);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public boolean contains(String id) {
		if(arenas.getConfigurationSection("Arenas" + "." + id) != null) {
			return true;
		}
		return false;
	}
}


text:
package org.gradoop.storage.impl.hbase.api;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.gradoop.common.model.api.entities.EPGMGraphElement;
import org.gradoop.common.model.impl.id.GradoopIdSet;

import java.io.IOException;

/**
 * Responsible for reading and writing graph element entity data from and to
 * HBase. These are usually vertex and edge data objects.
 */
public interface GraphElementHandler extends ElementHandler {
  /**
   * Adds the given graph identifiers to the given {@link Put} and returns it.
   *
   * @param put          {@link Put} to add graph identifiers to
   * @param graphElement graph element
   * @return put with graph identifiers
   */
  Put writeGraphIds(
    final Put put,
    final EPGMGraphElement graphElement
  ) throws
    IOException;

  /**
   * Reads the graph identifiers from the given {@link Result}.
   *
   * @param res HBase row
   * @return graphs identifiers
   */
  GradoopIdSet readGraphIds(final Result res);
}


text:
/* -*-  mode: c++; indent-tabs-mode: nil -*- */

/*
  SubgridAggregateEvaluator is the generic evaluator for multipying two vectors.

  Authors: Ahmad Jan (jana@ornl.gov)
*/

#include "SubgridAggregateEvaluator.hh"

namespace Amanzi {
namespace Relations {

// registry of method
Utils::RegisteredFactory<Evaluator,SubgridAggregateEvaluator> SubgridAggregateEvaluator::factory_("subgrid aggregate evaluator");

} // namespace
} // namespace


text:
/**

	File:		TypePosition.h

	Project:	DCPU-16 Tools
	Component:	LibDCPU-ci-lang

	Authors:	James Rhodes

	Description:	Declares the TypePosition class.

**/

#ifndef __DCPU_LIBDCC_TYPEPOSITION_H
#define __DCPU_LIBDCC_TYPEPOSITION_H

#include <stdint.h>
#include <string>

class TypePosition
{
	private:
		bool m_Found;
		bool m_Global;
		bool m_Function;
		bool m_StackStartAtC;
		uint16_t m_Position;
		std::string m_FunctionName;
	public:
		TypePosition(bool isFound, bool isGlobal, bool hasStackStartAtC, uint16_t position);
		TypePosition(bool isFound, std::string funcName);
		bool isFound();
		bool isFunction();
		std::string pushAddress(char registr);
};

#endif


text:
from unittest import TestCase

import numpy as np
import pytest

import mxnet as mx
from zoo.orca.learn.mxnet import Estimator, create_config

np.random.seed(1337)  # for reproducibility

def get_train_data_iter(config, kv):
    train_data = np.random.rand(200, 30)
    train_label = np.random.randint(0, 10, (200,))
    train = mx.io.NDArrayIter({"input": train_data}, {"label": train_label},
                              batch_size=config["batch_size"], shuffle=True)
    return train

def get_test_data_iter(config, kv):
    test_data = np.random.rand(80, 30)
    test_label = np.random.randint(0, 10, (80,))
    test = mx.io.NDArrayIter({"input": test_data}, {"label": test_label},
                             batch_size=config["batch_size"], shuffle=True)
    return test

def get_model(config):
    input_data = mx.symbol.Variable('input')
    y_true = mx.symbol.Variable('label')
    fc1 = mx.symbol.FullyConnected(data=input_data, num_hidden=20, name='fc1')
    fc2 = mx.symbol.FullyConnected(data=fc1, num_hidden=10, name='fc2')
    output = mx.symbol.SoftmaxOutput(data=fc2, label=y_true, name='output')
    mod = mx.mod.Module(symbol=output,
                        data_names=['input'],
                        label_names=['label'],
                        context=mx.cpu())
    return mod

def get_metrics(config):
    return 'accuracy'

class TestMXNetSymbol(TestCase):
    def test_symbol(self):
        config = create_config(log_interval=2, seed=42)
        estimator = Estimator.from_mxnet(config=config, model_creator=get_model,
                                         validation_metrics_creator=get_metrics,
                                         eval_metrics_creator=get_metrics)
        estimator.fit(get_train_data_iter, validation_data=get_test_data_iter,
                      epochs=2, batch_size=16)
        estimator.shutdown()

if __name__ == "__main__":
    pytest.main([__file__])


text:
package org.motechproject.dhis2.web;

import org.motechproject.dhis2.service.Settings;
import org.motechproject.dhis2.service.SettingsService;
import org.motechproject.dhis2.service.SyncService;
import org.motechproject.dhis2.service.TasksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * The controller that handles both changes to module settings and syncing to the DHIS2 server.
 * @see org.motechproject.dhis2.service.SyncService
 * @see org.motechproject.dhis2.service.SettingsService
 */
@Controller
public class DhisSettingsController {
    @Autowired
    @Qualifier("dhisSettingsService")
    private SettingsService settingsService;

    @Autowired
    private SyncService syncService;

    @Autowired
    private TasksService tasksService;

    /**
     * Returns the settings for the module
     * @return an {@link Settings} object for the DHIS2 module
     */
    @RequestMapping(value = "/dhis2-settings", method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasRole('configureDhis')")
    public Settings getSettings() {
        return settingsService.getSettings();
    }

    /**
     * Updates the settings to the configuration specfied in the parameters
     * @param settings the new settings configuration
     * @return the new settings configuration
     */
    @RequestMapping(value = "/dhis2-settings", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @PreAuthorize("hasRole('configureDhis')")
    public Settings updateSettings(@RequestBody Settings settings) {
        settingsService.updateSettings(settings);
        return settingsService.getSettings();
    }

    /**
     * Attempts to sync the module to the DHIS2 server. If successful, updates
     * the task channel to reflect any changes to the DHIS2 schema
     * @return a boolean value indicating success or failure
     */
    @RequestMapping(value = "/sync", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    @PreAuthorize("hasRole('syncDhis')")
    public boolean sync() {
        boolean success = syncService.sync();

        if (success) {
            tasksService.updateChannel();
        }

        return success;
    }
}


text:
@implementation WSAssetWrapper

@synthesize asset = _asset;
@synthesize selected = _selected;

+ (WSAssetWrapper *)wrapperWithAsset:(ALAsset *)asset
{
    WSAssetWrapper *wrapper = [[WSAssetWrapper alloc] initWithAsset:asset];
    return wrapper;
}

- (id)initWithAsset:(ALAsset *)asset
{
    if ((self = [super init])) {
        _asset = asset;
    }
    return self;
}

@end


text:
/** @file
 * VBox Remote Desktop Extension (VRDE) - Graphics Orders Structures.
 */

/*
 * Copyright (C) 2006-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */

#ifndef ___VBox_RemoteDesktop_VRDEOrders_h
#define ___VBox_RemoteDesktop_VRDEOrders_h

#include <iprt/types.h>

/*
 * VRDE gets an information about a graphical update as a pointer
 * to a memory block and the size of the memory block.
 * The memory block layout is:
 *    VRDEORDERHDR - Describes the affected rectangle.
 *    Then VRDE orders follow:
 *        VRDEORDERCODE;
 *        a VRDEORDER* structure.
 *
 * If size of the memory block is equal to the VRDEORDERHDR, then a bitmap
 * update is assumed.
 */

/* VRDE order codes. Must be >= 0, because the VRDE internally
 * uses negative values to mark some operations.
 */
#define VRDE_ORDER_DIRTY_RECT     (0)
#define VRDE_ORDER_SOLIDRECT      (1)
#define VRDE_ORDER_SOLIDBLT       (2)
#define VRDE_ORDER_DSTBLT         (3)
#define VRDE_ORDER_SCREENBLT      (4)
#define VRDE_ORDER_PATBLTBRUSH    (5)
#define VRDE_ORDER_MEMBLT         (6)
#define VRDE_ORDER_CACHED_BITMAP  (7)
#define VRDE_ORDER_DELETED_BITMAP (8)
#define VRDE_ORDER_LINE           (9)
#define VRDE_ORDER_BOUNDS         (10)
#define VRDE_ORDER_REPEAT         (11)
#define VRDE_ORDER_POLYLINE       (12)
#define VRDE_ORDER_ELLIPSE        (13)
#define VRDE_ORDER_SAVESCREEN     (14)
#define VRDE_ORDER_TEXT           (15)

/* 128 bit bitmap hash. */
typedef uint8_t VRDEBITMAPHASH[16];

#pragma pack(1)
typedef struct _VRDEORDERHDR
{
   /** Coordinates of the affected rectangle. */
   int16_t x;
   int16_t y;
   uint16_t w;
   uint16_t h;
} VRDEORDERHDR;

typedef struct _VRDEORDERCODE
{
   uint32_t u32Code;
} VRDEORDERCODE;

typedef struct _VRDEORDERPOINT
{
    int16_t  x;
    int16_t  y;
} VRDEORDERPOINT;

typedef struct _VRDEORDERPOLYPOINTS
{
    uint8_t  c;
    VRDEORDERPOINT a[16];
} VRDEORDERPOLYPOINTS;

typedef struct _VRDEORDERAREA
{
    int16_t  x;
    int16_t  y;
    uint16_t w;
    uint16_t h;
} VRDEORDERAREA;

typedef struct _VRDEORDERRECT
{
    int16_t left;
    int16_t top;
    int16_t right;
    int16_t bottom;
} VRDEORDERRECT;

typedef struct _VRDEORDERBOUNDS
{
    VRDEORDERPOINT pt1;
    VRDEORDERPOINT pt2;
} VRDEORDERBOUNDS;

typedef struct _VRDEORDERREPEAT
{
    VRDEORDERBOUNDS bounds;
} VRDEORDERREPEAT;

/* Header for bitmap bits. */
typedef struct _VRDEDATABITS
{
    uint32_t cb; /* Size of bitmap data without the header. */
    int16_t  x;
    int16_t  y;
    uint16_t cWidth;
    uint16_t cHeight;
    uint8_t  cbPixel;
    /* Bitmap data follow. */
} VRDEDATABITS;

typedef struct _VRDEORDERSOLIDRECT
{
    int16_t  x;
    int16_t  y;
    uint16_t w;
    uint16_t h;
    uint32_t rgb;
} VRDEORDERSOLIDRECT;

typedef struct _VRDEORDERSOLIDBLT
{
    int16_t  x;
    int16_t  y;
    uint16_t w;
    uint16_t h;
    uint32_t rgb;
    uint8_t  rop;
} VRDEORDERSOLIDBLT;

typedef struct _VRDEORDERDSTBLT
{
    int16_t  x;
    int16_t  y;
    uint16_t w;
    uint16_t h;
    uint8_t  rop;
} VRDEORDERDSTBLT;

typedef struct _VRDEORDERSCREENBLT
{
    int16_t  x;
    int16_t  y;
    uint16_t w;
    uint16_t h;
    int16_t  xSrc;
    int16_t  ySrc;
    uint8_t  rop;
} VRDEORDERSCREENBLT;

typedef struct _VRDEORDERPATBLTBRUSH
{
    int16_t  x;
    int16_t  y;
    uint16_t w;
    uint16_t h;
    int8_t   xSrc;
    int8_t   ySrc;
    uint32_t rgbFG;
    uint32_t rgbBG;
    uint8_t  rop;
    uint8_t  pattern[8];
} VRDEORDERPATBLTBRUSH;

typedef struct _VRDEORDERMEMBLT
{
    int16_t  x;
    int16_t  y;
    uint16_t w;
    uint16_t h;
    int16_t  xSrc;
    int16_t  ySrc;
    uint8_t  rop;
    VRDEBITMAPHASH hash;
} VRDEORDERMEMBLT;

typedef struct _VRDEORDERCACHEDBITMAP
{
    VRDEBITMAPHASH hash;
    /* VRDEDATABITS and the bitmap data follow. */
} VRDEORDERCACHEDBITMAP;

typedef struct _VRDEORDERDELETEDBITMAP
{
    VRDEBITMAPHASH hash;
} VRDEORDERDELETEDBITMAP;

typedef struct _VRDEORDERLINE
{
    int16_t  x1;
    int16_t  y1;
    int16_t  x2;
    int16_t  y2;
    int16_t  xBounds1;
    int16_t  yBounds1;
    int16_t  xBounds2;
    int16_t  yBounds2;
    uint8_t  mix;
    uint32_t rgb;
} VRDEORDERLINE;

typedef struct _VRDEORDERPOLYLINE
{
    VRDEORDERPOINT ptStart;
    uint8_t  mix;
    uint32_t rgb;
    VRDEORDERPOLYPOINTS points;
} VRDEORDERPOLYLINE;

typedef struct _VRDEORDERELLIPSE
{
    VRDEORDERPOINT pt1;
    VRDEORDERPOINT pt2;
    uint8_t  mix;
    uint8_t  fillMode;
    uint32_t rgb;
} VRDEORDERELLIPSE;

typedef struct _VRDEORDERSAVESCREEN
{
    VRDEORDERPOINT pt1;
    VRDEORDERPOINT pt2;
    uint8_t ident;
    uint8_t restore;
} VRDEORDERSAVESCREEN;

typedef struct _VRDEORDERGLYPH
{
    uint32_t o32NextGlyph;
    uint64_t u64Handle;

    /* The glyph origin position on the screen. */
    int16_t  x;
    int16_t  y;

    /* The glyph bitmap dimensions. Note w == h == 0 for the space character. */
    uint16_t w;
    uint16_t h;

    /* The character origin in the bitmap. */
    int16_t  xOrigin;
    int16_t  yOrigin;

    /* 1BPP bitmap. Rows are byte aligned. Size is (((w + 7)/8) * h + 3) & ~3. */
    uint8_t au8Bitmap[1];
} VRDEORDERGLYPH;

typedef struct _VRDEORDERTEXT
{
    uint32_t cbOrder;

    int16_t  xBkGround;
    int16_t  yBkGround;
    uint16_t wBkGround;
    uint16_t hBkGround;

    int16_t  xOpaque;
    int16_t  yOpaque;
    uint16_t wOpaque;
    uint16_t hOpaque;

    uint16_t u16MaxGlyph;

    uint8_t  u8Glyphs;
    uint8_t  u8Flags;
    uint16_t u8CharInc;
    uint32_t u32FgRGB;
    uint32_t u32BgRGB;

    /* u8Glyphs glyphs follow. Size of each glyph structure may vary. */
} VRDEORDERTEXT;
#pragma pack()

#endif


text:
package org.apache.maven.test.error.mojoFailure;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        StringUtils utils;
    }
}


text:
using KSP.UI.Screens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace LaunchNumbering
{
	[KSPScenario(ScenarioCreationOptions.AddToAllGames, new GameScenes[] { GameScenes.SPACECENTER, GameScenes.EDITOR, GameScenes.FLIGHT })]
	public class LaunchNumberer : ScenarioModule
	{
		public override void OnAwake()
		{
			_numbering = new Dictionary<string, Dictionary<int, Bloc>>();
			GameEvents.OnVesselRollout.Add(RenameVessel);
		}

		public void OnDestroy()
		{
			GameEvents.OnVesselRollout.Remove(RenameVessel);
		}

		private const string TopLevelNodeLabel = "LAUNCHNUMBERS";
		private const string SeriesNodeLabel = "SERIES";
		private const string BlocNodeLabel = "BLOC";
		private const string BlocNameLabel = "name";
		private const string VesselHashLabel = "vessel-hash";
		private const string BlocNumberLabel = "bloc-number";
		private const string VesselCountLabel = "vessel-count";
		private const string ShowBlocLabel = "bloc-shown";
		private const string BlocRomanLabel = "bloc-roman";
		private const string VesselRomanLabel = "vessel-roman";
		private const float MessageDisplayLength = 5.0f;

		public override void OnLoad(ConfigNode node)
		{
			_numbering = new Dictionary<string, Dictionary<int, Bloc>>();
			foreach(var serNode in node.GetNodes(SeriesNodeLabel))
			{
				var blocs = new Dictionary<int, Bloc>();
				_numbering.Add(serNode.GetValue(BlocNameLabel), blocs);
				foreach(var blocNode in serNode.GetNodes(BlocNodeLabel))
				{
					blocs.Add(int.Parse(blocNode.GetValue(VesselHashLabel)), new Bloc
					{
						blocNumber = int.Parse(blocNode.GetValue(BlocNumberLabel)),
						vessel = int.Parse(blocNode.GetValue(VesselCountLabel)),
						blocRoman = bool.Parse(blocNode.GetValue(BlocRomanLabel)),
						vesselRoman = bool.Parse(blocNode.GetValue(VesselRomanLabel)),
						showBloc = bool.Parse(blocNode.GetValue(ShowBlocLabel))
					});
				}
			}
		}
		public override void OnSave(ConfigNode node)
		{
			node.ClearNodes();
			foreach (var series in _numbering)
			{
				var serNode = new ConfigNode(SeriesNodeLabel);
				serNode.AddValue(BlocNameLabel, series.Key);
				foreach (var bloc in series.Value)
				{
					var blocNode = new ConfigNode(BlocNodeLabel);
					blocNode.AddValue(VesselHashLabel, bloc.Key);
					blocNode.AddValue(VesselCountLabel, bloc.Value.vessel);
					blocNode.AddValue(BlocNumberLabel, bloc.Value.blocNumber);
					blocNode.AddValue(BlocRomanLabel, bloc.Value.blocRoman);
					blocNode.AddValue(VesselRomanLabel, bloc.Value.vesselRoman);
					blocNode.AddValue(ShowBlocLabel, bloc.Value.showBloc);
					serNode.AddNode(blocNode);
				}
				node.AddNode(serNode);
			}
		}

		private Dictionary<string, Dictionary<int, Bloc>> _numbering;

		public void RenameVessel(ShipConstruct sc)
		{
			Vessel v = FlightGlobals.ActiveVessel;
			int vesselHash = ComputeVesselHash(v);
			var vesselNumber = 1;
			var blocNumber = 1;
			if (Char.IsDigit(v.vesselName[v.vesselName.Length - 1])) return;
			if (!_numbering.ContainsKey(v.vesselName))
			{
				_numbering.Add(v.vesselName, new Dictionary<int, Bloc>());
			}
			var nDict = _numbering[v.vesselName];
			Bloc b;
			if (vesselHash!=1 && nDict.Count == 1 && nDict.ContainsKey(1))
			{
				//Upgrade from earlier version
				b = nDict[1];
				nDict.Remove(1);
				nDict.Add(vesselHash, b);
			}
			if (!nDict.ContainsKey(vesselHash))
			{
				blocNumber = nDict.Count + 1;
				b = InitializeNewBloc(blocNumber);
				nDict.Add(vesselHash, b);
			}
			else
			{
				b = nDict[vesselHash];
				vesselNumber = b.vessel + 1;
				b.vessel = vesselNumber;
				blocNumber = b.blocNumber;
			}
			string addition = string.Empty;
			if (vesselNumber > 1)
			{
				addition = addition + " " + (b.vesselRoman ? ToRoman(vesselNumber) : vesselNumber.ToString());
			}
			if (blocNumber > 1&&b.showBloc)
			{
				addition = addition + " (Bloc " + (b.blocRoman ? ToRoman(blocNumber) : blocNumber.ToString()) + ")";
			}

			if (!string.IsNullOrEmpty(addition))
			{
				var oldName = v.vesselName;
				var newName = oldName + addition;
				v.vesselName = newName;
				ScreenMessages.PostScreenMessage("Launch: " + newName, MessageDisplayLength, ScreenMessageStyle.UPPER_CENTER);
			}
			else
			{
				ScreenMessages.PostScreenMessage("Initial launch", MessageDisplayLength, ScreenMessageStyle.UPPER_CENTER);
			}
		}

		private static Bloc InitializeNewBloc(int blocNumber)
		{
			var settings = HighLogic.CurrentGame.Parameters.CustomParams<LNSettings>();
			return new Bloc {
				vessel = 1,
				blocNumber = blocNumber,
				showBloc = settings.ShowBloc,
				vesselRoman = settings.Scheme== LNSettings.NumberScheme.Roman,
				blocRoman = settings.BlocScheme==LNSettings.NumberScheme.Roman
			};
		}

		private static int ComputeVesselHash(Vessel v)
		{
			int nameCounter = 0;
			var names = new Dictionary<string, int>();
			var treeItems = new List<int>();
			foreach(var p in v.Parts)
			{
				if (!names.ContainsKey(p.name)) names.Add(p.name, ++nameCounter);
				treeItems.Add(names[p.name]);
				if (p.children.Count > 0)
				{
					treeItems.Add(-1);
					foreach(var c in p.children)
					{
						if (!names.ContainsKey(c.name)) names.Add(c.name, ++nameCounter);
						treeItems.Add(names[c.name]);
					}
					treeItems.Add(-2);
				}
			}
			return QuickHash(treeItems);
		}
		private static int QuickHash(List<int> items)
		{
			int hashCode = items.Count;
			foreach (int item in items)
			{
				hashCode = unchecked(hashCode * 314159 + item);
			}
			return hashCode;
		}

		private readonly int[] _RValues = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
		private readonly string[] _RStrings = new string[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };

		public string ToRoman(int value)
		{
			var rindex = 0;
			var result = string.Empty;
			while (value > 0)
			{
				while (_RValues[rindex] > value)
				{
					rindex++;
				}
				value = value - _RValues[rindex];
				result = result + _RStrings[rindex];
			}
			return result;
		}

	}
}


text:
require 'test_helper'

describe API::Player do
  subject { API::Player }

  it 'should respond to get_all' do
    subject.must_respond_to :get_all
  end

  it 'should respond to get_quarterbacks' do
    subject.must_respond_to :get_quarterbacks
  end

  it 'should respond to get_runningbacks' do
    subject.must_respond_to :get_runningbacks
  end

  it 'should respond to get_wide_receivers' do
    subject.must_respond_to :get_wide_receivers
  end

  it 'should respond to get_tight_ends' do
    subject.must_respond_to :get_tight_ends
  end
end


text:
package com.example;

import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import com.code_intelligence.jazzer.api.FuzzerSecurityIssueLow;
import com.code_intelligence.jazzer.api.Jazzer;

public class JazzerApiFuzzer {
  public static void fuzzerTestOneInput(FuzzedDataProvider data) {
    Jazzer.exploreState(data.consumeByte(), 1);
    Jazzer.guideTowardsEquality(data.consumeString(10), data.pickValue(new String[] {"foo"}), 1);
    Jazzer.guideTowardsEquality(data.consumeBytes(10), new byte[] {}, 2);
    Jazzer.guideTowardsContainment(data.consumeAsciiString(10), "bar", 2);
    throw new FuzzerSecurityIssueLow("Jazzer API calls succeed");
  }
}


text:
from __future__ import unicode_literals

import os

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',

    'import_export',

    'core',

]

# INSTALLED_APPS += [
#     'debug_toolbar'
#     'django.contrib.staticfiles'
# ]

SITE_ID = 1

ROOT_URLCONF = "urls"

DEBUG = True

STATIC_URL = '/static/'

SECRET_KEY = '2n6)=vnp8@bu0om9d05vwf7@=5vpn%)97-!d*t4zq1mku%0-@j'

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

if os.environ.get('IMPORT_EXPORT_TEST_TYPE') == 'mysql-innodb':
    IMPORT_EXPORT_USE_TRANSACTIONS = True
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'TEST_NAME': 'import_export_test',
            'USER': os.environ.get('IMPORT_EXPORT_MYSQL_USER', 'root'),
            'OPTIONS': {
               'init_command': 'SET storage_engine=INNODB',
            }
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(os.path.dirname(__file__), 'database.db'),
        }
    }

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'handlers': {
        'console': {
            'class': 'logging.NullHandler'
        }
    },
    'root': {
        'handlers': ['console'],
    }}