text:
import { Component, Input, OnChanges } from '@angular/core'
import { CHALLENGE_DIFFICULTY } from '../../shared/types'

@Component({
	selector: 'gt-challenge-difficulty',
	styles: [`
		:host {
			text-align: center !important;
			opacity: .8;
			display: inline-block;
			line-height: 20px;
		}

		:host md-icon {
			width: auto;
			height: auto;
			font-size: 16px !important;
			line-height: 18px;
			vertical-align: text-top;
		}

		.name {
			font-weight: bold;
			display: block;
		}

		.easy { color: green; }
		.medium { color: darkorange; }
		.hard { color: crimson; }
	`],
	template: `
	<b class="difficulty {{ passive ? '' : (name | lowercase) }}" [class.with-name]="full"
	title="Challenge Difficulty: {{ name | uppercase }}">
		<span *ngIf="full" class="name">{{ name }}</span>
		<template [ngIf]="level === levels.EASY">
			<md-icon>star</md-icon>
			<md-icon>star_border</md-icon>
			<md-icon>star_border</md-icon>
		</template>
		<template [ngIf]="level === levels.INTERMEDIATE">
			<md-icon>star</md-icon>
			<md-icon>star</md-icon>
			<md-icon>star_border</md-icon>
		</template>
		<template [ngIf]="level === levels.HARD">
			<md-icon>star</md-icon>
			<md-icon>star</md-icon>
			<md-icon>star</md-icon>
		</template>
	</b>
	`
})
export class ChallengeDifficultyComponent implements OnChanges {
	@Input() level: CHALLENGE_DIFFICULTY
	@Input() full: boolean
	@Input() passive: boolean

	levels = CHALLENGE_DIFFICULTY
	name: string

	ngOnChanges() {
		switch (this.level) {
			case CHALLENGE_DIFFICULTY.EASY:
				this.name = 'Easy'
				break

			case CHALLENGE_DIFFICULTY.INTERMEDIATE:
				this.name = 'Medium'
				break

			case CHALLENGE_DIFFICULTY.HARD:
				this.name = 'Hard'
				break
		}
	}
}


text:
<?php

declare(strict_types=1);

namespace Eloquent\Phony\Kahlan;

/**
 * A place for namespaced global state.
 */
class Globals
{
    /**
     * The container used by the static facade and facade functions.
     *
     * @var FacadeContainer
     */
    public static $container;
}

redpajama_set_name: RedPajamaGithub


text:
export class A {}

// This test is testing the case where the exported class is also repeated in
// the name of the module. Here we export C from exporting.C.
export class C {}


text:
#include <copybit.h>
struct copybit_iterator : public copybit_region_t {
    copybit_iterator(const copybit_rect_t& rect) {
        mRect = rect;
        mCount = 1;
        this->next = iterate;
    }
private:
    static int iterate(copybit_region_t const * self, copybit_rect_t* rect) {
        if (!self || !rect) {
            return 0;
        }

        copybit_iterator const* me = static_cast<copybit_iterator const*>(self);
        if (me->mCount) {
            rect->l = me->mRect.l;
            rect->t = me->mRect.t;
            rect->r = me->mRect.r;
            rect->b = me->mRect.b;
            me->mCount--;
            return 1;
        }
        return 0;
    }
    copybit_rect_t mRect;
    mutable int mCount;
};


text:
package self.micromagic.util.container;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import junit.framework.TestCase;

public class RequestParameterMapTest extends TestCase
{
	public void testEntrySet()
	{
		HashMap map = new HashMap();
		map.put("k1", "v1");
		map.put("k2", new Integer(2));
		map.put("k3", new String[]{"a", "b", "c"});
		map.put("k4", Arrays.asList(new Object[]{new Integer(100), "200", new Long(300L)}));
		map.put("k5", new Object[]{new Integer(110), "220", new Long(330L)});
		RequestParameterMap rmap = RequestParameterMap.create(map);
		rmap.setParseValue(true);

		Iterator itr = rmap.entrySet().iterator();
		while (itr.hasNext())
		{
			Map.Entry entry = (Map.Entry) itr.next();
			assertTrue(entry.getValue() instanceof String);
		}

		itr = rmap.values().iterator();
		while (itr.hasNext())
		{
			assertTrue(itr.next() instanceof String);
		}

	}

	public void testGetValue()
	{
		HashMap map = new HashMap();
		map.put("k1", "v1");
		map.put("k2", new Integer(2));
		map.put("k3", new String[]{"a", "b", "c"});
		map.put("k4", Arrays.asList(new Object[]{new Integer(100), "200", new Long(300L)}));
		map.put("k5", new Object[]{new Integer(110), "220", new Long(330L)});
		RequestParameterMap rmap = RequestParameterMap.create(map);
		rmap.setParseValue(true);

		assertEquals(rmap.get("k1"), "v1");
		assertEquals(rmap.get("k2"), "2");
		assertEquals(rmap.get("k3"), "a");
		assertEquals(rmap.get("k4"), "100");
		assertEquals(rmap.get("k5"), "110");
		assertEquals(rmap.get("k6"), null);

		String[] arr;

		arr = (String[]) rmap.get("k1[]");
		assertEquals(arr.length, 1);
		assertEquals(arr[0], "v1");

		arr = (String[]) rmap.get("k2[]");
		assertEquals(arr.length, 1);
		assertEquals(arr[0], "2");

		arr = (String[]) rmap.get("k3[]");
		assertEquals(arr.length, 3);
		assertTrue(Arrays.equals(arr, new String[]{"a", "b", "c"}));

		arr = (String[]) rmap.get("k4[]");
		assertEquals(arr.length, 3);
		assertTrue(Arrays.equals(arr, new String[]{"100", "200", "300"}));

		arr = (String[]) rmap.get("k5[]");
		assertEquals(arr.length, 3);
		assertTrue(Arrays.equals(arr, new String[]{"110", "220", "330"}));

		arr = (String[]) rmap.get("k6[]");
		assertEquals(arr, null);
	}

}


text:
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AdventureWorks.WebServices.Models;
using AdventureWorks.WebServices.Repositories;
using AdventureWorks.WebServices.Strings;

namespace AdventureWorks.WebServices.Controllers
{
    public class PaymentMethodController : ApiController
    {
        private readonly IPaymentMethodRepository _paymentMethodRepository;

        public PaymentMethodController():this(new PaymentMethodRepository())
        {
        }

        public PaymentMethodController(IPaymentMethodRepository paymentMethodRepository)
        {
            _paymentMethodRepository = paymentMethodRepository;
        }

        // GET /api/PaymentMethod
        [Authorize]
        public IEnumerable<PaymentMethod> GetAll()
        {
            return _paymentMethodRepository.GetAll(this.User.Identity.Name);
        }

        // POST /api/PaymentMethod
        [Authorize]
        public HttpResponseMessage PostAddress(PaymentMethod paymentMethod)
        {
            if (paymentMethod == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, Resources.InvalidAddress);
            }

            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            _paymentMethodRepository.AddUpdate(this.User.Identity.Name, paymentMethod);
            return Request.CreateResponse(HttpStatusCode.OK, true);
        }

        // PUT /api/PaymentMethod?defaultPaymentMethodId=[defaultAddressId]
        [Authorize]
        public HttpResponseMessage Put(string defaultPaymentMethodId)
        {
            _paymentMethodRepository.SetDefault(this.User.Identity.Name, defaultPaymentMethodId);
            return Request.CreateResponse(HttpStatusCode.OK, true);
        }
    }
}


text:
package org.apache.shardingsphere.database.protocol.postgresql.packet.command;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.database.protocol.packet.CommandPacketType;

/**
 * Command packet type for PostgreSQL.
 */
@RequiredArgsConstructor
@Getter
public enum PostgreSQLCommandPacketType implements CommandPacketType {

    AUTHENTICATION_OK('R'),

    AUTHENTICATION_KERBEROS_V5('R'),

    AUTHENTICATION_CLEARTEXT_PASSWORD('R'),

    AUTHENTICATION_MD5_PASSWORD('R'),

    AUTHENTICATION_SCM_CREDENTIAL('R'),

    AUTHENTICATION_GSS('R'),

    AUTHENTICATION_SSPI('R'),

    AUTHENTICATION_GSS_CONTINUE('R'),

    AUTHENTICATION_SASL('R'),

    AUTHENTICATION_SASL_CONTINUE('R'),

    AUTHENTICATION_SASL_FINAL('R'),

    QUERY('Q'),

    PARSE('P'),

    BIND('B'),

    DESCRIBE('D'),

    EXECUTE('E'),

    SYNC('S'),

    PARSE_COMPLETE('1'),

    BIND_COMPLETE('2'),

    ROW_DESCRIPTION('T'),

    DATA_ROW('D'),

    COMMAND_COMPLETE('C'),

    READY_FOR_QUERY('Z'),

    CLOSE('C'),

    CLOSE_COMPLETE('3'),

    BACKEND_KEY_DATA('K'),

    COPY_DATA('d'),

    COPY_DONE('c'),

    COPY_FAIL('f'),

    COPY_IN_RESPONSE('G'),

    COPY_OUT_RESPONSE('H'),

    COPY_BOTH_RESPONSE('W'),

    EMPTY_QUERY_RESPONSE('I'),

    ERROR_RESPONSE('E'),

    FLUSH('H'),

    FUNCTION_CALL('F'),

    FUNCTION_CALL_RESPONSE('V'),

    GSS_RESPONSE('p'),

    NEGOTIATE_PROTOCOL_VERSION('v'),

    NO_DATA('n'),

    NOTICE_RESPONSE('N'),

    NOTIFICATION_RESPONSE('A'),

    PARAMETER_DESCRIPTION('t'),

    PARAMETER_STATUS('S'),

    PASSWORD_MESSAGE('p'),

    PORTAL_SUSPENDED('s'),

    SASL_INITIAL_RESPONSE('p'),

    SASL_RESPONSE('p'),

    TERMINATE('X');

    private final char value;

    /**
     * Value of integer.
     *
     * @param value integer value
     * @return command packet type enum
     */
    public static PostgreSQLCommandPacketType valueOf(final int value) {
        for (PostgreSQLCommandPacketType each : PostgreSQLCommandPacketType.values()) {
            if (value == each.value) {
                return each;
            }
        }
        throw new IllegalArgumentException(String.format("Cannot find '%s' in PostgreSQL command packet type", value));
    }
}


text:
_IMPORTANT:_ there has been a change in the SignalK API url construct used by sQuidd.io. /api/v1 is no longer supported. Install the latest version of signalk-oauth-server as previous ones will not work!

SignalK Server with client Oauth Authentication
================

