text:
var m = require("mithril")
require("../../scss/layout/_index.scss")
require("../../scss/base/_index.scss")
var HeaderComponent = require('./components/HeaderComponent')
var MenuComponent = require('./components/MenuComponent')
var PageCarcassModel = require("./models/PageCarcassModel")
var states = require("../utils/states")
var loading = require("../basic/loading")
var forbidden = require("../basic/forbidden")
var notfound = require("../basic/notfound")

function renderStatedContent(content, stateFunction) {
  switch (stateFunction()) {
    case states.LOADING:
      return m(loading)
    case states.FORBIDDEN:
      return m(forbidden)
    case states.NOTAUTHORIZED:
      return m(forbidden)
    default:
      return content
  }
}
module.exports = {
  view: function (vnode) {
    document.title = vnode.attrs.title
    var content = (!!vnode.attrs.getState && typeof vnode.attrs.getState === "function") ? renderStatedContent(vnode.attrs.content, vnode.attrs.getState) : vnode.attrs.content
    return m("section#main", [
      m("#site-menu", {
        class: PageCarcassModel.sideMenuShown == true ? "shown" : "hidden"
      }, m(MenuComponent, {
        route: vnode.attrs.route,
        channelID: vnode.attrs.channelID,
        hideMenu: function () {
          PageCarcassModel.sideMenuShown = false
        },
        showMenu: function () {
          PageCarcassModel.sideMenuShown = true
        }
      })),
      m("header#siteHeader", m(HeaderComponent, {

      })),
      m("section#siteContent", m(".content", content)),
    ])
  }
}


text:
public class JavaClass {
    public class Inner {
        public class InnerInner {
            public static final String CONST = "A";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
.. include:: shortcuts

.. _grayscale:

Grayscale
=========

So far, you have been annotating black-and-white images (these are called
*binary* in literature, as they only consist of two colors, and can
be characterized using just 0s for black pixels -- background --
and 1s for white pixels -- foreground). Now, we proceed into the realm
of images that consist of all sorts of shades of gray (called *grayscale*).
This document will teach you how to use MUSCIMarker to annotate grayscale
images efficiently.

Why are we talking about binarization?
--------------------------------------

MUSCIMarker has tools that speed up annotation of images
with a black background.
However, these tools do not work on normal
grayscale images. The Trimmed Lasso behaves like a normal lasso
(selecting all pixels that you draw it around) without the black
background, and the Connected Component tool fails completely -- if
there is no background, the entire image is a single connected component
of the foreground.

Especially for musical scores, it is hard to automate
*binarization* -- the process of determining which pixels belong
to the background, and which do not -- of document images in general,
because the pen strokes usually come out with different intensities,
the paper is dirty, lighting is uneven, etc. In the end, really accurate
binarization is practically equivalent to annotating the score
in the first place.

Therefore, instead of supplying already binarized
images, **you will mark the background as you go**. This way, at
the cost of doing binarization together with annotation, you retain
the power of MUSCIMarker annotation tools, and the resulting annotation
will at the same time remain accurate.

.. note::

