text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Android extends CI_Controller {

	public function __construct() {
	    parent::__construct();
	    LibsLoader();
	    $this->load->model('Lessee');
	    $this->load->model('Category');
	    $this->load->model('RentalShop');
	    $this->load->model('AndroidModel');
	    $this->load->model('MyInterest');
	    $this->load->model('MyShop');
	    $this->load->library('MyPusher');
		$this->Lessee->setId($this->session->userdata('lessee_id'));
		$this->MyShop->setLesseeId($this->session->userdata('lessee_id'));
		$this->MyInterest->setLesseeId($this->session->userdata('lessee_id'));
	}

	public function index(){

		$module = $this->input->post("module") ;
		$data = array();
		$success = 1;

		switch($module){

			case '1': // login
				$this->Lessee->setUsername($this->input->post('username', TRUE));
				$this->Lessee->setPassword($this->input->post('password', TRUE));
				$user = $this->Lessee->authenticate();

				if(!empty($user)){
					$userdata = array(
					    'lessee_id' => $user['lessee_id'],
					    'username' => $user['username'],
					    'lessee_fname' => $user['lessee_fname'],
					    'lessee_lname' => $user['lessee_lname'],
					    'lessee_email' => $user['lessee_email'],
					    'lessee_phoneno' => $user['lessee_phoneno'],
					    'image' => $user['image'],
					    'logged_in' => TRUE
					);
					$this->session->set_userdata($userdata);
					$data['result'] = "Login Successful";
					$data['user_id'] = $user['lessee_id'];
					$success = 1;

				}else{
					$data['result'] = "Login Failed.";
					$success = 0;
				}
				break;
			case '2': // fetch items by category

				$data['items'] = $this->AndroidModel->getItemsPerCategory($this->input->post('id', TRUE));
				$success = 1;
				break;
			case '3': // get all shops
				$data['shops'] = $this->RentalShop->all($select = "*");
				$success = 1;
				break;
			case '4': // get items by shop
				$data['items'] = $this->AndroidModel->getItemsPerShop($this->input->post('id', TRUE));
				$success = 1;
				break;
			case '5': // get interest items
				$data['items']= $this->AndroidModel->getInterestsItems($this->input->post('id', TRUE));
				$success = 1;
				break;
			case '6': // get all items
				$data['items']= $this->AndroidModel->getAllItems();
				$success = 1;
				break;
			case '40': //  get myshops

				$data['shops'] = $this->AndroidModel->getShopsByLesseeId($this->input->post('id', TRUE));

				$success = 1;

				break;

			case '41':// add to my shop
				$post = $this->input->post(NULL, TRUE);
				$this->MyShop->setMyShopName($post['shop_name']);
				$this->MyShop->setShopId($post['shop_id']);
				$this->MyShop->setLesseeId($post['id']);
				if($this->notify('Shop has been added','Your shop has been added','lessor')):
				  	$this->MyShop->insert();
					$data['result'] = "Shop successfully added";
					$success = 1;
				else:
					$data['result'] = "Shop addition failed";
				 	$success = 0;
				endif;
				break;
			case '42': // delete from my shop
				$post = $this->input->post(NULL, TRUE);
				$this->MyShop->setId($post['myshop_id']);
				$this->MyShop->setLesseeId($post['id']);
				$result = $this->MyShop->delete();

				if ($result):
				    $data['shops'] = $this->AndroidModel->getShopsByLesseeId($post['id']);
				    $data['result'] = "Shop has been successfully deleted";
				    $success = 1;
				else:
				    $data['result'] = "Shop deletion failed";
				    $success = 0;
				endif;
				break;
			case '51': // add item to interest
					$post = $this->input->post(NULL, TRUE);
					$this->MyInterest->setMyInterestName($post['interest_name']);
					$this->MyInterest->setItemId($post['item_id']);
					$this->MyInterest->setLesseeId($post['id']);
					if($this->notify('Item has been added','Your item has been added','lessor')):
					   	$this->MyInterest->insert();
						$data['result'] = "Item has been added to your Interest";
						$success = 1;
					else:
						$data['result'] = "Item addition failed";
					   $success = 0;
					endif;
				break;
			case '52': // delete item from interest
				$this->MyInterest->setId($this->input->post('interest_id', TRUE));
				$result = $this->MyInterest->delete();

				if ($result):
					$data['items']= $this->AndroidModel->getInterestsItems($this->input->post('id', TRUE));
					$data['result'] = "Item has been deleted successfully";
				    $success = 1;
				else:
				    $data['result'] = "Item deletion failed";
				    $success = 0;
				endif;

				break;
			default: // dashboard

				$data['categories'] = $this->Category->all($select = "category_id,category_type", $like = "");
				$success = 1;

				break;
		}
		$data['success'] = $success;
		echo json_encode($data);
	}

	private function notify($subject,$message,$type) {
	  $data['subject']  = $subject;
	  $data['message']  = $message;
	  $data['receiver'] = ($this->session->has_userdata('lessee_id')) ? $this->session->userdata('lessee_id') : $this->session->userdata('lessor_id') ;
	  $data['date']     = date("Y/m/d");
	  $data['usertype'] = $type;
	  if($this->mypusher->Message('notify-channel', 'notify-event', $data)):
	    return TRUE;
	  else:
	    return FALSE;
	  endif;

	}

	/*public function addMyInterest() {
	    $post = $this->input->post(NULL, TRUE);
	    $this->MyInterest->setMyInterestName($post['interest_name']);
	    $this->MyInterest->setItemId($post['item_id']);
	    $this->MyInterest->setLesseeId($post['id']);

	    if($this->notify('Item has been added','Your item has been added','lessor')):
	       echo $this->MyInterest->insert();
	    else:
	      echo FALSE;
	    endif;
	}

	public function removeMyInterest($id) {
	  $this->MyInterest->setId($id);
	  $result = $this->MyInterest->delete();

	  if ($result):
	      $this->session->set_flashdata('success', TRUE);
	      redirect('lessee/myinterests', 'refresh');
	  else:
	      $this->session->set_flashdata('error', TRUE);
	      redirect('lessee/myinterests', 'refresh');
	  endif;
	}*/
	public function download(){

		$file = 'uploads/rentrmnl.apk';

		if (file_exists($file)) {
		    header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.basename($file).'"');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    readfile($file);

		}

	}
}


text:
---
external help file: Microsoft.Azure.Commands.Resources.dll-Help.xml
Module Name: AzureRM.Resources
ms.assetid: 8300B143-E322-419E-BC98-DBA56DD90A59
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermroledefinition
schema: 2.0.0
---

# New-AzureRmRoleDefinition

## SYNOPSIS
Creates a custom role in Azure RBAC.
Provide either a JSON role definition file or a PSRoleDefinition object as input.
First, use the Get-AzureRmRoleDefinition command to generate a baseline role definition object.
Then, modify its properties as required.
Finally, use this command to create a custom role using role definition.

## SYNTAX

### InputFileParameterSet
```
New-AzureRmRoleDefinition [-InputFile] <String> [-DefaultProfile <IAzureContextContainer>] [<CommonParameters>]
```

### RoleDefinitionParameterSet
```
New-AzureRmRoleDefinition [-Role] <PSRoleDefinition> [-DefaultProfile <IAzureContextContainer>]
 [<CommonParameters>]
```

## DESCRIPTION
The New-AzureRmRoleDefinition cmdlet creates a custom role in Azure Role-Based Access Control.
Provide a role definition as an input to the command as a JSON file or a PSRoleDefinition object.

The input role definition MUST contain the following properties:

1) DisplayName: the name of the custom role

2) Description: a short description of the role that summarizes the access that the role grants.

3) Actions: the set of operations to which the custom role grants access.
Use Get-AzureRmProviderOperation to get the operation for Azure resource providers that can be secured using Azure RBAC.
Following are some valid operation strings:
 - "*/read" grants access to read operations of all Azure resource providers.
 - "Microsoft.Network/*/read" grants access to read operations for all resource types in the Microsoft.Network resource provider of Azure.
 - "Microsoft.Compute/virtualMachines/*" grants access to all operations of virtual machines and its child resource types.

4) AssignableScopes: the set of scopes (Azure subscriptions or resource groups) in which the custom role will be available for assignment.
Using AssignableScopes you can make the custom role available for assignment in only the subscriptions or resource groups that need it, and not clutter the user experience for the rest of the subscriptions or resource groups.
Following are some valid assignable scopes:
 - "/subscriptions/c276fc76-9cd4-44c9-99a7-4fd71546436e", "/subscriptions/e91d47c4-76f3-4271-a796-21b4ecfe3624": makes the role available for assignment in two subscriptions.
 - "/subscriptions/c276fc76-9cd4-44c9-99a7-4fd71546436e": makes the role available for assignment in a single subscription.
 - "/subscriptions/c276fc76-9cd4-44c9-99a7-4fd71546436e/resourceGroups/Network": makes the role available for assignment only in the Network resource group.

The input role definition MAY contain the following properties:

1) NotActions: the set of operations that must be excluded from the Actions to determine the effective actions for the custom role.
If there is a specific operation that you do not wish to grant access to in a custom role, it is convenient to use NotActions to exclude it, rather than specifying all operations other than that specific operation in Actions.

NOTE: If a user is assigned a role that specifies an operation in NotActions and also assigned another role grants access to the same operation - the user will be able to perform that operation.
NotActions is not a deny rule - it is simply a convenient way to create a set of allowed operations when specific operations need to be excluded.

Following is a sample json role definition that can be provided as input
        {
        "Name": "Contoso On-call",
        "Description": "Can monitor compute, network and storage, and restart virtual machines",
        "Actions": \[
        "Microsoft.Compute/*/read",
        "Microsoft.Compute/virtualMachines/start/action",
        "Microsoft.Compute/virtualMachines/restart/action",
        "Microsoft.Compute/virtualMachines/downloadRemoteDesktopConnectionFile/action",
        "Microsoft.Network/*/read",
        "Microsoft.Storage/*/read",
        "Microsoft.Authorization/*/read",
        "Microsoft.Resources/subscriptions/resourceGroups/read",
        "Microsoft.Resources/subscriptions/resourceGroups/resources/read",
        "Microsoft.Insights/alertRules/*",
        "Microsoft.Support/*"
        \],
        "AssignableScopes": \["/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx","/subscriptions/yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"\]
        }

## EXAMPLES

