text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appDevDebugProjectContainerUrlMatcher.
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appDevDebugProjectContainerUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        if (0 === strpos($pathinfo, '/_')) {
            // _wdt
            if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array (  '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
            }

            if (0 === strpos($pathinfo, '/_profiler')) {
                // _profiler_home
                if (rtrim($pathinfo, '/') === '/_profiler') {
                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', '_profiler_home');
                    }

                    return array (  '_controller' => 'web_profiler.controller.profiler:homeAction',  '_route' => '_profiler_home',);
                }

                if (0 === strpos($pathinfo, '/_profiler/search')) {
                    // _profiler_search
                    if ($pathinfo === '/_profiler/search') {
                        return array (  '_controller' => 'web_profiler.controller.profiler:searchAction',  '_route' => '_profiler_search',);
                    }

                    // _profiler_search_bar
                    if ($pathinfo === '/_profiler/search_bar') {
                        return array (  '_controller' => 'web_profiler.controller.profiler:searchBarAction',  '_route' => '_profiler_search_bar',);
                    }

                }

                // _profiler_info
                if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array (  '_controller' => 'web_profiler.controller.profiler:infoAction',));
                }

                // _profiler_phpinfo
                if ($pathinfo === '/_profiler/phpinfo') {
                    return array (  '_controller' => 'web_profiler.controller.profiler:phpinfoAction',  '_route' => '_profiler_phpinfo',);
                }

                // _profiler_search_results
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array (  '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
                }

                // _profiler_open_file
                if ($pathinfo === '/_profiler/open') {
                    return array (  '_controller' => 'web_profiler.controller.profiler:openAction',  '_route' => '_profiler_open_file',);
                }

                // _profiler
                if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array (  '_controller' => 'web_profiler.controller.profiler:panelAction',));
                }

                // _profiler_router
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array (  '_controller' => 'web_profiler.controller.router:panelAction',));
                }

                // _profiler_exception
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array (  '_controller' => 'web_profiler.controller.exception:showAction',));
                }

                // _profiler_exception_css
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array (  '_controller' => 'web_profiler.controller.exception:cssAction',));
                }

            }

            // _twig_error_test
            if (0 === strpos($pathinfo, '/_error') && preg_match('#^/_error/(?P<code>\\d+)(?:\\.(?P<_format>[^/]++))?$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => '_twig_error_test')), array (  '_controller' => 'twig.controller.preview_error:previewErrorPageAction',  '_format' => 'html',));
            }

        }

        if (0 === strpos($pathinfo, '/student')) {
            // just_student_index
            if (rtrim($pathinfo, '/') === '/student') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'just_student_index');
                }

                return array (  '_controller' => 'JustBundle\\Controller\\StudentController::indexAction',  '_route' => 'just_student_index',);
            }

            if (0 === strpos($pathinfo, '/studenttype')) {
                // studenttype_index
                if (rtrim($pathinfo, '/') === '/studenttype') {
                    if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'HEAD'));
                        goto not_studenttype_index;
                    }

                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', 'studenttype_index');
                    }

                    return array (  '_controller' => 'JustBundle\\Controller\\StudentTypeController::indexAction',  '_route' => 'studenttype_index',);
                }
                not_studenttype_index:

                // studenttype_new
                if ($pathinfo === '/studenttype/new') {
                    if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
                        goto not_studenttype_new;
                    }

                    return array (  '_controller' => 'JustBundle\\Controller\\StudentTypeController::newAction',  '_route' => 'studenttype_new',);
                }
                not_studenttype_new:

                // studenttype_show
                if (preg_match('#^/studenttype/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                    if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'HEAD'));
                        goto not_studenttype_show;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'studenttype_show')), array (  '_controller' => 'JustBundle\\Controller\\StudentTypeController::showAction',));
                }
                not_studenttype_show:

                // studenttype_edit
                if (preg_match('#^/studenttype/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
                    if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
                        goto not_studenttype_edit;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'studenttype_edit')), array (  '_controller' => 'JustBundle\\Controller\\StudentTypeController::editAction',));
                }
                not_studenttype_edit:

                // studenttype_delete
                if (preg_match('#^/studenttype/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                    if ($this->context->getMethod() != 'DELETE') {
                        $allow[] = 'DELETE';
                        goto not_studenttype_delete;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'studenttype_delete')), array (  '_controller' => 'JustBundle\\Controller\\StudentTypeController::deleteAction',));
                }
                not_studenttype_delete:

            }

        }

        // bunker_default_index
        if (rtrim($pathinfo, '/') === '') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'bunker_default_index');
            }

            return array (  '_controller' => 'BunkerBundle\\Controller\\DefaultController::indexAction',  '_route' => 'bunker_default_index',);
        }

        if (0 === strpos($pathinfo, '/chevalier')) {
            // chevalier_index
            if (rtrim($pathinfo, '/') === '/chevalier') {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_chevalier_index;
                }

                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'chevalier_index');
                }

                return array (  '_controller' => 'JustBundle\\Controller\\ChevalierController::indexAction',  '_route' => 'chevalier_index',);
            }
            not_chevalier_index:

            // chevalier_new
            if ($pathinfo === '/chevalier/new') {
                if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
                    goto not_chevalier_new;
                }

                return array (  '_controller' => 'JustBundle\\Controller\\ChevalierController::newAction',  '_route' => 'chevalier_new',);
            }
            not_chevalier_new:

            // chevalier_show
            if (preg_match('#^/chevalier/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_chevalier_show;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'chevalier_show')), array (  '_controller' => 'JustBundle\\Controller\\ChevalierController::showAction',));
            }
            not_chevalier_show:

            // chevalier_edit
            if (preg_match('#^/chevalier/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
                    goto not_chevalier_edit;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'chevalier_edit')), array (  '_controller' => 'JustBundle\\Controller\\ChevalierController::editAction',));
            }
            not_chevalier_edit:

            // chevalier_delete
            if (preg_match('#^/chevalier/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                if ($this->context->getMethod() != 'DELETE') {
                    $allow[] = 'DELETE';
                    goto not_chevalier_delete;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'chevalier_delete')), array (  '_controller' => 'JustBundle\\Controller\\ChevalierController::deleteAction',));
            }
            not_chevalier_delete:

        }

        // just_homepage
        if (rtrim($pathinfo, '/') === '') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'just_homepage');
            }

            return array (  '_controller' => 'JustBundle\\Controller\\DefaultController::indexAction',  '_route' => 'just_homepage',);
        }

        if (0 === strpos($pathinfo, '/creaturefantastique')) {
            // app_creaturefantastique_index
            if (rtrim($pathinfo, '/') === '/creaturefantastique') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'app_creaturefantastique_index');
                }

                return array (  '_controller' => 'AppBundle\\Controller\\CreatureFantastiqueController::indexAction',  '_route' => 'app_creaturefantastique_index',);
            }

            // app_creaturefantastique_show
            if (0 === strpos($pathinfo, '/creaturefantastique/show') && preg_match('#^/creaturefantastique/show/(?P<id>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'app_creaturefantastique_show')), array (  '_controller' => 'AppBundle\\Controller\\CreatureFantastiqueController::showAction',));
            }

            // app_creaturefantastique_new
            if ($pathinfo === '/creaturefantastique/new') {
                return array (  '_controller' => 'AppBundle\\Controller\\CreatureFantastiqueController::newAction',  '_route' => 'app_creaturefantastique_new',);
            }

        }

        // homepage
        if (rtrim($pathinfo, '/') === '') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'homepage');
            }

            return array (  '_controller' => 'AppBundle\\Controller\\DefaultController::indexAction',  '_route' => 'homepage',);
        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}


text:
<component name="libraryTable">
  <library name="SBT: org.openrdf.sesame:sesame-repository-sparql:2.7.14:jar">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.openrdf.sesame/sesame-repository-sparql/jars/sesame-repository-sparql-2.7.14.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.openrdf.sesame/sesame-repository-sparql/docs/sesame-repository-sparql-2.7.14-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/org.openrdf.sesame/sesame-repository-sparql/srcs/sesame-repository-sparql-2.7.14-sources.jar!/" />
    </SOURCES>
  </library>
</component>

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace BeanIO.Types
{
    ///
    /// A TypeHandler is used to convert field text into a Java object and vice versa.
    ///
    /// <remarks>
    /// Implementations should be thread-safe if multiple threads may concurrently process the
    /// same stream type.  All included BeanIO type handlers are thread safe.
    /// </remarks>
    public interface ITypeHandler
    {
        ///
        /// Gets the class type supported by this handler.
        ///
        Type TargetType { get; }

        ///
        /// Parses field text into an object.
        ///
        /// <param name="text">The field text to parse, which may be null if the field was not passed in the record</param>
        /// <returns>The parsed object</returns>
        object Parse(string text);

        ///
        /// Formats an object into field text.
        ///
        /// <param name="value">The value to format, which may be null</param>
        /// <returns>The formatted field text, or null to indicate the value is not present</returns>
        string Format(object value);
    }
}


