text:
package org.apache.servicecomb.serviceregistry.registry;

import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.configuration.Configuration;
import org.apache.servicecomb.foundation.common.concurrency.SuppressedRunnableWrapper;
import org.apache.servicecomb.foundation.common.utils.SPIServiceUtils;
import org.apache.servicecomb.serviceregistry.client.ServiceRegistryClient;
import org.apache.servicecomb.serviceregistry.config.ServiceRegistryConfig;
import org.apache.servicecomb.serviceregistry.event.HeartbeatFailEvent;
import org.apache.servicecomb.serviceregistry.event.HeartbeatSuccEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class RemoteServiceRegistry extends AbstractServiceRegistry {
  private static final Logger LOGGER = LoggerFactory.getLogger(RemoteServiceRegistry.class);

  private ScheduledThreadPoolExecutor taskPool;

  private List<ServiceRegistryTaskInitializer> taskInitializers = SPIServiceUtils
      .getOrLoadSortedService(ServiceRegistryTaskInitializer.class);

  private AtomicBoolean heartBeatStatus = new AtomicBoolean(true);

  public RemoteServiceRegistry(EventBus eventBus, ServiceRegistryConfig serviceRegistryConfig,
      Configuration configuration) {
    super(eventBus, serviceRegistryConfig, configuration);
  }

  @Override
  public void init() {
    super.init();
    taskPool = new ScheduledThreadPoolExecutor(3,
        new ThreadFactory() {
          private int taskId = 0;

          @Override
          public Thread newThread(Runnable r) {
            Thread thread = new Thread(r,
                RemoteServiceRegistry.super.getName() + " Service Center Task [" + (taskId++) + "]");
            thread.setUncaughtExceptionHandler(
                (t, e) -> LOGGER.error("Service Center Task Thread is terminated! thread: [{}]", t, e));
            return thread;
          }
        },
        (task, executor) -> LOGGER.warn("Too many pending tasks, reject " + task.toString())
    );
    executorService = taskPool;
  }

  @Override
  protected ServiceRegistryClient createServiceRegistryClient() {
    return serviceRegistryConfig.createServiceRegistryClient(this);
  }

  @Override
  public void run() {
    super.run();

    taskPool.scheduleAtFixedRate(serviceCenterTask,
        serviceRegistryConfig.getHeartbeatInterval(),
        serviceRegistryConfig.getHeartbeatInterval(),
        TimeUnit.SECONDS);

    taskPool.scheduleAtFixedRate(
        new SuppressedRunnableWrapper(() -> {
          if (!heartBeatStatus.get()) {
            LOGGER.warn("heart beat currently not success, pause for pulling instance.");
            return;
          }
          serviceRegistryCache.refreshCache();
        }),
        serviceRegistryConfig.getInstancePullInterval(),
        serviceRegistryConfig.getInstancePullInterval(),
        TimeUnit.SECONDS);

    for (ServiceRegistryTaskInitializer initializer : taskInitializers) {
      initializer.init(this);
    }
  }

  public ScheduledThreadPoolExecutor getTaskPool() {
    return this.taskPool;
  }

  @Subscribe
  public void onHeartbeatSuccEvent(HeartbeatSuccEvent heartbeatSuccEvent) {
    // 可以考虑多等待一个心跳周期,这样的好处是尽可能避免provider滞后于consumer注册的情况,consumer访问provider失败
    // 但是这样的坏处是当服务中心两个实例,一个可用,另外一个不可用的情况下,长期处于不查询实例状态。 目前按照一次的实际效果
    // 还是挺好的,也是和版本一直的实现一致。
    heartBeatStatus.set(true);
  }

  @Subscribe
  public void onHeartbeatFailEvent(HeartbeatFailEvent heartbeatFailEvent) {
    heartBeatStatus.set(false);
  }
}


text:
import world
import dnf
import mh
import utils
import math
import random

class BinaryFeatureLearnerModel(object):

    def __init__(self, world, outlier_param=float('Inf'),
            rules=dnf.RULE_SETS[0]):
        """exp(-outlier_param) is the probability that an observation
        is to be discounted"""

        self.world = world
        self.outlier_param = outlier_param

        # define grammar

        def feature_decider(feat):
            return lambda obj, e: feat in obj.features
        symbols = [dnf.PredicateSymbol(str(feat),
            feature_decider(feat)) for feat in world.features]
        self.grammar = dnf.DNF(symbols, rules)

        self.samples = {} # {sample: count for each sample}

    def sample_formulas(self, n=30000):
        """Sample n formulas from the posterior using Metropolis-Hastings.
        Result is returned and stored in self.samples"""

        self.samples = {}

        for f in mh.mh(self._regen_proposer(), self._regen_accept(), n):
            if f not in self.samples:
                self.samples[f] = 0
            self.samples[f] += 1

        return self.samples

    def prob_in_concept(self, obj, use_only_top=utils.MAXSIZE):
        """Return the probability that obj is in the concept,
        according to self.samples. Only the top use_only_top formulas from
        self.sample will be used; if use_only_top is not set."""

        if not self.samples:
            raise error("prob_in_concept called before formulas sampled")

        yes = 0
        total = 0
        for f, count in self.top_formulas(use_only_top):
            if self.grammar.evaluate(f, obj):
                yes += count
            total += count
        return float(yes)/total

    def top_formulas(self, k=10):
        """Return list of (formula, count) pairs for k most frequent
        formulas in self.samples"""

        return sorted(self.samples.items(), key=lambda (f, c): -c)[:k]

    def _regen_proposer(self):

        def proposer(formula):
            if formula is None:
                return self.grammar.random_formula()
            formula2 = formula
            while formula2 == formula:
                formula2 = self.grammar.regenerate_subtree(formula)
            return formula2

        return proposer

    def _regen_accept(self):

        G = self.grammar

        def accept(formula, formula2):
            log_ratio = self.log_likelihood(formula2)\
                - self.log_likelihood(formula)\
                + G.log_prior(formula2) - G.log_prior(formula)\
                + math.log(formula.size_no_leaves)\
                - math.log(formula2.size_no_leaves)\
                + G.log_prob(formula) - G.log_prob(formula2)
            return random.random() < math.exp(log_ratio)

        return accept

    @utils.memoize
    def log_likelihood(self, formula):

        W = self.world

        concept = set([obj for obj in W.objects
            if self.grammar.evaluate(formula, obj)])
        not_concept = W.objects - concept
        observed = W.observed_pos | W.observed_neg

        n_wrong = len(W.observed_pos & not_concept)\
            + len(W.observed_neg & concept)

        #return -utils.binomln(len(concept), len(observed & concept))\
        #    - (0 if n_wrong==0 else n_wrong*self.outlier_param)
        return -utils.binomln(len(concept), len(observed & concept))\
            - utils.binomln(len(not_concept), len(observed - concept))\
            - (0 if n_wrong==0 else n_wrong*self.outlier_param)
                # conditional necessary since self.outlier_param could
                # be inf

    def likelihood(self, formula):
        """P(world|formula)"""

        return math.exp(self.log_likelihood(formula))

redpajama_set_name: RedPajamaGithub


text:
var	mapstraction;

function initialize() {
	var	counter = 0;

	mapstraction = new mxn.Mapstraction('map', 'ovi');
	mapstraction.addControls({
    	pan: true,
		zoom: 'small',
		map_type: true
	});
	mapstraction.setCenterAndZoom(new mxn.LatLonPoint(37.75, -122.44), 7);

	mapstraction.click.addHandler(function(event_name, event_source, event_args){
    	var coords = event_args.location;
		var	disp = document.getElementById('events');
		var marker;
		var text;

		disp.innerHTML += "\n" + ++counter + ". Mouse Click at: " +
			coords.lat.toFixed(4) + ' / ' +
			coords.lon.toFixed(4);
		disp.scrollTop = disp.scrollHeight - disp.clientHeight;

        marker = new mxn.Marker(coords);
        text = "
Lat: " + coords.lat.toFixed(4) +
		" Lon: " + coords.lon.toFixed(4) + "
";
        marker.setInfoBubble(text);
        mapstraction.addMarker(marker);
        marker.openBubble();
	});
	mapstraction.changeZoom.addHandler(function(event_name, event_source, event_args){
		var	disp = document.getElementById('events');

		disp.innerHTML += "\n" + ++counter + ". Zoom level changed";
		disp.scrollTop = disp.scrollHeight - disp.clientHeight;
	});

	mapstraction.endPan.addHandler(function(event_name, event_source, event_args){
		var	disp = document.getElementById('events');

		disp.innerHTML += "\n" + ++counter + ". Map panned";
		disp.scrollTop = disp.scrollHeight - disp.clientHeight;
	});

	mapstraction.mousePosition('position');
};


text:
<?php

namespace Weba\Domain\Metric\Uniqueness;

use Weba\Domain\Metric\Criteria\Criteria;

interface Repository
{
    public function findByCriteria(Criteria $criteria): Collection;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="BCN data">

    <title>Sex in the city - BCN data</title>

    <link rel="canonical" href="http://bcndata.cat/en/2016/02/06/gender.en/">

    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <link rel="stylesheet" href="/css/clean-blog.css">

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

    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            BCN data

                    About

                    Català

                    English

                    Español

Sex in the city

The city's surprisingly heterogeneous distribution of men and women

                    Posted by  on February 6, 2016

                        Aquest post en català

                        Este post en español

Some things are best not left to chance

Finding a significant other can be a significant challenge. But ultimately, like so many other things in life, it's a numbers game - the likelihood of finding Mr(s). Right is dependent on the number of Mr(s). Wrongs you're willing to sift through first.

And right or wrong, if you're looking for humans of a particular gender in Barcelona, you're best off not leaving your search to chance alone. There are neighborhoods where men outnumber women 3 to 2. On the other hand, in the most female-dense neighborhood, there are 70% more women than men.

Where to go to find a boyfriend / girlfriend

So, what does the break-down look like? The below map shows the distribution of the sexes by census tract. Use it wisely.

Women flock to the beach. Men run for the hills.

Data sources, code, etc.

As always, the code and data for this post (including source files, cleaning script, visualizations, etc.) can all be found on github.

The data that inspired this post was made accessible by those at BCN Analytics.