### Create using PSRoleDefinitionObject
```
PS C:\> $role = Get-AzureRmRoleDefinition -Name "Virtual Machine Contributor"
          PS C:\> $role.Id = $null
          PS C:\> $role.Name = "Virtual Machine Operator"
          PS C:\> $role.Description = "Can monitor, start, and restart virtual machines."
          PS C:\> $role.Actions.RemoveRange(0,$role.Actions.Count)
          PS C:\> $role.Actions.Add("Microsoft.Compute/*/read")
          PS C:\> $role.Actions.Add("Microsoft.Compute/virtualMachines/start/action")
          PS C:\> $role.Actions.Add("Microsoft.Compute/virtualMachines/restart/action")
          PS C:\> $role.Actions.Add("Microsoft.Compute/virtualMachines/downloadRemoteDesktopConnectionFile/action")
          PS C:\> $role.Actions.Add("Microsoft.Network/*/read")
          PS C:\> $role.Actions.Add("Microsoft.Storage/*/read")
          PS C:\> $role.Actions.Add("Microsoft.Authorization/*/read")
          PS C:\> $role.Actions.Add("Microsoft.Resources/subscriptions/resourceGroups/read")
          PS C:\> $role.Actions.Add("Microsoft.Resources/subscriptions/resourceGroups/resources/read")
          PS C:\> $role.Actions.Add("Microsoft.Insights/alertRules/*")
          PS C:\> $role.Actions.Add("Microsoft.Support/*")
          PS C:\> $role.AssignableScopes.Clear()
          PS C:\> $role.AssignableScopes.Add("/subscriptions/c276fc76-9cd4-44c9-99a7-4fd71546436e")

          PS C:\> New-AzureRmRoleDefinition -Role $role
```

### Create using JSON file
```
PS C:\> New-AzureRmRoleDefinition -InputFile C:\Temp\roleDefinition.json
```

## PARAMETERS

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with azure

```yaml
Type: IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -InputFile
File name containing a single json role definition.

```yaml
Type: String
Parameter Sets: InputFileParameterSet
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Role
Role definition object.

