text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.content_capture;

import android.annotation.TargetApi;
import android.os.Build;
import android.view.ViewStructure;
import android.view.autofill.AutofillId;
import android.view.contentcapture.ContentCaptureSession;

import androidx.annotation.VisibleForTesting;

import org.chromium.base.annotations.VerifiesOnQ;

/**
 * The class to wrap ContentCapture platform APIs, catches the exception from platform, and
 * re-throws with PlatformAPIException, so the call sites can catch platform exception to avoid
 * the crash.
 */
@VerifiesOnQ
@TargetApi(Build.VERSION_CODES.Q)
public abstract class PlatformAPIWrapper {
    private static PlatformAPIWrapper sImpl;
    public static PlatformAPIWrapper getInstance() {
        if (sImpl == null) {
            sImpl = new PlatformAPIWrapperImpl();
        }
        return sImpl;
    }

    public abstract ContentCaptureSession createContentCaptureSession(
            ContentCaptureSession parent, String url, String favicon);

    public abstract void destroyContentCaptureSession(ContentCaptureSession session);

    public abstract AutofillId newAutofillId(
            ContentCaptureSession parent, AutofillId rootAutofillId, long id);

    public abstract ViewStructure newVirtualViewStructure(
            ContentCaptureSession parent, AutofillId parentAutofillId, long id);

    public abstract void notifyViewAppeared(
            ContentCaptureSession session, ViewStructure viewStructure);

    public abstract void notifyViewDisappeared(
            ContentCaptureSession session, AutofillId autofillId);

    public abstract void notifyViewsDisappeared(
            ContentCaptureSession session, AutofillId autofillId, long[] ids);

    public abstract void notifyViewTextChanged(
            ContentCaptureSession session, AutofillId autofillId, String newContent);

    public abstract void notifyFaviconUpdated(ContentCaptureSession session, String favicon);

    @VisibleForTesting
    public static void setPlatformAPIWrapperImplForTesting(PlatformAPIWrapper impl) {
        sImpl = impl;
    }
}


text:
package com.microsoft.azure.management.cosmosdb.v2020_04_01.implementation;

import com.microsoft.azure.management.cosmosdb.v2020_04_01.PartitionUsage;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.cosmosdb.v2020_04_01.MetricName;
import com.microsoft.azure.management.cosmosdb.v2020_04_01.UnitType;