                        ← Previous

Copyright © BCN data 2016


text:
from __future__ import unicode_literals

import logging

from django import forms
from django.contrib import messages
from django.forms import widgets
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from djblets.avatars.forms import (
    AvatarSettingsForm as DjbletsAvatarSettingsForm)
from djblets.forms.fields import TimeZoneField
from djblets.siteconfig.models import SiteConfiguration
from djblets.configforms.forms import ConfigPageForm

from reviewboard.accounts.backends import get_enabled_auth_backends
from reviewboard.avatars import avatar_services
from reviewboard.reviews.models import Group
from reviewboard.site.urlresolvers import local_site_reverse

class AccountPageForm(ConfigPageForm):
    """Base class for a form on the My Account page.

    AccountPageForms belong to AccountPages, and will be displayed on the
    My Account page for a user.

    A simple form presents fields that can be filled out and posted.
    More advanced forms can supply their own template or even their own
    JavaScript models and views.
    """

class AccountSettingsForm(AccountPageForm):
    """Form for the Settings page for an account."""

    form_id = 'settings'
    form_title = _('Settings')
    save_label = _('Save Settings')

    timezone = TimeZoneField(
        label=_('Time zone'),
        required=True,
        help_text=_("The time zone you're in."))

    syntax_highlighting = forms.BooleanField(
        label=_('Enable syntax highlighting in the diff viewer'),
        required=False)
    open_an_issue = forms.BooleanField(
        label=_('Always open an issue when comment box opens'),
        required=False)

    should_send_email = forms.BooleanField(
        label=_('Get e-mail notification for review requests and reviews'),
        required=False)

    should_send_own_updates = forms.BooleanField(
        label=_('Get e-mail notifications for my own activity'),
        required=False)

    enable_desktop_notifications = forms.BooleanField(
        label=_('Show desktop notifications'),
        required=False)

    default_use_rich_text = forms.BooleanField(
        label=_('Always use Markdown for text fields'),
        required=False)

    def load(self):
        """Load data for the form."""
        self.set_initial({
            'open_an_issue': self.profile.open_an_issue,
            'should_send_email': self.profile.should_send_email,
            'should_send_own_updates': self.profile.should_send_own_updates,
            'enable_desktop_notifications':
                self.profile.should_enable_desktop_notifications,
            'syntax_highlighting': self.profile.syntax_highlighting,
            'timezone': self.profile.timezone,
            'default_use_rich_text': self.profile.should_use_rich_text,
        })

        siteconfig = SiteConfiguration.objects.get_current()

        if not siteconfig.get('diffviewer_syntax_highlighting'):
            del self.fields['syntax_highlighting']

    def save(self):
        """Save the form."""
        if 'syntax_highlighting' in self.cleaned_data:
            self.profile.syntax_highlighting = \
                self.cleaned_data['syntax_highlighting']

        self.profile.open_an_issue = self.cleaned_data['open_an_issue']
        self.profile.should_send_email = self.cleaned_data['should_send_email']
        self.profile.should_send_own_updates = \
            self.cleaned_data['should_send_own_updates']
        self.profile.settings['enable_desktop_notifications'] = \
            self.cleaned_data['enable_desktop_notifications']
        self.profile.default_use_rich_text = \
            self.cleaned_data['default_use_rich_text']
        self.profile.timezone = self.cleaned_data['timezone']
        self.profile.save()

        messages.add_message(self.request, messages.INFO,
                             _('Your settings have been saved.'))

class AvatarSettingsForm(DjbletsAvatarSettingsForm):
    """A form for configuring the avatar for a user.

    This form will only be shown when avatars are enabled for the server.
    """
    avatar_service_registry = avatar_services

    def is_visible(self):
        """Return whether or not to show the avatar settings form.

        Returns:
            bool:
            Whether or not to show the avatar settings form.
        """
        return (self.avatar_service_registry.avatars_enabled and
                len(self.avatar_service_registry.enabled_services) > 0)

class APITokensForm(AccountPageForm):
    """Form for showing a user's API tokens."""

    form_id = 'api_tokens'
    form_title = _('API Tokens')
    save_label = None

    js_view_class = 'RB.APITokensView'

    def get_js_view_data(self):
        """Get data to pass to the JavaScript view."""
        # Fetch the list of the user's API tokens, globally.
        api_tokens = self.user.webapi_tokens.all()

        # Group the API tokens by LocalSite or the global site.
        serialized_api_tokens = SortedDict()
        serialized_api_tokens[''] = \
            self._serialize_api_tokens(None, api_tokens)

        for local_site in self.page.config_view.ordered_user_local_sites:
            serialized_api_tokens[local_site.name] = \
                self._serialize_api_tokens(local_site, api_tokens)

        return {
            'apiTokens': serialized_api_tokens,
        }

    def _serialize_api_tokens(self, local_site, api_tokens):
        if local_site:
            local_site_prefix = local_site_reverse(
                'root',
                local_site_name=local_site.name)[1:]
        else:
            local_site_prefix = None

        return {
            'localSitePrefix': local_site_prefix,
            'tokens': [
                {
                    'id': api_token.pk,
                    'tokenValue': api_token.token,
                    'timeAdded': api_token.time_added,
                    'lastUpdated': api_token.last_updated,
                    'note': api_token.note,
                    'policy': api_token.policy,
                }
                for api_token in api_tokens
                if api_token.local_site == local_site
            ]
        }

class ChangePasswordForm(AccountPageForm):
    """Form for changing a user's password."""

    form_id = 'change_password'
    form_title = _('Change Password')
    save_label = _('Change Password')

    old_password = forms.CharField(
        label=_('Current password'),
        required=True,
        widget=widgets.PasswordInput())
    password1 = forms.CharField(
        label=_('New password'),
        required=True,
        widget=widgets.PasswordInput())
    password2 = forms.CharField(
        label=_('New password (confirm)'),
        required=True,
        widget=widgets.PasswordInput())

    def is_visible(self):
        """Get whether or not the "change password" form should be shown."""
        backend = get_enabled_auth_backends()[0]

        return backend.supports_change_password

    def clean_old_password(self):
        """Validate the 'old_password' field.

        This checks to make sure the old password is correct when changing the
        password.
        """
        backend = get_enabled_auth_backends()[0]

        password = self.cleaned_data['old_password']

        try:
            is_authenticated = backend.authenticate(self.user.username,
                                                    password)
        except Exception as e:
            logging.error('Error when calling authenticate for auth backend '
                          '%r: %s',
                          backend, e, exc_info=1)
            raise forms.ValidationError(_('Unexpected error when validating '
                                          'the password. Please contact the '
                                          'administrator.'))

        if not is_authenticated:
            raise forms.ValidationError(_('This password is incorrect'))

    def clean_password2(self):
        """Validate the 'password2' field.

        This makes sure that the two password fields match.
        """
        p1 = self.cleaned_data['password1']
        p2 = self.cleaned_data['password2']

        if p1 != p2:
            raise forms.ValidationError(_('Passwords do not match'))

        return p2

    def save(self):
        """Save the form."""
        backend = get_enabled_auth_backends()[0]

        try:
            backend.update_password(self.user, self.cleaned_data['password1'])

            self.user.save()

            messages.add_message(self.request, messages.INFO,
                                 _('Your password has been changed.'))
        except Exception as e:
            logging.error('Error when calling update_password for auth '
                          'backend %r: %s',
                          backend, e, exc_info=1)
            messages.add_message(self.request, messages.INFO,
                                 _('Unexpected error when changing your '
                                   'password. Please contact the '
                                   'administrator.'))

class ProfileForm(AccountPageForm):
    """Form for the Profile page for an account."""

    form_id = 'profile'
    form_title = _('Profile')
    save_label = _('Save Profile')

    first_name = forms.CharField(
        label=_('First name'),
        required=False)
    last_name = forms.CharField(
        label=_('Last name'),
        required=False)
    email = forms.EmailField(
        label=_('E-mail address'),
        required=True)
    profile_private = forms.BooleanField(
        required=False,
        label=_("Keep profile information private"))

    def load(self):
        """Load data for the form."""
        self.set_initial({
            'first_name': self.user.first_name,
            'last_name': self.user.last_name,
            'email': self.user.email,
            'profile_private': self.profile.is_private,
        })

        backend = get_enabled_auth_backends()[0]

        if not backend.supports_change_name:
            del self.fields['first_name']
            del self.fields['last_name']

        if not backend.supports_change_email:
            del self.fields['email']

    def save(self):
        """Save the form."""
        backend = get_enabled_auth_backends()[0]

        if backend.supports_change_name:
            self.user.first_name = self.cleaned_data['first_name']
            self.user.last_name = self.cleaned_data['last_name']

            try:
                backend.update_name(self.user)
            except Exception as e:
                logging.error('Error when calling update_name for auth '
                              'backend %r: %s',
                              backend, e, exc_info=1)

        if backend.supports_change_email:
            new_email = self.cleaned_data['email']

            if new_email != self.user.email:
                self.user.email = new_email

                try:
                    backend.update_email(self.user)
                except Exception as e:
                    logging.error('Error when calling update_email for auth '
                                  'backend %r: %s',
                                  backend, e, exc_info=1)

        self.user.save()

        self.profile.is_private = self.cleaned_data['profile_private']
        self.profile.save()

        messages.add_message(self.request, messages.INFO,
                             _('Your profile has been saved.'))

class GroupsForm(AccountPageForm):
    """Form for the group membership page.

    Unlike most forms, this doesn't deal with fields or saving to the database.
    Instead, it sets up the JavaScript View and provides serialized data
    representing the groups. The View handles group membership through the
    API.
    """

    form_id = 'groups'
    form_title = _('Groups')
    save_label = None

    js_view_class = 'RB.JoinedGroupsView'

    def get_js_view_data(self):
        """Get data to pass to the JavaScript view."""
        # Fetch the list of IDs of groups the user has joined.
        joined_group_ids = self.user.review_groups.values_list('pk', flat=True)

        # Fetch the list of groups available to the user.
        serialized_groups = SortedDict()
        serialized_groups[''] = self._serialize_groups(None, joined_group_ids)

        for local_site in self.page.config_view.ordered_user_local_sites:
            serialized_groups[local_site.name] = self._serialize_groups(
                local_site, joined_group_ids)

        return {
            'groups': serialized_groups,
        }

    def _serialize_groups(self, local_site, joined_group_ids):
        if local_site:
            local_site_name = local_site.name
        else:
            local_site_name = None