```yaml
Type: PSRoleDefinition
Parameter Sets: RoleDefinitionParameterSet
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleDefinition

## NOTES
Keywords: azure, azurerm, arm, resource, management, manager, resource, group, template, deployment

## RELATED LINKS

[Get-AzureRmProviderOperation](./Get-AzureRmProviderOperation.md)

[Get-AzureRmRoleDefinition](./Get-AzureRmRoleDefinition.md)

[Set-AzureRmRoleDefinition](./Set-AzureRmRoleDefinition.md)

[Remove-AzureRmRoleDefinition](./Remove-AzureRmRoleDefinition.md)

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe User do
  it { should have_many(:repos).through(:memberships) }
  it { should validate_presence_of :github_username }

  describe '#create' do
    it 'generates a remember_token' do
      user = build(:user)
      allow(SecureRandom).to receive(:hex) { "remembertoken" }

      user.save

      expect(SecureRandom).to have_received(:hex).with(20)
      expect(user.remember_token).to eq 'remembertoken'
    end
  end

  describe '#to_s' do
    it 'returns GitHub username' do
      user = build(:user)

      user_string = user.to_s

      expect(user_string).to eq user.github_username
    end
  end

  describe '#has_repos_with_missing_information?' do
    context 'with repo without organization info' do
      it 'returns true' do
        user = create(:user)
        repo = create(:repo, in_organization: nil)
        user.repos << repo

        expect(user).to have_repos_with_missing_information
      end
    end

    context 'with repo without privacy info' do
      it 'return true' do
        user = create(:user)
        repo = create(:repo, private: nil)
        user.repos << repo

        expect(user).to have_repos_with_missing_information
      end
    end

    context 'with repo without organization and privacy info' do
      it 'returns true' do
        user = create(:user)
        repo = create(:repo, in_organization: nil, private: nil)
        user.repos << repo

        expect(user).to have_repos_with_missing_information
      end
    end

    context 'with repo with organization and privacy info' do
      it 'returns false' do
        user = create(:user)
        repo = create(:repo, in_organization: true, private: true)
        user.repos << repo

        expect(user).not_to have_repos_with_missing_information
      end
    end
  end
end


text:
<html>

<head></head>

<body>

<form method="POST" action="../teach">

<input type="text" name="mainURL"  >

<input type="submit" value="teach">

</form>

<form method="POST" action="../editor">

<input type="text" name="mainURL" >

<input type="submit" value="editor">

</form>

</body>

</html>


text:
import hexchat
import logging
import sys
import os

__module_name__ = 'Twitch'
__module_author__ = 'RenaKunisaki & TingPing'
__module_version__ = '1'
__module_description__ = 'Better integration with Twitch.tv'

# append current path to module load path
sys.path.append(os.path.join(
	hexchat.get_info("configdir"), "addons"))

import twitch
log = twitch.logger.get('main')

# set up an unload hook
def unload_cb(userdata):
	twitch.shutdown()
	msg = "{} v{} unloaded".format(__module_name__, __module_version__)
	print(msg)
	logging.info(msg)
hexchat.hook_unload(unload_cb)

msg = "{} v{} loaded".format(__module_name__, __module_version__)
print(msg)
logging.info(msg)

twitch.run()
logging.info("{} v{} setup OK".format(__module_name__, __module_version__))


text:
<?php
/**
 *
 * Athene2 - Advanced Learning Resources Manager
 *
 * @author    Aeneas Rekkas (aeneas.rekkas@serlo.org)
 * @license    LGPL-3.0
 * @license    http://opensource.org/licenses/LGPL-3.0 The GNU Lesser General Public License, version 3.0
 * @link        https://github.com/serlo-org/athene2 for the canonical source repository
 */
namespace User\Form;

use Zend\Form\Element\Email;
use Zend\Form\Element\Submit;
use Zend\Form\Element\Textarea;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;

class SettingsForm extends Form
{
    public function __construct($entityManager, $dontValidate = false)
    {
        parent::__construct('settings');
        $this->setAttribute('method', 'post');
        $this->setAttribute('class', 'clearfix');
        $filter = new InputFilter();
        $this->setInputFilter($filter);

        $this->add((new Email('email'))->setAttribute('id', 'email')->setLabel('Email:'));
        $this->add((new Textarea('description'))->setAttribute('id', 'description')->setLabel('About me:'));

        $this->add((new Submit('submit'))->setValue('Update')
            ->setAttribute('class', 'btn btn-success pull-right'));

        if (!$dontValidate) {
            $filter->add([
                'name' => 'email',
                'required' => true,
                'validators' => [
                    [
                        'name' => 'EmailAddress'
                    ],
                    [
                        'name' => 'User\Validator\UniqueUser',
                        'options' => [
                            'object_repository' => $entityManager->getRepository('User\Entity\User'),
                            'fields' => ['email'],
                            'object_manager' => $entityManager
                        ]
                    ]
                ]
            ]);
        }
    }
}


text:
#include "HipKDF.h"
#include "HipCmac.h"
#include "HipCipher.h"

#define HIP_KDF_EXCEPTION_STR \
	"HIP key derivation failed: "

using namespace hipdex_vpn;

HipKDF::HipKDF(HipCipher* cipher, const ByteBlock& hostHit, const ByteBlock& peerHit)
	: m_cipher(cipher), m_hostHit(hostHit), m_peerHit(peerHit)
{
}

HipKDF::~HipKDF()
{
}

void HipKDF::Extract(const ByteBlock& key, const ByteBlock& salt, ByteBlock& extract)
{
	if (key.size() != m_cipher->KeyLength())
		throw Exception(Exception::Abort,
			HIP_KDF_EXCEPTION_STR \
			"KDF key size mismatch (extract).");

	HipCmac cmac(*m_cipher, key);
	cmac.Update(salt);

	if (m_peerHit < m_hostHit)
	{
		cmac.Update(m_peerHit);
		cmac.Update(m_hostHit);
	}
	else
	{
		cmac.Update(m_hostHit);
		cmac.Update(m_peerHit);
	}

	uint8_t info[] = "CKDF-Extract";
	cmac.Update(ByteBlock(info, info+12));

	extract.resize(cmac.DigestSize());
	cmac.Final(extract);
}

void HipKDF::Expand(const ByteBlock& key, ByteBlock& keymat)
{
	if ((keymat.size()%m_cipher->BlockSize()) != 0)
		throw Exception(Exception::Abort,
			HIP_KDF_EXCEPTION_STR \
			"Keymat size mismatch (expand).");

	if (key.size() != m_cipher->KeyLength())
		throw Exception(Exception::Abort,
			HIP_KDF_EXCEPTION_STR \
			"KDF key size mismatch (expand).");

	ByteBlock expand;
	uint8_t iter = 0;

	for (ByteBlock::size_type offset = 0;
		offset < keymat.size(); ++iter)
	{
		HipCmac cmac(*m_cipher, key);

		if (!expand.empty())
			cmac.Update(expand);

		if (m_peerHit < m_hostHit)
		{
			cmac.Update(m_peerHit);
			cmac.Update(m_hostHit);
		}
		else
		{
			cmac.Update(m_hostHit);
			cmac.Update(m_peerHit);
		}

		uint8_t info[] = "CKDF-Expand";
		cmac.Update(ByteBlock(info, info+11));
		cmac.Update(&iter, 1);

		expand.resize(cmac.DigestSize());
		cmac.Final(expand);

		std::copy(expand.begin(), expand.end(),
			keymat.data() + offset);

		offset += expand.size();
	}
}


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">

  <title>Check For An Key In Object in JS and PHP</title>
  <meta name="description" content="Coming From Python this felt a little funny since Python has so many nice features for looking up keys and setting defaults etc.">

  <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,700|Roboto+Mono:400,500' rel='stylesheet' type='text/css'>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://localhost:4000/2017/11/checking-empty-object">
  <link rel="alternate" type="application/rss+xml" title="Johnny Devriese" href="http://localhost:4000/feed.xml">

    Home
    Articles
    Resources
    About

Check For An Key In Object in JS and PHP

Coming From Python this felt a little funny since Python has so many nice features for looking up keys and setting defaults etc.

Check if object has a key in JavaScript

https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript

myObj.hasOwnProperty('key');

check if array has a key in PHP

array_key_exists('filename', $resourcePairedValue)

© Johnny Devriese 2020

        GitHub
        Instagram
      Twitter
      500px


text:
from Tkinter import *

# destroys the authentication window
def quit(self):
    self.root.destroy()

def authentication_password_main():
	root = Tk()

	root.geometry("500x200")
	root.wm_title("Authentication")

	'''
	These lines for adding text area on top of the authentication UI
	T = Text(root, height=1, width=8)
	T.pack()
	T.insert(END, "your text")
	'''

	username = "admin"
	password = "admin_123456" #that's the given password

	#username entry
	username_entry = Entry(root)
	username_entry.pack()

	#password entry
	password_entry = Entry(root, show='*')
	password_entry.pack()

	def trylogin(): #this method is called when the button is pressed
	    #to get what's written inside the entries, I use get()
	    #check if both username and password in the entry is same of the given ones
	    if username == username_entry.get() and password == password_entry.get():
		print("Login is successful!")
		root.quit() # Authentication is successfull
		#add your codes after this line for specifying what program does when login is successful
	    else:
		print("Wrong")

	#when you press this button, trylogin is called
	button = Button(root, text="Login", command = trylogin)
	button.pack()

	#App starter
	root.mainloop()

authentication_password_main()


text:
package org.springframework.security.test.web.servlet.showcase.secured;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.*;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SecurityRequestsTests.Config.class)
@WebAppConfiguration
public class SecurityRequestsTests {

	@Autowired
	private WebApplicationContext context;

	@Autowired
	private UserDetailsService userDetailsService;

	private MockMvc mvc;

	@Before
	public void setup() {
		mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
	}

	@Test
	public void requestProtectedUrlWithUser() throws Exception {
		mvc.perform(get("/").with(user("user")))
		// Ensure we got past Security
				.andExpect(status().isNotFound())
				// Ensure it appears we are authenticated with user
				.andExpect(authenticated().withUsername("user"));
	}

	@Test
	public void requestProtectedUrlWithAdmin() throws Exception {
		mvc.perform(get("/admin").with(user("admin").roles("ADMIN")))
		// Ensure we got past Security
				.andExpect(status().isNotFound())
				// Ensure it appears we are authenticated with admin
				.andExpect(authenticated().withUsername("admin"));
	}

	@Test
	public void requestProtectedUrlWithUserDetails() throws Exception {
		UserDetails user = userDetailsService.loadUserByUsername("user");
		mvc.perform(get("/").with(user(user)))
		// Ensure we got past Security
				.andExpect(status().isNotFound())
				// Ensure it appears we are authenticated with user
				.andExpect(authenticated().withAuthenticationPrincipal(user));
	}

	@Test
	public void requestProtectedUrlWithAuthentication() throws Exception {
		Authentication authentication = new TestingAuthenticationToken("test", "notused",
				"ROLE_USER");
		mvc.perform(get("/").with(authentication(authentication)))
		// Ensure we got past Security
				.andExpect(status().isNotFound())
				// Ensure it appears we are authenticated with user
				.andExpect(authenticated().withAuthentication(authentication));
	}

	@EnableWebSecurity
	@EnableWebMvc
	static class Config extends WebSecurityConfigurerAdapter {

		// @formatter:off
		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http
				.authorizeRequests()
					.antMatchers("/admin/**").hasRole("ADMIN")
					.anyRequest().authenticated()
					.and()
				.formLogin();
		}
		// @formatter:on

		// @formatter:off
		@Autowired
		public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
			auth
				.inMemoryAuthentication()
					.withUser("user").password("password").roles("USER");
		}
		// @formatter:on

		@Override
		@Bean
		public UserDetailsService userDetailsServiceBean() throws Exception {
			return super.userDetailsServiceBean();
		}
	}
}


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2013 Live Networks, Inc.  All rights reserved.
// Medium
// C++ header

#ifndef _MEDIA_HH
#define _MEDIA_HH

#ifndef _LIVEMEDIA_VERSION_HH
#include "liveMedia_version.hh"
#endif

#ifndef _HASH_TABLE_HH
#include "HashTable.hh"
#endif

#ifndef _USAGE_ENVIRONMENT_HH
#include "UsageEnvironment.hh"
#endif

// Lots of files end up needing the following, so just #include them here:
#ifndef _NET_COMMON_H
#include "NetCommon.h"
#endif
#include <stdio.h>

// The following makes the Borland compiler happy:
#ifdef __BORLANDC__
#define _strnicmp strnicmp
#define fabsf(x) fabs(x)
#endif

#define mediumNameMaxLen 30

class Medium {
public:
  static Boolean lookupByName(UsageEnvironment& env,
			      char const* mediumName,
			      Medium*& resultMedium);
  static void close(UsageEnvironment& env, char const* mediumName);
  static void close(Medium* medium); // alternative close() method using ptrs
      // (has no effect if medium == NULL)

  UsageEnvironment& envir() const {return fEnviron;}

  char const* name() const {return fMediumName;}

  // Test for specific types of media:
  virtual Boolean isSource() const;
  virtual Boolean isSink() const;
  virtual Boolean isRTCPInstance() const;
  virtual Boolean isRTSPClient() const;
  virtual Boolean isRTSPServer() const;
  virtual Boolean isMediaSession() const;
  virtual Boolean isServerMediaSession() const;
  virtual Boolean isDarwinInjector() const;

protected:
  friend class MediaLookupTable;
  Medium(UsageEnvironment& env); // abstract base class
  virtual ~Medium(); // instances are deleted using close() only

  TaskToken& nextTask() {
	return fNextTask;
  }

private:
  UsageEnvironment& fEnviron;
  char fMediumName[mediumNameMaxLen];
  TaskToken fNextTask;
};

// A data structure for looking up a Medium by its string name.
// (It is used only to implement "Medium", but we make it visible here, in case developers want to use it to iterate over
//  the whole set of "Medium" objects that we've created.)
class MediaLookupTable {
public:
  static MediaLookupTable* ourMedia(UsageEnvironment& env);
  HashTable const& getTable() { return *fTable; }

protected:
  MediaLookupTable(UsageEnvironment& env);
  virtual ~MediaLookupTable();

private:
  friend class Medium;

  Medium* lookup(char const* name) const;
  // Returns NULL if none already exists

  void addNew(Medium* medium, char* mediumName);
  void remove(char const* name);

  void generateNewName(char* mediumName, unsigned maxLen);

private:
  UsageEnvironment& fEnv;
  HashTable* fTable;
  unsigned fNameGenerator;
};

// The structure pointed to by the "liveMediaPriv" UsageEnvironment field:
class _Tables {
public:
  static _Tables* getOurTables(UsageEnvironment& env, Boolean createIfNotPresent = True);
      // returns a pointer to an "ourTables" structure (creating it if necessary)
  void reclaimIfPossible();
      // used to delete ourselves when we're no longer used

  MediaLookupTable* mediaTable;
  void* socketTable;

protected:
  _Tables(UsageEnvironment& env);
  virtual ~_Tables();

private:
  UsageEnvironment& fEnv;
};

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project relativePaths="false" version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/portfolio.iml" filepath="$PROJECT_DIR$/portfolio.iml" />
    </modules>
  </component>
</project>


text:
#make a Type PostRequest XML document using .Net XML document object
$xmlDoc = New-Object System.Xml.XmlDocument;
$decl = $xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", $null)

#add root element for request - which is a 'PostRequest' element
$xmlRootElem =  $xmlDoc.AppendChild($xmlDoc.CreateElement('Request'));
$xmlDoc.InsertBefore($decl, $xmlDoc.DocumentElement)

#create the first SetAttribute element (you can submit many in a request)
$xmlSetValueElem = $xmlRootElem.AppendChild($xmlDoc.CreateElement('Event'));

$xmlDevAttr = $xmlDoc.CreateAttribute('Device');
$xmlDevAttr.Value = '*GFX_LOGO';
$xmlSetValueElem.Attributes.Append($xmlDevAttr);

$xmlCmdAttr = $xmlDoc.CreateAttribute('Cmd');
$xmlCmdAttr.Value = 'EXIT_SCENE_LOOP';
$xmlSetValueElem.Attributes.Append($xmlCmdAttr);

$xmlSetOp1Elem = $xmlDoc.CreateElement('Op1');
$xmlSetOp1Elem.InnerText = "";
$xmlSetValueElem.AppendChild($xmlSetOp1Elem);

$xmlSetOp2Elem = $xmlDoc.CreateElement('Op2');
$xmlSetOp2Elem.InnerText = ""
$xmlSetValueElem.AppendChild($xmlSetOp2Elem);

$xmlSetOp3Elem = $xmlDoc.CreateElement('Op3');
$xmlSetOp3Elem.InnerText = "";
$xmlSetValueElem.AppendChild($xmlSetOp3Elem);
$xmlDoc.InnerXml;

#create a .Net webclient which will be used to perform the HTTP POST
$web = new-object net.webclient

#Air requires that the data is in XML format and declared properly - so add the HTTP Header to state this
$web.Headers.add("Content-Type", "text/xml; charset=utf-8")

#perform the actual HTTP post to the IP and port (which is 5521 + instance number) of the XML data
$web.UploadString("http://localhost:5521/video/command", $xmlDoc.OuterXml)

$xmlDoc.OuterXml | Out-File "D:\Temp\xmldoc.xml"


text: only test and learn git


text: Meet Magento Academy training course learning resources


text:
title: Comfortable distance
localeTitle: Удобное расстояние
---
## Задача 364: Удобное расстояние

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-364-comfortable-distance/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    netcell-node - A basic netcell node configuration
    Copyright (C) 2009  Adrian Cristian Ionescu - https://github.com/acionescu

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<!DOCTYPE entities SYSTEM "../../../dtds/entities.dtd">
<entities>
   <entity id="${entityDefinition.getId()}" type="configurable-component-definition"
      logic-type="dynamic-wrapper">
      <entity logic-type="config">
         <entity type="definition-params" logic-type="static-parameters">
            <value>
               <map>
                  #if($entityDefinition.getInputParameters()&& $entityDefinition.getInputParameters().size() > 0)
                  <entry key="inputParameters">
                     <value>
                        <list>
                           #foreach($param in $entityDefinition.getInputParameters())
                           <value>
                              #parse("root/config/definitions/templates/input-param-template.xml")
                           </value>
                           #end
                        </list>
                     </value>
                  </entry>
                  #end
                  <entry key="executionEntity">
                     <value>
                        <entity logic-type="dynamic-wrapper">
                           <entity logic-type="config">
                              <entity
                                 logic-type="static-parameters">
                                 <value>
                                    <map>
                                       <entry key="commandName"
                                          value="${entityDefinition.getCommandName()}"></entry>
                                       <entry key="commandManager">
                                          <value>
                                             <entity>
                                                <entity-ref
                                                   ref-id="${entityDefinition.getDataSourceName()}" />
                                             </entity>
                                          </value>
                                       </entry>
                                    </map>
                                 </value>
                              </entity>
                              <entity logic-type="executor">
                                 <entity-ref ref-id="dataAccessEntity" />
                              </entity>
                              <entity logic-type="original-input-name">
                                 <value>argsContext</value>
                              </entity>
                           </entity>
                        </entity>
                     </value>
                  </entry>
                  <entry key="outputParameters">
                     <value>
                        <list>
                           <value>
                              <entity type="output-parameter">
                                 <property name="name" value="count"></property>
                                 <property name="type" value="Number"></property>
                              </entity>
                           </value>
                           <value>
                              <entity type="output-parameter">
                                 <property name="name" value="result"></property>
                                 <property name="type"
                                    value="List[Context[]]"></property>
                              </entity>
                           </value>
                        </list>
                     </value>
                  </entry>
               </map>
            </value>
         </entity>
         <entity logic-type="original-input-name">
            <value>inputContext</value>
         </entity>
         <entity logic-type="executor">
            <entity-ref ref-id="executionEntityWrapper" />
         </entity>
      </entity>
   </entity>
</entities>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Acta Mycologica, Warszawa 11(1): 56 (1975)

#### Original name
Dimeromyces descarpentriesii Balazuc

### Remarks
null


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('aat', '0005_auto_20171129_1803'),
    ]

    operations = [
        migrations.AddField(
            model_name='recognizerpretraineddata',
            name='size',
            field=models.CharField(blank=True, max_length=10),
        ),
    ]


text:
shared_examples "serializable" do |version_strings|
  describe "#to_s" do
    version_strings.each do |v|
      it "reconstructs the initial input for #{v}" do
        expect(described_class.new(v).to_s).to eq(v)
      end # it
    end # version_strings
  end # describe

  describe "#to_semver_string" do
    version_strings.each do |v|
      it "generates a semver version string for #{v}" do
        subject = described_class.new(v)
        string = subject.to_semver_string
        semver = Mixlib::Versioning::Format::SemVer.new(string)
        expect(string).to eq semver.to_s
      end # it
    end # version_strings
  end # describe

  describe "#to_rubygems_string" do
    version_strings.each do |v|
      it "generates a rubygems version string for #{v}" do
        subject = described_class.new(v)
        string = subject.to_rubygems_string
        rubygems = Mixlib::Versioning::Format::Rubygems.new(string)
        expect(string).to eq rubygems.to_s
      end # it
    end # version_strings
  end # describe
end # shared_examples


text:
using UnityEngine;
using System.Collections;

public class Hunt : Objectif {
    public GameObject Mouton;
    private GameObject m_Alpha;
    private GameObject m_Mouton;
    private Animal m_Script;

    // Use this for initialization
    protected void Start()
    {
        detail = "Pour te nourrir, tu dois chasser le mouton entouré d'un cercle orange.\n\nPour se faire, passe en mode \"Chasse\" (icône rouge de ta barre d'action) et déplace ta meute en direction du mouton.\n\nTes loups s'attaqueront automatiquement au mouton lorsqu'ils seront à portée.";

        m_Alpha = null;
        foreach(Transform child in GameManager.getInstance().tutorialManager.Meute.transform) {
            if (child.gameObject.name == "LoupAlpha")
            {
                //Debug.Log("Alpha found at start");
                m_Alpha = child.gameObject;
            }
        }
        if (m_Alpha == null)
        {
            //Debug.Log("Aucun alpha at start ????");
            Destroy(this);
        }

        base.Start();
    }

    // Update is called once per frame
    void Update()
    {
        checkAchievement();
    }

    void initialize()
    {
        if (m_Alpha == null)
        {
            //Debug.Log("Aucun alpha ????");
            Destroy(this);
            return;
        }
        Vector2 pos = new Vector2();
        pos.x = m_Alpha.transform.position.x + Random.Range(-5, 5);
        pos.y = m_Alpha.transform.position.y + Random.Range(-5, 5);

        //Debug.Log("Instantiate");
        m_Mouton = Instantiate(Mouton, pos, m_Alpha.transform.rotation) as GameObject;

        m_Marqueur = Instantiate(m_Manager.Marqueur, pos, m_Alpha.transform.rotation) as GameObject;
        m_Marqueur.transform.parent = m_Mouton.transform;
        m_Marqueur.transform.localPosition = Vector3.zero;

        m_Script = m_Mouton.GetComponent<Animal>();

        GameManager.getInstance().setCameraFocus(m_Marqueur.transform);
    }

    /**
     * Check display condition on update.
     * Must be overidden.
     * */
    protected override void checkAchievement()
    {
        if (m_Script.estMort())
        {
            //Debug.Log("Achieved.");
            achieve();
        }
    }

    public override void activate()
    {
        //Debug.Log("Activate fils");
        initialize();
        base.activate();
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.jyore.uservices</groupId>
	<artifactId>authentication-server</artifactId>
	<version>1.0.0-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-parent</artifactId>
		<version>1.0.1.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security.oauth</groupId>
			<artifactId>spring-security-oauth2</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>


text:
from pyasn1.type import constraint
from pyasn1.type import namedtype
from pyasn1.type import tag
from pyasn1.type import univ

class ObjectName(univ.ObjectIdentifier):
    pass

class SimpleSyntax(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('number', univ.Integer()),
        namedtype.NamedType('string', univ.OctetString()),
        namedtype.NamedType('object', univ.ObjectIdentifier()),
        namedtype.NamedType('empty', univ.Null())
    )

class IpAddress(univ.OctetString):
    tagSet = univ.OctetString.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0)
    )
    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueSizeConstraint(
        4, 4
    )

class NetworkAddress(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('internet', IpAddress())
    )

class Counter(univ.Integer):
    tagSet = univ.Integer.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 1)
    )
    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(
        0, 4294967295
    )

class Gauge(univ.Integer):
    tagSet = univ.Integer.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 2)
    )
    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(
        0, 4294967295
    )

class TimeTicks(univ.Integer):
    tagSet = univ.Integer.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 3)
    )
    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(
        0, 4294967295
    )

class Opaque(univ.OctetString):
    tagSet = univ.OctetString.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 4)
    )

class ApplicationSyntax(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('address', NetworkAddress()),
        namedtype.NamedType('counter', Counter()),
        namedtype.NamedType('gauge', Gauge()),
        namedtype.NamedType('ticks', TimeTicks()),
        namedtype.NamedType('arbitrary', Opaque())
    )

class ObjectSyntax(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('simple', SimpleSyntax()),
        namedtype.NamedType('application-wide', ApplicationSyntax())
    )


text:
package com.linecorp.armeria.server;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicBoolean;

import org.assertj.core.data.Offset;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.util.TimeoutMode;
import com.linecorp.armeria.internal.server.DefaultServiceRequestContext;

class DefaultServiceRequestContextTest {

    AtomicBoolean finished;

    @BeforeEach
    void setUp() {
        finished = new AtomicBoolean();
    }

    @Test
    void requestTimedOut() {
        final HttpRequest request = HttpRequest.of(HttpMethod.GET, "/hello");
        final ServiceRequestContext ctx = ServiceRequestContext.builder(request).build();
        assertThat(ctx.isTimedOut()).isFalse();
        assert ctx instanceof DefaultServiceRequestContext;
        final DefaultServiceRequestContext defaultCtx = (DefaultServiceRequestContext) ctx;
        defaultCtx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, 1000);

        await().timeout(Duration.ofSeconds(3))
               .untilAsserted(() -> assertThat(ctx.isTimedOut()).isTrue());
    }

    @Test
    void extendRequestTimeout() {
        final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
        final ServiceRequestContext ctx = ServiceRequestContext.of(req);

        ctx.eventLoop().execute(() -> {
            ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, 1000);

            final long oldRequestTimeout1 = ctx.requestTimeoutMillis();
            ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 1000);
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(oldRequestTimeout1 + 1000);

            final long oldRequestTimeout2 = ctx.requestTimeoutMillis();
            ctx.setRequestTimeout(TimeoutMode.EXTEND, Duration.ofSeconds(-2));
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(oldRequestTimeout2 - 2000);

            final long oldRequestTimeout3 = ctx.requestTimeoutMillis();
            ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 0);
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(oldRequestTimeout3);

            finished.set(true);
        });

        await().untilTrue(finished);
    }

    @Test
    void extendRequestTimeoutFromZero() {
        final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
        final ServiceRequestContext ctx = ServiceRequestContext.of(req);

        ctx.eventLoop().execute(() -> {
            // This request now has an infinite timeout
            ctx.clearRequestTimeout();

            ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 1000);
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(0);

            ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, -1000);
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(0);
            finished.set(true);
        });

        await().untilTrue(finished);
    }

    @Test
    void setRequestTimeoutAfter() throws InterruptedException {
        final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
        final DefaultServiceRequestContext ctx = (DefaultServiceRequestContext) ServiceRequestContext.of(req);
        final long tolerance = 500;

        ctx.eventLoop().execute(() -> {
            ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, 1000);
            final long oldRequestTimeoutMillis = ctx.requestTimeoutMillis();
            ctx.setRequestTimeout(TimeoutMode.SET_FROM_NOW, Duration.ofSeconds(2));
            assertThat(ctx.requestTimeoutMillis()).isBetween(oldRequestTimeoutMillis + 1000 - tolerance,
                                                             oldRequestTimeoutMillis + 1000 + tolerance);
            finished.set(true);
        });
        await().untilTrue(finished);
    }

    @Test
    void setRequestTimeoutAfterWithNonPositive() {
        final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
        final DefaultServiceRequestContext ctx = (DefaultServiceRequestContext) ServiceRequestContext.of(req);
        assertThatThrownBy(() -> ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, 0))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("(expected: > 0)");

        assertThatThrownBy(() -> ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, -10))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("(expected: > 0)");
    }

    @Test
    void clearRequestTimeout() {
        final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
        final DefaultServiceRequestContext ctx = (DefaultServiceRequestContext) ServiceRequestContext.of(req);

        ctx.eventLoop().execute(() -> {
            ctx.setRequestTimeoutMillis(2000);
            assertThat(ctx.requestTimeoutMillis()).isCloseTo(2000, Offset.offset(400L));
            ctx.clearRequestTimeout();
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(0);
            finished.set(true);
        });

        await().untilTrue(finished);
    }

    @Test
    void setRequestTimeoutFromStart() {
        final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
        final ServiceRequestContext ctx = ServiceRequestContext.of(req);

        ctx.eventLoop().execute(() -> {
            ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, 1000);
            assertThat(ctx.requestTimeoutMillis()).isCloseTo(1000, Offset.offset(300L));
            ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, 2000);
            assertThat(ctx.requestTimeoutMillis()).isCloseTo(2000, Offset.offset(300L));
            ctx.setRequestTimeout(TimeoutMode.SET_FROM_START, Duration.ofSeconds(3));
            assertThat(ctx.requestTimeoutMillis()).isCloseTo(3000, Offset.offset(300L));
            ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, 0);
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(0);
            finished.set(true);
        });

        await().untilTrue(finished);
    }

    @Test
    void setRequestTimeoutZero() {
        final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
        final ServiceRequestContext ctx = ServiceRequestContext.of(req);

        ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_START, 0);
        await().untilAsserted(() -> {
            assertThat(ctx.requestTimeoutMillis()).isEqualTo(0);
        });
    }
}


text:
package com.werdpressed.partisan.reallyusefulnotes.designlibrary;

import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import com.werdpressed.partisan.reallyusefulnotes.designlibrary.notehelper.NoteRowItemTouchHelperAdapter;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class AllNotesFragmentAdapter extends RecyclerView.Adapter<AllNotesFragmentAdapter.ViewHolder>
        implements NoteRowItemTouchHelperAdapter{

    private WeakReference<AllNotesFragmentCallbacks> mWeakCallback;
    private ArrayList<NoteRowItem> mItems;

    public AllNotesFragmentAdapter(AllNotesFragmentCallbacks callback) {
        mWeakCallback = new WeakReference<>(callback);
        mItems = mWeakCallback.get().requestNotes();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.nf_recycler_view_row, parent, false);
        return new ViewHolder(v, mWeakCallback.get());
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.title.setText(mItems.get(position).getTitle());

    }

    @Override
    public int getItemCount() {
        if (mItems == null) {
            return 0;
        }
        return mItems.size();
    }

    public void updateAllData(ArrayList<NoteRowItem> items) {
        mItems = items;
        notifyDataSetChanged();
    }

    public void addNewEntry(int newItemPosition) {
        notifyItemInserted(newItemPosition);
    }

    public void deleteEntry(int itemPosition) {
        notifyItemRemoved(itemPosition);
    }

    public void moveEntry(int fromPosition, int toPosition) {
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public boolean onItemMove(int fromPosition, int toPosition) {
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++ ) {
                mWeakCallback.get().moveNote(i, i + 1);
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                mWeakCallback.get().moveNote(i, i - 1);
            }
        }
        return false;
    }

    @Override
    public void onItemMoveComplete() {
        for (NoteRowItem item : mItems) {
            Log.e(getClass().getSimpleName(), item.getTitle() + ": " + item.getListOrder());
        }
        mWeakCallback.get().updateNoteListOrders();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements
            PopupMenu.OnMenuItemClickListener, View.OnClickListener{

        private static final String TAG = "ViewHolder";

        private AllNotesFragmentCallbacks mCallback;

        private ImageButton menu;
        private TextView title;
        private PopupMenu popup;

        public ViewHolder(View itemView, AllNotesFragmentCallbacks callback) {
            super(itemView);

            mCallback = callback;

            title = (TextView) itemView.findViewById(R.id.nf_rv_title);
            menu = (ImageButton) itemView.findViewById(R.id.nf_rv_overflow_menu);
            menu.setOnClickListener(this);

            popup = new PopupMenu(itemView.getContext(), menu, Gravity.END);
            popup.getMenuInflater().inflate(R.menu.menu_row_overflow, popup.getMenu());
            popup.setOnMenuItemClickListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int id = item.getItemId();

            switch (id) {
                case R.id.row_action_edit:
                    Log.e(TAG, "edit: position " + getAdapterPosition());
                    break;
                case R.id.row_action_delete:
                    mCallback.deleteNote(getAdapterPosition());
                    break;
            }
            return false;
        }

        @Override
        public void onClick(View v) {
            popup.show();
        }
    }

}


text:
class Transaction < ActiveRecord::Base
  belongs_to :payment

  validates_numericality_of :amount

end


text:
using JetBrains.Annotations;

namespace LinqToDB.DataProvider.SqlCe
{
	using System.Collections.Generic;
	using Configuration;

	[UsedImplicitly]
	class SqlCeFactory : IDataProviderFactory
	{
		IDataProvider IDataProviderFactory.GetDataProvider(IEnumerable<NamedValue> attributes)
		{
			return SqlCeTools.GetDataProvider();
		}
	}
}


text:
title: Dropdown Menu
---


text:
#ifndef _RTPP_NETWORK_H_
#define _RTPP_NETWORK_H_

#include "config.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include "rtpp_defines.h"

#define	addr2port(sa)	ntohs(satosin(sa)->sin_port)

/* Function prototypes */
int ishostseq(struct sockaddr *, struct sockaddr *);
int ishostnull(struct sockaddr *);
char *addr2char_r(struct sockaddr *, char *buf, int size);
const char *addr2char(struct sockaddr *);
int resolve(struct sockaddr *, int, const char *, const char *, int);
uint16_t rtpp_in_cksum(void *, int);
struct sockaddr *addr2bindaddr(struct cfg *, struct sockaddr *, const char **);
struct sockaddr *host2bindaddr(struct cfg *, const char *, int, const char **);
int local4remote(struct sockaddr *, struct sockaddr_storage *);
int extractaddr(const char *, char **, char **, int *);
int setbindhost(struct sockaddr *, int, const char *, const char *);

/* Stripped down version of sockaddr_in* for saving space */
struct sockaddr_in4_s {
    sa_family_t sin_family;
    in_port_t sin_port;
    struct in_addr sin_addr;
};

struct sockaddr_in6_s {
    sa_family_t sin_family;
    in_port_t sin_port;
    struct in6_addr sin_addr;
};

union sockaddr_in_s {
    struct sockaddr_in4_s in4;
    struct sockaddr_in6_s in6;
};

/* Some handy/compat macros */
#if !defined(AF_LOCAL)
#define	AF_LOCAL	AF_UNIX
#endif
#if !defined(PF_LOCAL)
#define	PF_LOCAL	PF_UNIX
#endif

#if !defined(SA_LEN)
#define SA_LEN(sa) \
  (((sa)->sa_family == AF_INET) ? \
  sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))
#endif
#if !defined(SS_LEN)
#define SS_LEN(ss) \
  (((ss)->ss_family == AF_INET) ? \
  sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))
#endif

#if !defined(satosin)
#define	satosin(sa)	((struct sockaddr_in *)(sa))
#endif
#if !defined(satosin6)
#define	satosin6(sa)	((struct sockaddr_in6 *)(sa))
#endif
#if !defined(sstosa)
#define	sstosa(ss)	((struct sockaddr *)(ss))
#endif
#if !defined(satoss)
#define	satoss(sa)	((struct sockaddr_storage *)(sa))
#endif

#define	IS_VALID_PORT(p)	((p) > 0 && (p) < 65536)

#endif


text:
#import <MailServices/MSService.h>

@interface MSMailDefaultService : MSService
{
    _Bool _shouldLaunch;
}

@property(nonatomic) _Bool shouldLaunchMobileMail; // @synthesize shouldLaunchMobileMail=_shouldLaunch;
- (id)_handleMessageSendFailure:(id)arg1 message:(id)arg2 messageIndex:(long long)arg3 context:(inout id *)arg4;
- (id)_createServiceOnQueue:(id)arg1;
- (id)init;

@end


text:
package ch.bfh.progressor.executor.languages;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import ch.bfh.progressor.executor.api.ExecutorException;
import ch.bfh.progressor.executor.api.FunctionSignature;
import ch.bfh.progressor.executor.api.Result;
import ch.bfh.progressor.executor.api.TestCase;
import ch.bfh.progressor.executor.api.Value;
import ch.bfh.progressor.executor.api.ValueType;
import ch.bfh.progressor.executor.api.VersionInformation;
import ch.bfh.progressor.executor.impl.CodeExecutorBase;
import ch.bfh.progressor.executor.impl.CodeExecutorDockerBase;

/**
 * Code execution engine for JavaScript code.
 *
 * @author strut1, touwm1 & weidj1
 */
public class JavaScriptExecutor extends CodeExecutorDockerBase {

	/**
	 * Unique name of the language this executor supports.
	 */
	public static final String CODE_LANGUAGE = "javascript";

	/**
	 * Name of the JavaScript file.
	 */
	protected static final String FILE_NAME = "main";

	/**
	 * Regular expression pattern for extracting the compiler version.
	 */
	protected static final Pattern VERSION_PATTERN = Pattern.compile("\\d[\\d\\.]*");

	@Override
	public String getLanguage() {
		return JavaScriptExecutor.CODE_LANGUAGE;
	}

	@Override
	public VersionInformation fetchVersionInformation() throws ExecutorException {

		String version = null;

		String versionOutput = this.executeSafeCommand(CodeExecutorBase.CURRENT_DIRECTORY, "node", "--version");
		Matcher versionMatcher = JavaScriptExecutor.VERSION_PATTERN.matcher(versionOutput);
		if (versionMatcher.find())
			version = versionMatcher.group();

		return this.createVersionInformation("2015", "Node.js", version);
	}

	@Override
	protected String getTemplatePath() {
		return String.format("%s/template.js", this.getLanguage());
	}

	@Override
	protected List<Result> executeTestCases(String codeFragment, List<TestCase> testCases, File codeDirectory) throws ExecutorException {

		final File codeFile = new File(codeDirectory, String.format("%s.js", JavaScriptExecutor.FILE_NAME));

		//*********************
		//*** GENERATE CODE ***
		//*********************
		this.generateCodeFile(codeFile, codeFragment, testCases);

		//********************
		//*** EXECUTE CODE ***
		//********************
		final long executionStart = System.nanoTime();

		String executionOutput;
		try {
			executionOutput = this.executeCommand(codeDirectory, "node", new File(CodeExecutorBase.CURRENT_DIRECTORY, codeFile.getName()).getPath());

		} catch (ExecutorException ex) {
			throw new ExecutorException("Could not execute the user code.", ex);
		}

		final long executionEnd = System.nanoTime();

		//****************************
		//*** TEST CASE EVALUATION ***
		//****************************
		return this.createResults(executionOutput,
															Double.NaN,
															(executionEnd - executionStart) / CodeExecutorBase.MILLIS_IN_NANO);
	}

	@Override
	protected String getFunctionSignatures(List<FunctionSignature> functions) throws ExecutorException {

		StringBuilder sb = new StringBuilder();
		for (FunctionSignature function : functions) {

			//validate input / output types & names
			if (function.getOutputTypes().size() != 1)
				throw new ExecutorException("Exactly one output type has to be defined for a JavaScript sample.");

			sb.append("function ").append(function.getName()).append('(');

			for (int i = 0; i < function.getInputTypes().size(); i++) {
				if (i > 0) sb.append(", ");
				sb.append(function.getInputNames().get(i));
			}

			sb.append(") {").append(CodeExecutorBase.NEWLINE).append('\t').append(CodeExecutorBase.NEWLINE).append('}').append(CodeExecutorBase.NEWLINE);
		}

		return sb.toString();
	}

	@Override
	protected String getTestCaseSignatures(List<TestCase> testCases) throws ExecutorException {

		StringBuilder sb = new StringBuilder();
		for (TestCase testCase : testCases) {
			if (testCase.getExpectedOutputValues().size() != 1)
				throw new ExecutorException("Exactly one output value has to be defined for a JavaScript example.");

			sb.append(CodeExecutorBase.NEWLINE).append("try {").append(CodeExecutorBase.NEWLINE); //begin test case block

			sb.append("const start = process.hrtime();").append(CodeExecutorBase.NEWLINE);
			sb.append("const result = ").append(testCase.getFunction().getName()).append('('); //test case invocation
			for (int i = 0; i < testCase.getInputValues().size(); i++) {
				if (i > 0) sb.append(", ");
				sb.append(this.getValueLiteral(testCase.getInputValues().get(i)));
			}
			sb.append(");").append(CodeExecutorBase.NEWLINE);
			sb.append("const diff = process.hrtime(start);").append(CodeExecutorBase.NEWLINE);

			String comparisonPrefix = "", comparisonSeparator = "", comparisonSuffix = "";
			switch (testCase.getFunction().getOutputTypes().get(0).getBaseType()) {
				case ARRAY:
				case LIST:
				case SET:
				case MAP:
					comparisonPrefix = "hasSameElements("; //compare collections using custom equality comparison
					comparisonSeparator = ", ";
					comparisonSuffix = ")";
					break;

				case FLOAT32:
				case FLOAT64:
				case DECIMAL:
					comparisonPrefix = "hasMinimalDifference("; //compare floating-point numbers using custom equality comparison
					comparisonSeparator = ", ";
					comparisonSuffix = ")";
					break;

				default:
					comparisonSeparator = " === "; //compare objects using equality operator
					break;
			}

			sb.append("const success = ").append(comparisonPrefix).append("result").append(comparisonSeparator); //result evaluation
			sb.append(this.getValueLiteral(testCase.getExpectedOutputValues().get(0))).append(comparisonSuffix).append(';').append(CodeExecutorBase.NEWLINE);

			String formattingStringPrefix = "", formattingCodePrefix = "", formattingCodeSuffix = "", formattingStringSuffix = "";
			switch (testCase.getFunction().getOutputTypes().get(0).getBaseType()) {
				case ARRAY:
				case LIST:
					formattingStringPrefix = "{ ";
					formattingStringSuffix = " }";
					break;

				case SET:
					formattingStringPrefix = "{ ";
					formattingCodePrefix = "Array.from(";
					formattingCodeSuffix = ")";
					formattingStringSuffix = " }";
					break;

				case MAP:
					formattingStringPrefix = "{ ";
					formattingCodePrefix = "Array.from(";
					formattingCodeSuffix = ").map(function(i) { return `${i[0]}:${i[1]}` })";
					formattingStringSuffix = " }";
					break;
			}

			sb.append("console.log(`${success ? 'OK' : 'ER'}:${diff[0] * 1e3 + diff[1] * 1e-6}:"); //print result to the console
			sb.append(formattingStringPrefix).append("${").append(formattingCodePrefix).append("result");
			sb.append(formattingCodeSuffix).append('}').append(formattingStringSuffix).append("\\n`);").append(CodeExecutorBase.NEWLINE);

			sb.append("} catch (ex) {").append(CodeExecutorBase.NEWLINE); //finish test case block / begin exception handling
			sb.append("console.log(`ER:${ex}\\n`);").append(CodeExecutorBase.NEWLINE);
			sb.append('}'); //finish exception handling
		}

		return sb.toString();
	}

	@Override
	protected String getValueLiteral(Value value) throws ExecutorException {

		switch (value.getType().getBaseType()) {
			case ARRAY:
			case LIST:
			case SET:
				StringBuilder sb = new StringBuilder();
				if (value.getType().getBaseType() == ValueType.BaseType.SET)
					sb.append("new Set(");
				sb.append("[ "); //begin initialisation

				boolean first = true; //generate collection elements
				for (Value element : value.getCollection()) {
					if (first) first = false;
					else sb.append(", ");
					sb.append(this.getValueLiteral(element));
				}

				sb.append(" ]");
				if (value.getType().getBaseType() == ValueType.BaseType.SET)
					sb.append(')');
				return sb.toString(); //finish collection initialisation and return literal

			case MAP:
				sb = new StringBuilder(); //begin initialisation
				sb.append("new Map([ "); //begin initialisation

				first = true; //generate collection elements
				for (List<Value> element : value.get2DCollection()) { //generate key/value pairs
					if (element.size() != 2) //validate key/value pair
						throw new ExecutorException("Map entries always need a key and a value.");

					if (first) first = false;
					else sb.append(", ");
					sb.append("[ ").append(this.getValueLiteral(element.get(0))).append(", ").append(this.getValueLiteral(element.get(1))).append(" ]");
				}

				return sb.append(" ])").toString(); //finish initialisation and return literal

			case STRING:
			case CHARACTER:
				String valueSafe = IntStream.range(0, value.getSingle().length()).map(value.getSingle()::charAt).mapToObj(i -> String.format("\\u%04X", i))
																		.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();

				return String.format("'%s'", valueSafe);

			case BOOLEAN:
				return Boolean.toString("true".equalsIgnoreCase(value.getSingle()));

			case INT8:
			case INT16:
			case INT32:
			case INT64:
				if (!CodeExecutorBase.NUMERIC_INTEGER_PATTERN.matcher(value.getSingle()).matches())
					throw new ExecutorException(String.format("Value %s is not a valid numeric integer literal.", value));
				return value.getSingle();

			case FLOAT32:
			case FLOAT64:
			case DECIMAL:
				if (!CodeExecutorBase.NUMERIC_FLOATING_EXPONENTIAL_PATTERN.matcher(value.getSingle()).matches())
					throw new ExecutorException(String.format("Value %s is not a valid numeric literal.", value));
				return value.getSingle();

			default:
				throw new ExecutorException(String.format("Value type %s is not supported.", value.getType()));
		}
	}

	@Override
	protected String getTypeName(ValueType type) throws ExecutorException {
		throw new UnsupportedOperationException();
	}
}


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