class PartitionUsageImpl extends WrapperImpl<PartitionUsageInner> implements PartitionUsage {
    private final CosmosDBManager manager;
    PartitionUsageImpl(PartitionUsageInner inner, CosmosDBManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public CosmosDBManager manager() {
        return this.manager;
    }

    @Override
    public Long currentValue() {
        return this.inner().currentValue();
    }

    @Override
    public Long limit() {
        return this.inner().limit();
    }

    @Override
    public MetricName name() {
        return this.inner().name();
    }

    @Override
    public String partitionId() {
        return this.inner().partitionId();
    }

    @Override
    public String partitionKeyRangeId() {
        return this.inner().partitionKeyRangeId();
    }

    @Override
    public String quotaPeriod() {
        return this.inner().quotaPeriod();
    }

    @Override
    public UnitType unit() {
        return this.inner().unit();
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace Semmle.Util
{
    public static class Enumerators
    {
        /// <summary>
        /// Create an enumerable with a single element.
        /// </summary>
        ///
        /// <typeparam name="T">The type of the enumerable/element.</typeparam>
        /// <param name="t">The element.</param>
        /// <returns>An enumerable containing a single element.</returns>
        public static IEnumerable<T> Singleton<T>(T t)
        {
            yield return t;
        }
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--

    Copyright (C) 2011-2012 Esup Portail http://www.esup-portail.org
    Copyright (C) 2011-2012 UNR RUNN http://www.unr-runn.fr
    @Author (C) 2011-2012 Jean-Pierre Tran <Jean-Pierre.Tran@univ-rouen.fr>
    @Contributor (C) 2011-2012 Vincent Bonamy <Vincent.Bonamy@univ-rouen.fr>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>esup-helpdeskviewer-web-springmvc-portlet</display-name>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>esup-helpdeskviewer-web-springmvc-portlet</param-value>
    </context-param>
    <context-param>
        <param-name>log4jExposeWebAppRoot</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--
     | The order of these listeners is important and should not be changed
     +-->
    <listener>
        <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--
     | This servlet is needed by the spring DispatcherPortlet for rendering.
     +-->
    <servlet>
        <servlet-name>ViewRendererServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- [INSERT JSPC FRAGMENT HERE] -->

    <servlet-mapping>
        <servlet-name>ViewRendererServlet</servlet-name>
        <url-pattern>/WEB-INF/servlet/view</url-pattern>
    </servlet-mapping>

</web-app>


text:
package net.thetranquilpsychonaut.hashtagger.events;

/**
 * Created by itwenty on 5/17/14.
 */
public class SavedHashtagDeletedEvent
{
    private String deletedHashtag;

    public SavedHashtagDeletedEvent( String deletedHashtag )
    {
        this.deletedHashtag = deletedHashtag;
    }

    public String getDeletedHashtag()
    {
        return this.deletedHashtag;
    }
}


text:
package facebook4j.internal.json;

import facebook4j.Category;
import facebook4j.FacebookException;
import facebook4j.Offer;
import facebook4j.ResponseList;
import facebook4j.conf.Configuration;
import facebook4j.internal.http.HttpResponse;
import facebook4j.internal.org.json.JSONArray;
import facebook4j.internal.org.json.JSONException;
import facebook4j.internal.org.json.JSONObject;

import java.net.URL;
import java.util.Date;

import static facebook4j.internal.util.z_F4JInternalParseUtil.*;

/**
 * @author Ryuji Yamashita - roundrop at gmail.com
 */
/*package*/ final class OfferJSONImpl extends FacebookResponseImpl implements Offer, java.io.Serializable {
    private static final long serialVersionUID = -1552332355107913815L;

    private String id;
    private Category from;
    private String title;
    private Date createdTime;
    private Date expirationTime;
    private String terms;
    private URL imageURL;
    private Integer claimLimit;
    private String couponType;
    private URL redemptionLink;
    private String redemptionCode;
    private Boolean isPublished;
    private Integer scheduledPublishTime;
    private Date reminderTime;

    /*package*/OfferJSONImpl(HttpResponse res, Configuration conf) throws FacebookException {
        super(res);
        JSONObject json = res.asJSONObject();
        init(json);
        if (conf.isJSONStoreEnabled()) {
            DataObjectFactoryUtil.clearThreadLocalMap();
            DataObjectFactoryUtil.registerJSONObject(this, json);
        }
    }

    /*package*/OfferJSONImpl(JSONObject json) throws FacebookException {
        super();
        init(json);
    }

    private void init(JSONObject json) throws FacebookException {
        try {
            id = getRawString("id", json);
            if (!json.isNull("from")) {
                JSONObject fromJSONObject = json.getJSONObject("from");
                from = new CategoryJSONImpl(fromJSONObject);
            }
            title = getRawString("title", json);
            createdTime = getISO8601Datetime("created_time", json);
            expirationTime = getISO8601Datetime("expiration_time", json);
            terms = getRawString("terms", json);
            imageURL = getURL("image_url", json);
            claimLimit = getInt("claim_limit", json);
            couponType = getRawString("coupon_type", json);
            redemptionLink = getURL("redemption_link", json);
            redemptionCode = getRawString("redemption_code", json);
            isPublished = getBoolean("published", json);
            scheduledPublishTime = getInt("scheduled_publish_time", json);
            reminderTime = getISO8601Datetime("reminder_time", json);
        } catch (JSONException jsone) {
            throw new FacebookException(jsone.getMessage(), jsone);
        }
    }

    public String getId() {
        return id;
    }

    public Category getFrom() {
        return from;
    }

    public String getTitle() {
        return title;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public Date getExpirationTime() {
        return expirationTime;
    }

    public String getTerms() {
        return terms;
    }

    public URL getImageURL() {
        return imageURL;
    }

    public Integer getClaimLimit() {
        return claimLimit;
    }

    public String getCouponType() {
        return couponType;
    }

    public URL getRedemptionLink() {
        return redemptionLink;
    }

    public String getRedemptionCode() {
        return redemptionCode;
    }

    public Boolean isPublished() {
        return isPublished;
    }

    public Integer getScheduledPublishTime() {
        return scheduledPublishTime;
    }

    public Date getReminderTime() {
        return reminderTime;
    }

    /*package*/
    static ResponseList<Offer> createOfferList(HttpResponse res, Configuration conf) throws FacebookException {
        try {
            if (conf.isJSONStoreEnabled()) {
                DataObjectFactoryUtil.clearThreadLocalMap();
            }
            JSONObject json = res.asJSONObject();
            JSONArray list = json.getJSONArray("data");
            final int size = list.length();
            ResponseList<Offer> offers = new ResponseListImpl<Offer>(size, json);
            for (int i = 0; i < size; i++) {
                JSONObject offerJSONObject = list.getJSONObject(i);
                Offer offer = new OfferJSONImpl(offerJSONObject);
                if (conf.isJSONStoreEnabled()) {
                    DataObjectFactoryUtil.registerJSONObject(offer, offerJSONObject);
                }
                offers.add(offer);
            }
            if (conf.isJSONStoreEnabled()) {
                DataObjectFactoryUtil.registerJSONObject(offers, list);
            }
            return offers;
        } catch (JSONException jsone) {
            throw new FacebookException(jsone);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof OfferJSONImpl)) return false;

        OfferJSONImpl offerJSON = (OfferJSONImpl) o;

        if (id != null ? !id.equals(offerJSON.id) : offerJSON.id != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }

    @Override
    public String toString() {
        return "OfferJSONImpl{" +
                "id='" + id + '\'' +
                ", from=" + from +
                ", title='" + title + '\'' +
                ", createdTime=" + createdTime +
                ", expirationTime=" + expirationTime +
                ", terms='" + terms + '\'' +
                ", imageURL=" + imageURL +
                ", claimLimit=" + claimLimit +
                ", couponType='" + couponType + '\'' +
                ", redemptionLink=" + redemptionLink +
                ", redemptionCode='" + redemptionCode + '\'' +
                ", isPublished=" + isPublished +
                ", scheduledPublishTime=" + scheduledPublishTime +
                ", reminderTime=" + reminderTime +
                '}';
    }
}


text:
package org.ovirt.engine.core.common.queries;

import org.ovirt.engine.core.common.businessentities.*;

public class GetAllUsersInVdcRoleParameters extends VdcQueryParametersBase {
    private static final long serialVersionUID = 4075283289991368556L;

    public GetAllUsersInVdcRoleParameters(VdcRole id) {
        _id = id;
    }

    private VdcRole _id = VdcRole.forValue(0);

    public VdcRole getId() {
        return _id;
    }

    public GetAllUsersInVdcRoleParameters() {
    }
}


text:
module Masamune::Transform::Postgres
  class RelabelDimension
    def initialize(options = {})
      @target = options[:target]
    end

    def locals
      { target: target }
    end

    def target
      TargetPresenter.new(@target)
    end

    class TargetPresenter < SimpleDelegator
      def window(*extra)
        (columns.values.select { |column| extra.delete(column.name) || column.natural_key || column.auto_reference }.map(&:name) + extra).uniq
      end
    end
  end
end


text:
<?php

namespace vakata\database\test;

class SchemaPostgreTest extends Schema
{
    protected function getConnectionString()
    {
        return "postgre://postgres:postgres@DESKTOP.local/test?schema=public";
    }
}


text:
<?php

/**
 * Before showing users a registration form, show them the registration agreement.
 */
function template_registration_agreement()
{
	global $context, $txt;

	echo '
		<form action="', getUrl('action', ['action' => 'register']), '" method="post" accept-charset="UTF-8" id="registration">';

	if (!empty($context['languages']))
	{
		if (count($context['languages']) === 1)
		{
			foreach ($context['languages'] as $lang_key => $lang_val)
			{
				echo '
				<input type="hidden" name="lngfile" value="', $lang_key, '" />';
			}
		}
		else
		{
			echo '
				<select onchange="this.form.submit()" class="floatright" name="lngfile">';

			foreach ($context['languages'] as $lang_key => $lang_val)
			{
				echo '
					<option value="', $lang_key, '"', empty($lang_val['selected']) ? '' : ' selected="selected"', '>', $lang_val['name'], '</option>';
			}

			echo '
				</select>';
		}
	}

	if (!empty($context['agreement']))
	{
		echo '

', $txt['registration_agreement'], '

', $context['agreement'], '

';
	}

	if (!empty($context['privacy_policy']))
	{
		echo '

', $txt['registration_privacy_policy'], '

', $context['privacy_policy'], '

';
	}

	echo '

';

	// Age restriction in effect?
	if ($context['show_coppa'])
	{
		echo '
				<input type="submit" name="accept_agreement" value="', $context['coppa_agree_above'], '" />

				<input type="submit" name="accept_agreement_coppa" value="', $context['coppa_agree_below'], '" />';
	}
	else
	{
		echo '
				<input type="submit" id="accept_agreement" name="accept_agreement" value="', $txt['agreement_agree'], '" />';
	}

	echo '
				<input type="submit" id="no_accept" name="no_accept" value="', $txt['agreement_no_agree'], '" />';

	if ($context['show_contact_button'])
	{
		echo '

				<input type="submit" name="show_contact" value="', $txt['contact'], '" />';
	}

	if (!empty($context['register_subaction']))
	{
		echo '
				<input type="hidden" name="sa" value="', $context['register_subaction'], '" />';
	}

	echo '
			<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
			<input type="hidden" name="', $context['register_token_var'], '" value="', $context['register_token'], '" />

			<input type="hidden" name="step" value="1" />
		</form>';
}

/**
 * Before registering - get their information.
 *
 * @uses ParseError
 */
function template_registration_form()
{
	global $context, $txt, $modSettings;

	theme()->addInlineJavascript('
		function verifyAgree()
		{
			if (document.forms.registration.elk_autov_pwmain.value !== document.forms.registration.elk_autov_pwverify.value)
			{
				alert("' . $txt['register_passwords_differ_js'] . '");
				return false;
			}

			return true;
		}', true);

	// Any errors?
	if (!empty($context['registration_errors']))
	{
		echo '

			', $txt['registration_errors_occurred'], '

';

		// Cycle through each error and display an error message.
		foreach ($context['registration_errors'] as $error)
		{
			echo '

', $error, '
';
		}

		echo '

';
	}

	echo '
		<form action="', getUrl('atcion', ['action' => 'register', 'sa' => 'register2']), '" method="post" accept-charset="UTF-8" name="registration" id="registration" onsubmit="return verifyAgree();">

', $txt['registration_form'], '

			<input type="text" name="reason_for_joining_hp" class="hide" autocomplete="off" />
			<input type="hidden" name="allow_email" value="0" />

						<input type="text" name="user" id="elk_autov_username" size="30" tabindex="', $context['tabindex']++, '" maxlength="25" value="', $context['username'] ?? '', '" class="input_text" placeholder="', $txt['username'], '" required="required" autofocus="autofocus" />
						', $txt['username'], '

';

	if ($context['insert_display_name'] == true)
	{
		echo '

						<input type="text" name="display" id="elk_autov_displayname" size="30" tabindex="', $context['tabindex']++, '" maxlength="25" value="', $context['display_name'] ?? '', '" class="input_text" placeholder="', $txt['display_name'], '" required="required" />
						', $txt['display_name'], '

';
	}

	echo '

						<input type="email" name="email" id="elk_autov_reserve1" size="30" tabindex="', $context['tabindex']++, '" value="', $context['email'] ?? '', '" class="input_text" placeholder="', $txt['user_email_address'], '" required="required" />
						', $txt['user_email_address'], '

						<input type="checkbox" name="notify_announcements" id="notify_announcements" tabindex="', $context['tabindex']++, '"', $context['notify_announcements'] ? ' checked="checked"' : '', ' class="input_check" />
						', $txt['notify_announcements'], '

						<input type="password" name="passwrd1" id="elk_autov_pwmain" size="30" tabindex="', $context['tabindex']++, '" class="input_password" placeholder="', $txt['choose_pass'], '" required="required" autocomplete="new-password" />
						', $txt['choose_pass'], '

						<input type="password" name="passwrd2" id="elk_autov_pwverify" size="30" tabindex="', $context['tabindex']++, '" class="input_password" placeholder="', $txt['verify_pass'], '" required="required" autocomplete="new-password" />
						', $txt['verify_pass'], '

';

	// If there is any custom/profile field marked as required, show it here!
	if (!empty($context['custom_fields_required']) && !empty($context['custom_fields']))
	{
		foreach ($context['custom_fields'] as $key => $field)
		{
			if ($field['show_reg'] > 1)
			{
				echo '

', preg_replace_callback('~<(input|select|textarea) ~', function ($matches) {
							global $context;

							return '<' . $matches[1] . ' tabindex="' . ($context['tabindex']++) . '"';
						}, $field['input_html']);

				// Fieldsets already have a legend
				if (strpos($field['input_html'], 'fieldset') === false)
				{
					echo '
						', $field['name'], '';
				}

				echo '

', $field['desc'], '

';

				// Drop this one so we don't show the additonal information header unless needed
				unset($context['custom_fields'][$key]);
			}
		}
	}

	echo '

';

	// If we have stand or custom fields to display, show the optional grouping area
	if (!empty($context['profile_fields']) || !empty($context['custom_fields']))
	{
		echo '

', $txt['additional_information'], '

			<fieldset class="content">

';

		$lastItem = template_profile_options();
		template_custom_profile_options($lastItem);

		echo '

			</fieldset>';
	}

	// Any verification tests to pass?
	if (isset($context['visual_verification']) && $context['visual_verification'] !== false)
	{
		template_verification_controls($context['visual_verification_id'], '

' . $txt['verification'] . '

			<fieldset class="content centertext">
				', '
			</fieldset>');
	}

	if ($context['checkbox_agreement'] && $context['require_agreement'])
	{
		echo '
			<fieldset class="content">

					', $context['agreement'], '

					<input type="checkbox" name="checkbox_agreement" id="checkbox_agreement" value="1"', ($context['registration_passed_agreement'] ? ' checked="checked"' : ''), ' tabindex="', $context['tabindex']++, '" />
					', $txt['checkbox_agreement'], '

					', $context['privacy_policy'], '

					<input type="checkbox" name="checkbox_privacypol" id="checkbox_privacypol" value="1"', ($context['registration_passed_privacypol'] ? ' checked="checked"' : ''), ' tabindex="', $context['tabindex']++, '" />
					', $txt['checkbox_privacypol'], '
				';

		if (!empty($context['languages']))
		{
			echo '

				<select id="agreement_lang" class="input_select">';

			foreach ($context['languages'] as $key => $val)
			{
				echo '
					<option value="', $key, '"', !empty($val['selected']) ? ' selected="selected"' : '', '>', $val['name'], '</option>';
			}

			echo '
				</select>';
		}

		echo '
			</fieldset>';
	}

	echo '

';

	// Age restriction in effect?
	if ((!$context['require_agreement'] || $context['checkbox_agreement']) && $context['show_coppa'])
	{
		echo '
				<input type="submit" name="accept_agreement" value="', $context['coppa_agree_above'], '" />

				<input type="submit" name="accept_agreement_coppa" value="', $context['coppa_agree_below'], '" />';
	}
	else
	{
		echo '
				<input type="submit" name="regSubmit" value="', $txt['register'], '" tabindex="', $context['tabindex']++, '" />';
	}

	if ($context['show_contact_button'])
	{
		echo '
				<input type="submit" name="show_contact" value="', $txt['contact'], '" />';
	}

	echo '

			<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
			<input type="hidden" name="', $context['register_token_var'], '" value="', $context['register_token'], '" />
			<input type="hidden" name="step" value="2" />
		</form>

		';
}

/**
 * After registration... all done ;).
 */
function template_after()
{
	global $context;

	// Not much to see here, just a quick... "you're now registered!" or what have you.
	echo '

', $context['title'], '

				', $context['description'], '

';
}

/**
 * Template for giving instructions about COPPA activation.
 */
function template_coppa()
{
	global $context, $txt;

	// Formulate a nice complicated message!
	echo '

', $context['page_title'], '

', $context['coppa']['body'], '

					 'register', 'sa' => 'coppa', 'form', 'member' => $context['coppa']['id']]), '" target="_blank" class="new_win">', $txt['coppa_form_link_popup'], ' |  'register', 'sa' => 'coppa;form;dl', 'member' => $context['coppa']['id']]), '">', $txt['coppa_form_link_download'], '

', $context['coppa']['many_options'] ? $txt['coppa_send_to_two_options'] : $txt['coppa_send_to_one_option'], '

';

	// Can they send by post?
	if (!empty($context['coppa']['post']))
	{
		echo '

 ', $txt['coppa_send_by_post'], '

						', $context['coppa']['post'], '

';

		// Can they send by fax??
		if (!empty($context['coppa']['fax']))
		{
			echo '

', $txt['coppa_send_by_fax'], '

						', $context['coppa']['fax'], '

';
		}

		// Offer an alternative Phone Number?
		if ($context['coppa']['phone'])
		{
			echo '

', $context['coppa']['phone'], '
';
		}

		echo '

';
	}
}

/**
 * An easily printable form for giving permission to access the forum for a minor.
 */
function template_coppa_form()
{
	global $context, $txt;

	// Show the form (As best we can)
	echo '

				', $context['forum_contacts'], '

					', $txt['coppa_form_address'], ': ', $context['ul'], '

					', $context['ul'], '

					', $context['ul'], '

					', $context['ul'], '

					', $txt['coppa_form_date'], ': ', $context['ul'], '

					', $context['coppa_body'], '

';
}

/**
 * Show a window containing the spoken verification code.
 */
function template_verification_sound()
{
	global $context, $settings, $txt, $db_show_debug;

	$db_show_debug = false;

	echo '<!DOCTYPE html>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>', $txt['visual_verification_sound'], '</title>
		<meta name="robots" content="noindex" />
		<link rel="stylesheet" href="', $settings['theme_url'], '/css/index.css', CACHE_STALE, '" />
		<link rel="stylesheet" href="', $settings['theme_url'], '/css/', $context['theme_variant_url'], 'index', $context['theme_variant'], '.css', CACHE_STALE, '" />';

	// Just show the help text and a "close window" link.
	echo '

				🔊

			<audio controls="controls" autoplay="autoplay">
				<source src="', $context['verification_sound_href'], '" type="audio/x-wav">
			</audio>

			', $txt['visual_verification_sound_again'], '

			', $txt['visual_verification_sound_direct'], '

			', $txt['visual_verification_sound_close'], '

';
}

/**
 * Show a page for admins to register new members.
 */
function template_admin_register()
{
	global $context, $txt, $modSettings;

	echo '

			<form id="postForm" action="', getUrl('admin', ['action' => 'admin', 'area' => 'regcenter']), '" method="post" autocomplete="off" accept-charset="UTF-8" name="postForm">

', $txt['admin_browse_register_new'], '

';

	if (!empty($context['registration_done']))
	{
		echo '

						', $context['registration_done'], '

';
	}

	echo '

							<input type="text" name="user" id="user_input" tabindex="', $context['tabindex']++, '" size="30" maxlength="25" class="input_text" />
							', $txt['admin_register_username'], '
							', $txt['admin_register_username_desc'], '

							<input type="email" name="email" id="email_input" tabindex="', $context['tabindex']++, '" size="30" class="input_text" />
							', $txt['admin_register_email'], '
							', $txt['admin_register_email_desc'], '

							<input type="password" name="password" id="password_input" tabindex="', $context['tabindex']++, '" size="30" class="input_password" onchange="onCheckChange();" />
							', $txt['admin_register_password'], '
							', $txt['admin_register_password_desc'], '

';

	if (!empty($context['member_groups']))
	{
		echo '

							<select name="group" id="group_select" tabindex="', $context['tabindex']++, '">';

		foreach ($context['member_groups'] as $id => $name)
		{
			echo '
								<option value="', $id, '">', $name, '</option>';
		}

		echo '
							</select>
							', $txt['admin_register_group'], '

', $txt['admin_register_group_desc'], '

';
	}

	echo '

							<input type="checkbox" name="emailPassword" id="emailPassword_check" tabindex="', $context['tabindex']++, '" checked="checked" disabled="disabled" />
							', $txt['admin_register_email_detail'], '
							', $txt['admin_register_email_detail_desc'], '

							<input type="checkbox" name="emailActivate" id="emailActivate_check" tabindex="', $context['tabindex']++, '"', !empty($modSettings['registration_method']) && $modSettings['registration_method'] == 1 ? ' checked="checked"' : '', ' onclick="onCheckChange();" />
							', $txt['admin_register_email_activate'], '

						<input type="submit" name="regSubmit" value="', $txt['register'], '" tabindex="', $context['tabindex']++, '" class="right_submit" />
						<input type="hidden" name="sa" value="register" />
						<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
						<input type="hidden" name="', $context['admin-regc_token_var'], '" value="', $context['admin-regc_token'], '" />

			</form>

';
}

/**
 * Form for editing the agreement shown for people registering to the forum.
 */
function template_edit_agreement()
{
	global $context, $txt;

	// Just a big box to edit the text file ;).
	echo '
		<form id="admin_form_wrapper" action="', getUrl('admin', ['action' => 'admin', 'area' => 'regcenter']), '" method="post" accept-charset="UTF-8" onsubmit="return confirmAgreement(', JavaScriptEscape($txt['confirm_request_accept_agreement']), ');">

', $context['page_title'], '
';

	// Warning for if the file isn't writable.
	if (!empty($context['warning']))
	{
		echo '

', $context['warning'], '
';
	}

	echo '

					<input type="hidden" name="agree_lang" value="', $context['current_agreement'], '" />';

	// Is there more than one language to choose from?
	if (count($context['editable_agreements']) > 1)
	{
		echo '

', $txt['language_configuration'], '

						', $txt['admin_agreement_select_language'], ':
						<select name="agree_lang" onchange="document.getElementById(\'admin_form_wrapper\').submit();" tabindex="', $context['tabindex']++, '">';

		foreach ($context['editable_agreements'] as $file => $name)
		{
			echo '
							<option value="', $file, '" ', $context['current_agreement'] == $file ? 'selected="selected"' : '', '>', $name, '</option>';
		}

		echo '
						</select>

							<input type="hidden" name="sa" value="agreement" />
							<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
							<input type="submit" name="change" value="', $txt['admin_agreement_select_language_change'], '" tabindex="', $context['tabindex']++, '" />

';
	}

	// Show the actual agreement in an oversized text box.
	echo '

						<textarea rows="10" name="agreement" id="agreement">', $context['agreement'], '</textarea>

						<input type="checkbox" name="requireAgreement" id="requireAgreement"', $context['require_agreement'] ? ' checked="checked"' : '', ' tabindex="', $context['tabindex']++, '" value="1" /> ', $txt['admin_agreement'], '.';

	if (!empty($context['agreement_show_options']))
	{
		echo '

						<input type="checkbox" name="checkboxAgreement" id="checkboxAgreement"', $context['checkbox_agreement'] ? ' checked="checked"' : '', ' tabindex="', $context['tabindex']++, '" value="1" /> ', $txt['admin_checkbox_agreement'], '.';
	}

	echo '

						<input type="checkbox" name="checkboxAcceptAgreement" id="checkboxAcceptAgreement" tabindex="', $context['tabindex']++, '" value="1" /> ', $txt['admin_checkbox_accept_agreement'], '.

						<input type="submit" name="save" value="', $txt['save'], '" tabindex="', $context['tabindex']++, '" />
						<input type="hidden" name="sa" value="', $context['subaction'], '" />
						<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
						<input type="hidden" name="', $context['admin-rega_token_var'], '" value="', $context['admin-rega_token'], '" />

		</form>';
}

/**
 * Interface to edit reserved words in admin panel.
 */
function template_edit_reserved_words()
{
	global $context, $txt;

	echo '
		<form id="admin_form_wrapper" class="content" action="', getUrl('admin', ['action' => 'admin', 'area' => 'regcenter']), '" method="post" accept-charset="UTF-8">

', $txt['admin_reserved_set'], '

', $txt['admin_reserved_line'], '

					<textarea cols="30" rows="6" name="reserved" id="reserved">', implode("\n", $context['reserved_words']), '</textarea>

						', $txt['admin_match_whole'], '

						<input type="checkbox" name="matchword" id="matchword" tabindex="', $context['tabindex']++, '" ', $context['reserved_word_options']['match_word'] ? 'checked="checked"' : '', ' />

						', $txt['admin_match_case'], '

						<input type="checkbox" name="matchcase" id="matchcase" tabindex="', $context['tabindex']++, '" ', $context['reserved_word_options']['match_case'] ? 'checked="checked"' : '', ' />

						', $txt['admin_check_user'], '

						<input type="checkbox" name="matchuser" id="matchuser" tabindex="', $context['tabindex']++, '" ', $context['reserved_word_options']['match_user'] ? 'checked="checked"' : '', ' />

						', $txt['admin_check_display'], '

						<input type="checkbox" name="matchname" id="matchname" tabindex="', $context['tabindex']++, '" ', $context['reserved_word_options']['match_name'] ? 'checked="checked"' : '', ' />

					<input type="submit" value="', $txt['save'], '" name="save_reserved_names" tabindex="', $context['tabindex']++, '" />
					<input type="hidden" name="sa" value="reservednames" />
					<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
					<input type="hidden" name="', $context['admin-regr_token_var'], '" value="', $context['admin-regr_token'], '" />

		</form>';
}

/**
 * Interface for contact form.
 */
function template_contact_form()
{
	global $context, $txt;

	echo '

', $txt['admin_contact_form'], '

		<form id="contact_form" class="content" action="', getUrl('action', ['action' => 'register', 'sa' => 'contact']), '" method="post" accept-charset="UTF-8">

';

	if (!empty($context['errors']))
	{
		echo '

', $txt['errors_contact_form'], ':

', implode('

', $context['errors']), '

';
	}

	echo '

						', $txt['admin_register_email'], '

						<input type="email" name="emailaddress" id="emailaddress" value="', !empty($context['emailaddress']) ? $context['emailaddress'] : '', '" tabindex="', $context['tabindex']++, '" />

						', $txt['contact_your_message'], '

						<textarea id="contactmessage" name="contactmessage" cols="50" rows="10" tabindex="', $context['tabindex']++, '">', !empty($context['contactmessage']) ? $context['contactmessage'] : '', '</textarea>

';

	if (!empty($context['require_verification']))
	{
		template_verification_controls($context['visual_verification_id'], '

							' . $txt['verification'] . ':

							', '

');
	}

	echo '

					<input type="submit" value="', $txt['sendtopic_send'], '" name="send" tabindex="', $context['tabindex']++, '" />
					<input type="hidden" name="sa" value="reservednames" />
					<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
					<input type="hidden" name="', $context['contact_token_var'], '" value="', $context['contact_token'], '" />

		</form>';
}

/**
 * Show a success page when contact form is submitted.
 */
function template_contact_form_done()
{
	global $txt;

	echo '

', $txt['admin_contact_form'], '

', $txt['contact_thankyou'], '
';
}


text:
namespace JustOrderIt.Data.DbAccessConfig.IdentityStores
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;

    using Microsoft.AspNet.Identity.EntityFramework;
    using Models;
    using Models.Identity;

    /// <summary>
    /// Inherits and extends the EntityFramework based user store implementation that supports
    /// IUserStore, IUserLoginStore, IUserClaimStore and IUserRoleStore
    /// </summary>
    public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
    {
        public ApplicationUserStore(DbContext context)
            : base(context)
        {
        }
    }
}


text:
require 'spec_helper'

module Punchblock
  class Event
    describe Ringing do
      it 'registers itself' do
        RayoNode.class_from_registration(:ringing, 'urn:xmpp:rayo:1').should be == described_class
      end

      describe "from a stanza" do
        let :stanza do
          <<-MESSAGE
<ringing xmlns='urn:xmpp:rayo:1'>
  <!-- Signaling (e.g. SIP) Headers -->
  <header name="X-skill" value="agent" />
  <header name="X-customer-id" value="8877" />
</ringing>
          MESSAGE
        end

        subject { RayoNode.from_xml parse_stanza(stanza).root, '9f00061', '1' }

        it { should be_instance_of described_class }

        it_should_behave_like 'event'
        its(:headers) { should == { 'X-skill' => 'agent', 'X-customer-id' => '8877' } }

        context "with no headers provided" do
          let(:stanza) { '<ringing xmlns="urn:xmpp:rayo:1"/>' }

          its(:headers) { should == {} }
        end
      end

      describe "when setting options in initializer" do
        subject { described_class.new headers: { 'X-skill' => 'agent', 'X-customer-id' => '8877' } }

        its(:headers) { should == { 'X-skill' => 'agent', 'X-customer-id' => '8877' } }
      end
    end
  end
end


text:
using System;
using System.Buffers;
using System.Text;
using Xunit;

namespace HarfBuzzSharp.Tests
{
	public class HbFontTest : HBTest
	{
		[SkippableFact]
		public void ShouldHaveDefaultSupportedShapers()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.Equal(new[] { "ot", "fallback" }, font.SupportedShapers);
			}
		}

		[SkippableFact]
		public void ShouldGetGlyphByUnicode()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.True(font.TryGetGlyph('A', out var glyph));
				Assert.Equal(42u, glyph);
			}
		}

		[SkippableFact]
		public void ShouldHaveDefaultScale()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				font.GetScale(out var xScale, out var yScale);
				Assert.Equal(2048, xScale);
				Assert.Equal(2048, yScale);
			}
		}

		[SkippableFact]
		public void ShouldGetHorizontalGlyphOrigin()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				font.TryGetHorizontalGlyphOrigin(49, out var xOrigin, out var yOrigin);
				Assert.Equal(0, xOrigin);
				Assert.Equal(0, yOrigin);
			}
		}

		[SkippableFact]
		public void ShouldGetVerticalGlyphOrigin()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.True(font.TryGetVerticalGlyphOrigin(49, out var xOrigin, out var yOrigin));
				Assert.Equal(557, xOrigin);
				Assert.Equal(1022, yOrigin);
			}
		}

		[SkippableFact]
		public void ShouldGetHorizontalGlyphAdvance()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.Equal(1114, font.GetHorizontalGlyphAdvance(49));
			}
		}

		[SkippableFact]
		public void ShouldGetVerticalGlyphAdvance()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.Equal(-2048, font.GetVerticalGlyphAdvance(49));
			}
		}

		[SkippableFact]
		public void ShouldGetHorizontalGlyphAdvances()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				var advances = font.GetHorizontalGlyphAdvances(new[] { 49u, 50u, 51u });

				Assert.Equal(1114, advances[0]);
				Assert.Equal(514, advances[1]);
				Assert.Equal(602, advances[2]);
			}
		}

		[SkippableFact]
		public void ShouldGetVerticalGlyphAdvances()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				var advances = font.GetVerticalGlyphAdvances(new[] { 49u, 50u, 51u });

				Assert.Equal(-2048, advances[0]);
				Assert.Equal(-2048, advances[1]);
				Assert.Equal(-2048, advances[2]);
			}
		}

		[SkippableFact]
		public void ShouldGetGlyphName()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				font.TryGetGlyphName(49, out var name);

				Assert.Equal("H", name);
			}
		}

		[SkippableFact]
		public void ShouldGetGlyphFromName()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				font.TryGetGlyphFromName("H", out var glyph);

				Assert.Equal(49u, glyph);
			}
		}

		[SkippableFact]
		public void ShouldGetGlyphFromString()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.True(font.TryGetGlyphFromString("H", out var glyph));
				Assert.Equal(49u, glyph);
			}
		}

		[SkippableFact]
		public void ShouldConvertGlyphToString()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				var s = font.GlyphToString(49);

				Assert.Equal("H", s);
			}
		}

		[SkippableFact]
		public void GlyphToStringIsCorrectWithDelegate()
		{
			// get an array and fill it with things
			var pool = ArrayPool<byte>.Shared;
			var buffer = pool.Rent(Font.NameBufferLength);
			for (int i = 0; i < buffer.Length; i++)
				buffer[i] = (byte)i;
			pool.Return(buffer);

			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				var s = font.GlyphToString(49);

				Assert.Equal("H", s);
			}
		}

		[SkippableFact]
		public void ShouldGetGlyphContourPointForOrigin()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.False(font.TryGetGlyphContourPointForOrigin(49, 0, Direction.LeftToRight, out _, out _));
			}
		}

		[SkippableFact]
		public void ShouldGetGlyphContourPoint()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				Assert.False(font.TryGetGlyphContourPoint(49, 0, out _, out _));
			}
		}

		[SkippableFact]
		public void ShouldGetGlyphAdvanceForDirection()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				font.GetGlyphAdvanceForDirection(49, Direction.LeftToRight, out var x, out _);

				Assert.Equal(1114, x);
			}
		}

		[SkippableFact]
		public void ShouldGetHorizontalGlyphKerning()
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				var kerning = font.GetHorizontalGlyphKerning(49, 50);

				Assert.Equal(0, kerning);
			}
		}

		[Theory]
		[InlineData(OpenTypeMetricsTag.UnderlineOffset, -60)]
		[InlineData(OpenTypeMetricsTag.UnderlineSize, 9)]
		[InlineData(OpenTypeMetricsTag.StrikeoutOffset, 1049)]
		[InlineData(OpenTypeMetricsTag.StrikeoutSize, 209)]
		public void ShouldGetOpenTypeMetrics(OpenTypeMetricsTag tag, int expected)
		{
			using (var face = new Face(Blob, 0))
			using (var font = new Font(face))
			{
				var result = font.OpenTypeMetrics.TryGetPosition(tag, out var position);

				Assert.True(result);

				Assert.Equal(expected, position);
			}
		}
	}
}