An experimental implementation of a [Signal K](http://signalk.org) server using OAuth2 Authentication through sQuidd.io.
It allows you to control access to your Signalk server without the need to manage user credentials, passwords, certificates etc. locally. It also provides the server with access to a number of sQuidd.io [authenticated APIs](https://squidd.io/api_docs) for the sharing and retrieval of vessel GPS position, NMEA status updates and general nautical information (see below).

Kicking the tires with a live SignalK Oauth server on sQuidd.io
------------------

Before you try anything on your own SignalK Oauth server, you may want to peek at a demo implementation of the SignalK Oauth server running on sQuiddio. To do that:

* Obtain a (free) sQuidd.io account at https://squidd.io/signup if you don't already have one. Create a boat (it will be needed to obtain an authentication Application ID and Secret for your SignalK Oauth server and to log in). [Update](https://squidd.io/positions/new) your boat's current position. Some of the sample API requests require a known vessel position).

* Go to https://squidd.io::27065 and sign in

Select one of the few sample queries in the home page or view the live streaming page for real-time log updates. (Note that the demo server is located on a fictitious boat - Sloop sQuiddio - so "self" is not your boat in this case. You are simply asked to authorize the demo server to use your sQuiddio account to log in)
                                                                                .

## Get up and running with your own authenticated SignalK Server

#### Prerequisites:
* MongoDB previously installed on the server (used to store credentials). Refer to the installation instructions for your OS. Here's what I used on [Ubuntu 14.04](https://www.digitalocean.com/community/tutorials/how-to-install-mongodb-on-ubuntu-14-04). Alternatively, you can use a cloud-based version of MongoDB (e.g. Mongolab).
* A sQuiddio account with at least one boat defined. Create at least one manual [position report](https://squidd.io/positions/new) and, if you feel like it, create a follow list. Some of the sample API calls in the home menu require a known position and a follow list.
* Node and npm installed. See [instructions](https://github.com/signalk/signalk-server-node) directly at the official SignalK repo.

* Get the repo with `git clone https://github.com/mauroc/signalk-oauth-node.git`

* Go to the directory where you put the downloaded code and install dependencies with
````
npm install
````

#### Basic Settings
* Configure your server by creating the settings/oauth-settings.json file like so:
````
{
    "clientID":       "<your sQuiddio Application ID>",
    "clientSecret":   "<your sQuiddio secret>",
    "serverName":     "Authenticated SignalK Server on <your boat name>",
    "localStorage":   "mongodb://localhost/test",

    "authServer":       "https://squidd.io",
    "tokenURL":         "https://squidd.io/oauth/token",
    "authorizationURL": "https://squidd.io/oauth/authorize",
    "profileURL":       "https://squidd.io/apps/v1/api/users/me",
    "callbackURL":      "https://localhost::27065/login/squiddio/callback",
    "sessionDuration":  86400
}
````
Note:
* _clientID and clientSecret_: Obtain these by logging into your sQuidd.io account and clicking on the boat's link in the Dashboard to access the boat's profile (create a boat if you have not done it yet). Then edit your boat's profile and go to the APIs tab.  More info in the [FAQs](http://squidd.io/faq).
* _localStorage_: The MongoDB database uri (e.g. MongoDB://localhost/test) if you intend to use a local version of MongoDB to store user's credentials. If you use a cloud version (e.g. Mongolab), you can enter the service url. On Mongolab, it will look something like this: 'url' : 'mongodb://mymongodb:mymongodb123@ds041404.mongolab.com:41404/squiddio_test'
* _authServer....profileURL_: The authentication endpoints on sQuiddio. Leave the default values as indicated above.
* _callbackURL_: The value above works in most cases. If not, replace localhost::27065 with whatever host name and port you use for your authenticated SignalK. For instance, if you run SignalK Oauth on a headless server on your boat's LAN, you can enter the LAN address followed by port number, e.g. 192.168.1.55:3000. In this case you also need to update the default callback url in your boat profile, APIs tab.
* _sessionDuration_: The expiration time in seconds of the session cookie.
* remember to add settings/oauth-settings.json to your .gitinore file to avoid publishing your keys to the an online repo.

Add the following setting to the SignalK settings files you will be using (for instance, nmea-from-file.json or myboat-tcp-settings.json ) as a first-level JSON key/value pair (for instance, right before your "pipedProviders" key/value pair):
````
"ssl": true
````
This tells SignalK to accept *only https requests*, which is a good idea since the server will exchange private information, such as tokens and API keys, with the authentication server.

#### Optional Settings
* By default _anyone with a sQuiddio account can log into the server_. Add the following option to your settings file to restrict access to only members of your sQuiddio's [follow list](http://squidd.io/faq#follow_list):
````
"friendsOnly": 1
````
* You can set up the Signalk Oauth server to automatically share your latest GPS position and the most recent NMEA messages with other sQuiddio users periodically by adding the setting:
````
 "updInterval": 120
````
 where 120 is the number of seconds between updates (minimum is 10). Obviously, there must be an active Internet connection available to the server at the time of the post (or the update will be skipped - no store-and-forward in the current version). Position updates are reflected in your and sQuiddio dashboard and to users in your Follow List, [iFrame-enabled](http://blog.squidd.io/2015/07/sharing-your-positions-map-on-your-blog.html) blogs and web sites and users of the [OpenCPN plugin](http://squidd.io/squiddio_pi).

#### Start the server:
````
bin/nmea-from-file
````

#### Use
Point your browser to https://localhost::27065 (or whatever the hostname/port of your sever) and try the various requests on the home page with and without logging in. You will also be provided with a command to try an authenticated websocket request in terminal, using the wscat command.  The first time you log in, you will be redirected to a sQuiddio page asking your permission to share basic account information (first any last name, user id, email address) with the Signalk server.

How it works
----
Read this [wiki article](https://github.com/mauroc/signalk-oauth-node/wiki/The-%22skinny%22-on-how-SignalK-Oauth-works) if you want to find out more.

Related information
----
* API [discovery.json](https://squidd.io/signalk)
* API [interactive console](https://squidd.io/api_docs)

Create your own authenticated app:
* [squiddio-omniauth](https://github.com/mauroc/omniauth-squiddio) gem for Ruby on Rails
* [passport-squiddio](https://github.com/mauroc/passport-squiddio) oauth module for Node.js

License
-------
Copyright [2016] [Mauro Calvi, Fabian Tollenaar, Teppo Kurki and SignalK committers]

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.


text:
HKScript::HKScript(void)
{
    HK::instance<HKStore>().init(&m_engine);

    m_engine.globalObject().setProperty("HK"     , m_engine.newQObject(&HK::instance<HKFunctions>()));
    m_engine.globalObject().setProperty("HKStore", m_engine.newQObject(&HK::instance<HKStore>()));
}

void HKScript::evaluate(const QString& value)
{
    if (value.isEmpty()) return;
    QString program;
    QFileInfo info(value);
    if (info.isFile())
    {
        qDebug("[HKScript] value is file: %s", info.fileName().toUtf8().data());
        QFile script(value);
        if (script.open(QIODevice::ReadOnly))
        {
            QTextStream stream(&script);
            program = stream.readAll();
            script.close();
        }
    }
    else
    {
        program = value;
    }
    m_engine.evaluate(program);
}


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

<title>GNU Compiler Collection (GCC) Internals: Function Properties</title>

<meta name="description" content="GNU Compiler Collection (GCC) Internals: Function Properties">
<meta name="keywords" content="GNU Compiler Collection (GCC) Internals: Function Properties">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Functions.html#Functions" rel="up" title="Functions">
<link href="Language_002ddependent-trees.html#Language_002ddependent-trees" rel="next" title="Language-dependent trees">
<link href="Function-Basics.html#Function-Basics" rel="prev" title="Function Basics">

Previous: Function Basics, Up: Functions   [Contents][Index]

10.8.2 Function Properties

To determine the scope of a function, you can use the
DECL_CONTEXT macro.  This macro will return the class
(either a RECORD_TYPE or a UNION_TYPE) or namespace (a
NAMESPACE_DECL) of which the function is a member.  For a virtual
function, this macro returns the class in which the function was
actually defined, not the base class in which the virtual declaration
occurred.

In C, the DECL_CONTEXT for a function maybe another function.
This representation indicates that the GNU nested function extension
is in use.  For details on the semantics of nested functions, see the
GCC Manual.  The nested function can refer to local variables in its
containing function.  Such references are not explicitly marked in the
tree structure; back ends must look at the DECL_CONTEXT for the
referenced VAR_DECL.  If the DECL_CONTEXT for the
referenced VAR_DECL is not the same as the function currently
being processed, and neither DECL_EXTERNAL nor
TREE_STATIC hold, then the reference is to a local variable in
a containing function, and the back end must take appropriate action.

DECL_EXTERNAL

This predicate holds if the function is undefined.

TREE_PUBLIC

This predicate holds if the function has external linkage.

TREE_STATIC

This predicate holds if the function has been defined.

TREE_THIS_VOLATILE

This predicate holds if the function does not return normally.

TREE_READONLY

This predicate holds if the function can only read its arguments.

DECL_PURE_P

This predicate holds if the function can only read its arguments, but
may also read global memory.

DECL_VIRTUAL_P

This predicate holds if the function is virtual.

DECL_ARTIFICIAL

This macro holds if the function was implicitly generated by the
compiler, rather than explicitly declared.  In addition to implicitly
generated class member functions, this macro holds for the special
functions created to implement static initialization and destruction, to
compute run-time type information, and so forth.

DECL_FUNCTION_SPECIFIC_TARGET

This macro returns a tree node that holds the target options that are
to be used to compile this particular function or NULL_TREE if
the function is to be compiled with the target options specified on
the command line.

DECL_FUNCTION_SPECIFIC_OPTIMIZATION

This macro returns a tree node that holds the optimization options
that are to be used to compile this particular function or
NULL_TREE if the function is to be compiled with the
optimization options specified on the command line.

Previous: Function Basics, Up: Functions   [Contents][Index]


text:
package apple.uikit.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NInt;

@Generated
public final class UIAlertViewStyle {
    @Generated @NInt public static final long Default = 0x0000000000000000L;
    @Generated @NInt public static final long SecureTextInput = 0x0000000000000001L;
    @Generated @NInt public static final long PlainTextInput = 0x0000000000000002L;
    @Generated @NInt public static final long LoginAndPasswordInput = 0x0000000000000003L;

    @Generated
    private UIAlertViewStyle() {
    }
}


text:
try:
    import koji
    from koji_cli.lib import activate_session
    HAS_KOJI = True
except ImportError:
    HAS_KOJI = False

def get_session(profile):
    """
    Return an anonymous koji session for this profile name.

    :param str profile: profile name, like "koji" or "cbs"
    :returns: anonymous koji.ClientSession
    """
    # Note: this raises koji.ConfigurationError if we could not find this
    # profile name.
    # (ie. "check /etc/koji.conf.d/*.conf")
    conf = koji.read_config(profile)
    conf['authtype'] = 'noauth'
    hub = conf['server']
    session = koji.ClientSession(hub, {})
    activate_session(session, conf)
    return session

def get_koji_pathinfo(profile):
    """
    Return a Koji PathInfo object for our profile.

    :param str profile: profile name, like "koji" or "cbs"
    :returns: koji.PathInfo
    """
    conf = koji.read_config(profile)
    top = conf['topurl']  # or 'topdir' here for NFS access
    pathinfo = koji.PathInfo(topdir=top)
    return pathinfo


text:
#include <aws/acm/model/ListTagsForCertificateRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ACM::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListTagsForCertificateRequest::ListTagsForCertificateRequest() :
    m_certificateArnHasBeenSet(false)
{
}

Aws::String ListTagsForCertificateRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_certificateArnHasBeenSet)
  {
   payload.WithString("CertificateArn", m_certificateArn);

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection ListTagsForCertificateRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CertificateManager.ListTagsForCertificate"));
  return headers;

}


text:
module.exports = function(grunt)
{
    'use strict';

    var Routes = require('./lib/routes.js');

    // the main task
    grunt.registerMultiTask('acf', 'exports ACF fields', function()
    {
        var self = this,
            options = this.options({
                encoding: grunt.file.defaultEncoding,
            });

        new Routes(options, grunt, self);
    });
};


text:
import datetime
import functools
import logging

import markdown
import pytz
from django.db.models.expressions import F
from django.db.models.aggregates import Max
from django.core.exceptions import ValidationError
from django.utils import timezone
from framework.auth.core import Auth
from addons.base.models import BaseNodeSettings
from bleach.callbacks import nofollow
from bleach import Cleaner
from functools import partial
from bleach.linkifier import LinkifyFilter
from django.db import models
from framework.forms.utils import sanitize
from markdown.extensions import codehilite, fenced_code, wikilinks
from osf.models import NodeLog, OSFUser, Comment
from osf.models.base import BaseModel, GuidMixin, ObjectIDMixin
from osf.models.spam import SpamStatus
from osf.utils.fields import NonNaiveDateTimeField
from osf.utils.requests import get_request_and_user_id, string_type_request_headers
from osf.exceptions import NodeStateError
from addons.wiki import utils as wiki_utils
from addons.wiki.exceptions import (
    PageCannotRenameError,
    PageConflictError,
)
from website.util import api_v2_url
from website.files.exceptions import VersionNotFoundError
from website import settings

from .exceptions import (
    NameEmptyError,
    NameInvalidError,
    NameMaximumLengthError,
)

logger = logging.getLogger(__name__)

SHAREJS_HOST = 'localhost'
SHAREJS_PORT = 7007
SHAREJS_URL = '{}:{}'.format(SHAREJS_HOST, SHAREJS_PORT)

SHAREJS_DB_NAME = 'sharejs'
SHAREJS_DB_URL = 'mongodb://{}:{}/{}'.format(settings.DB_HOST, settings.DB_PORT, SHAREJS_DB_NAME)

# TODO: Change to release date for wiki change
WIKI_CHANGE_DATE = datetime.datetime.utcfromtimestamp(1423760098).replace(tzinfo=pytz.utc)

def validate_page_name(value):
    value = (value or '').strip()

    if not value:
        # TODO: determine if this if possible anymore, deprecate if not
        raise NameEmptyError('Page name cannot be blank.')
    if value.find('/') != -1:
        raise NameInvalidError('Page name cannot contain forward slashes.')
    if len(value) > 100:
        raise NameMaximumLengthError('Page name cannot be greater than 100 characters.')
    return True

def build_html_output(content, node):
    return markdown.markdown(
        content,
        extensions=[
            wikilinks.WikiLinkExtension(
                configs=[
                    ('base_url', ''),
                    ('end_url', ''),
                    ('build_url', functools.partial(build_wiki_url, node))
                ]
            ),
            fenced_code.FencedCodeExtension(),
            codehilite.CodeHiliteExtension(
                [('css_class', 'highlight')]
            )
        ]
    )

def render_content(content, node):
    html_output = build_html_output(content, node)

    # linkify gets called after santize, because we're adding rel="nofollow"
    #   to <a> elements - but don't want to allow them for other elements.
    sanitized_content = sanitize(html_output, **settings.WIKI_WHITELIST)
    return sanitized_content

def build_wiki_url(node, label, base, end):
    return '/{pid}/wiki/{wname}/'.format(pid=node._id, wname=label)

class WikiVersionNodeManager(models.Manager):

    def get_for_node(self, node, name=None, version=None, id=None):
        if name:
            wiki_page = WikiPage.objects.get_for_node(node, name)
            if not wiki_page:
                return None

            if version == 'previous':
                version = wiki_page.current_version_number - 1
            elif version == 'current' or version is None:
                version = wiki_page.current_version_number
            elif not ((isinstance(version, int) or version.isdigit())):
                return None

            try:
                return wiki_page.get_version(version=version)
            except WikiVersion.DoesNotExist:
                return None
        return WikiVersion.load(id)

class WikiVersion(ObjectIDMixin, BaseModel):
    objects = WikiVersionNodeManager()

    user = models.ForeignKey('osf.OSFUser', null=True, blank=True, on_delete=models.CASCADE)
    wiki_page = models.ForeignKey('WikiPage', null=True, blank=True, on_delete=models.CASCADE, related_name='versions')
    content = models.TextField(default='', blank=True)
    identifier = models.IntegerField(default=1)

    @property
    def is_current(self):
        return not self.wiki_page.deleted and self.id == self.wiki_page.versions.order_by('-created').first().id

    def html(self, node):
        """The cleaned HTML of the page"""
        html_output = build_html_output(self.content, node=node)
        try:
            cleaner = Cleaner(
                tags=settings.WIKI_WHITELIST['tags'],
                attributes=settings.WIKI_WHITELIST['attributes'],
                styles=settings.WIKI_WHITELIST['styles'],
                filters=[partial(LinkifyFilter, callbacks=[nofollow, ])]
            )
            return cleaner.clean(html_output)
        except TypeError:
            logger.warning('Returning unlinkified content.')
            return render_content(self.content, node=node)

    def raw_text(self, node):
        """ The raw text of the page, suitable for using in a test search"""

        return sanitize(self.html(node), tags=[], strip=True)

    @property
    def rendered_before_update(self):
        return self.created < WIKI_CHANGE_DATE

    def get_draft(self, node):
        """
        Return most recently edited version of wiki, whether that is the
        last saved version or the most recent sharejs draft.
        """

        db = wiki_utils.share_db()
        sharejs_uuid = wiki_utils.get_sharejs_uuid(node, self.wiki_page.page_name)

        doc_item = db['docs'].find_one({'_id': sharejs_uuid})
        if doc_item:
            sharejs_version = doc_item['_v']
            sharejs_timestamp = doc_item['_m']['mtime']
            sharejs_timestamp /= 1000  # Convert to appropriate units
            sharejs_date = datetime.datetime.utcfromtimestamp(sharejs_timestamp).replace(tzinfo=pytz.utc)

            if sharejs_version > 1 and sharejs_date > self.created:
                return doc_item['_data']

        return self.content

    def save(self, *args, **kwargs):
        rv = super(WikiVersion, self).save(*args, **kwargs)
        if self.wiki_page.node:
            self.wiki_page.node.update_search()
        self.wiki_page.modified = self.created
        self.wiki_page.save()
        self.check_spam()
        return rv

    def check_spam(self):
        request, user_id = get_request_and_user_id()
        user = OSFUser.load(user_id)
        request_headers = string_type_request_headers(request)
        node = self.wiki_page.node

        if not settings.SPAM_CHECK_ENABLED:
            return False
        if settings.SPAM_CHECK_PUBLIC_ONLY and not node.is_public:
            return False
        if user.spam_status == SpamStatus.HAM:
            return False

        content = self._get_spam_content(node)
        if not content:
            return
        is_spam = node.do_check_spam(
            user.fullname,
            user.username,
            content,
            request_headers
        )

        logger.info("Node ({}) '{}' smells like {} (tip: {})".format(
            node._id, node.title.encode('utf-8'), 'SPAM' if is_spam else 'HAM', node.spam_pro_tip
        ))
        if is_spam:
            node._check_spam_user(user)
        return is_spam

    def _get_spam_content(self, node):
        content = []
        content.append(self.raw_text(node))
        if not content:
            return None
        return ' '.join(content)

    def clone_version(self, wiki_page, user):
        """Clone a node wiki page.
        :param wiki_page: The wiki_page you want attached to the clone.
        :return: The cloned wiki version
        """
        clone = self.clone()
        clone.wiki_page = wiki_page
        clone.user = user
        clone.save()
        return clone

    @property
    def absolute_api_v2_url(self):
        path = '/wiki_versions/{}/'.format(self._id)
        return api_v2_url(path)

    # used by django and DRF
    def get_absolute_url(self):
        return self.absolute_api_v2_url

class WikiPageNodeManager(models.Manager):

    def create_for_node(self, node, name, content, auth):
        existing_wiki_page = WikiPage.objects.get_for_node(node, name)
        if existing_wiki_page:
            raise NodeStateError('Wiki Page already exists.')

        wiki_page = WikiPage.objects.create(
            node=node,
            page_name=name,
            user=auth.user
        )
        # Creates a WikiVersion object
        wiki_page.update(auth.user, content)
        return wiki_page

    def get_for_node(self, node, name=None, id=None):
        if name:
            try:
                name = (name or '').strip()
                return WikiPage.objects.get(page_name__iexact=name, deleted__isnull=True, node=node)
            except WikiPage.DoesNotExist:
                return None
        return WikiPage.load(id)

    def get_wiki_pages_latest(self, node):
        wiki_page_ids = node.wikis.filter(deleted__isnull=True).values_list('id', flat=True)
        return WikiVersion.objects.annotate(name=F('wiki_page__page_name'), newest_version=Max('wiki_page__versions__identifier')).filter(identifier=F('newest_version'), wiki_page__id__in=wiki_page_ids)

    def include_wiki_settings(self, node):
        """Check if node meets requirements to make publicly editable."""
        return node.get_descendants_recursive()

class WikiPage(GuidMixin, BaseModel):
    objects = WikiPageNodeManager()

    page_name = models.CharField(max_length=200, validators=[validate_page_name, ])
    user = models.ForeignKey('osf.OSFUser', null=True, blank=True, on_delete=models.CASCADE)
    node = models.ForeignKey('osf.AbstractNode', null=True, blank=True, on_delete=models.CASCADE, related_name='wikis')
    deleted = NonNaiveDateTimeField(blank=True, null=True, db_index=True)

    class Meta:
        indexes = [
            models.Index(fields=['page_name', 'node'])
        ]

    def save(self, *args, **kwargs):
        rv = super(WikiPage, self).save(*args, **kwargs)
        if self.node and self.node.is_public:
            self.node.update_search()
        return rv

    def update(self, user, content):
        """
        Updates the wiki with the provided content by creating a new version

        :param user: The user that is updating the wiki
        :param content: Latest content for wiki
        """
        version = WikiVersion(user=user, wiki_page=self, content=content, identifier=self.current_version_number + 1)
        version.save()

        self.node.add_log(
            action=NodeLog.WIKI_UPDATED,
            params={
                'project': self.node.parent_id,
                'node': self.node._primary_key,
                'page': self.page_name,
                'page_id': self._primary_key,
                'version': version.identifier,
            },
            auth=Auth(user),
            log_date=version.created,
            save=True
        )
        return version

    def update_active_sharejs(self, node):
        """
        Update all active sharejs sessions with latest wiki content.
        """

        """
        TODO: This def is meant to be used after updating wiki content via
        the v2 API, once updating has been implemented. It should be removed
        if not used for that purpose.
        """

        sharejs_uuid = wiki_utils.get_sharejs_uuid(node, self.page_name)
        contributors = [user._id for user in node.contributors]
        wiki_utils.broadcast_to_sharejs('reload',
                                        sharejs_uuid,
                                        data=contributors)

    def belongs_to_node(self, node_id):
        """Check whether the wiki is attached to the specified node."""
        return self.node._id == node_id

    @property
    def current_version_number(self):
        return self.versions.order_by('-created').values_list('identifier', flat=True).first() or 0

    @property
    def url(self):
        return u'{}wiki/{}/'.format(self.node.url, self.page_name)

    def get_version(self, version=None):
        if version:
            ret = self.versions.filter(identifier=version).order_by('-created').first()
            if not ret:
                raise VersionNotFoundError(version)
            return ret
        else:
            return self.versions.order_by('-created').first()

    def get_versions(self):
        return self.versions.all().order_by('-created')

    @property
    def root_target_page(self):
        """The comment page type associated with WikiPages."""
        return 'wiki'

    @property
    def deep_url(self):
        return u'{}wiki/{}/'.format(self.node.deep_url, self.page_name)

    def clone_wiki_page(self, copy, user, save=True):
        """Clone a wiki page.
        :param node: The Node of the cloned wiki page
        :return: The cloned wiki page
        """
        new_wiki_page = self.clone()
        new_wiki_page.node = copy
        new_wiki_page.user = user
        new_wiki_page.save()
        for version in self.versions.all().order_by('created'):
            new_version = version.clone_version(new_wiki_page, user)
            if save:
                new_version.save()
        return

    @classmethod
    def clone_wiki_pages(cls, node, copy, user, save=True):
        """Clone wiki pages for a forked or registered project.
        First clones the WikiPage, then clones all WikiPage versions.
        :param node: The Node that was forked/registered
        :param copy: The fork/registration
        :param user: The user who forked or registered the node
        :param save: Whether to save the fork/registration
        :return: copy
        """
        for wiki_page in node.wikis.filter(deleted__isnull=True):
            wiki_page.clone_wiki_page(copy, user, save)
        return copy

    def to_json(self, user):
        return {}

    def get_extra_log_params(self, comment):
        return {'wiki': {'name': self.page_name, 'url': comment.get_comment_page_url()}}

    # For Comment API compatibility
    @property
    def target_type(self):
        """The object "type" used in the OSF v2 API."""
        return 'wiki'

    # used by django and DRF
    def get_absolute_url(self):
        return self.absolute_api_v2_url

    @property
    def absolute_api_v2_url(self):
        path = '/wikis/{}/'.format(self._id)
        return api_v2_url(path)

    def rename(self, new_name, auth):
        """
        Rename the wiki page with the new_name. Logs this information to the wiki's node.

        :param new_name: A string, the new page's name, e.g. ``"My Renamed Page"``.
        :param auth: All the auth information including user, API key.
        """
        new_name = (new_name or '').strip()
        existing_wiki_page = WikiPage.objects.get_for_node(self.node, new_name)
        key = wiki_utils.to_mongo_key(self.page_name)
        new_key = wiki_utils.to_mongo_key(new_name)

        if key == 'home':
            raise PageCannotRenameError('Cannot rename wiki home page')
        if (existing_wiki_page and not existing_wiki_page.deleted and key != new_key) or new_key == 'home':
            raise PageConflictError(
                'Page already exists with name {0}'.format(
                    new_name,
                )
            )

        # rename the page first in case we hit a validation exception.
        old_name = self.page_name
        self.page_name = new_name

        # TODO: merge historical records like update (prevents log breaks)
        # transfer the old page versions/current keys to the new name.
        if key != new_key:
            if key in self.node.wiki_private_uuids:
                self.node.wiki_private_uuids[new_key] = self.node.wiki_private_uuids[key]
                del self.node.wiki_private_uuids[key]

        self.node.add_log(
            action=NodeLog.WIKI_RENAMED,
            params={
                'project': self.node.parent_id,
                'node': self.node._primary_key,
                'page': self.page_name,
                'page_id': self._primary_key,
                'old_page': old_name,
                'version': self.current_version_number,
            },
            auth=auth,
            save=True,
        )
        self.save()
        return self

    def delete(self, auth):
        """
        Marks the wiki as deleted by setting the deleted field to the current datetime.
        Logs this information to the wiki's node.

        :param auth: All the auth information including user, API key.
        """
        if self.page_name.lower() == 'home':
            raise ValidationError('The home wiki page cannot be deleted.')
        self.deleted = timezone.now()

        Comment.objects.filter(root_target=self.guids.first()).update(root_target=None)

        self.node.add_log(
            action=NodeLog.WIKI_DELETED,
            params={
                'project': self.node.parent_id,
                'node': self.node._primary_key,
                'page': self.page_name,
                'page_id': self._primary_key,
            },
            auth=auth,
            save=True,
        )
        return self.save()

class NodeSettings(BaseNodeSettings):
    complete = True
    has_auth = True
    is_publicly_editable = models.BooleanField(default=False, db_index=True)

    def set_editing(self, permissions, auth=None, log=False):
        """Set the editing permissions for this node.

        :param auth: All the auth information including user, API key
        :param bool permissions: True = publicly editable
        :param bool save: Whether to save the privacy change
        :param bool log: Whether to add a NodeLog for the privacy change
            if true the node object is also saved
        """
        node = self.owner

        if permissions and not self.is_publicly_editable:
            if node.is_public:
                self.is_publicly_editable = True
            else:
                raise NodeStateError('Private components cannot be made publicly editable.')
        elif not permissions and self.is_publicly_editable:
            self.is_publicly_editable = False
        else:
            raise NodeStateError('Desired permission change is the same as current setting.')

        if log:
            node.add_log(
                action=(NodeLog.MADE_WIKI_PUBLIC
                        if self.is_publicly_editable
                        else NodeLog.MADE_WIKI_PRIVATE),
                params={
                    'project': node.parent_id,
                    'node': node._primary_key,
                },
                auth=auth,
                save=True,
            )

        self.save()

    def after_fork(self, node, fork, user, save=True):
        """Copy wiki settings and wiki pages to forks."""
        WikiPage.clone_wiki_pages(node, fork, user, save)
        return super(NodeSettings, self).after_fork(node, fork, user, save)

    def after_register(self, node, registration, user, save=True):
        """Copy wiki settings and wiki pages to registrations."""
        WikiPage.clone_wiki_pages(node, registration, user, save)
        clone = self.clone()
        clone.owner = registration
        if save:
            clone.save()
        return clone, None

    def after_set_privacy(self, node, permissions):
        """

        :param Node node:
        :param str permissions:
        :return str: Alert message

        """
        if permissions == 'private':
            if self.is_publicly_editable:
                self.set_editing(permissions=False, log=False)
                return (
                    'The wiki of {name} is now only editable by write contributors.'.format(
                        name=node.title,
                    )
                )

    def to_json(self, user):
        return {}


text:
package org.darkstorm.minecraft.bukkit.config;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.*;

public final class Config {
	private static final Pattern timePattern = Pattern.compile("(?i)([0-9]+d)?([0-9]+h)?([0-9]+m)?([0-9]+s)?([0-9]+ms)?");

	private final Map<String, String> config;

	public Config(Map<String, String> config) {
		if(config == null)
			throw new NullPointerException();
		for(String key : config.keySet())
			if(key == null)
				throw new IllegalArgumentException("Null key in config");
			else if(config.get(key) == null)
				throw new IllegalArgumentException("Null value in config");
		this.config = Collections.unmodifiableMap(new HashMap<String, String>(config));
	}

	public String getString(ConfigNode node) {
		if(node == null)
			throw new NullPointerException();
		if(node.getNode() == null)
			throw new IllegalArgumentException("ConfigNode node is null");
		String value = getString(node.getNode());
		if(value == null || !node.isValid(value))
			return node.getDefaultValue();
		return value;
	}

	public boolean has(ConfigNode node) {
		if(node == null)
			throw new NullPointerException();
		if(node.getNode() == null)
			throw new IllegalArgumentException("ConfigNode node is null");
		String value = getString(node.getNode());
		return value != null && node.isValid(value);
	}

	public boolean getBoolean(ConfigNode node) {
		return getBooleanValue(getString(node));
	}

	public boolean isBoolean(ConfigNode node) {
		if(!has(node))
			return false;
		return isBooleanValue(getString(node));
	}

	public int getInt(ConfigNode node) {
		return getIntValue(getString(node));
	}

	public boolean isInt(ConfigNode node) {
		if(!has(node))
			return false;
		return isIntValue(getString(node));
	}

	public long getLong(ConfigNode node) {
		return getLongValue(getString(node));
	}

	public boolean isLong(ConfigNode node) {
		if(!has(node))
			return false;
		return isLongValue(getString(node));
	}

	public double getDouble(ConfigNode node) {
		return getDoubleValue(getString(node));
	}

	public boolean isDouble(ConfigNode node) {
		if(!has(node))
			return false;
		return isDoubleValue(getString(node));
	}

	public float getFloat(ConfigNode node) {
		return getFloatValue(getString(node));
	}

	public boolean isFloat(ConfigNode node) {
		if(!has(node))
			return false;
		return isFloatValue(getString(node));
	}

	public List<String> getStringList(ConfigNode node) {
		return getStringListValue(getString(node));
	}

	public long getTime(ConfigNode node) {
		return getTimeValue(getString(node));
	}

	public boolean isTime(ConfigNode node) {
		if(!has(node))
			return false;
		return isTimeValue(getString(node));
	}

	public String getString(String node) {
		if(node == null)
			throw new NullPointerException();
		return config.get(node.toLowerCase());
	}

	public boolean has(String node) {
		if(node == null)
			throw new NullPointerException();
		return config.get(node) != null;
	}

	public List<String> getSubNodes(String node) {
		if(node == null)
			throw new NullPointerException();
		node = node.concat(".");
		List<String> subNodes = new ArrayList<String>();
		for(String subNode : config.keySet())
			if(subNode.startsWith(node) && !subNode.substring(node.length()).isEmpty())
				subNodes.add(subNode);
		return Collections.unmodifiableList(subNodes);
	}

	public boolean getBoolean(String node) {
		String value = getString(node);
		return getBooleanValue(value);
	}

	public static boolean getBooleanValue(String value) {
		if(value != null)
			if(value.equals("true"))
				return true;
			else if(value.equals("false"))
				return false;
		throw new IllegalArgumentException("Invalid value");
	}

	public boolean isBoolean(String node) {
		if(!has(node))
			return false;
		String value = getString(node);
		return isBooleanValue(value);
	}

	public static boolean isBooleanValue(String value) {
		return value.equals("true") || value.equals("false");
	}

	public int getInt(String node) {
		String value = getString(node);
		return getIntValue(value);
	}

	public static int getIntValue(String value) {
		if(value != null) {
			try {
				return Integer.parseInt(value);
			} catch(NumberFormatException exception) {}
		}
		throw new IllegalArgumentException("Invalid value");
	}

	public boolean isInt(String node) {
		if(!has(node))
			return false;
		String value = getString(node);
		return isIntValue(value);
	}

	public static boolean isIntValue(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch(NumberFormatException exception) {
			return false;
		}
	}

	public long getLong(String node) {
		String value = getString(node);
		return getLongValue(value);
	}

	public static long getLongValue(String value) {
		if(value != null) {
			try {
				return Long.parseLong(value);
			} catch(NumberFormatException exception) {}
		}
		throw new IllegalArgumentException("Invalid value");
	}

	public boolean isLong(String node) {
		if(!has(node))
			return false;
		String value = getString(node);
		return isLongValue(value);
	}

	public static boolean isLongValue(String value) {
		try {
			Long.parseLong(value);
			return true;
		} catch(NumberFormatException exception) {
			return false;
		}
	}

	public double getDouble(String node) {
		String value = getString(node);
		return getDoubleValue(value);
	}

	public static double getDoubleValue(String value) {
		if(value != null) {
			try {
				return Double.parseDouble(value);
			} catch(NumberFormatException exception) {}
		}
		throw new IllegalArgumentException("Invalid value");
	}

	public boolean isDouble(String node) {
		if(!has(node))
			return false;
		String value = getString(node);
		return isDoubleValue(value);
	}

	public static boolean isDoubleValue(String value) {
		try {
			Double.parseDouble(value);
			return true;
		} catch(NumberFormatException exception) {
			return false;
		}
	}

	public float getFloat(String node) {
		String value = getString(node);
		return getFloatValue(value);
	}

	public static float getFloatValue(String value) {
		if(value != null) {
			try {
				return Float.parseFloat(value);
			} catch(NumberFormatException exception) {}
		}
		throw new IllegalArgumentException("Invalid value");
	}

	public boolean isFloat(String node) {
		if(!has(node))
			return false;
		String value = getString(node);
		return isFloatValue(value);
	}

	public static boolean isFloatValue(String value) {
		try {
			Float.parseFloat(value);
			return true;
		} catch(NumberFormatException exception) {
			return false;
		}
	}

	public List<String> getStringList(String node) {
		String nodeValue = getString(node);
		return getStringListValue(nodeValue);
	}

	public static List<String> getStringListValue(String nodeValue) {
		List<String> values = new ArrayList<String>();
		for(String part : nodeValue.split(",")) {
			String value = part.trim();
			if(value.isEmpty())
				continue;
			values.add(value);
		}
		return Collections.unmodifiableList(values);
	}

	public long getTime(String node) {
		String value = getString(node);
		return getTimeValue(value);
	}

	public static long getTimeValue(String value) {
		Matcher matcher = timePattern.matcher(value);
		if(!matcher.matches())
			throw new IllegalArgumentException("Invalid value");
		long millis = 0;
		millis += toMillis(matcher.group(1), TimeUnit.DAYS);
		millis += toMillis(matcher.group(2), TimeUnit.HOURS);
		millis += toMillis(matcher.group(3), TimeUnit.MINUTES);
		millis += toMillis(matcher.group(4), TimeUnit.SECONDS);
		millis += toMillis(matcher.group(5), TimeUnit.MILLISECONDS);
		return millis;
	}

	private static long toMillis(String value, TimeUnit unit) {
		if(value != null && !value.isEmpty()) {
			Matcher matcher = Pattern.compile("[0-9]+").matcher(value);
			if(!matcher.find())
				return 0;
			return unit.toMillis(Integer.parseInt(matcher.group()));
		}
		return 0;
	}

	public boolean isTime(String node) {
		if(!has(node))
			return false;
		String value = getString(node);
		return isTimeValue(value);
	}

	public static boolean isTimeValue(String value) {
		return timePattern.matcher(value).matches();
	}
}


text:
describe Fastlane::Actions::RunLaneAction do
  describe '#run' do
    it 'prints a message' do
      expect(Fastlane::UI).to receive(:message).with("The run_lane plugin is working!")

      Fastlane::Actions::RunLaneAction.run(nil)
    end
  end
end


text:
package com.xtremelabs.robolectric.shadows;

import android.telephony.PhoneNumberUtils;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

@RunWith(WithTestDefaultsRunner.class)
public class PhoneNumberUtilTest {
    @Test
    public void testFormatNumber() {
        assertThat(PhoneNumberUtils.formatNumber("12345678901"), equalTo("12345678901-formatted"));
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="twitter:site" content="@kivyframework">

    <title>Vertex Instructions — Kivy 1.10.0 ドキュメント</title>
    <link href='//fonts.googleapis.com/css?family=Source+Code+Pro:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="_static/fresh.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="top" title="Kivy 1.10.0 ドキュメント" href="index.html" />
    <link rel="up" title="Graphics(翻訳中)" href="api-kivy.graphics.html" />
    <link rel="next" title="Input management" href="api-kivy.input.html" />
    <link rel="prev" title="Transformation" href="api-kivy.graphics.transformation.html" />

Guides

Garden

API Reference

PDF

Wiki

Quick search

            <form class="search" action="search.html" method="get">

                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
                <input type="text" class="text" name="q" />
            </form>

Getting Started(翻訳済み)

Introduction (翻訳済み)

Installation(翻訳済み)

A first App(翻訳済み)

Properties(翻訳済み)

Kv Design Language(翻訳済み)

Events(翻訳済み)

Non-widget stuff(翻訳済み)

Layouts(翻訳済み)

Drawing(翻訳済み)

Packaging(翻訳済み)

Examples(翻訳済み)

Diving in(翻訳済み)

Gallery of Examples(翻訳済み)

Gallery(翻訳済み)

3D Rotating Monkey Head(翻訳済み)

Widget animation(翻訳済み)

Suite of Application Builders(翻訳済み)

Application example using build() + return(翻訳済み)

Application built from a  .kv fil(翻訳済み)

Application from a .kv in a Template Directory(翻訳済み)

Camera Example(翻訳済み)

Bezier Example(翻訳済み)

Canvas stress(翻訳済み)

Circle Example(翻訳済み)

FBO Canvas(翻訳済み)

Line (SmoothLine) Experiment(翻訳済み)

Lines Extended Demo(翻訳済み)

Mesh test(翻訳済み)

Multitexture Example(翻訳済み)

Repeat Texture on Resize(翻訳済み)

Rotation Example(翻訳済み)

Stencil demo(翻訳済み)

Tesselate Demonstration

Texture Wrapping and Coordinates Example(翻訳済み)

Shuffled Camera Feed Puzzle(翻訳済み)

Kivy Catalog(翻訳済み)

Multistroke Recognition Database Demonstration(翻訳済み)

Basic Picture Viewer(翻訳済み)

Live Shader Editor(翻訳済み)

Showcase of Kivy Features

Touch Tracer Line Drawing Demonstration(翻訳済み)

User's Guide(翻訳済み)

Installation(翻訳済み)

Philosophy(翻訳済み)

Contributing(翻訳済み)

FAQ (翻訳済み)

Contact Us(翻訳済み)

Programming Guide(翻訳済み)

Kivy Basics(翻訳済み)

Controlling the environment(翻訳済み)

Configure Kivy(翻訳済み)

Architectural Overview(翻訳済み)

Events and Properties (翻訳済み)

Input management (翻訳済み)

Widgets(翻訳済み)

Graphics (翻訳済み)

Kv language(翻訳済み)

Integrating with other Frameworks(翻訳済み)

Packaging your application(翻訳済み)

Package licensing (翻訳済み)

Tutorials(翻訳済み)

Pong Game Tutorial(翻訳済み)

A Simple Paint App(翻訳済み)

Crash Course(翻訳済み)

API Reference

Kivy framework(翻訳済み)

Adapters

Adapter

List Item View Argument Converters

DictAdapter

ListAdapter

SelectableDataItem

SimpleListAdapter

Animation(翻訳済み)

Application (翻訳中)

Atlas

Kivy Base

Cache manager

Clock object(翻訳ずみ)

Compatibility module for Python 2.7 and > 3.3

Configuration object

Context

Core Abstraction(翻訳済み)

Audio

Camera

Clipboard(翻訳済み)

OpenGL

Image

Spelling

Text

Text Markup

Text layout

Video

Window

Kivy module for binary dependencies.

Effects

Damped scroll effect

Kinetic effect

Opacity scroll effect

Scroll effect

Event dispatcher

Factory object

Garden

Geometry utilities

Gesture recognition

Graphics(翻訳中)

CGL: standard C interface for OpenGL

Graphics compiler

Context management

Context instructions

Framebuffer

GL instructions

Canvas

OpenGL

OpenGL utilities

Scissor Instructions

Shader

Stencil instructions

SVG

Tesselator

Texture

Transformation

Input management

Motion Event Factory

Motion Event

Input Postprocessing

Calibration

Dejitter

Double Tap

Ignore list

Retain Touch

Triple Tap

Motion Event Provider

Providers

Android Joystick Input Provider

Native support for HID input from the linux kernel

Leap Motion - finger only

Native support of Wacom tablet from linuxwacom driver

Native support of MultitouchSupport framework for MacBook (MaxOSX platform)

Mouse provider implementation

Native support for Multitouch devices on Linux, using libmtdev.

Auto Create Input Provider Config Entry for Available MT Hardware (linux only).

TUIO Input Provider

Common definitions for a Windows provider

Support for WM_PEN messages (Windows platform)

Support for WM_TOUCH messages (Windows platform)

Input recorder

Motion Event Shape

Interactive launcher

Kivy Language(翻訳済み)

Builder

Parser

External libraries

DDS File library

GstPlayer

Python mtdev

OSC

NO DOCUMENTATION (module kivy.uix.recycleview)

simpleOSC 0.2

Asynchronous data loader

Logger object

Metrics

Modules

Console

Inspector

JoyCursor

Keybinding

Monitor module

Recorder module

Screen

Touchring

Web Debugger

Multistroke gesture recognizer

Network support

UrlRequest

Parser utilities

Properties

Resources management

Storage

Dictionary store

JSON store

Redis Store

Support

Tools

Packaging

Pyinstaller hooks

Widgets(翻訳済み)

Abstract View

Accordion

Action Bar

Anchor Layout

Behaviors

Button Behavior

Code Navigation Behavior

Compound Selection Behavior

Cover Behavior

Drag Behavior

Emacs Behavior

Focus Behavior

Kivy Namespaces

ToggleButton Behavior

Box Layout

Bubble

Button

Camera

Carousel

CheckBox

Code Input

Color Picker

Drop-Down List

EffectWidget

FileChooser

Float Layout

Gesture Surface

Grid Layout

Image

Label(翻訳済み)

Layout

List View

ModalView

PageLayout

Popup

Progress Bar

RecycleBoxLayout

RecycleGridLayout

RecycleLayout

RecycleView

RecycleView Data Model

RecycleView Layouts

RecycleView Views

Relative Layout

reStructuredText renderer

Sandbox

Scatter

Scatter Layout

Screen Manager

ScrollView

SelectableView

Settings (翻訳中)

Slider

Spinner

Splitter

Stack Layout

Stencil View

Switch

TabbedPanel

Text Input

Toggle button

Tree View

Video

Video player

VKeyboard

Widget class

Utils

Vector

Weak Method

Weak Proxy

Table Of Contents

Vertex Instructions

Updating properties

Vertex Instructions¶

This module includes all the classes for drawing simple vertex objects.

Updating properties¶

The list attributes of the graphics instruction classes (e.g.
Triangle.points, Mesh.indices etc.) are not Kivy
properties but Python properties. As a consequence, the graphics will only
be updated when the list object itself is changed and not when list values
are modified.

For example in python:

class MyWidget(Button):

    triangle = ObjectProperty(None)
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
        with self.canvas:
            self.triangle = Triangle(points=[0,0, 100,100, 200,0])

and in kv:

<MyWidget>:
    text: 'Update'
    on_press:
        self.triangle.points[3] = 400

Although pressing the button will change the triangle coordinates,
the graphics will not be updated because the list itself has not
changed. Similarly, no updates will occur using any syntax that changes
only elements of the list e.g. self.triangle.points[0:2] = [10,10] or
self.triangle.points.insert(10) etc.
To force an update after a change, the list variable itself must be
changed, which in this case can be achieved with:

<MyWidget>:
    text: 'Update'
    on_press:
        self.triangle.points[3] = 400
        self.triangle.points = self.triangle.points

class kivy.graphics.vertex_instructions.Triangle¶

ベースクラス: kivy.graphics.instructions.VertexInstruction

A 2d triangle.

<col class="field-name" />
<col class="field-body" />

Parameters:

points: list

List of points in the format (x1, y1, x2, y2, x3, y3).

points¶

Property for getting/settings points of the triangle.

class kivy.graphics.vertex_instructions.Quad¶

ベースクラス: kivy.graphics.instructions.VertexInstruction

A 2d quad.

<col class="field-name" />
<col class="field-body" />

Parameters:

points: list

List of point in the format (x1, y1, x2, y2, x3, y3, x4, y4).

points¶

Property for getting/settings points of the quad.

class kivy.graphics.vertex_instructions.Rectangle¶

ベースクラス: kivy.graphics.instructions.VertexInstruction

A 2d rectangle.

<col class="field-name" />
<col class="field-body" />

Parameters:

pos: list

Position of the rectangle, in the format (x, y).

size: list

Size of the rectangle, in the format (width, height).

pos¶

Property for getting/settings the position of the rectangle.

size¶

Property for getting/settings the size of the rectangle.

class kivy.graphics.vertex_instructions.RoundedRectangle¶

ベースクラス: kivy.graphics.vertex_instructions.Rectangle

A 2D rounded rectangle.

バージョン 1.9.1 で追加.

<col class="field-name" />
<col class="field-body" />

Parameters:

segments: int, defaults to 10

Define how many segments are needed for drawing the round corner.
The drawing will be smoother if you have many segments.

radius: list, defaults to [(10.0, 10.0), (10.0, 10.0), (10.0, 10.0), (10.0, 10.0)]

Specifies the radiuses of the round corners clockwise:
top-left, top-right, bottom-right, bottom-left.
Elements of the list can be numbers or tuples of two numbers to specify different x,y dimensions.
One value will define all corner dimensions to that value.
Four values will define dimensions for each corner separately.
Higher number of values will be truncated to four.
The first value will be used for all corners, if there is fewer than four values.

radius¶

Corner radiuses of the rounded rectangle, defaults to [10,].

segments¶

Property for getting/setting the number of segments for each corner.

class kivy.graphics.vertex_instructions.BorderImage¶

ベースクラス: kivy.graphics.vertex_instructions.Rectangle

A 2d border image. The behavior of the border image is similar to the
concept of a CSS3 border-image.

<col class="field-name" />
<col class="field-body" />

Parameters:

border: list

Border information in the format (bottom, right, top, left).
Each value is in pixels.

auto_scale: string

バージョン 1.9.1 で追加.

バージョン 1.9.2 で変更: This used to be a bool and has been changed to be a string
state.

Can be one of ‘off’, ‘both’, ‘x_only’, ‘y_only’, ‘y_full_x_lower’,
‘x_full_y_lower’, ‘both_lower’.

Autoscale controls the behavior of the 9-slice.

By default the border values are preserved exactly, meaning that
if the total size of the object is smaller than the border values
you will have some ‘rendering errors’ where your texture appears
inside out. This also makes it impossible to achieve a rounded
button that scales larger than the size of its source texture. The
various options for auto_scale will let you achieve some mixes of
the 2 types of rendering.

‘off’: is the default and behaves as BorderImage did when auto_scale
was False before.

‘both’: Scales both x and y dimension borders according to the size
of the BorderImage, this disables the BorderImage making it render
the same as a regular Image.

‘x_only’: The Y dimension functions as the default, and the X
scales to the size of the BorderImage’s width.

‘y_only’: The X dimension functions as the default, and the Y
scales to the size of the BorderImage’s height.

‘y_full_x_lower’: Y scales as in ‘y_only’, Y scales if the
size of the scaled version would be smaller than the provided
border only.

‘x_full_y_lower’: X scales as in ‘x_only’, Y scales if the
size of the scaled version would be smaller than the provided
border only.

‘both_lower’: This is what auto_scale did when it was True in 1.9.1
Both X and Y dimensions will be scaled if the BorderImage is
smaller than the source.

If the BorderImage’s size is less than the sum of it’s
borders, horizontally or vertically, and this property is
set to True, the borders will be rescaled to accommodate for
the smaller size.

auto_scale¶

Property for setting if the corners are automatically scaled
when the BorderImage is too small.

border¶

Property for getting/setting the border of the class.

display_border¶

Property for getting/setting the border display size.

class kivy.graphics.vertex_instructions.Ellipse¶

ベースクラス: kivy.graphics.vertex_instructions.Rectangle

A 2D ellipse.

バージョン 1.0.7 で変更: Added angle_start and angle_end.

<col class="field-name" />
<col class="field-body" />

Parameters:

segments: int, defaults to 180

Define how many segments are needed for drawing the ellipse.
The drawing will be smoother if you have many segments.

angle_start: int, defaults to 0

Specifies the starting angle, in degrees, of the disk portion.

angle_end: int, defaults to 360

Specifies the ending angle, in degrees, of the disk portion.

angle_end¶

End angle of the ellipse in degrees, defaults to 360.

angle_start¶

Start angle of the ellipse in degrees, defaults to 0.

segments¶

Property for getting/setting the number of segments of the ellipse.

class kivy.graphics.vertex_instructions.Line¶

ベースクラス: kivy.graphics.instructions.VertexInstruction

A 2d line.

Drawing a line can be done easily:

with self.canvas:
    Line(points=[100, 100, 200, 100, 100, 200], width=10)

The line has 3 internal drawing modes that you should be aware of
for optimal results:

If the width is 1.0, then the standard GL_LINE drawing from
OpenGL will be used. dash_length and dash_offset will
work, while properties for cap and joint have no meaning here.

If the width is greater than 1.0, then a custom drawing method,
based on triangulation, will be used. dash_length and
dash_offset do not work in this mode.
Additionally, if the current color has an alpha less than 1.0, a
stencil will be used internally to draw the line.

<col class="field-name" />
<col class="field-body" />

Parameters:

points: list

List of points in the format (x1, y1, x2, y2...)

dash_length: int

Length of a segment (if dashed), defaults to 1.

dash_offset: int

Offset between the end of a segment and the beginning of the
next one, defaults to 0. Changing this makes it dashed.

width: float

Width of the line, defaults to 1.0.

cap: str, defaults to ‘round’

See cap for more information.

joint: str, defaults to ‘round’

See joint for more information.

cap_precision: int, defaults to 10

See cap_precision for more information

joint_precision: int, defaults to 10

See joint_precision for more information
See cap_precision for more information.

joint_precision: int, defaults to 10

See joint_precision for more information.

close: bool, defaults to False

If True, the line will be closed.

circle: list

If set, the points will be set to build a circle. See
circle for more information.

ellipse: list

If set, the points will be set to build an ellipse. See
ellipse for more information.

rectangle: list

If set, the points will be set to build a rectangle. See
rectangle for more information.

bezier: list

If set, the points will be set to build a bezier line. See
bezier for more information.

bezier_precision: int, defaults to 180

Precision of the Bezier drawing.

バージョン 1.0.8 で変更: dash_offset and dash_length have been added.

バージョン 1.4.1 で変更: width, cap, joint, cap_precision, joint_precision, close,
ellipse, rectangle have been added.

バージョン 1.4.1 で変更: bezier, bezier_precision have been added.

bezier¶

Use this property to build a bezier line, without calculating the
points. You can only set this property, not get it.

The argument must be a tuple of 2n elements, n being the number of points.

Usage:

Line(bezier=(x1, y1, x2, y2, x3, y3)

バージョン 1.4.2 で追加.

注釈

Bezier lines calculations are inexpensive for a low number of
points, but complexity is quadratic, so lines with a lot of points
can be very expensive to build, use with care!

bezier_precision¶

Number of iteration for drawing the bezier between 2 segments,
defaults to 180. The bezier_precision must be at least 1.

バージョン 1.4.2 で追加.

cap¶

Determine the cap of the line, defaults to ‘round’. Can be one of
‘none’, ‘square’ or ‘round’

バージョン 1.4.1 で追加.

cap_precision¶

Number of iteration for drawing the “round” cap, defaults to 10.
The cap_precision must be at least 1.

バージョン 1.4.1 で追加.

circle¶

Use this property to build a circle, without calculating the
points. You can only set this property, not get it.

The argument must be a tuple of (center_x, center_y, radius, angle_start,
angle_end, segments):

center_x and center_y represent the center of the circle

radius represent the radius of the circle

(optional) angle_start and angle_end are in degree. The default
value is 0 and 360.

(optional) segments is the precision of the ellipse. The default
value is calculated from the range between angle.

Note that it’s up to you to close the circle or not.

For example, for building a simple ellipse, in python:

# simple circle
Line(circle=(150, 150, 50))

# only from 90 to 180 degrees
Line(circle=(150, 150, 50, 90, 180))

# only from 90 to 180 degrees, with few segments
Line(circle=(150, 150, 50, 90, 180, 20))

バージョン 1.4.1 で追加.

close¶

If True, the line will be closed.

バージョン 1.4.1 で追加.

dash_length¶

Property for getting/setting the length of the dashes in the curve

バージョン 1.0.8 で追加.

dash_offset¶

Property for getting/setting the offset between the dashes in the curve

バージョン 1.0.8 で追加.

ellipse¶

Use this property to build an ellipse, without calculating the
points. You can only set this property, not get it.

The argument must be a tuple of (x, y, width, height, angle_start,
angle_end, segments):

x and y represent the bottom left of the ellipse

width and height represent the size of the ellipse

(optional) angle_start and angle_end are in degree. The default
value is 0 and 360.

(optional) segments is the precision of the ellipse. The default
value is calculated from the range between angle.

Note that it’s up to you to close the ellipse or not.

For example, for building a simple ellipse, in python:

# simple ellipse
Line(ellipse=(0, 0, 150, 150))

# only from 90 to 180 degrees
Line(ellipse=(0, 0, 150, 150, 90, 180))

# only from 90 to 180 degrees, with few segments
Line(ellipse=(0, 0, 150, 150, 90, 180, 20))

バージョン 1.4.1 で追加.

joint¶

Determine the join of the line, defaults to ‘round’. Can be one of
‘none’, ‘round’, ‘bevel’, ‘miter’.

バージョン 1.4.1 で追加.

joint_precision¶

Number of iteration for drawing the “round” joint, defaults to 10.
The joint_precision must be at least 1.

バージョン 1.4.1 で追加.

points¶

Property for getting/settings points of the line

警告

This will always reconstruct the whole graphics from the new points
list. It can be very CPU expensive.

rectangle¶

Use this property to build a rectangle, without calculating the
points. You can only set this property, not get it.

The argument must be a tuple of (x, y, width, height):

x and y represent the bottom-left position of the rectangle

width and height represent the size

The line is automatically closed.

Usage:

Line(rectangle=(0, 0, 200, 200))

バージョン 1.4.1 で追加.

rounded_rectangle¶

Use this property to build a rectangle, without calculating the
points. You can only set this property, not get it.

The argument must be a tuple of one of the following forms:

(x, y, width, height, corner_radius)

(x, y, width, height, corner_radius, resolution)

(x, y, width, height, corner_radius1, corner_radius2, corner_radius3, corner_radius4)

(x, y, width, height, corner_radius1, corner_radius2, corner_radius3, corner_radius4, resolution)

x and y represent the bottom-left position of the rectangle

width and height represent the size

corner_radius is the number of pixels between two borders and the center of the circle arc joining them

resolution is the number of line segment that will be used to draw the circle arc at each corner (defaults to 30)

The line is automatically closed.

Usage:

Line(rounded_rectangle=(0, 0, 200, 200, 10, 20, 30, 40, 100))

バージョン 1.9.0 で追加.

width¶

Determine the width of the line, defaults to 1.0.

バージョン 1.4.1 で追加.

class kivy.graphics.vertex_instructions.Point¶

ベースクラス: kivy.graphics.instructions.VertexInstruction

A list of 2d points. Each point is represented as a square with a
width/height of 2 times the pointsize.

<col class="field-name" />
<col class="field-body" />

Parameters:

points: list

List of points in the format (x1, y1, x2, y2...), where each pair
of coordinates specifies the center of a new point.

pointsize: float, defaults to 1.

The size of the point, measured from the center to the edge. A
value of 1.0 therefore means the real size will be 2.0 x 2.0.

警告

Starting from version 1.0.7, vertex instruction have a limit of 65535
vertices (indices of vertex to be accurate).
2 entries in the list (x, y) will be converted to 4 vertices. So the
limit inside Point() class is 2^15-2.

add_point()¶

Add a point to the current points list.

If you intend to add multiple points, prefer to use this method instead
of reassigning a new points list. Assigning a new points
list will recalculate and reupload the whole buffer into the GPU.
If you use add_point, it will only upload the changes.

points¶

Property for getting/settings the center points in the points list.
Each pair of coordinates specifies the center of a new point.

pointsize¶

Property for getting/setting point size.
The size is measured from the center to the edge, so a value of 1.0
means the real size will be 2.0 x 2.0.

class kivy.graphics.vertex_instructions.Mesh¶

ベースクラス: kivy.graphics.instructions.VertexInstruction

A 2d mesh.

In OpenGL ES 2.0 and in our graphics implementation, you cannot have more
than 65535 indices.

A list of vertices is described as:

vertices = [x1, y1, u1, v1, x2, y2, u2, v2, ...]
            |            |  |            |
            +---- i1 ----+  +---- i2 ----+

If you want to draw a triangle, add 3 vertices. You can then make an
indices list as follows:

indices = [0, 1, 2]

バージョン 1.1.0 で追加.

<col class="field-name" />
<col class="field-body" />

Parameters:

vertices: iterable

List of vertices in the format (x1, y1, u1, v1, x2, y2, u2, v2...).

indices: iterable

List of indices in the format (i1, i2, i3...).

mode: str

Mode of the vbo. Check mode for more information. Defaults to
‘points’.

fmt: list

The format for vertices, by default, each vertex is described by 2D
coordinates (x, y) and 2D texture coordinate (u, v).
Each element of the list should be a tuple or list, of the form

(variable_name, size, type)

which will allow mapping vertex data to the glsl instructions.

[(b’v_pos’, 2, b’float’), (b’v_tc’, 2, b’float’),]

will allow using

attribute vec2 v_pos;
attribute vec2 v_tc;

in glsl’s vertex shader.

バージョン 1.8.1 で変更: Before, vertices and indices would always be converted to a list,
now, they are only converted to a list if they do not implement the
buffer interface. So e.g. numpy arrays, python arrays etc. are used
in place, without creating any additional copies. However, the
buffers cannot be readonly (even though they are not changed, due to
a cython limitation) and must be contiguous in memory.

注釈

When passing a memoryview or a instance that implements the buffer
interface, vertices should be a buffer of floats (‘f’ code in
python array) and indices should be a buffer of unsigned short (‘H’
code in python array). Arrays in other formats will still have to be
converted internally, negating any potential gain.

indices¶

Vertex indices used to specify the order when drawing the
mesh.

mode¶

VBO Mode used for drawing vertices/indices. Can be one of ‘points’,
‘line_strip’, ‘line_loop’, ‘lines’, ‘triangles’, ‘triangle_strip’ or
‘triangle_fan’.

vertices¶

List of x, y, u, v coordinates used to construct the Mesh. Right now,
the Mesh instruction doesn’t allow you to change the format of the
vertices, which means it’s only x, y + one texture coordinate.

exception kivy.graphics.vertex_instructions.GraphicException¶

ベースクラス: Exception

Exception raised when a graphics error is fired.

class kivy.graphics.vertex_instructions.Bezier¶

ベースクラス: kivy.graphics.instructions.VertexInstruction

A 2d Bezier curve.

バージョン 1.0.8 で追加.

<col class="field-name" />
<col class="field-body" />

Parameters:

points: list

List of points in the format (x1, y1, x2, y2...)

segments: int, defaults to 180

Define how many segments are needed for drawing the curve.
The drawing will be smoother if you have many segments.

loop: bool, defaults to False

Set the bezier curve to join the last point to the first.

dash_length: int

Length of a segment (if dashed), defaults to 1.

dash_offset: int

Distance between the end of a segment and the start of the
next one, defaults to 0. Changing this makes it dashed.

dash_length¶

Property for getting/setting the length of the dashes in the curve.

dash_offset¶

Property for getting/setting the offset between the dashes in the
curve.

points¶

Property for getting/settings the points of the triangle.

警告

This will always reconstruct the whole graphic from the new points
list. It can be very CPU intensive.

segments¶

Property for getting/setting the number of segments of the curve.

class kivy.graphics.vertex_instructions.SmoothLine¶

ベースクラス: kivy.graphics.vertex_instructions.Line

Experimental line using over-draw methods to get better anti-aliasing
results. It has few drawbacks:

drawing a line with alpha will probably not have the intended result if
the line crosses itself.

cap, joint and dash properties
are not supported.

it uses a custom texture with a premultiplied alpha.

lines under 1px in width are not supported: they will look the same.

警告

This is an unfinished work, experimental, and subject to crashes.

バージョン 1.9.0 で追加.

overdraw_width¶

Determine the overdraw width of the line, defaults to 1.2.

                  « Transformation

                  Input management »


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'base32_pure'
require 'spec'
require 'spec/autorun'

Spec::Runner.configure do |config|

end


text:
<?php

/**
 * Client Object
 */

class Client{
    use GenericScheme, TraitArrayTranspose;

    public function __construct($array){
        $this->unwind($array);
    }
}


text:
package org.elasticsearch.index.store;

import org.apache.lucene.store.StoreRateLimiting;
import org.elasticsearch.index.shard.ShardId;

import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;

/**
 * Index store is an index level information of the {@link Store} each shard will use.
 */
public interface IndexStore extends Closeable {

    /**
     * Returns the rate limiting, either of the index is explicitly configured, or
     * the node level one (defaults to the node level one).
     */
    StoreRateLimiting rateLimiting();

    /**
     * The shard store class that should be used for each shard.
     */
    Class<? extends DirectoryService> shardDirectory();

    /**
     * Returns <tt>true</tt> if this shard is allocated on this node. Allocated means
     * that it has storage files that can be deleted using {@link #deleteUnallocated(org.elasticsearch.index.shard.ShardId)}.
     */
    boolean canDeleteUnallocated(ShardId shardId);

    /**
     * Deletes this shard store since its no longer allocated.
     */
    void deleteUnallocated(ShardId shardId) throws IOException;

    Path[] shardIndexLocations(ShardId shardId);
}


text:
'use strict';

const models = require('./index');

/**
 * The diagnostic setting resource.
 *
 * @extends models['ProxyOnlyResource']
 */
class DiagnosticSettingsResource extends models['ProxyOnlyResource'] {
  /**
   * Create a DiagnosticSettingsResource.
   * @member {string} [storageAccountId] The resource ID of the storage account
   * to which you would like to send Diagnostic Logs.
   * @member {string} [eventHubAuthorizationRuleId] The resource Id for the
   * event hub authorization rule.
   * @member {string} [eventHubName] The name of the event hub. If none is
   * specified, the default event hub will be selected.
   * @member {array} [metrics] the list of metric settings.
   * @member {array} [logs] the list of logs settings.
   * @member {string} [workspaceId] The workspace ID (resource ID of a Log
   * Analytics workspace) for a Log Analytics workspace to which you would like
   * to send Diagnostic Logs. Example:
   * /subscriptions/4b9e8510-67ab-4e9a-95a9-e2f1e570ea9c/resourceGroups/insights-integration/providers/Microsoft.OperationalInsights/workspaces/viruela2
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of DiagnosticSettingsResource
   *
   * @returns {object} metadata of DiagnosticSettingsResource
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'DiagnosticSettingsResource',
      type: {
        name: 'Composite',
        className: 'DiagnosticSettingsResource',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          storageAccountId: {
            required: false,
            serializedName: 'properties.storageAccountId',
            type: {
              name: 'String'
            }
          },
          eventHubAuthorizationRuleId: {
            required: false,
            serializedName: 'properties.eventHubAuthorizationRuleId',
            type: {
              name: 'String'
            }
          },
          eventHubName: {
            required: false,
            serializedName: 'properties.eventHubName',
            type: {
              name: 'String'
            }
          },
          metrics: {
            required: false,
            serializedName: 'properties.metrics',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'MetricSettingsElementType',
                  type: {
                    name: 'Composite',
                    className: 'MetricSettings'
                  }
              }
            }
          },
          logs: {
            required: false,
            serializedName: 'properties.logs',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'LogSettingsElementType',
                  type: {
                    name: 'Composite',
                    className: 'LogSettings'
                  }
              }
            }
          },
          workspaceId: {
            required: false,
            serializedName: 'properties.workspaceId',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = DiagnosticSettingsResource;


text:
<?php

namespace Searcher\LoopBack\Parser\Pagination;

use Searcher\Events\OffsetEvent;
use Searcher\LoopBack\Parser\BuilderInterface;
use Searcher\LoopBack\Parser\Filter\Condition\Exception\InvalidConditionException;
use Searcher\LoopBack\Parser\Filter\FilterInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

class OffsetBuilder implements BuilderInterface, FilterInterface
{
    const OFFSET_DEFAULT = 0;
    private $offset = 0;
    /**
     * @var EventDispatcherInterface
     */
    private $dispatcher = null;

    /**
     * @param EventDispatcherInterface $dispatcher
     */
    public function setDispatcher(EventDispatcherInterface $dispatcher = null)
    {
        $this->dispatcher = $dispatcher;
    }

    /**
     * @return int
     */
    public function getOffset()
    {
        return (int) $this->offset;
    }

    /**
     * @param int $offset
     */
    public function setOffset($offset)
    {
        if (!is_numeric($this->offset)) {
            $offset = self::OFFSET_DEFAULT;
        }

        $this->offset = (int) $offset;
    }

    /**
     * @inheritdoc
     * @return $this
     * @throws InvalidConditionException
     */
    public function build($conditions = null)
    {
        if ($this->dispatcher) {
            $this->dispatcher->dispatch(OffsetEvent::EVENT_NAME, new OffsetEvent($this));
        }

        return $this;
    }

    /**
     * @param $offset
     * @param EventDispatcherInterface $dispatcher
     */
    public static function create($offset, EventDispatcherInterface $dispatcher = null)
    {
        $instance = new static();
        $instance->setDispatcher($dispatcher);
        $instance->setOffset($offset);
        return $instance->build();
    }
}


text:
<?php

/**
 * This file replaces the legacy STATEMENTS section in db/install.xml,
 * lib.php/modulename_install() post installation hook and partially defaults.php
 *
 * author : Pasan Buddhika Weerathunga
 * email : me@pasanlive.com
 *
 * @package    mod_pasanliveresultmanagers
 */

/**
 * Post installation procedure
 *
 * @see upgrade_plugins_modules()
 */
function xmldb_resultmanager_install() {
}

/**
 * Post installation recovery procedure
 *
 * @see upgrade_plugins_modules()
 */
function xmldb_resultmanager_install_recovery() {
}


text:
#pragma once
#include <aws/comprehend/Comprehend_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Comprehend
{
namespace Model
{
  enum class DocumentReadMode
  {
    NOT_SET,
    SERVICE_DEFAULT,
    FORCE_DOCUMENT_READ_ACTION
  };

namespace DocumentReadModeMapper
{
AWS_COMPREHEND_API DocumentReadMode GetDocumentReadModeForName(const Aws::String& name);

AWS_COMPREHEND_API Aws::String GetNameForDocumentReadMode(DocumentReadMode value);
} // namespace DocumentReadModeMapper
} // namespace Model
} // namespace Comprehend
} // namespace Aws


text:
using Azure;
using Azure.Core;
using Azure.Messaging.EventHubs;
using Orleans.Runtime;
using Orleans.Streams;
using System;

namespace Orleans.Configuration
{
    /// <summary>
    /// EventHub settings for a specific hub
    /// </summary>
    public class EventHubOptions
    {
        /// <summary>
        /// Gets the delegate used to create connections to Azure Event Hub.
        /// </summary>
        internal CreateConnectionDelegate CreateConnection { get; private set; }

        /// <summary>
        /// Event Hub consumer group.
        /// </summary>
        internal string ConsumerGroup { get; private set; }

        /// <summary>
        /// Event Hub name.
        /// </summary>
        internal string EventHubName { get; private set; }

        /// <summary>
        /// Connection options used when creating a connection to an Azure Event Hub.
        /// </summary>
        public EventHubConnectionOptions ConnectionOptions { get; set; } = new EventHubConnectionOptions { TransportType = EventHubsTransportType.AmqpTcp };

        /// <summary>
        /// Creates an Azure Event Hub connection.
        /// </summary>
        /// <param name="connectionOptions">The connection options.</param>
        /// <returns>An Azure Event Hub connection.</returns>
        public delegate EventHubConnection CreateConnectionDelegate(EventHubConnectionOptions connectionOptions);

        /// <summary>
        /// Configures the Azure Event Hub connection using the provided connection string.
        /// </summary>
        public void ConfigureEventHubConnection(string connectionString, string eventHubName, string consumerGroup)
        {
            EventHubName = eventHubName;
            ConsumerGroup = consumerGroup;

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(connectionString));
            }

            ValidateValues(eventHubName, consumerGroup);

            CreateConnection = connectionOptions => new EventHubConnection(connectionString, EventHubName, connectionOptions);
        }

        /// <summary>
        /// Configures the Azure Event Hub connection using the provided fully-qualified namespace string and credential.
        /// </summary>
        public void ConfigureEventHubConnection(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, AzureNamedKeyCredential credential)
        {
            EventHubName = eventHubName;
            ConsumerGroup = consumerGroup;

            if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace))
            {
                throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(fullyQualifiedNamespace));
            }

            ValidateValues(eventHubName, consumerGroup);

            if (credential is null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            CreateConnection = connectionOptions => new EventHubConnection(fullyQualifiedNamespace, EventHubName, credential, connectionOptions);
        }

        /// <summary>
        /// Configures the Azure Event Hub connection using the provided fully-qualified namespace string and credential.
        /// </summary>
        public void ConfigureEventHubConnection(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, AzureSasCredential credential)
        {
            EventHubName = eventHubName;
            ConsumerGroup = consumerGroup;

            if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace))
            {
                throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(fullyQualifiedNamespace));
            }

            ValidateValues(eventHubName, consumerGroup);

            if (credential is null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            CreateConnection = connectionOptions => new EventHubConnection(fullyQualifiedNamespace, EventHubName, credential, connectionOptions);
        }

        /// <summary>
        /// Configures the Azure Event Hub connection using the provided fully-qualified namespace string and credential.
        /// </summary>
        public void ConfigureEventHubConnection(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, TokenCredential credential)
        {
            EventHubName = eventHubName;
            ConsumerGroup = consumerGroup;
            if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace))
            {
                throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(fullyQualifiedNamespace));
            }

            ValidateValues(eventHubName, consumerGroup);
            if (credential is null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            CreateConnection = connectionOptions => new EventHubConnection(fullyQualifiedNamespace, EventHubName, credential, connectionOptions);
        }

        /// <summary>
        /// Configures the Azure Event Hub connection using the provided connection instance.
        /// </summary>
        public void ConfigureEventHubConnection(EventHubConnection connection, string consumerGroup)
        {
            EventHubName = connection.EventHubName;
            ConsumerGroup = consumerGroup;
            ValidateValues(connection.EventHubName, consumerGroup);
            if (connection is null) throw new ArgumentNullException(nameof(connection));
            CreateConnection = _ => connection;
        }

        /// <summary>
        /// Configures the Azure Event Hub connection using the provided delegate.
        /// </summary>
        public void ConfigureEventHubConnection(CreateConnectionDelegate createConnection, string eventHubName, string consumerGroup)
        {
            EventHubName = eventHubName;
            ConsumerGroup = consumerGroup;
            ValidateValues(eventHubName, consumerGroup);
            CreateConnection = createConnection ?? throw new ArgumentNullException(nameof(createConnection));
        }

        private void ValidateValues(string eventHubName, string consumerGroup)
        {
            if (string.IsNullOrWhiteSpace(eventHubName))
            {
                throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(eventHubName));
            }

            if (string.IsNullOrWhiteSpace(consumerGroup))
            {
                throw new ArgumentException("A non-null, non-empty value must be provided.", nameof(consumerGroup));
            }
        }
    }

    public class EventHubOptionsValidator : IConfigurationValidator
    {
        private readonly EventHubOptions options;
        private readonly string name;
        public EventHubOptionsValidator(EventHubOptions options, string name)
        {
            this.options = options;
            this.name = name;
        }
        public void ValidateConfiguration()
        {
            if (options.CreateConnection is null)
            {
                throw new OrleansConfigurationException($"Azure Event Hub connection not configured for stream provider options {nameof(EventHubOptions)} with name \"{name}\". Use the {options.GetType().Name}.{nameof(EventHubOptions.ConfigureEventHubConnection)} method to configure the connection.");
            }

            if (string.IsNullOrEmpty(options.ConsumerGroup))
            {
                throw new OrleansConfigurationException($"{nameof(EventHubOptions)} on stream provider {this.name} is invalid. {nameof(EventHubOptions.ConsumerGroup)} is invalid");
            }

            if (string.IsNullOrEmpty(options.EventHubName))
            {
                throw new OrleansConfigurationException($"{nameof(EventHubOptions)} on stream provider {this.name} is invalid. {nameof(EventHubOptions.EventHubName)} is invalid");
            }
        }
    }

    public class StreamCheckpointerConfigurationValidator : IConfigurationValidator
    {
        private readonly IServiceProvider services;
        private string name;
        public StreamCheckpointerConfigurationValidator(IServiceProvider services, string name)
        {
            this.services = services;
            this.name = name;
        }
        public void ValidateConfiguration()
        {
            var checkpointerFactory = services.GetServiceByName<IStreamQueueCheckpointerFactory>(this.name);
            if (checkpointerFactory == null)
                throw new OrleansConfigurationException($"No IStreamQueueCheckpointer is configured with PersistentStreamProvider {this.name}. Please configure one.");
        }
    }

    public class EventHubReceiverOptions
    {
        /// <summary>
        /// Optional parameter that configures the receiver prefetch count.
        /// </summary>
        public int? PrefetchCount { get; set; }
        /// <summary>
        /// In cases where no checkpoint is found, this indicates if service should read from the most recent data, or from the beginning of a partition.
        /// </summary>
        public bool StartFromNow { get; set; } = DEFAULT_START_FROM_NOW;
        public const bool DEFAULT_START_FROM_NOW = true;
    }

    public class EventHubStreamCachePressureOptions
    {
        /// <summary>
        /// SlowConsumingPressureMonitorConfig
        /// </summary>
        public double? SlowConsumingMonitorFlowControlThreshold { get; set; }

        /// <summary>
        /// SlowConsumingMonitorPressureWindowSize
        /// </summary>
        public TimeSpan? SlowConsumingMonitorPressureWindowSize { get; set; }

        /// <summary>
        /// AveragingCachePressureMonitorFlowControlThreshold, AveragingCachePressureMonitor is turn on by default.
        /// User can turn it off by setting this value to null
        /// </summary>
        public double? AveragingCachePressureMonitorFlowControlThreshold { get; set; } = DEFAULT_AVERAGING_CACHE_PRESSURE_MONITORING_THRESHOLD;
        public const double AVERAGING_CACHE_PRESSURE_MONITORING_OFF = 1.0;
        public const double DEFAULT_AVERAGING_CACHE_PRESSURE_MONITORING_THRESHOLD = 1.0 / 3.0;
    }
}