namespace Searching
{
    static class LinearSearch
    {
        public static int FindFirst<T>(this IEnumerable<T> array, T value)
            where T : IComparable<T>
        {
            int index = 0;
            foreach(var x in array)
            {
                if (x.CompareTo(value) == 0)
                {
                    return index;
                }
                ++index;
            }

            return -1;
        }

        public static int FindFirst<T>(this IEnumerable<T> array, Func<T, bool> f)
        {
            int index = 0;
            foreach(var x in array)
            {
                if (f(x))
                {
                    return index;
                }
                ++index;
            }

            return -1;
        }
    }
}


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

<TITLE>
RotatingRangeScanner (leJOS NXJ PC API documentation)
</TITLE>

<META NAME="date" CONTENT="2011-05-16">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

lejos.robotics

Class RotatingRangeScanner

java.lang.Object
  lejos.robotics.RotatingRangeScanner

All Implemented Interfaces:
RangeScanner

public class RotatingRangeScanner
extends java.lang.Object
implements RangeScanner

Implementation of RangeScanner with a rotating ultrasonic sensor or other range finder

Author:

Roger Glassey

Field Summary

protected  float[]
angles

protected  RegulatedMotor
head

protected  int
MAX_RELIABLE_RANGE_READING

protected  RangeFinder
rangeFinder