text:
"""
Half-hearted implementation of
https://en.wikipedia.org/wiki/Canopy_clustering_algorithm
"""

from collections import defaultdict
from mathlib import cosine_similarity

def calculate_similarity(history):
	"""calculate cosine similarity between user

	[description]

	Arguments:
		history {dictionary of list of binary} --
			key <- user_id
			value <- list of user-item interaction (binary)
			example:
			{
				'u1':[0,1,1,1,0],
				'u2':[0,1,1,1,0],
				'u3':[0,1,1,1,0]
			}
	Returns:
		dictionary of similarities --
			key <- user_id_1
			value <- dictionary of float
				key <- user_id_2
				value <- cosine similarity between history of user_id_1 and user_id_2
			example:
			{
				'u1': {'u2': 0.4, 'u3': 0.5},
				'u2': {'u1': 0.4, 'u3': 0.6},
				'u3': {'u1': 0.5, 'u3': 0.6},
			}
	"""

	result = defaultdict(dict)
	users = list(history.keys())
	for i, user1 in enumerate(users):
		for user2 in users[i+1:]:
			x = history[user1]
			y = history[user2]
			distance = cosine_similarity(x, y)
			result[user1][user2] = distance
			result[user2][user1] = distance
	return result

def cluster_canopy(user_similarity, loose=0.3, tight=0.6):
	"""cluster user based on similarity, canopy style

	Arguments:
		user_similarity {dictionary of similarities} -- output of calculate_similarity

	Keyword Arguments:
		loose {number} -- lower bound for outer cluster (default: {0.3})
		tight {number} -- lower bound for inner cluster (default: {0.6})

	Returns:
		dictionary of list of user_id --
			key <- cluster id
			value <- list of cluster member
			{
				0: [1, 2, 3, 6, 7, 8, 9],
				1: [2, 3, 5, 6, 8, 9],
				2: [8, 9, 4, 5],
				3: [8, 5, 6]
			}
	"""

	if loose > tight:
		tight, loose = loose, tight
	users = set(user_similarity.keys())
	clusters = defaultdict(set)
	cluster_number = 0

	while users:
		center = users.pop()
		cluster = set([center])
		removable = set()

		for candidate in users:
			score = user_similarity[center][candidate]
			if score > tight:
				cluster.add(candidate)
				removable.add(candidate)
			elif score > loose:
				cluster.add(candidate)

		for x in removable:
			users.remove(x)

		if cluster:
			clusters[cluster_number] = cluster
			cluster_number += 1
	return clusters

