text:
import os
import json
import logging
from functools import wraps

import six

from six.moves import urllib

from st2client.utils import httpclient

LOG = logging.getLogger(__name__)

def add_auth_token_to_kwargs_from_env(func):
    @wraps(func)
    def decorate(*args, **kwargs):
        if not kwargs.get('token') and os.environ.get('ST2_AUTH_TOKEN', None):
            kwargs['token'] = os.environ.get('ST2_AUTH_TOKEN')
        if not kwargs.get('api_key') and os.environ.get('ST2_API_KEY', None):
            kwargs['api_key'] = os.environ.get('ST2_API_KEY')

        return func(*args, **kwargs)
    return decorate

class Resource(object):

    # An alias to use for the resource if different than the class name.
    _alias = None

    # Display name of the resource. This may be different than its resource
    # name specifically when the resource name is composed of multiple words.
    _display_name = None

    # URL path for the resource.
    _url_path = None

    # Plural form of the resource name. This will be used to build the
    # latter part of the REST URL.
    _plural = None

    # Plural form of the resource display name.
    _plural_display_name = None

    # A list of class attributes which will be included in __repr__ return value
    _repr_attributes = []

    def __init__(self, *args, **kwargs):
        for k, v in six.iteritems(kwargs):
            setattr(self, k, v)

    def to_dict(self, exclude_attributes=None):
        """
        Return a dictionary representation of this object.

        :param exclude_attributes: Optional list of attributes to exclude.
        :type exclude_attributes: ``list``

        :rtype: ``dict``
        """
        exclude_attributes = exclude_attributes or []

        attributes = self.__dict__.keys()
        attributes = [attr for attr in attributes if not attr.startswith('__') and
                      attr not in exclude_attributes]

        result = {}
        for attribute in attributes:
            value = getattr(self, attribute, None)
            result[attribute] = value

        return result

    @classmethod
    def get_alias(cls):
        return cls._alias if cls._alias else cls.__name__

    @classmethod
    def get_display_name(cls):
        return cls._display_name if cls._display_name else cls.__name__

    @classmethod
    def get_plural_name(cls):
        if not cls._plural:
            raise Exception('The %s class is missing class attributes '
                            'in its definition.' % cls.__name__)
        return cls._plural

    @classmethod
    def get_plural_display_name(cls):
        return (cls._plural_display_name
                if cls._plural_display_name
                else cls._plural)

    @classmethod
    def get_url_path_name(cls):
        if cls._url_path:
            return cls._url_path

        return cls.get_plural_name().lower()

    def serialize(self):
        return dict((k, v)
                    for k, v in six.iteritems(self.__dict__)
                    if not k.startswith('_'))

    @classmethod
    def deserialize(cls, doc):
        if type(doc) is not dict:
            doc = json.loads(doc)
        return cls(**doc)

    def __str__(self):
        return str(self.__repr__())

    def __repr__(self):
        if not self._repr_attributes:
            return super(Resource, self).__repr__()

        attributes = []
        for attribute in self._repr_attributes:
            value = getattr(self, attribute, None)
            attributes.append('%s=%s' % (attribute, value))

        attributes = ','.join(attributes)
        class_name = self.__class__.__name__
        result = '<%s %s>' % (class_name, attributes)
        return result