protected  RangeReadings
readings

protected  int
ZERO

Constructor Summary

RotatingRangeScanner(RegulatedMotor head,
                     RangeFinder rangeFinder)

          The constructor specifies the motor and range finder used

Method Summary

 RangeFinder
getRangeFinder()

          returns the rangeFinder - allows other objects to get a range value.

 RangeReadings
getRangeValues()

          Returns a set of Range Readings taken the angles specified.

 void
setAngles(float[] angles)

          set the angles to be used by the getRangeValues() method

Methods inherited from class java.lang.Object

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

Field Detail

MAX_RELIABLE_RANGE_READING

protected final int MAX_RELIABLE_RANGE_READING

See Also:
Constant Field Values

ZERO

protected final int ZERO

See Also:
Constant Field Values

readings

protected RangeReadings readings

rangeFinder

protected RangeFinder rangeFinder

head

protected RegulatedMotor head

angles

protected float[] angles

Constructor Detail

RotatingRangeScanner

public RotatingRangeScanner(RegulatedMotor head,
                            RangeFinder rangeFinder)

The constructor specifies the motor and range finder used

Parameters:
head - the motor that rotates the sensor
rangeFinder - the range finder

Method Detail

getRangeValues

public RangeReadings getRangeValues()

Returns a set of Range Readings taken the angles specified.