if __name__ == '__main__':
	import random
	history = {}
	user_number = 10
	item_number = 10
	loose = 0.4
	tight = 0.7

	for u in range(user_number):
		h = [random.randint(0, 1) for y in range(item_number)]
		history[u] = h
	user_similarity = calculate_similarity(history)
	s = cluster_canopy(user_similarity, loose, tight)
	print(s)


text:
#import <Cocoa/Cocoa.h>

@interface O2ViewerThumbnailsMatrix : NSMatrix {
    BOOL avoidRecursive;
}

@end

@interface O2ViewerThumbnailsMatrixRepresentedObject : NSObject {
    id _object;
    NSArray* _children;
}

@property(retain) id object;
@property(retain) NSArray* children;

+ (id)object:(id)object;
+ (id)object:(id)object children:(NSArray*)children;

@end


text:
package com.svbio.cloudkeeper.linker;

import com.svbio.cloudkeeper.model.LinkerException;
import com.svbio.cloudkeeper.model.bare.element.BarePluginDeclarationVisitor;
import com.svbio.cloudkeeper.model.bare.element.module.BareCompositeModuleDeclaration;
import com.svbio.cloudkeeper.model.bare.element.module.BareModuleDeclaration;
import com.svbio.cloudkeeper.model.bare.element.module.BareModuleDeclarationVisitor;
import com.svbio.cloudkeeper.model.bare.element.module.BarePort;
import com.svbio.cloudkeeper.model.bare.element.module.BareSimpleModuleDeclaration;
import com.svbio.cloudkeeper.model.runtime.element.RuntimePluginDeclarationVisitor;
import com.svbio.cloudkeeper.model.runtime.element.module.RuntimeModuleDeclaration;

import javax.annotation.Nullable;
import java.util.List;

/**
 * Abstract module declaration, containing static information about a module, such as the name (identifier), in- and
 * out-port types and other aspects.
 *
 * Only simple and composite modules can be declared. Therefore, the only two subclasses are
 * {@link SimpleModuleDeclarationImpl} and {@link CompositeModuleDeclarationImpl}.
 */