        groups = Group.objects.accessible(user=self.user,
                                          local_site=local_site)
        return [
            {
                'name': group.name,
                'reviewGroupID': group.pk,
                'displayName': group.display_name,
                'localSiteName': local_site_name,
                'joined': group.pk in joined_group_ids,
                'url': local_site_reverse('group',
                                          local_site_name=local_site_name,
                                          kwargs={'name': group.name}),
            }
            for group in groups.order_by('name')
        ]


text:
p.test a { background-color : red }
p.test *:link { background-color : lime }


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'rack/read_only'


text:
var assert = require('../lib/extended-assert'),
    figaro = require('../../index');

log.level = 'silent';

describe('figaro.travis', function () {
    describe('#getPublicKey', function () {
        it('should find public key', function (done) {
            this.timeout(figaro.travis.networkTimeout);
            figaro.travis.getPublicKey(null, function (err, publicKey) {
                assert.ok(!err);
                assert.ok(publicKey);
                done();
            });
        });

        it('should not find public key', function (done) {
            this.timeout(figaro.travis.networkTimeout);
            figaro.travis.getPublicKey('mysuperbogus/slug-that-shoud-not-exist', function (err, publicKey) {
                assert.ok(err);
                assert.ok(!publicKey);
                done();
            });
        });
    });
});


text:
<?php

//define core class
if (!class_exists('FramePress_WordPress_002')) {
class FramePress_WordPress_002
{

	public $pages = array();

	public $hooks = array();

	public $shortcodes = array();

	public $metaboxes = array();

	public $Core = null;

	public function __construct(&$fp)
	{
		$this->Core = $fp;

		add_action('admin_menu', array($this, 'addAdminPagesReal'));
		add_action('add_meta_boxes', array($this, 'addMetaboxesReal'));
	}

	public function addAdminPage($type, $page = array())
	{
		$this->adminPages(array($type => array($page)));
	}

	public function adminPages($pages = array())
	{
		foreach ($pages as $type => $childs) {
			for ($i=0; $i<count($childs); $i++) {
				$page = $this->populatePage($childs[$i]);
				$this->pages[$type][] = $page;
			}
		}
	}

	public function addAdminPagesReal()
	{
		foreach ($this->pages as $type => $pages){
			for($i=0; $i<count($pages); $i++){

				$page = $pages[$i];

				switch($type) {
					case 'menu':
						add_menu_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback'], $page['icon'], $page['position'] );
					break;
					case 'submenu':
						add_submenu_page( $page['parent.slug'], $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'dashboard':
						add_dashboard_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'posts':
						add_posts_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'media':
						add_media_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'links':
						add_links_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'pages':
						add_pages_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'comments':
						add_comments_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'appearance':
						add_theme_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'plugins':
						add_plugins_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'users':
						add_users_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'tools':
						add_management_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					case 'settings':
						add_options_page( $page['page.title'], $page['menu.title'], $page['capability'], $page['menu.slug'], $page['callback']);
					break;
					default:break;
				}
			}
		}
	}

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

	public function addShortcode($shortcode)
	{
		$this->shortcodes(array($shortcode));
	}

	public function shortcodes( $shortcodes=array() )
	{
		foreach ($shortcodes as $sc){
			$this->shortcodes[] = $sc = $this->populateShortcode($sc);
			add_shortcode($sc['tag'] , $sc['callback']);
		}
	}

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

	public function addAction($action)
	{
		$this->hooks(array($action));
	}

	public function addFilter($filter)
	{
		$this->hooks(array($filter));
	}

	public function hooks( $hooks=array() )
	{
		foreach ($hooks as $hook) {

			$this->hooks[] = $hook = $this->populateHook($hook);
			foreach ($hook['callback'] as $tag => $callback) {

				if (!$hook['is_ajax']) {
					add_action($tag, $callback, $hook['priority'], $hook['accepted_args']);
				} else {

					if (in_array($hook['is_ajax'], array(true, 'both', 'private'))) {
						add_action('wp_ajax_' . $tag, $callback, $hook['priority'], $hook['accepted_args']);
					}

					if (in_array($hook['is_ajax'], array(true, 'both', 'public'))) {
						add_action('wp_ajax_nopriv_' . $tag, $callback, $hook['priority'], $hook['accepted_args']);
					}
				}
			}
		}
	}

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

	public function addMetabox($metabox)
	{
		$this->metaboxes(array($metabox));
	}

	public function metaboxes ($metaboxes = array())
	{
		$metab_defaults = array('id'=> null, 'title'=> null, 'post_type'=> null, 'context'=> 'advanced', 'priority'=>null, 'callback_args' => null, 'controller'=> null, 'function'=> null);

		foreach ($metaboxes as $mb){
			$mb = $this->populateMetabox($mb);
			$this->metaboxes[] = $mb;
		}
	}

	public function addMetaboxesReal ($postType)
	{
		foreach ($this->metaboxes as $mb){
			if(in_array($postType, (array)$mb['post_type'])){
				add_meta_box( $mb['id'], $mb['title'], $mb['callback'], $postType, $mb['context'], $mb['priority'], $mb['callback_args'] );
			}
		}
	}

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

	public function router ($url=array())
	{
		//string pased, nothing to do
		if (!is_array($url)){ return $url; }

		//complete $url
		$defaults = array('menu_type' => null, 'controller' => null, 'function'=> null, 'params'=> '');
		$url = array_merge($defaults, $url);

		//search menu slug
		if($url['controller']){
			$aux_slug = $this->config['prefix'] . '-' . $url['controller'];
			foreach ($this->pages as $type => $pages){
				for($i=0; $i<count($pages); $i++){
					if (strpos($pages[$i]['menu.slug'], $aux_slug) !== false) {
						$url['menu.slug'] = $pages[$i]['menu.slug'];
						if(!$url['menu_type']){ $url['menu_type'] = $type; }
					}
				}
			}
		}

		//correct values
		$url['controller'] = ($url['controller'])? $url['menu.slug'] : $_GET['page'];
		$url['function'] = ($url['function'])?'&function='.$url['function']:'';

		//parameter to the funcion
		foreach($url as $key =>$value) {
			if(preg_match("/^[[:digit:]]+$/", $key)) { $url['params'].='&fargs[]='.urlencode($value); }
		}

		$wpurl = get_bloginfo('wpurl');
		switch ($url['menu_type']){
			case 'menu':		$base = $wpurl.'/wp-admin/admin.php?'; break;
			case 'dashboard':	$base = $wpurl.'/wp-admin/index.php?'; break;
			case 'posts':		$base = $wpurl.'/wp-admin/edit.php?'; break;
			case 'media':		$base = $wpurl.'/wp-admin/upload.php?'; break;
			case 'links':		$base = $wpurl.'/wp-admin/link-manager.php?'; break;
			case 'pages':		$base = $wpurl.'/wp-admin/edit.php?post_type=page&'; break;
			case 'comments':	$base = $wpurl.'/wp-admin/edit-comments.php?'; break;
			case 'appearance':	$base = $wpurl.'/wp-admin/themes.php?'; break;
			case 'plugins':		$base = $wpurl.'/wp-admin/plugins.php?'; break;
			case 'users':		$base = $wpurl.'/wp-admin/users.php?'; break;
			case 'tools':		$base = $wpurl.'/wp-admin/tools.php?'; break;
			case 'settings':	$base = $wpurl.'/wp-admin/options-general.php?'; break;
			default: 			$base = $_SERVER['PHP_SELF'].'?'; break;
		}

		return $base . 'page=' . $url['controller'] . $url['function'] . $url['params'];
	}

	private function populateHook($hook)
	{
		//populate missing/default info
		$hook_defaults = array('tag'=> null, 'controller' => null, 'function' => null, 'is_ajax'=> false, 'priority' => 10, 'accepted_args' => 1);
		$hook = array_merge($hook_defaults, $hook);

		if (!is_array($hook['tag'])) {
			$hook['tag'] = (array)$hook['tag'];
		}

		foreach ($hook['tag'] as $t) {
			$hook['callback'][$t] = array($this->Core->Dispatcher, 'hook' . '__AYNIL__' . $hook['controller'] . '__AYNIL__' . $hook['function'] . '__AYNIL__' . $t);
		}

		return $hook;
	}

	private function populateMetabox($mb)
	{
		$metabox_defaults = array('id'=> null, 'title'=> null, 'post_type'=> null, 'context'=> 'advanced', 'priority'=>null, 'callback_args' => null, 'controller'=> null, 'function'=> null);
		$mb = array_merge($metabox_defaults, $mb);
		$mb['callback'] = array($this->Core->Dispatcher, 'metabox' . '__AYNIL__' . $mb['controller'] . '__AYNIL__' . $mb['function'] . '__AYNIL__' . $mb['id']);
		return $mb;
	}

	private function populateShortcode($sc)
	{
		$short_defaults = array('tag'=> null, 'controller'=> null, 'function'=> null);
		$sc = array_merge($short_defaults, $sc);
		$sc['callback'] =  array($this->Core->Dispatcher, 'shortcode' . '__AYNIL__' . $sc['controller'] . '__AYNIL__' . $sc['function'] . '__AYNIL__' . $sc['tag']);
		return $sc;
	}

	private function populatePage($page= array())
	{
		//populate missing/default info
		$page_defaults = array('page.title'=> null, 'menu.title'=> null, 'capability'=> null, 'controller'=> null, 'function'=>'index', 'parent'=> null, 'icon'=> null, 'position'=> null);
		$page = array_merge($page_defaults, $page);

		//generate url for image selected
		if ( $page['icon'] && file_exists( $this->Core->paths['img'] . DS . $page['icon'])) {
			$page['icon'] =  $this->Core->paths['img.url'] . DS . $page['icon'];
		}

		//generate slug for this menu
		$page['menu.slug'] = sanitize_title($this->Core->config['prefix'] . ' ' . $page['menu.title']);

		//find parent menu
		if ($page['parent']){
			$menus = (isset($this->pages['menu']))?$this->pages['menu']:array();
			for ($p=0; $p < count($menus); $p++){
				if( $menus[$p]['menu.title'] == $page['parent'] ) {
					$page['parent.slug'] = sanitize_title($this->Core->config['prefix'] . ' ' . $menus[$p]['menu.title']);
					break;
				}
			}
			if(!isset($page['parent.slug'] )){ $page['parent.slug'] = $page['parent']; }
		}

		//callback
		$page['callback'] =  array($this->Core->Dispatcher, 'adminpage' . '__AYNIL__' . $page['controller'] . '__AYNIL__' . $page['function'] . '__AYNIL__' . $page['menu.slug']);

		return $page;
	}

}//end class
}//end if class exist

//Export framework className
$GLOBALS["FramePressWordPress"] = 'FramePress_WordPress_002';
$FramePressWordPress = 'FramePress_WordPress_002';


text:
var Konami = function (callback) {
        var konami = {
                addEvent: function (obj, type, fn, ref_obj) {
                        if (obj.addEventListener)
                                obj.addEventListener(type, fn, false);
                        else if (obj.attachEvent) {
                                // IE
                                obj["e" + type + fn] = fn;
                                obj[type + fn] = function () {
                                        obj["e" + type + fn](window.event, ref_obj);
                                }
                                obj.attachEvent("on" + type, obj[type + fn]);
                        }
                },
                input: "",
                pattern: "38384040373937396665",
                load: function (link) {
                        this.addEvent(document, "keydown", function (e, ref_obj) {
                                if (ref_obj) konami = ref_obj; // IE
                                konami.input += e ? e.keyCode : event.keyCode;
                                if (konami.input.length > konami.pattern.length)
                                        konami.input = konami.input.substr((konami.input.length - konami.pattern.length));
                                if (konami.input == konami.pattern) {
                                        konami.code(link);
                                        konami.input = "";
                                        e.preventDefault();
                                        return false;
                                }
                        }, this);
                        this.iphone.load(link);
                },
                code: function (link) {
                        window.location = link
                },
                iphone: {
                        start_x: 0,
                        start_y: 0,
                        stop_x: 0,
                        stop_y: 0,
                        tap: false,
                        capture: false,
                        orig_keys: "",
                        keys: ["UP", "UP", "DOWN", "DOWN", "LEFT", "RIGHT", "LEFT", "RIGHT", "TAP", "TAP"],
                        code: function (link) {
                                konami.code(link);
                        },
                        load: function (link) {
                                this.orig_keys = this.keys;
                                konami.addEvent(document, "touchmove", function (e) {
                                        if (e.touches.length == 1 && konami.iphone.capture == true) {
                                                var touch = e.touches[0];
                                                konami.iphone.stop_x = touch.pageX;
                                                konami.iphone.stop_y = touch.pageY;
                                                konami.iphone.tap = false;
                                                konami.iphone.capture = false;
                                                konami.iphone.check_direction();
                                        }
                                });
                                konami.addEvent(document, "touchend", function (evt) {
                                        if (konami.iphone.tap == true) konami.iphone.check_direction(link);
                                }, false);
                                konami.addEvent(document, "touchstart", function (evt) {
                                        konami.iphone.start_x = evt.changedTouches[0].pageX;
                                        konami.iphone.start_y = evt.changedTouches[0].pageY;
                                        konami.iphone.tap = true;
                                        konami.iphone.capture = true;
                                });
                        },
                        check_direction: function (link) {
                                x_magnitude = Math.abs(this.start_x - this.stop_x);
                                y_magnitude = Math.abs(this.start_y - this.stop_y);
                                x = ((this.start_x - this.stop_x) < 0) ? "RIGHT" : "LEFT";
                                y = ((this.start_y - this.stop_y) < 0) ? "DOWN" : "UP";
                                result = (x_magnitude > y_magnitude) ? x : y;
                                result = (this.tap == true) ? "TAP" : result;

                                if (result == this.keys[0]) this.keys = this.keys.slice(1, this.keys.length);
                                if (this.keys.length == 0) {
                                        this.keys = this.orig_keys;
                                        this.code(link);
                                }
                        }
                }
        }

        typeof callback === "string" && konami.load(callback);
        if (typeof callback === "function") {
                konami.code = callback;
                konami.load();
        }

        return konami;
};

function nederen() {
      audior = document.createElement("audio");
      audior.src = ['resources/kedeligt/musik.mp3'] ;
      audio.addEventListener("ended",function() {
    audior.src = songs[Math.floor(Math.random() * songs.length)]
    audior.play();
      })
      audior.play();
    };

    var easter_egg =
new Konami(
function () {
    audio.pause();
    nederen();
    $('#wrapper').css('background', 'url(images/kedeligt.png) no-repeat');
    $('#wrapper').css('color', 'rgb(255,255,255)');
    $('#wrapper').css('padding-bottom', '0px');

    $('body').css('background-image', 'url(resources/kedeligt/skidt.gif)');
    $('#wrapper').empty();

}
           );


text:
package com.streamsets.pipeline.stage.origin.udp;

import com.streamsets.pipeline.api.ConfigDef;
import com.streamsets.pipeline.api.ConfigGroups;
import com.streamsets.pipeline.api.ExecutionMode;
import com.streamsets.pipeline.api.FieldSelectorModel;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Source;
import com.streamsets.pipeline.api.StageDef;
import com.streamsets.pipeline.api.ValueChooserModel;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.config.CharsetChooserValues;
import com.streamsets.pipeline.configurablestage.DSource;
import com.streamsets.pipeline.lib.parser.net.netflow.NetflowDataParserFactory;
import com.streamsets.pipeline.lib.parser.net.netflow.OutputValuesMode;
import com.streamsets.pipeline.lib.parser.net.netflow.OutputValuesModeChooserValues;
import com.streamsets.pipeline.lib.parser.net.raw.RawDataMode;
import com.streamsets.pipeline.lib.parser.net.raw.RawDataModeChooserValues;
import com.streamsets.pipeline.lib.parser.udp.ParserConfig;
import com.streamsets.pipeline.config.DatagramMode;
import com.streamsets.pipeline.config.DatagramModeChooserValues;
import com.streamsets.pipeline.stage.common.MultipleValuesBehavior;
import com.streamsets.pipeline.stage.common.MultipleValuesBehaviorChooserValues;
import org.apache.commons.lang3.StringEscapeUtils;

import java.util.List;

import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.AUTH_FILE_PATH;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.CHARSET;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.CONVERT_TIME;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.EXCLUDE_INTERVAL;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.NETFLOW_MAX_TEMPLATE_CACHE_SIZE;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.NETFLOW_OUTPUT_VALUES_MODE;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.NETFLOW_TEMPLATE_CACHE_TIMEOUT_MS;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.RAW_DATA_MODE;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.RAW_DATA_MULTIPLE_VALUES_BEHAVIOR;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.RAW_DATA_OUTPUT_FIELD_PATH;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.RAW_DATA_SEPARATOR_BYTES;
import static com.streamsets.pipeline.lib.parser.udp.ParserConfigKey.TYPES_DB_PATH;

@StageDef(
    version = 3,
    label = "UDP Source",
    description = "Listens for UDP messages on a single port",
    icon = "udp.png",
    execution = ExecutionMode.STANDALONE,
    recordsByRef = true,
    upgrader = UDPSourceUpgrader.class,
    onlineHelpRefUrl = "index.html#Origins/UDP.html#task_kgn_rcv_1s"
)

@ConfigGroups(Groups.class)
@GenerateResourceBundle
public class UDPDSource extends DSource {
  public static final String DEFAULT_RAW_DATA_MODE_STR = "CHARACTER";
  public static final RawDataMode DEFAULT_RAW_DATA_MODE = RawDataMode.valueOf(DEFAULT_RAW_DATA_MODE_STR);
  public static final String DEFAULT_RAW_DATA_CHARSET = "UTF-8";
  public static final String DEFAULT_RAW_DATA_OUTPUT_FIELD = "/data";
  public static final String DEFAULT_RAW_DATA_MULTI_VALUES_BEHAVIOR_STR = "FIRST_ONLY";
  public static final MultipleValuesBehavior DEFAULT_RAW_DATA_MULTI_VALUES_BEHAVIOR = MultipleValuesBehavior.valueOf(
      DEFAULT_RAW_DATA_MULTI_VALUES_BEHAVIOR_STR
  );
  public static final String DEFAULT_RAW_DATA_SEPARATOR_BYTES = "\\u000A";

  private ParserConfig parserConfig = new ParserConfig();

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.LIST,
      label = "Port",
      defaultValue = "[\"9995\"]",
      description = "Port to listen on",
      group = "UDP",
      displayPosition = 10
  )
  public List<String> ports; // string so we can listen on multiple ports in the future

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.BOOLEAN,
      label = "Enable Multithreading",
      description = "Use multiple receiver threads for each port. Only available on 64-bit Linux systems",
      defaultValue = "false",
      group = "UDP",
      displayPosition = 15
  )
  public boolean enableEpoll;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.NUMBER,
      label = "Number of Receiver Threads",
      description = "Number of receiver threads for each port. It should be based on the CPU cores expected to be dedicated to the pipeline",
      defaultValue = "1",
      group = "UDP",
      dependsOn = "enableEpoll",
      triggeredByValue = "true",
      displayPosition = 16
  )
  public int numThreads;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      label = "Data Format",
      defaultValue = "SYSLOG",
      group = "UDP",
      displayPosition = 20
  )
  @ValueChooserModel(DatagramModeChooserValues.class)
  public DatagramMode dataFormat;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.NUMBER,
      defaultValue = "1000",
      label = "Max Batch Size (messages)",
      group = "UDP",
      displayPosition = 30,
      min = 0,
      max = Integer.MAX_VALUE
  )
  public int batchSize;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.NUMBER,
      defaultValue = "1000",
      label = "Batch Wait Time (ms)",
      description = "Max time to wait for data before sending a batch",
      displayPosition = 40,
      group = "UDP",
      min = 1,
      max = Integer.MAX_VALUE
  )
  public int maxWaitTime;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue = "UTF-8",
      label = "Charset",
      displayPosition = 5,
      group = "SYSLOG",
      dependsOn = "dataFormat",
      triggeredByValue = "SYSLOG"
  )
  @ValueChooserModel(CharsetChooserValues.class)
  public String syslogCharset;

  @ConfigDef(
      required = false,
      type = ConfigDef.Type.STRING,
      label = "TypesDB File Path",
      description = "User-specified TypesDB file. Overrides the included version.",
      displayPosition = 10,
      group = "COLLECTD",
      dependsOn = "dataFormat",
      triggeredByValue = "COLLECTD"
  )
  public String typesDbPath;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.BOOLEAN,
      defaultValue = "false",
      label = "Convert Hi-Res Time & Interval",
      description = "Converts high resolution time format interval and timestamp to unix time in (ms).",
      displayPosition = 20,
      group = "COLLECTD",
      dependsOn = "dataFormat",
      triggeredByValue = "COLLECTD"
  )
  public boolean convertTime;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.BOOLEAN,
      defaultValue = "true",
      label = "Exclude Interval",
      description = "Excludes the interval field from output records.",
      displayPosition = 30,
      group = "COLLECTD",
      dependsOn = "dataFormat",
      triggeredByValue = "COLLECTD"
  )
  public boolean excludeInterval;

  @ConfigDef(
      required = false,
      type = ConfigDef.Type.STRING,
      label = "Auth File",
      description = "",
      displayPosition = 40,
      group = "COLLECTD",
      dependsOn = "dataFormat",
      triggeredByValue = "COLLECTD"
  )
  public String authFilePath;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue = "UTF-8",
      label = "Charset",
      displayPosition = 50,
      group = "COLLECTD",
      dependsOn = "dataFormat",
      triggeredByValue = "COLLECTD"
  )
  @ValueChooserModel(CharsetChooserValues.class)
  public String collectdCharset;

  // Netflow v9
  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue = NetflowDataParserFactory.DEFAULT_OUTPUT_VALUES_MODE_STR,
      label = NetflowDataParserFactory.OUTPUT_VALUES_MODE_LABEL,
      description = NetflowDataParserFactory.OUTPUT_VALUES_MODE_TOOLTIP,
      displayPosition = 80,
      group = "NETFLOW_V9",
      dependsOn = "dataFormat",
      triggeredByValue = "NETFLOW"
  )
  @ValueChooserModel(OutputValuesModeChooserValues.class)
  public OutputValuesMode netflowOutputValuesMode = NetflowDataParserFactory.DEFAULT_OUTPUT_VALUES_MODE;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.NUMBER,
      defaultValue = NetflowDataParserFactory.DEFAULT_MAX_TEMPLATE_CACHE_SIZE_STR,
      label = NetflowDataParserFactory.MAX_TEMPLATE_CACHE_SIZE_LABEL,
      description = NetflowDataParserFactory.MAX_TEMPLATE_CACHE_SIZE_TOOLTIP,
      displayPosition = 90,
      group = "NETFLOW_V9",
      dependsOn = "dataFormat",
      triggeredByValue = "NETFLOW"
  )
  public int maxTemplateCacheSize = NetflowDataParserFactory.DEFAULT_MAX_TEMPLATE_CACHE_SIZE;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.NUMBER,
      defaultValue = NetflowDataParserFactory.DEFAULT_TEMPLATE_CACHE_TIMEOUT_MS_STR,
      label = NetflowDataParserFactory.TEMPLATE_CACHE_TIMEOUT_MS_LABEL,
      description = NetflowDataParserFactory.TEMPLATE_CACHE_TIMEOUT_MS_TOOLTIP,
      displayPosition = 100,
      group = "NETFLOW_V9",
      dependsOn = "dataFormat",
      triggeredByValue = "NETFLOW"
  )
  public int templateCacheTimeoutMs = NetflowDataParserFactory.DEFAULT_TEMPLATE_CACHE_TIMEOUT_MS;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue = DEFAULT_RAW_DATA_MODE_STR,
      label = "Raw Data Mode",
      description = "The mode that controls how the raw packet data should be treated (character-based or binary)." +
          " This selection determines what type of field will be created.",
      displayPosition = 110,
      group = "RAW_DATA",
      dependsOn = "dataFormat",
      triggeredByValue = "RAW_DATA"
  )
  @ValueChooserModel(RawDataModeChooserValues.class)
  public RawDataMode rawDataMode = DEFAULT_RAW_DATA_MODE;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue = DEFAULT_RAW_DATA_CHARSET,
      label = "Charset",
      description = "The character set used to interpret character-based separated data.",
      displayPosition = 120,
      group = "RAW_DATA",
      dependsOn = "rawDataMode",
      triggeredByValue = "CHARACTER"
  )
  @ValueChooserModel(CharsetChooserValues.class)
  public String rawDataCharset = DEFAULT_RAW_DATA_CHARSET;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue = DEFAULT_RAW_DATA_OUTPUT_FIELD,
      label = "Output field path",
      description = "The output field path to place the separated data values into.",
      displayPosition = 150,
      group = "RAW_DATA",
      dependsOn = "dataFormat",
      triggeredByValue = "RAW_DATA"
  )
  @FieldSelectorModel(singleValued = true)
  public String rawDataOutputField = DEFAULT_RAW_DATA_OUTPUT_FIELD;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      label = "Multiple Values Behavior",
      description = "How to handle multiple values produced by the parser after applying the separator.",
      defaultValue = DEFAULT_RAW_DATA_MULTI_VALUES_BEHAVIOR_STR,
      displayPosition = 160,
      group = "RAW_DATA",
      dependsOn = "dataFormat",
      triggeredByValue = "RAW_DATA"
  )
  @ValueChooserModel(MultipleValuesBehaviorChooserValues.class)
  public MultipleValuesBehavior rawDataMultipleValuesBehavior = DEFAULT_RAW_DATA_MULTI_VALUES_BEHAVIOR;

  @ConfigDef(
      required = false,
      type = ConfigDef.Type.STRING,
      label = "Data Separator",
      description = "The bytes to use to separate data in the UDP packet.  If multiple values are found in a packet" +
          " after applying this separator, then the Multiple Values Behavior setting comes into play..  Specify byte" +
          " literals using using Java Unicode syntax (\"\\uxxxx\").  To capture the entire UDP packet (i.e. do not split" +
          " using any delimiter), leave this blank.  Defaults to line feed (000A).",
      defaultValue = DEFAULT_RAW_DATA_SEPARATOR_BYTES,
      group = "RAW_DATA",
      dependsOn = "dataFormat",
      triggeredByValue = "RAW_DATA"
  )
  public String rawDataSeparatorBytes = DEFAULT_RAW_DATA_SEPARATOR_BYTES;

  @Override
  protected Source createSource() {
    Utils.checkNotNull(dataFormat, "Data format cannot be null");
    Utils.checkNotNull(ports, "Ports cannot be null");

    switch (dataFormat) {
      case SYSLOG:
        parserConfig.put(CHARSET, syslogCharset);
        break;
      case COLLECTD:
        parserConfig.put(CHARSET, collectdCharset);
        break;
      case RAW_DATA:
        parserConfig.put(CHARSET, rawDataCharset);
        parserConfig.put(RAW_DATA_MODE, rawDataMode);
        parserConfig.put(RAW_DATA_MULTIPLE_VALUES_BEHAVIOR, rawDataMultipleValuesBehavior);
        parserConfig.put(RAW_DATA_OUTPUT_FIELD_PATH, rawDataOutputField);
        parserConfig.put(
            RAW_DATA_SEPARATOR_BYTES,
            StringEscapeUtils.unescapeJava(rawDataSeparatorBytes).getBytes()
        );
        break;
      case NETFLOW:
        parserConfig.put(NETFLOW_OUTPUT_VALUES_MODE, netflowOutputValuesMode);
        parserConfig.put(NETFLOW_MAX_TEMPLATE_CACHE_SIZE, maxTemplateCacheSize);
        parserConfig.put(NETFLOW_TEMPLATE_CACHE_TIMEOUT_MS, templateCacheTimeoutMs);
        break;
      default:
        // NOOP
    }

    parserConfig.put(CONVERT_TIME, convertTime);
    parserConfig.put(TYPES_DB_PATH, typesDbPath);
    parserConfig.put(EXCLUDE_INTERVAL, excludeInterval);
    parserConfig.put(AUTH_FILE_PATH, authFilePath);

    // Force single thread if epoll not enabled.
    if (!enableEpoll) {
      numThreads = 1;
    }
    return new UDPSource(ports, enableEpoll, numThreads, parserConfig, dataFormat, batchSize, maxWaitTime);
  }
}