Specified by:
getRangeValues in interface RangeScanner

Returns:
the set of range values

setAngles

public void setAngles(float[] angles)

set the angles to be used by the getRangeValues() method

Specified by:
setAngles in interface RangeScanner

Parameters:
angles -

getRangeFinder

public RangeFinder getRangeFinder()

returns the rangeFinder - allows other objects to get a range value.

Specified by:
getRangeFinder in interface RangeScanner

Returns:
the range finder

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
class Packet;
class GameConsoleWindow;

class ClientMessageParser
{
public:
	ClientMessageParser(GameConsoleWindow* const console);
	~ClientMessageParser();

	//Returns the queue that is processed in MessageHandler's update function.
	std::vector<std::unique_ptr<Packet>>& GetInMessageQueue() { return inMessageQueue; }
	std::vector<std::unique_ptr<Packet>>& GetOutMessageQueue() { return outMessageQueue; }

	//Process any messages that could be in the inMessageQueue
	void Update();

	void SendTextPacket(CEGUI::String text, bool sendColor, CEGUI::argb_t color = 0);
	void SendUserDataPacket(ChatUserData& userData);

	private:
		void ReadStringData(std::unique_ptr<Packet> packet,  bool containsColorData);
		void ReadUserData(std::unique_ptr<Packet> packet);
		void ReadDisconnectData(std::unique_ptr<Packet> packet);

private:
	GameConsoleWindow* consoleWindow;

	//... I use a preallocated vector because it feels like the cleanest and it's probably the fastest
	std::vector<std::unique_ptr<Packet>> inMessageQueue;
	std::vector<std::unique_ptr<Packet>> outMessageQueue;
};