abstract class ModuleDeclarationImpl
        extends PluginDeclarationImpl
        implements RuntimeModuleDeclaration, IPortContainerImpl {
    ModuleDeclarationImpl(BareModuleDeclaration original, CopyContext parentContext) throws LinkerException {
        super(original, parentContext);
    }

    private enum CopyVisitor
            implements BareModuleDeclarationVisitor<Try<? extends ModuleDeclarationImpl>, CopyContext> {
        INSTANCE;

        @Override
        @Nullable
        public Try<CompositeModuleDeclarationImpl> visit(BareCompositeModuleDeclaration declaration,
                @Nullable CopyContext parentContext) {
            assert parentContext != null;
            return Try.run(() -> new CompositeModuleDeclarationImpl(declaration, parentContext));
        }

        @Override
        @Nullable
        public Try<SimpleModuleDeclarationImpl> visit(BareSimpleModuleDeclaration declaration,
                @Nullable CopyContext parentContext) {
            assert parentContext != null;
            return Try.run(() -> new SimpleModuleDeclarationImpl(declaration, parentContext));
        }
    }

    static ModuleDeclarationImpl copyOf(BareModuleDeclaration original, CopyContext parentContext)
            throws LinkerException {
        Preconditions.requireNonNull(original, parentContext);
        @Nullable Try<? extends ModuleDeclarationImpl> copyTry = original.accept(CopyVisitor.INSTANCE, parentContext);
        assert copyTry != null;
        return copyTry.get();
    }

    @Override
    @Nullable
    public final <T, P> T accept(BarePluginDeclarationVisitor<T, P> visitor, @Nullable P parameter) {
        return visitor.visit(this, parameter);
    }

    @Override
    @Nullable
    public final <T, P> T accept(RuntimePluginDeclarationVisitor<T, P> visitor, @Nullable P parameter) {
        return visitor.visit(this, parameter);
    }

    @Override
    public final IElementImpl getEnclosingElement() {
        return null;
    }

    /**
     * {@inheritDoc}
     *
     *
Since there is currently no support for inheritance of module declarations, annotations can likewise not be
     * inherited.
     */
    @Override
    @Nullable
    public ModuleDeclarationImpl getSuperAnnotatedConstruct() {
        return null;
    }

    /**
     * Returns the list of ports, similar to {@link #getPorts()} but with weaker return type.
     *
     *
This method may be called (and its return value be used) safely even before the module declaration is fully
     * constructed; that is, before the state is {@link State#PRECOMPUTED}. Once this instance is frozen, this method
     * will return the same reference as {@code #getPorts()}.
     *
     *
Note that this method can be called also if the state is {@link State#PRECOMPUTED}: For instance, when a new
     * proxy module is linked against a fully linked and verified repository.
     *
     *
Since this method is a package-private method, no precaution is taken to prevent exposing internal mutable
     * data structures. Callers are expected not to modify the returned list.
     *
     * @see ProxyModuleImpl#preProcessFreezable(FinishContext)
     */
    abstract List<? extends BarePort> getBarePorts();

    @Override
    final void verifyFreezable(VerifyContext context) { }
}


text:
package com.nh.micro.template;

public interface MicroTranAopInter {
public Object execGroovyRetObjByDbTran(String groovyName, String methodName,Object... paramArray);
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Dialog example - jQuery Mobile Demos</title>
	<link rel="stylesheet" href="../css/themes/default/jquery.mobile-1.4.5.min.css">
	<link rel="stylesheet" href="../_assets/css/jqm-demos.css">
	<link rel="shortcut icon" href="../favicon.ico">

Dialog

Custom overlay

This dialog adds data-overlay-theme="b" to the page container to set the overlay swatch color.

			I like it


text:
class ImageDialogController extends ModalController {
    constructor(options) {
        // console.log('ImageDialogController.constructor', options);
        super(options);
        if (!options.src) throw new Error('no src');
    }
    getViewClass() {
        console.log('ImageDialogController.getViewClass');
        return ImageDialogView;
    }
    getSrc() {
        return this.options.src;
    }
    onCloseClick = async e => {
        await this.close();
    }
    onKeyDown = async e => {
        if (e.key === 'Escape') {
            await this.close();
        }
    }
    onImageClick = async e => {
        console.log('ImageDialogController.onImageClick');
        await this.close();
    }
}


text:
package com.chrisgammage.gwtjitsu.shared;

/**
 * Created with IntelliJ IDEA.
 * User: gammagec
 * Date: 11/1/12
 * Time: 4:54 PM
 */
public @interface AfterSubModelPropertyChanged {
  String subModel();
  String property();
}


text:
from odin import exceptions

class TestValidationException:
    def test_with_string(self):
        test_message = "Test message"
        target = exceptions.ValidationError(test_message)

        assert [test_message] == target.messages
        assert not hasattr(target, "message_dict")
        assert "['Test message']" == str(target)
        assert "ValidationError(['Test message'])" == repr(target)

    def test_with_list(self):
        test_message_list = ["Test message", "Test message 2"]
        target = exceptions.ValidationError(test_message_list)

        assert test_message_list == target.messages
        assert not hasattr(target, "message_dict")
        assert "['Test message', 'Test message 2']" == str(target)
        assert "ValidationError(['Test message', 'Test message 2'])" == repr(target)

    def test_with_dict(self):
        test_message_dict = {
            "Test Key 1": ["Test Message 1"],
            "Test Key 2": ["Test Message 2"],
        }
        target = exceptions.ValidationError(test_message_dict)

        assert test_message_dict == target.message_dict
        assert [
            {
                "Test Key 1": ["Test Message 1"],
                "Test Key 2": ["Test Message 2"],
            }
        ] == target.messages

