text:
"""autogenerated by genpy from map_msgs/GetMapROIRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct

class GetMapROIRequest(genpy.Message):
  _md5sum = "43c2ff8f45af555c0eaf070c401e9a47"
  _type = "map_msgs/GetMapROIRequest"
  _has_header = False #flag to mark the presence of a Header object
  _full_text = """float64 x
float64 y
float64 l_x
float64 l_y

"""
  __slots__ = ['x','y','l_x','l_y']
  _slot_types = ['float64','float64','float64','float64']

  def __init__(self, *args, **kwds):
    """
    Constructor. Any message fields that are implicitly/explicitly
    set to None will be assigned a default value. The recommend
    use is keyword arguments as this is more robust to future message
    changes.  You cannot mix in-order arguments and keyword arguments.

    The available fields are:
       x,y,l_x,l_y

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(GetMapROIRequest, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.x is None:
        self.x = 0.
      if self.y is None:
        self.y = 0.
      if self.l_x is None:
        self.l_x = 0.
      if self.l_y is None:
        self.l_y = 0.
    else:
      self.x = 0.
      self.y = 0.
      self.l_x = 0.
      self.l_y = 0.

  def _get_types(self):
    """
    internal API method
    """
    return self._slot_types

  def serialize(self, buff):
    """
    serialize message into buffer
    :param buff: buffer, ``StringIO``
    """
    try:
      _x = self
      buff.write(_struct_4d.pack(_x.x, _x.y, _x.l_x, _x.l_y))
    except struct.error as se: self._check_types(se)
    except TypeError as te: self._check_types(te)

  def deserialize(self, str):
    """
    unpack serialized message in str into this message instance
    :param str: byte array of serialized message, ``str``
    """
    try:
      end = 0
      _x = self
      start = end
      end += 32
      (_x.x, _x.y, _x.l_x, _x.l_y,) = _struct_4d.unpack(str[start:end])
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

  def serialize_numpy(self, buff, numpy):
    """
    serialize message with numpy array types into buffer
    :param buff: buffer, ``StringIO``
    :param numpy: numpy python module
    """
    try:
      _x = self
      buff.write(_struct_4d.pack(_x.x, _x.y, _x.l_x, _x.l_y))
    except struct.error as se: self._check_types(se)
    except TypeError as te: self._check_types(te)

  def deserialize_numpy(self, str, numpy):
    """
    unpack serialized message in str into this message instance using numpy for array types
    :param str: byte array of serialized message, ``str``
    :param numpy: numpy python module
    """
    try:
      end = 0
      _x = self
      start = end
      end += 32
      (_x.x, _x.y, _x.l_x, _x.l_y,) = _struct_4d.unpack(str[start:end])
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

_struct_I = genpy.struct_I
_struct_4d = struct.Struct("<4d")
"""autogenerated by genpy from map_msgs/GetMapROIResponse.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct

import geometry_msgs.msg
import nav_msgs.msg
import genpy
import std_msgs.msg

class GetMapROIResponse(genpy.Message):
  _md5sum = "4d1986519c00d81967d2891a606b234c"
  _type = "map_msgs/GetMapROIResponse"
  _has_header = False #flag to mark the presence of a Header object
  _full_text = """nav_msgs/OccupancyGrid sub_map

================================================================================
MSG: nav_msgs/OccupancyGrid
# This represents a 2-D grid map, in which each cell represents the probability of
# occupancy.

Header header

#MetaData for the map
MapMetaData info

# The map data, in row-major order, starting with (0,0).  Occupancy
# probabilities are in the range [0,100].  Unknown is -1.
int8[] data

================================================================================
MSG: std_msgs/Header
# Standard metadata for higher-level stamped data types.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.secs: seconds (stamp_secs) since epoch
# * stamp.nsecs: nanoseconds since stamp_secs
# time-handling sugar is provided by the client library
time stamp
#Frame this data is associated with
# 0: no frame
# 1: global frame
string frame_id

================================================================================
MSG: nav_msgs/MapMetaData
# This hold basic information about the characterists of the OccupancyGrid

# The time at which the map was loaded
time map_load_time
# The map resolution [m/cell]
float32 resolution
# Map width [cells]
uint32 width
# Map height [cells]
uint32 height
# The origin of the map [m, m, rad].  This is the real-world pose of the
# cell (0,0) in the map.
geometry_msgs/Pose origin
================================================================================
MSG: geometry_msgs/Pose
# A representation of pose in free space, composed of postion and orientation.
Point position
Quaternion orientation

================================================================================
MSG: geometry_msgs/Point
# This contains the position of a point in free space
float64 x
float64 y
float64 z

================================================================================
MSG: geometry_msgs/Quaternion
# This represents an orientation in free space in quaternion form.

float64 x
float64 y
float64 z
float64 w

"""
  __slots__ = ['sub_map']
  _slot_types = ['nav_msgs/OccupancyGrid']

  def __init__(self, *args, **kwds):
    """
    Constructor. Any message fields that are implicitly/explicitly
    set to None will be assigned a default value. The recommend
    use is keyword arguments as this is more robust to future message
    changes.  You cannot mix in-order arguments and keyword arguments.

    The available fields are:
       sub_map

    :param args: complete set of field values, in .msg order
    :param kwds: use keyword arguments corresponding to message field names
    to set specific fields.
    """
    if args or kwds:
      super(GetMapROIResponse, self).__init__(*args, **kwds)
      #message fields cannot be None, assign default values for those that are
      if self.sub_map is None:
        self.sub_map = nav_msgs.msg.OccupancyGrid()
    else:
      self.sub_map = nav_msgs.msg.OccupancyGrid()

  def _get_types(self):
    """
    internal API method
    """
    return self._slot_types

  def serialize(self, buff):
    """
    serialize message into buffer
    :param buff: buffer, ``StringIO``
    """
    try:
      _x = self
      buff.write(_struct_3I.pack(_x.sub_map.header.seq, _x.sub_map.header.stamp.secs, _x.sub_map.header.stamp.nsecs))
      _x = self.sub_map.header.frame_id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_struct_2If2I7d.pack(_x.sub_map.info.map_load_time.secs, _x.sub_map.info.map_load_time.nsecs, _x.sub_map.info.resolution, _x.sub_map.info.width, _x.sub_map.info.height, _x.sub_map.info.origin.position.x, _x.sub_map.info.origin.position.y, _x.sub_map.info.origin.position.z, _x.sub_map.info.origin.orientation.x, _x.sub_map.info.origin.orientation.y, _x.sub_map.info.origin.orientation.z, _x.sub_map.info.origin.orientation.w))
      length = len(self.sub_map.data)
      buff.write(_struct_I.pack(length))
      pattern = '<%sb'%length
      buff.write(struct.pack(pattern, *self.sub_map.data))
    except struct.error as se: self._check_types(se)
    except TypeError as te: self._check_types(te)

  def deserialize(self, str):
    """
    unpack serialized message in str into this message instance
    :param str: byte array of serialized message, ``str``
    """
    try:
      if self.sub_map is None:
        self.sub_map = nav_msgs.msg.OccupancyGrid()
      end = 0
      _x = self
      start = end
      end += 12
      (_x.sub_map.header.seq, _x.sub_map.header.stamp.secs, _x.sub_map.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.sub_map.header.frame_id = str[start:end].decode('utf-8')
      else:
        self.sub_map.header.frame_id = str[start:end]
      _x = self
      start = end
      end += 76
      (_x.sub_map.info.map_load_time.secs, _x.sub_map.info.map_load_time.nsecs, _x.sub_map.info.resolution, _x.sub_map.info.width, _x.sub_map.info.height, _x.sub_map.info.origin.position.x, _x.sub_map.info.origin.position.y, _x.sub_map.info.origin.position.z, _x.sub_map.info.origin.orientation.x, _x.sub_map.info.origin.orientation.y, _x.sub_map.info.origin.orientation.z, _x.sub_map.info.origin.orientation.w,) = _struct_2If2I7d.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      pattern = '<%sb'%length
      start = end
      end += struct.calcsize(pattern)
      self.sub_map.data = struct.unpack(pattern, str[start:end])
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

  def serialize_numpy(self, buff, numpy):
    """
    serialize message with numpy array types into buffer
    :param buff: buffer, ``StringIO``
    :param numpy: numpy python module
    """
    try:
      _x = self
      buff.write(_struct_3I.pack(_x.sub_map.header.seq, _x.sub_map.header.stamp.secs, _x.sub_map.header.stamp.nsecs))
      _x = self.sub_map.header.frame_id
      length = len(_x)
      if python3 or type(_x) == unicode:
        _x = _x.encode('utf-8')
        length = len(_x)
      buff.write(struct.pack('<I%ss'%length, length, _x))
      _x = self
      buff.write(_struct_2If2I7d.pack(_x.sub_map.info.map_load_time.secs, _x.sub_map.info.map_load_time.nsecs, _x.sub_map.info.resolution, _x.sub_map.info.width, _x.sub_map.info.height, _x.sub_map.info.origin.position.x, _x.sub_map.info.origin.position.y, _x.sub_map.info.origin.position.z, _x.sub_map.info.origin.orientation.x, _x.sub_map.info.origin.orientation.y, _x.sub_map.info.origin.orientation.z, _x.sub_map.info.origin.orientation.w))
      length = len(self.sub_map.data)
      buff.write(_struct_I.pack(length))
      pattern = '<%sb'%length
      buff.write(self.sub_map.data.tostring())
    except struct.error as se: self._check_types(se)
    except TypeError as te: self._check_types(te)

  def deserialize_numpy(self, str, numpy):
    """
    unpack serialized message in str into this message instance using numpy for array types
    :param str: byte array of serialized message, ``str``
    :param numpy: numpy python module
    """
    try:
      if self.sub_map is None:
        self.sub_map = nav_msgs.msg.OccupancyGrid()
      end = 0
      _x = self
      start = end
      end += 12
      (_x.sub_map.header.seq, _x.sub_map.header.stamp.secs, _x.sub_map.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      start = end
      end += length
      if python3:
        self.sub_map.header.frame_id = str[start:end].decode('utf-8')
      else:
        self.sub_map.header.frame_id = str[start:end]
      _x = self
      start = end
      end += 76
      (_x.sub_map.info.map_load_time.secs, _x.sub_map.info.map_load_time.nsecs, _x.sub_map.info.resolution, _x.sub_map.info.width, _x.sub_map.info.height, _x.sub_map.info.origin.position.x, _x.sub_map.info.origin.position.y, _x.sub_map.info.origin.position.z, _x.sub_map.info.origin.orientation.x, _x.sub_map.info.origin.orientation.y, _x.sub_map.info.origin.orientation.z, _x.sub_map.info.origin.orientation.w,) = _struct_2If2I7d.unpack(str[start:end])
      start = end
      end += 4
      (length,) = _struct_I.unpack(str[start:end])
      pattern = '<%sb'%length
      start = end
      end += struct.calcsize(pattern)
      self.sub_map.data = numpy.frombuffer(str[start:end], dtype=numpy.int8, count=length)
      return self
    except struct.error as e:
      raise genpy.DeserializationError(e) #most likely buffer underfill

_struct_I = genpy.struct_I
_struct_3I = struct.Struct("<3I")
_struct_2If2I7d = struct.Struct("<2If2I7d")
class GetMapROI(object):
  _type          = 'map_msgs/GetMapROI'
  _md5sum = '81aa75ecf00f4571a9be0d9dc6dea512'
  _request_class  = GetMapROIRequest
  _response_class = GetMapROIResponse


text:
package de.kumpelblase2.remoteentities.entities;

import de.kumpelblase2.remoteentities.api.Fightable;
import de.kumpelblase2.remoteentities.api.RemoteEntity;

public interface RemoteWither extends RemoteEntity, Fightable
{
}

redpajama_set_name: RedPajamaGithub


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Strings Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are used in strings throughout the system.
    | Regardless where it is placed, a string can be listed here so it is easily
    | found in a intuitive way.
    |
    */

    'backend' => [
        'access' => [
            'users' => [
                'delete_user_confirm' => 'Är du säker på att du vill radera denna användare permanent? Om användaren har material någonstans i programmet som pekar på sitt ID så kommer det troligtvis generera ett felmeddelande. Denna åtgärd går inte att ångra. Du fortsätter på egen risk.',
                'if_confirmed_off' => '(Om bekräftan är avstängt)',
                'restore_user_confirm' => 'Återställ användaren till sitt ursprungliga läge.',
            ],
        ],

        'dashboard' => [
            'title' => 'Adminpanelen',
            'welcome' => 'Välkommen',
        ],

        'general' => [
            'all_rights_reserved' => 'Alla rättigheter förbehålls.',
            'are_you_sure' => 'Är du säker?',
            'boilerplate_link' => 'Laravel 5 Boilerplate',
            'continue' => 'Fortsätt',
            'member_since' => 'Registrerad',
            'minutes' => ' minutes',
            'search_placeholder' => 'Sök...',
            'timeout' => 'You were automatically logged out for security reasons since you had no activity in ',

            'see_all' => [
                'messages' => 'Se alla meddelanden',
                'notifications' => 'Se alla notiser',
                'tasks' => 'Se alla punkter',
            ],

            'status' => [
                'online' => 'Online',
                'offline' => 'Offline',
            ],

            'you_have' => [
                'messages' => '{0} Du har inga meddelanden|{1} Du har 1 meddelande|[2,Inf] Du har :number meddelanden',
                'notifications' => '{0} Du har inga aviseringar|{1} Du har 1 avisering|[2,Inf] Du har :number aviseringar',
                'tasks' => '{0} Du har inga punkter att göra|{1} Du har 1 punkt att göra|[2,Inf] Du har :number punkter att göra',
            ],
        ],

		'search' => [
			'empty' => 'Please enter a search term.',
			'incomplete' => 'You must write your own search logic for this system.',
			'title' => 'Search Results',
			'results' => 'Search Results for :query',
		],
    ],
    'emails' => [
        'auth' => [
            'error' => 'Hoppsan!',
            'greeting' => 'Hej!',
            'regards' => 'Hälsningar',
            'trouble_clicking_button' => 'Fungerar inte knappen ":action_text"? Kopiera då länken nedan och klistra in den i din webbläsare.',
            'thank_you_for_using_app' => 'Tack för att du använder vår hemsida!',

            'password_reset_subject' => 'Återställ lösenord',
            'password_cause_of_email' => 'Du får detta meddelande eftersom det begärts en återställning av lösenord för ditt konto.',
            'password_if_not_requested' => 'Om det inte var du som begärde återställning av lösenord kan du helt bortse från detta mail.',
            'reset_password' => 'Klicka här för att återställa ditt lösenord:',

            'click_to_confirm' => 'Klicka här för att bekräfta ditt konto:',
        ],
    ],

    'frontend' => [
        'test' => 'Test',

        'tests' => [
            'based_on' => [
                'permission' => 'Tillstånd baserad - ',
                'role' => 'Roll baserad - ',
            ],

            'js_injected_from_controller' => 'Javascript som fått sin data direkt från en controller',

            'using_blade_extensions' => 'Avänder utbyggda @Blade-funktioner',

            'using_access_helper' => [
                'array_permissions' => 'Använder Access Helper med en array av rättighetens namn eller ID då användaren måste ha alla rättigheter.',
                'array_permissions_not' => 'Använder Access Helper med en array av rättighetens namn eller ID då användaren INTE måste ha alla rättigheter.',
                'array_roles' => 'Använder Access Helper med en array av rollens namn eller ID då användaren måste ha alla roller.',
                'array_roles_not' => 'Använder Access Helper med en array av roll-namn eller roll-ID då användaren INTE måste ha alla roller.',
                'permission_id' => 'Använder Access Helper med rättighetens ID',
                'permission_name' => 'Använder Access Helper med rättighetens namn',
                'role_id' => 'Använder Access Helper med rollens ID',
                'role_name' => 'Använder Access Helper med rollens namn',
            ],

            'view_console_it_works' => 'Kolla konsollen, du borde se \'it works!\' som skickas direkt från FrontendController@index',
            'you_can_see_because' => 'Du kan se detta för att du har rollen \':role\'!',
            'you_can_see_because_permission' => 'Du kan se detta för att du har rättiheten \':permission\'!',
        ],

        'user' => [
            'profile_updated' => 'Din profil är nu uppdaterad.',
            'password_updated' => 'Ditt lösenord har nu uppdaterats.',
        ],

        'welcome_to' => 'Välkommen till :place',
    ],
];


text:
<?php

$REGISTER_LTI2 = array(
"name" => "External Grades Tool",
"short_name" => "External Grades",
"description" => "This tool allows both the students and instructors to view their grades for this course that are coming from LTI tools hosted on this server.  This tool also provides simple grade review and maintenance tools for instructors."
);


text:
//
//  TTBaseShareCenter.h
//  TT
//
//  Created by 张福润 on 2017/3/21.
//  Copyright © 2017年 张福润. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "TTShareUser.h"
#import "TTAuthInfo.h"
#import "ShareContentInfo.h"

#import "NSUserDefaults+TTUserDefaults.h"

typedef void(^ShareSuccessBlock)();
typedef void(^ShareCancelBlock)(BOOL cancelled);
typedef void(^ShareFailureBlock)(NSError *error);

typedef NS_ENUM(NSUInteger, InstallClientType) {
    InstallClientType_None,
    InstallClientType_QQ,
    InstallClientType_QZone,
    InstallClientType_Both_QQ_QZone,
    InstallClientType_Weibo,
    InstallClientType_WeChat
};

typedef enum : NSUInteger {
    SourceAppTypeUnknow,
    SourceAppTypeQQ,
    SourceAppTypeWX,
    SourceAppTypeWB,
} SourceAppType;

FOUNDATION_EXTERN NSString * const ErrorDescKey;

FOUNDATION_EXTERN NSString * const QQAppIdKey;
FOUNDATION_EXTERN NSString * const SinaAppIdKey;
FOUNDATION_EXTERN NSString * const SinaRedirectURIKey;
FOUNDATION_EXTERN NSString * const WeChatAppIdKey;
FOUNDATION_EXTERN NSString * const WeChatAppSecretKey;

@interface TTBaseShareCenter : NSObject
@property (nonatomic, strong) TTShareUser *user;
@property (nonatomic, strong) TTAuthInfo *authInfo;
@property (nonatomic, strong, readonly) NSDictionary *AppIdDict;
@property (nonatomic, assign, readonly, getter=isInstalledClient) InstallClientType installedClient;

- (void)openClientAuthWithShareType:(ShareType)shareType successBlock:(ShareSuccessBlock)shareSuccessBlock cancelBlock:(ShareCancelBlock)shareCancelBlock failureBlock:(ShareFailureBlock)shareFailureBlock;
+ (SourceAppType)sourceAppTypeWithSourceAppString:(NSString *)sourceApplication;
+ (BOOL)handlerOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication;
/**
 *  设置各平台的AppId、AppSecret、RedirectURI
 *
 *  @param appIdDict       key 为QQAppIdKey,SinaAppIdKey,WeChatAppIdKey value 为各平台AppId
 *  @param appSecretDict   key 为WeChatAppSecretKey,... value为各平台的Secret
 *  @param redirectURIDict key 为SinaRedirectURIKey,... value为各平台的RedirectURI
 */
+ (void)setAppId:(NSDictionary *)appIdDict appSecret:(NSDictionary *)appSecretDict redirectURI:(NSDictionary *)redirectURIDict;
+ (TTBaseShareCenter *)getShareCenterWithShareType:(ShareType)shareType;
- (void)shareContentInfo:(ShareContentInfo *)contentInfo successBlock:(ShareSuccessBlock)successBlock cancelBlock:(ShareCancelBlock)cancelBlock failureBlock:(ShareFailureBlock)failureBlock;
- (void)executeFailureBlock:(ShareFailureBlock)failureBlock errorDomain:(NSString *)ErrorDomain errorMsg:(NSString *)errorMsg errorCode:(NSInteger)errorCode;

@end


text:
namespace walle {
namespace net {

class EventLoop;
class AddrInet;

class Acceptor
{
 public:
  typedef std::function<void (int sockfd,AddrInet&)> NewConnectionCallback;

  Acceptor(EventLoop* loop,  AddrInet& listenAddr, bool reuseport );
  ~Acceptor();

  void setNewConnectionCallback(const NewConnectionCallback& cb)
  { _newConnectionCallback = cb; }

  bool listenning() const { return _listenning; }
  void listen();

 private:
  void handleRead();

  EventLoop* _loop;
  Socket _acceptSocket;
  Channel _acceptChannel;
  NewConnectionCallback _newConnectionCallback;
  bool _listenning;
  int _idleFd;
};

}
}

#endif


text:
package org.apache.flink.core.memory;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

/** Tests for the {@link MemorySegment} in off-heap mode using unsafe memory. */
@RunWith(Parameterized.class)
public class OffHeapUnsafeMemorySegmentTest extends MemorySegmentTestBase {

    public OffHeapUnsafeMemorySegmentTest(int pageSize) {
        super(pageSize);
    }

    @Override
    MemorySegment createSegment(int size) {
        return MemorySegmentFactory.allocateOffHeapUnsafeMemory(size);
    }

    @Override
    MemorySegment createSegment(int size, Object owner) {
        return MemorySegmentFactory.allocateOffHeapUnsafeMemory(size, owner, () -> {});
    }

    @Override
    @Test(expected = UnsupportedOperationException.class)
    public void testByteBufferWrapping() {
        createSegment(10).wrap(1, 2);
    }

    @Test
    public void testCallCleanerOnFree() {
        final CompletableFuture<Void> cleanerFuture = new CompletableFuture<>();
        MemorySegmentFactory.allocateOffHeapUnsafeMemory(
                        10, null, () -> cleanerFuture.complete(null))
                .free();
        assertTrue(cleanerFuture.isDone());
    }

    @Test
    public void testCallCleanerOnceOnConcurrentFree() throws InterruptedException {
        final AtomicInteger counter = new AtomicInteger(0);
        final Runnable cleaner =
                () -> {
                    try {
                        counter.incrementAndGet();
                        // make the cleaner unlikely to finish before another invocation (if any)
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                };

        final MemorySegment segment =
                MemorySegmentFactory.allocateOffHeapUnsafeMemory(10, null, cleaner);

        final Thread t1 = new Thread(segment::free);
        final Thread t2 = new Thread(segment::free);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        assertThat(counter.get(), is(1));
    }
}


text:
<?php

namespace SearchSites\Form;

use Zend\Form\Form;

class SearchSitesForm extends Form
{

    public function __construct()
    {
        parent::__construct('search');

        $this->setAttribute('method', 'post')
             ->add(new SearchSitesFieldset())
             ->add(array(
                 'name' => 'submit',
                 'attributes' => array(
                     'type'  => 'submit',
                     'value' => 'Search',
                     'id' => 'submitbutton',
                 ),
             ));
    }

}


text:
package config

import (
	"testing"
	"time"

	graphite "github.com/criteo/graphite-remote-adapter/client/graphite/config"
	"github.com/go-kit/kit/log"
)

var expectedConf = &Config{
	Web: webOptions{
		ListenAddress: "1.2.3.4:666",
		TelemetryPath: "/coolMetrics",
	},
	Read: readOptions{
		Timeout:     18 * time.Minute,
		Delay:       42 * time.Minute,
		IgnoreError: true,
	},
	Write: writeOptions{
		Timeout: 18 * time.Minute,
	},
	Graphite: graphite.DefaultConfig,
	original: "",
}

func TestLoadConfigFile(t *testing.T) {
	c, err := LoadFile(log.NewNopLogger(), "testdata/conf.good.yml")
	if err != nil {
		t.Fatalf("Error parsing %s: %s", "testdata/conf.good.yml", err)
	}
	c.original = ""

	if c.String() != expectedConf.String() {
		t.Fatalf("%s: unexpected config result: \n%s\nExpecting:\n%s",
			"testdata/conf.good.yml", c.String(), expectedConf.String())
	}
}


text:
import os,sys
PROJECT_FOLDER=os.path.dirname(os.path.realpath(__file__))
sys.path.append( "{}/packages".format(PROJECT_FOLDER) )

import argparse

import numpy as np
from scipy import misc

import matplotlib.pyplot as plt
from improc.denoise import chambolle,rof,tikhonov,fista,rof_modified_curvature

def read_input():
	parser = argparse.ArgumentParser(description="Denoising tools")

	parser.add_argument("input_image",type=str,action="store",help="Image to be denoised.")
	parser.add_argument("algorithm",type=str,action="store", help="Choose among {tikhonov, rof, chambolle, fista}.")

	parser.add_argument("-l",dest="lbda",type=float,action="store",default=0.12,help="Regularization weight.")
	parser.add_argument("-t",dest="tolerance",type=float,action="store",default=1e-5,help="Stop if the new energy value differs of less than [tolerance].")
	parser.add_argument("-e",dest="ev_stop",type=float,action="store",default=None,help="Stop if energy reaches this value.")
	parser.add_argument("-i",dest="max_iterations",type=int,action="store",default=100,help="Stop after the i-th iteration.")
	parser.add_argument("-o",dest="output_image",type=str,action="store",help="Output image filepath.")
	parser.add_argument("-v",dest="verbose",action="store_true",help="Print algorithms outputs.")

	args = parser.parse_args()
	return args

def make3channel(img):
	if len(img.shape)==2:
		_img = np.zeros( img.shape + (3,) )

		for c in range(3):
			_img[:,:,c] = img.copy()

		img = _img
	return img

def set_plot_no_axes():
	plt.gca().set_axis_off()
	plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
		    hspace = 0, wspace = 0)
	plt.margins(0,0)
	plt.gca().xaxis.set_major_locator(plt.NullLocator())
	plt.gca().yaxis.set_major_locator(plt.NullLocator())

def main():
	inp = read_input()

	noisy_img = np.asfarray( misc.imread(inp.input_image) )
	noisy_img /= 255.0
	noisy_img = make3channel(noisy_img)

	if inp.max_iterations<0:
		inp.max_iterations=1e10

	if inp.algorithm=="chambolle":
		dimg = chambolle.denoise_image(noisy_img, inp.lbda, inp.tolerance, inp.max_iterations,inp.verbose)
	elif inp.algorithm=="rof":
		dimg = rof.denoise_image(noisy_img, inp.lbda, inp.tolerance, inp.max_iterations, inp.verbose,inp.ev_stop)
	elif inp.algorithm=="fista":
		dimg = fista.denoise_image(noisy_img, inp.lbda, inp.max_iterations)
	elif inp.algorithm=="tikhonov":
		dimg = tikhonov.denoise_image(noisy_img, inp.lbda, inp.max_iterations,inp.verbose)
	elif inp.algorithm=="rof_curvature":
		dimg = rof_modified_curvature.denoise_image(noisy_img, inp.lbda,inp.tolerance, inp.max_iterations,inp.verbose,inp.ev_stop)

	if inp.output_image is not None:
		dirname = os.path.dirname(inp.output_image)
		if not os.path.exists(os.path.dirname(inp.output_image)):
			os.makedirs(dirname)
		set_plot_no_axes()

		plt.imshow(dimg)
		plt.savefig(inp.output_image,bbox_inches = 'tight',pad_inches = 0)
	else:
		fig,axs=plt.subplots(1,2)
		axNoisy,axDenoise = axs

		axNoisy.imshow(noisy_img)
		axDenoise.imshow(dimg)
		plt.show()

if __name__=="__main__":
	main()


text:
import json
import os
import random
import re
from collections import defaultdict

from nlaugmenter.interfaces.SentenceOperation import SentenceOperation
from nlaugmenter.tasks.TaskTypes import TaskType

class CountryStateAbbreviation(SentenceOperation):
    tasks = [
        TaskType.TEXT_CLASSIFICATION,
        TaskType.TEXT_TO_TEXT_GENERATION,
    ]
    languages = ["en"]
    keywords = ["lexical", "rule-based", "high-coverage", "high-precision"]

    def __init__(
        self,
        seed=0,
        country=True,
        state=True,
        country_filter="USA",
        abbr=True,
        exp=True,
    ):
        super().__init__(seed)
        self.country = country
        self.state = state
        self.country_filter = country_filter
        self.abbr = abbr
        self.exp = exp

    def generate(self, sentence: str):
        perturbed_texts = self.country_state_abbreviation(text=sentence)
        return perturbed_texts

    def build_mapping(self):
        abbr_file_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "country_state_abbreviation.json",
        )
        abbr_json = json.load(open(abbr_file_path, "r"))
        country_abbr = {
            country["name"]: country["abbr"] for country in abbr_json
        }
        country_exp = {
            country["abbr"]: country["name"] for country in abbr_json
        }
        state_abbr = {}
        state_exp = {}

        if self.country_filter:
            country = next(
                (x for x in abbr_json if x["abbr"] == self.country_filter),
                None,
            )
            if country:
                for state in country["states"]:
                    state_abbr[state["name"]] = state["abbr"]
                    state_exp[state["abbr"]] = state["name"]
        else:
            state_exp = defaultdict(list)
            state_abbr = defaultdict(list)
            for country in abbr_json:
                for state in country["states"]:
                    state_exp[state["abbr"]].append(state["name"])
                    state_abbr[state["name"]].append(state["abbr"])

        country_mapping = {}
        state_mapping = {}
        if self.country:
            if self.abbr:
                country_mapping = {**country_mapping, **country_abbr}
            if self.exp:
                country_mapping = {**country_mapping, **country_exp}
        if self.state:
            if self.abbr:
                state_mapping = {**state_mapping, **state_abbr}
            if self.exp:
                state_mapping = {**state_mapping, **state_exp}

        return country_mapping, state_mapping

    def country_state_abbreviation(self, text):
        # Build mapping dictionary of abbreviation -> full name and full name -> abbreviation
        # country_mapping contains mapping between country's full name and abbreviation
        # country_mapping = {
        #   ...,
        #   "United States": "USA",
        #   ...,
        #   "USA": "United States",
        #   ...
        # }
        # state_mapping contains mapping between state's full name and abbreviation
        # state_mapping = {
        #   ...,
        #   "Pennsylvania": "PA",
        #   ...,
        #   "PA": "Pennsylvania",
        #   ...
        # }
        country_mapping, state_mapping = self.build_mapping()

        # Build regex pattern for country abbreviation/full name by joining country_mapping keys
        # eg. country_pattern = '...|United States|...|USA|...'
        country_pattern = "|".join(country_mapping.keys())
        # Adding backslash before '(' and ')' in country name as the escape character (eg. Virgin Islands (US))
        country_pattern = country_pattern.replace("(", r"\(")
        country_pattern = country_pattern.replace(")", r"\)")
        country_regex = re.compile(
            r"(^|\s+)(" + country_pattern + r")(\s+|\?|!|$|\.|,)"
        )
        perturbed_text = country_regex.sub(
            lambda y: y[1] + country_mapping[y[2]] + y[3],
            text,
        )

        # Build regex pattern for state abbreviation/full name by joining state_mapping keys
        # eg. state_pattern = '...|Pennsylvania|...|PA|...'
        state_pattern = "|".join(state_mapping.keys())
        # Adding backslash before '(' and ')' in state name as the escape character
        state_pattern = state_pattern.replace("(", r"\(")
        state_pattern = state_pattern.replace(")", r"\)")
        state_regex = re.compile(
            r"(^|\s+)(" + state_pattern + r")(\s+|\?|!|$|\.|,)"
        )
        perturbed_text = state_regex.sub(
            lambda y: y[1]
            + self.dict_value_helper(state_mapping, y[2])
            + y[3],
            perturbed_text,
        )
        return [perturbed_text]

    def dict_value_helper(self, d, key):
        if type(d[key]) is list:
            random.seed(self.seed)
            return random.choice(d[key])
        else:
            return d[key]


text:
const { parseString } = require('xml2js');

module.exports = (text, { manifest = {} }) => {
  const typeHandlers = {
    bool: (x = '', type, errorCallback) => {
      x = x.toLowerCase();

      if (x === 'true') {
        return true;
      } else if (x === 'false') {
        return false;
      }
      errorCallback();
    },
    int: (x, type, errorCallback) => {
      try {
        return parseInt(x, 10);
      } catch (err) {
        errorCallback();
      }
    },
    float: (x, type, errorCallback) => {
      try {
        return parseFloat(x, 10)
      } catch (err) {
        errorCallback();
      }
    },
    array: (value, arr, errorCallback) => {
      if (arr.indexOf(value) > -1) {
        return value;
      } else {
        errorCallback();
      }
    },
  };

  const reviseItem = item => {
    for (let key in item) {
      if (key !== 'items' && Array.isArray(item[key])) {
        delete item[key];
      }

      if (key === '#name') {
        let value = item[key];
        item.type = value;
        delete item[key];
      }
    }

    item.properties = item.properties || {};
    const control = manifest[item.type];

    if (!control) {
      throw new Error(`Недопустимый тэг ${item.type}.`);
    }

    return item;
  };

  const processTemplate = template => {
    const errors = [];

    const iterate = (node, parent) => {
      node = reviseItem(node);

      const control = manifest[node.type];
      const { properties = {}, placing = {} } = control;
      const { type: parentType = '', items: parentItems = [] } = parent || {};

      const places = Object.keys(placing).filter(key => {
        const control = manifest[parentType];
        const { categories = [] } = control || {};

        return categories.indexOf(key) > -1 || (key === '' && parent == null);
      }).map(key => placing[key]);

      if (!places.length) {
        errors.push(`Тэг ${node.type} не может быть помещён в тэг ${parentType}`);
        return;
      }

      places.forEach(place => {
        if (!place) {
          errors.push(`Тэг ${node.type} не может быть помещён в тэг ${parentType}`);
          return;
        }

        switch (place) {
          case 'multiple':
            //всё норм. лепи что хочешь
            break;
          case 'unique':
            {
              const sameTags = parentItems.filter(item => {
                const { type: itemType } = item;
                return node !== item && itemType == node.type;
              });

              if (sameTags.length) {
                errors.push(`Тэг ${parentType} не может содержать несколько тэгов ${node.type}.`);
              }
            }

            break;
          default:
            {
              //объект (или повреждённый манифест)
              //раз объект - значит, исключающее размещение (другого пока нет)
              const { tags = [] } = place;
              const sameCategories = parentItems.filter(item => {
                if (item == node) {
                  return false;
                }

                item = reviseItem(item);

                const { type: itemType = '' } = item;
                const control = manifest[itemType];
                const { categories: itemCategories = [] } = control;

                return tags.filter(tag => {
                  return itemCategories.indexOf(tag) > -1;
                }).length;
              }).map(({ type }) => type);

              if (sameCategories.length) {
                const categories = sameCategories.join(', ');
                errors.push(`Тэг ${node.type} не может быть размещён вместе с тэгами ` +
                  `${categories} в тэге ${parentType}.`);
              }
            }
        }
      });

      for (let prop in node.properties) {
        const desc = properties[prop];

        if (!desc) {
          errors.push(`Тэг ${node.type} имеет недопустимое свойство "${prop}".`);
          continue;
        }

        const type = desc.type;
        const handler = Array.isArray(type) ? typeHandlers['array'] : typeHandlers[type];
        if (!handler) {
          continue;
        }

        const errorCallback = () => {
          errors.push(`Тэг ${node.type} имеет недопустимое значение свойства "${prop}"` +
            ` ("${node.properties[prop]}").`);
        }

        let value = handler(node.properties[prop], type, errorCallback);
        node.properties[prop] = value;
      }

      node.items = node.items || [];
      node.items.forEach(item => {
        iterate(item, node);
      });
    };

    iterate(template);

    if (errors.length) {
      throw new Error(errors.join('\n'));
    }

    return template;
  };

  return new Promise((resolve, reject) => {
    parseString(text, {
      explicitRoot: true,
      explicitChildren: true,
      preserveChildrenOrder: true,
      attrkey: 'properties',
      childkey: 'items',
      charkey: 'content'
    }, (err, { Form } = {}) => {
      let template;

      if (!err) {
        try {
          template = processTemplate(Form, manifest);
        } catch (e) {
          err = e;
        }
      }

      if (err) {
        reject(err);
      } else {
        resolve(template);
      }
    });
  });
};


text:
package org.springframework.data.elasticsearch.repository.query.parser;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.geo.GeoBox;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.context.PersistentPropertyPath;
import org.springframework.data.repository.query.ParameterAccessor;
import org.springframework.data.repository.query.parser.AbstractQueryCreator;
import org.springframework.data.repository.query.parser.Part;
import org.springframework.data.repository.query.parser.PartTree;

/**
 * ElasticsearchQueryCreator
 *
 * @author Rizwan Idrees
 * @author Mohsin Husen
 * @author Franck Marchand
 * @author Artur Konczak
 */
public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuery, CriteriaQuery> {

	private final MappingContext<?, ElasticsearchPersistentProperty> context;

	public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters,
									 MappingContext<?, ElasticsearchPersistentProperty> context) {
		super(tree, parameters);
		this.context = context;
	}

	public ElasticsearchQueryCreator(PartTree tree, MappingContext<?, ElasticsearchPersistentProperty> context) {
		super(tree);
		this.context = context;
	}

	@Override
	protected CriteriaQuery create(Part part, Iterator<Object> iterator) {
		PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
				.getPersistentPropertyPath(part.getProperty());
		return new CriteriaQuery(from(part,
				new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
	}

	@Override
	protected CriteriaQuery and(Part part, CriteriaQuery base, Iterator<Object> iterator) {
		if (base == null) {
			return create(part, iterator);
		}
		PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
				.getPersistentPropertyPath(part.getProperty());
		return base.addCriteria(from(part,
				new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
	}

	@Override
	protected CriteriaQuery or(CriteriaQuery base, CriteriaQuery query) {
		return new CriteriaQuery(base.getCriteria().or(query.getCriteria()));
	}

	@Override
	protected CriteriaQuery complete(CriteriaQuery query, Sort sort) {
		if (query == null) {
			return null;
		}
		return query.addSort(sort);
	}

	private Criteria from(Part part, Criteria instance, Iterator<?> parameters) {
		Part.Type type = part.getType();

		Criteria criteria = instance;
		if (criteria == null) {
			criteria = new Criteria();
		}
		switch (type) {
			case TRUE:
				return criteria.is(true);
			case FALSE:
				return criteria.is(false);
			case NEGATING_SIMPLE_PROPERTY:
				return criteria.is(parameters.next()).not();
			case REGEX:
				return criteria.expression(parameters.next().toString());
			case LIKE:
			case STARTING_WITH:
				return criteria.startsWith(parameters.next().toString());
			case ENDING_WITH:
				return criteria.endsWith(parameters.next().toString());
			case CONTAINING:
				return criteria.contains(parameters.next().toString());
			case GREATER_THAN:
				return criteria.greaterThan(parameters.next());
			case AFTER:
			case GREATER_THAN_EQUAL:
				return criteria.greaterThanEqual(parameters.next());
			case LESS_THAN:
				return criteria.lessThan(parameters.next());
			case BEFORE:
			case LESS_THAN_EQUAL:
				return criteria.lessThanEqual(parameters.next());
			case BETWEEN:
				return criteria.between(parameters.next(), parameters.next());
			case IN:
				return criteria.in(asArray(parameters.next()));
			case NOT_IN:
				return criteria.notIn(asArray(parameters.next()));
			case SIMPLE_PROPERTY:
			case WITHIN: {
				Object firstParameter = parameters.next();
				Object secondParameter = null;
				if (type == Part.Type.SIMPLE_PROPERTY) {
					if (part.getProperty().getType() != GeoPoint.class)
						return criteria.is(firstParameter);
					else {
						// it means it's a simple find with exact geopoint matching (e.g. findByLocation)
						// and because Elasticsearch does not have any kind of query with just a geopoint
						// as argument we use a "geo distance" query with a distance of one meter.
						secondParameter = ".001km";
					}
				} else {
					secondParameter = parameters.next();
				}

				if (firstParameter instanceof GeoPoint && secondParameter instanceof String)
					return criteria.within((GeoPoint) firstParameter, (String) secondParameter);

				if (firstParameter instanceof Point && secondParameter instanceof Distance)
					return criteria.within((Point) firstParameter, (Distance) secondParameter);

				if (firstParameter instanceof String && secondParameter instanceof String)
					return criteria.within((String) firstParameter, (String) secondParameter);
			}
			case NEAR: {
				Object firstParameter = parameters.next();

				if (firstParameter instanceof GeoBox) {
					return criteria.boundedBy((GeoBox) firstParameter);
				}

				if (firstParameter instanceof Box) {
					return criteria.boundedBy(GeoBox.fromBox((Box) firstParameter));
				}

				Object secondParameter = parameters.next();

				// "near" query can be the same query as the "within" query
				if (firstParameter instanceof GeoPoint && secondParameter instanceof String)
					return criteria.within((GeoPoint) firstParameter, (String) secondParameter);

				if (firstParameter instanceof Point && secondParameter instanceof Distance)
					return criteria.within((Point) firstParameter, (Distance) secondParameter);

				if (firstParameter instanceof String && secondParameter instanceof String)
					return criteria.within((String) firstParameter, (String) secondParameter);
			}

			default:
				throw new InvalidDataAccessApiUsageException("Illegal criteria found '" + type + "'.");
		}
	}

	private Object[] asArray(Object o) {
		if (o instanceof Collection) {
			return ((Collection<?>) o).toArray();
		} else if (o.getClass().isArray()) {
			return (Object[]) o;
		}
		return new Object[]{o};
	}
}


text:
require 'delegate'

# Delegator with some handy shortcuts
class Calendar < SimpleDelegator
  attr_accessor :filename
  # Write 'back' to file.
  def write_back!
    File.open(@filename, 'w') do |file|
      export_to file
    end
  end
end


text:
<?php

namespace MpaFirephpWrapper;

use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Mvc\MvcEvent;

class Module implements ConfigProviderInterface
{
    /**
     * @param MvcEvent $event
     */
    public function onBootstrap(MvcEvent $event)
    {
        $serviceManager = $event->getApplication()->getServiceManager();
        $pluralHelper   = $serviceManager->get('ViewHelperManager')->get('Plural');
        $pluralHelper->setPluralRule('nplurals=2; plural=n!=1');
    }

    /**
     * {@inheritDoc}
     */
    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }
}


text:
import os
from datetime import datetime

# Run this example with LC_TIME=[other locale] to use a different
# locale's datetime formatting, eg:
#
# LC_TIME=en_US python examples/datetimecol.py
# or
# LC_TIME=en_GB python examples/datetimecol.py
os.environ.setdefault('LC_TIME', 'en_GB')  # noqa

from flask_table import Table, Col, DatetimeCol

class Item(object):
    def __init__(self, name, dt):
        self.name = name
        self.dt = dt

class ItemTable(Table):
    name = Col('Name')
    dt = DatetimeCol('Datetime')

def main():
    items = [
        Item('Name1', datetime.now()),
        Item('Name2', datetime(2018, 1, 1, 12, 34, 56)),
    ]

    table = ItemTable(items)

    # or {{ table }} in jinja
    print(table.__html__())

if __name__ == '__main__':
    main()


text:
require 'helper'
require 'cloudapp/collection_json/collection'

describe CloudApp::CollectionJson::Collection do
  let(:collection) { described_class.new(data) }
  subject { collection }

  describe 'the collection item' do
    let(:data) {{ 'collection' => { 'href' => 'http://href.com' }}}
    its(:href) { should eq 'http://href.com' }
  end

  describe '#items' do
    let(:data) {{
      'collection' => {
        'items' => [
          { 'href' => 'http://one.com' },
          { 'href' => 'http://two.com' } ]}
    }}
    subject { collection.items }

    it { should be_an Array }
    it { should have(2).items }

    it 'returns an array of Items' do
      subject.each do |item|
        item.should be_an CloudApp::CollectionJson::Item
      end

      item = subject.first
      item.href.should eq 'http://one.com'
    end

    context 'with no items' do
      let(:data) {{ 'collection' => {} }}
      it { should be_empty }
    end
  end

  describe '#item' do
    let(:data) {{
      'collection' => {
        'items' => [
          { 'href' => 'http://one.com' },
          { 'href' => 'http://two.com' } ]}}}
    subject { collection.item }

    it { should eq collection.items.first }

    context 'with no items' do
      let(:data) {{ 'collection' => {} }}
      it { should be_nil }
    end
  end

  describe '#template' do
    let(:data) {{
      'collection' => {
        'href' => 'http://href.com',
        'template' => {
          'data' => [
            { 'name' => 'first_name', 'value' => '' },
            { 'name' => 'last_name', 'value' => '' } ]}}}}
    subject { collection.template }

    it { should be_an CloudApp::CollectionJson::Template }
    its(:href) { should eq 'http://href.com' }
    its(:data) { should eq 'first_name' => '', 'last_name' => '' }
  end

  describe '#error' do
    let(:data) {{
      'collection' => {
        'error' => { 'message' => 'error!' }}}}
    subject { collection.error }

    it { should be_an CloudApp::CollectionJson::Item }
    its(:message) { should eq 'error!' }

    context 'with no error' do
      let(:data) {{ 'collection' => {} }}
      it { should be_nil }
    end
  end
end


text:
package org.sakaiproject.sitestats.tool.facade;

import org.sakaiproject.authz.api.AuthzGroupService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.sitestats.api.ServerWideReportManager;
import org.sakaiproject.sitestats.api.StatsAuthz;
import org.sakaiproject.sitestats.api.StatsManager;
import org.sakaiproject.sitestats.api.StatsUpdateManager;
import org.sakaiproject.sitestats.api.chart.ChartService;
import org.sakaiproject.sitestats.api.event.EventRegistryService;
import org.sakaiproject.sitestats.api.event.detailed.DetailedEventsManager;
import org.sakaiproject.sitestats.api.report.ReportManager;
import org.sakaiproject.time.api.UserTimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.UserDirectoryService;

public interface SakaiFacade {

	// SiteStats services

	public StatsManager getStatsManager();
	public StatsAuthz getStatsAuthz();
	public EventRegistryService getEventRegistryService();
	public ReportManager getReportManager();
	public ChartService getChartService();
	public StatsUpdateManager getStatsUpdateManager();
	public ServerWideReportManager getServerWideReportManager();
	public DetailedEventsManager getDetailedEventsManager();

	// Sakai services

	public SessionManager getSessionManager();
	public ToolManager getToolManager();
	public SiteService getSiteService();
	public AuthzGroupService getAuthzGroupService();
	public UserDirectoryService getUserDirectoryService();
	public ContentHostingService getContentHostingService();
	public UserTimeService getUserTimeService();

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Res. 103(5): 611 (1999)

#### Original name
Mycosphaerella syzygii Crous

### Remarks
null


text:
"""
Blocks and related utilities.
"""

from constants.direction import Direction
from simulator.quartet import Quartet, connect_quartets

class Block:
    """
    A group of four quartets (sixteen processing elements) that in hardware share the same clock and reset tree and the same configuration
    logic, MMIO access port, and eventually a load-store queue.
    """

    def __init__(self, name, row_base_index, column_base_index, num_columns, cp, ip):
        """
        Initialize a block.

        :param name: the quartet name
        :param row_base_index: base index for row iteration
        :param column_base_index: base index for column iteration
        :param num_columns: number of columns of processing elements in the entire array
        :param cp: a CoreParameters instance
        :param ip: an InterconnectParameters instance
        """

        # Fill in name, and instantiate underlying quartets.
        self.name = name
        quartet_names = []
        quartet_base_indices = []
        quartet_row_base_index = int(row_base_index / 2)
        quartet_column_base_index = int(column_base_index / 2)
        quartet_num_columns = int(num_columns / 2)
        for i in range(quartet_row_base_index, quartet_column_base_index + 2):
            for j in range(quartet_column_base_index, quartet_column_base_index + 2):
                quartet_index = i * quartet_num_columns + j
                quartet_names.append(f"quartet_{quartet_index}")
                quartet_base_indices.append((i * 2, j * 2))
        self.quartets = []
        for quartet_name, quartet_base_index_tuple in zip(quartet_names, quartet_base_indices):
            self.quartets.append(Quartet(name=quartet_name,
                                         row_base_index=quartet_base_index_tuple[0],
                                         column_base_index=quartet_base_index_tuple[1],
                                         num_columns=num_columns,
                                         cp=cp,
                                         ip=ip))

        # Wire up the quartets.
        for i in range(2):
            for j in range(2):
                if j < 2 - 1:
                    connect_quartets(self.quartets[i * 2 + j],
                                     self.quartets[i * 2 + j + 1],
                                     Direction.east)
                if i < 2 - 1:
                    connect_quartets(self.quartets[i * 2 + j],
                                     self.quartets[(i + 1) * 2 + j],
                                     Direction.south)

    # --- System Registration Method ---

    def _register(self, system):
        """
        Register the block with the system event loop.

        :param system: the rest of the system
        """

        # Add ourselves as a hierarchical element.
        system.blocks.append(self)

        # Call the underlying quartet registration functions.
        for quartet in self.quartets:
            quartet._register(system)

def connect_blocks(block_a, block_b, direction_a_to_b):
    """
    Use the quartet connection function to conveniently connect two quartets along an axis defined by
    direction_a_to_b.

    :param direction_a_to_b: the cardinal direction between processing elements a and b
    :param block_a: the first block
    :param block_b: the second block
    """

    # Possibly something to refactor at some point.
    if direction_a_to_b == Direction.north:
        for j in range(2):
            connect_quartets(block_a.quartets[0 * 2 + j],
                             block_b.quartets[1 * 2 + j],
                             Direction.north)
    elif direction_a_to_b == Direction.east:
        for i in range(2):
            connect_quartets(block_a.quartets[i * 2 + 1],
                             block_b.quartets[i * 2 + 0],
                             Direction.east)
    elif direction_a_to_b == Direction.south:
        for j in range(2):
            connect_quartets(block_a.quartets[1 * 2 + j],
                             block_b.quartets[0 * 2 + j],
                             Direction.south)
    elif direction_a_to_b == Direction.west:
        for i in range(2):
            connect_quartets(block_a.quartets[i * 2 + 0],
                             block_b.quartets[i * 2 + 1],
                             Direction.west)
    else:
        raise RuntimeError("Invalid direction to connect two blocks.")


text:
using Newtonsoft.Json;
using System.Collections.Generic;
using ZKWeb.Localize;
using ZKWeb.Plugins.Common.Base.src.UIComponents.Forms;
using ZKWeb.Plugins.Common.Base.src.UIComponents.Forms.Interfaces;
using ZKWeb.Plugins.Shopping.Product.src.Domain.Structs;
using ZKWeb.Plugins.Shopping.Product.src.UIComponents.FormFieldAttributes;
using ZKWeb.Templating;
using ZKWebStandard.Ioc;

namespace ZKWeb.Plugins.Shopping.Product.src.UIComponents.FormFieldHandlers {
	/// <summary>
	/// 商品关联的属性值的编辑器
	/// 编辑商品时使用
	/// </summary>
	[ExportMany(ContractKey = typeof(ProductToProperyValuesEditorAttribute)), SingletonReuse]
	public class ProductToProperyValuesEditor : IFormFieldHandler {
		/// <summary>
		/// 获取表单字段的html
		/// </summary>
		public string Build(FormField field, IDictionary<string, string> htmlAttributes) {
			var attribute = (ProductToProperyValuesEditorAttribute)field.Attribute;
			var templateManager = Application.Ioc.Resolve<TemplateManager>();
			var translations = new Dictionary<string, string>() {
				{ "Sure to change category? The properties you selected will lost!",
					new T("Sure to change category? The properties you selected will lost!") }
			};
			return templateManager.RenderTemplate(
				"shopping.product/tmpl.form.product_to_property_values_editor.html", new {
					name = attribute.Name,
					value = JsonConvert.SerializeObject(field.Value),
					attributes = htmlAttributes,
					categoryFieldName = attribute.CategoryFieldName,
					translations = JsonConvert.SerializeObject(translations)
				});
		}

		/// <summary>
		/// 解析提交的字段的值
		/// </summary>
		public object Parse(FormField field, IList<string> values) {
			return JsonConvert.DeserializeObject<List<ProductToPropertyValueForEdit>>(values[0]) ??
				new List<ProductToPropertyValueForEdit>();
		}
	}
}


text:
<?php

(!defined('SISTEMA')) ? exit('No se permite el acceso directo al script.') : false;
// cargar ayudas
$config['ayudas']    = array('ecos','recursos','sis_sql','sql', 'arreglos');
// cargar librerias
$config['librerias'] = array();
// carga de modelos
$config['modelos']   = array();


text:
require 'forwardable'
require 'twitter/default'
require 'twitter/error/configuration_error'

module Twitter
  module Configurable
    extend Forwardable
    attr_writer :consumer_secret, :oauth_token, :oauth_token_secret, :bearer_token
    attr_accessor :consumer_key, :endpoint, :connection_options, :identity_map, :middleware
    def_delegator :options, :hash

    class << self

      def keys
        @keys ||= [
          :consumer_key,
          :consumer_secret,
          :oauth_token,
          :oauth_token_secret,
          :bearer_token,
          :endpoint,
          :connection_options,
          :identity_map,
          :middleware,
        ]
      end

    end

    # Convenience method to allow configuration options to be set in a block
    #
    # @raise [Twitter::Error::ConfigurationError] Error is raised when supplied
    #   twitter credentials are not a String or Symbol.
    def configure
      yield self
      validate_credential_type!
      self
    end

    def reset!
      Twitter::Configurable.keys.each do |key|
        instance_variable_set(:"@#{key}", Twitter::Default.options[key])
      end
      self
    end
    alias setup reset!

    # @return [Boolean]
    def user_token?
      !!(@oauth_token && @oauth_token_secret)
    end

    # @return [Boolean]
    def bearer_token?
      !!@bearer_token
    end

    # @return [Boolean]
    def credentials?
      credentials.values.all? || bearer_token?
    end

  private

    # @return [Hash]
    def credentials
      {
        :consumer_key    => @consumer_key,
        :consumer_secret => @consumer_secret,
        :token           => @oauth_token,
        :token_secret    => @oauth_token_secret,
      }
    end

    # @return [Hash]
    def options
      Hash[Twitter::Configurable.keys.map{|key| [key, instance_variable_get(:"@#{key}")]}]
    end

    # Ensures that all credentials set during configuration are of a
    # valid type. Valid types are String and Symbol.
    #
    # @raise [Twitter::Error::ConfigurationError] Error is raised when
    #   supplied twitter credentials are not a String or Symbol.
    def validate_credential_type!
      credentials.each do |credential, value|
        next if value.nil?

        unless value.is_a?(String) || value.is_a?(Symbol)
          raise(Error::ConfigurationError, "Invalid #{credential} specified: #{value} must be a string or symbol.")
        end
      end
    end

  end
end


text:
title:  UYesu, UMthetheli Womnqophiso Omtsha
date:  12/02/2022
---

### Fundela Le Veki
Heb. 7:11–19; Heb. 8:10–12; Yer. 31:31–34; Heb. 8:1–6; Eks. 24:1–8; Hezek. 36:26, 27.

>
Indima Yenkumbulo "Kanti ke, njengoko kunjalo, uKristu uzuze ulungiselelo oluhle kakhulu kunoludala kuba umnqophiso awuthethelayo ungaphezulu, njengoko wenziwe phezu kwezithembiso ezilunge kakhulu" (Hebhere 8:6, ESV).

> Ngokuphila ubomi obugqibeleleyo, nangokufa endaweni yethu uYesu walicima ityala lokufa okwakufuneka ngenxa yezikreqo zethu waza wenza ukuba ukwazi ukubakho umnqophiso omtsha.

Le nyaniso ichazwe kumaHebhere 10:5–10, ambona uYesu ebonakalalise ukuthobela okufezekileyo okufunwa ngumnqophiso. Acaphula INdumiso 40, eyayibhekisa ekuqaleni kumnqweno kaDavide wokunikela kuThixo ukuthobela okupheleleyo: "Yabona, Ndiyeza; encwadini esongwayo kubhalwe ngam. Ukwenza okulikholo kuwe, Thixo wam, ndikunanzile; umthetho wakho ungaphakathi entliziyweni yam'" (INd. 40:7, 8, ESV). Le Ndumiso yayibeka imeko yomnqophiso kaThixo noIsrayeli: ukuthobela okwakuluvuyo nomthetho owawubhalwe entliziyweni (Dut. 6:4–6). Kanti ke, into eyayikuphela komnqweno kaDavide, uYesu wayifeza.

KuPawulos, le Ndumiso yaba nokubaluleka okukodwa ngokuzalwa kukaYesu [esenyameni]. UYesu wayeyintlanganisela yokuthobela komnqophiso omtsha. Ungumzekelo wethu. Sisindisiwe, kungekuphela ngenxa yokufa kwaKhe, kodwa nangenxa yokuthobela kwaKhe okugqibeleleyo.

*Funda isifundo sale veki ulungiselela iSabatha kaFebruwari 19.


text:
<?php namespace PHPFHIRGenerated\FHIRDomainResource;

use PHPFHIRGenerated\FHIRResource\FHIRDomainResource;
use PHPFHIRGenerated\JsonSerializable;

/**
 * Represents a defined collection of entities that may be discussed or acted upon collectively but which are not expected to act collectively and are not formally or legally recognized; i.e. a collection of entities that isn't an Organization.
 * If the element is present, it must have either a @value, an @id, or extensions
 */
class FHIRGroup extends FHIRDomainResource implements JsonSerializable
{
    /**
     * A unique business identifier for this group.
     * @var \PHPFHIRGenerated\FHIRElement\FHIRIdentifier[]
     */
    public $identifier = array();

    /**
     * Identifies the broad classification of the kind of resources the group includes.
     * @var \PHPFHIRGenerated\FHIRElement\FHIRGroupType
     */
    public $type = null;

    /**
     * If true, indicates that the resource refers to a specific group of real individuals.  If false, the group defines a set of intended individuals.
     * @var \PHPFHIRGenerated\FHIRElement\FHIRBoolean
     */
    public $actual = null;

    /**
     * Provides a specific type of resource the group includes; e.g. "cow", "syringe", etc.
     * @var \PHPFHIRGenerated\FHIRElement\FHIRCodeableConcept
     */
    public $code = null;

    /**
     * A label assigned to the group for human identification and communication.
     * @var \PHPFHIRGenerated\FHIRElement\FHIRString
     */
    public $name = null;

    /**
     * A count of the number of resource instances that are part of the group.
     * @var \PHPFHIRGenerated\FHIRElement\FHIRUnsignedInt
     */
    public $quantity = null;

    /**
     * Identifies the traits shared by members of the group.
     * @var \PHPFHIRGenerated\FHIRResource\FHIRGroup\FHIRGroupCharacteristic[]
     */
    public $characteristic = array();

    /**
     * Identifies the resource instances that are members of the group.
     * @var \PHPFHIRGenerated\FHIRResource\FHIRGroup\FHIRGroupMember[]
     */
    public $member = array();

    /**
     * @var string
     */
    private $_fhirElementName = 'Group';

    /**
     * A unique business identifier for this group.
     * @return \PHPFHIRGenerated\FHIRElement\FHIRIdentifier[]
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * A unique business identifier for this group.
     * @param \PHPFHIRGenerated\FHIRElement\FHIRIdentifier[] $identifier
     * @return $this
     */
    public function addIdentifier($identifier)
    {
        $this->identifier[] = $identifier;
        return $this;
    }

    /**
     * Identifies the broad classification of the kind of resources the group includes.
     * @return \PHPFHIRGenerated\FHIRElement\FHIRGroupType
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Identifies the broad classification of the kind of resources the group includes.
     * @param \PHPFHIRGenerated\FHIRElement\FHIRGroupType $type
     * @return $this
     */
    public function setType($type)
    {
        $this->type = $type;
        return $this;
    }

    /**
     * If true, indicates that the resource refers to a specific group of real individuals.  If false, the group defines a set of intended individuals.
     * @return \PHPFHIRGenerated\FHIRElement\FHIRBoolean
     */
    public function getActual()
    {
        return $this->actual;
    }

    /**
     * If true, indicates that the resource refers to a specific group of real individuals.  If false, the group defines a set of intended individuals.
     * @param \PHPFHIRGenerated\FHIRElement\FHIRBoolean $actual
     * @return $this
     */
    public function setActual($actual)
    {
        $this->actual = $actual;
        return $this;
    }

    /**
     * Provides a specific type of resource the group includes; e.g. "cow", "syringe", etc.
     * @return \PHPFHIRGenerated\FHIRElement\FHIRCodeableConcept
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Provides a specific type of resource the group includes; e.g. "cow", "syringe", etc.
     * @param \PHPFHIRGenerated\FHIRElement\FHIRCodeableConcept $code
     * @return $this
     */
    public function setCode($code)
    {
        $this->code = $code;
        return $this;
    }

    /**
     * A label assigned to the group for human identification and communication.
     * @return \PHPFHIRGenerated\FHIRElement\FHIRString
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * A label assigned to the group for human identification and communication.
     * @param \PHPFHIRGenerated\FHIRElement\FHIRString $name
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * A count of the number of resource instances that are part of the group.
     * @return \PHPFHIRGenerated\FHIRElement\FHIRUnsignedInt
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * A count of the number of resource instances that are part of the group.
     * @param \PHPFHIRGenerated\FHIRElement\FHIRUnsignedInt $quantity
     * @return $this
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
        return $this;
    }

    /**
     * Identifies the traits shared by members of the group.
     * @return \PHPFHIRGenerated\FHIRResource\FHIRGroup\FHIRGroupCharacteristic[]
     */
    public function getCharacteristic()
    {
        return $this->characteristic;
    }

    /**
     * Identifies the traits shared by members of the group.
     * @param \PHPFHIRGenerated\FHIRResource\FHIRGroup\FHIRGroupCharacteristic[] $characteristic
     * @return $this
     */
    public function addCharacteristic($characteristic)
    {
        $this->characteristic[] = $characteristic;
        return $this;
    }

    /**
     * Identifies the resource instances that are members of the group.
     * @return \PHPFHIRGenerated\FHIRResource\FHIRGroup\FHIRGroupMember[]
     */
    public function getMember()
    {
        return $this->member;
    }

    /**
     * Identifies the resource instances that are members of the group.
     * @param \PHPFHIRGenerated\FHIRResource\FHIRGroup\FHIRGroupMember[] $member
     * @return $this
     */
    public function addMember($member)
    {
        $this->member[] = $member;
        return $this;
    }

    /**
     * @return string
     */
    public function get_fhirElementName()
    {
        return $this->_fhirElementName;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->get_fhirElementName();
    }

    /**
     * @return array
     */
    public function jsonSerialize()
    {
        $json = parent::jsonSerialize();
        $json['resourceType'] = $this->_fhirElementName;
        if (0 < count($this->identifier)) {
            $json['identifier'] = array();
            foreach($this->identifier as $identifier) {
                $json['identifier'][] = $identifier->jsonSerialize();
            }
        }
        if (null !== $this->type) $json['type'] = $this->type->jsonSerialize();
        if (null !== $this->actual) $json['actual'] = $this->actual->jsonSerialize();
        if (null !== $this->code) $json['code'] = $this->code->jsonSerialize();
        if (null !== $this->name) $json['name'] = $this->name->jsonSerialize();
        if (null !== $this->quantity) $json['quantity'] = $this->quantity->jsonSerialize();
        if (0 < count($this->characteristic)) {
            $json['characteristic'] = array();
            foreach($this->characteristic as $characteristic) {
                $json['characteristic'][] = $characteristic->jsonSerialize();
            }
        }
        if (0 < count($this->member)) {
            $json['member'] = array();
            foreach($this->member as $member) {
                $json['member'][] = $member->jsonSerialize();
            }
        }
        return $json;
    }

    /**
     * @param boolean $returnSXE
     * @param \SimpleXMLElement $sxe
     * @return string|\SimpleXMLElement
     */
    public function xmlSerialize($returnSXE = false, $sxe = null)
    {
        if (null === $sxe) $sxe = new \SimpleXMLElement('<Group xmlns="http://hl7.org/fhir"></Group>');
        parent::xmlSerialize(true, $sxe);
        if (0 < count($this->identifier)) {
            foreach($this->identifier as $identifier) {
                $identifier->xmlSerialize(true, $sxe->addChild('identifier'));
            }
        }
        if (null !== $this->type) $this->type->xmlSerialize(true, $sxe->addChild('type'));
        if (null !== $this->actual) $this->actual->xmlSerialize(true, $sxe->addChild('actual'));
        if (null !== $this->code) $this->code->xmlSerialize(true, $sxe->addChild('code'));
        if (null !== $this->name) $this->name->xmlSerialize(true, $sxe->addChild('name'));
        if (null !== $this->quantity) $this->quantity->xmlSerialize(true, $sxe->addChild('quantity'));
        if (0 < count($this->characteristic)) {
            foreach($this->characteristic as $characteristic) {
                $characteristic->xmlSerialize(true, $sxe->addChild('characteristic'));
            }
        }
        if (0 < count($this->member)) {
            foreach($this->member as $member) {
                $member->xmlSerialize(true, $sxe->addChild('member'));
            }
        }
        if ($returnSXE) return $sxe;
        return $sxe->saveXML();
    }

}


text:
package ddf.minim.analysis;

import ddf.minim.AudioBuffer;
import ddf.minim.Minim;

/**
 * The BeatDetect class allows you to analyze an audio stream for beats (rhythmic onsets).
 * Beat
 * Detection Algorithms by Frederic Patin describes beats in the following
 * way:
 The human listening system determines the rhythm of music
 * by detecting a pseudo periodical succession of beats. The signal which is
 * intercepted by the ear contains a certain energy, this energy is converted
 * into an electrical signal which the brain interprets. Obviously, The more
 * energy the sound transports, the louder the sound will seem. But a sound will
 * be heard as a beat only if his energy is largely superior to the
 * sound's energy history, that is to say if the brain detects a
 * brutal variation in sound energy. Therefore if the ear intercepts
 * a monotonous sound with sometimes big energy peaks it will detect beats,
 * however, if you play a continuous loud sound you will not perceive any beats.
 * Thus, the beats are big variations of sound energy.
 In fact,
 * the two algorithms in this class are based on two algorithms described in
 * that paper.
 *

 * To use this class, inside of draw() you must first call
 * detect(), passing the AudioBuffer you want to
 * analyze. You may then use the isXXX functions to find out what
 * beats have occurred in that frame. For example, you might use
 * isKick() to cause a circle to pulse.
 *

 * BeatDetect has two modes: sound energy tracking and frequency energy
 * tracking. In sound energy mode, the level of the buffer, as returned by
 * level(), is used as the instant energy in each frame. Beats,
 * then, are spikes in this value, relative to the previous one second of sound.
 * In frequency energy mode, the same process is used but instead of tracking
 * the level of the buffer, an FFT is used to obtain a spectrum, which is then
 * divided into average bands using logAverages(), and each of
 * these bands is tracked individually. The result is that it is possible to
 * track sounds that occur in different parts of the frequency spectrum
 * independently (like the kick drum and snare drum).
 *

 * In sound energy mode you use isOnset() to query the algorithm
 * and in frequency energy mode you use isOnset(int i),
 * isKick(), isSnare(), and
 * isRange() to query particular frequnecy bands or ranges of
 * frequency bands. It should be noted that isKick(),
 * isSnare(), and isHat() merely call
 * isRange() with values determined by testing the algorithm
 * against music with a heavy beat and they may not be appropriate for all kinds
 * of music. If you find they are performing poorly with your music, you should
 * use isRange() directly to locate the bands that provide the
 * most meaningful information for you.
 *
 * @author Damien Di Fede
 *
 * @example Analysis/SoundEnergyBeatDetection
 */

public class BeatDetect
{
	/** Constant used to request frequency energy tracking mode.
	 *
	 *  @example Analysis/FrequencyEnergyBeatDetection
	 */
	public static final int	FREQ_ENERGY		= 0;

	/** Constant used to request sound energy tracking mode.
	 *
	 *  @example Analysis/SoundEnergyBeatDetection
	 */
	public static final int	SOUND_ENERGY	= 1;

	private int					algorithm;
	private int					sampleRate;
	private int					timeSize;
	private int					valCnt;
	private float[]			valGraph;
	private int					sensitivity;
	// for circular buffer support
	private int					insertAt;
	// vars for sEnergy
	private boolean			isOnset;
	private float[]			eBuffer;
	private float[]			dBuffer;
	private long				timer;
	// vars for fEnergy
	private boolean[]			fIsOnset;
	private FFT					spect;
	private float[][]			feBuffer;
	private float[][]			fdBuffer;
	private long[]				fTimer;
	private float[]			varGraph;
	private int					varCnt;

	/**
	 * Create a BeatDetect object that is in SOUND_ENERGY mode.
	 * timeSize and sampleRate will be set to 1024
	 * and 44100, respectively, so that it is possible to switch into FREQ_ENERGY
	 * mode with meaningful values.
	 *
	 */
	public BeatDetect()
	{
		sampleRate = 44100;
		timeSize = 1024;
		initSEResources();
		initGraphs();
		algorithm = SOUND_ENERGY;
		sensitivity = 10;
	}

	/**
	 * Create a BeatDetect object that is in FREQ_ENERGY mode and expects a
	 * sample buffer with the requested attributes.
	 *
	 * @param timeSize
	 *           int: the size of the buffer
	 * @param sampleRate
	 *           float: the sample rate of the samples in the buffer
	 *
	 * @related BeatDetect
	 */
	public BeatDetect(int timeSize, float sampleRate)
	{
		this.sampleRate = (int) sampleRate;
		this.timeSize = timeSize;
		initFEResources();
		initGraphs();
		algorithm = FREQ_ENERGY;
		sensitivity = 10;
	}

	/**
	 * Set the object to use the requested algorithm. If an invalid value is
	 * passed, the function will report and error and default to
	 * BeatDetect.SOUND_ENERGY
	 *
	 * @param algo
	 *           int: either BeatDetect.SOUND_ENERGY or BeatDetect.FREQ_ENERGY
	 *
	 * @related BeatDetect
	 */
	public void detectMode(int algo)
	{
		if (algo < 0 || algo > 1)
		{
			Minim.error("Unrecognized detect mode, defaulting to SOUND_ENERGY.");
			algo = SOUND_ENERGY;
		}
		if (algo == SOUND_ENERGY)
		{
			if (algorithm == FREQ_ENERGY)
			{
				releaseFEResources();
				initSEResources();
				initGraphs();
				algorithm = algo;
			}
		}
		else
		{
			if (algorithm == SOUND_ENERGY)
			{
				releaseSEResources();
				initFEResources();
				initGraphs();
				algorithm = FREQ_ENERGY;
			}
		}
	}

	private void initGraphs()
	{
		valCnt = varCnt = 0;
		valGraph = new float[512];
		varGraph = new float[512];
	}

	private void initSEResources()
	{
		isOnset = false;
		eBuffer = new float[sampleRate / timeSize];
		dBuffer = new float[sampleRate / timeSize];
		timer = System.currentTimeMillis();
		insertAt = 0;
	}

	private void initFEResources()
	{
		spect = new FFT(timeSize, sampleRate);
		spect.logAverages(60, 3);
		int numAvg = spect.avgSize();
		fIsOnset = new boolean[numAvg];
		feBuffer = new float[numAvg][sampleRate / timeSize];
		fdBuffer = new float[numAvg][sampleRate / timeSize];
		fTimer = new long[numAvg];
		long start = System.currentTimeMillis();
		for (int i = 0; i < fTimer.length; i++)
		{
			fTimer[i] = start;
		}
		insertAt = 0;
	}

	private void releaseSEResources()
	{
		isOnset = false;
		eBuffer = null;
		dBuffer = null;
		timer = 0;
	}

	private void releaseFEResources()
	{
		spect = null;
		fIsOnset = null;
		feBuffer = null;
		fdBuffer = null;
		fTimer = null;
	}

	/**
	 * Analyze the samples in buffer.
	 * This is a cumulative process, so you must call this function every frame.
	 *
	 * @param buffer
	 *           AudioBuffer: the buffer to analyze.
	 *
	 * @example Analysis/SoundEnergyBeatDetection
	 *
	 * @related BeatDetect
	 */
	public void detect(AudioBuffer buffer)
	{
		detect( buffer.toArray() );
	}

	/**
	 * Analyze the samples in buffer. This is a cumulative
	 * process, so you must call this function every frame.
	 *
	 * @param buffer
	 *           float[]: the buffer to analyze
	 *
	 * @related BeatDetect
	 */
	public void detect(float[] buffer)
	{
		switch (algorithm)
		{
		case SOUND_ENERGY:
			sEnergy(buffer);
			break;
		case FREQ_ENERGY:
			fEnergy(buffer);
			break;
		}
	}

	/**
	 * In frequency energy mode this returns the number of frequency bands
	 * currently being used. In sound energy mode this always returns 0.
	 *
	 * @return int: the length of the FFT's averages array
	 *
	 * @related BeatDetect
	 */
	public int dectectSize()
	{
	  if ( algorithm == FREQ_ENERGY )
	  {
	    return spect.avgSize();
	  }

	  return 0;
	}

	/**
	 * Returns the center frequency of the ith frequency band.
	 * In sound energy mode this always returns 0.
	 *
	 * @param i
	 *     int: which detect band you want the center frequency of.
	 *
	 *  @return float: the center frequency of the ith frequency band
	 *
	 *  @related BeatDetect
	 */
	public float getDetectCenterFrequency(int i)
	{
	  if ( algorithm == FREQ_ENERGY )
	  {
	    return spect.getAverageCenterFrequency(i);
	  }

	  return 0;
	}

	/**
	 * Sets the sensitivity of the algorithm. After a beat has been detected, the
	 * algorithm will wait for millis milliseconds before allowing
	 * another beat to be reported. You can use this to dampen the algorithm if
	 * it is giving too many false-positives. The default value is 10, which is
	 * essentially no damping. If you try to set the sensitivity to a negative
	 * value, an error will be reported and it will be set to 10 instead.
	 *
	 * @param millis
	 *           int: the sensitivity in milliseconds
	 *
	 * @example Analysis/FrequencyEnergyBeatDetection
	 *
	 * @related BeatDetect
	 */
	public void setSensitivity(int millis)
	{
		if (millis < 0)
		{
			Minim.error("BeatDetect: sensitivity cannot be less than zero. Defaulting to 10.");
			sensitivity = 10;
		}
		else
		{
			sensitivity = millis;
		}
	}

	/**
	 * In sound energy mode this returns true when a beat has been detected. In
	 * frequency energy mode this always returns false.
	 *
	 * @return boolean: true if a beat has been detected.
	 *
	 * @example Analysis/SoundEnergyBeatDetection
	 *
	 * @related BeatDetect
	 */
	public boolean isOnset()
	{
		return isOnset;
	}

	/**
	 * In frequency energy mode this returns true when a beat has been detect in
	 * the ith frequency band. In sound energy mode
	 * this always returns false.
	 *
	 * @param i
	 *           int: the frequency band to query
	 * @return boolean: true if a beat has been detected in the requested band
	 *
	 * @example Analysis/SoundEnergyBeatDetection
	 *
	 * @related BeatDetect
	 */
	public boolean isOnset(int i)
	{
		if (algorithm == SOUND_ENERGY)
		{
			return false;
		}
		return fIsOnset[i];
	}

	/**
	 * In frequency energy mode this returns true if a beat corresponding to the
	 * frequency range of a kick drum has been detected. This has been tuned to
	 * work well with dance / techno music and may not perform well with other
	 * styles of music. In sound energy mode this always returns false.
	 *
	 * @return boolean: true if a kick drum beat has been detected
	 *
	 * @example Analysis/FrequencyEnergyBeatDetection
	 *
	 * @related BeatDetect
	 */
	public boolean isKick()
	{
		if (algorithm == SOUND_ENERGY)
		{
			return false;
		}
		int upper = 6 >= spect.avgSize() ? spect.avgSize() : 6;
		return isRange(1, upper, 2);
	}

	/**
	 * In frequency energy mode this returns true if a beat corresponding to the
	 * frequency range of a snare drum has been detected. This has been tuned to
	 * work well with dance / techno music and may not perform well with other
	 * styles of music. In sound energy mode this always returns false.
	 *
	 * @return boolean: true if a snare drum beat has been detected
	 *
	 * @example Analysis/FrequencyEnergyBeatDetection
	 *
	 * @related BeatDetect
	 */
	public boolean isSnare()
	{
		if (algorithm == SOUND_ENERGY)
		{
			return false;
		}
		int lower = 8 >= spect.avgSize() ? spect.avgSize() : 8;
		int upper = spect.avgSize() - 1;
		int thresh = (upper - lower) / 3 + 1;
		return isRange(lower, upper, thresh);
	}

	/**
	 * In frequency energy mode this returns true if a beat corresponding to the
	 * frequency range of a hi hat has been detected. This has been tuned to work
	 * well with dance / techno music and may not perform well with other styles
	 * of music. In sound energy mode this always returns false.
	 *
	 * @return boolean: true if a hi hat beat has been detected
	 *
	 * @example Analysis/FrequencyEnergyBeatDetection
	 *
	 * @related BeatDetect
	 */
	public boolean isHat()
	{
		if (algorithm == SOUND_ENERGY)
		{
			return false;
		}
		int lower = spect.avgSize() - 7 < 0 ? 0 : spect.avgSize() - 7;
		int upper = spect.avgSize() - 1;
		return isRange(lower, upper, 1);
	}

	/**
	 * In frequency energy mode this returns true if at least
	 * threshold bands of the bands included in the range
	 * [low, high] have registered a beat. In sound energy mode
	 * this always returns false.
	 *
	 * @param low
	 *           int: the index of the lower band
	 * @param high
	 *           int: the index of the higher band
	 * @param threshold
	 *           int: the smallest number of bands in the range
	 *           [low, high] that need to have registered a beat
	 *           for this to return true
	 * @return boolean: true if at least threshold bands of the bands
	 *         included in the range [low, high] have registered a
	 *         beat
	 *
	 * @related BeatDetect
	 */
	public boolean isRange(int low, int high, int threshold)
	{
		if (algorithm == SOUND_ENERGY)
		{
			return false;
		}
		int num = 0;
		for (int i = low; i < high + 1; i++)
		{
			if (isOnset(i))
			{
				num++;
			}
		}
		return num >= threshold;
	}

	/**
	 * Draws some debugging visuals in the passed PApplet. The visuals drawn when
	 * in frequency energy mode are a good way to determine what values to use
	 * with inRange() if the provided drum detecting functions
	 * aren't what you need or aren't working well.
	 *
	 * @param p
	 *           the PApplet to draw in
	 */
//	public void drawGraph(PApplet p)
//	{
//		if (algorithm == SOUND_ENERGY)
//		{
//			// draw valGraph
//			for (int i = 0; i < valCnt; i++)
//			{
//				p.stroke(255);
//				p.line(i, (p.height / 2) - valGraph[i], i, (p.height / 2)
//						+ valGraph[i]);
//			}
//			// draw varGraph
//			for (int i = 0; i < varCnt - 1; i++)
//			{
//				p.stroke(255);
//				p.line(i, p.height - varGraph[i], i + 1, p.height - varGraph[i + 1]);
//			}
//		}
//		else
//		{
//			p.strokeWeight(5);
//			for (int i = 0; i < fTimer.length; i++)
//			{
//				int c = (i % 3 == 0) ? p.color(255, 0, 0) : p.color(255);
//				p.stroke(c);
//				long clock = System.currentTimeMillis();
//				if (clock - fTimer[i] < sensitivity)
//				{
//					float h = PApplet.map(clock - fTimer[i], 0, sensitivity, 100, 0);
//					p.line((i * 10), p.height - h, (i * 10), p.height);
//				}
//			}
//		}
//	}

	private void sEnergy(float[] samples)
	{
		// compute the energy level
		float level = 0;
		for (int i = 0; i < samples.length; i++)
		{
			level += (samples[i] * samples[i]);
		}
		level /= samples.length;
		level = (float) Math.sqrt(level);
		float instant = level * 100;
		// compute the average local energy
		float E = average(eBuffer);
		// compute the variance of the energies in eBuffer
		float V = variance(eBuffer, E);
		// compute C using a linear digression of C with V
		float C = (-0.0025714f * V) + 1.5142857f;
		// filter negaive values
		float diff = (float)Math.max(instant - C * E, 0);
		pushVal(diff);
		// find the average of only the positive values in dBuffer
		float dAvg = specAverage(dBuffer);
		// filter negative values
		float diff2 = (float)Math.max(diff - dAvg, 0);
		pushVar(diff2);
		// report false if it's been less than 'sensitivity'
		// milliseconds since the last true value
		if (System.currentTimeMillis() - timer < sensitivity)
		{
			isOnset = false;
		}
		// if we've made it this far then we're allowed to set a new
		// value, so set it true if it deserves to be, restart the timer
		else if (diff2 > 0 && instant > 2)
		{
			isOnset = true;
			timer = System.currentTimeMillis();
		}
		// OMG it wasn't true!
		else
		{
			isOnset = false;
		}
		eBuffer[insertAt] = instant;
		dBuffer[insertAt] = diff;
		insertAt++;
		if (insertAt == eBuffer.length)
			insertAt = 0;
	}

	private void fEnergy(float[] in)
	{
		spect.forward(in);
		float instant, E, V, C, diff, dAvg, diff2;
		for (int i = 0; i < feBuffer.length; i++)
		{
			instant = spect.getAvg(i);
			E = average(feBuffer[i]);
			V = variance(feBuffer[i], E);
			C = (-0.0025714f * V) + 1.5142857f;
			diff = (float)Math.max(instant - C * E, 0);
			dAvg = specAverage(fdBuffer[i]);
			diff2 = (float)Math.max(diff - dAvg, 0);
			if (System.currentTimeMillis() - fTimer[i] < sensitivity)
			{
				fIsOnset[i] = false;
			}
			else if (diff2 > 0)
			{
				fIsOnset[i] = true;
				fTimer[i] = System.currentTimeMillis();
			}
			else
			{
				fIsOnset[i] = false;
			}
			feBuffer[i][insertAt] = instant;
			fdBuffer[i][insertAt] = diff;
		}
		insertAt++;
		if (insertAt == feBuffer[0].length)
		{
			insertAt = 0;
		}
	}

	private void pushVal(float v)
	{
		// println(valCnt);
		if (valCnt == valGraph.length)
		{
			valCnt = 0;
			valGraph = new float[valGraph.length];
		}
		valGraph[valCnt] = v;
		valCnt++;
	}

	private void pushVar(float v)
	{
		// println(valCnt);
		if (varCnt == varGraph.length)
		{
			varCnt = 0;
			varGraph = new float[varGraph.length];
		}
		varGraph[varCnt] = v;
		varCnt++;
	}

	private float average(float[] arr)
	{
		float avg = 0;
		for (int i = 0; i < arr.length; i++)
		{
			avg += arr[i];
		}
		avg /= arr.length;
		return avg;
	}

	private float specAverage(float[] arr)
	{
		float avg = 0;
		float num = 0;
		for (int i = 0; i < arr.length; i++)
		{
			if (arr[i] > 0)
			{
				avg += arr[i];
				num++;
			}
		}
		if (num > 0)
		{
			avg /= num;
		}
		return avg;
	}

	private float variance(float[] arr, float val)
	{
		float V = 0;
		for (int i = 0; i < arr.length; i++)
		{
			V += (float)Math.pow(arr[i] - val, 2);
		}
		V /= arr.length;
		return V;
	}
}


text:
import os

import pytest

from whoisp.parser import MainParser

TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_data')

def domain_list():
    domains = [domain for domain in os.listdir(TEST_DATA_PATH) if not domain.startswith('.')]
    return domains

@pytest.mark.parametrize(
    'zone', domain_list()
)
def test_parser(zone):
    domain = 'test.{}'.format(zone)
    zone_file = os.path.join(TEST_DATA_PATH, zone)
    with open(zone_file) as f:
        raw_whois = f.read()

    parser = MainParser.load(domain, raw_whois=raw_whois)
    whois_data = parser.parsed
    assert any(whois_data.values())


text:
using SharpDX;
using System;

#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
    namespace Utilities
    {
        public class UniformRandomVectorGenerator : IRandomVector
        {
            public Vector3 MinVector { set; get; } = -Vector3.One;

            public Vector3 MaxVector { set; get; } = Vector3.One;

            public Vector3 RandomVector3
            {
                get
                {
                    return random.NextVector3(MinVector, MaxVector);
                }
            }

            public uint Seed
            {
                get
                {
                    return (uint)Math.Abs(random.Next());
                }
            }

            private readonly Random random = new Random(Environment.TickCount);
        }
    }
}


text:
package postgra.app;

import vellum.jx.JMap;

/**
 *
 * @author evan.summers
 */
public interface PostgraHttpxHandler {

    public JMap handle(PostgraApp app, PostgraHttpx httpx) throws Exception;
}


text:
from common_fixtures import *  # NOQA

import requests

def test_proxy(client, admin_user_client):
    domain = 'releases.rancher.com'
    s = admin_user_client.by_id_setting('api.proxy.whitelist')

    if domain not in s.value:
        s.value += ',{}'.format(domain)
        admin_user_client.update(s, value=s.value)

    def func():
        s = admin_user_client.by_id_setting('api.proxy.whitelist')
        return domain in s.activeValue

    wait_for(func)

    base_url = client.schema.types['schema'].links['collection']
    base_url = base_url.replace('/schemas', '')

    r = requests.get(base_url + '/proxy/{}/{}'.format(domain,
                                                      'ui/latest/humans.txt'),
                     headers=auth_header_map(client))

    assert r.status_code == 200
    assert 'Darren' in r.text

def test_aws_proxy(client):
    base_url = client.schema.types['schema'].links['collection']
    base_url = base_url.replace('/schemas', '')

    host = 'ec2.us-west-2.amazonaws.com'
    r = requests.post(base_url + '/proxy/{}'.format(host),
                      headers=auth_header_map(client))

    assert r.status_code == 400