text:
[![Build Status](https://travis-ci.org/Sentenai/solr-query.svg?branch=master)](https://travis-ci.org/Sentenai/solr-query)

# solr-query

A type-safe interface to constructing Solr queries.

See the [documentation](http://sentenai.github.io/solr-query/).


text:
module.exports = {
  description: "",
  ns: "react-material-ui",
  type: "ReactNode",
  dependencies: {
    npm: {
      "material-ui/svg-icons/device/battery-50": require('material-ui/svg-icons/device/battery-50')
    }
  },
  name: "DeviceBattery50",
  ports: {
    input: {},
    output: {
      component: {
        title: "DeviceBattery50",
        type: "Component"
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ParquetSharp.External
{
    public class DecompressorStream
    {
        private int bufferSize;
        protected Decompressor decompressor;
        private InputStream stream;

        public DecompressorStream(InputStream stream, Decompressor decompressor, int bufferSize)
        {
            this.stream = stream;
            this.decompressor = decompressor;
            this.bufferSize = bufferSize;
        }
    }
}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { MaterialModule } from '@angular/material';

import { FilesComponent } from './files.component'

@NgModule({
  imports:      [
      CommonModule,
      MaterialModule
  ],
  declarations: [
      FilesComponent
  ],
  exports:      [ FilesComponent ]
})

export class FilesModule { }


text:
package fr.istic.taa.jaxrs.service;

import fr.istic.taa.jaxrs.domain.BaseEntity;
import fr.istic.taa.jaxrs.repository.BaseRepository;
import org.codehaus.jackson.map.util.BeanUtil;

import java.util.List;
import java.util.Optional;

/**
 * A base service
 * @param <Entity>      Entity represented by the service
 * @param <Repository>  The service repository
 */
public abstract class BaseService<Entity, Repository extends BaseRepository> {

    Repository repository;

    public BaseService(Repository repository) {
        this.repository = repository;
    }

    public List<Entity> findAll(){
        return repository.findAll();
    }

    public Entity findOneById(Long id){
        return (Entity) repository.findOneById(id);
    }

    public void create(Entity entity) {
        repository.persist(entity);
    }

    public void update(Long id, Entity entity) {
        Entity oldEntity = this.findOneById(id);

        repository.persist(oldEntity);
    }

    public void removeOneById(Long id){
        Entity entity = (Entity) repository.findOneById(id);
        repository.remove(entity);
    }
}


text:
using System;
using System.Runtime.InteropServices;
using System.Security;

#endregion

namespace Crystalbyte.Spectre.Projections {
    [SuppressUnmanagedCodeSecurity]
    public static class CefAppCapi {
        [DllImport(CefAssembly.Name, EntryPoint = "cef_execute_process", CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Unicode)]
        public static extern int CefExecuteProcess(IntPtr args, IntPtr application);

        [DllImport(CefAssembly.Name, EntryPoint = "cef_initialize", CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Unicode)]
        public static extern int CefInitialize(IntPtr args, IntPtr settings, IntPtr application);

        [DllImport(CefAssembly.Name, EntryPoint = "cef_shutdown", CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Unicode)]
        public static extern void CefShutdown();

        [DllImport(CefAssembly.Name, EntryPoint = "cef_do_message_loop_work",
            CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
        public static extern void CefDoMessageLoopWork();

        [DllImport(CefAssembly.Name, EntryPoint = "cef_run_message_loop", CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Unicode)]
        public static extern void CefRunMessageLoop();

        [DllImport(CefAssembly.Name, EntryPoint = "cef_quit_message_loop", CallingConvention = CallingConvention.Cdecl,
            CharSet = CharSet.Unicode)]
        public static extern void CefQuitMessageLoop();
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct CefApp {
        public CefBase Base;
        public IntPtr OnBeforeCommandLineProcessing;
        public IntPtr OnRegisterCustomSchemes;
        public IntPtr CefCallbackGetResourceBundleHandler;
        public IntPtr CefCallbackGetBrowserProcessHandler;
        public IntPtr CefCallbackGetRenderProcessHandler;
    }

    [SuppressUnmanagedCodeSecurity]
    public static class CefAppCapiDelegates {
        public delegate void OnBeforeCommandLineProcessingCallback(IntPtr self, IntPtr processType, IntPtr commandLine);

        public delegate void OnRegisterCustomSchemesCallback(IntPtr self, IntPtr registrar);

        public delegate IntPtr GetResourceBundleHandlerCallback(IntPtr self);

        public delegate IntPtr GetBrowserProcessHandlerCallback(IntPtr self);

        public delegate IntPtr GetRenderProcessHandlerCallback(IntPtr self);
    }
}


text:
package org.openfact.subsystem.server.extension;

import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.dmr.ModelNode;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;

/**
 * Remove an auth-server from a organization.
 *
 * @author Stan Silvert ssilvert@redhat.com (C) 2014 Red Hat Inc.
 */
public final class OpenfactSubsystemRemoveHandler extends ReloadRequiredRemoveStepHandler {

    static OpenfactSubsystemRemoveHandler INSTANCE = new OpenfactSubsystemRemoveHandler();

    private OpenfactSubsystemRemoveHandler() {}

    @Override
    protected void performRemove(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
        String deploymentName = ServerUtil.getDeploymentName(operation);
        OpenfactAdapterConfigService.INSTANCE.setWebContext(null);

        if (requiresRuntime(context)) { // don't do this on a domain controller
            addStepToRemoveServerWar(context, deploymentName);
        }

        super.performRemove(context, operation, model);
    }

    private void addStepToRemoveServerWar(OperationContext context, String deploymentName) {
        PathAddress deploymentAddress = PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT, deploymentName));
        ModelNode op = Util.createOperation(REMOVE, deploymentAddress);
        context.addStep(op, getRemoveHandler(context, deploymentAddress), OperationContext.Stage.MODEL);
    }

    private OperationStepHandler getRemoveHandler(OperationContext context, PathAddress address) {
        ImmutableManagementResourceRegistration rootResourceRegistration = context.getRootResourceRegistration();
        return rootResourceRegistration.getOperationHandler(address, REMOVE);
    }
}


text:
<?php

require_once '../header.php';

if (!isset($_SESSION['id_user'])) {
    echo '';
    return;
}

require_once '../constants.php';
require_once '../../Model/UsuarioModel.php';
require_once '../../Objects/Usuario.php';

$error = '';

$id = $_SESSION['id_user'];
$model = new UsuarioModel();
$usuario = $model->getById($id);

?>

          <img src="../../<?php echo $usuario->Foto ?>" alt="" class='logo1'/>

          <a id="Z"class='tabs <?php if($_SESSION["error_pass"]==""){echo " active1";} ?>' href="#z">Información de perfil

          Imagen de perfil

          Editar perfil

          <a id='C' class='tabs <?php if($_SESSION["error_pass"]!=""){echo " active1";} ?>' href="#c">Contraseña

            <form class="formulario" action="" name="muestra" method="post">

                  <input type="text" id="nombre" name="nombre" pattern="^@?(\w){1,50}$" required value='<?php echo $usuario->NombreUsuario; ?>' readonly>
                  Nombre de usuario:

                  <input type="email" id="email" name="email" required value='<?php echo $usuario->Email ?>' readonly>
                  Correo:

                  <input type="radio" name="sexo" id="hombre1" value="<?php echo $usuario->Sexo;?>" checked readonly>
                  <?php echo $usuario->Sexo;?>

            </form>

        <form class='panel' name="form_image" enctype="multipart/form-data" action="../../Controller/Usuario/change-foto.php" method="post">

              <img class="logo-muestra" src="../../<?php echo $usuario->Foto ?>" alt="" />

                <input class="upload" name="uploadedfile" type="file" required/>
                <input id= "img-submit" type="submit" value="Subir archivo" />

        </form>

        <?php include_once 'edit-user/change-info.php' ?>

        <?php include_once 'edit-user/change-password.php' ?>


text:
"""
Proposal Target Operator selects foreground and background roi and assigns label, bbox_transform to them.
"""

import logging
import mxnet as mx
import numpy as np
from distutils.util import strtobool

from ..logger import logger
from vis.rcnn.io.rcnn import sample_rois

class ProposalTargetOperator(mx.operator.CustomOp):
    def __init__(self, num_classes, batch_images, batch_rois, fg_fraction):
        super(ProposalTargetOperator, self).__init__()
        self._num_classes = num_classes
        self._batch_images = batch_images
        self._batch_rois = batch_rois
        self._fg_fraction = fg_fraction

        if logger.level == logging.DEBUG:
            self._count = 0
            self._fg_num = 0
            self._bg_num = 0

    def forward(self, is_train, req, in_data, out_data, aux):
        assert self._batch_rois % self._batch_images == 0, \
            'BATCHIMAGES {} must devide BATCH_ROIS {}'.format(self._batch_images, self._batch_rois)
        rois_per_image = self._batch_rois / self._batch_images
        fg_rois_per_image = np.round(self._fg_fraction * rois_per_image).astype(int)

        all_rois = in_data[0].asnumpy()
        gt_boxes = in_data[1].asnumpy()

        # Include ground-truth boxes in the set of candidate rois
        zeros = np.zeros((gt_boxes.shape[0], 1), dtype=gt_boxes.dtype)
        all_rois = np.vstack((all_rois, np.hstack((zeros, gt_boxes[:, :-1]))))
        # Sanity check: single batch only
        assert np.all(all_rois[:, 0] == 0), 'Only single item batches are supported'

        rois, labels, bbox_targets, bbox_weights = \
            sample_rois(all_rois, fg_rois_per_image, rois_per_image, self._num_classes, gt_boxes=gt_boxes)

        if logger.level == logging.DEBUG:
            logger.debug("labels: %s" % labels)
            logger.debug('num fg: {}'.format((labels > 0).sum()))
            logger.debug('num bg: {}'.format((labels == 0).sum()))
            self._count += 1
            self._fg_num += (labels > 0).sum()
            self._bg_num += (labels == 0).sum()
            logger.debug("self._count: %d" % self._count)
            logger.debug('num fg avg: %d' % (self._fg_num / self._count))
            logger.debug('num bg avg: %d' % (self._bg_num / self._count))
            logger.debug('ratio: %.3f' % (float(self._fg_num) / float(self._bg_num)))

        for ind, val in enumerate([rois, labels, bbox_targets, bbox_weights]):
            self.assign(out_data[ind], req[ind], val)

    def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
        self.assign(in_grad[0], req[0], 0)
        self.assign(in_grad[1], req[1], 0)

@mx.operator.register('proposal_target')
class ProposalTargetProp(mx.operator.CustomOpProp):
    def __init__(self, num_classes, batch_images, batch_rois, fg_fraction='0.25'):
        super(ProposalTargetProp, self).__init__(need_top_grad=False)
        self._num_classes = int(num_classes)
        self._batch_images = int(batch_images)
        self._batch_rois = int(batch_rois)
        self._fg_fraction = float(fg_fraction)

    def list_arguments(self):
        return ['rois', 'gt_boxes']

    def list_outputs(self):
        return ['rois_output', 'label', 'bbox_target', 'bbox_weight']

    def infer_shape(self, in_shape):
        rpn_rois_shape = in_shape[0]
        gt_boxes_shape = in_shape[1]

        output_rois_shape = (self._batch_rois, 5)
        label_shape = (self._batch_rois, )
        bbox_target_shape = (self._batch_rois, self._num_classes * 4)
        bbox_weight_shape = (self._batch_rois, self._num_classes * 4)

        return [rpn_rois_shape, gt_boxes_shape], \
               [output_rois_shape, label_shape, bbox_target_shape, bbox_weight_shape]

    def create_operator(self, ctx, shapes, dtypes):
        return ProposalTargetOperator(self._num_classes, self._batch_images, self._batch_rois, self._fg_fraction)

    def declare_backward_dependency(self, out_grad, in_data, out_data):
        return []


text:
using System.Data.Entity.ModelConfiguration;
using Advertise.DomainClasses.Entities.Companies;

namespace Advertise.DomainClasses.Configurations.Companies
{
    /// <summary>
    /// </summary>
    public class CompanyAttachmentConfig : EntityTypeConfiguration<CompanyAttachment>
    {
        /// <summary>
        /// </summary>
        public CompanyAttachmentConfig()
        {
            Property(attachment => attachment.FileName).IsRequired().HasMaxLength(100);
            Property(attachment => attachment.RowVersion).IsRowVersion();
        }
    }
}


text:
package org.wso2.carbon.identity.entitlement.internal;

import org.wso2.carbon.identity.entitlement.PAPStatusDataHandler;
import org.wso2.carbon.identity.entitlement.dto.PublisherDataHolder;
import org.wso2.carbon.identity.entitlement.pap.EntitlementDataFinderModule;
import org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder;
import org.wso2.carbon.identity.entitlement.pip.PIPExtension;
import org.wso2.carbon.identity.entitlement.pip.PIPResourceFinder;
import org.wso2.carbon.identity.entitlement.policy.collection.PolicyCollection;
import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule;
import org.wso2.carbon.identity.entitlement.policy.publisher.PolicyPublisherModule;
import org.wso2.carbon.identity.entitlement.policy.publisher.PostPublisherModule;
import org.wso2.carbon.identity.entitlement.policy.publisher.PublisherVerificationModule;
import org.wso2.carbon.identity.entitlement.policy.store.PolicyDataStore;
import org.wso2.carbon.identity.entitlement.policy.store.PolicyStoreManageModule;
import org.wso2.carbon.identity.entitlement.policy.version.PolicyVersionManager;

import javax.xml.validation.Schema;
import java.util.*;

/**
 * keeps track of the configuration found in entitlement-config.xml
 */
public class EntitlementConfigHolder {

    /**
     * PIPExtensions will be fired for each and every XACML request - which will give a handle to
     * the incoming request.
     */
    private Map<PIPExtension, Properties> extensions = new HashMap<PIPExtension, Properties>();

    /**
     * This will be fired by CarbonAttributeFinder whenever it finds an attribute supported by this
     * module and missing in the XACML request.
     */
    private Map<PIPAttributeFinder, Properties> designators = new HashMap<PIPAttributeFinder, Properties>();

    /**
     * This will be fired by CarbonResourceFinder whenever it wants to find a descendant or child resource
     * of a given resource
     */
    private Map<PIPResourceFinder, Properties> resourceFinders = new HashMap<PIPResourceFinder, Properties>();

    /**
     * This will be fired by EntitlementDataFinder, whenever it wants to retrieve an attribute values to build the
     * XACML policy
     */
    private Map<EntitlementDataFinderModule, Properties> policyEntitlementDataFinders =
            new HashMap<EntitlementDataFinderModule, Properties>();

    /**
     * Will be fired by PolicyPublisher, whenever it wants to publish a policy
     */
    private Map<PolicyPublisherModule, Properties> policyPublisherModules =
            new HashMap<PolicyPublisherModule, Properties>();

    /**
     * Will be fired by PolicyPublisher, after a policy is published
     */
    private Map<PostPublisherModule, Properties> policyPostPublisherModules =
            new HashMap<PostPublisherModule, Properties>();

    /**
     * Will be fired by PolicyPublisher, before a policy is published
     */
    private Map<PublisherVerificationModule, Properties> publisherVerificationModule =
            new HashMap<PublisherVerificationModule, Properties>();

    /**
     * Will be fired by CarbonPolicyFinder, whenever it wants to find policies
     */
    private Map<PolicyFinderModule, Properties> policyFinderModules =
            new HashMap<PolicyFinderModule, Properties>();

    /**
     * This holds all the policies of entitlement engine
     */
    private Map<PolicyCollection, Properties> policyCollections =
            new HashMap<PolicyCollection, Properties>();

    /**
     * Will be fired by admin services, whenever it wants send notifications
     */
    private Map<PAPStatusDataHandler, Properties> papStatusDataHandlers =
            new HashMap<PAPStatusDataHandler, Properties>();

    /**
     * This holds all the policy storing logic of entitlement engine
     */
    private Map<PolicyStoreManageModule, Properties> policyStore =
            new HashMap<PolicyStoreManageModule, Properties>();

    /**
     * This holds all the policy versioning of PAP
     */
    private Map<PolicyDataStore, Properties> policyDataStore =
            new HashMap<PolicyDataStore, Properties>();

    /**
     * This holds all the policy storing logic of entitlement engine
     */
    private Map<PolicyVersionManager, Properties> policyVersionModule =
            new HashMap<PolicyVersionManager, Properties>();

    /**
     * This holds the policy schema against its version
     */
    private Map<String, Schema> policySchemaMap = new HashMap<String, Schema>();

    /**
     * Holds all caching related configurations
     */
    private Properties engineProperties;

    /**
     * Holds the properties of all modules.
     */
    private Map<String, List<PublisherDataHolder>> modulePropertyHolderMap =
            new HashMap<String, List<PublisherDataHolder>>();

    public Map<PIPExtension, Properties> getExtensions() {
        return extensions;
    }

    public void addExtensions(PIPExtension extension, Properties properties) {
        this.extensions.put(extension, properties);
    }

    public Map<PIPAttributeFinder, Properties> getDesignators() {
        return designators;
    }

    public void addDesignators(PIPAttributeFinder attributeFinder, Properties properties) {
        this.designators.put(attributeFinder, properties);
    }

    public Map<PIPResourceFinder, Properties> getResourceFinders() {
        return resourceFinders;
    }

    public void addResourceFinders(PIPResourceFinder resourceFinder, Properties properties) {
        this.resourceFinders.put(resourceFinder, properties);
    }

    public Map<EntitlementDataFinderModule, Properties> getPolicyEntitlementDataFinders() {
        return policyEntitlementDataFinders;
    }

    public void addPolicyEntitlementDataFinder(EntitlementDataFinderModule metaDataFinderModule,
                                               Properties properties) {
        this.policyEntitlementDataFinders.put(metaDataFinderModule, properties);
    }

    public Properties getEngineProperties() {
        return engineProperties;
    }

    public void setEngineProperties(Properties engineProperties) {
        this.engineProperties = engineProperties;
    }

    public Map<String, Schema> getPolicySchemaMap() {
        return policySchemaMap;
    }

    public void setPolicySchema(String schemaNS, Schema schema) {
        this.policySchemaMap.put(schemaNS, schema);
    }

    public Map<PolicyPublisherModule, Properties> getPolicyPublisherModules() {
        return policyPublisherModules;
    }

    public void addPolicyPublisherModule(PolicyPublisherModule policyPublisherModules,
                                         Properties properties) {
        this.policyPublisherModules.put(policyPublisherModules, properties);
    }

    public List<PublisherDataHolder> getModulePropertyHolders(String type) {
        return modulePropertyHolderMap.get(type);
    }

    public void addModulePropertyHolder(String type, PublisherDataHolder holder) {
        if (this.modulePropertyHolderMap.get(type) == null) {
            List<PublisherDataHolder> holders = new ArrayList<PublisherDataHolder>();
            holders.add(holder);
            this.modulePropertyHolderMap.put(type, holders);
        } else {
            this.modulePropertyHolderMap.get(type).add(holder);
        }
    }

    public Map<PolicyFinderModule, Properties> getPolicyFinderModules() {
        return policyFinderModules;
    }

    public void addPolicyFinderModule(PolicyFinderModule policyFinderModule,
                                      Properties properties) {
        this.policyFinderModules.put(policyFinderModule, properties);
    }

    public Map<PolicyCollection, Properties> getPolicyCollections() {
        return policyCollections;
    }

    public void addPolicyCollection(PolicyCollection collection, Properties properties) {
        this.policyCollections.put(collection, properties);
    }

    public Map<PolicyStoreManageModule, Properties> getPolicyStore() {
        return policyStore;
    }

    public void addPolicyStore(PolicyStoreManageModule policyStoreStore, Properties properties) {
        this.policyStore.put(policyStoreStore, properties);
    }

    public Map<PostPublisherModule, Properties> getPolicyPostPublisherModules() {
        return policyPostPublisherModules;
    }

    public void addPolicyPostPublisherModule(PostPublisherModule postPublisherModule, Properties properties) {
        this.policyPostPublisherModules.put(postPublisherModule, properties);
    }

    public Map<PublisherVerificationModule, Properties> getPublisherVerificationModule() {
        return publisherVerificationModule;
    }

    public void addPublisherVerificationModule(PublisherVerificationModule publisherVerificationModule,
                                               Properties properties) {
        this.publisherVerificationModule.put(publisherVerificationModule, properties);
    }

    public Map<PAPStatusDataHandler, Properties> getPapStatusDataHandlers() {
        return papStatusDataHandlers;
    }

    public void addNotificationHandler(PAPStatusDataHandler notificationHandler,
                                       Properties properties) {
        this.papStatusDataHandlers.put(notificationHandler, properties);
    }

    public Map<PolicyVersionManager, Properties> getPolicyVersionModule() {
        return policyVersionModule;
    }

    public void addPolicyVersionModule(PolicyVersionManager policyVersionModule, Properties properties) {
        this.policyVersionModule.put(policyVersionModule, properties);
    }

    public Map<PolicyDataStore, Properties> getPolicyDataStore() {
        return policyDataStore;
    }

    public void addPolicyDataStore(PolicyDataStore policyDataStore, Properties properties) {
        this.policyDataStore.put(policyDataStore, properties);
    }
}


text:
package br.edu.ifmt.cba.alphalab.entity.laboratorio;

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

import br.edu.ifmt.cba.alphalab.entity.IEntity;
import br.edu.ifmt.cba.alphalab.entity.exception.RequisitoException;
import br.edu.ifmt.cba.alphalab.entity.software.SoftwareEntity;

public class RequisitoEntity implements IEntity<RequisitoException> {

	private Long id;

	private int qtdAlunos;

	private List<SoftwareEntity> softwares;

	public RequisitoEntity() {
	}

	public RequisitoEntity(Long id, int qtdAlunos, List<SoftwareEntity> softwares) {
		super();
		this.id = id;
		this.qtdAlunos = qtdAlunos;
		this.softwares = softwares;
	}

	@Override
	public Long getId() {
		return id;
	}

	@Override
	public RequisitoException validar() {
		StringBuilder msg = new StringBuilder();
		if (qtdAlunos <= 0)
			msg.append("Quantidade de alunos inválida!\n");

		if (msg.length() > 0)
			return new RequisitoException(msg.toString());
		else
			return null;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public int getQtdAlunos() {
		return qtdAlunos;
	}

	public void setQtdAlunos(int qtdAlunos) {
		this.qtdAlunos = qtdAlunos;
	}

	public List<SoftwareEntity> getSoftwares() {
		return softwares;
	}

	public void setSoftwares(List<SoftwareEntity> softwares) {
		this.softwares = softwares;
	}

	@Override
	public String toString() {
		String requisito = this.qtdAlunos + " alunos" + "\n";
		for (SoftwareEntity lista : softwares) {
			requisito = requisito + lista.getDescricao() + "\n";
		}
		return requisito;
	}
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>Project Royale: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Project Royale

powerful software framework for time-of-flight cameras

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

RoyaleDotNet

DepthPoint

RoyaleDotNet.DepthPoint Member List

This is the complete list of members for RoyaleDotNet.DepthPoint, including all inherited members.

depthConfidence	RoyaleDotNet.DepthPoint

grayValue	RoyaleDotNet.DepthPoint

noise	RoyaleDotNet.DepthPoint

x	RoyaleDotNet.DepthPoint

y	RoyaleDotNet.DepthPoint

z	RoyaleDotNet.DepthPoint

<address class="footer">
Generated on Thu Sep 3 2015 17:06:52 for Project Royale by

 1.8.10
</address>


text:
import { fakeState } from "../../__test_support__/fake_state";
import { overwrite, refreshStart, refreshOK, refreshNO } from "../../api/crud";
import {
  SpecialStatus,
  TaggedSequence,
  TaggedDevice,
  ResourceName,
  TaggedResource,
  TaggedTool,
} from "farmbot";
import { buildResourceIndex } from "../../__test_support__/resource_index_builder";
import { GeneralizedError } from "../actions";
import { Actions } from "../../constants";
import { fakeResource } from "../../__test_support__/fake_resource";
import { resourceReducer } from "../reducer";
import { findByUuid } from "../reducer_support";
import { EditResourceParams } from "../../api/interfaces";
import { fakeFolder } from "../../__test_support__/fake_state/resources";

describe("resource reducer", () => {
  it("marks resources as DIRTY when reducing OVERWRITE_RESOURCE", () => {
    const state = fakeState().resources;
    const uuid = Object.keys(state.index.byKind.Sequence)[0];
    const sequence = state.index.references[uuid] as TaggedSequence;
    expect(sequence).toBeTruthy();

    expect(sequence.kind).toBe("Sequence");
    const next = resourceReducer(state, overwrite(sequence, {
      kind: "sequence",
      name: "wow",
      folder_id: undefined,
      args: { version: -0, locals: { kind: "scope_declaration", args: {} } },
      body: [],
      color: "red"
    }));
    const seq2 = next.index.references[uuid] as TaggedSequence;
    expect(seq2.specialStatus).toBe(SpecialStatus.DIRTY);
  });

  it("marks resources as SAVING when reducing REFRESH_RESOURCE_START", () => {
    const state = fakeState().resources;
    const uuid = Object.keys(state.index.byKind.Device)[0];
    const device = state.index.references[uuid] as TaggedDevice;
    expect(device).toBeTruthy();

    expect(device.kind).toBe("Device");
    const afterStart = resourceReducer(state, refreshStart(device.uuid));
    const dev2 = afterStart.index.references[uuid] as TaggedDevice;
    expect(dev2.specialStatus).toBe(SpecialStatus.SAVING);

    // SCENARIO: REFRESH_START ===> REFRESH_OK
    const afterOk = resourceReducer(afterStart, refreshOK(device));
    const dev3 = afterOk.index.references[uuid] as TaggedDevice;
    expect(dev3.specialStatus).toBe(SpecialStatus.SAVED);
    const payl: GeneralizedError = {
      err: "X",
      uuid: dev3.uuid,
      statusBeforeError: SpecialStatus.DIRTY
    };
    // SCENARIO: REFRESH_START ===> REFRESH_NO
    const afterNo =
      resourceReducer(afterStart, refreshNO(payl));
    const dev4 = afterNo.index.references[uuid] as TaggedDevice;
    expect(dev4.specialStatus).toBe(SpecialStatus.SAVED);
  });

  const TEST_RESOURCE_NAMES: TaggedResource["kind"][] = ["Crop", "Device",
    "FarmEvent", "FarmwareInstallation", "FbosConfig",
    "FirmwareConfig", "Log", "Peripheral", "PinBinding", "PlantTemplate",
    "Point", "Regimen", "SavedGarden", "Sensor"];

  it("EDITs a _RESOURCE", () => {
    const startingState = fakeState().resources;
    const { index } = startingState;
    const uuid = Object.keys(index.byKind.Tool)[0];
    const update: Partial<TaggedTool["body"]> = { name: "after" };
    const payload: EditResourceParams = {
      uuid,
      update,
      specialStatus: SpecialStatus.SAVED
    };
    const action = { type: Actions.EDIT_RESOURCE, payload };
    const newState = resourceReducer(startingState, action);
    const oldTool = index.references[uuid] as TaggedTool;
    const newTool = newState.index.references[uuid] as TaggedTool;
    expect(oldTool.body.name).not.toEqual("after");
    expect(newTool.body.name).toEqual("after");
  });

  it("handles resource failures", () => {
    const startingState = fakeState().resources;
    const uuid = Object.keys(startingState.index.byKind.Tool)[0];
    const action = {
      type: Actions._RESOURCE_NO,
      payload: { uuid, err: "Whatever", statusBeforeError: SpecialStatus.DIRTY }
    };
    const newState = resourceReducer(startingState, action);
    const tool = newState.index.references[uuid] as TaggedTool;
    expect(tool.specialStatus).toBe(SpecialStatus.DIRTY);
  });

  it("covers destroy resource branches", () => {
    const testResourceDestroy = (kind: ResourceName) => {

      const state = fakeState().resources;
      const resource = fakeResource(kind as TaggedResource["kind"], {});
      const action = {
        type: Actions.DESTROY_RESOURCE_OK,
        payload: resource
      };
      const newState = resourceReducer(state, action);
      expect(newState.index.references[resource.uuid]).toEqual(undefined);
    };
    TEST_RESOURCE_NAMES
      .concat(["Image", "SensorReading"])
      .map((kind: ResourceName) => testResourceDestroy(kind));
  });

  it("toggles folder open state", () => {
    const folder = fakeFolder();
    folder.body.id = 1;
    const startingState = buildResourceIndex([folder]);
    delete startingState.index.sequenceFolders.localMetaAttributes[1].open;
    const action = { type: Actions.FOLDER_TOGGLE, payload: { id: 1 } };
    const newState = resourceReducer(startingState, action);
    expect(newState.index.sequenceFolders.localMetaAttributes[1].open)
      .toEqual(false);
  });
});

describe("findByUuid", () => {
  it("crashes on bad UUIDs", () => {
    expect(() => findByUuid(buildResourceIndex().index, "Nope!")).toThrow();
  });
});


text:
package security

import (
	. "launchpad.net/gocheck"
	//"testing"
)

// Hook up gocheck into the "go test" runner.
//func Test(t *testing.T) { TestingT(t) }

//type SecuritySuite struct{}
//var _ = Suite(&SecuritySuite{})

type dbBridgeTest func(username string, hash string) (bool, error)

//FIXME Mysql is still waiting for a hash, although etcd use plain password
func testCheck(dbCallback dbBridgeTest, hash string, c *C) {
	username := "xav"
	//FIXME The database is hardcoded in db.go !!
	isOK, err := dbCallback(username, hash)
	c.Assert(err, IsNil)
	c.Check(isOK, Equals, true)

	incorrectHash := hash[2:]
	isOK, err = dbCallback(username, incorrectHash)
	c.Assert(err, IsNil)
	c.Check(isOK, Equals, false)

	incorrectUsername := "CheckNorris"
	isOK, err = dbCallback(incorrectUsername, hash)
	c.Assert(err, NotNil)
	c.Check(isOK, Equals, false)
}

/*
 *func (s *SecuritySuite) TestMysqlCheck(c *C) {
 *    hash := "eGF2OmJvc3M="
 *    testCheck(MysqlCheckCredentials, hash, c)
 *}
 *
 *
 *func (s *SecuritySuite) TestEtcdCheck(c *C) {
 *    hash := "boss"
 *    testCheck(EtcdCheckCredentials, hash, c)
 *}
 */


text:
#ifndef _TEMPLATE_PROJECT_DATA_H_
#define _TEMPLATE_PROJECT_DATA_H_

// Our example data consists of a single tFloat64 value
typedef tFloat64 tTemplateData;

/*
 * Major-type of our template data type.
 *
 * In order to be able to distinguish our data we define custom media type identifiers.
 * Please note that in this example we do not require any additional metadata, so we use
 * an "ordinary" OID_ADTF_MEDIA_TYPE media type with the following major- and subtype. If you want to pass on
 * additional meta data please have a look at the demo_versioned_media_type example.
 */
#define MEDIA_TYPE_TEMPLATE     0x00040677

/*
 * Sub-type of our template data type.
 */
#define MEDIA_SUBTYPE_TEMPLATE  0x00040677

#endif


text:
@interface KYSAlertController()

@property(nonatomic,strong)id alertObject;

@end

@implementation KYSAlertController

+ (instancetype)alertWithType:(UIAlertControllerStyle)type
                        title:(NSString *)title
                      message:(NSString *)message
                 buttonTitles:(NSArray<NSString *> *)buttonTitles
                        block:(KYSAlertControllerActionBlock) block{
    return [[KYSAlertController alloc] initWithType:type title:title message:message buttonTitles:buttonTitles block:block];
}

- (instancetype)initWithType:(UIAlertControllerStyle)type
                       title:(NSString *)title
                     message:(NSString *)message{
    return [self initWithType:type title:title message:message buttonTitles:nil block:nil];
}

- (instancetype)initWithType:(UIAlertControllerStyle)type
                       title:(NSString *)title
                     message:(NSString *)message
                buttonTitles:(NSArray<NSString *> *)buttonTitles
                       block:(KYSAlertControllerActionBlock) block{

    self=[super init];
    if (self) {
        self.actionBlock=block;
        self.alertObject=[UIAlertController alertControllerWithTitle:title message:message preferredStyle:type];
        for (int i=0;i<buttonTitles.count;i++) {
            NSString *buttonTitle = buttonTitles[i];
            __weak typeof(self) wSelf=self;
            UIAlertAction *action=[UIAlertAction actionWithTitle:buttonTitle
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                             wSelf.actionBlock(i,action);
                                                         }];
            [self.alertObject addAction:action];
        }
    }
    return self;
}

- (void)KYSShow{
    [[self p_activityViewController] presentViewController:self.alertObject animated:YES completion:^{

    }];
}

#pragma mark - private
// 获取当前处于activity状态的view controller
- (UIViewController *)p_activityViewController{
    UIViewController* activityViewController = nil;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if(window.windowLevel != UIWindowLevelNormal){
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow *tmpWin in windows){
            if(tmpWin.windowLevel == UIWindowLevelNormal){
                window = tmpWin;
                break;
            }
        }
    }
    NSArray *viewsArray = [window subviews];
    if([viewsArray count] > 0){
        UIView *frontView = [viewsArray objectAtIndex:0];
        id nextResponder = [frontView nextResponder];
        if([nextResponder isKindOfClass:[UIViewController class]]){
            activityViewController = nextResponder;
        }else{
            activityViewController = window.rootViewController;
        }
    }
    return activityViewController;
}

@end


text:
import urllib2
import sys, os
from django.http import HttpResponse

def index(request):

    allowedHosts = ['www.openlayers.org', 'openlayers.org',
                'labs.metacarta.com', 'world.freemap.in',
                'prototype.openmnnd.org', 'geo.openplans.org',
                'sigma.openplans.org', 'demo.opengeo.org',
                'www.openstreetmap.org', 'sample.avencia.com',
                'v-swe.uni-muenster.de:8080', 'local.yahooapis.com',
                'ispatial.t-sciences.com','haiti.sahanafoundation.org','haiti.opensgi.net',
                'haiti.ushahidi.com','ose.petschge.de','openstreetbugs.appspot.com',
                'www.sharedgeo.org', 'hurakan.ucsd.edu', 'www.google.com', 'hurakan.telascience.org']

    if request.POST:
        if "url" in request.POST:
            url = request.POST["url"]
        else:
            url = "http://www.openlayers.org"
    elif 'url' in request.GET:
        url = request.GET['url']
    else:
        return HttpResponse("No url supplied", mimetype="text/plain")

    try:
        host = url.split("/")[2]
        if allowedHosts and not host in allowedHosts:
            content = "Status: 502 Bad Gateway\n"
            content += "Content-Type: text/plain\n"
            content += "\n"
            content += "This proxy does not allow you to access that location (%s)." % (host,)
            return HttpResponse(content, mimetype="text/plain", status=502)

        elif url.startswith("http://") or url.startswith("https://"):
            if request.POST:
                length = request.META["CONTENT_LENGTH"]
                headers = {"Content-Type": request.META["CONTENT_TYPE"]}
                body = request.META['QUERY_STRING']
                r = urllib2.Request(url, body, headers)
                y = urllib2.urlopen(r)
            else:
                y = urllib2.urlopen(url)

            i = y.info()
            if i.has_key("Content-Type"):
                mimetype = i["Content-Type"]
            else:
                mimetype = "text/plain"

            content = y.read()
            y.close()
            return HttpResponse(content, mimetype=mimetype)
        else:
            return HttpResponse("Illegal request.", mimetype="text/plain")

    except Exception, E:
        content = "Some unexpected error occurred. Error text was: %s" % E
        return HttpResponse(content, mimetype="text/plain", status=500)


text:
<?php

use UliCMS\Packages\PatchManager;

class PatchManagerTest extends \PHPUnit\Framework\TestCase
{
    protected function setUp(): void
    {
        for ($i = 1; $i <= 3; $i++) {
            Database::pQuery(
                "insert into {prefix}installed_patches "
                    . "(name, description, url, date) VALUES "
                    . "(?,?,?, NOW())",
                [
                        "patch-$i",
                        "Beschreibung $i",
                        "https://google.de",
                    ],
                true
            );
        }
    }

    protected function tearDown(): void
    {
        $patchManager = new PatchManager();
        $patchManager->truncateInstalledPatches();
    }

    public function testGetInstalledPatches()
    {
        $patchManager = new PatchManager();
        $patches = $patchManager->getInstalledPatches();

        $this->assertIsArray($patches);

        $this->assertCount(3, $patches);

        foreach ($patches as $patch) {
            $this->assertNotEmpty($patch->id);
            $this->assertNotEmpty($patch->name);
            $this->assertNotEmpty($patch->description);
            $this->assertNotEmpty($patch->url);
            $this->assertNotEmpty($patch->date);
        }
    }

    public function testGetAvailablePatches()
    {
        $patchManager = new PatchManager();
        $patches = $patchManager->getAvailablePatches();

        $this->assertIsArray($patches);
        foreach ($patches as $patch) {
            $this->assertNotEmpty($patch->name);
            $this->assertNotEmpty($patch->description);
            $this->assertNotEmpty($patch->url);
            $this->assertNotEmpty($patch->hash);
        }
    }

    public function testFetchpageIndex()
    {
        $patchManager = new PatchManager();
        $this->assertIsString($patchManager->fetchPackageIndex());
    }

    public function testTruncateInstalledPatches()
    {
        $patchManager = new PatchManager();
        $patchManager->truncateInstalledPatches();
        $query = Database::selectAll("installed_patches");
        $this->assertFalse(Database::any($query));
    }

    public function testGetInstalledPatchNames()
    {
        for ($i = 1; $i <= 3; $i++) {
            Database::pQuery(
                "insert into {prefix}installed_patches "
                    . "(name, description, url, date) VALUES "
                    . "(?,?,?, NOW())",
                [
                        "patch-$i",
                        "Beschreibung $i",
                        "https://google.de",
                    ],
                true
            );
        }
        $patchManager = new PatchManager();
        $patches = $patchManager->GetInstalledPatchNames();

        $this->assertIsArray($patches);

        foreach ($patches as $patch) {
            $this->assertNotEmpty($patch);
        }
    }
}


text:
declare namespace _default {
    export const ADDFEATURE: string;
    export const CHANGEFEATURE: string;
    export const CLEAR: string;
    export const REMOVEFEATURE: string;
    export const FEATURESLOADSTART: string;
    export const FEATURESLOADEND: string;
    export const FEATURESLOADERROR: string;
}
export default _default;
export type VectorSourceEventTypes = "clear" | "addfeature" | "removefeature" | "featuresloadstart" | "featuresloadend" | "featuresloaderror";
//# sourceMappingURL=VectorEventType.d.ts.map


text:
chrome.app.runtime.onLaunched.addListener( function() {

  var width = 300;
  var height = 300;
  chrome.app.window.create('login.html', {
    'bounds': {
      width: width,
      height: height,
      left: Math.round((screen.availWidth-width)/2),
      top: Math.round((screen.availHeight-height)/2)
    },
    minWidth: width,
    minHeight: height,
    maxWidth: width,
    maxHeight: height
  });

});


text: Application oriented database.


text:
import math
import numpy as np
from var import n, g, p

class Wurfobjekt:

    def __init__(self, cw, A, m, pos):
        self.cw = cw
        self.A = A
        self.m = m

        self.pos = np.array(pos)
        self.velocity = np.array([0,0])

    def update_velocity(self, force):
        self.velocity = self.velocity + np.array(force) / self.m / n

    def updatePosition(self):
        self.update_velocity(self.drag()+np.array([0, -1 * self.m * g / n]))
        self.pos = self.pos + self.velocity

    def drag(self):
        return np.array(norm(self.velocity) * -1 * 0.5 * self.cw * self.A * p * mag(self.velocity)**2)

    def throw(self, angle, velocity):
        self.velocity = np.array([velocity*math.cos(math.radians(angle)), velocity*math.sin(math.radians(angle))]) / n

def norm(vector):
    if mag(vector) > 0:
        return np.array([x / mag(vector) for x in vector])
    else:
        return np.array(vector)

def mag(vector):
    return math.sqrt(sum([x**2 for x in vector]))


text:
package org.apache.hadoop.hbase.mapreduce;

import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.experimental.categories.Category;

/**
 * Test of simple partitioner.
 */
@Category(SmallTests.class)
public class TestSimpleTotalOrderPartitioner extends HBaseTestCase {
  public void testSplit() throws Exception {
    String start = "a";
    String end = "{";
    SimpleTotalOrderPartitioner<byte []> p =
      new SimpleTotalOrderPartitioner<byte []>();
    this.conf.set(SimpleTotalOrderPartitioner.START, start);
    this.conf.set(SimpleTotalOrderPartitioner.END, end);
    p.setConf(this.conf);
    ImmutableBytesWritable c = new ImmutableBytesWritable(Bytes.toBytes("c"));
    // If one reduce, partition should be 0.
    int partition = p.getPartition(c, HConstants.EMPTY_BYTE_ARRAY, 1);
    assertEquals(0, partition);
    // If two reduces, partition should be 0.
    partition = p.getPartition(c, HConstants.EMPTY_BYTE_ARRAY, 2);
    assertEquals(0, partition);
    // Divide in 3.
    partition = p.getPartition(c, HConstants.EMPTY_BYTE_ARRAY, 3);
    assertEquals(0, partition);
    ImmutableBytesWritable q = new ImmutableBytesWritable(Bytes.toBytes("q"));
    partition = p.getPartition(q, HConstants.EMPTY_BYTE_ARRAY, 2);
    assertEquals(1, partition);
    partition = p.getPartition(q, HConstants.EMPTY_BYTE_ARRAY, 3);
    assertEquals(2, partition);
    // What about end and start keys.
    ImmutableBytesWritable startBytes =
      new ImmutableBytesWritable(Bytes.toBytes(start));
    partition = p.getPartition(startBytes, HConstants.EMPTY_BYTE_ARRAY, 2);
    assertEquals(0, partition);
    partition = p.getPartition(startBytes, HConstants.EMPTY_BYTE_ARRAY, 3);
    assertEquals(0, partition);
    ImmutableBytesWritable endBytes =
      new ImmutableBytesWritable(Bytes.toBytes("z"));
    partition = p.getPartition(endBytes, HConstants.EMPTY_BYTE_ARRAY, 2);
    assertEquals(1, partition);
    partition = p.getPartition(endBytes, HConstants.EMPTY_BYTE_ARRAY, 3);
    assertEquals(2, partition);
  }

}


text:
(function(){
    var app = window.app;
    var config = app('app-config');

    app('process-my-config', function(){
        // define you own code for processing config
        !config.features && (config.features = {});
    });
})();


text:
import deprecationWarning from '../../src/utils/deprecationWarning';

describe('deprecationWarning', () => {
  it('warns exactly once', () => {
    // console.warn has already been stubbed out by test setup.

    deprecationWarning('foo', 'bar');
    expect(console.warn).to.have.been.calledOnce;

    deprecationWarning('foo', 'bar');
    expect(console.warn).to.have.been.calledOnce;

    // Reset the stub to avoid unhandled warnings.
    console.warn.reset();
  });
});


text:
/* global angular, _ */

angular
  .module('scenario', ['ngMockE2E', 'multimocks.responseDelay'])

  .provider('multimocksData', function () {
    var mockData = {},
      mockHeaders = {
        'Content-type': 'application/json'
      },
      defaultScenario = '_default';

    this.setHeaders = function (data) {
      mockHeaders = data;
    };

    this.setMockData = function (data) {
      mockData = data;
    };

    this.addMockData = function (name, data) {
      mockData[name] = data;
    };

    this.setDefaultScenario = function (scenario) {
      defaultScenario = scenario;
    };

    this.$get = function $get() {
      return {
        getMockData: function () {
          return mockData;
        },
        getDefaultScenario: function () {
          return defaultScenario;
        },
        getHeaders: function () {
          return mockHeaders;
        }
      };
    };
  })

  .factory('multimocks', [
    '$q',
    '$http',
    '$httpBackend',
    'multimocksData',
    'scenarioMocks',
    function ($q, $http, $httpBackend, multimocksData, scenarioMocks) {
      var setupHttpBackendForMockResource = function (deferred, mock) {
        var mockHeaders = multimocksData.getHeaders(),
          uriRegExp = new RegExp('^' + mock.uri + '$');

        // Mock a polling resource.
        if (mock.poll) {
          var pollCounter = 0,
              pollCount = _.has(mock, 'pollCount') ? mock.pollCount : 2;

          // Respond with a 204 which will then get polled until a 200 is
          // returned.
          $httpBackend
            .when(mock.httpMethod, uriRegExp, mock.requestData)
            .respond(function () {
              // Call a certain amount of times to simulate polling.
              if (pollCounter < pollCount) {
                pollCounter++;
                return [204, {}, mockHeaders];
              }
              return [200, mock.response, mockHeaders];
            });
        } else {
          $httpBackend
            .when(mock.httpMethod, uriRegExp, mock.requestData)
            .respond(mock.statusCode, mock.response, mockHeaders);
        }

        // Make this HTTP request now if required otherwise just resolve
        // TODO deprecated?
        if (mock.callInSetup) {
          var req = {method: mock.httpMethod, url: mock.uri};
          $http(req).success(function () {
            deferred.resolve();
          });
        } else {
          deferred.resolve();
        }
      };

      return {
        setup: function (scenarioName) {
          var deferred = $q.defer();

          // Set mock for each item.
          _.forOwn(scenarioMocks.getMocks(scenarioName),
            function (mock) {
              setupHttpBackendForMockResource(deferred, mock);
            }
          );

          return deferred.promise;
        }
      };
    }
  ])

  .factory('currentScenario', [
    '$window',
    'multimocksData',
    function ($window, multimocksData) {

      function getScenarioFromPath (path) {
        if (path.indexOf('scenario') !== -1) {
          var scenarioParams = path
            .slice(1)
            .split('&')
            .map(function (s) { return s.split('='); })
            .filter(function (kv) { return kv[0] === 'scenario'; });
          return scenarioParams[0][1];
        } else {
          return undefined;
        }
      }

      return {
        getName: function () {
          var scenarioFromURL = getScenarioFromPath($window.location.search);
          if (_.isUndefined(scenarioFromURL)) {
            return multimocksData.getDefaultScenario();
          }
          return scenarioFromURL;
        }
      };
    }
  ])

  .factory('scenarioMocks', [
    '$log',
    'multimocksData',
    'currentScenario',
    'multimocksLocation',
    function ($log, multimocksData, currentScenario, multimocksLocation) {
      var mockData = multimocksData.getMockData();

      function urlMatchesRegex(url, regex) {
        var pattern = new RegExp(regex);
        return pattern.test(url);
      }

      var scenarioMocks =  {
        getMocks: function (scenarioToLoad) {
          if (_.has(mockData, scenarioToLoad)) {
            return mockData[scenarioToLoad];
          }

          if (scenarioToLoad) {
            $log.log('Mocks not found for scenario: ' + scenarioToLoad);
          }
        },
        getMocksForCurrentScenario: function () {
          return scenarioMocks.getMocks(currentScenario.getName());
        },
        getDelayForResponse: function (response) {
          var globalDelay = multimocksLocation
            .getQueryStringValuesByKey('global_delay');
          if (globalDelay) {
            return parseInt(globalDelay[0]);
          }
          var availableMocks = scenarioMocks.getMocksForCurrentScenario();
          var matchedMockIndex = _.findIndex(availableMocks, function (mock) {
            var sameURL = urlMatchesRegex(response.config.url, mock.uri);
            var sameMethod = (mock.httpMethod === response.config.method);
            return sameMethod && sameURL;
          });
          if (matchedMockIndex < 0) {
            return 0;
          }
          return availableMocks[matchedMockIndex].responseDelay || 0;
        }
      };
      return scenarioMocks;
    }
  ])

  /**
   * Service to interact with the browser location
   */
  .service('multimocksLocation', [
    '$window',
    function ($window) {
      var multimocksLocation = {};

      /**
       * Returns an array of values for a specified query string parameter.
       *
       * Handles multivalued keys and encoded characters.
       *
       * Usage:
       *
       * If the URL is /?foo=bar
       *
       * multimocksLocation.getQueryStringValuesByKey('foo')
       *
       * Will return
       *
       * ['bar']
       *
       * @return Array
       *   An array of values for the specified key.
       */
      multimocksLocation.getQueryStringValuesByKey = function (key) {
        var queryDictionary = {};
        $window.location.search
          .substr(1)
          .split('&')
          .forEach(function (item) {
            var s = item.split('='),
              k = s[0],
              v = s[1] && decodeURIComponent(s[1]);

            if (queryDictionary[k ]) {
              queryDictionary[k].push(v);
            } else {
              queryDictionary[k] = [v];
            }
          });
        return queryDictionary[key];
      };

      return multimocksLocation;
    }])

  .run([
    'multimocks',
    'currentScenario',
    function (multimocks, currentScenario) {
      // load a scenario based on URL string,
      // e.g. http://example.com/?scenario=scenario1
      multimocks.setup(currentScenario.getName());
    }
  ]);

/* global angular */

angular
  .module('multimocks.responseDelay', [])

  .factory('responseDelay', [
    '$q',
    '$timeout',
    'scenarioMocks',
    function ($q, $timeout, scenarioMocks) {
      return {
        response: function (response) {
          var delayedResponse = $q.defer();

          $timeout(function () {
            delayedResponse.resolve(response);
          }, scenarioMocks.getDelayForResponse(response));

          return delayedResponse.promise;
        }
      };
    }
  ])

  .config([
    '$httpProvider',
    function ($httpProvider) {
      $httpProvider.interceptors.push('responseDelay');
    }
  ]);


text:
(function () {

  'use strict';

  angular
  .module('projects')
  .factory('checkProjectStatus', checkProjectStatus);

  checkProjectStatus.$inject = ['$http', 'Authentication'];

  function checkProjectStatus($stateParams, $http, Authentication, $state) {
    return $http.get('api/v1/projects/' + $stateParams.projectId)
    .then(function(project) {
      if (project.data.user._id === Authentication.user._id) {
        return Authentication.user;
      } else {
        $state.go('home');
      }
    }, function (err) {
      return console.error('err: ', err);
    });
  }

  return checkProjectStatus;

}());


text:
var UserFactory = Factories.user,
    PhotoFactory = Factories.photo;

describe('bulk routes', function () {
    /**
     * Calls route to clear DB, then calls callback function
     * @param cb callback function
     */
    function clearAll(cb) {
        server.get(url.format({pathname: '/bulk/clear', query: {password: settings.ADMIN_PASSWORD}})).expect(200, 'DB cleared').end(function (err) {
            if (err) throw err;
            return cb();
        });
    }

    /**
     * Calls bulk upload route to add users to DB, then calls callback function
     * @param users the users to create (see project documentation)
     * @param cb callback function
     */
    function createUsers(users, cb) {
        //Perform bulk upload request
        server.post(url.format({pathname: '/bulk/users', query: {password: settings.ADMIN_PASSWORD}})).send(users)
            .expect(200)
            .end(function (err) {
                if (err) throw err;
                cb();
            });
    }

    /**
     * Calls bulk upload route to add photo to DB, then calls callback function
     * @param photos the photos to create (see project documentation)
     * @param cb callback function
     */
    function createPhotos(photos, cb) {
        //Perform bulk upload request
        server.post(url.format({pathname: '/bulk/streams', query: {password: settings.ADMIN_PASSWORD}})).send(photos)
            .expect(200)
            .end(function (err) {
                if (err) throw err;
                cb();
            });
    }

    describe('clear', function (done) {
        it('refuses request without admin password', function () {
            server.post(url.format({pathname: '/bulk/clear', query: {password: 'notrealpassword'}}))
                .expect(401, done);
        });

        it('deletes all data in the table', function (done) {
            //Create dummy items in DB
            var promise = q.all(
                UserFactory.basic(),
                PhotoFactory.basic()
            );

            promise.then(function () {
                //Perform DB clear
                clearAll(function () {
                    //Ensure databases are empty
                    db.User.count().success(function (userCount) {
                        db.Photo.count().success(function (photoCount) {
                            userCount.should.equal(0);
                            photoCount.should.equal(0);

                            done();
                        });
                    });
                });
            });

        });
    });

    describe('users', function (done) {
        it('refuses request without admin password', function () {
            server.post(url.format({pathname: '/bulk/users', query: {password: 'notrealpassword'}}))
                .expect(401, done);
        });

        it('Creates users given in JSON', function (done) {
            var users = [
                {id: 1, name: 'jill', follows: [2, 3], password: 'test1'},
                {id: 3, name: 'tim', follows: [1, 2], password: 'test3'},
                {id: 2, name: 'alice', follows: [3], password: 'test2'}
            ];

            //Clear DB (required for bulk upload)
            clearAll(function () {
                //Create given users
                createUsers(users, function () {

                    //Ensure test data was created in database
                    db.User.findAll().then(function (users) {
                        users.length.should.equal(3);

                        helpers.md5.hash('test3').should.equal(users[2].password);
                        users[2].fullName.should.equal('tim');
                        users[2].id.should.equal(3);

                        //Ensure each user has to proper amount of followers
                        users[2].getFollowers().then(function (followers) {
                            followers.length.should.equal(2);
                            done();
                        });
                    });
                });
            });
        });
    });

    describe('streams', function () {
        it('refuses request without admin password', function (done) {
            server.post(url.format({pathname: '/bulk/streams', query: {password: 'notrealpassword'}}))
                .expect(401, done);
        });

        it('Creates photos given in JSON', function (done) {
            var users = [
                {id: 1, name: 'jill', follows: [2, 3], password: 'test1'},
                {id: 3, name: 'tim', follows: [1, 2], password: 'test3'},
                {id: 2, name: 'alice', follows: [3], password: 'test2'}
            ];

            var imagePath = system.pathTo('test/unit/fixtures/routes/bulk/image.png'),
                photos = [
                    {id: 1, user_id: 3, path: imagePath, timestamp: 1392403505782},
                    {id: 2, user_id: 2, path: imagePath, timestamp: 1392305505782},
                    {id: 4, user_id: 2, path: imagePath, timestamp: 1392405505781},
                    {id: 5, user_id: 2, path: imagePath, timestamp: 1392405505782},
                    {id: 3, user_id: 1, path: imagePath, timestamp: 1392404505782}
                ];

            //Simulate pre-requisite clear & user creation
            clearAll(function () {
                createUsers(users, function () {
                    //Create test photos
                    createPhotos(photos, function () {
                        //Ensure test data was created in database
                        db.Photo.findAll().then(function (photos) {
                            photos.length.should.equal(5);

                            photos[4].id.should.equal(5);
                            photos[4].imagePath.should.equal(settings.UPLOADS_URL_PATH + '5.png');
                            photos[4].createdAt.should.be.approximately(1392405505782, 1000); //Had to approximate, as the milliseconds are different

                            //Ensure photos were added to users
                            db.User.find(2).then(function (user) {
                                user.getPhotoes().then(function (photos) {
                                    photos.length.should.equal(3);
                                    done();
                                });
                            })
                        });
                    });
                });
            });
        });
    });
});


text:
package org.kuali.rice.kns.web.struts.action;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.exception.RiceRuntimeException;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kim.api.KimConstants;
import org.kuali.rice.kim.api.permission.Permission;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.kns.web.struts.form.BackdoorForm;
import org.kuali.rice.krad.UserSession;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A Struts Action which permits a user to execute a backdoor login to masquerade
 * as another user.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 * @deprecated KNS Struts deprecated, use KRAD and the Spring MVC framework.
 */
@Deprecated
public class BackdoorAction extends KualiAction {

    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BackdoorAction.class);
    private List<Permission> perms;

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        this.initForm(request, form);
        return super.execute(mapping, form, request, response);
    }

    public ActionForward menu(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOG.debug("menu");
        return mapping.findForward("basic");
    }

    @Override
    public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    	return portal(mapping, form, request, response);
    }

    public ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOG.debug("start");
        return portal(mapping, form, request, response);
    }

    public ActionForward portal(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	LOG.debug("portal started");
    	return mapping.findForward("viewPortal");
    }

    public ActionForward administration(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOG.debug("administration");
        return mapping.findForward("administration");
    }

    public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOG.debug("logout");

        String forward = "viewPortal";
        UserSession uSession = getUserSession(request);

        if (uSession.isBackdoorInUse()) {
            uSession.clearBackdoorUser();
            setFormGroupPermission((BackdoorForm)form, request);
            //request.setAttribute("reloadPage","true");

            org.kuali.rice.krad.UserSession KnsUserSession;
            KnsUserSession = GlobalVariables.getUserSession();
            KnsUserSession.clearBackdoorUser();
        }
        else {
            forward = "logout";
        }

        return mapping.findForward(forward);
    }

    public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        LOG.debug("login");
        UserSession uSession = getUserSession(request);
        BackdoorForm backdoorForm = (BackdoorForm) form;

        uSession.clearObjectMap();

        if (!isBackdoorAuthorized(uSession, request)) {
            request.setAttribute("backdoorRestriction", "User " + uSession.getActualPerson().getPrincipalName()
                    + " not permitted to use backdoor functionality inside application: "
                    + ConfigContext.getCurrentContextConfig().getProperty("app.code") + ".");
            return logout(mapping, form, request, response);
        }

        //if backdoor Id is empty or equal to currently logged in user, clear backdoor id
        if (uSession.isBackdoorInUse() &&
                (StringUtils.isEmpty(backdoorForm.getBackdoorId())
                || uSession.getLoggedInUserPrincipalName().equals(backdoorForm.getBackdoorId()))) {
            return logout(mapping, form, request, response);
        }

        try {
        	uSession.setBackdoorUser(backdoorForm.getBackdoorId());
        } catch (RiceRuntimeException e) {
        	LOG.warn("invalid backdoor id " + backdoorForm.getBackdoorId(), e);
            //Commenting this out since it is not being read anywhere
            //request.setAttribute("badbackdoor", "Invalid backdoor Id given '" + backdoorForm.getBackdoorId() + "'");
            return mapping.findForward("invalid_backdoor_portal");
        }

        setFormGroupPermission(backdoorForm, request);

        return mapping.findForward("portal");
    }

    private void setFormGroupPermission(BackdoorForm backdoorForm, HttpServletRequest request) {
    	// based on whether or not they have permission to use the fictional "AdministrationAction", kind of a hack for now since I don't have time to
    	// split this single action up and I can't pass the methodToCall to the permission check
    	Map<String, String> permissionDetails = new HashMap<String, String>();
    	permissionDetails.put(KimConstants.AttributeConstants.NAMESPACE_CODE, KewApiConstants.KEW_NAMESPACE);
    	permissionDetails.put(KimConstants.AttributeConstants.ACTION_CLASS, "org.kuali.rice.kew.web.backdoor.AdministrationAction");
    	boolean isAdmin = KimApiServiceLocator.getPermissionService().isAuthorizedByTemplate(getUserSession(request)
                .getPrincipalId(), KRADConstants.KNS_NAMESPACE, KimConstants.PermissionTemplateNames.USE_SCREEN,
                permissionDetails, new HashMap<String, String>());
        backdoorForm.setIsAdmin(isAdmin);
    }

    public void initForm(HttpServletRequest request, ActionForm form) throws Exception {
    	BackdoorForm backdoorForm = (BackdoorForm) form;

    	Boolean showBackdoorLogin = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsBoolean(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.BACKDOOR_DETAIL_TYPE, KewApiConstants.SHOW_BACK_DOOR_LOGIN_IND);
        backdoorForm.setShowBackdoorLogin(showBackdoorLogin);
        setFormGroupPermission(backdoorForm, request);
        if (backdoorForm.getGraphic() != null) {
        	request.getSession().setAttribute("showGraphic", backdoorForm.getGraphic());
        }
    }

    public static UserSession getUserSession(HttpServletRequest request) {
        return GlobalVariables.getUserSession();
    }

    public boolean isBackdoorAuthorized(UserSession uSession, HttpServletRequest request) {
        boolean isAuthorized = true;

        //we should check to see if a kim permission exists for the requested application first
        Map<String, String> permissionDetails = new HashMap<String, String>();
        String requestAppCode = ConfigContext.getCurrentContextConfig().getProperty("app.code");
        permissionDetails.put(KimConstants.AttributeConstants.APP_CODE, requestAppCode);
        List<Permission> perms = KimApiServiceLocator.getPermissionService().findPermissionsByTemplate(
                KRADConstants.KUALI_RICE_SYSTEM_NAMESPACE, KimConstants.PermissionTemplateNames.BACKDOOR_RESTRICTION);
        for (Permission kpi : perms) {
            if (kpi.getAttributes().values().contains(requestAppCode)) {
                //if a permission exists, is the user granted permission to use backdoor?
                isAuthorized = KimApiServiceLocator.getPermissionService().isAuthorizedByTemplate(
                        uSession.getActualPerson().getPrincipalId(), KRADConstants.KUALI_RICE_SYSTEM_NAMESPACE,
                        KimConstants.PermissionTemplateNames.BACKDOOR_RESTRICTION, permissionDetails,
                        Collections.<String, String>emptyMap());
            }
        }
        if (!isAuthorized) {
            LOG.warn("Attempt to backdoor was made by user: "
                    + uSession.getPerson().getPrincipalId()
                    + " into application with app code: "
                    + requestAppCode
                    + " but they do not have appropriate permissions. Backdoor processing aborted.");
        }
        return isAuthorized;
    }
}


text:
<?php
namespace MangoPay\Libraries;

/**
 * Authentication manager
 */
class ApiOAuth extends ApiBase
{
    /**
     * Get token information to OAuth Authentication
     * @return \MangoPay\Libraries\OAuthToken OAuthToken object with token information
     */
    public function CreateToken()
    {
        $urlMethod = $this->GetRequestUrl('authentication_oauth');
        $requestType = $this->GetRequestType('authentication_oauth');
        $requestData = array(
            'grant_type' => 'client_credentials'
        );

        $rest = new RestTool(false, $this->_root);
        $authHlp = new AuthenticationHelper($this->_root);

        $urlDetails = parse_url($this->_root->Config->BaseUrl);
        $rest->AddRequestHttpHeader('Host: ' . @$urlDetails['host']);
        $rest->AddRequestHttpHeader('Authorization: Basic ' . $authHlp->GetHttpHeaderBasicKey());
        $rest->AddRequestHttpHeader('Content-Type: application/x-www-form-urlencoded');
        $response = $rest->Request($urlMethod, $requestType, $requestData);
        return $this->CastResponseToEntity($response, '\MangoPay\Libraries\OAuthToken');
    }
}


text:
FOUNDATION_EXPORT double CAAnimationBlocksVersionNumber;
FOUNDATION_EXPORT const unsigned char CAAnimationBlocksVersionString[];


text:
import * as types from '../actions/actionTypes';
import initialState from './initialState';

/**
 * Users Reducer
 * @desc Handles Authentication Action
 * @param {object} state the user information
 * @param {function} action the action to check
 * @returns {any} any
 */
export default function document(state = initialState.documents, action) {
  switch (action.type) {
    case types.ADD_NEW_DOCUMENT:
      return Object.assign(
        {},
        state,
        {
          private: state.private.concat(
            [action.document]
          )
        }
      );

    case types.UPDATE_EXISTING_DOCUMENT: {
      const filteredDocuments = state.current.data.filter(
        updatedDocument => updatedDocument.id !== action.updatedDocument.id
      );
      return Object.assign(
        {},
        state,
        {
          current: {
            data: [action.updatedDocument, ...filteredDocuments],
            pagination: state.current.pagination
          }
        }
      );
    }

    case types.DELETE_EXISTING_DOCUMENT: {
      const filteredDocuments = state.current.data.filter(
        deletedDocument => deletedDocument.id !== parseInt(action.id, 10)
      );
      const total = state.current.pagination.total - 1;
      const pagination = Object.assign({}, state.current.pagination, { total });
      return Object.assign(
        {},
        state,
        {
          current: {
            data: filteredDocuments,
            pagination
          }
        }
      );
    }

    case types.GET_DOCUMENT_DETAILS:
      return Object.assign(
        {},
        state,
        {
          currentDocument: action.document
        }
      );

    case types.GET_CURRENT_DOCUMENTS:
      return Object.assign(
        {},
        state,
        {
          current: action.documents
        }
      );

    case types.SEARCH_FOR_DOCUMENTS: {
      return Object.assign(
        {},
        state,
        {
          current: action.documents
        }
      );
    }

    case types.GET_PUBLIC_DOCUMENTS:
      return Object.assign(
        {},
        state,
        {
          public: action.documents
        }
      );

    case types.GET_PRIVATE_DOCUMENTS:
      return Object.assign(
        {},
        state,
        {
          private: action.documents
        }
      );

    case types.GET_ROLE_DOCUMENTS:
      return Object.assign(
        {},
        state,
        {
          role: action.documents
        }
      );

    default:
      return state;
  }
}


text:
const rnpmPlugin = require('rnpm-plugin-windows');

module.exports = [
  rnpmPlugin[1] // WPF
]


text:
import curses.ascii

class EditField:

    """Single line edit field.

    Returns content on Enter, None on cancel (Escape).

    Does not touch attributes, does not care about win size.
    Does not touch area behind current cursor pos + width.
    Clears the touched are when done.

    """

    def __init__(self, win, width=0):
        """Assign the field to `win`, allowing at max `width` chars.

        Zero width allows to uses all space up to the end of window.

        """
        # Compute width
        _, w = win.getmaxyx()
        by, bx = win.getbegyx()
        y, x = win.getyx()
        self.width = width or w - x
        # Create new window for edit box
        self.win = curses.newwin(1, width, by + y, bx + x)
        self.win.keypad(1)
        # Edited text is split to left and right part
        self.left = ''  # Text on left side of the cursor
        self.right = ''  # Text on right side of the cursor

    def edit(self):
        """Run edit loop, return the content."""
        while True:
            wc = self.win.get_wch()
            res = self.process_input(wc)
            if res == 'enter':
                return self.left + self.right
            if res == 'escape':
                return None
            self.draw()

    def draw(self):
        """Draw current content, move cursor to current position."""
        left, right = self.left, self.right
        # If whole content cannot fit, clip it
        while len(left) + len(right) > self.width - 1:
            if len(left) > self.width // 2:
                left = left[1:]
            else:
                right = right[:-1]
        if left != self.left:
            left = '<' + left[1:]
        if right != self.right:
            right = right[:-1] + '>'
        # Draw the (possibly clipped) content
        self.win.move(0, 0)
        self.win.addnstr(left, self.width)
        _, curs_x = self.win.getyx()
        self.win.addnstr(right, self.width - curs_x)
        _, end_x = self.win.getyx()
        self.win.hline(' ', self.width - end_x)
        self.win.move(0, curs_x)
        self.win.refresh()

    def process_input(self, wc):
        """Process character obtained from get_wch().

        Returns None if not resolved, or string with resolution type:

        * 'enter' - input finished, text is valid
        * 'escape' - input canceled, text is invalid

        """
        if wc == chr(curses.ascii.ESC):
            return 'escape'
        elif wc == curses.KEY_LEFT:
            self.right = self.left[-1:] + self.right
            self.left = self.left[:-1]
        elif wc == curses.KEY_RIGHT:
            self.left = self.left + self.right[:1]
            self.right = self.right[1:]
        elif wc == curses.KEY_HOME:
            self.right = self.left + self.right
            self.left = ''
        elif wc == curses.KEY_END:
            self.left = self.left + self.right
            self.right = ''
        elif wc == curses.KEY_BACKSPACE or wc == chr(curses.ascii.BS):
            self.left = self.left[:-1]
        elif wc == curses.KEY_DC or wc == chr(curses.ascii.DEL):
            self.right = self.right[1:]
        elif wc == chr(curses.ascii.NL):
            return 'enter'
        elif isinstance(wc, str):
            self.left += wc

if __name__ == '__main__':
    # Demo
    def curses_main(stdscr):
        w = 20
        stdscr.move(9, 10)
        stdscr.hline('-', w)
        stdscr.move(11, 10)
        stdscr.hline('-', w)
        stdscr.move(10, 10)
        stdscr.refresh()
        field = EditField(stdscr, w)
        return field.edit()
    result = curses.wrapper(curses_main)
    print(result)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BaseFragment</title>
<meta name="date" content="2014-10-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

org.kymjs.aframe.ui.fragment

类 BaseFragment

java.lang.Object

Fragment

org.kymjs.aframe.ui.fragment.KJFrameFragment

org.kymjs.aframe.ui.fragment.BaseFragment

直接已知子类:

ChoiceImageTemplate

public abstract class BaseFragment
extends KJFrameFragment

Application's base Fragment,you should inherit it for your Fragment

 创建时间 2014-5-28

版本:

1.0

作者:

kymjs(kymjs123@gmail.com)

构造器概要

构造器

构造器和说明

BaseFragment()

方法概要

All Methods Instance Methods Concrete Methods

限定符和类型
方法和说明

void
onCreate(Bundle savedInstanceState)

print Fragment callback methods

void
onDestroyView()

void
onPause()

void
onResume()

void
onStop()

从类继承的方法 org.kymjs.aframe.ui.fragment.KJFrameFragment

inflaterView, initData, initDataFromThread, initWidget, onClick, onCreateView, threadDataInited, widgetClick

从类继承的方法 java.lang.Object

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

构造器详细资料

BaseFragment

public BaseFragment()

方法详细资料

onCreate

public void onCreate(Bundle savedInstanceState)

print Fragment callback methods

onResume

public void onResume()

onPause

public void onPause()

onStop

public void onStop()

onDestroyView

public void onDestroyView()

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法