text:
<?php

namespace App\Containers\User\Actions;

use Apiato\Core\Foundation\Facades\Apiato;
use App\Ship\Parents\Actions\Action;
use App\Ship\Transporters\DataTransporter;

class GetUserFeedAction extends Action
{
    public function run(DataTransporter $dataTransporter)
    {
        $authenticatedUser = Apiato::call('Authentication@GetAuthenticatedUserTask');
        return Apiato::call('User@GetUserFeedTask', [$authenticatedUser, $dataTransporter->limit]);
    }
}


text:
<title>Enum Target Types - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Target-Descriptions.html#Target-Descriptions" title="Target Descriptions">
<link rel="prev" href="Predefined-Target-Types.html#Predefined-Target-Types" title="Predefined Target Types">
<link rel="next" href="Standard-Target-Features.html#Standard-Target-Features" title="Standard Target Features">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Standard Target Features,
Previous: Predefined Target Types,
Up: Target Descriptions

G.4 Enum Target Types

Enum target types are useful in ‘<samp>struct</samp>’ and ‘<samp>flags</samp>’
register descriptions.  See Target Description Format.

Enum types have a name, size and a list of name/value pairs.

     <enum id="<var>id</var>" size="<var>size</var>">
       <evalue name="<var>name</var>" value="<var>value</var>"/>
       ...
     </enum>

Enums must be defined before they are used.

     <enum id="levels_type" size="4">
       <evalue name="low" value="0"/>
       <evalue name="high" value="1"/>
     </enum>
     <flags id="flags_type" size="4">
       <field name="X" start="0"/>
       <field name="LEVEL" start="1" end="1" type="levels_type"/>
     </flags>
     <reg name="flags" bitsize="32" type="flags_type"/>

Given that description, a value of 3 for the ‘<samp>flags</samp>’ register
would be printed as:

     (gdb) info register flags
     flags 0x3 [ X LEVEL=high ]


text:
//
// Copyright 2018 ZetaSQL Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#ifndef THIRD_PARTY_ZETASQL_ZETASQL_BASE_ARENA_ALLOCATOR_H_
#define THIRD_PARTY_ZETASQL_ZETASQL_BASE_ARENA_ALLOCATOR_H_

// In this file we define the arena template code.  This includes the
// ArenaAllocator, which is meant only to be used with STL, and also
// the Gladiator (which needs to know how to new and delete various
// types of objects).
//
// If you're only using the MALLOC-LIKE functionality of the arena,
// you don't need to include this file at all!  You do need to include
// it (in your own .cc file) if you want to use the STRING, STL, or
// NEW aspects of the arena.  See arena.h for details on these types.
//
// ArenaAllocator is an STL allocator, but because it relies on unequal
// instances, it may not work with all standards-conforming STL
// implementations.  But it works with SGI STL so we're happy.
//
// Here's an example of how the ArenaAllocator would be used.
// Say we have a vector of ints that we want to have use the arena
// for memory allocation.  Here's one way to do it:
//    UnsafeArena* arena = new UnsafeArena(1024); // or SafeArena
//    std::vector<int, ArenaAllocator<int, UnsafeArena> > v(arena);
//
// Note that every STL type always allows the allocator (in this case,
// the arena, which is automatically promoted to an allocator) as the last
// arg to the constructor.  So if you would normally do
//    std::vector<...> v(foo, bar),
// with the arena you can do
//    std::vector<...> v(foo, bar, arena);

#include "zetasql/base/arena.h"

#include <assert.h>
#include <stddef.h>
#include <new>
#include <memory>
#include <type_traits>

#include "absl/base/macros.h"
#include "zetasql/base/logging.h"

namespace zetasql_base {

// T is the type we want to allocate, and C is the type of the arena.
// ArenaAllocator has the thread-safety characteristics of C.
template <class T, class C> class ArenaAllocator {
 public:
  typedef T value_type;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;

  // These are required for gcc-4.7 / crosstoolv16 to match default behavior
  // of gcc-4.6, so e.g.
  //   Arena a1, a2;
  //   astring s1(&a1), s2(&a2);
  //   s1.swap(s2);  // s1 should now use a2, s2 should now use a1.
  //   s2 = s1;      // s2 should now use a2, s1 should still use a2.
  typedef std::true_type propagate_on_container_copy_assignment;
  typedef std::true_type propagate_on_container_move_assignment;
  typedef std::true_type propagate_on_container_swap;

  typedef T* pointer;
  typedef const T* const_pointer;
  typedef T& reference;
  typedef const T& const_reference;
  typedef std::false_type is_always_equal;

  size_type max_size() const {
    return size_t(std::numeric_limits<size_type>::max()) / sizeof(value_type);
  }

  pointer address(reference x) const noexcept {
    return std::addressof(x);
  }

  const_pointer address(const_reference x) const noexcept {
    return std::addressof(x);
  }

  template <class U, class... Args>
  void construct(U* u, Args&&... args) {
    new(static_cast<void*>(u)) U(std::forward<Args>(args)...);
  }

  template <class U>
  void destroy(U* u) { u->~U(); }

  // This is not an explicit constructor!  So you can pass in an arena*
  // to functions needing an ArenaAllocator (like the astring constructor)
  // and everything will work ok.
  ArenaAllocator(C* arena) : arena_(arena) { }  // NOLINT

  pointer allocate(size_type n,
                   std::allocator<void>::const_pointer /*hint*/ = nullptr) {
    assert(arena_ && "No arena to allocate from!");
    return reinterpret_cast<T*>(arena_->AllocAligned(n * sizeof(T),
                                                     kAlignment));
  }
  void deallocate(pointer p, size_type n) {
    arena_->Free(p, n * sizeof(T));
  }

  C* arena(void) const { return arena_; }

  template<class U> struct rebind {
    typedef ArenaAllocator<U, C> other;
  };

  template<class U> ArenaAllocator(const ArenaAllocator<U, C>& other)
    : arena_(other.arena()) { }

  template<class U> bool operator==(const ArenaAllocator<U, C>& other) const {
    return arena_ == other.arena();
  }

  template<class U> bool operator!=(const ArenaAllocator<U, C>& other) const {
    return arena_ != other.arena();
  }

 protected:
  static const int kAlignment;
  C* arena_;
};

template <class T, class C>
const int ArenaAllocator<T, C>::kAlignment = alignof(T);

// Ordinarily in C++, one allocates all instances of a class from an
// arena.  If that's what you want to do, you don't need Gladiator.
// (However you may find ArenaOnlyGladiator useful.)
//
// However, for utility classes that are used by multiple clients, the
// everything-in-one-arena model may not work.  Some clients may wish
// not to use an arena at all.  Or perhaps a composite structure
// (tree) will contain multiple objects (nodes) and some of those
// objects will be created by a factory, using an arena, while other
// objects will be created on-the-fly by an unsuspecting user who
// doesn't know anything about the arena.
//
// To support that, have the arena-allocated class inherit from
// Gladiator.  The ordinary operator new will continue to allocate
// from the heap.  To allocate from an arena, do
//     Myclass * m = new (AllocateInArena, a) Myclass (args, to, constructor);
// where a is either an arena or an allocator.  Now you can call
// delete on all the objects, whether they are allocated from an arena
// or on the heap.  Heap memory will be released, while arena memory will
// not be.
//
// If a client knows that no objects were allocated on the heap, it
// need not delete any objects (but it may if it wishes).  The only
// objects that must be deleted are those that were actually allocated
// from the heap.
//
// NOTE: an exception to the google C++ style guide rule for "No multiple
// implementation inheritance" is granted for this class: you can treat this
// class as an "Interface" class, and use it in a multiple inheritance context,
// even though it implements operator new/delete.

class Gladiator {
 public:
  Gladiator() { }
  virtual ~Gladiator() { }

  // We do not override the array allocators, so array allocation and
  // deallocation will always be from the heap.  Typically, arrays are
  // larger, and thus the costs of arena allocation are higher and the
  // benefits smaller.  Since arrays are typically allocated and deallocated
  // very differently from scalars, this may not interfere too much with
  // the arena concept.  If it does pose a problem, flesh out the
  // ArrayGladiator class below.

  void* operator new(const size_t size) {
    void* ret = ::operator new(1 + size);
    static_cast<char *>(ret)[size] = 1;     // mark as heap-allocated
    return ret;
  }
  // the ignored parameter keeps us from stepping on placement new
  template<class T> void* operator new(const size_t size, const int ignored,
                                       T* allocator) {
    if (allocator) {
      void* ret = allocator->AllocAligned(1 + size,
                                          BaseArena::kDefaultAlignment);
      static_cast<char*>(ret)[size] = 0;  // mark as arena-allocated
      return ret;
    } else {
      return operator new(size);          // this is the function above
    }
  }
  void operator delete(void* memory, const size_t size) {
    if (static_cast<char*>(memory)[size]) {
      assert (1 == static_cast<char *>(memory)[size]);
      ::operator delete(memory);
    } else {
      // We never call the allocator's Free method.  If we need to do
      // that someday, we can store a pointer to the arena instead of
      // the Boolean marker flag.
    }
  }
  template<class T> void operator delete(void* memory, const size_t size,
                                         const int ign, T* allocator) {
    // This "placement delete" can only be called if the constructor
    // throws an exception.
    if (allocator) {
      allocator->Free(memory, 1 + size);
    } else {
      ::operator delete(memory);
    }
  }

 private:
  virtual void UnusedKeyMethod();  // Dummy key method to avoid weak vtable.
};

// ArenaOnlyGladiator is a base class of types intended to be allocated only in
// arenas. It enables allocation with zetasql_base::NewInArea and prevents accidental
// use of the global operator new and delete with derived types.
//
// Brief example (see documentation for zetasql_base::NewInArena / zetasql_base::DeleteInArena
// for full details):
//
//   class MyType : public ArenaOnlyGladiator {
//     // ...
//   };
//
//   UnsafeArena arena(1024);
//   MyType* t1 = zetasql_base::NewInArena<MyType>(&arena);
//
//   MyType* t2 = new MyType();  // ERROR
//
class ArenaOnlyGladiator {
 public:
  ArenaOnlyGladiator() { }
  // No virtual destructor is needed because we ignore the size
  // parameter in all the delete functions.
  // virtual ~ArenaOnlyGladiator() { }

  void* operator new(size_t) = delete;
  void* operator new[](size_t) = delete;

  // the ignored parameter keeps us from stepping on placement new
  template <class T>
  ABSL_DEPRECATED("use zetasql_base::NewInArena from base/arena_allocator.h instead")
  void* operator new(const size_t size, const int ignored, T* allocator) {
    assert(allocator);
    return allocator->AllocAligned(size, BaseArena::kDefaultAlignment);
  }