class ResourceManager(object):

    def __init__(self, resource, endpoint, cacert=None, debug=False):
        self.resource = resource
        self.debug = debug
        self.client = httpclient.HTTPClient(endpoint, cacert=cacert, debug=debug)

    @staticmethod
    def handle_error(response):
        try:
            content = response.json()
            fault = content.get('faultstring', '') if content else ''
            if fault:
                response.reason += '\nMESSAGE: %s' % fault
        except Exception as e:
            response.reason += ('\nUnable to retrieve detailed message '
                                'from the HTTP response. %s\n' % str(e))
        response.raise_for_status()

    @add_auth_token_to_kwargs_from_env
    def get_all(self, **kwargs):
        # TODO: This is ugly, stop abusing kwargs
        url = '/%s' % self.resource.get_url_path_name()
        limit = kwargs.pop('limit', None)
        pack = kwargs.pop('pack', None)
        prefix = kwargs.pop('prefix', None)
        user = kwargs.pop('user', None)

        params = kwargs.pop('params', {})
        if limit and limit <= 0:
            limit = None
        if limit:
            params['limit'] = limit

        if pack:
            params['pack'] = pack

        if prefix:
            params['prefix'] = prefix

        if user:
            params['user'] = user

        response = self.client.get(url=url, params=params, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        return [self.resource.deserialize(item)
                for item in response.json()]

    @add_auth_token_to_kwargs_from_env
    def get_by_id(self, id, **kwargs):
        url = '/%s/%s' % (self.resource.get_url_path_name(), id)
        response = self.client.get(url, **kwargs)
        if response.status_code == 404:
            return None
        if response.status_code != 200:
            self.handle_error(response)
        return self.resource.deserialize(response.json())

    @add_auth_token_to_kwargs_from_env
    def get_property(self, id_, property_name, self_deserialize=True, **kwargs):
        """
        Gets a property of a Resource.
        id_ : Id of the resource
        property_name: Name of the property
        self_deserialize: #Implies use the deserialize method implemented by this resource.
        """
        token = kwargs.pop('token', None)
        api_key = kwargs.pop('api_key', None)

        if kwargs:
            url = '/%s/%s/%s/?%s' % (self.resource.get_url_path_name(), id_, property_name,
                                     urllib.parse.urlencode(kwargs))
        else:
            url = '/%s/%s/%s/' % (self.resource.get_url_path_name(), id_, property_name)

        if token:
            response = self.client.get(url, token=token)
        elif api_key:
            response = self.client.get(url, api_key=api_key)
        else:
            response = self.client.get(url)

        if response.status_code == 404:
            return None
        if response.status_code != 200:
            self.handle_error(response)

        if self_deserialize:
            return [self.resource.deserialize(item) for item in response.json()]
        else:
            return response.json()

    @add_auth_token_to_kwargs_from_env
    def get_by_ref_or_id(self, ref_or_id, **kwargs):
        return self.get_by_id(id=ref_or_id, **kwargs)

    @add_auth_token_to_kwargs_from_env
    def query(self, **kwargs):
        if not kwargs:
            raise Exception('Query parameter is not provided.')
        if 'limit' in kwargs and kwargs.get('limit') <= 0:
            kwargs.pop('limit')

        token = kwargs.get('token', None)
        api_key = kwargs.get('api_key', None)
        params = kwargs.get('params', {})

        for k, v in six.iteritems(kwargs):
            # Note: That's a special case to support api_key and token kwargs
            if k not in ['token', 'api_key']:
                params[k] = v

        url = '/%s/?%s' % (self.resource.get_url_path_name(),
                           urllib.parse.urlencode(params))

        if token:
            response = self.client.get(url, token=token)
        elif api_key:
            response = self.client.get(url, api_key=api_key)
        else:
            response = self.client.get(url)

        if response.status_code == 404:
            return []
        if response.status_code != 200:
            self.handle_error(response)
        items = response.json()
        instances = [self.resource.deserialize(item) for item in items]
        return instances

    @add_auth_token_to_kwargs_from_env
    def get_by_name(self, name, **kwargs):
        instances = self.query(name=name, **kwargs)
        if not instances:
            return None
        else:
            if len(instances) > 1:
                raise Exception('More than one %s named "%s" are found.' %
                                (self.resource.__name__.lower(), name))
            return instances[0]

    @add_auth_token_to_kwargs_from_env
    def create(self, instance, **kwargs):
        url = '/%s' % self.resource.get_url_path_name()
        response = self.client.post(url, instance.serialize(), **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        instance = self.resource.deserialize(response.json())
        return instance

    @add_auth_token_to_kwargs_from_env
    def update(self, instance, **kwargs):
        url = '/%s/%s' % (self.resource.get_url_path_name(), instance.id)
        response = self.client.put(url, instance.serialize(), **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        instance = self.resource.deserialize(response.json())
        return instance

    @add_auth_token_to_kwargs_from_env
    def delete(self, instance, **kwargs):
        url = '/%s/%s' % (self.resource.get_url_path_name(), instance.id)
        response = self.client.delete(url, **kwargs)

        if response.status_code not in [200, 204, 404]:
            self.handle_error(response)
            return False

        return True

    @add_auth_token_to_kwargs_from_env
    def delete_by_id(self, instance_id, **kwargs):
        url = '/%s/%s' % (self.resource.get_url_path_name(), instance_id)
        response = self.client.delete(url, **kwargs)
        if response.status_code not in [200, 204, 404]:
            self.handle_error(response)
            return False
        try:
            resp_json = response.json()
            if resp_json:
                return resp_json
        except:
            pass
        return True

class ActionAliasResourceManager(ResourceManager):
    def __init__(self, resource, endpoint, cacert=None, debug=False):
        self.resource = resource
        self.debug = debug
        self.client = httpclient.HTTPClient(root=endpoint, cacert=cacert, debug=debug)

    @add_auth_token_to_kwargs_from_env
    def match(self, instance, **kwargs):
        url = '/%s/match' % self.resource.get_url_path_name()
        response = self.client.post(url, instance.serialize(), **kwargs)
        if response.status_code != 201:
            self.handle_error(response)
        matches = response.json()
        if len(matches) > 0:
            return (self.resource.deserialize(matches[0]['actionalias']),
                    matches[0]['representation'])
        else:
            return matches

class LiveActionResourceManager(ResourceManager):
    @add_auth_token_to_kwargs_from_env
    def re_run(self, execution_id, parameters=None, tasks=None, no_reset=None, **kwargs):
        url = '/%s/%s/re_run' % (self.resource.get_url_path_name(), execution_id)

        tasks = tasks or []
        no_reset = no_reset or []

        if list(set(no_reset) - set(tasks)):
            raise ValueError('List of tasks to reset does not match the tasks to rerun.')

        data = {
            'parameters': parameters or {},
            'tasks': tasks,
            'reset': list(set(tasks) - set(no_reset))
        }

        response = self.client.post(url, data, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)

        instance = self.resource.deserialize(response.json())
        return instance

class TriggerInstanceResourceManager(ResourceManager):
    @add_auth_token_to_kwargs_from_env
    def re_emit(self, trigger_instance_id, **kwargs):
        url = '/%s/%s/re_emit' % (self.resource.get_url_path_name(), trigger_instance_id)
        response = self.client.post(url, None, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        return response.json()

class AsyncRequest(Resource):
    pass

class PackResourceManager(ResourceManager):
    @add_auth_token_to_kwargs_from_env
    def install(self, packs, force=False, **kwargs):
        url = '/%s/install' % (self.resource.get_url_path_name())
        payload = {
            'packs': packs,
            'force': force
        }
        response = self.client.post(url, payload, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        instance = AsyncRequest.deserialize(response.json())
        return instance

    @add_auth_token_to_kwargs_from_env
    def remove(self, packs, **kwargs):
        url = '/%s/uninstall' % (self.resource.get_url_path_name())
        response = self.client.post(url, {'packs': packs}, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        instance = AsyncRequest.deserialize(response.json())
        return instance

    @add_auth_token_to_kwargs_from_env
    def search(self, args, **kwargs):
        url = '/%s/index/search' % (self.resource.get_url_path_name())
        if 'query' in vars(args):
            payload = {'query': args.query}
        else:
            payload = {'pack': args.pack}
        response = self.client.post(url, payload, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        data = response.json()
        if isinstance(data, list):
            return [self.resource.deserialize(item) for item in data]
        else:
            return self.resource.deserialize(data) if data else None

    @add_auth_token_to_kwargs_from_env
    def register(self, packs=None, types=None, **kwargs):
        url = '/%s/register' % (self.resource.get_url_path_name())
        payload = {}
        if types:
            payload['types'] = types
        if packs:
            payload['packs'] = packs
        response = self.client.post(url, payload, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        instance = self.resource.deserialize(response.json())
        return instance

class ConfigManager(ResourceManager):
    @add_auth_token_to_kwargs_from_env
    def update(self, instance, **kwargs):
        url = '/%s/%s' % (self.resource.get_url_path_name(), instance.pack)
        response = self.client.put(url, instance.values, **kwargs)
        if response.status_code != 200:
            self.handle_error(response)
        instance = self.resource.deserialize(response.json())
        return instance

class StreamManager(object):
    def __init__(self, endpoint, cacert, debug):
        self._url = httpclient.get_url_without_trailing_slash(endpoint) + '/stream'
        self.debug = debug
        self.cacert = cacert

    @add_auth_token_to_kwargs_from_env
    def listen(self, events, **kwargs):
        # Late import to avoid very expensive in-direct import (~1 second) when this function is
        # not called / used
        from sseclient import SSEClient

        url = self._url

        if 'token' in kwargs:
            url += '?x-auth-token=%s' % kwargs.get('token')

        if 'api_key' in kwargs:
            url += '?st2-api-key=%s' % kwargs.get('api_key')

        if isinstance(events, six.string_types):
            events = [events]

        for message in SSEClient(url):
            if message.event in events:
                yield json.loads(message.data)


text:
package org.kie.remote.command;

import java.io.Serializable;

import org.kie.remote.message.Message;

public interface RemoteCommand extends Message, Serializable {

    boolean isPermittedForReplicas();
}

redpajama_set_name: RedPajamaGithub


text:
package com.podio.sdk.json;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.podio.sdk.domain.notification.CommentNotification;
import com.podio.sdk.domain.notification.GrantNotification;
import com.podio.sdk.domain.notification.Notification;
import com.podio.sdk.domain.notification.ParticipationNotification;
import com.podio.sdk.domain.notification.RatingNotification;
import com.podio.sdk.domain.notification.UnknownNotification;
import com.podio.sdk.domain.notification.VoteNotification;
import com.podio.sdk.internal.DefaultHashMap;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Notifications contains a dynamic "data" part that can have different content depending on the
 * type of notifications so we need to have this deserializer/serializer to decide what kind of
 * notification we are handling.
 *
 */
class NotificationDeserializerSerializer implements JsonDeserializer<Notification>, JsonSerializer<Notification> {

    private Map<Notification.NotificationType, Class<? extends Notification>> mNotificationClassesMap;

    public NotificationDeserializerSerializer() {
        mNotificationClassesMap = new DefaultHashMap<Notification.NotificationType, Class<? extends Notification>>(UnknownNotification.class);
        mNotificationClassesMap.put(Notification.NotificationType.comment, CommentNotification.class);
        mNotificationClassesMap.put(Notification.NotificationType.rating, RatingNotification.class);
        mNotificationClassesMap.put(Notification.NotificationType.participation, ParticipationNotification.class);
        mNotificationClassesMap.put(Notification.NotificationType.vote, VoteNotification.class);
        mNotificationClassesMap.put(Notification.NotificationType.grant_create, GrantNotification.class);
    }

    @Override
    public Notification deserialize(JsonElement element, Type type, JsonDeserializationContext gsonContext) throws JsonParseException {
        if (element == null || element.isJsonNull()) {
            return null;
        }

        JsonObject jsonObject = element.getAsJsonObject();

        Notification.NotificationType notificationType = Notification.NotificationType.getType(jsonObject.get("type").getAsString());

        return gsonContext.deserialize(jsonObject, mNotificationClassesMap.get(notificationType));
    }

    @Override
    public JsonElement serialize(Notification notification, Type typeOfSrc, JsonSerializationContext gsonContext) {
        return gsonContext.serialize(notification, mNotificationClassesMap.get(notification.getType()));
    }
}


text:
import os
from distutils.core import setup

setup(
    name = "hippocampus",
    version = "0.1.0",
    url = 'http://github.com/threadsafelabs/hippocampus',
    license = 'BSD',
    description = "Object-level analytics for Django models",
    author = 'Jonathan Lukens',
    author_email = 'jonathan@threadsafelabs.com',
    packages = ['hippocampus', 'hippocampus.templatetags'],
    classifiers = [
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Framework :: Django',
    ]
)


text:
<?php
namespace PlaygroundCore\Controller\Admin;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
use Laminas\ServiceManager\ServiceLocatorInterface;

class FormgenController extends AbstractActionController
{

    protected $formgenService;
    protected $websiteService;

    /**
     *
     * @var ServiceManager
     */
    protected $serviceLocator;

    public function __construct(ServiceLocatorInterface $locator)
    {
        $this->serviceLocator = $locator;
    }

    public function getServiceLocator()
    {

        return $this->serviceLocator;
    }

    public function indexAction()
    {
        return array();
    }

    public function listAction()
    {
        $mapper = $this->getFormgenService()->getformgenMapper();
        $forms = $mapper->findAll();

        return new ViewModel(array(
            'forms' => $forms,
        ));
    }

    public function generateAction()
    {
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost()->toArray();
            $formGenService = $this->getFormgenService();
            $formGenService->insert($data);
            return $this->redirect()->toRoute('admin/formgen/list');
        }

        $websites = $this->getWebsiteService()->getWebsiteMapper()->findAll();
        return new ViewModel(array(
            'websites' => $websites,
        ));
    }
    public function editAction()
    {
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost()->toArray();
            $formGenService = $this->getFormgenService();
            $formgen = $this->getFormgenService()->getFormgenMapper()->findById($data['formId']);
            $formGenService->update($formgen, $data);

            return $this->redirect()->toRoute('admin/formgen/list');
        }

        $formId = $this->getEvent()->getRouteMatch()->getParam('formId');
        $formgen = $formGenService = $this->getFormgenService()->getFormgenMapper()->findById($formId);

        $websites = $this->getWebsiteService()->getWebsiteMapper()->findAll();
        return new ViewModel(array(
           'websites' => $websites,
           'form' => $formgen,
        ));
    }

    public function activateAction()
    {
        $formId = $this->getEvent()->getRouteMatch()->getParam('formId');
        $formgen = $this->getFormgenService()->getFormgenMapper()->findById($formId);
        $formgen->setActive(!$formgen->getActive());
        $this->getFormgenService()->getFormgenMapper()->update($formgen);

        return $this->redirect()->toRoute('admin/formgen/list');
    }

    public function viewAction()
    {
        $renderer = $this->serviceLocator->get('Laminas\View\Renderer\RendererInterface');
        $headScript = $this->getServiceLocator()->get('ViewHelperManager')->get('HeadScript');
        $headScript->appendFile($renderer->adminAssetPath() . '/js/form/parse.form.js');

        $formId = $this->params('form');

        return array('form_id' => $formId);
    }

    public function createAction()
    {
        $renderer = $this->serviceLocator->get('Laminas\View\Renderer\RendererInterface');
        $headScript = $this->getServiceLocator()->get('ViewHelperManager')->get('HeadScript');
        $headScript->appendFile($renderer->adminAssetPath() . '/js/form/create.form.js');
        $headScript->appendFile($renderer->adminAssetPath() . '/js/form/line.text.js');
        $headScript->appendFile($renderer->adminAssetPath() . '/js/form/add.form.js');
        $headScript->appendFile($renderer->adminAssetPath() . '/js/form/json.form.js');
        $headScript->appendFile($renderer->adminAssetPath() . '/js/form/edit.form.js');

        return array();
    }

    public function inputAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function passwordAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function passwordverifyAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function numberAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function phoneAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function paragraphAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function checkboxAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function radioAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function dropdownAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function emailAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function dateAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function uploadAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function creditcardAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function captchaAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function urlAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function keyAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function hiddenAction()
    {
        $result = $this->getAjax();

        return $result;
    }

    public function getAjax()
    {
        $request = $this->getRequest();
        $results = $request->getQuery();

        $result = new ViewModel(array(
                'result' => $results,
        ));

        $result->setTerminal(true);

        return $result;
    }

    public function getFormgenService()
    {
        if (!$this->formgenService) {
            $this->formgenService = $this->getServiceLocator()->get('playgroundcore_formgen_service');
        }

        return $this->formgenService;
    }

    public function getWebsiteService()
    {
        if (!$this->websiteService) {
            $this->websiteService = $this->getServiceLocator()->get('playgroundcore_website_service');
        }

        return $this->websiteService;
    }

    public function setFormgenService($formgenService)
    {
        $this->formgenService = $formgenService;

        return $this;
    }
}


text:
package de.lessvoid.nifty;

import de.lessvoid.nifty.loaderv2.types.RegisterEffectType;

import javax.annotation.Nonnull;

public class NiftyDefaults {
  private NiftyDefaults() {
  }

  public static void initDefaultEffects(@Nonnull final Nifty nifty) {
    nifty.registerEffect(new RegisterEffectType("alphaHide", "de.lessvoid.nifty.effects.impl.AlphaHide"));
    nifty.registerEffect(new RegisterEffectType("autoScroll", "de.lessvoid.nifty.effects.impl.AutoScroll"));
    nifty.registerEffect(new RegisterEffectType("border", "de.lessvoid.nifty.effects.impl.Border"));
    nifty.registerEffect(new RegisterEffectType("blendMode", "de.lessvoid.nifty.effects.impl.BlendMode"));
    nifty.registerEffect(new RegisterEffectType("changeColor", "de.lessvoid.nifty.effects.impl.ChangeColor"));
    nifty.registerEffect(new RegisterEffectType("changeFont", "de.lessvoid.nifty.effects.impl.ChangeFont"));
    nifty.registerEffect(new RegisterEffectType("changeImage", "de.lessvoid.nifty.effects.impl.ChangeImage"));
    nifty.registerEffect(new RegisterEffectType("changeMouseCursor", "de.lessvoid.nifty.effects.impl.ChangeMouseCursor"));
    nifty.registerEffect(new RegisterEffectType("clip", "de.lessvoid.nifty.effects.impl.Clip"));
    nifty.registerEffect(new RegisterEffectType("colorBar", "de.lessvoid.nifty.effects.impl.ColorBar"));
    nifty.registerEffect(new RegisterEffectType("colorPulsate", "de.lessvoid.nifty.effects.impl.ColorPulsate"));
    nifty.registerEffect(new RegisterEffectType("fade", "de.lessvoid.nifty.effects.impl.Fade"));
    nifty.registerEffect(new RegisterEffectType("fadeSound", "de.lessvoid.nifty.effects.impl.FadeSound"));
    nifty.registerEffect(new RegisterEffectType("fadeMusic", "de.lessvoid.nifty.effects.impl.FadeMusic"));
    nifty.registerEffect(new RegisterEffectType("focus", "de.lessvoid.nifty.effects.impl.Focus"));
    nifty.registerEffect(new RegisterEffectType("followMouse", "de.lessvoid.nifty.effects.impl.FollowMouse"));
    nifty.registerEffect(new RegisterEffectType("gradient", "de.lessvoid.nifty.effects.impl.Gradient"));
    nifty.registerEffect(new RegisterEffectType("hide", "de.lessvoid.nifty.effects.impl.Hide"));
    nifty.registerEffect(new RegisterEffectType("hint", "de.lessvoid.nifty.effects.impl.Hint"));
    nifty.registerEffect(new RegisterEffectType("imageOverlay", "de.lessvoid.nifty.effects.impl.ImageOverlay"));
    nifty.registerEffect(new RegisterEffectType("imageOverlayPulsate", "de.lessvoid.nifty.effects.impl.ImageOverlayPulsate"));
    nifty.registerEffect(new RegisterEffectType("imageSize", "de.lessvoid.nifty.effects.impl.ImageSize"));
    nifty.registerEffect(new RegisterEffectType("imageSizePulsate", "de.lessvoid.nifty.effects.impl.ImageSizePulsate"));
    nifty.registerEffect(new RegisterEffectType("move", "de.lessvoid.nifty.effects.impl.Move"));
    nifty.registerEffect(new RegisterEffectType("nop", "de.lessvoid.nifty.effects.impl.Nop"));
    nifty.registerEffect(new RegisterEffectType("particle", "de.lessvoid.nifty.effects.impl.Particle"));
    nifty.registerEffect(new RegisterEffectType("playMusic", "de.lessvoid.nifty.effects.impl.PlayMusic"));
    nifty.registerEffect(new RegisterEffectType("playSound", "de.lessvoid.nifty.effects.impl.PlaySound"));
    nifty.registerEffect(new RegisterEffectType("pulsate", "de.lessvoid.nifty.effects.impl.Pulsate"));
    nifty.registerEffect(new RegisterEffectType("remote", "de.lessvoid.nifty.effects.impl.Remote"));
    nifty.registerEffect(new RegisterEffectType("renderElement", "de.lessvoid.nifty.effects.impl.RenderElement"));
    nifty.registerEffect(new RegisterEffectType("renderQuad", "de.lessvoid.nifty.effects.impl.RenderQuad"));
    nifty.registerEffect(new RegisterEffectType("restoreState", "de.lessvoid.nifty.effects.impl.RestoreState"));
    nifty.registerEffect(new RegisterEffectType("saveState", "de.lessvoid.nifty.effects.impl.SaveState"));
    nifty.registerEffect(new RegisterEffectType("simpleHint", "de.lessvoid.nifty.effects.impl.SimpleHint"));
    nifty.registerEffect(new RegisterEffectType("shake", "de.lessvoid.nifty.effects.impl.Shake"));
    nifty.registerEffect(new RegisterEffectType("show", "de.lessvoid.nifty.effects.impl.Show"));
    nifty.registerEffect(new RegisterEffectType("textColor", "de.lessvoid.nifty.effects.impl.TextColor"));
    nifty.registerEffect(new RegisterEffectType("textColorAnimated", "de.lessvoid.nifty.effects.impl.TextColorAnimated"));
    nifty.registerEffect(new RegisterEffectType("textSize", "de.lessvoid.nifty.effects.impl.TextSize"));
    nifty.registerEffect(new RegisterEffectType("textSizePulsate", "de.lessvoid.nifty.effects.impl.TextSizePulsate"));
    nifty.registerEffect(new RegisterEffectType("updateScrollpanelPositionToDisplayElement", "de.lessvoid.nifty.controls.scrollbar.UpdateScrollpanelPositionToDisplayElement"));
  }
}


text:
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 *
 */

import ApiClient from '../ApiClient';
import BranchImpllinks from './BranchImpllinks';
import BranchImplpermissions from './BranchImplpermissions';
import PipelineRunImpl from './PipelineRunImpl';
import StringParameterDefinition from './StringParameterDefinition';

/**
 * The BranchImpl model module.
 * @module model/BranchImpl
 * @version 1.5.1-pre.0
 */
class BranchImpl {
    /**
     * Constructs a new BranchImpl.
     * @alias module:model/BranchImpl
     */
    constructor() {

        BranchImpl.initialize(this);
    }

    /**
     * Initializes the fields of this object.
     * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
     * Only for internal use.
     */
    static initialize(obj) {
    }

    /**
     * Constructs a BranchImpl from a plain JavaScript object, optionally creating a new instance.
     * Copies all relevant properties from data to obj if supplied or a new instance if not.
     * @param {Object} data The plain JavaScript object bearing properties of interest.
     * @param {module:model/BranchImpl} obj Optional instance to populate.
     * @return {module:model/BranchImpl} The populated BranchImpl instance.
     */
    static constructFromObject(data, obj) {
        if (data) {
            obj = obj || new BranchImpl();

            if (data.hasOwnProperty('_class')) {
                obj['_class'] = ApiClient.convertToType(data['_class'], 'String');
            }
            if (data.hasOwnProperty('displayName')) {
                obj['displayName'] = ApiClient.convertToType(data['displayName'], 'String');
            }
            if (data.hasOwnProperty('estimatedDurationInMillis')) {
                obj['estimatedDurationInMillis'] = ApiClient.convertToType(data['estimatedDurationInMillis'], 'Number');
            }
            if (data.hasOwnProperty('fullDisplayName')) {
                obj['fullDisplayName'] = ApiClient.convertToType(data['fullDisplayName'], 'String');
            }
            if (data.hasOwnProperty('fullName')) {
                obj['fullName'] = ApiClient.convertToType(data['fullName'], 'String');
            }
            if (data.hasOwnProperty('name')) {
                obj['name'] = ApiClient.convertToType(data['name'], 'String');
            }
            if (data.hasOwnProperty('organization')) {
                obj['organization'] = ApiClient.convertToType(data['organization'], 'String');
            }
            if (data.hasOwnProperty('parameters')) {
                obj['parameters'] = ApiClient.convertToType(data['parameters'], [StringParameterDefinition]);
            }
            if (data.hasOwnProperty('permissions')) {
                obj['permissions'] = BranchImplpermissions.constructFromObject(data['permissions']);
            }
            if (data.hasOwnProperty('weatherScore')) {
                obj['weatherScore'] = ApiClient.convertToType(data['weatherScore'], 'Number');
            }
            if (data.hasOwnProperty('pullRequest')) {
                obj['pullRequest'] = ApiClient.convertToType(data['pullRequest'], 'String');
            }
            if (data.hasOwnProperty('_links')) {
                obj['_links'] = BranchImpllinks.constructFromObject(data['_links']);
            }
            if (data.hasOwnProperty('latestRun')) {
                obj['latestRun'] = PipelineRunImpl.constructFromObject(data['latestRun']);
            }
        }
        return obj;
    }

}

/**
 * @member {String} _class
 */
BranchImpl.prototype['_class'] = undefined;

/**
 * @member {String} displayName
 */
BranchImpl.prototype['displayName'] = undefined;

/**
 * @member {Number} estimatedDurationInMillis
 */
BranchImpl.prototype['estimatedDurationInMillis'] = undefined;

/**
 * @member {String} fullDisplayName
 */
BranchImpl.prototype['fullDisplayName'] = undefined;

/**
 * @member {String} fullName
 */
BranchImpl.prototype['fullName'] = undefined;

/**
 * @member {String} name
 */
BranchImpl.prototype['name'] = undefined;

/**
 * @member {String} organization
 */
BranchImpl.prototype['organization'] = undefined;

/**
 * @member {Array.<module:model/StringParameterDefinition>} parameters
 */
BranchImpl.prototype['parameters'] = undefined;

/**
 * @member {module:model/BranchImplpermissions} permissions
 */
BranchImpl.prototype['permissions'] = undefined;

/**
 * @member {Number} weatherScore
 */
BranchImpl.prototype['weatherScore'] = undefined;

/**
 * @member {String} pullRequest
 */
BranchImpl.prototype['pullRequest'] = undefined;

/**
 * @member {module:model/BranchImpllinks} _links
 */
BranchImpl.prototype['_links'] = undefined;

/**
 * @member {module:model/PipelineRunImpl} latestRun
 */
BranchImpl.prototype['latestRun'] = undefined;

export default BranchImpl;


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

import java.io.IOException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.junit.Test;

public class RestoreSnapshotFromClientCloneTestBase extends RestoreSnapshotFromClientTestBase {

  @Test
  public void testCloneSnapshotOfCloned() throws IOException, InterruptedException {
    TableName clonedTableName =
      TableName.valueOf(getValidMethodName() + "-" + EnvironmentEdgeManager.currentTime());
    admin.cloneSnapshot(snapshotName0, clonedTableName);
    verifyRowCount(TEST_UTIL, clonedTableName, snapshot0Rows);
    SnapshotTestingUtils.verifyReplicasCameOnline(clonedTableName, admin, getNumReplicas());
    admin.disableTable(clonedTableName);
    admin.snapshot(snapshotName2, clonedTableName);
    TEST_UTIL.deleteTable(clonedTableName);
    waitCleanerRun();

    admin.cloneSnapshot(snapshotName2, clonedTableName);
    verifyRowCount(TEST_UTIL, clonedTableName, snapshot0Rows);
    SnapshotTestingUtils.verifyReplicasCameOnline(clonedTableName, admin, getNumReplicas());
    TEST_UTIL.deleteTable(clonedTableName);
  }

  @Test
  public void testCloneAndRestoreSnapshot() throws IOException, InterruptedException {
    TEST_UTIL.deleteTable(tableName);
    waitCleanerRun();

    admin.cloneSnapshot(snapshotName0, tableName);
    verifyRowCount(TEST_UTIL, tableName, snapshot0Rows);
    SnapshotTestingUtils.verifyReplicasCameOnline(tableName, admin, getNumReplicas());
    waitCleanerRun();

    admin.disableTable(tableName);
    admin.restoreSnapshot(snapshotName0);
    admin.enableTable(tableName);
    verifyRowCount(TEST_UTIL, tableName, snapshot0Rows);
    SnapshotTestingUtils.verifyReplicasCameOnline(tableName, admin, getNumReplicas());
  }

  private void waitCleanerRun() throws InterruptedException {
    TEST_UTIL.getMiniHBaseCluster().getMaster().getHFileCleaner().choreForTesting();
  }
}


text:
package org.openhab.binding.elements.handler;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.NotAuthorizedException;

import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.StringType;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.binding.BaseThingHandler;
import org.eclipse.smarthome.core.types.Command;
import org.openhab.binding.elements.ElementsBindingConstants;
import org.openhab.binding.elements.ElementsConfiguration;
import org.openhab.elements.ElementsClient;
import org.openhab.elements.EventType;
import org.openhab.elements.api.cloud.Base;
import org.openhab.elements.api.cloud.Event;
import org.openhab.elements.api.cloud.EventResult;
import org.openhab.elements.api.cloud.Sensor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The {@link ElementsBridgeHandler} is responsible for handling commands, which are
 * sent to one of the channels.
 *
 *
 *
 * @author Harald Kuhn - Initial contribution
 */
public class ElementsBridgeHandler extends BaseThingHandler {

    private ElementsClient client;
    private ElementsDiscoveryService service;
    private String usertoken;

    private Logger logger = LoggerFactory.getLogger(ElementsBridgeHandler.class);

    private Base base;

    private ScheduledFuture<?> baseRefreshJob;
    private ScheduledFuture<?> eventsJob;

    public ElementsBridgeHandler(Thing thing, ElementsDiscoveryService service) {
        super(thing);
        this.service = service;
    }

    private void initBase() {
        Thing bridge = getThing();
        if (bridge != null) {
            ElementsConfiguration config = bridge.getConfiguration().as(ElementsConfiguration.class);
            logger.info("connection to cloud wither user " + config.getUser());

            if (client == null) {
                try {
                    client = new ElementsClient();

                    try {
                        if (usertoken == null) {
                            usertoken = client.getUserToken(config.getUser(), config.getPassword());
                            client.getBase(usertoken);
                        }
                        Base[] bases = client.getBase(usertoken);
                        base = bases[0];
                    } catch (NotAuthorizedException e) {
                        usertoken = client.getUserToken(config.getUser(), config.getPassword());
                        Base[] bases = client.getBase(usertoken);
                        base = bases[0];
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void initialize() {
        super.initialize();
        try {
            initBase();
            if (base != null) {
                String mode = base.getIntrusionSettings().getActiveMode();
                updateState(new ChannelUID(getThing().getUID(), "mode"), new StringType(mode));
                updateStatus(ThingStatus.ONLINE);

                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            initBase();
                            if (base != null) {
                                String mode = base.getIntrusionSettings().getActiveMode();
                                updateState(new ChannelUID(getThing().getUID(), "mode"), new StringType(mode));

                                List<Thing> things = ((Bridge) getThing()).getThings();
                                for (Thing thing : things) {
                                    ((ElementsThingHandler) thing.getHandler()).refreshStatus();
                                }
                            } else {
                                System.err.println("base is null");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                baseRefreshJob = scheduler.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.MINUTES);

                runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            EventResult eventResult = client.getEvents(usertoken);
                            for (Event event : eventResult.getEvents()) {
                                EventType type = EventType.fromString(event.getType());

                                String channel = null;
                                switch (type) {
                                    case OPEN:
                                    case CLOSE:
                                        channel = ElementsBindingConstants.CHANNEL_TYPE_POSITION_STATUS;
                                        break;
                                    case MOVEMENT:
                                        channel = "motion";
                                        break;
                                    case HOMECOMING:
                                        break;
                                    default:
                                        logger.warn("unknown event type " + event.getType() + " " + event);
                                        break;
                                }
                                if (channel != null) {
                                    ThingUID sensor = new ThingUID(ElementsBindingConstants.THING_TYPE_DOOR,
                                            event.getO().getId());
                                    updateState(new ChannelUID(sensor, channel), new StringType(event.getType()));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                eventsJob = scheduler.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS);

            } else {
                updateStatus(ThingStatus.OFFLINE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateStatus(ThingStatus.OFFLINE);
        }

    }

    @Override
    public void dispose() {
        baseRefreshJob.cancel(true);
        eventsJob.cancel(true);
    }

    @Override
    public void handleCommand(ChannelUID channelUID, Command command) {

        if (channelUID.getId().equals("mode")) {
            if (command instanceof StringType) {
                StringType type = (StringType) command;
                try {
                    ElementsConfiguration config = getThing().getConfiguration().as(ElementsConfiguration.class);
                    try {
                        // gej.setMode(gej.getBase(), mode);
                        String usertoken = getThing().getProperties().get("usertoken");
                        if (usertoken == null) {
                            usertoken = client.getUserToken(config.getUser(), config.getPassword());
                            client.setMode(base.getId(), type.toString(), usertoken);
                        }
                        client.setMode(base.getId(), type.toString(), usertoken);
                    } catch (NotAuthorizedException e) {
                        usertoken = client.getUserToken(config.getUser(), config.getPassword());
                        client.setMode(base.getId(), type.toString(), usertoken);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (channelUID.getId().equals("discover")) {
            service.scan();
            updateState(new ChannelUID(getThing().getUID(), "discover"), OnOffType.OFF);
        }
        // Sensor
        logger.debug("########### gigaset channel " + channelUID + " gets command " + command + " ##############");
    }

    public Base getBase() {
        if (base == null) {
            initBase();
        }
        return base;
    }

    public void setBase(Base base) {
        this.base = base;
    }

    public Collection<Sensor> getSensors() {
        return getBase().getSensors();
    }

    public Sensor getSensor(String id) {
        Collection<Sensor> sensors = getSensors();
        if (sensors == null) {
            return null;
        }
        for (Sensor sensor : sensors) {
            if (id != null && id.equalsIgnoreCase(sensor.getId())) {
                return sensor;
            }
        }
        return null;
    }
}


text:
#ifndef MBED_DIGITALOUT_H
#define MBED_DIGITALOUT_H

#include "platform.h"
#include "gpio_api.h"

namespace mbed {

/** A digital output, used for setting the state of a pin
 *
 * Example:
 * @code
 * // Toggle a LED
 * #include "mbed.h"
 *
 * DigitalOut led(LED1);
 *
 * int main() {
 *     while(1) {
 *         led = !led;
 *         wait(0.2);
 *     }
 * }
 * @endcode
 */
class DigitalOut {

public:
    /** Create a DigitalOut connected to the specified pin
     *
     *  @param pin DigitalOut pin to connect to
     */
    DigitalOut(PinName pin) : gpio() {
        gpio_init_out(&gpio, pin);
    }

    /** Create a DigitalOut connected to the specified pin
     *
     *  @param pin DigitalOut pin to connect to
     *  @param value the initial pin value
     */
    DigitalOut(PinName pin, int value) : gpio() {
        gpio_init_out_ex(&gpio, pin, value);
    }

    /** Set the output, specified as 0 or 1 (int)
     *
     *  @param value An integer specifying the pin output value,
     *      0 for logical 0, 1 (or any other non-zero value) for logical 1
     */
    void write(int value) {
        gpio_write(&gpio, value);
    }

    /** Return the output setting, represented as 0 or 1 (int)
     *
     *  @returns
     *    an integer representing the output setting of the pin,
     *    0 for logical 0, 1 for logical 1
     */
    int read() {
        return gpio_read(&gpio);
    }

    /** Return the output setting, represented as 0 or 1 (int)
     *
     *  @returns
     *    Non zero value if pin is connected to uc GPIO
     *    0 if gpio object was initialized with NC
     */
    int is_connected() {
        return gpio_is_connected(&gpio);
    }

#ifdef MBED_OPERATORS
    /** A shorthand for write()
     */
    DigitalOut& operator= (int value) {
        write(value);
        return *this;
    }

    DigitalOut& operator= (DigitalOut& rhs) {
        write(rhs.read());
        return *this;
    }

    /** A shorthand for read()
     */
    operator int() {
        return read();
    }
#endif

protected:
    gpio_t gpio;
};

} // namespace mbed

#endif


text:
using NPOI.SS.Formula.Eval;
using System;
using System.Collections.Generic;
using System.Text;

namespace NPOI.SS.Formula.Functions
{
    public class DollarDe : Fixed2ArgFunction, FreeRefFunction
    {
        public static FreeRefFunction instance = new DollarDe();
        private static Double evaluateValue(ValueEval arg, int srcRowIndex, int srcColumnIndex)
        {
            ValueEval veText = OperandResolver.GetSingleValue(arg, srcRowIndex, srcColumnIndex);
            String strText1 = OperandResolver.CoerceValueToString(veText);
            return OperandResolver.ParseDouble(strText1);
        }
        public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg1, ValueEval arg2)
        {
            try
            {
                Double number1 = evaluateValue(arg1, srcRowIndex, srcColumnIndex);
                if (Double.IsNaN(number1))
                {
                    return ErrorEval.VALUE_INVALID;
                }
                Double number2 = evaluateValue(arg2, srcRowIndex, srcColumnIndex);
                if (Double.IsNaN(number2))
                {
                    return ErrorEval.VALUE_INVALID;
                }
                int fraction = (int)number2;
                if (fraction < 0)
                {
                    return ErrorEval.NUM_ERROR;
                }
                else if (fraction == 0)
                {
                    return ErrorEval.DIV_ZERO;
                }
                int fractionLength = fraction.ToString().Length;

                bool negative = false;
                long valueLong = (long)number1;
                if (valueLong < 0)
                {
                    negative = true;
                    valueLong = -valueLong;
                    number1 = -number1;
                }
                double valueFractional = number1 - valueLong;
                if (valueFractional == 0.0)
                {
                    return new NumberEval(valueLong);
                }
                double inflated = valueFractional * Math.Pow(10, fractionLength);
                double result = inflated / fraction + valueLong;
                if (negative)
                {
                    result = result*-1;
                }
                return new NumberEval(result);
            }
            catch (EvaluationException e)
            {
                return e.GetErrorEval();
            }
        }
        public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec)
        {
            if (args.Length == 2)
            {
                return Evaluate(ec.RowIndex, ec.ColumnIndex, args[0], args[1]);
            }

            return ErrorEval.VALUE_INVALID;
        }
    }
}


text:
extern "C" {
#include <errno.h>
#include <stdint.h>
#include <sys/ebpf.h>

#include "../test_common.hpp"
}

namespace {

class PercpuHashTableMapDeleteTest : public CommonFixture {
 protected:
  struct ebpf_map *em;

  virtual void SetUp() {
    int error;
    uint32_t gkey = 50;
    uint32_t gval = 100;

    CommonFixture::SetUp();

    struct ebpf_map_attr attr;
    attr.type = EBPF_MAP_TYPE_PERCPU_HASHTABLE;
    attr.key_size = sizeof(uint32_t);
    attr.value_size = sizeof(uint32_t);
    attr.max_entries = 100;
    attr.flags = 0;

    error = ebpf_map_create(ee, &em, &attr);
    ASSERT_TRUE(!error);

    error = ebpf_map_update_elem_from_user(em, &gkey, &gval, 0);
    ASSERT_TRUE(!error);
  }

  virtual void TearDown() {
    ebpf_map_destroy(em);
    CommonFixture::TearDown();
  }
};

TEST_F(PercpuHashTableMapDeleteTest, CorrectDelete) {
  int error;
  uint32_t key = 50;

  error = ebpf_map_delete_elem_from_user(em, &key);
  EXPECT_EQ(0, error);
}
}  // namespace


text:
<!DOCTYPE  html>

    <meta charset="utf-8">

    <title>doc</title>

Data Table Directive

Documentation & Live Demo

http://nickburns2006.github.io/rxDataTable/

Overview

The rx-data-table directive is designed to pretty much be a catch-all
solution for displaying data in a table format in a basic or extremely
complex style. It has some basic CSS styling included, but provides hooks
for you to attach conditional styles to each row or column.

Some Key Features

Single or Multi-Column Sorting

Column Display Presets

Individual Data-Driven Cell Styling

CSS FlexBox display for fluid space display

Inline Field Editing

Text Editing

Multi-Option Selects

Typeahead auto-complete

Get started

You must already have an angular project set up.

Install via bower:
bower install angular-rx-data-table

Include angular-rx-data-table in your code
<link href="bower_components/angular-rx-data-table/dist/styles/rx-data-table.min.css" rel="stylesheet">
<script src="bower_components/angular-rx-data-table/dist/scripts/rx-data-table.min.js"></script>

Add the module to your app's dependencies:
var app = angular.module("app", ["rxDataTable"]);

For further instructions on how to use the directive, view the full
documentation here.

Dependencies

Obviously this requires you to have an angularjs
project to use this.

This project uses the angular-xeditable for it's inline editing capabilities.

TODO

...

License

MIT


text:
package com.coding4people.mosquitoreport.api.buckets;

import org.glassfish.hk2.utilities.binding.AbstractBinder;

public class BucketBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(PictureBucket.class).to(PictureBucket.class);
    }
}


text:
{% extends "layouts/base.html" %}

{% block content %}
<p>{{ error }}</p>
{% endblock %}


text:
from . import *
from util import *

class DPty(object):
  def __init__(self,master_fd,slave_fd):
    self._name = None
    self._name_changed = Event()

    self._master_fd = master_fd
    self._slave_fd = slave_fd

  def set_name(self,name):
    self._name = name
    self._name_changed.fire(self)
  name = property(lambda self: self._name, set_name)
  name_changed = property(lambda self: self._name_changed)

  @property
  def slave_fd(self):
    return self._slave_fd

  @property
  def master_fd(self):
    return self._master_fd


text:
module Striped
  class Error < StandardError
    class BadRequest  < Error; end
    class ServerError < Error; end

    class Unauthorized  < Error::BadRequest; end
    class RequestFailed < Error::BadRequest; end
    class NotFound      < Error::BadRequest; end

    class InvalidRequest < Error::RequestFailed; end
    class APIError       < Error::RequestFailed; end
    class CardError      < Error::RequestFailed; end
  end
end


text:
#include <string>
#include <vector>
#include <algorithm>
#include <boost/optional.hpp>
#include <boost/bind.hpp>

#include <tchar.h>
#include <windows.h>
#include <shlobj.h>

BOOL	SafeSHGetSpecialFolderPath(HWND hwndOwner,LPTSTR lpszPath,int nFolder,BOOL fCreate);
boost::optional<std::string> reg_query_value(const std::string &path, const std::string &key);

#if 0

boost::optional<std::string> get_application_data_path()
{
#if defined _MSC_VER
	std::vector<char> buf;
	buf.resize(MAX_PATH * 8);

	if (SafeSHGetSpecialFolderPath(NULL, &buf[0], CSIDL_APPDATA, false)) {
		return std::string(&buf[0]);
	}
	return boost::optional<std::string>();
#else
	return "~";
#endif
}

#else

boost::optional<std::string> get_application_data_path()
{
#if defined _MSC_VER
	return reg_query_value("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", "AppData");
#else
	return "~";
#endif
}

#endif

int main(int argc, char *argv[])
{
	using namespace std;

	vector<string> argvec;
	for_each(argv, argv + argc, boost::bind(&vector<string>::push_back, &argvec, _1));

	string outputFile;
	for (size_t i = 0; i < argvec.size(); ++i) {
		string argi = argvec[i];
		if (argi == "-h") {
			printf("usage: getfolder [-o file]\n");
			return 0;
		}
		else if (argi == "-o") {
			if (! (i + 1 < argvec.size())) {
				fprintf(stderr, "error: option -o requires an argument.\n");
				return 1;
			}
			outputFile = argvec[i + 1];
			i += 1;
		}
		else if (argi.substr(0, 1) == "-") {
			fprintf(stderr, "error: unknown option: '%s'\n", argi.c_str());
			return 1;
		}
	}

	boost::optional<string> s = get_application_data_path();

	if (! s) {
		fprintf(stderr, "error: can't get application data folder\n");
		return 2;
	}

	if (outputFile.empty()) {
		printf("%s\n", (*s).c_str());
	}
	else {
		FILE *pf = fopen(outputFile.c_str(), "w");
		if (! pf) {
			fprintf(stderr, "error: can't create a file: '%s'\n", outputFile.c_str());
			return 2;
		}
		fprintf(pf, "%s\n", (*s).c_str());
		fclose(pf);
	}

	return 0;
}

//http://www.usefullcode.net/2006/12/os.html

BOOL	SafeSHGetSpecialFolderPath(HWND hwndOwner,LPTSTR lpszPath,int nFolder,BOOL fCreate)
{
	BOOL	(CALLBACK* g_pfnSHGetSpecialFolderPath)(HWND,LPTSTR,int,BOOL);
	HRESULT	(CALLBACK* g_pfnSHGetFolderPath)(HWND,int,HANDLE,DWORD,LPTSTR);

	int			i;
	BOOL		ret;
	HRESULT		hr;
	HMODULE		hDLL;
	TCHAR		pszDllFile[][15] = {_T("shfolder.dll"),_T("shell32.dll")};

	if(lpszPath == NULL)
		return	FALSE;
	*lpszPath = NULL;

	ret = FALSE;
	for(i = 0; i < 2; i++)
	{
		hDLL = ::LoadLibrary(pszDllFile[i]);
		if(hDLL == NULL)
			continue;

		#ifdef UNICODE
			(*(FARPROC*)&g_pfnSHGetSpecialFolderPath = ::GetProcAddress(hDLL,"SHGetSpecialFolderPathW"));
			(*(FARPROC*)&g_pfnSHGetFolderPath = ::GetProcAddress(hDLL,"SHGetFolderPathW"));
		#else
			(*(FARPROC*)&g_pfnSHGetSpecialFolderPath = ::GetProcAddress(hDLL,"SHGetSpecialFolderPathA"));
			(*(FARPROC*)&g_pfnSHGetFolderPath = ::GetProcAddress(hDLL,"SHGetFolderPathA"));
		#endif

		if(g_pfnSHGetSpecialFolderPath)
			ret = g_pfnSHGetSpecialFolderPath(hwndOwner,lpszPath,nFolder,fCreate);
		if(ret == FALSE && g_pfnSHGetFolderPath)
		{
			hr = g_pfnSHGetFolderPath(hwndOwner,nFolder | (fCreate ? CSIDL_FLAG_CREATE : 0),NULL,SHGFP_TYPE_DEFAULT,lpszPath);
			ret = (SUCCEEDED(hr)) ? TRUE : FALSE;
		}

		::FreeLibrary(hDLL);

		if(ret)
			return	TRUE;
	}

	return	FALSE;
}

boost::optional<std::string> reg_query_value(const std::string &path, const std::string &key)
{
	HKEY hKey;

	LONG r = ::RegOpenKeyEx(HKEY_CURRENT_USER, path.c_str(), 0, KEY_QUERY_VALUE, &hKey);
	if (r != ERROR_SUCCESS) {
		return boost::optional<std::string>(); // fail
	}

	DWORD dwType;
	DWORD dwSize;
	r = ::RegQueryValueEx(hKey, key.c_str(), NULL, &dwType, NULL, &dwSize);
	if (r != ERROR_SUCCESS) {
		return boost::optional<std::string>(); // fail
	}
	if (dwType != REG_SZ) {
		return boost::optional<std::string>(); // fail
	}

	std::vector<char> buf(dwSize);
	::RegQueryValueEx(hKey, key.c_str(), NULL, &dwType, (LPBYTE)&buf[0], &dwSize);
	if (r != ERROR_SUCCESS) {
		return boost::optional<std::string>(); // fail
	}

	assert(buf.size() >= 1);
	assert(buf[buf.size() - 1] == '\0');
	std::string value(&buf[0], buf.size() - 1);

	::RegCloseKey(hKey);

	return value;
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Form from 'grommet/components/Form';
import FormFields from 'grommet/components/FormFields';
import FormField from 'grommet/components/FormField';
import Header from 'grommet/components/Header';
import CheckBox from 'grommet/components/CheckBox';
import RadioButton from 'grommet/components/RadioButton';
import TextInput from 'grommet/components/TextInput';
import Select from 'grommet/components/Select';
import NumberInput from 'grommet/components/NumberInput';
import Table from 'grommet/components/Table';
import Footer from 'grommet/components/Footer';
import Button from 'grommet/components/Button';
import Anchor from 'grommet/components/Anchor';
import DateTime from 'grommet/components/DateTime';
import Example from '../../Example';

const VALUES = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
  'eight'];

export default class FullFormExample extends Component {

  constructor () {
    super();
    this._onChangeRange = this._onChangeRange.bind(this);
    this._onChange = this._onChange.bind(this);
    this._onSearchInputChange = this._onSearchInputChange.bind(this);
    this._onDateTimeChange = this._onDateTimeChange.bind(this);
    this._onTextInputDOMChange = this._onTextInputDOMChange.bind(this);
    this._onTextInputSelect = this._onTextInputSelect.bind(this);
    this._onSelectSearch = this._onSelectSearch.bind(this);
    this._onSelectChange = this._onSelectChange.bind(this);
    this.state = {
      rangeValue: 10,
      searchInput: { suggestions: VALUES },
      select: { options: VALUES },
      textInput: { suggestions: VALUES, value: '' },
      calendarDate: (new Date()).toISOString().slice(0, 10)
    };
  }

  _onChangeRange (event) {
    this.setState({rangeValue: parseInt(event.target.value, 10)});
  }

  _onChange (event) {
    // console.log('!!! FullForm changed', event.target, 'to',
    //   event.target.value);
  }

  _onSearchInputChange (value) {
    // console.log('!!! FullForm _onSearchInputChange', value);
    this.setState({
      searchInput: {
        value: value,
        suggestions: this._searchInputSuggestions
      }
    });
  }

  _onTextInputDOMChange (event) {
    const regexp = new RegExp('^' + event.target.value);
    const suggestions = VALUES.filter(val => {
      return regexp.test(val);
    });
    this.setState({
      textInput: { value: event.target.value, suggestions: suggestions }
    });
  }

  _onTextInputSelect (pseudoEvent) {
    this.setState({
      textInput: { value: pseudoEvent.suggestion, suggestions: VALUES }
    });
  }

  _onSelectSearch (event) {
    const regexp = new RegExp('^' + event.target.value);
    const options = VALUES.filter(val => regexp.test(val));
    this.setState({ select: { options: options } });
  }

  _onSelectChange (pseudoEvent) {
    this.setState({ select: { value: pseudoEvent.option, options: VALUES } });
  }

  _onDateTimeChange (value) {
    this.setState({ date: value });
  }

  render () {
    const p = this.props.prefix;

    return (
      <Example align="start" code={
        <Form onSubmit={this.props.onSubmit} compact={this.props.compact}>

Edit

          <FormFields>
            <fieldset>
              <legend>First section</legend>
              <FormField label="Item 1" htmlFor={p + "item1"}
                help="something helpful">
                <input id={p + "item1"} name="item-1" type="text"
                  onChange={this._onChange} />
              </FormField>
              <FormField>
                <CheckBox id={p + "item2"} name="item-2" label="Item 2"
                  onChange={this._onChange} />
              </FormField>
              <FormField>
                <CheckBox id={p + "item3"} name="item-3" label="Item 3"
                  toggle={true}
                  onChange={this._onChange} />
              </FormField>
              <FormField label="Item 4">
                <RadioButton id={p + "item4-1"} name="item-4" label="first"
                  onChange={this._onChange} />
                <RadioButton id={p + "item4-2"} name="item-4" label="second"
                  onChange={this._onChange} />
              </FormField>
              <FormField label="Item 5" htmlFor={p + "item5"}
                error="something's wrong">
                <textarea id={p + "item5"} name="item-5" />
              </FormField>
              <FormField label="Item 6" htmlFor={p + "item6"}>
                <TextInput id={p + "item6"} name="item-6"
                  value={this.state.textInput.value}
                  suggestions={this.state.textInput.suggestions}
                  onDOMChange={this._onTextInputDOMChange}
                  onSelect={this._onTextInputSelect} />
              </FormField>
              <FormField label="Item 7a" htmlFor={p + "item7a"}
                help={<Anchor>learn more ...</Anchor>}>
                <select id={p + "item7a"} name="item-7a">
                  <option>first</option>
                  <option>second</option>
                  <option>third</option>
                </select>
              </FormField>
              <FormField label="Item 7b" htmlFor={p + "item7b"}>
                <Select id={p + "item6b"} name="item-7b"
                  value={this.state.select.value}
                  options={this.state.select.options}
                  onSearch={this._onSelectSearch}
                  onChange={this._onSelectChange} />
              </FormField>
              <FormField label="Item 9" htmlFor={p + "item9"}>
                <NumberInput id={p + "item9"} name="item-9"
                  value={this.state.rangeValue}
                  onChange={this._onChangeRange} />
              </FormField>
              <FormField label="Item 10" htmlFor={p + "item10"}
                help={this.state.rangeValue}>
                <input id={p + "item10"} name="item-10" type="range"
                  min="1" max="20" value={this.state.rangeValue}
                  onChange={this._onChangeRange}
                  onMouseUp={this._onChangeRange}/>
              </FormField>
            </fieldset>
            <fieldset>
              <legend>Another section</legend>

Some informational text.

              <FormField label="Item 11">

                      first
                      123

                      second
                      456

                      third
                      789

              </FormField>
              <FormField label="Item 12" htmlFor={p + "item12"}>
                <input id={p + "item12"} name="item-12" type="file" />
              </FormField>
              <FormField label="Item 13" htmlFor={p + "item13"}>
                <DateTime id={p + "item13"} name="item-13"
                  format="YYYY-MM-DD h:mm a" step={5}
                  value={this.state.date}
                  onChange={this._onDateTimeChange} />
              </FormField>
            </fieldset>
          </FormFields>

            <Button label="OK" primary={true}
              onClick={() => alert('submit')} />

        </Form>
      } />
    );
  }
};

FullFormExample.propTypes = {
  compact: PropTypes.bool,
  onCancel: PropTypes.func,
  onSubmit: PropTypes.func,
  prefix: PropTypes.string
};

FullFormExample.defaultProps = {
  prefix: 'ff'
};


text:
class CollectionService
  class << self
    def create
      Dotenv.load ".env.collection"

      card_set   = ENV["COLLECTION_CARD_SET"].tr(" ", "")

      card_class =
        if ENV["CARD_CLASS"].present?
          ENV["CARD_CLASS"]
        else
          "NEUTRAL,DRUID,HUNTER,MAGE,PALADIN,PRIEST,ROGUE,SHAMAN,WARLOCK,WARRIOR"
        end

      header               = ENV["COLLECTION_HEADER"].tr(" ", "")
      highlander           = ENV["HIGHLANDER"].squish
      collection_file_path = ENV["COLLECTION_FILE_PATH"].squish

      new(card_set, card_class, header, highlander, collection_file_path)
    end
  end

  attr_reader :collection

  def initialize(card_set, card_class, header, highlander, collection_file_path)
    @card_sets            = card_set.split(",")
    @card_classes         = card_class.split(",")
    @headers              = header.split(",").map(&:to_sym)
    @highlander           = highlander.inquiry.true?
    @collection_file_path = collection_file_path

    @collection = Collection.create(card_set: card_set, card_class: card_class, highlander: highlander?)
  end

  def highlander?
    !!@highlander
  end

  def quantity(rarity)
    return 1 if highlander? || rarity == "LEGENDARY"

    2
  end

  def delete_cards
    @collection.collection_card_ids.each do |collection_card_id|
      CollectionCard.destroy(collection_card_id)
    end
  end

  def create_collection
    delete_cards

    Card.each do |card|
      next unless @card_sets.include?(card.card_set) && @card_classes.include?(card.card_class)

      CollectionCard.create(
        collection_id: @collection.id,
        card_id:       card.id,
        quantity:      quantity(card.rarity)
      )
    end
  end

  def export_collection
    if @collection.cards.count.zero?
      create_collection
    end

    CSV.open(@collection_file_path, "wb", headers: @headers + [:quantity], write_headers: true) do |csv|
      @collection.collection_cards.each do |collection_card|
        card_params = collection_card.card.to_h.values_at(*@headers)
        quantity    = collection_card.quantity

        csv << card_params.push(quantity)
      end
    end
  end
end


text:
#include "../stdafx.h"

#include "../AimEnum.h"

#include "AimBase.h"
#include "CharacteristicQuantification.h"
#include "Interval.h"

#include "../memdebug.h"

using std::string;
using namespace aim_lib;

Interval::Interval(void) : CharacteristicQuantification(C_QUANTIFICATION_INTERVAL_NAME)
{
	_minValue		= 0.0;
	_maxValue		= 0.0;
	_minOperator	= None;
	_maxOperator	= None;
}

Interval::Interval(const Interval& interval) : CharacteristicQuantification(interval)
{
	*this = interval;
}

Interval::~Interval(void)
{
}

Interval& Interval::operator=(const Interval& interval)
{
	if (this != &interval)
	{
		CharacteristicQuantification::operator=(interval);
		_minValue		= interval._minValue;
		_maxValue		= interval._maxValue;
		_minOperator	= interval._minOperator;
		_maxOperator	= interval._maxOperator;
		_ucumString		= interval._ucumString;
	}

	return *this;
}

Interval* Interval::Clone() const
{
	return new Interval(*this);
}

double Interval::GetMinValue() const
{
	return _minValue;
}

double Interval::GetMaxValue() const
{
	return _maxValue;
}

ComparisonOperatorType Interval::GetMinOperator() const
{
	return _minOperator;
}

ComparisonOperatorType Interval::GetMaxOperator() const
{
	return _maxOperator;
}

const string& Interval::GetUcumString() const
{
	return _ucumString;
}

void Interval::SetMinValue(double newVal)
{
	_minValue = newVal;
}

void Interval::SetMaxValue(double newVal)
{
	_maxValue = newVal;
}

void Interval::SetMinOperator(ComparisonOperatorType newVal)
{
	_minOperator = newVal;
}

void Interval::SetMaxOperator(ComparisonOperatorType newVal)
{
	_maxOperator = newVal;
}

void Interval::SetUcumString(const string& newVal)
{
	_ucumString = newVal;
}


text:
layout:     post
title:      Digging into GRASS with Python
date:       2013-08-10 12:00:00
summary:    Using code to leverage GIS tools is tricky, but rewarding.
categories: codemonkey gis python
commentIssueId: 11
redirect_from:
  - /codemonkey/gis/python/2013/08/10/digging-into-GRASS-with-python/
---

One of my projects at the Blue Oak Ranch Reserve involves making spatial predictions of evapotranspiration. Many of the ET models (such as Priestly-Taylor) require solar radiation as input, which means I need solar radiation maps to perform the calculations. Both ArcGIS and GRASS offer solar radiation models, but I find GRASS advantageous because the documentation is well-developed and the radiation model can incorporate a number of features that the ArcGIS radiation model cannot, such as terrain shadowing.

When I say the documentation is well-developed, I mean the command manuals in the function reference specifically; documentation for setup and GRASS in general leaves a lot to be desired. My biggest issue was that I needed to run the radiation model for a number of days of the year, and running it manually would be tedious and time-consuming. I wanted to develop a simple loop that would run the radiation model for a specified sequence of days. GRASS supports this kind of functionality; in addition to being callable in text mode, it also interfaces with both R and Python.

Unfortunately, I could not get much of anything to run using Bash or R. A combination of complicated setup requirements, poorly-developed help files and my limited experience with GRASS resulted in repeated failures. I couldn't even set up the environment variables properly to initialize GRASS and create a new mapset. But I did find a way with Python! It's a bit primitive, but hey---it works, and that's all I care about at this point.

I'm going to assume you know how to set up a mapset in GRASS and add/import some layers; the documentation will get you that far at least. The tricky part can be the region setting, but I made things easy for myself by defining the extent based on my DEM. The next thing I did was run r.slope.aspect, since r.sun (the radiation model) uses slope and aspect as well as elevation to computer solar radiation.

If you're in the Layer Manager window, you should see the Python Shell tab at the bottom of the window. Going to this tab gives you a Python interface, and you can get access to GRASS functions by importing the grass.script module. The module includes the `run_command()` function, which can be used to run basically any GRASS function. It supports flags through the flags argument, as well as any other named arguments relevant to the function you're calling.

So let's keep things simple and just run a script by first navigating to its parent folder (using `chdir()` from the os module), and then calling it using `execfile()`:

{% highlight python %}
import os
os.chdir("C:\myfolder\")
execfile("myscript.py")
{% endhighlight %}

And the script itself:

{% highlight python %}
import grass.script as grass

# i is the day of year (DOY) to use for running r.sun
for i in [51, 65, 79, 93, 107, 121, 135, 149, 161, 172, 182, 191, 205, 219,
          233, 247, 257, 266, 278, 289, 303, 317, 331, 344, 356, 365]:
	# want to get insolation time, global radiation
	insolname = "insol_DOY" + str(i) + "_16ft"
	radname = "globrad_DOY" + str(i) + "_16ft"
	# run the solar model
	grass.run_command("r.sun", flags = "s",
			  elevin = "BORR_DEM16ft@PERMANENT",
			  aspin = "aspect_16ft@PERMANENT",
			  slopein = "slope_16ft@PERMANENT",
			  insol_time = insolname, glob_rad = radname, day = i)
	# export the outputs to GTiff files
	grass.run_command("r.out.gdal", input = insolname + "@PERMANENT", output = insolname)
	grass.run_command("r.out.gdal", input = radname + "@PERMANENT", output = radname)
{% endhighlight %}

And that's it! The script is running as I type this, and I'm free to write about it on my blog without having to stop every 15 minutes to set up another run of the solar radiation model.


text:
package org.onetwo.ext.poi.excel.generator;

import java.util.Collection;

import org.apache.poi.ss.usermodel.Cell;
import org.onetwo.ext.poi.excel.data.CellContextData;
import org.onetwo.ext.poi.excel.exception.ExcelException;

public class SmartIteratorRowProcessor extends IteratorRowProcessor {

	public SmartIteratorRowProcessor(PoiExcelGenerator excelGenerator, RowProcessor titleRowProcessor) {
		super(excelGenerator, titleRowProcessor);
	}

	@Override
	protected void processSingleField(CellContextData cellContext){
		int cellIndex = cellContext.getCellIndex();

		Object v = getFieldValue(cellContext);
		cellContext.setFieldValue(v);

		if(Collection.class.isInstance(v)){
			Collection<?> values = (Collection<?>) v;
			int rowCount = cellContext.getRowCount();
			for(Object value : values){
				cellContext.setFieldValue(value);
				this.doFieldValueExecutors(cellContext);
				this.createSingleCell(cellContext, rowCount, cellIndex, value);
				rowCount++;
				cellContext.addRowSpanCount(1);

				//clear
				cellContext.setFieldValue(null);
			}
		}else{
//			this.createSingleCell(ele, row, field, cellIndex, v);
			super.processSingleField(cellContext);
		}

	}

	private Cell createSingleCell(CellContextData cellContext, int rowCount, int cellIndex, Object cellValue){
		Cell cell = null;
		if(cellContext==null)
			throw new ExcelException("the cell of row has not created yet : " + cellContext.getFieldModel().getName());

		CellContextData subCellContext = createCellContext(cellContext.getObjectValue(), rowCount, cellContext.getRowContext(), cellContext.getFieldModel(), cellIndex);
		cell = createCell(subCellContext);

		setCellValue(cellContext.getFieldModel(), cell, cellValue);

		return cell;
	}

}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Link extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('Link_model');
        $this->load->library('form_validation');
    }

    public function index()
    {
        $link = $this->Link_model->get_all();

        $data = array(
            'link_data' => $link
        );

        $this->template->load('template','link_list', $data);
    }

    public function read($id)
    {
        $row = $this->Link_model->get_by_id($id);
        if ($row) {
            $data = array(
		'id' => $row->id,
		'nama' => $row->nama,
		'url' => $row->url,
		'tab_baru' => $row->tab_baru,
		'url_gambar' => $row->url_gambar,
		'urutan' => $row->urutan,
		'hits' => $row->hits,
		'ip' => $row->ip,
		'waktu' => $row->waktu,
	    );
            $this->template->load('template','link_read', $data);
        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('link'));
        }
    }

    public function create()
    {
        $data = array(
            'button' => 'Create',
            'action' => site_url('link/create_action'),
	    'id' => set_value('id'),
	    'nama' => set_value('nama'),
	    'url' => set_value('url'),
	    'tab_baru' => set_value('tab_baru'),
	    'url_gambar' => set_value('url_gambar'),
	    'urutan' => set_value('urutan'),
	    'hits' => set_value('hits'),
	    'ip' => set_value('ip'),
	    'waktu' => set_value('waktu'),
	);
        $this->template->load('template','link_form', $data);
    }

    public function create_action()
    {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->create();
        } else {
            $data = array(
		'nama' => $this->input->post('nama',TRUE),
		'url' => $this->input->post('url',TRUE),
		'tab_baru' => $this->input->post('tab_baru',TRUE),
		'url_gambar' => $this->input->post('url_gambar',TRUE),
		'urutan' => $this->input->post('urutan',TRUE),
		'hits' => $this->input->post('hits',TRUE),
		'ip' => $this->input->post('ip',TRUE),
		'waktu' => $this->input->post('waktu',TRUE),
	    );

            $this->Link_model->insert($data);
            $this->session->set_flashdata('message', 'Create Record Success');
            redirect(site_url('link'));
        }
    }

    public function update($id)
    {
        $row = $this->Link_model->get_by_id($id);

        if ($row) {
            $data = array(
                'button' => 'Update',
                'action' => site_url('link/update_action'),
		'id' => set_value('id', $row->id),
		'nama' => set_value('nama', $row->nama),
		'url' => set_value('url', $row->url),
		'tab_baru' => set_value('tab_baru', $row->tab_baru),
		'url_gambar' => set_value('url_gambar', $row->url_gambar),
		'urutan' => set_value('urutan', $row->urutan),
		'hits' => set_value('hits', $row->hits),
		'ip' => set_value('ip', $row->ip),
		'waktu' => set_value('waktu', $row->waktu),
	    );
            $this->template->load('template','link_form', $data);
        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('link'));
        }
    }

    public function update_action()
    {
        $this->_rules();

        if ($this->form_validation->run() == FALSE) {
            $this->update($this->input->post('id', TRUE));
        } else {
            $data = array(
		'nama' => $this->input->post('nama',TRUE),
		'url' => $this->input->post('url',TRUE),
		'tab_baru' => $this->input->post('tab_baru',TRUE),
		'url_gambar' => $this->input->post('url_gambar',TRUE),
		'urutan' => $this->input->post('urutan',TRUE),
		'hits' => $this->input->post('hits',TRUE),
		'ip' => $this->input->post('ip',TRUE),
		'waktu' => $this->input->post('waktu',TRUE),
	    );

            $this->Link_model->update($this->input->post('id', TRUE), $data);
            $this->session->set_flashdata('message', 'Update Record Success');
            redirect(site_url('link'));
        }
    }

    public function delete($id)
    {
        $row = $this->Link_model->get_by_id($id);

        if ($row) {
            $this->Link_model->delete($id);
            $this->session->set_flashdata('message', 'Delete Record Success');
            redirect(site_url('link'));
        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('link'));
        }
    }

    public function _rules()
    {
	$this->form_validation->set_rules('nama', 'nama', 'trim|required');
	$this->form_validation->set_rules('url', 'url', 'trim|required');
	$this->form_validation->set_rules('tab_baru', 'tab baru', 'trim|required');
	$this->form_validation->set_rules('url_gambar', 'url gambar', 'trim|required');
	$this->form_validation->set_rules('urutan', 'urutan', 'trim|required');
	$this->form_validation->set_rules('hits', 'hits', 'trim|required');
	$this->form_validation->set_rules('ip', 'ip', 'trim|required');
	$this->form_validation->set_rules('waktu', 'waktu', 'trim|required');

	$this->form_validation->set_rules('id', 'id', 'trim');
	$this->form_validation->set_error_delimiters('', '');
    }

}

/* End of file Link.php */
/* Location: ./application/controllers/Link.php */
/* Please DO NOT modify this information : */
/* Generated by Harviacode Codeigniter CRUD Generator 2017-03-01 09:08:14 */
/* http://harviacode.com */


text:
<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class AuthLoginRequest extends Request
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        /*
         * Предварительно отрабатывается app/Http/Middleware/MobilePhoneCheck.php
         */
        return ['login' => 'login', 'password' => 'required'];
    }

}


text:
class SessionController < ApplicationController
  def register_user
    @user = User.new(params[:user])
    if request.post? and @user.save
      flash[:message] = 'You are successfully registered'
      session[:user_id] = @user.id
      redirect_to(controller: 'decks', action: 'list')
    end
  end

  def login
    if request.post?
      current_user = User.find_by_login_and_password(params[:login], params[:password])
      if current_user
        session[:user_id] = current_user.id
        if session[:return_to]
          redirect_to session[:return_to]
          session[:return_to] = nil
        else
          redirect_to(controller: 'decks', action: 'list')
        end
      else
        flash[:error] = 'The login/password pair is invalid'
      end
    end
  end

  def logout
    session[:user_id] = nil
    redirect_to '/'
  end
end


text:
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import javax.swing.ToolTipManager;

public class DoctorGo extends JFrame{
    public static int i, j, x, y, count, check=0;
    public static int board[][] = new int[21][21];
    JToggleButton clara[][] = new JToggleButton[20][20];
    ImageIcon DoctorGo = new ImageIcon(getClass().getResource("DoctorGo.png"));
    ImageIcon JennaGo = new ImageIcon(getClass().getResource("JennaGo0.png"));
    ImageIcon JennaGo1 = new ImageIcon(getClass().getResource("JennaGo1.png")); //Black
    ImageIcon JennaGo2 = new ImageIcon(getClass().getResource("JennaGo2.png")); //White
    ImageIcon Foul = new ImageIcon(getClass().getResource("Foul.png"));

    public DoctorGo() {
        Jenna();
    }

    public void Jenna() {
        String [] colors = {"WHITE", "BLACK"};
    	JFrame choice = new JFrame("Opening");
        String color = (String) JOptionPane.showInputDialog(choice,
        "Which side do you want?", "DoctorGo 1.0", JOptionPane.QUESTION_MESSAGE, DoctorGo, colors, colors[0]);

        if(color==null)
        	System.exit(0);
        else if(color.equals(colors[0])){
        	ImageIcon temp = JennaGo1;
            JennaGo1 = JennaGo2;
            JennaGo2 = temp;
            check=1;
        }//1:Human(WHITE) 2:Computer(BLACK)

        setTitle("DOCTOR GO!");
        setSize(1000, 1025);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);

        Container c = getContentPane();
        c.setLayout(null);
        c.setBackground(new Color(187,137,33));

        JLabel [][] mark = new JLabel[19][2];
        for(i=0;i<19;i++){
        	mark[i][0]=new JLabel(String.format("%02d", i));
        	mark[i][1]=new JLabel(String.format("%02d", i));
        	mark[i][0].setBounds(i*50+38,3,15,15);
        	mark[i][1].setBounds(3,i*50+38,15,15);
        	mark[i][0].setForeground(Color.white);
        	mark[i][1].setForeground(Color.white);
        	c.add(mark[i][0]);
        	c.add(mark[i][1]);
        }

        ToolTipManager.sharedInstance().setInitialDelay(0);

        for(i=1;i<=19;i++){
            for(j=1;j<=19;j++){
            clara[i][j] = new JToggleButton(JennaGo);
            clara[i][j].setSelectedIcon(JennaGo1);
            clara[i][j].putClientProperty("column", i);
            clara[i][j].putClientProperty("row", j);
            clara[i][j].setToolTipText("("+Integer.toString(i-1)+","+Integer.toString(j-1)+")");
            clara[i][j].setBorder(null);
            clara[i][j].addKeyListener(new Listen());
            clara[i][j].setBounds(i*50-30,j*50-30,50,50);
            c.add(clara[i][j]);
            clara[i][j].addActionListener((ActionEvent e) -> {
            	JToggleButton b = (JToggleButton) e.getSource();
                x = (int)b.getClientProperty("column");
                y = (int)b.getClientProperty("row");
                if(board[x][y]!=0){
                    JFrame frame= new JFrame();
                    JOptionPane.showMessageDialog(frame, null, "GAME OVER", JOptionPane.PLAIN_MESSAGE, Foul);
                    System.exit(0);
                }
                board[x][y]=1;
                Idea.AI();
                board[Idea.x][Idea.y]=2;
                clara[Idea.x][Idea.y].setIcon(JennaGo2);
                count++;
            });
            }
        }
        if(check==1){
        	board[10][10]=2;
        	clara[10][10].setIcon(JennaGo2);
        }
        Window.MyJenna();
    }

    public static void Win(int k){
        if(k==1){
            JFrame frame= new JFrame();
            ImageIcon Win1 = new ImageIcon(DoctorGo.class.getResource("Win1.png"));
            JOptionPane.showMessageDialog(frame, null, "GAME OVER", JOptionPane.PLAIN_MESSAGE, Win1);
        }
        else{
            JFrame frame= new JFrame();
            ImageIcon Win2 = new ImageIcon(DoctorGo.class.getResource("Win2.png"));
            JOptionPane.showMessageDialog(frame, null, "GAME OVER", JOptionPane.PLAIN_MESSAGE, Win2);
        }
        System.exit(0);
    }

    public class Listen extends KeyAdapter{
    	int enable=0;
    	JFrame frame = new JFrame("Message");
    	ImageIcon off = new ImageIcon(getClass().getResource("TipOff.png"));
    	ImageIcon on = new ImageIcon(getClass().getResource("TipOn.png"));

    	public void keyPressed (KeyEvent e) {
            if(e.getKeyCode()==KeyEvent.VK_F1)
                Window.f.setVisible(true);
            else if(e.getKeyCode()==KeyEvent.VK_F2){
            	if(enable==0){
            		JOptionPane.showMessageDialog(frame, null, "Notice!", JOptionPane.PLAIN_MESSAGE, off);
            	    ToolTipManager.sharedInstance().setEnabled(false);
            		enable=1;
            	}
            	else{
            		JOptionPane.showMessageDialog(frame, null, "Notice!", JOptionPane.PLAIN_MESSAGE, on);
            		ToolTipManager.sharedInstance().setEnabled(true);
            		enable=0;
            	}
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new DoctorGo().setVisible(true);
        });
    }
}


text:
package com.mauriciotogneri.dry.compiler.types;

import com.mauriciotogneri.dry.compiler.lexical.Lexeme;
import com.mauriciotogneri.dry.compiler.lexical.Token;
import com.mauriciotogneri.dry.compiler.lexical.tokens.arithmetic.ArithmeticAdditionToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.arithmetic.ArithmeticDivisionToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.arithmetic.ArithmeticModuleToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.arithmetic.ArithmeticMultiplicationToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.arithmetic.ArithmeticPowerToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.arithmetic.ArithmeticSubtractionToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.blocks.ParenthesisCloseToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.blocks.ParenthesisOpenToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.comparison.ComparisonEqualToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.comparison.ComparisonGreaterEqualToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.comparison.ComparisonGreaterToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.comparison.ComparisonLessEqualToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.comparison.ComparisonLessToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.comparison.ComparisonNotEqualToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.conditional.ConditionalElseIfToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.conditional.ConditionalElseToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.conditional.ConditionalEndIfToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.conditional.ConditionalIfToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.delimiters.NewLineToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.delimiters.SpaceToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.logic.LogicAndToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.logic.LogicNotToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.logic.LogicOrToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.special.AssignmentToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.special.CommaToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.special.FunctionDefToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.special.SymbolToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.special.TypeOfToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.special.TypeReturnToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.types.BooleanToken;
import com.mauriciotogneri.dry.compiler.lexical.tokens.types.NumberToken;

import java.util.Optional;

public enum TokenType
{
    // delimiters
    SPACE(" +"), //
    TAB("\\t+"), //
    NEW_LINE("\\n+"), //

    // literals
    NUMBER("\\d*\\.?\\d+"),
    STRING("\"[^\"]*\""),
    BOOLEAN("true|false"),

    // arithmetic
    ARITHMETIC_ADDITION("\\+"), //
    ARITHMETIC_SUBTRACTION("\\-"), //
    ARITHMETIC_MULTIPLICATION("\\*"), //
    ARITHMETIC_DIVISION("\\/"), //
    ARITHMETIC_POWER("^"), //
    ARITHMETIC_MODULE("%"), //

    // special
    MEMBER_ACCESS("\\."), //
    COMMA(","), //
    TYPE_OF(":"), //
    TYPE_RETURN("::"), //
    ASSIGNMENT("="), //
    IMPORT("\\$"), //

    // comparison
    LOGIC_EQUAL("=="), //
    LOGIC_NOT_EQUAL("!="), //
    LOGIC_GREATER(">"), //
    LOGIC_GREATER_EQUAL(">="), //
    LOGIC_LESS("<"), //
    LOGIC_LESS_EQUAL("<="), //

    // logic
    LOGIC_NOT("!"), //
    LOGIC_AND("&"), //
    LOGIC_OR("|"), //

    // conditional
    IF("if"), //
    ELSE("else"), //
    ELSE_IF("elsif"), //
    END_IF("end"), //

    // parenthesis
    PARENTHESIS_OPEN("\\("), //
    PARENTHESIS_CLOSE("\\)"), //

    // lists
    LIST_OPEN("\\["), //
    LIST_CLOSE("\\]"), //

    // brackets
    BRACKETS_OPEN("\\{"), //
    BRACKETS_CLOSE("\\}"), //

    // symbols
    FUNCTION_DEF("\\\\[a-zA-Z]\\w*"), //
    SYMBOL("[a-zA-Z]\\w*");

    private final String pattern;

    TokenType(String pattern)
    {
        this.pattern = pattern;
    }

    public String pattern()
    {
        return pattern;
    }

    public static Optional<Token> ofLexeme(Lexeme lexeme)
    {
        for (TokenType tokenType : TokenType.values())
        {
            if (lexeme.matches(tokenType.pattern()))
            {
                return Optional.of(ofType(tokenType, lexeme));
            }
        }

        return Optional.empty();
    }

    private static Token ofType(TokenType type, Lexeme lexeme)
    {
        switch (type)
        {
            case NUMBER:
                return new NumberToken(lexeme);

            case PARENTHESIS_OPEN:
                return new ParenthesisOpenToken(lexeme);

            case PARENTHESIS_CLOSE:
                return new ParenthesisCloseToken(lexeme);

            case ARITHMETIC_ADDITION:
                return new ArithmeticAdditionToken(lexeme);

            case ARITHMETIC_SUBTRACTION:
                return new ArithmeticSubtractionToken(lexeme);

            case ARITHMETIC_MULTIPLICATION:
                return new ArithmeticMultiplicationToken(lexeme);

            case ARITHMETIC_DIVISION:
                return new ArithmeticDivisionToken(lexeme);

            case ARITHMETIC_POWER:
                return new ArithmeticPowerToken(lexeme);

            case ARITHMETIC_MODULE:
                return new ArithmeticModuleToken(lexeme);

            case SYMBOL:
                return new SymbolToken(lexeme);

            case FUNCTION_DEF:
                return new FunctionDefToken(lexeme);

            case COMMA:
                return new CommaToken(lexeme);

            case TYPE_OF:
                return new TypeOfToken(lexeme);

            case TYPE_RETURN:
                return new TypeReturnToken(lexeme);

            case ASSIGNMENT:
                return new AssignmentToken(lexeme);

            case BOOLEAN:
                return new BooleanToken(lexeme);

            case IF:
                return new ConditionalIfToken(lexeme);

            case ELSE:
                return new ConditionalElseToken(lexeme);

            case ELSE_IF:
                return new ConditionalElseIfToken(lexeme);

            case END_IF:
                return new ConditionalEndIfToken(lexeme);

            case NEW_LINE:
                return new NewLineToken(lexeme);

            case SPACE:
            case TAB:
                return new SpaceToken(lexeme);

            case LOGIC_EQUAL:
                return new ComparisonEqualToken(lexeme);

            case LOGIC_NOT_EQUAL:
                return new ComparisonNotEqualToken(lexeme);

            case LOGIC_LESS:
                return new ComparisonLessToken(lexeme);

            case LOGIC_LESS_EQUAL:
                return new ComparisonLessEqualToken(lexeme);

            case LOGIC_GREATER:
                return new ComparisonGreaterToken(lexeme);

            case LOGIC_GREATER_EQUAL:
                return new ComparisonGreaterEqualToken(lexeme);

            case LOGIC_NOT:
                return new LogicNotToken(lexeme);

            case LOGIC_AND:
                return new LogicAndToken(lexeme);

            case LOGIC_OR:
                return new LogicOrToken(lexeme);

            //--------------------

            /*case STRING:
                break;
            case MEMBER_ACCESS:
                break;
            case LIST_OPEN:
                break;
            case LIST_CLOSE:
                break;
            case BRACKETS_OPEN:
                break;
            case BRACKETS_CLOSE:
                break;
            case IMPORT:
                break;*/

            default:
                throw new RuntimeException(lexeme.toString());
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.grarak.kerneladiutor.views.AdNativeExpress xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />


text:
import turtle

class C(turtle.TurtleScreenBase):
    def __init__(self, cv):
        <selection>super(C, self).__init__(cv)</selection>