    Grayscale images harder to annotate accurately than binary (black-and-white).
    We do not expect the same level of annotation accuracy as we did for
    binary images, as that would take too long. (However, accuracy still
    matters -- it's just that in situations where symbols have e.g. unclear
    edges dissolving gradually into the background, don't sweat it too much.
    In general, making the symbols a little bit *larger* is better than
    making them smaller.

How to binarize efficiently
---------------------------

Binarization is *not* another result of the annotation. Binarization tools
just make temporary changes to the image so that you have an easier life
trying to annotate the symbols.

**Best practice 1:** First binarize a region of the image, then annotate it.

**Best practice 2:** Don't binarize too much at once. Stick to binarizing
areas that fit on your screen when you are zoomed in to annotate.

Remember: the goal is *NOT* to binarize the input image accurately. The goal
is to *annotate the symbols and their relationships*, and binarization is
a way to help you do it faster.

.. note::

    In general, binarization and annotation do not mix. If you binarize a part
    of the image, the objects and relationships that are already there will
    not be affected at all.

    This may lead to slightly counterintuitive results. If you
    annotate an object, and then mark a part of the object as background
    (and, therefore, the pixels should not participate in any future
    symbols), that part of the object will *remain* in the previously
    marked object.

Binarization Tools
------------------

MUSCIMarker gives you the following tools for binarization:

* **Background Lasso** (really easy!)
* **Region Binarization** (a little tricky)

We will now explain how to use each of these.

Background Lasso
^^^^^^^^^^^^^^^^

With the Background Lasso tool, you mark a part of the image as background.
It works like any other lasso tool. Once you release the mouse button,
the selected region will turn black and subsequently will be correctly
handled by Trimmed Lasso and Connected Components.

Region Binarization
^^^^^^^^^^^^^^^^^^^

The Region Binarization tool attempts to guess which parts of a given region
belong to the background. It guesses a cutoff intensity that should produce
a separation into foreground and background pixel intensities.

When using region binarization:

* Apply it to regions of the size that you will be annotating without moving
  around. Apply region binarization when you are already zoomed in
  at your preferred zoom for annotating.
* Don't apply it to regions that overlap with already binarized regions
  by more than a few pixels. The uniform black of the background in the
  already binarized part of the region will confuse the guessing algorithm.

The gory details, if you're interested (but you don't have to read this):

We use Otsu's binarization algorithm.
It assumes the intensity (brightness) of a pixel
comes from either a *background* source, or a *foreground* source.
Each of these two assumed sources is assumed to have a default intensity
which it prefers to assign to "its" pixels, but there is some randomness
in the process of generating intensities, so instead of the default intensity,
each pixel comes out somewhat different from the given source's default.
Think of it like throwing darts: the background source and foreground source
each have a default intensity in the middle of the dart board, and as
the darts land further from the target, the output intensity will be more
and more different from the default. Otsu's algorithm assumes

This makes Otsu's algorithm fast to compute, but it's quite fragile
when the image has varying lighting conditions, e.g. when taking a photo
under a lamp (the corners come out darker).

Discarding binarization
-----------------------

Binarization is done on the fly and does not affect the source image.
In case you want to reload the original image, before starting work
on binarization, use the **RELOAD IMG** command in the bottom bar.


text:
<#
.SYNOPSIS
Uninstall a Neo4j Arbiter Windows Service

.DESCRIPTION
Uninstall a Neo4j Arbiter Windows Service

.PARAMETER Neo4jServer
An object representing a Neo4j Server.  Either an empty string (path determined by Get-Neo4jHome), a string (path to Neo4j installation) or a valid Neo4j Server object

.PARAMETER ServiceName
The name of the Neo4j Arbiter service.  If no name is specified, the name is determined from the Neo4j Configuration files (default)

.PARAMETER SucceedIfNotExist
Do not raise an error if the service does not exist

.EXAMPLE
'C:\Neo4j\neo4j-enterprise' | Uninstall-Neo4jArbiter

Uninstall the Neo4j Arbiter Windows Service for the Neo4j installation at 'C:\Neo4j\neo4j-enterprise'

.OUTPUTS
System.Management.Automation.PSCustomObject
Neo4j Server object

.NOTES
This function is only applicable to Neo4j editions which support HA

#>
Function Uninstall-Neo4jArbiter
{
  [cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
  param (
    [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
    [object]$Neo4jServer = ''

    ,[Parameter(Mandatory=$false)]
    [string]$ServiceName = ''

    ,[Parameter(Mandatory=$false)]
    [switch]$SucceedIfNotExist
  )

  Begin
  {
  }

  Process
  {
    # Get the Neo4j Server information
    if ($Neo4jServer -eq $null) { $Neo4jServer = '' }
    switch ($Neo4jServer.GetType().ToString())
    {
      'System.Management.Automation.PSCustomObject'
      {
        if (-not (Confirm-Neo4jServerObject -Neo4jServer $Neo4jServer))
        {
          Write-Error "The specified Neo4j Server object is not valid"
          return
        }
        $thisServer = $Neo4jServer
      }
      default
      {
        $thisServer = Get-Neo4jServer -Neo4jHome $Neo4jServer
      }
    }
    if ($thisServer -eq $null) { return }

    # Check if this feature is supported
    if ($thisServer.ServerType -ne 'Enterprise')
    {
      Write-Error "Neo4j Server type $($thisServer.ServerType) does not support HA"
      return
    }

    if ($ServiceName -eq '')
    {
      $setting = ($thisServer | Get-Neo4jSetting -ConfigurationFile 'arbiter-wrapper.conf' -Name 'wrapper.name')
      if ($setting -ne $null) { $ServiceName = $setting.Value }
    }

    if ($ServiceName -eq '')
    {
      Write-Error 'Could not find the Windows Service Name for Neo4j Arbiter'
      return
    }

    # Get the Service object as a WMI object.  Can only do deletions through WMI or SC.EXE
    $service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'"
    if (($service -eq $null) -and (-not $SucceedIfNotExist) )
    {
      Write-Error "Windows service $ServiceName cannot be removed as it does not exist"
      return
    }

    if ($service -ne $null)
    {
      Stop-Service -ServiceName $ServiceName | Out-Null
      if ($PSCmdlet.ShouldProcess($ServiceName, 'Remove Windows Service'))
      {
        $service.delete() | Out-Null
      }
    }

    Write-Output $thisServer
  }

  End
  {
  }
}


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

    <title>UMD vs. UNC Basketball Game Events</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <link rel="stylesheet" href="../keshif.css"/ type="text/css">
    <link rel="stylesheet" href="../font-awesome/css/font-awesome.min.css">

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

UMD vs. UNC Basketball - March 16, 2013

      Game events from
      UMD vs. UNC Basketball Game,
      Saturday, March 16, 2013.

      To analyze event sequences, you can use
          EventFlow.


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mapviewer.business.servlets;

import com.mapviewer.business.GeneraSolicitudesWCS;
import com.mapviewer.business.LayerMenuManagerSingleton;
import com.mapviewer.business.OpenLayersManager;
import com.mapviewer.model.Layer;
import com.mapviewer.conf.OpenLayerMapConfig;
import com.mapviewer.exceptions.XMLFilesException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * This servlet is in charge of receiving the request of the tematic data. Like then the
 * user want to download a geotiff file.
 */
public class WCSServlet extends HttpServlet {

	OpenLayersManager opManager;//incharge of OpenLayers code.
	OpenLayerMapConfig mapConfig;
	String basePath;

	@Override
	public void init() throws ServletException {
		super.init();
	}

	/**
	 * Processes requests for both HTTP
	 * GET and
	 * POST methods.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=iso-8859-1");
		PrintWriter out = response.getWriter();

		try {
			String mainLayer = request.getParameter("mainLayer");

			Layer selectedLayer = LayerMenuManagerSingleton.getInstance().getLayerByName(mainLayer);

			String format = "";
			String cqlfilter = "";
			if (selectedLayer.isVectorLayer()) {
				format = "SHAPE-ZIP";
				cqlfilter = request.getParameter("CQLFILTER");
			} else {
				format = "image/geotiff";
			}

			String[][] solicitudWCS = GeneraSolicitudesWCS.wcsManager(selectedLayer, format, cqlfilter);
			out.println(solicitudWCS[0][0]);
//			out.println(""+solicitudWCS[i][2]+".
Capa GeoTiff
 Resolución  "+solicitudWCS[i][1]+" m

");
		}catch(XMLFilesException ex){
			out.println("XMLFiles Exception: "+ ex.getMessage());
		}
		finally {
			out.close();
		}
	}

	// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	/**
	 * Handles the HTTP
	 * GET method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP
	 * POST method.
	 *
	 * @param request servlet request
	 * @param response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 *
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}


text:
template<typename T>
struct TErrorResult {
  enum UnionState {
    HasMessage,
    HasException,
  };
  int mResult;
  struct Message;
  struct DOMExceptionInfo;
  union {
    Message* mMessage;
    DOMExceptionInfo* mDOMExceptionInfo;
  };

  bool mMightHaveUnreported;
  UnionState mUnionState;
};

struct ErrorResult : public TErrorResult<int> {
};


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 52(3): 477 (1969)

#### Original name
Endophragmia alternata Tubaki & Saito, 1969

### Remarks
null


text:
<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://getfrapi.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@getfrapi.com so we can send you a copy immediately.
 *
 * @license   New BSD
 * @package   frapi-admin
 */
class TesterController extends Lupin_Controller_Base
{
    private $tr;

    public function init($styles = array())
    {
        $this->tr = Zend_Registry::get('tr');
        $actions = array('index', 'ajax', 'history');
        $this->_helper->_acl->allow('admin', $actions);
        parent::init($styles);
    }

    public function indexAction()
    {
        $request     = $this->getRequest();
        $form        = new Default_Form_Tester;

        $confModel   = new Default_Model_Configuration();
        if (!$confModel->getKey("api_url")) {
            $this->addInfoMessage($this->tr->_('TESTER_API_INFO_MESSAGE'));
        }

        $this->view->form = $form;
    }

    public function ajaxAction()
    {
        $this->view  = new Lupin_View();

        $method      = strtolower($this->_request->getParam('method'));
        $query_uri   = trim($this->_request->getParam('query_uri'), '/ ');
        $url         = $this->_request->getParam('url');
        $ssl         = $this->_request->getParam('ssl');
        $extraParams = $this->_request->getParam('param');

        $params      = array();

        $session_query_uri = '/' . substr($query_uri, 0, strrpos($query_uri, '.'));
        $test_history      = new Zend_Session_Namespace('test_history');
        $history           = $test_history->value;

        $history[$session_query_uri] = $this->getRequest()->getParams();

        $test_history->value = $history;

        if (!empty($extraParams)) {
            foreach ($extraParams as $newParam) {
                $parms                 = explode('=', $newParam, 2);
                if (count($parms) > 1) {
                    list($key, $value) = $parms;
                    $params[$key]      = $value;
                }
            }
        }

        require_once 'HTTP/Request2.php';

        $newMethod = HTTP_Request2::METHOD_GET;

        switch ($method) {
            case 'get':
                $newMethod = HTTP_Request2::METHOD_GET;
                break;
            case 'post':
                $newMethod = HTTP_Request2::METHOD_POST;
                break;
            case 'put':
                $newMethod = HTTP_Request2::METHOD_PUT;
                break;
            case 'delete':
                $newMethod = HTTP_Request2::METHOD_DELETE;
                break;
            case 'head':
                $newMethod = HTTP_Request2::METHOD_HEAD;

                break;
        }

        $email = $this->_request->getParam('email');
        $pass = $this->_request->getParam('secretKey');

        $request_url = 'http' . ($ssl == true ? 's' : '') . '://' . $url . '/' . $query_uri;

        $request = new HTTP_Request2($request_url, $newMethod);
        $request->setConfig(array(
            'ssl_verify_peer' => false,
            'ssl_verify_host' => false,
        ));

        if ($email && $pass) {
            $request->setAuth($email, $pass, HTTP_Request2::AUTH_DIGEST);
            $request->setHeader(array(
                'Accept' => '*/*'
            ));
        }
        if ($method == 'post') {
            $request->addPostParameter($params);
        } else {
            $url = $request->getUrl();
            $url->setQueryVariables(array() + $params);
        }

        try {
            $res = $request->send();
        } catch (Exception $e) {
            return $this->view->renderJson(array(
                'request_url' => $request_url,
                'response_headers' => $this->collapseHeaders(array(
                    'error' => $e->getMessage())
                ),

                'content' => $e->getMessage(),
                'status' => 'Could not connect',
                'method' => strtoupper($method)
            ));
        }

        $response = array(
            'request_url'         => $request_url,
            'response_headers'    => $this->collapseHeaders($res->getHeader()),
            'content'             => $res->getBody(),
            'status'              => $res->getStatus(),
            'method'              => strtoupper($method),
        );

        $this->view->renderJson($response);
    }

    public function historyAction()
    {
        $this->view  = new Lupin_View();

        $url = strtolower($this->_request->getParam('url'));

        $test_history             = new Zend_Session_Namespace('test_history');
        $history                  = $test_history->value;
        $return_data              = $history[$url];
        $return_data['format']    = substr($return_data['query_uri'], strrpos($return_data['query_uri'], '.') +1);
        $return_data['query_uri'] = substr($return_data['query_uri'], 0, strrpos($return_data['query_uri'], '.'));

        $this->view->renderJson($return_data);
    }

    protected function collapseHeaders($headers)
    {
        $header_string = "";

        foreach ($headers as $name => $value) {
            if (is_array($value)) {
                $value = implode("\n\t", $value);
            }

            $header_string .= ucfirst($name) . ": " . wordwrap($value, 45, "\n\t") . "\n";
        }
        return $header_string;
    }
}


text:
import logging
import inspect
import typing

class RuntimeTypeCheckError(TypeError):
    pass

def _type_eq(value, value_type):

    value_type_class = value_type.__class__
    value_type_info = str(value_type)

    if value_type_class == typing.TypeVar:
        type_var_constraints = value_type.__constraints__

        # empty TypeVar matches everything
        if not type_var_constraints:
            return True

        if not any(_type_eq(value, constraint)
                   for constraint
                   in type_var_constraints):
            return False
        return True

    if str(typing.Tuple) in value_type_info:
        if not isinstance(value, tuple):
            return False

        # python 3.5 support
        if hasattr(value_type, '__tuple_params__'):
            tuple_params = value_type.__tuple_params__
        else:
            tuple_params = value_type.__args__

        if not tuple_params:
            return True

        if not hasattr(value, '__iter__'):
            return False

        if len(value) != len(tuple_params):
            return False

        if not all(_type_eq(inner_value, inner_value_type)
                   for inner_value, inner_value_type
                   in zip(value, tuple_params)):
            return False

        return True

    if str(typing.Union) in value_type_info:

        # python 3.5 support
        if hasattr(value_type, '__union_params__'):
            union_params = value_type.__union_params__
        else:
            union_params = value_type.__args__

        if not union_params:
            return True

        if not any(_type_eq(value, constraint)
                   for constraint
                   in union_params):
            return False
        return True

    if not isinstance(value, value_type):
        return False

    return True

def _validate_types(value, value_type, error_message):
    if not _type_eq(value, value_type):
        raise RuntimeTypeCheckError(error_message)

def runtime_type_checks(func):
    """
    Decorator that performs a runtime check of passed and returned types.
    :param func: function to be decorated (valid Python 3.5+ function with full typing hints support)
    :return: decorated function which is provided with runtime type checks
    """

    def func_wrapper(*args, **kwargs):
        # get type hints of the function
        type_hints = typing.get_type_hints(func)

        func_spec = inspect.getfullargspec(func)

        # check *args
        args_names = func_spec.args
        for i, (key, value) in enumerate(zip(args_names, args)):
            _validate_types(value, type_hints[key],
                            error_message='Positional argument #{} ({}) of type {} does not match required'
                                          'type {}'.format(i, key, type(value), type_hints[key]))

        # check **kwargs
        for key, value in kwargs.items():
            if key in type_hints:
                _validate_types(value, type_hints[key],
                                error_message='{} of type {} does not match required type {}'.format(key,
                                                                                type(value),
                                                                                type_hints[key]))

        # return type if specified
        result = func(*args, **kwargs)
        if 'return' in func_spec.annotations:
            return_type = func_spec.annotations['return']
            _validate_types(result, return_type,
                            error_message='Returned value of type {} does not match required type'
                                          'return {}'.format(type(result), return_type))

        return result

    return func_wrapper


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">

    <include resource="org/springframework/boot/logging/logback/base.xml"/>

    <springProperty scope="context" name="appName" source="info.app.name"/>
    <springProperty scope="context" name="appVersion" source="info.app.version"/>

    <springProfile name="logtoconsole">
        <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
            <layout class="ch.qos.logback.classic.PatternLayout">
                <Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
            </layout>
        </appender>
    </springProfile>

    <springProfile name="!logtoconsole">
        <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
            <encoder class="net.logstash.logback.encoder.LogstashEncoder">
                <includeCallerInfo>true</includeCallerInfo>
            </encoder>
        </appender>
    </springProfile>

    <logger name="uk.gov" additivity="false" level="INFO">
        <appender-ref ref="consoleAppender"/>
    </logger>

    <logger name="com.github.tomakehurst.wiremock" additivity="false" level="INFO">
        <appender-ref ref="consoleAppender"/>
    </logger>

    <root level="INFO">
        <appender-ref ref="consoleAppender"/>
    </root>

</configuration>


text:
'use strict';

var connector = require('./mod/connector');
var docs = require('./mod/docs');

var connection;

var collections = {
    person: {
        versionable: false,
        versionTime: 0,
        closable: false,
        closeTime: 0,
        exclusive: false,
        id: '_id',
        idAuto: true,
        add: [],
        set: []
    }
};

var conf = {
    server: 'localhost',
    database: 'mongoOp'
};

var permmisions = 'RW_';

connector(conf, collections, function (_connection) {
    connection = _connection;
    console.log(connection.getCollectionId("person"));
    console.log("connectado a mongo");
    var request = {
        user: 1,
        data: {
            name: "Carlos"
        },
        operation: "readList",
        ips: "localhost"
    };
    docs(connection, request, "RW_", "person", (res) => {
        console.log(res);
        connection.getDB().close();
    });
    console.log("guardando persona a mongo");
});


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

<title>asgn2Passengers</title>
<meta name="date" content="2016-05-24">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package asgn2Passengers

Class Summary

Class
Description

Business

Economy

First

Passenger

Passenger is an abstract class specifying the basic state of an airline passenger,
 and providing methods to set and access that state.

Premium

Exception Summary

Exception
Description

PassengerException

This class represents exceptions associated with the misuse of the Passenger hierarchy.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
> Rails-inspired generator system that provides scaffolding for your apps

![](https://raw.githubusercontent.com/yeoman/media/master/optimized/yeoman-masthead.png)

## Getting Started

If you're interested in writing your own Yeoman generator we recommend reading [the official getting started guide](http://yeoman.io/authoring/). The guide covers all the basics you need to get started.

A generator can be as complex as you want it to be. It can simply copy a bunch of boilerplate files, or it can be more advanced asking the user's preferences to scaffold a tailor made project. This decision is up to you.

The fastest way to get started is to use  [generator-generator](https://github.com/yeoman/generator-generator), a Yeoman generator to generate a Yeoman generator.

After reading the getting started guide, you might want to read the code source or visit our [API documentation](http://yeoman.io/generator/) for a list of all methods available.

[API documentation for v4.x](https://yeoman.github.io/generator/4.x).

### Debugging

See the [debugging guide](http://yeoman.io/authoring/debugging.html).

## Contributing

We love contributors! See our [contribution guideline](http://yeoman.io/contributing/) to get started.

## Sponsors
Love Yeoman work and community? Help us keep it alive by donating funds to cover project expenses!

[[Become a sponsor](https://opencollective.com/yeoman#support)]

## License

[BSD license](http://opensource.org/licenses/bsd-license.php)
Copyright (c) Google


text:
import DS from 'ember-data';
import Validator from '../../mixins/model-validator';

export default DS.Model.extend(Validator,{
  anInteger: DS.attr('number'),
  anIntegerLessThan4: DS.attr('number'),
  anIntegerGreaterThan4: DS.attr('number'),
  anIntegerGreaterThanOrEqual7: DS.attr('number'),
  anIntegerLessThanOrEqual6: DS.attr('number'),
  aTenNumber: DS.attr('number'),
  anOddNumber: DS.attr('number'),
  anEvenNumber: DS.attr('number'),
  anOptionalNumber: DS.attr('number'),

  validations: {
    anInteger:{
      numericality: {onlyInteger: true }
    },
    anIntegerLessThan4:{
      numericality: {lessThan: 4}
    },
    anIntegerGreaterThan4:{
      numericality: {greaterThan: 4}
    },
    anIntegerGreaterThanOrEqual7:{
      numericality: {greaterThanOrEqualTo: 7}
    },
    anIntegerLessThanOrEqual6:{
      numericality: {lessThanOrEqualTo: 6}
    },
    aTenNumber:{
      numericality: {equalTo: 10}
    },
    anOddNumber:{
      numericality: {odd: true}
    },
    anEvenNumber:{
      numericality: {even: true}
    },
    anOptionalNumber:{
      numericality: {onlyInteger: true, allowBlank: true}
    }
  }
});


text:
from itsdangerous import Serializer, BadSignature
from itsdangerous import SignatureExpired
from sqlalchemy.orm import sessionmaker
import AppConfig
from dbmodels.Models import User, Post

class BaseService():
    __dbEngine = None
    __session = None

    def __init__(self, dbEngine=None):
        if dbEngine is None:
            self.__dbEngine = AppConfig.DBENGINE
        else:
            self.__dbEngine = dbEngine
        Session = sessionmaker(bind=self.__dbEngine)
        self.__session = Session()

    def get_session(self):
        return self.__session

class PostService(BaseService):
    def __init__(self):
        super(PostService, self).__init__()

    def getAll(self):
        return self.get_session().query(Post)

    def getById(self, id):
        return self.get_session().query(Post).filter_by(id=id).first()

class UserService(BaseService):
    def __init__(self):
        super(UserService, self).__init__()

    def getUserByUsername(self, username):
        user = self.get_session().query(User).filter_by(username=username).first()
        return user

    def getById(self, id):
        user = self.get_session().query(User).filter_by(id=id).first()
        return user

    def getAll(self):
        return self.get_session().query(User)

    def validate(self, username, password):
        user = self.getAll().filter_by(username=username, password=password).first()
        return user is not None


text:
package com.bluedot.efactura.model;

import java.util.Map;
import java.util.TreeMap;

public enum IndicadorFacturacion {

	INDICADOR_FACTURACION_EXCENTO_IVA(1, true),

	INDICADOR_FACTURACION_IVA_TASA_MINIMA(2, true),

	INDICADOR_FACTURACION_IVA_TASA_BASICA(3, true),

	INDICADOR_FACTURACION_IVA_OTRA_TASA(4, true),

	INDICADOR_FACTURACION_ENTREGA_GRATUITA(5, true),

	/*
	 * 4.10. ¿Cómo se documentan las cobranzas de terceros? (01/12/2011) Las
	 * cobranzas de terceros como pueden ser las de los entes públicos, están
	 * contempladas en el campo de los CFE "montos no facturables", debiendo
	 * utilizar en la línea de detalle el indicador de facturación 6 "Producto o
	 * servicio no facturable". Si fuere necesario anular uno de estos conceptos
	 * en el mismo comprobante se debe utilizar el indicador de facturación 7
	 * "Producto o servicio no facturable negativo".
	 */
	INDICADOR_FACTURACION_NO_FACTURABLE(6, true),

	INDICADOR_FACTURACION_NO_FACTURABLE_NEGATIVO(7, true),

	/*
	 * 4.20. ¿Es posible corregir un e-Remito o un e-Remito de exportación? Sí.
	 * En caso que corresponda corregir un e-Remito o un e-Remito de exportación
	 * recibido por DGI, el mismo se ajustará con otro CFE del mismo tipo. En
	 * caso que el ajuste sea negativo se debe utilizar el indicador de
	 * facturación 8 (código "B-C4" de Formato de CFE)
	 */
	INDICADOR_FACTURACION_REBAJAR_EN_REMITOS(8),

	/*
	 * 4.25. ¿Qué indicador de facturación se utiliza en los e-resguardos? En la
	 * confección de los e-resguardos no corresponde utilizar indicador de
	 * facturación. Únicamente en el caso que deba anular, total o parcialmente
	 * otro e-resguardo ya emitido, deberá utilizar el indicador de facturación
	 * 9, debiendo indicar en el área de referencia el Nº de resguardo que
	 * ajusta.y la expresión "Corrección de e-Resguardo" en la Adenda. (Creada
	 * 10/02/2015)
	 */
	INDICADOR_FACTURACION_ANULAR_EN_RESGUARDOS(9),

	INDICADOR_FACTURACION_EXPORTACION_Y_ASIMILADAS(10, true),

	INDICADOR_FACTURACION_IMPUESTO_PERCIBIDO(11),

	INDICADOR_FACTURACION_IVA_SUSPENSO(12, true);

	private int indice;
	private boolean soportado;

	public static int maxIndice;

	private static Map<Integer, IndicadorFacturacion> idMap = new TreeMap<Integer, IndicadorFacturacion>();

	IndicadorFacturacion(int indice) {
		this.indice = indice;
		this.soportado = false;
	}

	IndicadorFacturacion(int indice, boolean soportado) {
		this.indice = indice;
		this.soportado = soportado;
	}

	static {
		maxIndice = 0;
		for (IndicadorFacturacion iva : values()) {
			idMap.put(iva.indice, iva);
			if (iva.indice > maxIndice)
				maxIndice = iva.indice;
		}
	}

	public static IndicadorFacturacion fromInt(int i) {
		return idMap.get(i);
	}

	public int getIndice() {
		return indice;
	}

	public boolean isSoportado() {
		return soportado;
	}

}


text:
package com.google.android.apps.common.testing.ui.espresso.base;

import com.google.android.apps.common.testing.ui.espresso.IdlingResource;

/**
 * An {@link IdlingResource} for testing that becomes idle on demand.
 */
public class OnDemandIdlingResource implements IdlingResource {
  private final String name;

  private boolean isIdle = false;
  private ResourceCallback callback;

  public OnDemandIdlingResource(String name) {
    this.name = name;
  }

  @Override
  public void registerIdleTransitionCallback(ResourceCallback callback) {
    this.callback = callback;
  }

  @Override
  public boolean isIdleNow() {
    return isIdle;
  }

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

  public void forceIdleNow() {
    isIdle = true;
    if (callback != null) {
      callback.onTransitionToIdle();
    }
  }

  public void reset() {
    isIdle = false;
  }
}


text:
package monix.execution.schedulers

import monix.execution.Scheduler

/** Defines extension methods for [[Scheduler]] meant for
  * executing runnables.
  *
  * NOTE: these extension methods are only defined as macros
  * for Scala < 2.12, because in Scala 2.12 we simply rely on
  * its SAM support.
  */
private[execution] trait ExecuteExtensions extends Any {
  def source: Scheduler

  /** Schedules the given callback for asynchronous
    * execution in the thread-pool.
    *
    * On Scala < 2.12 it is described as a macro, so it
    * has zero overhead, being perfectly equivalent with
    * `execute(new Runnable { ... })`.
    *
    * On Scala 2.12 because of the Java 8 SAM types integration,
    * this extension macro is replaced with a method that takes
    * a plain `Runnable` as parameter.
    *
    * @param cb the callback to execute asynchronously
    */
  def executeAsync(cb: () => Unit): Unit =
    source.execute(new Runnable { def run() = cb() })

  /** Schedules the given callback for asynchronous
    * execution in the thread-pool, but also indicates the
    * start of a
    * [[monix.execution.schedulers.TrampolinedRunnable thread-local trampoline]]
    * in case the scheduler is a
    * [[monix.execution.schedulers.BatchingScheduler BatchingScheduler]].
    *
    * This utility is provided as an optimization. If you don't understand
    * what this does, then don't worry about it.
    *
    * On Scala < 2.12 it is described as a macro, so it
    * has zero overhead. On Scala 2.12 because of the Java 8 SAM
    * types integration, this extension macro is replaced with a
    * method that takes a plain `TrampolinedRunnable` as parameter.
    *
    * @param cb the callback to execute asynchronously
    */
  def executeAsyncBatch(cb: () => Unit): Unit = {
    def r = new TrampolinedRunnable { def run() = cb() }
    source.execute(new StartAsyncBatchRunnable(r, source))
  }

  /** Schedules the given callback for immediate execution as a
    * [[monix.execution.schedulers.TrampolinedRunnable TrampolinedRunnable]].
    * Depending on the execution context, it might
    * get executed on the current thread by using an internal
    * trampoline, so it is still safe from stack-overflow exceptions.
    *
    * On Scala < 2.12 it is described as a macro, so it
    * has zero overhead, being perfectly equivalent with
    * `execute(new TrampolinedRunnable { ... })`.
    *
    * On Scala 2.12 because of the Java 8 SAM types integration,
    * this extension macro is replaced with a method that takes
    * a plain `TrampolinedRunnable` as parameter.
    *
    * @param cb the callback to execute asynchronously
    */
  def executeTrampolined(cb: () => Unit): Unit =
    source.execute(new TrampolinedRunnable { def run() = cb() })
}


text:
require 'active_support/concern'

module ReTrack
  module Trackable
    extend ActiveSupport::Concern

    included do
      has_one :referer_tracking,
        class_name: 'ReTrack::RefererTracking',
        as: :trackable,
        validate: false
    end
  end
end


text:
import React, { useReducer, useCallback,useMemo, useEffect, useState } from "react"
import { useSelector } from "react-redux"
import { Box, Typography, Grid, Button, ButtonGroup, Slider } from "@material-ui/core"
import { If } from "jsx-control-statements"

import Wrestler from "components/wrestler/wrestler"
import Gender from "components/gender"
import { useButtonStyles } from "theme"

import reducer, { initialState } from "./rumble.reducer"
import { useRumbleStyle } from "./rumble.style"

const speed = 100
const longSpeed = 100000

const defaultMarks = [
  {
    value: 30,
    label: "30",
  },
]

const genderValue = (male, defaultValue) => male !== null ? male : defaultValue

export default function() {
  const classes = useRumbleStyle()
  const bClasses = useButtonStyles()
  const memoizedReducer = useCallback(reducer, initialState)
  const [ state, dispatch, ] = useReducer(memoizedReducer, initialState)
  const [ count, setCount, ] = useState(0)

  const wrestlers = useSelector(state => state.wrestlers.filter(item => !item.championshipId))

  const maxItems = useMemo(() => wrestlers.filter(item => item.male === state.male).length, [ wrestlers.length, state.male, ])
  const marks = useMemo(() => maxItems > 30 ? defaultMarks : [], [ maxItems, ])

  const eliminated = state.items.filter(item => item.elimination).length
  const hasWinner = eliminated === state.amount - 1
  const canSimulate = !hasWinner && state.items.length > 0

  useEffect(() => {
    const interval = setInterval(() => {
      if (state.simulate) {
        dispatch({
          type: "ELIMINATE_ITEM",
          payload: { wrestlers, },
        })
        setCount(count + 1)
      }
    }, state.simulate ? speed : longSpeed)
    return () => clearInterval(interval)
  }, [ state.simulate, count, wrestlers, ])

  return (
    <React.Fragment>
      <Grid container spacing={2}>
        <Grid item xs={12} lg={8}>
          <Box display="flex" alignItems="center" justifyContent="start" height="100%">
            <Typography variant="h3">
              Rumble
            </Typography>
          </Box>
        </Grid>
        <Grid item xs={12} lg display="flex">
          <If condition={!state.simulate}>
            <Box display="flex" alignItems="center" justifyContent="flex-end" height="100%">
              <Slider
                valueLabelDisplay="on"
                value={state.amount}
                onChange={(event, amount) => dispatch({
                  type: "UPDATE_FILTER",
                  payload: { amount, },
                })}
                aria-labelledby="continuous-slider"
                max={maxItems}
                min={10}
                marks={marks}
              />
            </Box>
          </If>
        </Grid>
        <Grid item xs={12} lg>
          <Box display="flex" alignItems="center" justifyContent="space-around" height="100%">
            <If condition={!state.simulate}>
              <Gender
                both={false}
                male={state.male}
                onChange={(male) => dispatch({
                  type: "UPDATE_FILTER",
                  payload: { male: genderValue(male, state.male), },
                })}
              />

            </If>
            <ButtonGroup>
              <Button
                className={bClasses.info}
                onClick={() => dispatch({
                  type: "GENERATE_ITEMS",
                  payload: { wrestlers, },
                })}
              >
                Generate
              </Button>
              <Button
                disabled={!canSimulate}
                className={state.simulate ? bClasses.error : bClasses.success}
                onClick={() => dispatch({
                  type: "UPDATE_FILTER",
                  payload: { simulate: !state.simulate, },
                })}>
                {state.simulate ? "Simulating..." : "Simulate"}
              </Button>
            </ButtonGroup>
          </Box>
        </Grid>
      </Grid>
      <br />
      <If condition={state.items.length > 0}>
        <Grid spacing={2} container>
          {state.items.map(item => {
            const className = item.elimination ? classes.eliminated : (hasWinner ? classes.winner : classes.ready)
            const title = item.elimination > 0 ? "Eliminated" : `#${item.entry + 1}`

            return (
              <Grid className={className} key={item.id} item xs={4} sm={3} md={2} lg={1}>
                <Wrestler wrestler={item.model} drag={false} />
                <Box display="flex" alignItems="center" justifyContent="center">{title}</Box>
              </Grid>
            )
          })}
        </Grid>
      </If>
    </React.Fragment>
  )
}


text:
var test = require('tap').test
var lockFile = require('../lockfile.js')
var path = require('path')
var fs = require('fs')
var touch = require('touch')

test('setup', function (t) {
  try { lockFile.unlockSync('basic-lock') } catch (er) {}
  try { lockFile.unlockSync('sync-lock') } catch (er) {}
  try { lockFile.unlockSync('never-forget') } catch (er) {}
  try { lockFile.unlockSync('stale-lock') } catch (er) {}
  try { lockFile.unlockSync('watch-lock') } catch (er) {}
  try { lockFile.unlockSync('retry-lock') } catch (er) {}
  try { lockFile.unlockSync('contentious-lock') } catch (er) {}
  try { lockFile.unlockSync('stale-wait-lock') } catch (er) {}
  t.end()
})

test('lock contention', function (t) {
  var gotlocks = 0;
  var N = 200
  var delay = 10
  // allow for some time for each lock acquisition and release.
  // note that raising N higher will mean that the overhead
  // increases, because we're creating more and more watchers.
  // irl, you should never have several hundred contenders for a
  // single lock, so this situation is somewhat pathological.
  var overhead = 200
  var wait = N * overhead + delay

  // first make it locked, so that everyone has to wait
  lockFile.lock('contentious-lock', function(er, lock) {
    t.ifError(er, 'acquiring starter')
    if (er) throw er;
    t.pass('acquired starter lock')
    setTimeout(function() {
      lockFile.unlock('contentious-lock', function (er) {
        t.ifError(er, 'unlocking starter')
        if (er) throw er
        t.pass('unlocked starter')
      })
    }, delay)
  })

  for (var i=0; i < N; i++)
    lockFile.lock('contentious-lock', { wait: wait }, function(er, lock) {
      if (er) throw er;
      lockFile.unlock('contentious-lock', function(er) {
        if (er) throw er
        gotlocks++
        t.pass('locked and unlocked #' + gotlocks)
        if (gotlocks === N) {
          t.pass('got all locks')
          t.end()
        }
      })
    })
})

test('basic test', function (t) {
  lockFile.check('basic-lock', function (er, locked) {
    if (er) throw er
    t.notOk(locked)
    lockFile.lock('basic-lock', function (er) {
      if (er) throw er
      lockFile.lock('basic-lock', function (er) {
        t.ok(er)
        lockFile.check('basic-lock', function (er, locked) {
          if (er) throw er
          t.ok(locked)
          lockFile.unlock('basic-lock', function (er) {
            if (er) throw er
            lockFile.check('basic-lock', function (er, locked) {
              if (er) throw er
              t.notOk(locked)
              t.end()
            })
          })
        })
      })
    })
  })
})

test('sync test', function (t) {
  var locked
  locked = lockFile.checkSync('sync-lock')
  t.notOk(locked)
  lockFile.lockSync('sync-lock')
  locked = lockFile.checkSync('sync-lock')
  t.ok(locked)
  lockFile.unlockSync('sync-lock')
  locked = lockFile.checkSync('sync-lock')
  t.notOk(locked)
  t.end()
})

test('exit cleanup test', function (t) {
  var child = require.resolve('./fixtures/child.js')
  var node = process.execPath
  var spawn = require('child_process').spawn
  spawn(node, [child]).on('exit', function () {
    setTimeout(function () {
      var locked = lockFile.checkSync('never-forget')
      t.notOk(locked)
      t.end()
    }, 100)
  })
})

test('error exit cleanup test', function (t) {
  var child = require.resolve('./fixtures/bad-child.js')
  var node = process.execPath
  var spawn = require('child_process').spawn
  spawn(node, [child]).on('exit', function () {
    setTimeout(function () {
      var locked = lockFile.checkSync('never-forget')
      t.notOk(locked)
      t.end()
    }, 100)
  })
})

test('staleness test', function (t) {
  lockFile.lock('stale-lock', function (er) {
    if (er) throw er

    var opts = { stale: 1 }
    setTimeout(next, 1000)
    function next () {
      lockFile.check('stale-lock', opts, function (er, locked) {
        if (er) throw er
        t.notOk(locked)
        lockFile.lock('stale-lock', opts, function (er) {
          if (er) throw er
          lockFile.unlock('stale-lock', function (er) {
            if (er) throw er
            t.end()
          })
        })
      })
    }
  })
})

test('staleness sync test', function (t) {
  var opts = { stale: 1 }
  lockFile.lockSync('stale-lock')
  setTimeout(next, 1000)
  function next () {
    var locked
    locked = lockFile.checkSync('stale-lock', opts)
    t.notOk(locked)
    lockFile.lockSync('stale-lock', opts)
    lockFile.unlockSync('stale-lock')
    t.end()
  }
})

test('watch test', function (t) {
  var opts = { wait: 100 }
  var fdx
  lockFile.lock('watch-lock', function (er, fd1) {
    if (er) throw er
    setTimeout(unlock, 10)
    function unlock () {
      console.error('unlocking it')
      lockFile.unlockSync('watch-lock')
      // open another file, so the fd gets reused
      // so we can know that it actually re-opened it fresh,
      // rather than just getting the same lock as before.
      fdx = fs.openSync('x', 'w')
      fdy = fs.openSync('x', 'w')
    }

    // should have gotten a new fd
    lockFile.lock('watch-lock', opts, function (er, fd2) {
      if (er) throw er
      t.notEqual(fd1, fd2)
      fs.closeSync(fdx)
      fs.closeSync(fdy)
      fs.unlinkSync('x')
      lockFile.unlockSync('watch-lock')
      t.end()
    })
  })
})

test('retries', function (t) {
  // next 5 opens will fail.
  var opens = 5
  fs._open = fs.open
  fs.open = function (path, mode, cb) {
    if (--opens === 0) {
      fs.open = fs._open
      return fs.open(path, mode, cb)
    }
    var er = new Error('bogus')
    // to be, or not to be, that is the question.
    er.code = opens % 2 ? 'EEXIST' : 'ENOENT'
    process.nextTick(cb.bind(null, er))
  }

  lockFile.lock('retry-lock', { retries: opens }, function (er, fd) {
    if (er) throw er
    t.equal(opens, 0)
    t.ok(fd)
    lockFile.unlockSync('retry-lock')
    t.end()
  })
})

test('retryWait', function (t) {
  // next 5 opens will fail.
  var opens = 5
  fs._open = fs.open
  fs.open = function (path, mode, cb) {
    if (--opens === 0) {
      fs.open = fs._open
      return fs.open(path, mode, cb)
    }
    var er = new Error('bogus')
    // to be, or not to be, that is the question.
    er.code = opens % 2 ? 'EEXIST' : 'ENOENT'
    process.nextTick(cb.bind(null, er))
  }

  var opts = { retries: opens, retryWait: 100 }
  lockFile.lock('retry-lock', opts, function (er, fd) {
    if (er) throw er
    t.equal(opens, 0)
    t.ok(fd)
    lockFile.unlockSync('retry-lock')
    t.end()
  })
})

test('retry sync', function (t) {
  // next 5 opens will fail.
  var opens = 5
  fs._openSync = fs.openSync
  fs.openSync = function (path, mode) {
    if (--opens === 0) {
      fs.openSync = fs._openSync
      return fs.openSync(path, mode)
    }
    var er = new Error('bogus')
    // to be, or not to be, that is the question.
    er.code = opens % 2 ? 'EEXIST' : 'ENOENT'
    throw er
  }

  var opts = { retries: opens }
  lockFile.lockSync('retry-lock', opts)
  t.equal(opens, 0)
  lockFile.unlockSync('retry-lock')
  t.end()
})

test('wait and stale together', function (t) {
  // first locker.
  var interval
  lockFile.lock('stale-wait-lock', function(er) {
    // keep refreshing the lock, so we keep it forever
    interval = setInterval(function() {
      touch.sync('stale-wait-lock')
    }, 10)

    // try to get another lock.  this must fail!
    var opt = { stale: 1000, wait: 2000 }
    lockFile.lock('stale-wait-lock', opt, function (er) {
      if (!er)
        t.fail('got second lock?  that unpossible!')
      else
        t.pass('second lock failed, as i have foreseen it')
      clearInterval(interval)
      t.end()
    })
  })
})

test('cleanup', function (t) {
  try { lockFile.unlockSync('basic-lock') } catch (er) {}
  try { lockFile.unlockSync('sync-lock') } catch (er) {}
  try { lockFile.unlockSync('never-forget') } catch (er) {}
  try { lockFile.unlockSync('stale-lock') } catch (er) {}
  try { lockFile.unlockSync('watch-lock') } catch (er) {}
  try { lockFile.unlockSync('retry-lock') } catch (er) {}
  try { lockFile.unlockSync('contentious-lock') } catch (er) {}
  try { lockFile.unlockSync('stale-wait-lock') } catch (er) {}
  t.end()
})


text:
Myblog::App.controllers :order do

  # get :index, :map => '/foo/bar' do
  #   session[:foo] = 'bar'
  #   render 'index'
  # end

  # get :sample, :map => '/sample/url', :provides => [:any, :js] do
  #   case content_type
  #     when :js then ...
  #     else ...
  # end

  # get :foo, :with => :id do
  #   "Maps to url '/foo/#{params[:id]}'"
  # end

  # get '/example' do
  #   'Hello world!'
  # end

  get :intend_to_buy, :with => :id do
    @order = Order.new

    if current_user
      @seller = UserNode.find(session[:user_node]).seller
      @order.seller = @seller
      @order.user = current_user
      @order.amount = 0
      @order.status = "正在进行中"
      @order.customer_mobile = current_user.mobile
      @order.save
      @order_product = OrderProduct.new
      @order_product.product = Product.find(params[:id])
      @order_product.order = @order
      @order_product.counter = 1
      @order_product.save

    else
      session[:intend_to_buy] = true
      session[:product_id] = params[:id]
      redirect url('/login')
    end
    render 'order/show'

  end

end


text:
"""
Various functionality for OpenNSA CLI options.
"""

import time
import datetime

from twisted.python import log

from opennsa import config

# option names, as constants so we don't use strings in other modules
VERBOSE         = 'verbose'
DEFAULTS_FILE   = 'defaults-file'
DUMP_PAYLOAD    = 'dump-payload'
WSDL_DIRECTORY  = 'wsdl'
HOST            = 'host'
PORT            = 'port'

TOPOLOGY_FILE   = 'topology'
NETWORK         = 'network'
SERVICE_URL     = 'service'
REQUESTER       = 'requester'
PROVIDER        = 'provider'

CONNECTION_ID   = 'connection-id'
GLOBAL_ID       = 'global-id'

SOURCE_STP      = 'source'
DEST_STP        = 'dest'
BANDWIDTH       = 'bandwidth'
START_TIME      = 'starttime'
END_TIME        = 'endtime'

TLS             = config.TLS
KEY             = config.KEY
CERTIFICATE     = config.CERTIFICATE
CERTIFICATE_DIR = config.CERTIFICATE_DIR
VERIFY_CERT     = config.VERIFY_CERT

FULL_GRAPH      = 'fullgraph'

# other constants
XSD_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"

def parseTimestamp(value):

    if value.startswith('+'):
        offset = int(value[1:])
        ts = datetime.datetime.utcfromtimestamp(time.time() + offset)
    else:
        ts = datetime.datetime.strptime(value, XSD_DATETIME_FORMAT)
    return ts

def readDefaults(file_):

    defaults = {}

    for line in file_.readlines():

        try:
            line = line.strip()

            if not line or line.startswith('#'):
                continue # skip comment

            option, value = line.split('=',2)

            # parse datetimes
            if option in (START_TIME, END_TIME):
                value = parseTimestamp(value)

            if option in (PORT, BANDWIDTH):
                value = int(value)

            if option in (TLS,VERIFY_CERT): # flags
                value = False if value.lower() in ('false', 'no', '0') else True

            defaults[option] = value

        except Exception, e:
            log.msg('Error parsing line "%s" in defaults file. Error: %s' % (line, str(e)))

    return defaults


text:
angular.module('app-demand').controller('PersonSelectCtrl',  function($scope){
	$scope.test = function (){
		alert(88)
	};
	$scope.disablePrePage = true;
	$scope.persons = [];
	$scope.persons.push({'name':'张三','image':'assets/images/head.png'});
	$scope.persons.push({'name':'张三','image':'assets/images/head.png'});
	$scope.persons.push({'name':'张三','image':'assets/images/head.png'});
	$scope.persons.push({'name':'张三','image':'assets/images/head.png'});
	$scope.persons.push({'name':'张三','image':'assets/images/head.png'});

	$scope.nextPage = function (){
		$scope.disablePrePage = false;
		$scope.persons.length = 0;
		$scope.persons.push({'name':'李四','image':'assets/images/head.png'});
		$scope.persons.push({'name':'李四','image':'assets/images/head.png'});
		$scope.persons.push({'name':'李四','image':'assets/images/head.png'});
	}

})


text:
package org.apache.beam.runners.core.metrics;

import static org.apache.beam.runners.core.metrics.MonitoringInfoEncodings.decodeInt64Counter;

import org.apache.beam.model.pipeline.v1.MetricsApi.MonitoringInfo;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

/** Matchers for {@link MonitoringInfo}. */
public class MonitoringInfoMatchers {

  /**
   * Matches a {@link MonitoringInfo} with that has the set fields in the provided MonitoringInfo.
   *
   *
Currently this will only check for URNs, labels, type URNs and payloads.
   */
  public static TypeSafeMatcher<MonitoringInfo> matchSetFields(final MonitoringInfo mi) {
    return new TypeSafeMatcher<MonitoringInfo>() {

      @Override
      protected boolean matchesSafely(MonitoringInfo item) {
        return (mi.getUrn().isEmpty() || mi.getUrn().equals(item.getUrn()))
            && (mi.getLabelsMap().isEmpty() || mi.getLabelsMap().equals(item.getLabelsMap()))
            && (mi.getType().isEmpty() || mi.getType().equals(item.getType()))
            && (mi.getPayload().isEmpty() || mi.getPayload().equals(item.getPayload()));
      }

      @Override
      public void describeTo(Description description) {
        description
            .appendText("URN=")
            .appendValue(mi.getUrn())
            .appendText(", labels=")
            .appendValue(mi.getLabelsMap())
            .appendText(", type=")
            .appendValue(mi.getType())
            .appendText(", payload=")
            .appendValue(mi.getPayload());
      }
    };
  }

  /**
   * Matches a {@link MonitoringInfo} with a {@code value} greater then or equal to the {@code
   * value} supplied.
   *
   *
Currently this will only check for {@code beam:coder:varint:v1} encoded values.
   */
  public static TypeSafeMatcher<MonitoringInfo> counterValueGreaterThanOrEqualTo(final long value) {
    return new TypeSafeMatcher<MonitoringInfo>() {

      @Override
      protected boolean matchesSafely(MonitoringInfo item) {
        long decodedValue = decodeInt64Counter(item.getPayload());
        return decodedValue >= value;
      }

      @Override
      public void describeTo(Description description) {
        description.appendText("value=").appendValue(value);
      }
    };
  }
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>jQuery Mobile: hashchange Tester: Another page</title>
	<link rel="stylesheet"  href="../../../css/themes/default/jquery.mobile.css" />
	<link rel="stylesheet" href="../../../docs/_assets/css/jqm-docs.css" />

		Go To

Another page

Navigation

				A page
				Another page

		A page
		Yet another page

Popup on another page

		Popup on another page
		A dialog

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

		A page

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
from django.core.urlresolvers import reverse_lazy
from django.conf.urls import include, url
from django.views.generic import RedirectView, TemplateView

from django.contrib import admin
from django.contrib.auth import views as auth_views

from djauth.views import loggedout

admin.autodiscover()
admin.site.site_header = 'Carthage College'

handler404 = 'djtools.views.errors.four_oh_four_error'
handler500 = 'djtools.views.errors.server_error'

urlpatterns = [
    url(
        r'^admin/', include(admin.site.urls)
    ),
    # auth
    url(
        r'^accounts/login/$',auth_views.login,
        {'template_name': 'accounts/login.html'},
        name='auth_login'
    ),
    url(
        r'^accounts/logout/$',auth_views.logout,
        {'next_page': reverse_lazy("auth_loggedout")},
        name="auth_logout"
    ),
    url(
        r'^accounts/loggedout/$',loggedout,
        {'template_name': 'accounts/logged_out.html'},
        name="auth_loggedout"
    ),
    url(
        r'^accounts/$',
        RedirectView.as_view(url=reverse_lazy("auth_login"))
    ),
    # core app
    url(
        r'^core/', include("djequis.core.urls")
    ),
    url(
        r'^denied/$',
        TemplateView.as_view(
            template_name="denied.html"
        ), name="access_denied"
    ),
    # redirect
    #url(
    #    r'^$', RedirectView.as_view(url="/foobar/")
    #),
]


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Roy. Soc. South Australia 60: 160 (1931)

#### Original name
Clavaria ochraceosalmonicolor Cleland, 1931

### Remarks
null


text:
namespace boost {
namespace numeric {
namespace bindings {
namespace lapack {

//
// The detail namespace contains value-type-overloaded functions that
// dispatch to the appropriate back-end LAPACK-routine.
//
namespace detail {

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * float value-type.
//
inline std::ptrdiff_t steqr( const char compz, const fortran_int_t n, float* d,
        float* e, float* z, const fortran_int_t ldz, float* work ) {
    fortran_int_t info(0);
    LAPACK_SSTEQR( &compz, &n, d, e, z, &ldz, work, &info );
    return info;
}

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * double value-type.
//
inline std::ptrdiff_t steqr( const char compz, const fortran_int_t n,
        double* d, double* e, double* z, const fortran_int_t ldz,
        double* work ) {
    fortran_int_t info(0);
    LAPACK_DSTEQR( &compz, &n, d, e, z, &ldz, work, &info );
    return info;
}

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * complex<float> value-type.
//
inline std::ptrdiff_t steqr( const char compz, const fortran_int_t n, float* d,
        float* e, std::complex<float>* z, const fortran_int_t ldz,
        float* work ) {
    fortran_int_t info(0);
    LAPACK_CSTEQR( &compz, &n, d, e, z, &ldz, work, &info );
    return info;
}

//
// Overloaded function for dispatching to
// * netlib-compatible LAPACK backend (the default), and
// * complex<double> value-type.
//
inline std::ptrdiff_t steqr( const char compz, const fortran_int_t n,
        double* d, double* e, std::complex<double>* z,
        const fortran_int_t ldz, double* work ) {
    fortran_int_t info(0);
    LAPACK_ZSTEQR( &compz, &n, d, e, z, &ldz, work, &info );
    return info;
}

} // namespace detail

//
// Value-type based template class. Use this class if you need a type
// for dispatching to steqr.
//
template< typename Value, typename Enable = void >
struct steqr_impl {};

//
// This implementation is enabled if Value is a real type.
//
template< typename Value >
struct steqr_impl< Value, typename boost::enable_if< is_real< Value > >::type > {

    typedef Value value_type;
    typedef typename remove_imaginary< Value >::type real_type;

    //
    // Static member function for user-defined workspaces, that
    // * Deduces the required arguments for dispatching to LAPACK, and
    // * Asserts that most arguments make sense.
    //
    template< typename VectorD, typename VectorE, typename MatrixZ,
            typename WORK >
    static std::ptrdiff_t invoke( const char compz, VectorD& d, VectorE& e,
            MatrixZ& z, detail::workspace1< WORK > work ) {
        namespace bindings = ::boost::numeric::bindings;
        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixZ >::value) );
        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<
                typename bindings::value_type< VectorD >::type >::type,
                typename remove_const< typename bindings::value_type<
                VectorE >::type >::type >::value) );
        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<
                typename bindings::value_type< VectorD >::type >::type,
                typename remove_const< typename bindings::value_type<
                MatrixZ >::type >::type >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorD >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorE >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixZ >::value) );
        BOOST_ASSERT( bindings::size(d) >= 0 );
        BOOST_ASSERT( bindings::size(e) >= bindings::size(d)-1 );
        BOOST_ASSERT( bindings::size(work.select(real_type())) >=
                min_size_work( bindings::size(d), compz ));
        BOOST_ASSERT( bindings::size_minor(z) == 1 ||
                bindings::stride_minor(z) == 1 );
        BOOST_ASSERT( compz == 'N' || compz == 'V' || compz == 'I' );
        return detail::steqr( compz, bindings::size(d),
                bindings::begin_value(d), bindings::begin_value(e),
                bindings::begin_value(z), bindings::stride_major(z),
                bindings::begin_value(work.select(real_type())) );
    }

    //
    // Static member function that
    // * Figures out the minimal workspace requirements, and passes
    //   the results to the user-defined workspace overload of the
    //   invoke static member function
    // * Enables the unblocked algorithm (BLAS level 2)
    //
    template< typename VectorD, typename VectorE, typename MatrixZ >
    static std::ptrdiff_t invoke( const char compz, VectorD& d, VectorE& e,
            MatrixZ& z, minimal_workspace ) {
        namespace bindings = ::boost::numeric::bindings;
        bindings::detail::array< real_type > tmp_work( min_size_work(
                bindings::size(d), compz ) );
        return invoke( compz, d, e, z, workspace( tmp_work ) );
    }

    //
    // Static member function that
    // * Figures out the optimal workspace requirements, and passes
    //   the results to the user-defined workspace overload of the
    //   invoke static member
    // * Enables the blocked algorithm (BLAS level 3)
    //
    template< typename VectorD, typename VectorE, typename MatrixZ >
    static std::ptrdiff_t invoke( const char compz, VectorD& d, VectorE& e,
            MatrixZ& z, optimal_workspace ) {
        namespace bindings = ::boost::numeric::bindings;
        return invoke( compz, d, e, z, minimal_workspace() );
    }

    //
    // Static member function that returns the minimum size of
    // workspace-array work.
    //
    static std::ptrdiff_t min_size_work( const std::ptrdiff_t n,
            const char compz ) {
        if ( compz == 'N' ) {
            return 1;
        } else {
            return std::max< std::ptrdiff_t >( 1, 2*n-2 );
        }
    }
};

//
// This implementation is enabled if Value is a complex type.
//
template< typename Value >
struct steqr_impl< Value, typename boost::enable_if< is_complex< Value > >::type > {

    typedef Value value_type;
    typedef typename remove_imaginary< Value >::type real_type;

    //
    // Static member function for user-defined workspaces, that
    // * Deduces the required arguments for dispatching to LAPACK, and
    // * Asserts that most arguments make sense.
    //
    template< typename VectorD, typename VectorE, typename MatrixZ,
            typename WORK >
    static std::ptrdiff_t invoke( const char compz, VectorD& d, VectorE& e,
            MatrixZ& z, detail::workspace1< WORK > work ) {
        namespace bindings = ::boost::numeric::bindings;
        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixZ >::value) );
        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<
                typename bindings::value_type< VectorD >::type >::type,
                typename remove_const< typename bindings::value_type<
                VectorE >::type >::type >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorD >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorE >::value) );
        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixZ >::value) );
        BOOST_ASSERT( bindings::size(d) >= 0 );
        BOOST_ASSERT( bindings::size(e) >= bindings::size(d)-1 );
        BOOST_ASSERT( bindings::size(work.select(real_type())) >=
                min_size_work( bindings::size(d), compz ));
        BOOST_ASSERT( bindings::size_minor(z) == 1 ||
                bindings::stride_minor(z) == 1 );
        BOOST_ASSERT( compz == 'N' || compz == 'V' || compz == 'I' );
        return detail::steqr( compz, bindings::size(d),
                bindings::begin_value(d), bindings::begin_value(e),
                bindings::begin_value(z), bindings::stride_major(z),
                bindings::begin_value(work.select(real_type())) );
    }

    //
    // Static member function that
    // * Figures out the minimal workspace requirements, and passes
    //   the results to the user-defined workspace overload of the
    //   invoke static member function
    // * Enables the unblocked algorithm (BLAS level 2)
    //
    template< typename VectorD, typename VectorE, typename MatrixZ >
    static std::ptrdiff_t invoke( const char compz, VectorD& d, VectorE& e,
            MatrixZ& z, minimal_workspace ) {
        namespace bindings = ::boost::numeric::bindings;
        bindings::detail::array< real_type > tmp_work( min_size_work(
                bindings::size(d), compz ) );
        return invoke( compz, d, e, z, workspace( tmp_work ) );
    }

    //
    // Static member function that
    // * Figures out the optimal workspace requirements, and passes
    //   the results to the user-defined workspace overload of the
    //   invoke static member
    // * Enables the blocked algorithm (BLAS level 3)
    //
    template< typename VectorD, typename VectorE, typename MatrixZ >
    static std::ptrdiff_t invoke( const char compz, VectorD& d, VectorE& e,
            MatrixZ& z, optimal_workspace ) {
        namespace bindings = ::boost::numeric::bindings;
        return invoke( compz, d, e, z, minimal_workspace() );
    }

    //
    // Static member function that returns the minimum size of
    // workspace-array work.
    //
    static std::ptrdiff_t min_size_work( const std::ptrdiff_t n,
            const char compz ) {
        if ( compz == 'N' ) {
            return 1;
        } else {
            return std::max< std::ptrdiff_t >( 1, 2*n-2 );
        }
    }
};

//
// Functions for direct use. These functions are overloaded for temporaries,
// so that wrapped types can still be passed and used for write-access. In
// addition, if applicable, they are overloaded for user-defined workspaces.
// Calls to these functions are passed to the steqr_impl classes. In the
// documentation, most overloads are collapsed to avoid a large number of
// prototypes which are very similar.
//

//
// Overloaded function for steqr. Its overload differs for
// * User-defined workspace
//
template< typename VectorD, typename VectorE, typename MatrixZ,
        typename Workspace >
inline typename boost::enable_if< detail::is_workspace< Workspace >,
        std::ptrdiff_t >::type
steqr( const char compz, VectorD& d, VectorE& e, MatrixZ& z,
        Workspace work ) {
    return steqr_impl< typename bindings::value_type<
            MatrixZ >::type >::invoke( compz, d, e, z, work );
}

//
// Overloaded function for steqr. Its overload differs for
// * Default workspace-type (optimal)
//
template< typename VectorD, typename VectorE, typename MatrixZ >
inline typename boost::disable_if< detail::is_workspace< MatrixZ >,
        std::ptrdiff_t >::type
steqr( const char compz, VectorD& d, VectorE& e, MatrixZ& z ) {
    return steqr_impl< typename bindings::value_type<
            MatrixZ >::type >::invoke( compz, d, e, z, optimal_workspace() );
}

} // namespace lapack
} // namespace bindings
} // namespace numeric
} // namespace boost

#endif


text:
package armapimanagement_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/apimanagement/armapimanagement"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementListGroupUsers.json
func ExampleGroupUserClient_NewListPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armapimanagement.NewGroupUserClient("subid", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListPager("rg1",
		"apimService1",
		"57d2ef278aa04f0888cba3f3",
		&armapimanagement.GroupUserClientListOptions{Filter: nil,
			Top:  nil,
			Skip: nil,
		})
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementHeadGroupUser.json
func ExampleGroupUserClient_CheckEntityExists() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armapimanagement.NewGroupUserClient("subid", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	_, err = client.CheckEntityExists(ctx,
		"rg1",
		"apimService1",
		"59306a29e4bbd510dc24e5f9",
		"5931a75ae4bbd512a88c680b",
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementCreateGroupUser.json
func ExampleGroupUserClient_Create() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armapimanagement.NewGroupUserClient("subid", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	res, err := client.Create(ctx,
		"rg1",
		"apimService1",
		"tempgroup",
		"59307d350af58404d8a26300",
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementDeleteGroupUser.json
func ExampleGroupUserClient_Delete() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armapimanagement.NewGroupUserClient("subid", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	_, err = client.Delete(ctx,
		"rg1",
		"apimService1",
		"templategroup",
		"59307d350af58404d8a26300",
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
}


text:
package io.github.harha.ircd.server;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ServMessage
{

    private String       m_prefix;
    private String       m_command;
    private List<String> m_parameters;

    public ServMessage(String prefix, String command, String... parameters)
    {
        m_prefix = prefix;
        m_command = command;
        m_parameters = new ArrayList<String>(Arrays.asList(parameters));
    }

    public ServMessage(IRCServer server, String command, String... parameters)
    {
        m_prefix = server.getHost().getHostName();
        m_command = command;
        m_parameters = new ArrayList<String>(Arrays.asList(parameters));
    }

    public ServMessage(Connection connection, String command, String... parameters)
    {
        m_prefix = connection.getNick() + "!" + connection.getUser().getUserName() + "@" + connection.getHost().getHostName();
        m_command = command;
        m_parameters = new ArrayList<String>(Arrays.asList(parameters));
    }

    @Override
    public String toString()
    {
        return ((m_prefix.isEmpty() ? "" : ":") + m_prefix + " " + m_command + " " + getParametersAsString()).trim() + "\r\n";
    }

    public String getPrefix()
    {
        return m_prefix;
    }

    public String getCommand()
    {
        return m_command;
    }

    public List<String> getParameters()
    {
        return m_parameters;
    }

    public String getParametersAsString()
    {
        String parameters = "";

        for (String p : m_parameters)
        {
            parameters += (p.contains(" ") && !p.startsWith(":") ? ":" : "") + p + " ";
        }

        return parameters.trim();
    }

}


text:
import {isFunction} from "@vessel/core";
/**
 * Decorator: @validate( <validate function> )
 *
 * Alters the original setter so each time
 * it is invoked it will proceed as follows:
 *
 *  1. Calls the built-in _validate function. This
 *  is a built-in framework function, responsible
 *  for general validation.
 *  2. The _validation function will delegate to
 *  the given validate function
 *  3. If the passed in validate function returns
 *  true it'll execute the setter.
 *  *3b. If the validate function results in false,
 *  The new value will not be setted.
 *
 * @param validationFn
 * @returns descriptor object
 */
export function validate(validationFn) {
    return function(proto, setterName, descriptor) {
        if ( !isFunction(validationFn) ) {
            throw TypeError("The @validate() decorator, " +
                "applied to '" + setterName + "()', requires a " +
                "valid validator function as parameter to be " +
                "passed in.");
        }

        let boundFn = descriptor.value;
        descriptor.value = function setAttribute(value) {
            if ( this._validate(value, validationFn) ) {
                return boundFn.call(this, value);
            }
        };
        return descriptor;
    }
}


text:
module AS
  def self.do_as(str)
    File.open('/tmp/foo.as', 'w') { |f| f.puts(str) }
    result = `osascript /tmp/foo.as`.chomp
    File.unlink('/tmp/foo.as')
    raise "error when executing osascript for '#{str}'" unless $?.success?
    result
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Bubble</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="This is UI for BUBBLE">
  <meta name="author" content="dusteacup">

  <link rel="stylesheet" href="css/bootstrap.css" type="text/css" media="screen" charset="utf-8">

  <link rel="stylesheet" href="css/supersized.core.css" type="text/css" media="screen" />

  <link rel="stylesheet" href="css/bubble.css">

  <link rel="shortcut icon" href="img/favicon.png">

   Bubble Home


text:
using AIWolf.Common.Util;
using System;
using System.IO;

namespace AIWolf.Server.Util
{
    /// <summary>
    /// GameLogger using file.
    /// <para>
    /// Original Java code was written by tori,
    /// and translated into C# by otsuki.
    /// </para>
    /// </summary>
    class FileGameLogger : IGameLogger
    {
        string logFile;
        TextWriter writer;

        public FileGameLogger(string path)
        {
            if (path != null)
            {
                if (Directory.Exists(path))
                {
                    logFile = Path.ChangeExtension(Path.Combine(path, CalendarTools.ToTimeString(DateTime.Now)), ".log");
                }
                else
                {
                    logFile = path;
                }
                Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(logFile)));
                try
                {
                    writer = new StreamWriter(logFile);
                    return;
                }
                catch (IOException e)
                {
                    Console.Error.WriteLine(e.StackTrace);
                    Console.Error.WriteLine("Fail to create logfile. Output log to Console.Out");
                }
            }
            writer = Console.Out;
        }

        public void Close()
        {
            writer.Close();
        }

        public void Flush()
        {
            writer.Flush();
        }

        /// <summary>
        /// Save log.
        /// </summary>
        /// <param name="log"></param>
        public void Log(string log)
        {
            writer.WriteLine(log);
        }
    }
}


text:
package morfologik.speller;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

import morfologik.stemming.Dictionary;

import org.assertj.core.api.Assertions;
import org.junit.BeforeClass;
import org.junit.Test;

public class SpellerTest {
  private static Dictionary dictionary;

  @BeforeClass
  public static void setup() throws Exception {
    final URL url = SpellerTest.class.getResource("slownik.dict");
    dictionary = Dictionary.read(url);
  }

  /*
    @Test
    public void testAbka() throws Exception {
        final Speller spell = new Speller(dictionary, 2);
        System.out.println("Replacements:");
        for (String s : spell.findReplacements("abka")) {
            System.out.println(s);
        }
    }
   */

  @Test
  public void testRunonWords() throws IOException {
    final Speller spell = new Speller(dictionary);
    Assertions.assertThat(spell.replaceRunOnWords("abaka")).isEmpty();
    Assertions.assertThat(spell.replaceRunOnWords("abakaabace")).contains("abaka abace");

    // Test on an morphological dictionary - should work as well
    final URL url1 = getClass().getResource("test-infix.dict");
    final Speller spell1 = new Speller(Dictionary.read(url1));
    assertTrue(spell1.replaceRunOnWords("Rzekunia").isEmpty());
    assertTrue(spell1.replaceRunOnWords("RzekuniaRzeczypospolitej").contains("Rzekunia Rzeczypospolitej"));
    assertTrue(spell1.replaceRunOnWords("RzekuniaRze").isEmpty()); //Rze is not found but is a prefix

    final URL url2 = getClass().getResource("single-char-word.dict");
    final Speller spell2 = new Speller(Dictionary.read(url2));
    assertTrue(spell2.replaceRunOnWords("alot").contains("a lot"));
    assertTrue(spell2.replaceRunOnWords("aalot").contains("aa lot"));
    assertTrue(spell2.replaceRunOnWords("aamusement").contains("a amusement"));
    assertTrue(spell2.replaceRunOnWords("clot").isEmpty());
    assertTrue(spell2.replaceRunOnWords("foobar").isEmpty());
  }

  @Test
  public void testIsInDictionary() throws IOException {
    // Test on an morphological dictionary, including separators
    final URL url1 = getClass().getResource("test-infix.dict");
    final Speller spell1 = new Speller(Dictionary.read(url1));
    assertTrue(spell1.isInDictionary("Rzekunia"));
    assertTrue(!spell1.isInDictionary("Rzekunia+"));
    assertTrue(!spell1.isInDictionary("Rzekunia+aaa"));
    // test UTF-8 dictionary
    final URL url = getClass().getResource("test-utf-spell.dict");
    final Speller spell = new Speller(Dictionary.read(url));
    assertTrue(spell.isInDictionary("jaźń"));
    assertTrue(spell.isInDictionary("zażółć"));
    assertTrue(spell.isInDictionary("żółwiową"));
    assertTrue(spell.isInDictionary("ćwikła"));
    assertTrue(spell.isInDictionary("Żebrowski"));
    assertTrue(spell.isInDictionary("Święto"));
    assertTrue(spell.isInDictionary("Świerczewski"));
    assertTrue(spell.isInDictionary("abc"));
  }

  @Test
  public void testFindReplacements() throws IOException {
    final Speller spell = new Speller(dictionary, 1);
    assertTrue(spell.findReplacements("abka").contains("abak"));
    //check if we get only dictionary words...
    List<String> reps = spell.findReplacements("bak");
    for (final String word: reps) {
      assertTrue(spell.isInDictionary(word));
    }
    assertTrue(spell.findReplacements("abka~~").isEmpty()); // 2 characters more -> edit distance too large
    assertTrue(!spell.findReplacements("Rezkunia").contains("Rzekunia"));

    final URL url1 = getClass().getResource("test-infix.dict");
    final Speller spell1 = new Speller(Dictionary.read(url1));
    assertTrue(spell1.findReplacements("Rezkunia").contains("Rzekunia"));
    //diacritics
    assertTrue(spell1.findReplacements("Rzękunia").contains("Rzekunia"));
    //we should get no candidates for correct words
    assertTrue(spell1.isInDictionary("Rzekunia"));
    assertTrue(spell1.findReplacements("Rzekunia").isEmpty());
    //and no for things that are too different from the dictionary
    assertTrue(spell1.findReplacements("Strefakibica").isEmpty());
    //nothing for nothing
    assertTrue(spell1.findReplacements("").isEmpty());
    //nothing for weird characters
    assertTrue(spell1.findReplacements("\u0000").isEmpty());
    //nothing for other characters
    assertTrue(spell1.findReplacements("«…»").isEmpty());
    //nothing for separator
    assertTrue(spell1.findReplacements("+").isEmpty());

  }

  @Test
  public void testFrequencyNonUTFDictionary() throws IOException {
    final URL url1 = getClass().getResource("test_freq_iso.dict");
    final Speller spell = new Speller(Dictionary.read(url1));
    assertTrue(spell.isInDictionary("a"));
    assertTrue(!spell.isInDictionary("aõh")); //non-encodable in UTF-8
  }

  @Test
  public void testFindReplacementsInUTF() throws IOException {
    final URL url = getClass().getResource("test-utf-spell.dict");
    final Speller spell = new Speller(Dictionary.read(url));
    assertTrue(spell.findReplacements("gęslą").contains("gęślą"));
    assertTrue(spell.findReplacements("ćwikla").contains("ćwikła"));
    assertTrue(spell.findReplacements("Swierczewski").contains("Świerczewski"));
    assertTrue(spell.findReplacements("zółwiową").contains("żółwiową"));
    assertTrue(spell.findReplacements("Żebrowsk").contains("Żebrowski"));
    assertTrue(spell.findReplacements("święto").contains("Święto"));
    //note: no diacritics here, but we still get matches!
    assertTrue(spell.findReplacements("gesla").contains("gęślą"));
    assertTrue(spell.findReplacements("swieto").contains("Święto"));
    assertTrue(spell.findReplacements("zolwiowa").contains("żółwiową"));
    //using equivalent characters 'x' = 'ź'
    assertTrue(spell.findReplacements("jexn").contains("jaźń"));
    // 'u' = 'ó', so the edit distance is still small...
    assertTrue(spell.findReplacements("zażulv").contains("zażółć"));
    // 'rz' = 'ż', so the edit distance is still small, but with string replacements...
    assertTrue(spell.findReplacements("zarzulv").contains("zażółć"));
    assertTrue(spell.findReplacements("Rzebrowski").contains("Żebrowski"));
    assertTrue(spell.findReplacements("rzółw").contains("żółw"));
    assertTrue(spell.findReplacements("Świento").contains("Święto"));
    // avoid mixed-case words as suggestions when using replacements ('rz' = 'ż')
    assertTrue(spell.findReplacements("zArzółć").get(0).equals("zażółć"));
  }

  @Test
  public void testFindReplacementsUsingFrequency() throws IOException {
    final URL url = getClass().getResource("dict-with-freq.dict");
    final Speller spell = new Speller(Dictionary.read(url));

    //check if we get only dictionary words...
    List<String> reps = spell.findReplacements("jist");
    for (final String word: reps) {
      assertTrue(spell.isInDictionary(word));
    }
    // get replacements ordered by frequency
    assertTrue(reps.get(0).equals("just"));
    assertTrue(reps.get(1).equals("list"));
    assertTrue(reps.get(2).equals("fist"));
    assertTrue(reps.get(3).equals("mist"));
    assertTrue(reps.get(4).equals("jest"));
    assertTrue(reps.get(5).equals("dist"));
    assertTrue(reps.get(6).equals("gist"));
  }

  @Test
  public void testConcurrentReplacements() throws IOException {
    final URL url = getClass().getResource("dict-with-freq.dict");
    final Speller spell = new Speller(Dictionary.read(url));
    //only the longest key is selected in replacement pairs
    List<String> reps = spell.getAllReplacements("teached", 0, 0);
    assertTrue(reps.contains("teached"));
    assertTrue(reps.contains("taught"));
    assertTrue(!reps.contains("tgheached"));
  }

  @Test
  public void testIsMisspelled() throws IOException {
    final URL url = getClass().getResource("test-utf-spell.dict");
    final Speller spell = new Speller(Dictionary.read(url));
    assertTrue(!spell.isMisspelled("Paragraf22"));  //ignorujemy liczby
    assertTrue(!spell.isMisspelled("!"));  //ignorujemy znaki przestankowe
    assertTrue(spell.isMisspelled("dziekie"));  //test, czy znajdujemy błąd
    assertTrue(!spell.isMisspelled("SłowozGarbem"));  //ignorujemy słowa w stylu wielbłąda
    assertTrue(!spell.isMisspelled("Ćwikła"));  //i małe litery
    assertTrue(!spell.isMisspelled("TOJESTTEST"));  //i wielkie litery
    final Speller oldStyleSpell = new Speller(dictionary, 1);
    assertTrue(oldStyleSpell.isMisspelled("Paragraf22"));  // nie ignorujemy liczby
    assertTrue(oldStyleSpell.isMisspelled("!"));  //nie ignorujemy znaków przestankowych
    // assertTrue(oldStyleSpell.isMisspelled("SłowozGarbem"));  //ignorujemy słowa w stylu wielbłąda
    assertTrue(oldStyleSpell.isMisspelled("Abaka"));  //i małe litery
    final URL url1 = getClass().getResource("test-infix.dict");
    final Speller spell1 = new Speller(Dictionary.read(url1));
    assertTrue(!spell1.isMisspelled("Rzekunia"));
    assertTrue(spell1.isAllUppercase("RZEKUNIA"));
    assertTrue(spell1.isMisspelled("RZEKUNIAA")); // finds a typo here
    assertTrue(!spell1.isMisspelled("RZEKUNIA")); // but not here
  }

  @Test
  public void testCamelCase() {
    final Speller spell = new Speller(dictionary, 1);
    assertTrue(spell.isCamelCase("CamelCase"));
    assertTrue(!spell.isCamelCase("Camel"));
    assertTrue(!spell.isCamelCase("CAMEL"));
    assertTrue(!spell.isCamelCase("camel"));
    assertTrue(!spell.isCamelCase("cAmel"));
    assertTrue(!spell.isCamelCase("CAmel"));
    assertTrue(!spell.isCamelCase(""));
    assertTrue(!spell.isCamelCase(null));
  }

  @Test
  public void testCapitalizedWord() {
    final Speller spell = new Speller(dictionary, 1);
    assertTrue(spell.isNotCapitalizedWord("CamelCase"));
    assertTrue(!spell.isNotCapitalizedWord("Camel"));
    assertTrue(spell.isNotCapitalizedWord("CAMEL"));
    assertTrue(spell.isNotCapitalizedWord("camel"));
    assertTrue(spell.isNotCapitalizedWord("cAmel"));
    assertTrue(spell.isNotCapitalizedWord("CAmel"));
    assertTrue(spell.isNotCapitalizedWord(""));
  }

  @Test
  public void testGetAllReplacements() throws IOException {
    final URL url = getClass().getResource("test-utf-spell.dict");
    final Speller spell = new Speller(Dictionary.read(url));
    assertTrue(spell.isMisspelled("rzarzerzarzu"));
    assertEquals("[rzarzerzarzu]",
        Arrays.toString(spell.getAllReplacements("rzarzerzarzu", 0, 0).toArray()));
  }

  @Test
  public void testEditDistanceCalculation() throws IOException {
    final Speller spell = new Speller(dictionary, 5);
    //test examples from Oflazer's paper
    assertTrue(getEditDistance(spell, "recoginze", "recognize") == 1);
    assertTrue(getEditDistance(spell, "sailn", "failing") == 3);
    assertTrue(getEditDistance(spell, "abc", "abcd") == 1);
    assertTrue(getEditDistance(spell, "abc", "abcde") == 2);
    //test words from fsa_spell output
    assertTrue(getEditDistance(spell, "abka", "abaka") == 1);
    assertTrue(getEditDistance(spell, "abka", "abakan") == 2);
    assertTrue(getEditDistance(spell, "abka", "abaką") == 2);
    assertTrue(getEditDistance(spell, "abka", "abaki") == 2);
  }

  @Test
  public void testCutOffEditDistance() throws IOException {
    final Speller spell2 = new Speller(dictionary, 2); //note: threshold = 2
    //test cut edit distance - reprter / repo from Oflazer
    assertTrue(getCutOffDistance(spell2, "repo", "reprter") == 1);
    assertTrue(getCutOffDistance(spell2, "reporter", "reporter") == 0);
  }

  @Test
  public void testReplacementsAndDistance2() throws Exception {
    /*File infoFile = new File("/tmp/morfologik.info");
    FileWriter fw1 = new FileWriter(infoFile);
    fw1.write("fsa.dict.separator=+\n");
    fw1.write("fsa.dict.encoding=utf-8\n");
    fw1.write("fsa.dict.speller.replacement-pairs=s ss,t d,R Rh,y ij,ę em,em ę\n");
    fw1.close();

    File inputFile = new File("/tmp/morfologik.txt");
    FileWriter fw2 = new FileWriter(inputFile);
    fw2.write("Mitmuss\n");
    fw2.write("Rhythmus\n");
    fw2.write("Wald\n");
    fw2.write("Band\n");
    fw2.write("ijo\n");
    fw2.write("ijond\n");
    fw2.write("youd\n");
    fw2.write("ijoussud\n");
    fw2.write("ijoussuud\n");
    fw2.write("ijussuud\n");
    fw2.write("ijousod\n");
    fw2.write("ij\n");
    fw2.write("ijo\n");
    fw2.write("Ciarkę\n");
    fw2.write("Czarkę\n");
    fw2.write("Clarke\n");
    fw2.write("Clarkiem\n");
    fw2.write("Clarkom\n");

    fw2.close();

    File dictFile = new File("/tmp/morfologik.dict");
    String[] buildToolOptions =
            {"-i", inputFile.getAbsolutePath(), "-o", dictFile.getAbsolutePath()};
    FSABuildTool.main(buildToolOptions);
    Dictionary dictionary = Dictionary.read(dictFile);
    Speller speller = new Speller(dictionary, 3);*/

    final URL url = getClass().getResource("reps_dist2.dict");
    final Speller speller = new Speller(Dictionary.read(url), 3);

    List<String> reps = speller.findReplacements("Rytmus");
    assertTrue(reps.get(0).equals("Rhythmus"));
    assertTrue(reps.get(1).equals("Mitmuss"));
    reps = speller.findReplacements("Walt");
    assertTrue(reps.get(0).equals("Wald"));
    assertTrue(reps.get(1).equals("Band"));
    reps = speller.findReplacements("yout");
    assertTrue(reps.get(0).equals("youd"));
    assertTrue(reps.get(1).equals("ijond"));
    assertTrue(reps.get(2).equals("ijo"));
    reps = speller.findReplacements("yousut");
    assertTrue(reps.get(0).equals("ijoussud"));
    assertTrue(reps.get(1).equals("ijousod"));
    assertTrue(reps.get(2).equals("ijoussuud"));
    assertTrue(reps.get(3).equals("youd"));
    reps = speller.findReplacements("yo");
    assertTrue(reps.get(0).equals("ijo"));
    assertTrue(reps.get(1).equals("ij"));
    reps = speller.findReplacements("Clarkem");
    assertTrue(reps.get(0).equals("Ciarkę"));
    assertTrue(reps.get(1).equals("Clarke"));
    assertTrue(reps.get(2).equals("Clarkiem"));
    assertTrue(reps.get(3).equals("Clarkom"));
    assertTrue(reps.get(4).equals("Czarkę"));
  }

  private int getCutOffDistance(final Speller spell, final String word, final String candidate) {
    // assuming there is no pair-replacement
    spell.setWordAndCandidate(word, candidate);
    final int [] ced = new int[spell.getCandLen() - spell.getWordLen()];
    for (int i = 0; i < spell.getCandLen() - spell.getWordLen(); i++) {
      ced[i] = spell.cuted(spell.getWordLen() + i, spell.getWordLen() + i, spell.getWordLen() + i);
    }
    Arrays.sort(ced);
    //and the min value...
    if (ced.length > 0) {
      return ced[0];
    }
    return 0;
  }

  private int getEditDistance(final Speller spell, final String word, final String candidate) {
    // assuming there is no pair-replacement
    spell.setWordAndCandidate(word, candidate);
    final int maxDistance = spell.getEffectiveED();
    final int candidateLen = spell.getCandLen();
    final int wordLen = spell.getWordLen();
    int ed = 0;
    for (int i = 0; i < candidateLen; i++) {
      if (spell.cuted(i, i, i) <= maxDistance) {
        if (Math.abs(wordLen - 1 - i) <= maxDistance) {
          ed = spell.ed(wordLen - 1, i, wordLen - 1, i);
        }
      }
    }
    return ed;
  }
}