text:
import type { QueryThunk, RejectedAction } from '../buildThunks'
import type { InternalHandlerBuilder } from './types'
import type {
  SubscriptionState,
  QuerySubstateIdentifier,
  Subscribers,
} from '../apiState'
import { produceWithPatches } from 'immer'
import { createSlice, PayloadAction, AnyAction } from '@reduxjs/toolkit'

// Copied from https://github.com/feross/queue-microtask
let promise: Promise<any>
const queueMicrotaskShim =
  typeof queueMicrotask === 'function'
    ? queueMicrotask.bind(
        typeof window !== 'undefined'
          ? window
          : typeof global !== 'undefined'
          ? global
          : globalThis
      )
    : // reuse resolved promise, and allocate it lazily
      (cb: () => void) =>
        (promise || (promise = Promise.resolve())).then(cb).catch((err: any) =>
          setTimeout(() => {
            throw err
          }, 0)
        )

export const buildBatchedActionsHandler: InternalHandlerBuilder<
  [actionShouldContinue: boolean, subscriptionExists: boolean]
> = ({ api, queryThunk, internalState }) => {
  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`

  let previousSubscriptions: SubscriptionState =
    null as unknown as SubscriptionState

  let dispatchQueued = false

  const { updateSubscriptionOptions, unsubscribeQueryResult } =
    api.internalActions

  // Actually intentionally mutate the subscriptions state used in the middleware
  // This is done to speed up perf when loading many components
  const actuallyMutateSubscriptions = (
    mutableState: SubscriptionState,
    action: AnyAction
  ) => {
    if (updateSubscriptionOptions.match(action)) {
      const { queryCacheKey, requestId, options } = action.payload

      if (mutableState?.[queryCacheKey]?.[requestId]) {
        mutableState[queryCacheKey]![requestId] = options
      }
      return true
    }
    if (unsubscribeQueryResult.match(action)) {
      const { queryCacheKey, requestId } = action.payload
      if (mutableState[queryCacheKey]) {
        delete mutableState[queryCacheKey]![requestId]
      }
      return true
    }
    if (api.internalActions.removeQueryResult.match(action)) {
      delete mutableState[action.payload.queryCacheKey]
      return true
    }
    if (queryThunk.pending.match(action)) {
      const {
        meta: { arg, requestId },
      } = action
      if (arg.subscribe) {
        const substate = (mutableState[arg.queryCacheKey] ??= {})
        substate[requestId] =
          arg.subscriptionOptions ?? substate[requestId] ?? {}

        return true
      }
    }
    if (queryThunk.rejected.match(action)) {
      const {
        meta: { condition, arg, requestId },
      } = action
      if (condition && arg.subscribe) {
        const substate = (mutableState[arg.queryCacheKey] ??= {})
        substate[requestId] =
          arg.subscriptionOptions ?? substate[requestId] ?? {}

        return true
      }
    }

    return false
  }

  return (action, mwApi) => {
    if (!previousSubscriptions) {
      // Initialize it the first time this handler runs
      previousSubscriptions = JSON.parse(
        JSON.stringify(internalState.currentSubscriptions)
      )
    }

    // Intercept requests by hooks to see if they're subscribed
    // Necessary because we delay updating store state to the end of the tick
    if (api.internalActions.internal_probeSubscription.match(action)) {
      const { queryCacheKey, requestId } = action.payload
      const hasSubscription =
        !!internalState.currentSubscriptions[queryCacheKey]?.[requestId]
      return [false, hasSubscription]
    }

    // Update subscription data based on this action
    const didMutate = actuallyMutateSubscriptions(
      internalState.currentSubscriptions,
      action
    )

    if (didMutate) {
      if (!dispatchQueued) {
        queueMicrotaskShim(() => {
          // Deep clone the current subscription data
          const newSubscriptions: SubscriptionState = JSON.parse(
            JSON.stringify(internalState.currentSubscriptions)
          )
          // Figure out a smaller diff between original and current
          const [, patches] = produceWithPatches(
            previousSubscriptions,
            () => newSubscriptions
          )

          // Sync the store state for visibility
          mwApi.next(api.internalActions.subscriptionsUpdated(patches))
          // Save the cloned state for later reference
          previousSubscriptions = newSubscriptions
          dispatchQueued = false
        })
        dispatchQueued = true
      }

      const isSubscriptionSliceAction =
        !!action.type?.startsWith(subscriptionsPrefix)
      const isAdditionalSubscriptionAction =
        queryThunk.rejected.match(action) &&
        action.meta.condition &&
        !!action.meta.arg.subscribe

      const actionShouldContinue =
        !isSubscriptionSliceAction && !isAdditionalSubscriptionAction

      return [actionShouldContinue, false]
    }

    return [true, false]
  }
}


text:
module Spreedly

  class Purchase < AuthPurchase

  end

end


text:
namespace UniShop.Data.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class AddFeedBack : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(AddFeedBack));

        string IMigrationMetadata.Id
        {
            get { return "201706141246181_Add  FeedBack"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
/**
 * @class Ext4.ux.DataView.LabelEditor
 * @extends Ext4.Editor
 */
Ext4.define('Ext4.ux.DataView.LabelEditor', {

    extend: 'Ext4.Editor',

    alignment: 'tl-tl',

    completeOnEnter: true,

    cancelOnEsc: true,

    shim: false,

    autoSize: {
        width: 'boundEl',
        height: 'field'
    },

    labelSelector: 'x-editable',

    requires: [
        'Ext4.form.field.Text'
    ],

    constructor: function(config) {
        config.field = config.field || Ext4.create('Ext4.form.field.Text', {
            allowBlank: false,
            selectOnFocus:true
        });
        this.callParent([config]);
    },

    init: function(view) {
        this.view = view;
        this.mon(view, 'render', this.bindEvents, this);
        this.on('complete', this.onSave, this);
    },

    // initialize events
    bindEvents: function() {
        this.mon(this.view.getEl(), {
            click: {
                fn: this.onClick,
                scope: this
            }
        });
    },

    // on mousedown show editor
    onClick: function(e, target) {
        var me = this,
            item, record;

        if (Ext4.fly(target).hasCls(me.labelSelector) && !me.editing && !e.ctrlKey && !e.shiftKey) {
            e.stopEvent();
            item = me.view.findItemByChild(target);
            record = me.view.store.getAt(me.view.indexOf(item));
            me.startEdit(target, record.data[me.dataIndex]);
            me.activeRecord = record;
        } else if (me.editing) {
            me.field.blur();
            e.preventDefault();
        }
    },

    // update record
    onSave: function(ed, value) {
        this.activeRecord.set(this.dataIndex, value);
    }
});


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

<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.solr.util.stats.EWMA (Solr 4.4.0 API)
</TITLE>

<META NAME="date" CONTENT="2013-07-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.solr.util.stats.EWMA

Packages that use EWMA

org.apache.solr.util.stats

Utilities for collecting statistics

Uses of EWMA in org.apache.solr.util.stats

Methods in org.apache.solr.util.stats that return EWMA

static EWMA
EWMA.fifteenMinuteEWMA()

          Creates a new EWMA which is equivalent to the UNIX fifteen minute load average and which
 expects to be ticked every 5 seconds.

static EWMA
EWMA.fiveMinuteEWMA()

          Creates a new EWMA which is equivalent to the UNIX five minute load average and which expects
 to be ticked every 5 seconds.

static EWMA
EWMA.oneMinuteEWMA()

          Creates a new EWMA which is equivalent to the UNIX one minute load average and which expects
 to be ticked every 5 seconds.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

          Copyright © 2000-2013 Apache Software Foundation.  All Rights Reserved.


text:
""" Implements generic caching as well as a caching decorator. """

__author__ = "Johannes Stuettgen <johannes.stuettgen@gmail.com>"

def lru_cache(func, maxsize=None):
    """ Decorator to use LRUCache on function arguments.

    If maxsize is not provided we use a Python dict instead,
    to provide an infinite cache. This can cause the Python process
    to run out of memory and crash.

    However, it allows for simple memoization of functions.
    """
    if maxsize:
        cache = LRUCache(maxsize)
    else:
        cache = {}
    def cached_func(*args, **kwargs):
        key = (args, tuple(kwargs.items()))
        if key in cache:
            return cache[key]
        cache[key] = func(*args, **kwargs)
        return cache[key]
    return cached_func

class LRUCache(object):
    """ Implements a last recently used cache in pure Python.

    The cache has a 'maxsize'. If you don't need this you also won't
    need the LRU property so just use a Python dict.

    The cache operates a queue, implemented as a linked list.
    Whenever an item is retrieved from the cache, it is bumped to the
    top of the queue. If an insertion exceeds the capacity, the item
    at the end of the queue is evicted.

    To facilitate O(1) cache retrieval we also operate a hash map
    (implemented as a Python dict), which is used to look up items by key.
    """
    def __init__(self, maxsize):
        self.cache = {}
        self.queue = None
        self.size = 0
        self.maxsize = maxsize

    def _update_node(self, node):
        """ Push a node to beginning of queue. """
        if self.queue:
            if node is not self.queue:
                node.unlink()
                self.queue.prepend(node)
        self.queue = node

    def _delete_oldest(self):
        """ Delete oldest item from cache. """
        if self.queue:
            node = self.queue.prev
            del self.cache[node.key]
            node.unlink()
            self.size -= 1

    def __getitem__(self, key):
        node = self.cache[key]
        self._update_node(node)
        return node.value

    def __setitem__(self, key, value):
        node = ListHead(key, value)
        self.cache[key] = node
        self._update_node(node)
        self.size += 1
        if self.size > self.maxsize:
            self._delete_oldest()

    def __contains__(self, key):
        return key in self.cache

    def __iter__(self):
        """ Iterator over the cache in order of use. """
        node = self.queue
        while node:
            yield node.key
            node = node.next

    def iteritems(self):
        node = self.queue
        while node:
            yield (node.key, node.value)
            node = node.next

    def items(self):
        result = []
        if not self.queue:
            return result
        result.append((self.queue.key, self.queue.value))
        node = self.queue.next
        while node is not self.queue:
            result.append((node.key, node.value))
            node = node.next
        return result

    def __len__(self):
        return self.size

class ListHead(object):
    """ A circular, doubly linked, list for storing key/value pairs.
    Normally, a linked list is a bad idea in Python so I didn't put this into
    its own module. However, this is the most efficient way to implement the
    maxsize property for a cache.

    Note: I didn't use collections.deque, because I couldn't find a way to
    manually relink nodes in the list and keep references to the internal list
    nodes for efficient integration into the hashmap.
    """
    def __init__(self, key=None, value=None):
        self.prev = self
        self.next = self
        self.key = key
        self.value = value

    def unlink(self):
        """ Remove a node from a list. """
        if self.prev and self.prev is not self:
            self.prev.next = self.next
        if self.next and self.next is not self:
            self.next.prev = self.prev

    def append(self, node):
        """ Insert a new node after this one. """
        if self.next:
            self.next.prev = node
            node.next = self.next
        node.prev = self
        self.next = node

    def prepend(self, node):
        """ Insert a new node in front of this one. """
        if self.prev:
            self.prev.next = node
            node.prev = self.prev
        self.prev = node
        node.next = self

def test_lrucache():
    test_keys = range(10)
    test_values = [x * 10 for x in test_keys]
    test_data = zip(test_keys, test_values)
    cache = LRUCache(len(test_data))
    # Check if it retains the correct values if we fill it to capacity.
    for key, value in test_data:
        cache[key] = value
    for key, value in test_data:
        assert cache[key] == value
    # Now see if we can iterate over items in the cache
    # Note that the order is reversed because of the LRU property
    assert cache.items() == list(reversed(test_data))
    for cache_tuple, test_tuple in zip(cache.iteritems(), reversed(test_data)):
        assert cache_tuple == test_tuple
    for cache_key, test_key in zip(cache, reversed(test_keys)):
        assert cache_key == test_key
    # Now see if an item gets evicted if we insert something to exceed capacity.
    cache["foo"] = "test"
    assert cache["foo"] == "test"
    assert "foo" in cache
    assert 0 not in cache
    # Check if the queue correctly updates the lru for an item.
    # 1 is next to be evicted, but because we access it 2 gets evicted instead.
    assert cache[1] == 10
    cache["bla"] = "howdi"
    assert 1 in cache
    assert 2 not in cache
    print "LRUCache tests completed successfully!"

if __name__ == "__main__":
    test_lrucache()


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Astragalus puberulus Ledeb.

### Remarks
null


text:
/**
 * PanelLayouts expand to cover the entire area of their parent. They can be configured with
 * scrolling, padding, and a frame, and are often used together with
 * {@link OO.ui.StackLayout StackLayouts}.
 *
 *     @example
 *     // Example of a panel layout
 *     var panel = new OO.ui.PanelLayout( {
 *         expanded: false,
 *         framed: true,
 *         padded: true,
 *         $content: $( '
A panel layout with padding and a frame.
' )
 *     } );
 *     $( document.body ).append( panel.$element );
 *
 * @class
 * @extends OO.ui.Layout
 *
 * @constructor
 * @param {Object} [config] Configuration options
 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside
 *  content.
 */
OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
	// Configuration initialization
	config = $.extend( {
		scrollable: false,
		padded: false,
		expanded: true,
		framed: false
	}, config );

	// Parent constructor
	OO.ui.PanelLayout.super.call( this, config );

	// Initialization
	this.$element.addClass( 'oo-ui-panelLayout' );
	if ( config.scrollable ) {
		this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
	}
	if ( config.padded ) {
		this.$element.addClass( 'oo-ui-panelLayout-padded' );
	}
	if ( config.expanded ) {
		this.$element.addClass( 'oo-ui-panelLayout-expanded' );
	}
	if ( config.framed ) {
		this.$element.addClass( 'oo-ui-panelLayout-framed' );
	}
};

/* Setup */

OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );

/* Static Methods */

/**
 * @inheritdoc
 */
OO.ui.PanelLayout.static.reusePreInfuseDOM = function ( node, config ) {
	config = OO.ui.PanelLayout.super.static.reusePreInfuseDOM( node, config );
	if ( config.preserveContent !== false ) {
		config.$content = $( node ).contents();
	}
	return config;
};

/* Methods */

/**
 * Focus the panel layout
 *
 * The default implementation just focuses the first focusable element in the panel
 */
OO.ui.PanelLayout.prototype.focus = function () {
	OO.ui.findFocusable( this.$element ).focus();
};


text:
package tccrouter.gbl.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import tccrouter.diamante.core.graph.Graph;
import tccrouter.gbl.common.entity.TSProblemModel;
import tccrouter.gbl.vrp.common.entity.VRProblemModel;
import tccrouter.ring.gui.UIFacade;

public class VRPSettings extends JDialog {

	private static final int DEMAND_INDEX = 1;
	private static final int TW_BEGIN_INDEX = 2;
	private static final int TW_END_INDEX = 3;
	private static final int TW_SERVICE_INDEX = 4;

	private static final String STRING_CLIENT = "Client";
	private static final String STRING_DEMAND = "Demand";
	private static final String STRING_INITIAL = "Initial";
	private static final String STRING_END = "End";
	private static final String STRING_SERVICE = "Service";

	/**
	 * The unique instance of this class.
	 */
	protected static VRPSettings instance;
	/**
	 * The requested clients from UI.
	 */
	TSProblemModel tModel = TSProblemModel.getInstance();

	/**
	 * The requested clients from UI.
	 */
	VRProblemModel vrpModel = VRProblemModel.getInstance();

	/**
	 * Properties panel. Where the properties will be asked for.
	 */
	JPanel centerPanel;

	JTable constraintsTable;

	/**
	 * The vehicle capacity setting
	 */
	JTextField capacityField;
	JLabel capacityLabel;

	/**
	 *
	 */
	JTextField initialWorkTime;
	JLabel initialWorkTimeLabel;

	/**
	 *
	 */
	JTextField maxTravelTime;
	JLabel maxTravelTimeLabel;

	/**
	 * The vehicle mean Velocity setting
	 */
	JTextField meanVelocity;
	JLabel meanVelocityLabel;

	final Action OK_ACTION = new AbstractAction("OK") {
		public void actionPerformed (ActionEvent evt) {

			/*
			 * Update the changes done in UI
			 */
			TableModel model = constraintsTable.getModel();
			int numRows = constraintsTable.getRowCount();
			//int numCols = constraintsTable.getColumnCount();

			/*
			 * Seting capacity
			 */
			vrpModel.setCapacity(new Integer(capacityField.getText()).intValue());

			/*
			 * Seting initial Time
			 */
			vrpModel.setInitialWorkTime(new Double(initialWorkTime.getText()).doubleValue());

			/*
			 * Seting max travel Time
			 */
			vrpModel.setMaxTravelTime(new Double(maxTravelTime.getText()).doubleValue());

			/*
			 * Seting mean Velocity
			 */
			vrpModel.setMeanVelocity(new Double(meanVelocity.getText()).doubleValue());

			/*
			 * Seting client constraints
			 */
			for (int i = 0; i < numRows; i++) {

                //	 Do something with the data for client
		        Object demand = model.getValueAt(i, DEMAND_INDEX);
		        vrpModel.setClientDemand(i, ((Integer)demand).intValue() );

		        Object twBegin = model.getValueAt(i, TW_BEGIN_INDEX);
	        	vrpModel.setClientTimeWindowBegin(i, ((Double)twBegin).doubleValue());

		        Object twEnd = model.getValueAt(i, TW_END_INDEX);
	        	vrpModel.setClientTimeWindowEnd(i, ((Double)twEnd).doubleValue());

		        Object twService = model.getValueAt(i, TW_SERVICE_INDEX);
	        	vrpModel.setClientTimeWindowService(i, ((Double)twService).doubleValue());
			}
			setVisible(false);
		}
	};

	final Action RESTORE_DEFAULT_ACTION = new AbstractAction("Default Values") {
		public void actionPerformed (ActionEvent evt) {
			//constraintsPanel.removeAll();
		}
	};

	final Action CANCEL_ACTION = new AbstractAction("Cancel") {
		public void actionPerformed (ActionEvent evt) {
			setVisible(false);
		}
	};

	public JTable createConstraintsTable(boolean rebuild) {
	    JTable table = new JTable(new VRPTableModel(rebuild));

	    table.setPreferredScrollableViewportSize(new Dimension(60, 60));
	    table.setAutoscrolls(true);
	    table.setAutoCreateColumnsFromModel(true);
	    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
	    table.setMaximumSize(new Dimension(60, 60));
	    table.setBackground(Color.LIGHT_GRAY);
	    table.setBorder(BorderFactory.createCompoundBorder());
	    table.setForeground(Color.BLACK);
	    table.setShowGrid(true);

	      return table;
	}

	/**
	 * Creates an instance of this class.
	 */
	protected VRPSettings () {
		setTitle("VRP Problem Constraints");
		setBounds(50,50,700,500);

		centerPanel = new JPanel(new FlowLayout());
		JPanel southPanel  = new JPanel(new FlowLayout());

		constraintsTable = createConstraintsTable(true);

		capacityLabel = new JLabel("Vehicle Capacity(u)");
		capacityField = new JTextField((new Integer(VRProblemModel.DEFAULT_VEHICLE_CAPACITY)).toString(), 4);
		initialWorkTimeLabel = new JLabel("Initial Work Time(h)");
		initialWorkTime = new JTextField((new Double(VRProblemModel.DEFAULT_TWVEHICLE_INITIAL)).toString(), 4);
		maxTravelTimeLabel = new JLabel("Max Travel Time(h)");
		maxTravelTime = new JTextField((new Double(VRProblemModel.DEFAULT_TWVEHICLE_MAX_TRAVEL)).toString(), 4);
		meanVelocityLabel = new JLabel("Mean Velocity(km/h)");
		meanVelocity = new JTextField((new Double(VRProblemModel.DEFAULT_TRAVEL_STEP)).toString(), 4);

		centerPanel.add(capacityLabel, BorderLayout.WEST);
		centerPanel.add(capacityField, BorderLayout.WEST);
		centerPanel.add(initialWorkTimeLabel, BorderLayout.WEST);
		centerPanel.add(initialWorkTime, BorderLayout.WEST);
		centerPanel.add(maxTravelTimeLabel, BorderLayout.WEST);
		centerPanel.add(maxTravelTime, BorderLayout.WEST);
		centerPanel.add(meanVelocityLabel, BorderLayout.WEST);
		centerPanel.add(meanVelocity, BorderLayout.WEST);

		centerPanel.add(constraintsTable,BorderLayout.CENTER);

		// Add demands table in Center Panel
		centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

		// Create buttons and buttons panel
		JPanel buttonsPanel = new JPanel(new FlowLayout());
		buttonsPanel.add(new JButton(RESTORE_DEFAULT_ACTION));
		buttonsPanel.add(new JButton(OK_ACTION));
		buttonsPanel.add(new JButton(CANCEL_ACTION));

		// Add buttons panel in South Panel
		southPanel.add(buttonsPanel,BorderLayout.EAST);

		// Add panels in Main Panel
		this.getContentPane().setLayout(new BorderLayout());
		this.getContentPane().add(southPanel,BorderLayout.SOUTH);
		this.getContentPane().add(centerPanel,BorderLayout.CENTER);
	}

	/**
	 * Retrieves the unique instance to this class.
	 * @return the instance to this class
	 */
	public static VRPSettings getInstance () {
		if (instance == null) instance = new VRPSettings();

		return instance;
	}

	/**
	 * Creates the constraints for the GridBagLayout to add components to
	 * the window.
	 * @param x the x coordinate of the component
	 * @param y the y coordinate of the component
	 * @param width the width of the component
	 * @param height the height of the component
	 * @return the GridBagConstraints created with the given parameters
	 */
	GridBagConstraints constraints (int x, int y, int width, int height) {
		GridBagConstraints constraints = new GridBagConstraints();

		constraints.gridx      = x;
		constraints.gridy      = y;
		constraints.gridwidth  = width;
		constraints.gridheight = height;
		constraints.weightx    = 80;
		constraints.weighty    = 80;

		return constraints;
	}

	class VRPTableModel extends AbstractTableModel {
	    private String[] columnNames = {
	    		STRING_CLIENT,
                STRING_DEMAND,
                STRING_INITIAL,
                STRING_END,
                STRING_SERVICE
                };

	    private Object[][] data;

	    public VRPTableModel(boolean newModel) {
			super();
			if (newModel) {
				data = VRProblemModel.getInstance().buildNewGraphDataModel();
			} else {
				data = VRProblemModel.getInstance().getGraphDataModel();
			}
		}

		public int getColumnCount() {
	        return columnNames.length;
	    }

	    public int getRowCount() {
	    	if (data == null) {
	    		return 0;
	    	}
	        return data.length;
	    }

	    public String getColumnName(int col) {
	        return columnNames[col];
	    }

	    public Object getValueAt(int row, int col) {
	        return data[row][col];
	    }

	    public Class getColumnClass(int c) {
	        return getValueAt(0, c).getClass();
	    }

	    public String[] getColumnNames() {
			return columnNames;
		}

		public void setColumnNames(String[] columnNames) {
			this.columnNames = columnNames;
		}

		public Object[][] getData() {
			return data;
		}

		public void setData(Object[][] data) {
			this.data = data;
		}

		/*
	     * Don't need to implement this method unless your table's
	     * editable.
	     */
	    public boolean isCellEditable(int row, int col) {
	        //Note that the data/cell address is constant,
	        //no matter where the cell appears onscreen.
	        if (col < 1) {
	            return false;
	        } else {
	            return true;
	        }
	    }

	    /*
	     * Don't need to implement this method unless your table's
	     * data can change.
	     */
	    public void setValueAt(Object value, int row, int col) {
	        data[row][col] = value;
	        fireTableCellUpdated(row, col);
	    }

	}

	public void rebuild() {
		//instance = new VRPSettings();

		/*
		 * Update the changes done in UI
		 */
		//TableModel model = constraintsTable.getModel();
		Graph g = UIFacade.getInstance().getGraph();

		if (g != null) {

				centerPanel.remove(constraintsTable);
				constraintsTable = createConstraintsTable(false);
				//constraintsTable = rebuildConstraintsTable();
				//constraintsTable.getModel().addTableModelListener(this);
				centerPanel.add(constraintsTable,BorderLayout.CENTER);

				/*
				 * Seting capacity
				 */
				capacityField.setText(new Integer(vrpModel.getCapacity()).toString());

				/*
				 * Seting initial Time
				 */
				initialWorkTime.setText(new Double(vrpModel.getInitialWorkTime()).toString());

				/*
				 * Seting max travel Time
				 */
				maxTravelTime.setText(new Double(vrpModel.getMaxTravelTime()).toString());

				/*
				 * Seting max travel Time
				 */
				meanVelocity.setText(new Double(vrpModel.getMeanVelocity()).toString());

				/*
				 * Seting client constraints
				 */
//				int nodes[] = tModel.getAllProblemNodes();
//				int numNodes = nodes.length;
//
//				for (int i = 0; i < numNodes; i++) {
//
//		            //	 Get the data for client
//					int row = (i + 1);
//					model.setValueAt(new Integer(nodes[i]), row, 0);
//			        model.setValueAt(new Integer(vrpModel.getClientDemand(nodes[i])), row, DEMAND_INDEX);
//			        TimeWindow tw = vrpModel.getClientTimeWindow(nodes[i]);
//			        model.setValueAt(new Double(tw.begin), row, TW_BEGIN_INDEX);
//			        model.setValueAt(new Double(tw.end), row, TW_END_INDEX);
//			        model.setValueAt(new Double(vrpModel.getClientTimeWindowService(nodes[i])), row, TW_SERVICE_INDEX);
//				}

			this.repaint();
		} // end if != null

	}
}


text:
{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% block title %}
    {% trans "Instamute.io: About" %}
{% endblock title %}
{% block extra_head %}

{% endblock extra_head %}
{% block content %}

{% trans "Share your microphone" %}

{% trans "That it!" %}

{% endblock content %}


text:
<!DOCTYPE HTML>

<title>GreyscaleImage.Type</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2022-10-10">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

Package algorithms.imageProcessing

Enum GreyscaleImage.Type

java.lang.Object

java.lang.Enum<GreyscaleImage.Type>

algorithms.imageProcessing.GreyscaleImage.Type

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<GreyscaleImage.Type>

Enclosing class:

GreyscaleImage

public static enum GreyscaleImage.Type
extends java.lang.Enum<GreyscaleImage.Type>

type for how data is stored which is by default Bits32 for a 32 bit
 platform and Bits64 for a 64 bit platform each holding values in
 range 0 to 255, inclusive, else user can
 specify Bits32Signed or Bits64Signed which is the Bits32 or Bits64
 storage with a range of -255 to 255 (needed for gradient images for
 example) else the Bits32FullRangeInt type can hold signed integers.

Enum Constant Summary

Enum Constants

Enum Constant
Description

Bits32

Bits32FullRangeInt

Bits32Signed

Bits64

Bits64Signed

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method
Description

GreyscaleImage.Type
copy(GreyscaleImage.Type t)

static GreyscaleImage.Type
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static GreyscaleImage.Type[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

Bits32

public static final GreyscaleImage.Type Bits32

Bits64

public static final GreyscaleImage.Type Bits64

Bits32Signed

public static final GreyscaleImage.Type Bits32Signed

Bits64Signed

public static final GreyscaleImage.Type Bits64Signed

Bits32FullRangeInt

public static final GreyscaleImage.Type Bits32FullRangeInt

Method Detail

values

public static GreyscaleImage.Type[] values()

Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:

for (GreyscaleImage.Type c : GreyscaleImage.Type.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static GreyscaleImage.Type valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

copy

public GreyscaleImage.Type copy(GreyscaleImage.Type t)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
---
uid: a_dev_virtual
---

# Virtual device

> [!IMPORTANT]
> Virtual devices API available for macOS only. For Windows you can use products like [virtualMIDI SDK](https://www.tobias-erichsen.de/software/virtualmidi/virtualmidi-sdk.html) or similar to work with virtual MIDI ports programmatically. Be careful with license of these products.

With DryWetMIDI you can programmatically create virtual MIDI devices with the specified name using [VirtualDevice.Create](xref:Melanchall.DryWetMidi.Multimedia.VirtualDevice.Create(System.String)) method. In fact virtual device is an [input](xref:a_dev_input) and an [output](xref:a_dev_output) devices paired together in a way that any MIDI event sent to the output device will be immediately transfered back from the virtual device and can be received by an application from its input subdevice.

Thus we have [loopback](https://en.wikipedia.org/wiki/Loopback) device here. Loopback device is useful, for example, as intermediate layer between an application and some software synthesizer. In this case:

1. you create virtual device, for example, named as _MyDevice_;
2. in the application you set _MyDevice_ as an output MIDI port, so the application will send MIDI data to the output subdevice of the virtual device;
3. in software synthesizer you set _MyDevice_ as an input MIDI port.

So when you create virtual device an input device and an output one are created with the same name as the one specified on virtual device creation. Subdevices of a virtual device are available via [InputDevice](xref:Melanchall.DryWetMidi.Multimedia.VirtualDevice.InputDevice) and [OutputDevice](xref:Melanchall.DryWetMidi.Multimedia.VirtualDevice.OutputDevice) properties of the [VirtualDevice](xref:Melanchall.DryWetMidi.Multimedia.VirtualDevice) class. Of course you can use those device separately as regular input and output devices:

```csharp
using System;
using Melanchall.DryWetMidi.Multimedia;

namespace DwmExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            var virtualDevice = VirtualDevice.Create("MyDevice");
            Console.WriteLine($"Virtual device {virtualDevice} created with subdevices:");
            Console.WriteLine($"  input = {virtualDevice.InputDevice.Name}");
            Console.WriteLine($"  output = {virtualDevice.OutputDevice.Name}");

            var inputDevice = InputDevice.GetByName("MyDevice");
            Console.WriteLine($"Input device {inputDevice.Name} got as regular input device.");

            var outputDevice = OutputDevice.GetByName("MyDevice");
            Console.WriteLine($"Output device {outputDevice.Name} got as regular output device.");

            Console.ReadKey();
        }
    }
}
```

Output of the program:

```
Virtual device Virtual device created with subdevices:
  input = MyDevice
  output = MyDevice