  template <class T>
  ABSL_DEPRECATED("use zetasql_base::NewInArena from base/arena_allocator.h instead")
  void* operator new[](const size_t size, const int ignored, T* allocator) {
    assert(allocator);
    return allocator->AllocAligned(size, BaseArena::kDefaultAlignment);
  }

  void operator delete(void* /*memory*/, const size_t /*size*/) {}

  template <class T>
  ABSL_DEPRECATED("use zetasql_base::DeleteInArena from base/arena_allocator.h instead")
  void operator delete(void* memory, const size_t size, const int ign,
                       T* allocator) {}

  void operator delete[](void* /*memory*/) {}

  template <class T>
  ABSL_DEPRECATED("use zetasql_base::DeleteInArena from base/arena_allocator.h instead")
  void operator delete(void* memory, const int ign, T* allocator) {}
};

#if 0  // ********** for example purposes only; 100% untested.

// Note that this implementation incurs an overhead of kHeaderSize for
// every array that is allocated.  *Before* the space is returned to the
// user, we store the address of the Arena that owns the space, and
// the length of th space itself.

class ArrayGladiator : public Gladiator {
 public:
  void * operator new[] (const size_t size) {
    const int sizeplus = size + kHeaderSize;
    void * const ret = ::operator new(sizeplus);
    *static_cast<Arena **>(ret) = nullptr;  // mark as heap-allocated
    *static_cast<size_t *>(ret + sizeof(Arena *)) = sizeplus;
    return ret + kHeaderSize;
  }
  // the ignored parameter keeps us from stepping on placement new
  template<class T> void * operator new[] (const size_t size,
                                           const int ignored, T * allocator) {
    if (allocator) {
      const int sizeplus = size + kHeaderSize;
      void * const ret =
          allocator->AllocAligned(sizeplus, BaseArena::kDefaultAlignment);
      *static_cast<Arena **>(ret) = allocator->arena();
      *static_cast<size_t *>(ret + sizeof(Arena *)) = sizeplus;
      return ret + kHeaderSize;
    } else {
      return operator new[](size);  // this is the function above
    }
  }
  void operator delete [] (void * memory) {
    memory -= kHeaderSize;
    Arena * const arena = *static_cast<Arena **>(memory);
    const size_t sizeplus = *static_cast<size_t *>(memory + sizeof(arena));
    if (arena) {
      arena->SlowFree(memory, sizeplus);
    } else {
      ::operator delete (memory);
    }
  }
  template<class T> void * operator delete (void * memory,
                                            const int ign, T * allocator) {
    // This "placement delete" can only be called if the constructor
    // throws an exception.
    memory -= kHeaderSize;
    const size_t sizeplus = *static_cast<size_t *>(memory + sizeof(Arena *));
    if (allocator) {
      allocator->Free(memory, 1 + size);
    } else {
      operator delete (memory);
    }
  }

 protected:
  static const int kMinSize = sizeof size_t + sizeof(Arena *);
  static const int kHeaderSize = kMinSize > BaseArena::kDefaultAlignment ?
    2 * BaseArena::kDefaultAlignment : BaseArena::kDefaultAlignment;
};

#endif  // ********** example

// NewInArena<T>, DeleteInArena<T>: functions for constructing and destroying
// C++ objects inside an Arena. This is useful when doing one-time allocations,
// instead of having to create a persisting ArenaAllocator for each desired
// type. It is also safer and less verbose than dealing with the C-style
// interface of Arena directly.
//
// NewInArena<T> properly supports over-aligned types. These are types with
// alignment requirement greater than that of any fundamental type
// (i.e. alignof(std::max_align_t)). These types can occur as either platform
// specific extension types or as user types defined with an alignas specifier.
//
// NewInArena<T> is a drop-in replacement for the `AllocateInArena` operator
// new overloads that are defined below and as part of `ArenaOnlyGladiator`
// above. It is *not* a replacement for the operator new overloads in
// `Gladiator`, and using the function in this way will result in compile-time
// error.
//
// Example allocation:
//
//   struct MyType {
//     MyType();
//     MyType(int, int);
//   };
//
//   UnsafeArena arena(1024);
//   MyType* p = zetasql_base::NewInArena<MyType>(&arena, 5, 3);
//   MyType* q = zetasql_base::NewInArena<MyType[]>(&arena, 10);
//
// When finished, you must destroy the objects and return memory as follows:
//
//   zetasql_base::DeleteInArena(&arena, p);
//   zetasql_base::DeleteInArena(&arena, q, 10);
//
// NOTE: there are current uses of the `AllocateInArena` operator new that
// do not call delete. These uses rely on Arena::Reset() or ~Arena() to return
// memory, because the types in question have trivial destructors or do not
// perform resource management. Such uses should be updated to use
// DeleteInArena<T> for safety against undefined behavior.
template <typename T, typename ArenaType, typename... Args,
          typename std::enable_if<!std::is_array<T>::value>::type* = nullptr>
// NOLINTNEXTLINE - suppress ClangTidy raw pointer return.
T* NewInArena(ArenaType* arena, Args&&... args) {
  static_assert(!std::is_base_of<Gladiator, T>::value,
                "Allocating an object with type inheriting from Gladiator is "
                "not supported by NewInArena.");
  return ::new (static_cast<void*>(arena->AllocAligned(sizeof(T), alignof(T))))
      T(std::forward<Args>(args)...);
}

template <typename T, typename ArenaType,
          typename std::enable_if<std::is_array<T>::value &&
                                  std::extent<T>::value == 0>::type* = nullptr>
// NOLINTNEXTLINE - suppress ClangTidy raw pointer return.
typename std::remove_extent<T>::type* NewInArena(ArenaType* arena, size_t n) {
  static_assert(!std::is_base_of<Gladiator, T>::value,
                "Allocating an object with type inheriting from Gladiator is "
                "not supported by NewInArena.");
  using U = typename std::remove_extent<T>::type;
  U* p = static_cast<U*>(arena->AllocAligned(n * sizeof(U), alignof(U)));
  for (size_t i = 0; i < n; ++i) ::new (static_cast<void*>(p + i)) U;
  return p;
}

template <typename T, typename... Args,
          typename std::enable_if<std::is_array<T>::value &&
                                  std::extent<T>::value != 0>::type* = nullptr>
// NOLINTNEXTLINE - suppress ClangTidy raw pointer return.
T* NewInArena(Args&&... args) = delete;

template <typename ArenaType, typename T>
void DeleteInArena(ArenaType* arena, T* t) {
  static_assert(!std::is_base_of<Gladiator, T>::value,
                "Destroying an object with type inheriting from Gladiator is "
                "not supported by DeleteInArena.");
  t->~T();
  arena->Free(t, sizeof(T));
}

template <typename ArenaType, typename T>
void DeleteInArena(ArenaType* arena, T* t, size_t n) {
  static_assert(!std::is_base_of<Gladiator, T>::value,
                "Destroying an object with type inheriting from Gladiator is "
                "not supported by DeleteInArena.");
  for (size_t i = 0; i < n; ++i) (t + i)->~T();
  arena->Free(t, n * sizeof(T));
}

enum AllocateInArenaType { AllocateInArena };

}  // namespace zetasql_base

#endif  // THIRD_PARTY_ZETASQL_ZETASQL_BASE_ARENA_ALLOCATOR_H_


text:
// @ts-check

export const CHANGE_DRAWER = 'CHANGE_DRAWER';

/**
 * Change drawer action creator
 *
 * @param {boolean} open Should the drawer change to open
 */
export function changeDrawer(open) {
  return {
    type: CHANGE_DRAWER,
    open
  };
}

export const ADD_LOGIN_DETAILS = 'ADD_LOGIN_DETAILS';

/**
 * Create an add login details action
 *
 * @param {string} name The name of the site
 * @param {string} url The url of the site
 * @param {string} username Username of the user
 * @param {string} password Password of the user
 */
export function addLoginDetails(id, name, url, username, password) {
  return {
    type: ADD_LOGIN_DETAILS,
    site: {
      id,
      name,
      url,
      username,
      password
    }
  };
}

export const ADD_MASTER_PASSWORD = 'ADD_MASTER_PASSWORD';

/**
 * Create and add login details action
 *
 * @param {string} masterPassword Master Password
 */
export function addMasterPassword(masterPassword) {
  return {
    type: ADD_MASTER_PASSWORD,
    masterPassword
  };
}

export const SAVED = 'SAVED';

/**
 * Indicate that the details have been saved
 */
export function saved() {
  return {
    type: SAVED
  };
}

export const REAUTH_AND_RESTORE_LOGIN_DETAILS =
  'REAUTH_AND_RESTORE_LOGIN_DETAILS';

/**
 * Master Password reauth and login details restored
 *
 * @param {string} masterPassword
 * @param {{[x: string]: {name: string, url: string, username: string, password: string}}} loginDetails
 */
export function reauthAndRestoreLoginDetails(masterPassword, loginDetails) {
  return {
    type: REAUTH_AND_RESTORE_LOGIN_DETAILS,
    masterPassword,
    loginDetails
  };
}


text:
Utilize the Steam API

- compare multiple friends games
- compare multiple friends achievements for a game, currently steam only allows one friend for one game
- utilized [this gem](https://github.com/Olgagr/steam-web-api)

## Ideas
 - show user stats, basic info
 - all the graphs of all the things
 - choose a random game based on unplayed games or some comparison of stats
 - maybe some kind of relation between time played, cost, etc vs actual prices, etc
 - if accessible, money spent over time, related to sales
 - if accessible, amount actually spent and how many games on sale, %-wise

## others
- [Python](https://github.com/smiley/steamapi)
- [Java](https://github.com/code-disaster/steamworks4j)
- [NodeJS](https://github.com/Tidwell/nodeSteam)


text:
<?xml version="1.0"?>
<Service xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.neeveresearch.com/schema/x-tsml"
    namespace="com.neeve.tick2trade.market" name="market">
    <Models>
        <Model file="com/neeve/tick2trade/messages/messages.xml" />
    </Models>
    <Channels prefixChannelNames="false">
        <Channel name="morders" bus="market" key="morders" />
        <Channel name="mtrade" bus="market" key="mtrade" />
    </Channels>
    <Roles>
        <To role="Market">
            <Message name="MarketNewOrderSingle" channel="morders" />
        </To>
        <To role="Ems">
            <Message name="MarketOrderNew" channel="mtrade" />
            <Message name="MarketTrade" channel="mtrade" />
        </To>
    </Roles>
</Service>