        expected = {"Test Key 2": ["Test Message 2"], "Test Key 1": ["Test Message 1"]}
        assert expected == target.message_dict
        assert (
            "ValidationError({'Test Key 1': ['Test Message 1'], 'Test Key 2': ['Test Message 2']})"
            == repr(target)
        )


text:
C-API using a Unix domain socket to communicate with the signal broker.

Documentation for the C-API is compilable with [Doxygen](http://doxygen.org/).
To generate the documentation make sure you have doxygen installed.
Then run the script:
```
cd c_lib
./doxygen.sh
```

## Native library
The source is found in the sub directory `c_lib`.
By default the project is set to compile a static library.

To explicitly compile a static library:
```
cmake -D CS_LIBRARY_TYPE:STRING=STATIC <source path>
```
Outputs a `.a` archive.

Explicitly compile a shared library:
```
cmake -D CS_LIBRARY_TYPE:STRING=SHARED <source path>
```
Outputs a `.so` library.

## Prebuilt samples
Prebuild binaries are automatically produced on build `iex -S mix` check out [sample](/apps/app_unixds/priv/sample) for starters.

namespace and signals are defined according to [docs](/apps/app_unixds/c_lib/csunixds.in.h#L35)


text:
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using System.Threading.Tasks;

namespace DesktopAntlrGrammarEditor
{
    public class MessageBox : Window
    {
        public MessageBox()
        {
            InitializeComponent();
        }

        public static async Task<bool> ShowDialog(Window window, string message, string title = "", MessageBoxType messageBoxType = MessageBoxType.Ok)
        {
            var messageBox = new MessageBox(message, title, messageBoxType);
            return await messageBox.ShowDialog<bool>(window);
        }

        public MessageBox(string message, string title = "", MessageBoxType messageBoxType = MessageBoxType.Ok)
        {
            InitializeComponent();
            DataContext = new MessageBoxViewModel(this, message, title, messageBoxType);
            Activate();
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}


text:
OAuth Integration
=================

Overview
--------

OAuth 2 is an open authentication protocol that describes how users can safely
grant third-party applications access to some or all of their accounts with
service providers.  Linode implements OAuth 2 with `https://login.linode.com`_,
allowing third-party developers worlds of possibilities when integrating with
Linode's service.  By making an OAuth application, you can allow users to
grant your app access to create, install, configure, and manage infrastructure
on their behalf.

.. _`https://login.linode.com`: https://login.linode.com

.. note::
   If you are simply trying out the API, or if you're writing a command line
   tool that accepts a Personal Access Token, you can safely skip this guide.

The OAuth 2 workflow has three actors:

.. glossary::

   end user
      The acting user who will log in to the application.

   authentication server
      The server that authorizes logins and issues tokens.  In this case, it will
      be login.linode.com

   client application
      The application you are writing, that Linode users will login to through
      Linode's OAuth server.  You must register OAuth clients at
      https://cloud.linode.com or through
      :any:`oauth_client_create<linode.linode_client.AccountGroup.oauth_client_create>`
      to generate a client ID and client secret (used in the exchange detailed
      below).

The OAuth 2 exchange works as follows:

#. The end user visits the client application's website and attempts to login
   using OAuth.
#. The client application redirects the end user to the authentication server
   with the client application's client ID and requested OAuth scopes in the
   query string.
#. The end user inputs their credentials to the authorization server and
   authorizes the login.
#. The authorization server redirects the end user to the client application
   with a temporary exchange code in the query string.
#. The client application issues a request to the authentication server
   containing the exchange code and the client application's client secret.
#. The authentication server responds to the client application with a newly
   issued OAuth token.

A working example of completing an OAuth exchange using this library is
available in the example project `Install on Linode`_

.. _Install on Linode: https://github.com/linode/linode_api4-python/tree/master/examples/install-on-linode

.. _oauth_scopes:

OAuth Scopes
------------

OAuth scopes define the level of access your client application has to the
accounts of users who authorize against it.  While it may be easier to always
request the broadest scopes, this is discouraged as it is more dangerous for
the end user.  The end user is presented with the requested scopes during the
authorization process and may choose to abort authorization of your application
based on the scopes requested.

OAuth scopes are represented by the
:any:`OAuthScopes<linode.login_client.OAuthScopes>` class, which can be used to
construct lists of scopes to request.  OAuth scopes are divided into
"superscopes," broad categories of entities/actions that may be requested
access to, and "subscopes," the level of access requested to a particular
entity class.  For example, if you are writing a frontend to manage
NodeBalancers, you may need access to create and modify NodeBalancers, and also
to list Linode Instances (to display more information about the individual
backends).  In this hypothetical case, you would likely want to construct your
requested scopes like this::

   requested_scopes = [OAuthScopes.NodeBalancer.all, OAuthScopes.Linodes.view]

Performing an OAuth Login
-------------------------

The :any:`LinodeLoginClient<linode.LinodeLoginClient>` class manages all
aspects of the OAuth exchange in this library.  To create a
:any:`LinodeLoginClient<linode.LinodeLoginClient>`, you must use your client ID
and client secret (generated upon registering a client application with Linode -
see above).::

   login_client = LinodeLoginClient(my_client_id, my_client_secret)

When a user attempts to login to your application using OAuth, you must issue a
redirect to our authentication server (step 2 above).  The
:any:`LinodeLoginClient<linode.LinodeLoginClient>` handles most of the details
of this for you, returning the complete URL to redirect the end user to::

   def begin_oauth_login():
       """
       An example function called when a user attempts to login user OAuth.
       """
       # generate a URL to redirect the user to, requested full access to their
       # account
       redirect_to = login_client.generate_login_url(scopes=OAuthScopes.all)

       # use your web framework to redirect the user to the generated URL
       return redirect(redirect_to)

Once the user has authenticated and approved this login, they will be redirected
to the URL configured when your client application was registered.  Your web
application must accept this request, and should use it to complete the OAuth
exchange (step 5 above)::

   def oauth_redirect(code=None):
       """
       An example callback function when a user authorizes this application.

       :param code: The exchange code provided by the authentication server,
                    present in the query string of the request.
       :type code: str
       """
       token, scopes = login_client.finish_oauth(code)

       # token is a valid OAuth token that may be used to construct a
       # LinodeClient and access the API on behalf of this user.

Now that you have been issued a token, be sure to keep it secret and specific
to this user - it should be tied to their session if possible.

Logging Out
-----------

When a user logs out of their account, you *must* call
:any:`LoginClient.expire_token<linode.LinodeLoginClient.expire_token>` with the
token issued to your application.  This will invalidate the OAuth token the
user generated by logging in, which will completely revoke their session.
Simply invalidating their session in your application and leaving their OAuth
token active is *not* a complete logout, and should be avoided.


text:
18. Editor of a Scholarly Journal, Service on an Editorial Advisory Board or Reviewer For a Scholarly Journal

	<form class="form-horizontal" novalidate>

    	<textarea data-ng-model="section18" name="section18" class="form-control" cols="30" rows="10" placeholder="Content" ui-tinymce="tinymceOptions"></textarea>

	        <button type="submit" class="col-md-offset-9 btn btn-primary" ng-click="update()">
	        	 Save
	        </button>

	</form>


text: String


text:
module Codebreaker
  class Marker
    def initialize(secret, guess)
      @secret = secret
      @guess = guess
    end

    def exact_match?(guess, index)
      guess[index] == @secret[index]
    end

    def number_match?(guess , index)
      @secret.include? guess[index] and not exact_match? guess, index
    end

    def exact_match_count
      (0 .. 3).inject(0) do |count, index|
        count + ((exact_match? @guess, index) ? 1 : 0)
      end
    end

    def number_match_count
      total_match_count - exact_match_count
    end

    def total_match_count
      secret = @secret.split('')
      @guess.split('').inject(0) do |count, n|
        count + (delete_first(secret, n) ? 1 : 0)
      end
    end

    def delete_first(code, n)
      code.delete_at(code.index(n)) if code.index(n)
    end
  end
end


text:
namespace Azure.ResourceManager.Storage.Models
{
    /// <summary> An error response from the Storage service. </summary>
    internal partial class CloudErrorAutoGenerated
    {
        /// <summary> Initializes a new instance of CloudErrorAutoGenerated. </summary>
        internal CloudErrorAutoGenerated()
        {
        }

        /// <summary> Initializes a new instance of CloudErrorAutoGenerated. </summary>
        /// <param name="error"> An error response from the Storage service. </param>
        internal CloudErrorAutoGenerated(CloudErrorBodyAutoGenerated error)
        {
            Error = error;
        }

        /// <summary> An error response from the Storage service. </summary>
        public CloudErrorBodyAutoGenerated Error { get; }
    }
}


text:
module Mount
  require 'mount/version'
  require 'mount/command'
end


text:
Swagger to OPENi types
======================

This module creates PEAT types from the specified swagger resource file.

* By default only models associated with PUT and POST actions are created. The -a flag overrides this and creates all.

* A file is created which maps the endpoint and the action to the type id in the OPENi platform.

Options
=========

Options:

    -h, --help                  output usage information
    -V, --version               output the version number
    -s, --swagger [value]       Link to root Swagger resource.
    -o, --openi_server [value]  OPENi server where the types are to be created.
    -f, --file_output [value]   File where output is written to.
    -a, --all                   If specified all Swagger Models are created, otherwise just models associated with PUT operations are created.

Samples
=========

node main.js -s https://dev.peat-platform.org/api-spec/v1/api_framework -o dev.peat-platform.org -f out.json

```json

```

node main.js -s http://petstore.swagger.wordnik.com/api/api-docs -o dev.peat-platform.org -f out.json -a


text:
layout: page
show_meta: false
title: "Upcoming Workshops"
header:
   image_fullwidth: "wood_plank.jpg"
permalink: "/workshops-upcoming/"
---

These are the upcoming workshops. Most are first advertised to the organization running the workshop, but some are open to other participants.

Don't see a workshop in your area, but wish there was one?

Become a host and request a workshop!

  {% for w in site.data.amy.workshops_current reversed %}

    {{w.venue}}
    {{w.humandate}}

  {% endfor %}


text:
Socket.IO and Go-FTL
====================================

This has been tested to work with version 1.4.7 through 1.7.4 of Socket.IO.    A newer version
of this will work with version 2.x of Socket.IO.


text:
module MetricFu
  class RoodiGrapher < Grapher
    attr_accessor :roodi_count, :labels

    def initialize
      super
      @roodi_count = []
      @labels = {}
    end

    def get_metrics(metrics, date)
      if metrics && metrics[:roodi]
        @roodi_count.push(metrics[:roodi][:problems].size)
        @labels.update( { @labels.size => date })
      end
    end
  end
end


text:
      <form class="form-inline">

      </form>

      <form accept-charset="utf-8" class="form-horizontal">

            Mode

            <select ng-options="m for m in modes" class="form-control" ng-model="config.mode">
            </select>

            Export Opts

            <input type="text" id="password" ng-model="config.exportOptions" class="form-control">

            Delay

            <input type="text" i="" placeholder="host" ng-model="config.delay" class="form-control">

            First Time

            <input type="text" placeholder="port" ng-model="config.firstTime" class="form-control">

            Target Directory

            <input type="text" placeholder="port" ng-model="config.targetDirectory" class="form-control">

            Target File Name

            <input type="text" placeholder="port" ng-model="config.targetFileName" class="form-control">

            Compression Level

            <input type="text" placeholder="port" ng-model="config.compressionLevel" class="form-control">

            Buffer Size

            <input type="text" id="port" placeholder="port" ng-model="config.bufferSize" class="form-control">

      </form>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hkust.coursecatalog.coursecatalog" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:name=".BaseApplication">
        <activity
            android:name="com.hkust.coursecatalog.coursecatalog.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>[cf354] B. Pyramid of Glasses — amoshyc's CPsolution 1.0 documentation</title>

    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="../../_static/css/mine.css" type="text/css" />

        <link rel="index" title="Index"
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="amoshyc's CPsolution 1.0 documentation" href="../../index.html"/>
        <link rel="up" title="#354" href="index.html"/>
        <link rel="next" title="[cf354] C. Vasya and String" href="pc.html"/>
        <link rel="prev" title="[cf354] A. Nicholas and Permutation" href="pa.html"/>

             amoshyc's CPsolution

                1.0

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

1. 常用演算法教學

2. CF

Regular Round

#375

#372

#371

#369

#368

#367

#354

[cf354] A. Nicholas and Permutation

[cf354] B. Pyramid of Glasses

[cf354] C. Vasya and String

[cf354] D. Theseus and labyrinth

[cf354] E. The Last Fight Between Human and AI

#353

#346

#343

#342

#319

Educational Round

Gym

3. POJ

4. UVA

5. PTC

6. Other

7. Template

8. Tags

9. Cheatsheet

          amoshyc's CPsolution

Docs »

2. CF »

#354 »

[cf354] B. Pyramid of Glasses

             View page source

[cf354] B. Pyramid of Glasses¶

Tags

tag_dp

TOC

[cf354] B. Pyramid of Glasses

題目

Specification

分析

AC Code 1

AC Code 2

題目¶

N 層的酒杯金字塔,每秒從頂端倒容量為一酒杯的香檳。
當一個酒杯已經滿了,流到它的香檳會往左往右流,各 1/2 的流量,流至下一層的酒杯中。
流動視為瞬間發生的事情,請問倒 T 秒後,有多少酒杯是滿的?

Specification¶

1 <= N <= 10
1 <= T <= 10^4

分析¶

Note

dp

流動是瞬間的,所以題目可以視為有 T 杯的香檳從頂端流下,問有多少酒杯會滿。

對於第 r 層,左邊數來的第 c 個酒杯,如果流到它的香檳量是 dp[r][c],那根據題意:

dp[r + 1][c + 0] += (dp[r][c] - 1) / 2
dp[r + 1][c + 1] += (dp[r][c] - 1) / 2

初使條件:

dp[i][j] = 0
dp[0][0] = T

轉移方程式會出現 Fraction…,所以 dp 每一項都要用 Fractioni 存。
用 c++ 不好實作,可以改用 python,有內建的 Fraction。

之後枚舉所有酒杯,看有多少酒杯是滿的即可。

所以如果要用 c++ 實作,可以只記錄分子。
分母可由公式推出。見 code

AC Code 1¶

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

from fractions import Fraction

inp = input().split()
N, T = int(inp[0]), int(inp[1])

if T is 0:
    print(0)
    exit()

dp = []
for r in range(N + 1):
    dp.append([Fraction(0) for _ in range(N + 1)])

dp[0][0] = Fraction(T)
for r in range(N):
    for c in range(r + 1):
        if dp[r][c] >= Fraction(1):
            dp[r + 1][c + 0] += (dp[r][c] - Fraction(1)) / Fraction(2);
            dp[r + 1][c + 1] += (dp[r][c] - Fraction(1)) / Fraction(2);

cnt = 0
for r in range(N):
    for c in range(r + 1):
        if dp[r][c] >= Fraction(1):
            cnt += 1

print(cnt)

AC Code 2¶

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int N, T; cin >> N >> T;

    ll dp[N + 1][N + 1]; // store the numerators only
    memset(dp, 0, sizeof(dp));

    // see my previous python3 AC code for clearness
    dp[0][0] = T;
    for (int r = 0; r < N; r++) {
        for (int c = 0; c <= r; c++) {
            if (dp[r][c] >= (1 << r)) { // (1 << r) is denominator
                dp[r + 1][c + 0] += (dp[r][c] - (1 << r));
                dp[r + 1][c + 1] += (dp[r][c] - (1 << r));
            }
        }
    }

    int cnt = 0;
    for (int r = 0; r < N; r++) {
        for (int c = 0; c <= r; c++) {
            if (dp[r][c] >= (1 << r)) {
                cnt++;
            }
        }
    }

    cout << cnt << endl;

    return 0;
}

        Next

         Previous

        © Copyright 2016, amoshyc.

  Built with Sphinx using a theme provided by Read the Docs.


text:
import {
    expect
} from 'chai';
import calculateCellWidthIndex from './../src/calculateCellWidthIndex';

describe('calculateCellWidthIndex', () => {
  context('all cells have different width', () => {
    it('describes each cell contents width', () => {
      const cellWidthIndex = calculateCellWidthIndex([
        'a',
        'aaa',
        'aaaaaa'
      ]);

      expect(cellWidthIndex[0]).to.equal(1, 'first column');
      expect(cellWidthIndex[1]).to.equal(3, 'second column');
      expect(cellWidthIndex[2]).to.equal(6, 'third column');
    });
  });
});


text:
.censusTable {
    width: 100%;
    border: 0 none;
    border-collapse:separate !important;
    margin: 0;
    padding: 0;
}

.censusTable th
{
    padding: 8px 5px;
    height: 15px;
    font-weight: bold;
    background: url(/umbraco_client/tabView/images/background.gif) 0 0 repeat-x #d9d7d7;
    border:0 none;
    border-bottom: 1px solid #c9c7c7;
    width: auto !important;
    text-align: left;
}
.censusTable td
{
    padding: 5px;
    background: #fff;
    border:0 none;
    border-bottom:1px solid #d9d7d7;
    border-collapse:separate;
    vertical-align:top;
}

.censusTable thead th:first-child, .censusTable tr td:first-child { border-left:1px solid #CCCCCC; }
.censusTable thead th:last-child, .censusTable tr td:last-child { border-right:1px solid #CCCCCC; }
.censusTable thead tr th { border-bottom:1px solid #CCCCCC; }
.censusTable thead th { border-top:1px solid #CCCCCC; }

.censusTable tbody tr:last-child td       { border-bottom:1px solid #CCCCCC; }
.censusTable tbody tr:first-child td      { border-top:1px solid silver; }

.description {
    padding: 8px 0 3px 5px;
    display: inline-block;
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.common.parsers.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * A very simple Dictionary backed by a tab delimited file.
 */
public abstract class FileBasedDictionaryParser<T> extends DictionaryBackedParser<T> {

  public FileBasedDictionaryParser(boolean caseSensitive) {
    super(caseSensitive);
  }

  protected void init(InputStream input) {
    init(input, null);
  }

  /**
   * Init the parser to read the InputStream and ignore lines starting with the commentMarker.
   *
   * @param input
   * @param commentMarker marker identifying a commented line (e.g. #) or null to read all lines
   */
  protected void init(InputStream input, String commentMarker) {
    init(new Source(input, commentMarker));
  }

  /**
   * Returns the value read from the dictionary as an instance of <T>
   *
   * @param value
   * @return
   */
  protected abstract T fromDictFile(String value);

  /**
   * An iterator over a well formed tab file.
   * Should the file be poorly formed expect runtime exceptions.
   */
  class Source implements Iterator<KeyValue<String, T>> {

    private final BufferedReader r;
    private final Pattern tab = Pattern.compile("\t");
    private final String commentMarker;
    private String line = null;

    Source(InputStream file) {
      this(file, null);
    }

    Source(InputStream file, String commentMarker) {
      r = new BufferedReader(new InputStreamReader(file, StandardCharsets.UTF_8));
      this.commentMarker = commentMarker;
    }

    @Override
    public boolean hasNext() {
      if (line != null) {
        return true;
      }

      try {
        // we discard empty or commented lines
        do {
          line = r.readLine();
        } while (line != null && !isValidLine(line));
      } catch (IOException ignored) {
        close();
        return false;
      }

      if (line == null) {
        close();
        return false;
      } else {
        return true;
      }
    }

    /**
     * Check if a line is valid or not.
     * A valid line is not a comment (if configured) and should be in the form "key<tab>value".
     *
     * @param line
     * @return
     */
    private boolean isValidLine(String line) {
      if (line == null) {
        return false;
      }

      if (commentMarker != null) {
        if (line.startsWith(commentMarker)) {
          return false;
        }
      }
      return (tab.split(line).length == 2);
    }

    @Override
    public KeyValue<String, T> next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }

      String[] atoms = tab.split(line);
      line = null;
      return new KeyValue<>(StringUtils.trimToNull(atoms[0]), fromDictFile(StringUtils.trimToNull(atoms[1])));
    }

    @Override
    public void remove() {
    }

    public void close() {
      if (r != null) {
        try {
          r.close();
        } catch (IOException ignored) {
        }
      }
    }
  }
}


text:
/* eslint-disable no-param-reassign */
/* eslint-disable strict */
/* eslint-disable no-unused-expressions */

// Use strict mode so that we can use let and const.
'use strict';

const exec = require('child_process').exec;
const simpleGit = require('simple-git');
const path = require('path');

const container = {
  css: null,
  html: null,
  js: null,
  rb: null,
  py: null,
  json: null,
  pdf: null,
  png: null,
};

function modifiedAnimation(info, object, item, string) {
  for (let i = 0, len = info.length; i < len; i++) {
    if (info[i].indexOf(item) > -1) {
      object.level = '#ccc';
      object.icon = `assets/64pxRed/${string}.png`;
      return;
    }
  }
  return;
}

function terminalParse(item, object) {
  let itemParse;
  if (item[item.length - 1] === '/') {
    itemParse = 'folder';
    object.name = item.substring(0, item.length - 1);
    object.type = 'directory';
    object.icon = 'assets/64pxBlue/folder.png';
  } else {
    itemParse = item.replace(/^\w+./, '');
    if (!(itemParse in container)) itemParse = 'file';
    object.icon = `assets/64pxBlue/${itemParse}.png`;
    return itemParse;
  }
  return itemParse;
}

const schemaMaker = (termOutput, directoryName, modified) => {
  let schema = {
    name: directoryName,
    children: [],
    position_x: '-10px',
    position_y: '-20px',
    value: 40,
    icon: 'assets/64pxBlue/folder.png',
    level: '#ccc',
  };

  // Loop through reply and put it into a structure D3 can read
  termOutput.forEach(index => {
    if (index === '' || (index[0] === '.' && index.substring(0, 4) !== '.git')) return undefined;
    const elementObj = {
      name: index,
      level: '#ccc',
    };
    if (index.substring(0, 4) === '.git') {
      if (index.substring(index.length - 1) === '/') {
        elementObj.icon = 'assets/folder.png';
        elementObj.name = index.substring(0, index.length - 1);
      } else {
        elementObj.icon = 'assets/git.png';
      }
      schema.children.push(elementObj);
      return undefined;
    }

    const temp = terminalParse(index, elementObj);
    if (modified) modifiedAnimation(modified, elementObj, index, temp);
    schema.children.push(elementObj);
    return undefined;
  });
  schema = [schema];
  return schema;
};

module.exports = {
  dataSchema(pwd, asyncWaterfallCallback) {
    // child process that gets all items in a directory
    const command = `cd ${pwd}; ls -ap;`;

    exec(command, (err, stdout) => {
      const stdoutArr = stdout.split('\n');
      const currentDirectoryName = path.parse(pwd).name;
      let modifiedFiles;
      // git command to check git status
      simpleGit(pwd).status((error, i) => {
        modifiedFiles = i.modified;
        const schema = schemaMaker(stdoutArr, currentDirectoryName, modifiedFiles);
        process.send ? process.send({ schema }) : asyncWaterfallCallback(null, schema);
        return schema;
      });
    });
  },
  schemaMaker,
};


text:
<!DOCTYPE html>

    <title>Kanban App</title>
    <link rel="stylesheet" href="styles.css">


text:
planets
=======

practice repo swc umich


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.02.08 at 03:02:05 PM PST
//

package com.wb.nextgenlibrary.parser.md.schema.v2_3;

import com.wb.nextgenlibrary.parser.XmlEnum;
import com.wb.nextgenlibrary.parser.XmlType;

/**
 *
Java class for string-DisplayIndicators.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="string-DisplayIndicators">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="CC"/>
 *     <enumeration value="F"/>
 *     <enumeration value="P"/>
 *     <enumeration value="DD"/>
 *     <enumeration value="SAP"/>
 *     <enumeration value="DVS"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "string-DisplayIndicators")
@XmlEnum
public enum StringDisplayIndicators {

    CC,
    F,
    P,
    DD,
    SAP,
    DVS;

    public String value() {
        return name();
    }

    public static StringDisplayIndicators fromValue(String v) {
        return valueOf(v);
    }

}


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

<title>Engine</title>
<meta name="date" content="2015-02-21">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

engine

Class Engine

java.lang.Object

engine.Engine

public class Engine
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

Engine()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
Gen(Difficulty dif)

void
Hide()

Retire un % de nombre de la grille de manière aléatoire

void
Load(java.lang.String saveName)

Charge une grille depuis un fichier

boolean
LoadFromCloud(Difficulty dif)

Télécharge une grille depuis files.darkube.net

int[][]
PlayGrille()

int[][]
ResolvedGrid()

void
Save(java.lang.String saveName)

Ecrit la grille dans fichier

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Engine

public Engine()

Method Detail

Gen

public void Gen(Difficulty dif)

Hide

public void Hide()

Retire un % de nombre de la grille de manière aléatoire

PlayGrille

public int[][] PlayGrille()

ResolvedGrid

public int[][] ResolvedGrid()

Save

public void Save(java.lang.String saveName)

Ecrit la grille dans fichier

Parameters:

saveName - Nom de la Sauvegarde

Load

public void Load(java.lang.String saveName)

Charge une grille depuis un fichier

Parameters:

saveName - Nom de la Sauvegarde

LoadFromCloud

public boolean LoadFromCloud(Difficulty dif)

Télécharge une grille depuis files.darkube.net

Parameters:

dif - La Difficule de la grille suivant l'enum Difficulty

Returns:

true si la récuperation est résusie

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceská Mykol. 22: 18 (1966)

#### Original name
Lactarius pilatii Z. Schaef.

### Remarks
null


text:
package org.scalex
package model

case class Comment(

    /** The main body of the comment that describes what the entity does and is.  */
    body: Block,

    /** A shorter version of the body. Usually, this is the first sentence of the body. */
    /** left empty if similar to body */
    summary: Option[Block],

    /**
     * A list of other resources to see, including links to other entities or
     * to external documentation. The empty list is used when no other resource
     * is mentionned.
     */
    see: List[Block],

    /**
     * A description of the result of the entity. Typically, this provides additional
     * information on the domain of the result, contractual post-conditions, etc.
     */
    result: Option[Block],

    /**
     * A map of exceptions that the entity can throw when accessed, and a
     * description of what they mean.
     */
    throws: Map[String, Block],

    /**
     * A map of value parameters, and a description of what they are. Typically,
     * this provides additional information on the domain of the parameters,
     * contractual pre-conditions, etc.
     */
    valueParams: Map[String, Block],

    /**
     * A map of type parameters, and a description of what they are. Typically,
     * this provides additional information on the domain of the parameters.
     */
    typeParams: Map[String, Block],

    /**
     * The version number of the entity. There is no formatting or further
     * meaning attached to this value.
     */
    version: Option[Block],

    /** A version number of a containing entity where this member-entity was introduced. */
    since: Option[Block],

    /** An annotation as to expected changes on this entity. */
    todo: List[Block],

    /**
     * Whether the entity is deprecated. Using the `@deprecated` Scala attribute
     * is prefereable to using this Scaladoc tag.
     */
    deprecated: Option[Block],

    /** An additional note concerning the contract of the entity. */
    note: List[Block],

    /** A usage example related to the entity. */
    example: List[Block],

    /** A description for the primary constructor */
    constructor: Option[Block]) {

  def summaryOrBody = summary | body

  override def toString =
    body.toString + "\n" +
      (result map ("@return " + _.toString)).mkString("\n") +
      (version map ("@version " + _.toString)).mkString
}


text:
using System;
using System.Globalization;
using Xunit;

namespace System.Globalization.Tests
{
    public class DateTimeFormatInfoUniversalSortableDateTimePattern
    {
        // PosTest1: Call UniversalSortableDateTimePattern getter method should return correct value for InvariantInfo
        [Fact]
        public void TestGetter()
        {
            VerificationHelper(DateTimeFormatInfo.InvariantInfo, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'");
            VerificationHelper(new CultureInfo("en-us").DateTimeFormat, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'");
            VerificationHelper(new CultureInfo("ja-jp").DateTimeFormat, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'");
            VerificationHelper(new CultureInfo("fr-fr").DateTimeFormat, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'");
        }

        private void VerificationHelper(DateTimeFormatInfo info, string expected)
        {
            string actual = info.UniversalSortableDateTimePattern;
            Assert.Equal(expected, actual);
        }
    }
}


text:
package org.onesocialweb.model.vcard4;

public abstract class URLField extends Field
{

public static final String NAME = "url";

	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public String getValue() {
		return getURL();
	}

	@Override
	public boolean isValid() {
		return true;
	}

	public abstract String getURL();

	public abstract void setURL(String url);
}


text:
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    QPushButton button("hello world");
    button.show();
    return app.exec();
}


text:
package org.apache.geronimo.bval;

import javax.naming.NamingException;
import javax.naming.Reference;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import org.apache.xbean.naming.reference.SimpleReference;

/**
 * @version $Rev$ $Date$
 */
public class DefaultValidatorFactoryReference extends SimpleReference {
    private ValidatorFactory factory;

    @Override
    public Object getContent() throws NamingException {
        if(factory == null) {
            factory = Validation.buildDefaultValidatorFactory();
        }

        return factory;
    }
}


text:
package com.amb.bus.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.core.event.AbstractRepositoryEventListener;
import org.springframework.stereotype.Component;

import com.amb.Utility;
import com.amb.bus.BusOrder;
import com.amb.bus.service.MailService;
import com.amb.core.Customer;

/**
 * Event listener to reject {@code DELETE} requests to Spring Data REST.
 *
 * @author Oliver Gierke
 */
@Component
class BusOrderControllerEventListener extends AbstractRepositoryEventListener<BusOrder> {

	@Autowired
	MailService mailService;

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.rest.repository.context.AbstractRepositoryEventListener#onBeforeDelete(java.lang.Object)
	 */
	@Override
	protected void onBeforeCreate(BusOrder order) {
		order.setBookingRefId(Utility.generateBookingRefNumber(6).toString());
		order.setTotalPrice(order.getBusRoute().getFare().multiply(order.getOrderItems().size()));

		// create customer
		String firstName = order.getOrderItems().get(0).getPassengerFirstName();
		String lastName = order.getOrderItems().get(0).getPassengerLastName();
		String email = order.getBuyerEmailAddress();
		String contact = order.getBuyerMobileNumber();

		Customer customer = new Customer(firstName, lastName, email, contact);
		order.setCustomer(customer);
	}

	@Override
	protected void onAfterCreate(BusOrder order) {
		mailService.sendEmail(order);
	}
}


text:
namespace CoCSharp.Network.Cryptography.NaCl.Internal
{
    internal static class verify_16
    {
        public static int crypto_verify(byte[] x, int xoffset, byte[] y)
        {
            int differentbits = 0;

            for (int i = 0; i < 15; i++)
                differentbits |= (x[xoffset + i] ^ y[i]) & 0xff;

            return (1 & (int)(((uint)differentbits - 1) >> 8)) - 1;
        }
    }
}


text:
namespace StudentSystem.Common
{
    using System;
    using System.Linq;

    public static class ConnectionStrings
    {
        public const string StudentSystemConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=StudentSystem;Integrated Security=True";
    }
}


text:
use serde_json::Value;
use tantivy::aggregation::agg_req::{
    Aggregation, Aggregations, BucketAggregation, BucketAggregationType, MetricAggregation,
    RangeAggregation,
};
use tantivy::aggregation::agg_result::AggregationResults;
use tantivy::aggregation::metric::AverageAggregation;
use tantivy::aggregation::AggregationCollector;
use tantivy::query::TermQuery;
use tantivy::schema::{self, Cardinality, IndexRecordOption, Schema, TextFieldIndexing};
use tantivy::{doc, Index, Term};

fn main() -> tantivy::Result<()> {
    let mut schema_builder = Schema::builder();
    let text_fieldtype = schema::TextOptions::default()
        .set_indexing_options(
            TextFieldIndexing::default().set_index_option(IndexRecordOption::WithFreqs),
        )
        .set_stored();
    let text_field = schema_builder.add_text_field("text", text_fieldtype);
    let score_fieldtype =
        crate::schema::NumericOptions::default().set_fast(Cardinality::SingleValue);
    let highscore_field = schema_builder.add_f64_field("highscore", score_fieldtype.clone());
    let price_field = schema_builder.add_f64_field("price", score_fieldtype.clone());

    let schema = schema_builder.build();

    // # Indexing documents
    //
    // Lets index a bunch of documents for this example.
    let index = Index::create_in_ram(schema);

    let mut index_writer = index.writer(50_000_000)?;
    // writing the segment
    index_writer.add_document(doc!(
        text_field => "cool",
        highscore_field => 1f64,
        price_field => 0f64,
    ))?;
    index_writer.add_document(doc!(
        text_field => "cool",
        highscore_field => 3f64,
        price_field => 1f64,
    ))?;
    index_writer.add_document(doc!(
        text_field => "cool",
        highscore_field => 5f64,
        price_field => 1f64,
    ))?;
    index_writer.add_document(doc!(
        text_field => "nohit",
        highscore_field => 6f64,
        price_field => 2f64,
    ))?;
    index_writer.add_document(doc!(
        text_field => "cool",
        highscore_field => 7f64,
        price_field => 2f64,
    ))?;
    index_writer.commit()?;
    index_writer.add_document(doc!(
        text_field => "cool",
        highscore_field => 11f64,
        price_field => 10f64,
    ))?;
    index_writer.add_document(doc!(
        text_field => "cool",
        highscore_field => 14f64,
        price_field => 15f64,
    ))?;

    index_writer.add_document(doc!(
        text_field => "cool",
        highscore_field => 15f64,
        price_field => 20f64,
    ))?;

    index_writer.commit()?;

    let reader = index.reader()?;
    let text_field = reader.searcher().schema().get_field("text").unwrap();

    let term_query = TermQuery::new(
        Term::from_field_text(text_field, "cool"),
        IndexRecordOption::Basic,
    );

    let sub_agg_req_1: Aggregations = vec![(
        "average_price".to_string(),
        Aggregation::Metric(MetricAggregation::Average(
            AverageAggregation::from_field_name("price".to_string()),
        )),
    )]
    .into_iter()
    .collect();

    let agg_req_1: Aggregations = vec![(
        "score_ranges".to_string(),
        Aggregation::Bucket(BucketAggregation {
            bucket_agg: BucketAggregationType::Range(RangeAggregation {
                field: "highscore".to_string(),
                ranges: vec![
                    (-1f64..9f64).into(),
                    (9f64..14f64).into(),
                    (14f64..20f64).into(),
                ],
            }),
            sub_aggregation: sub_agg_req_1.clone(),
        }),
    )]
    .into_iter()
    .collect();

    let collector = AggregationCollector::from_aggs(agg_req_1);

    let searcher = reader.searcher();
    let agg_res: AggregationResults = searcher.search(&term_query, &collector).unwrap();

    let res: Value = serde_json::from_str(&serde_json::to_string(&agg_res)?)?;
    println!("{}", serde_json::to_string_pretty(&res)?);

    Ok(())
}


text:
class BlobGameParser
{
public:

	BlobGameParser() {};

	bool Parse(const std::string& path);

	std::vector<MassAggregate*> GetMassAggregates() { return mp_MassAggregate; }

	ConstantGravityForceGenerator* GetGravity(){ return mp_Gravity; };
	GameObject* GetGround() { return mp_Ground; };

private:

	struct AggregateData
	{
		Vector3D Position;
		Color Color;
		float Size;
		float Mass;
	};

	void ParseGround(tinyxml2::XMLElement* dataElement);
	void ParseGravity(tinyxml2::XMLElement* dataElement);
	void ParseTetrahedronData(tinyxml2::XMLElement* dataElement);
	void ParseCubeData(tinyxml2::XMLElement* dataElement);
	void ParsePyramidData(tinyxml2::XMLElement* dataElement);

	AggregateData ParseAggregateData(tinyxml2::XMLElement* dataElement);

	std::vector<MassAggregate*> mp_MassAggregate;

	ConstantGravityForceGenerator* mp_Gravity;

	GameObject* mp_Ground;

};
#endif


text:
<?php

namespace spec\SharedExamples\Genesis\API\Request\Financial;

use Genesis\Exceptions\ErrorParameter;
use Genesis\Exceptions\InvalidArgument;

trait TokenizationAttributesExamples
{
    public function it_should_not_fail_when_missing_consumer_id()
    {
        $this->setRequestParameters();
        $this->setConsumerId(null);

        $this->shouldNotThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_fail_with_token_and_card_number_in_same_request()
    {
        $faker = $this->getFaker();

        $this->setRequestParameters();
        $this->setToken($faker->word);

        $this->shouldThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_fail_with_remember_card_and_without_card_number()
    {
        $this->setRequestParameters();
        $this->setRememberCard(true);
        $this->setCardNumber(null);

        $this->shouldThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_fail_with_both_set_remember_card_and_token()
    {
        $faker = $this->getFaker();

        $this->setRequestParameters();
        $this->setCardNumber(null);

        $this->setToken($faker->word);
        $this->setRememberCard(true);

        $this->shouldThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_fail_without_token_card_number_and_remember_card()
    {
        $this->setRequestParameters();
        $this->setCardNumber(null);
        $this->setToken(null);

        $this->shouldThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_fail_with_token_and_without_consumer_id()
    {
        $faker = $this->getFaker();

        $this->setRequestParameters();
        $this->setCardNumber(null);
        $this->setToken($faker->word);
        $this->setConsumerId(null);

        $this->shouldThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_not_fail_with_token_and_with_consumer_id()
    {
        $faker = $this->getFaker();

        $this->setRequestParameters();
        $this->setCardNumber(null);

        $this->setToken($faker->sha256);
        $this->setConsumerId($faker->numberBetween(1, PHP_INT_MAX));

        $this->shouldNotThrow()
            ->during('getDocument');
    }

    public function it_should_not_fail_without_consumer_id()
    {
        $this->setRequestParameters();
        $this->setRememberCard(true);

        $this->shouldNotThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_not_fail_with_consumer_id()
    {
        $faker = $this->getFaker();

        $this->setRequestParameters();
        $this->setRememberCard(true);
        $this->setConsumerId($faker->numberBetween());

        $this->shouldNotThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_fail_with_remember_card_and_without_customer_email()
    {
        $this->setRequestParameters();
        $this->setRememberCard(true);
        $this->setCustomerEmail(null);

        $this->shouldThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_fail_without_customer_email_and_with_consumer_id()
    {
        $this->setRequestParameters();
        $this->setConsumerId('12345');
        $this->setCustomerEmail(null);

        $this->shouldThrow(ErrorParameter::class)
            ->during('getDocument');
    }

    public function it_should_be_false_remember_card()
    {
        $faker = $this->getFaker();

       $this->setRememberCard($faker->randomElement(['false', false, 0]));

       $this->getRememberCard()->shouldBe(false);
    }

    public function it_should_be_true_remember_card()
    {
        $faker = $this->getFaker();

        $this->setRememberCard($faker->randomElement(['true', true, 1]));
        $this->getRememberCard()->shouldBe(true);
    }
}