Input device MyDevice got as regular input device.
Output device MyDevice got as regular output device.
```

You can even combine virtual devices and [DevicesConnector](xref:a_dev_connector) to broadcast MIDI data to several applications (synthesizers, for example) at the same time:

```csharp
using System;
using Melanchall.DryWetMidi.Common;
using Melanchall.DryWetMidi.Core;
using Melanchall.DryWetMidi.Multimedia;

namespace DwmExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            var rootDevice = VirtualDevice.Create("Root");
            rootDevice.InputDevice.StartEventsListening(); // Important, don't forget!

            var leafDevice1 = VirtualDevice.Create("Leaf1");
            leafDevice1.InputDevice.EventReceived += OnLeafEventReceived;

            var leafDevice2 = VirtualDevice.Create("Leaf2");
            leafDevice2.InputDevice.EventReceived += OnLeafEventReceived;

            var devicesConnector = rootDevice.InputDevice.Connect(
                leafDevice1.OutputDevice,
                leafDevice2.OutputDevice);
            leafDevice1.InputDevice.StartEventsListening();
            leafDevice2.InputDevice.StartEventsListening();

            var midiEvent = new NoteOnEvent((SevenBitNumber)70, (SevenBitNumber)60)
            {
                Channel = (FourBitNumber)5
            };

            Console.WriteLine($"Sending {midiEvent} event...");
            rootDevice.OutputDevice.SendEvent(midiEvent);

            Console.ReadKey();
        }

        private static void OnLeafEventReceived(object sender, MidiEventReceivedEventArgs e)
        {
            var device = (MidiDevice)sender;
            Console.WriteLine($"Event {e.Event} received on device {device.Name}.");
        }
    }
}
```

This program will print following lines:

```
Sending Note On [5] (70, 60) event...
Event Note On [5] (70, 60) received on device Leaf1.
Event Note On [5] (70, 60) received on device Leaf2.
```

As with input and output device you should always [dispose](xref:Melanchall.DryWetMidi.Multimedia.MidiDevice.Dispose) virtual device when you're done with it:

```csharp
virtualDevice.Dispose();
```

You must not explicitly dispose subdevices of a virtual device. More than that calling `Dispose` on `virtualDevice.InputDevice` and `virtualDevice.OutputDevice` will throw an exception. But if you got references to the subdevices by regular methods (for example, by [InputDevice.GetByName](xref:Melanchall.DryWetMidi.Multimedia.InputDevice.GetByName(System.String))), you can call `Dispose` on that references of course.