text:
from sys import version_info

if version_info < (3,):
    def _str(value):
        if isinstance(value, unicode):
            return value.encode('utf-8')

        return str(value)
else:
    _str = str

def _to_str(value):
    return _str(value) if value is not None else None

from azure.common import (
    AzureHttpError,
    AzureConflictHttpError,
    AzureMissingResourceHttpError,
    AzureException,
)
from ._constants import (
    _ENCRYPTION_PROTOCOL_V1,
)

_ERROR_CONFLICT = 'Conflict ({0})'
_ERROR_NOT_FOUND = 'Not found ({0})'
_ERROR_UNKNOWN = 'Unknown error ({0})'
_ERROR_STORAGE_MISSING_INFO = \
    'You need to provide an account name and either an account_key or sas_token when creating a storage service.'
_ERROR_EMULATOR_DOES_NOT_SUPPORT_FILES = \
    'The emulator does not support the file service.'
_ERROR_ACCESS_POLICY = \
    'share_access_policy must be either SignedIdentifier or AccessPolicy ' + \
    'instance'
_ERROR_PARALLEL_NOT_SEEKABLE = 'Parallel operations require a seekable stream.'
_ERROR_VALUE_SHOULD_BE_BYTES = '{0} should be of type bytes.'
_ERROR_VALUE_SHOULD_BE_BYTES_OR_STREAM = '{0} should be of type bytes or a readable file-like/io.IOBase stream object.'
_ERROR_VALUE_SHOULD_BE_SEEKABLE_STREAM = '{0} should be a seekable file-like/io.IOBase type stream object.'
_ERROR_VALUE_SHOULD_BE_STREAM = '{0} should be a file-like/io.IOBase type stream object with a read method.'
_ERROR_VALUE_NONE = '{0} should not be None.'
_ERROR_VALUE_NONE_OR_EMPTY = '{0} should not be None or empty.'
_ERROR_VALUE_NEGATIVE = '{0} should not be negative.'
_ERROR_START_END_NEEDED_FOR_MD5 = \
    'Both end_range and start_range need to be specified ' + \
    'for getting content MD5.'
_ERROR_RANGE_TOO_LARGE_FOR_MD5 = \
    'Getting content MD5 for a range greater than 4MB ' + \
    'is not supported.'
_ERROR_MD5_MISMATCH = \
    'MD5 mismatch. Expected value is \'{0}\', computed value is \'{1}\'.'
_ERROR_TOO_MANY_ACCESS_POLICIES = \
    'Too many access policies provided. The server does not support setting more than 5 access policies on a single resource.'
_ERROR_OBJECT_INVALID = \
    '{0} does not define a complete interface. Value of {1} is either missing or invalid.'
_ERROR_UNSUPPORTED_ENCRYPTION_VERSION = \
    'Encryption version is not supported.'
_ERROR_DECRYPTION_FAILURE = \
    'Decryption failed'
_ERROR_ENCRYPTION_REQUIRED = \
    'Encryption required but no key was provided.'
_ERROR_DECRYPTION_REQUIRED = \
    'Decryption required but neither key nor resolver was provided.' + \
    ' If you do not want to decypt, please do not set the require encryption flag.'
_ERROR_INVALID_KID = \
    'Provided or resolved key-encryption-key does not match the id of key used to encrypt.'
_ERROR_UNSUPPORTED_ENCRYPTION_ALGORITHM = \
    'Specified encryption algorithm is not supported.'
_ERROR_UNSUPPORTED_METHOD_FOR_ENCRYPTION = 'The require_encryption flag is set, but encryption is not supported' + \
                                           ' for this method.'
_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM = 'Unknown key wrap algorithm.'
_ERROR_DATA_NOT_ENCRYPTED = 'Encryption required, but received data does not contain appropriate metatadata.' + \
                            'Data was either not encrypted or metadata has been lost.'

def _dont_fail_on_exist(error):
    ''' don't throw exception if the resource exists.
    This is called by create_* APIs with fail_on_exist=False'''
    if isinstance(error, AzureConflictHttpError):
        return False
    else:
        raise error

def _dont_fail_not_exist(error):
    ''' don't throw exception if the resource doesn't exist.
    This is called by create_* APIs with fail_on_exist=False'''
    if isinstance(error, AzureMissingResourceHttpError):
        return False
    else:
        raise error

def _http_error_handler(http_error):
    ''' Simple error handler for azure.'''
    message = str(http_error)
    error_code = None

    if 'x-ms-error-code' in http_error.respheader:
        error_code = http_error.respheader['x-ms-error-code']
        message += ' ErrorCode: ' + error_code

    if http_error.respbody is not None:
        message += '\n' + http_error.respbody.decode('utf-8-sig')

    ex = AzureHttpError(message, http_error.status)
    ex.error_code = error_code

    raise ex

def _validate_type_bytes(param_name, param):
    if not isinstance(param, bytes):
        raise TypeError(_ERROR_VALUE_SHOULD_BE_BYTES.format(param_name))

def _validate_type_bytes_or_stream(param_name, param):
    if not (isinstance(param, bytes) or hasattr(param, 'read')):
        raise TypeError(_ERROR_VALUE_SHOULD_BE_BYTES_OR_STREAM.format(param_name))

def _validate_not_none(param_name, param):
    if param is None:
        raise ValueError(_ERROR_VALUE_NONE.format(param_name))

def _validate_content_match(server_md5, computed_md5):
    if server_md5 != computed_md5:
        raise AzureException(_ERROR_MD5_MISMATCH.format(server_md5, computed_md5))

def _validate_access_policies(identifiers):
    if identifiers and len(identifiers) > 5:
        raise AzureException(_ERROR_TOO_MANY_ACCESS_POLICIES)

def _validate_key_encryption_key_wrap(kek):
    # Note that None is not callable and so will fail the second clause of each check.
    if not hasattr(kek, 'wrap_key') or not callable(kek.wrap_key):
        raise AttributeError(_ERROR_OBJECT_INVALID.format('key encryption key', 'wrap_key'))
    if not hasattr(kek, 'get_kid') or not callable(kek.get_kid):
        raise AttributeError(_ERROR_OBJECT_INVALID.format('key encryption key', 'get_kid'))
    if not hasattr(kek, 'get_key_wrap_algorithm') or not callable(kek.get_key_wrap_algorithm):
        raise AttributeError(_ERROR_OBJECT_INVALID.format('key encryption key', 'get_key_wrap_algorithm'))

def _validate_key_encryption_key_unwrap(kek):
    if not hasattr(kek, 'get_kid') or not callable(kek.get_kid):
        raise AttributeError(_ERROR_OBJECT_INVALID.format('key encryption key', 'get_kid'))
    if not hasattr(kek, 'unwrap_key') or not callable(kek.unwrap_key):
        raise AttributeError(_ERROR_OBJECT_INVALID.format('key encryption key', 'unwrap_key'))

def _validate_encryption_required(require_encryption, kek):
    if require_encryption and (kek is None):
        raise ValueError(_ERROR_ENCRYPTION_REQUIRED)

def _validate_decryption_required(require_encryption, kek, resolver):
    if (require_encryption and (kek is None) and
            (resolver is None)):
        raise ValueError(_ERROR_DECRYPTION_REQUIRED)

def _validate_encryption_protocol_version(encryption_protocol):
    if not (_ENCRYPTION_PROTOCOL_V1 == encryption_protocol):
        raise ValueError(_ERROR_UNSUPPORTED_ENCRYPTION_VERSION)

def _validate_kek_id(kid, resolved_id):
    if not (kid == resolved_id):
        raise ValueError(_ERROR_INVALID_KID)

def _validate_encryption_unsupported(require_encryption, key_encryption_key):
    if require_encryption or (key_encryption_key is not None):
        raise ValueError(_ERROR_UNSUPPORTED_METHOD_FOR_ENCRYPTION)

def _validate_user_delegation_key(user_delegation_key):
    _validate_not_none('user_delegation_key.signed_oid', user_delegation_key.signed_oid)
    _validate_not_none('user_delegation_key.signed_tid', user_delegation_key.signed_tid)
    _validate_not_none('user_delegation_key.signed_start', user_delegation_key.signed_start)
    _validate_not_none('user_delegation_key.signed_expiry', user_delegation_key.signed_expiry)
    _validate_not_none('user_delegation_key.signed_version', user_delegation_key.signed_version)
    _validate_not_none('user_delegation_key.signed_service', user_delegation_key.signed_service)
    _validate_not_none('user_delegation_key.value', user_delegation_key.value)

# wraps a given exception with the desired exception type
def _wrap_exception(ex, desired_type):
    msg = ""
    if len(ex.args) > 0:
        msg = ex.args[0]
    if version_info >= (3,):
        # Automatic chaining in Python 3 means we keep the trace
        return desired_type(msg)
    else:
        # There isn't a good solution in 2 for keeping the stack trace
        # in general, or that will not result in an error in 3
        # However, we can keep the previous error type and message
        # TODO: In the future we will log the trace
        return desired_type('{}: {}'.format(ex.__class__.__name__, msg))

class AzureSigningError(AzureException):
    """
    Represents a fatal error when attempting to sign a request.
    In general, the cause of this exception is user error. For example, the given account key is not valid.
    Please visit https://docs.microsoft.com/en-us/azure/storage/common/storage-create-storage-account for more info.
    """
    pass


text:
package de.dhbw.star.ai.rating;

import de.dhbw.star.game.CheckGameStatus;
import de.dhbw.star.game.GameMap;

/**
 *
 * @author Robert Schütte
 */
public class Rating {

    private GameMap gameMap;

    public Rating(GameMap gameMap) {
        this.gameMap = gameMap;
    }

    /**
     * This function trys to rate a GameMap.
     * @return
     */
    public int getRatingScore() {
        int rating = 0;

        if (new CheckGameStatus(gameMap).checkIfLost()) {
            return 0;
        }

        //points for less boxes
        rating += (Util.countBoxes(gameMap, 0)) * 5;

        rating += (new Merge(gameMap).getMergeRating() / 1);

        //rating *= (new Strategie(gameMap).getStrategieRating() / 100);

        return rating;
    }

}

redpajama_set_name: RedPajamaGithub


text:
@echo off
setlocal

pushd %~dp0\..

set VSCODEUSERDATADIR=%TEMP%\vscodeuserfolder-%RANDOM%-%TIME:~6,2%
set VSCODECRASHDIR=%~dp0\..\.build\crashes

:: Figure out which Electron to use for running tests
if "%INTEGRATION_TEST_ELECTRON_PATH%"=="" (
	:: Run out of sources: no need to compile as code.bat takes care of it
	chcp 65001
	set INTEGRATION_TEST_ELECTRON_PATH=.\scripts\code.bat
	set VSCODE_BUILD_BUILTIN_EXTENSIONS_SILENCE_PLEASE=1

	echo Storing crash reports into '%VSCODECRASHDIR%'.
	echo Running integration tests out of sources.
) else (
	:: Run from a built: need to compile all test extensions
	:: because we run extension tests from their source folders
	:: and the build bundles extensions into .build webpacked
	call yarn gulp 	compile-extension:vscode-api-tests^
					compile-extension:vscode-colorize-tests^
					compile-extension:markdown-language-features^
					compile-extension:emmet^
					compile-extension:css-language-features-server^
					compile-extension:html-language-features-server^
					compile-extension:json-language-features-server^
					compile-extension:git

	:: Configuration for more verbose output
	set VSCODE_CLI=1
	set ELECTRON_ENABLE_LOGGING=1

	echo Storing crash reports into '%VSCODECRASHDIR%'.
	echo Running integration tests with '%INTEGRATION_TEST_ELECTRON_PATH%' as build.
)

:: Integration & performance tests in AMD
call .\scripts\test.bat --runGlob **\*.integrationTest.js %*
if %errorlevel% neq 0 exit /b %errorlevel%

:: Tests in the extension host

call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\vscode-api-tests\testWorkspace --enable-proposed-api=vscode.vscode-api-tests --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\singlefolder-tests --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR%
if %errorlevel% neq 0 exit /b %errorlevel%

call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\vscode-api-tests\testworkspace.code-workspace --enable-proposed-api=vscode.vscode-api-tests --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\workspace-tests --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR%
if %errorlevel% neq 0 exit /b %errorlevel%

call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\vscode-colorize-tests\test --extensionDevelopmentPath=%~dp0\..\extensions\vscode-colorize-tests --extensionTestsPath=%~dp0\..\extensions\vscode-colorize-tests\out --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR%
if %errorlevel% neq 0 exit /b %errorlevel%

call "%INTEGRATION_TEST_ELECTRON_PATH%" $%~dp0\..\extensions\markdown-language-features\out\test\test-fixtures --extensionDevelopmentPath=%~dp0\..\extensions\markdown-language-features --extensionTestsPath=%~dp0\..\extensions\markdown-language-features\out\test --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% .
if %errorlevel% neq 0 exit /b %errorlevel%

call "%INTEGRATION_TEST_ELECTRON_PATH%" $%~dp0\..\extensions\emmet\out\test\test-fixtures --extensionDevelopmentPath=%~dp0\..\extensions\emmet --extensionTestsPath=%~dp0\..\extensions\emmet\out\test --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% .
if %errorlevel% neq 0 exit /b %errorlevel%

for /f "delims=" %%i in ('node -p "require('fs').realpathSync.native(require('os').tmpdir())"') do set TEMPDIR=%%i
set GITWORKSPACE=%TEMPDIR%\git-%RANDOM%
mkdir %GITWORKSPACE%
call "%INTEGRATION_TEST_ELECTRON_PATH%" %GITWORKSPACE% --extensionDevelopmentPath=%~dp0\..\extensions\git --extensionTestsPath=%~dp0\..\extensions\git\out\test --enable-proposed-api=vscode.git --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR%
if %errorlevel% neq 0 exit /b %errorlevel%

:: Tests in commonJS (HTML, CSS, JSON language server tests...)
call .\scripts\node-electron.bat .\node_modules\mocha\bin\_mocha .\extensions\*\server\out\test\**\*.test.js
if %errorlevel% neq 0 exit /b %errorlevel%

rmdir /s /q %VSCODEUSERDATADIR%

popd

endlocal


text:
from google.cloud import appengine_admin_v1

def sample_delete_authorized_certificate():
    # Create a client
    client = appengine_admin_v1.AuthorizedCertificatesClient()

    # Initialize request argument(s)
    request = appengine_admin_v1.DeleteAuthorizedCertificateRequest(
    )

    # Make the request
    client.delete_authorized_certificate(request=request)

# [END appengine_v1_generated_AuthorizedCertificates_DeleteAuthorizedCertificate_sync]


text:
package org.nedervold.grammareditor.grammar.transformations

import org.nedervold.grammareditor.grammar.Grammar

/**
 * Returns a grammar with the productions sorted alphabetically by head (except the first,
 * assumed to be the start symbol).
 * @author nedervold
 */
object AlphabeticSort extends GrammarTransformation {
    def apply(gram: Grammar): Grammar = {
        require(gram != null)
        val hd :: tl = AddUndefinedProductions(gram).productions
        new Grammar(hd :: tl.sortBy(_.head.toString))
    }

    val displayName = "Sort alphabetically"
}


text:
class CHudElement;

//-----------------------------------------------------------------------------
// Purpose: Used by DECLARE_HUDELEMENT macro to create a linked list of
//  instancing functions
//-----------------------------------------------------------------------------
class CHudElementHelper
{
public:
	// Static list of helpers
	static CHudElementHelper *m_sHelpers;
	// Create all the hud elements
	static void CreateAllElements( void );

public:
	// Construction
	CHudElementHelper( CHudElement *( *pfnCreate )( void ), int depth );

	// Accessors
	CHudElementHelper *GetNext( void );

private:
	// Next factory in list
	CHudElementHelper	*m_pNext;
	// Creation function to use for this technology
	CHudElement			*( *m_pfnCreate )( void );

	//Depth used to determine hud panel ordering
	int					m_iDepth;
};

// This is the macro which implements creation of each hud element
// It creates a function which instances an object of the specified type
// It them hooks that function up to the helper list so that the CHud objects can create
//  the elements by name, with no header file dependency, etc.
#define DECLARE_HUDELEMENT( className )											\
	static CHudElement *Create_##className##( void )							\
		{																		\
			return new className( #className );									\
		};																		\
	static CHudElementHelper g_##className##_Helper( Create_##className##, 50 );

#define DECLARE_HUDELEMENT_DEPTH( className, depth )											\
	static CHudElement *Create_##className##( void )							\
		{																		\
			return new className( #className );									\
		};																		\
	static CHudElementHelper g_##className##_Helper( Create_##className##, depth );

#define DECLARE_NAMED_HUDELEMENT( className, panelName )						\
	static CHudElement *Create_##panelName##( void )							\
		{																		\
			return new className( #panelName );									\
		};																		\
	static CHudElementHelper g_##panelName##_Helper( Create_##panelName##, 50 );

// This macro can be used to get a pointer to a specific hud element
#define GET_HUDELEMENT( className )												\
	(##className##*)gHUD.FindElement( #className )

#define GET_NAMED_HUDELEMENT( className, panelName )							\
	(##className##*)gHUD.FindElement( #panelName )

// Things that inherit from vgui::Panel, too, will have ambiguous new operators
//  so this should disambiguate them
#define DECLARE_MULTIPLY_INHERITED()							\
    void *operator new( size_t stAllocateBlock )				\
	{															\
		return CHudElement::operator new ( stAllocateBlock );	\
	}															\
	void* operator new( size_t stAllocateBlock, int nBlockUse, const char *pFileName, int nLine )	\
	{ 																								\
		return CHudElement::operator new ( stAllocateBlock, nBlockUse, pFileName, nLine );	\
	}															\
	void operator delete( void *pMem )							\
	{															\
		CHudElement::operator delete ( pMem );					\
	}															\
	void operator delete( void *pMem, int nBlockUse, const char *pFileName, int nLine )	\
	{															\
		CHudElement::operator delete ( pMem, nBlockUse, pFileName, nLine );	\
	}

// Alias for base hud element
#define IMPLEMENT_OPERATORS_NEW_AND_DELETE			DECLARE_MULTIPLY_INHERITED

#endif // HUD_ELEMENT_HELPER_H


text:
/* global describe, it, require */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	factorialln = require( './../lib/number.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'number factorialln', function tests() {

	it( 'should export a function', function test() {
		expect( factorialln ).to.be.a( 'function' );
	});

	it( 'should evaluate the natural logarithm factorial', function test() {
		assert.closeTo( factorialln( 0 ), 0, 1e-4 );
		assert.closeTo( factorialln( 1.2 ), 0.09694747, 1e-4 );
		assert.closeTo( factorialln( 5 ), 4.78749174, 1e-4 );
		assert.closeTo( factorialln( 100 ), 363.73937556, 1e-4 );
	});

	it( 'should return NaN if provided a NaN', function test() {
		var val = factorialln( NaN );
		assert.isNumber( val );
		assert.ok( val !== val );
	});

	it( 'should return NaN if provided a negative number', function test() {

		// integer
		var val = factorialln( -3 );
		assert.isNumber( val );
		assert.ok( val !== val );

		// non-integer
		val = factorialln( -2.7 );
		assert.isNumber( val );
		assert.ok( val !== val );
	});

	it( 'should return a numeric value if provided a numeric value', function test() {
		assert.isNumber( factorialln( 1 ) );
	});

});


text:
def myfunc(self,            # gotta have self
           param1="value",  # values are cool
           param2=True,     # or False, whatever
           **kwargs):       # you never know
    pass

def           : meta.function.python, source.python, storage.type.function.python
              : meta.function.python, source.python
myfunc        : entity.name.function.python, meta.function.python, source.python
(             : meta.function.parameters.python, meta.function.python, punctuation.definition.parameters.begin.python, source.python
self          : meta.function.parameters.python, meta.function.python, source.python, variable.parameter.function.language.python, variable.parameter.function.language.special.self.python
,             : meta.function.parameters.python, meta.function.python, punctuation.separator.parameters.python, source.python
              : meta.function.parameters.python, meta.function.python, source.python
#             : comment.line.number-sign.python, meta.function.parameters.python, meta.function.python, punctuation.definition.comment.python, source.python
 gotta have self : comment.line.number-sign.python, meta.function.parameters.python, meta.function.python, source.python
              : meta.function.parameters.python, meta.function.python, source.python
param1        : meta.function.parameters.python, meta.function.python, source.python, variable.parameter.function.language.python
=             : keyword.operator.python, meta.function.parameters.python, meta.function.python, source.python
"             : meta.function.parameters.python, meta.function.python, punctuation.definition.string.begin.python, source.python, string.quoted.single.python
value         : meta.function.parameters.python, meta.function.python, source.python, string.quoted.single.python
"             : meta.function.parameters.python, meta.function.python, punctuation.definition.string.end.python, source.python, string.quoted.single.python
,             : meta.function.parameters.python, meta.function.python, punctuation.separator.parameters.python, source.python
              : meta.function.parameters.python, meta.function.python, source.python
#             : comment.line.number-sign.python, meta.function.parameters.python, meta.function.python, punctuation.definition.comment.python, source.python
 values are cool : comment.line.number-sign.python, meta.function.parameters.python, meta.function.python, source.python
              : meta.function.parameters.python, meta.function.python, source.python
param2        : meta.function.parameters.python, meta.function.python, source.python, variable.parameter.function.language.python
=             : keyword.operator.python, meta.function.parameters.python, meta.function.python, source.python
True          : constant.language.python, meta.function.parameters.python, meta.function.python, source.python
,             : meta.function.parameters.python, meta.function.python, punctuation.separator.parameters.python, source.python
              : meta.function.parameters.python, meta.function.python, source.python
#             : comment.line.number-sign.python, meta.function.parameters.python, meta.function.python, punctuation.definition.comment.python, source.python
 or False, whatever : comment.line.number-sign.python, meta.function.parameters.python, meta.function.python, source.python
              : meta.function.parameters.python, meta.function.python, source.python
**            : keyword.operator.unpacking.parameter.python, meta.function.parameters.python, meta.function.python, source.python
kwargs        : meta.function.parameters.python, meta.function.python, source.python, variable.parameter.function.language.python
)             : meta.function.parameters.python, meta.function.python, punctuation.definition.parameters.end.python, source.python
:             : meta.function.python, punctuation.section.function.begin.python, source.python
              : source.python
#             : comment.line.number-sign.python, punctuation.definition.comment.python, source.python
 you never know : comment.line.number-sign.python, source.python
              : source.python
pass          : keyword.control.flow.python, source.python


text:
package fr.openwide.maven.artifact.notifier.core.business.user.model;

import java.util.Set;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.OneToMany;

import org.bindgen.Bindable;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.SortNatural;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Fields;
import org.hibernate.search.annotations.Indexed;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Sets;

import fr.openwide.core.jpa.search.util.HibernateSearchAnalyzer;
import fr.openwide.core.jpa.security.business.person.model.GenericSimpleUser;
import fr.openwide.core.spring.util.StringUtils;
import fr.openwide.maven.artifact.notifier.core.business.artifact.model.ArtifactVersionNotification;
import fr.openwide.maven.artifact.notifier.core.business.artifact.model.FollowedArtifact;

@Indexed
@Bindable
@Cacheable
@Entity(name = "user_")
@AttributeOverrides({
		@AttributeOverride(name = "firstName", column = @Column(nullable = true)),
		@AttributeOverride(name = "lastName", column = @Column(nullable = true))
})
public class User extends GenericSimpleUser<User, UserGroup> {

	private static final long serialVersionUID = 1508647513049577617L;

	public static final String FULL_NAME_SORT_FIELD_NAME = "fullNameSort";

	public static final int MIN_USERNAME_LENGTH = 3;
	public static final int MAX_USERNAME_LENGTH = 25;

	public static final int MIN_PASSWORD_LENGTH = 6;
	public static final int MAX_PASSWORD_LENGTH = 15;

	@Column(nullable = false)
	@Enumerated(EnumType.STRING)
	private AuthenticationType authenticationType = AuthenticationType.LOCAL;

	@Column(unique = true)
	private String remoteIdentifier;

	@Column
	@Fields({
		@Field(analyzer = @Analyzer(definition = HibernateSearchAnalyzer.TEXT)),
		@Field(name = FULL_NAME_SORT_FIELD_NAME, analyzer = @Analyzer(definition = HibernateSearchAnalyzer.TEXT_SORT))
	})
	private String fullName;

	@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
	@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
	@SortNatural
	private Set<FollowedArtifact> followedArtifacts = Sets.newTreeSet();

	@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
	@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
	@SortNatural
	private Set<ArtifactVersionNotification> notifications = Sets.newTreeSet();

	@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
	@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
	@SortNatural
	private Set<EmailAddress> additionalEmails = Sets.newTreeSet();

	@JsonIgnore
	@Column(unique = true)
	private String notificationHash;

	@Column(nullable = false)
	private boolean notificationAllowed = true;

	public User() {
	}

	public void copyProfileToUser(User target) {
		for (FollowedArtifact followedArtifact : followedArtifacts) {
			target.addFollowedArtifact(followedArtifact.copyforUser(target));
		}
		for (ArtifactVersionNotification notification : notifications) {
			target.addNotification(notification.copyForUser(target));
		}
		for (EmailAddress emailAddress : additionalEmails) {
			target.addAdditionalEmail(emailAddress.copyForUser(target));
		}
	}

	public AuthenticationType getAuthenticationType() {
		return authenticationType;
	}

	public void setAuthenticationType(AuthenticationType authenticationType) {
		this.authenticationType = authenticationType;
	}

	public String getRemoteIdentifier() {
		return remoteIdentifier;
	}

	public void setRemoteIdentifier(String remoteIdentifier) {
		this.remoteIdentifier = remoteIdentifier;
	}

	public Set<FollowedArtifact> getFollowedArtifacts() {
		return followedArtifacts;
	}

	public void addFollowedArtifact(FollowedArtifact followedArtifact) {
		if (!followedArtifacts.contains(followedArtifact)) {
			followedArtifacts.add(followedArtifact);
			followedArtifact.setUser(this);
		}
	}

	public Set<ArtifactVersionNotification> getNotifications() {
		return notifications;
	}

	public void addNotification(ArtifactVersionNotification notification) {
		if (!notifications.contains(notification)) {
			notifications.add(notification);
			notification.setUser(this);
		}
	}

	public Set<EmailAddress> getAdditionalEmails() {
		return additionalEmails;
	}

	public void addAdditionalEmail(EmailAddress emailAddress) {
		if (!additionalEmails.contains(emailAddress)) {
			additionalEmails.add(emailAddress);
			emailAddress.setUser(this);
		}
	}

	public String getNotificationHash() {
		return notificationHash;
	}

	public void setNotificationHash(String notificationHash) {
		this.notificationHash = notificationHash;
	}

	public boolean isNotificationAllowed() {
		return notificationAllowed;
	}

	public void setNotificationAllowed(boolean notificationAllowed) {
		this.notificationAllowed = notificationAllowed;
	}

	@Override
	public String getDisplayName() {
		if (StringUtils.hasText(fullName)) {
			return fullName;
		} else {
			return getUserName();
		}
	}

	@Override
	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName = fullName;
	}

	@Override
	public int compareTo(User user) {
		if (this.equals(user)) {
			return 0;
		}

		return DEFAULT_STRING_COLLATOR.compare(this.getUserName(), user.getUserName());
	}

}


text:
bool movePiece(Chess alpha, string userIn1, string userIn2)
{
    //Assigning piece values so that I can easily replace the state of the board
    alpha.ConvertInput(userIn1);
    alpha.piece1 = alpha.board[alpha.column][alpha.row];
    alpha.ConvertInput(userIn2);
    alpha.piece2 = alpha.board[alpha.column][alpha.row];

    //Check for trivial case of player selecting an empty slot
    if (alpha.piece1 == 0)
    {cout << "No piece selected.\n"; return false;}

    //Start with all possible selections for top player
    if(alpha.piece1 == 1 || alpha.piece1 == -1)
    {
        //Check if move is possible
        alpha.PawnScan(alpha.player, userIn1);
        if(alpha.moves[alpha.column][alpha.row] == 1)
        {return true;}

        //Else ask user to input again.
        else
        {cout << "Not a valid move.\n"; return false;}
    }

    if(alpha.piece1 == 2 || alpha.piece1 == -2)
    {
        //Check if move is possible
        alpha.BishopScan(alpha.player, userIn1);
        if(alpha.moves[alpha.column][alpha.row] == 1)
        {return true;}

        //Else ask user to input again.
        else
        {cout << "Not a valid move.\n"; return false;}
    }

    if(alpha.piece1 == 3 || alpha.piece1 == -3)
    {
        //Check if move is possible
        alpha.KnightScan(alpha.player, userIn1);
        if(alpha.moves[alpha.column][alpha.row] == 1)
        {return true;}

        //Else ask user to input again.
        else
        {cout << "Not a valid move.\n"; return false;}
    }

    if(alpha.piece1 == 4 || alpha.piece1 == -4)
    {
        //Check if move is possible
        alpha.RookScan(alpha.player, userIn1);
        if(alpha.moves[alpha.column][alpha.row] == 1)
        {return true;}

        //Else ask user to input again.
        else
        {cout << "Not a valid move.\n"; return false;}
    }

    if(alpha.piece1 == 5 || alpha.piece1 == -5)
    {
        //Check if move is possible, Queen = Bishop + Rook
        alpha.RookScan(alpha.player, userIn1);
        alpha.BishopScan(alpha.player, userIn1);

        if(alpha.moves[alpha.column][alpha.row] == 1)
        {return true;}

        //Else ask user to input again.
        else
        {cout << "Not a valid move.\n"; return false;}
    }

    if(alpha.piece1 == 7 || alpha.piece1 == -7)
    {
        //Check if move is possible, Queen = Bishop + Rook
        alpha.KingScan(alpha.player, userIn1);
        if(alpha.moves[alpha.column][alpha.row] == 1)
        {return true;}

        //Else ask user to input again.
        else
        {cout << "Not a valid move.\n"; return false;}
    }

}


text:
package net.will_co21.application.googleAPIImageSearch;

import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.BiFunction;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;

public class HttpDownloadDelegate implements BiFunction<String, ILogger, Optional<HttpURLConnection>> {
	protected static final boolean[] ofContinue = new boolean[600];
	protected static final int redirectMax = 3;
	static {
		Arrays.fill(ofContinue, false);
		ofContinue[HttpURLConnection.HTTP_MOVED_PERM] = true;
		ofContinue[HttpURLConnection.HTTP_MOVED_TEMP] = true;
		ofContinue[HttpURLConnection.HTTP_SEE_OTHER] = true;
	}

	@Override
	public Optional<HttpURLConnection> apply(String strUrl, ILogger logger) {
		try {
			int httpStatus = 0;
			int redirectCount = 0;

			URL url = new URL(strUrl);

			do {
				HttpURLConnection connection = null;

				if(url.getProtocol().equals("https"))
				{
					SSLContext sslContext = SSLContext.getInstance("SSL");
					sslContext.init(null, new X509TrustManager[] {
						new LooseTrustManager()
					}, new SecureRandom());
					connection = (HttpURLConnection)url.openConnection();
					((HttpsURLConnection)connection).setSSLSocketFactory(sslContext.getSocketFactory());
				}
				else
				{
					connection = (HttpURLConnection)url.openConnection();
				}

				connection.setConnectTimeout(3000);
				connection.setRequestMethod("GET");
				connection.connect();

				httpStatus = connection.getResponseCode();

				if(redirectCount < redirectMax && httpStatus > 0 && httpStatus < 600 && ofContinue[httpStatus])
				{
					redirectCount++;
					String redirectUrl = connection.getHeaderField("Location");

					if(redirectUrl == null) return Optional.of(connection);
					else url = new URL(redirectUrl);
				}
				else
				{
					return Optional.of(connection);
				}
			} while(httpStatus > 0 && httpStatus < 600 && ofContinue[httpStatus]);
			return Optional.empty();
		} catch (Exception e) {
			logger.write(e);
			return Optional.empty();
		} catch (Error e) {
			logger.write(e);
			return Optional.empty();
		} catch (Throwable e) {
			logger.write(e);
			return Optional.empty();
		}
	}
}


text:
layout: link
type: link
link: https://medium.com/thrive-global/does-taking-pictures-on-our-smartphones-have-any-effect-on-our-memory-1a9ee03adbf8
title: "Does Taking Pictures on Our Smartphones Have Any Effect on Our Memory?"
category: links
tags:
    - psychology
    - addiction
    - smartphone
    - memories
    - "daily found"

published: true
---

> "When you take a photo of something, you're counting on the camera to remember for you," Prof. Henkel says. "You're basically saying, 'Okay, I don't need to think about this any further. The camera's captured the experience.' You don't engage in any of the elaborative or emotional kinds of processing that really would help you remember those experiences, because you've outsourced it to your camera."

and it goes

> This is called the *[photo taking impairment effect](http://journals.sagepub.com/doi/abs/10.1177/0956797613504438)*, where my camera functions as a dropbox for my brain.

This, indeed hit us hard, be mindful, remember where we stand, enjoy the moment. and i have to admit, sometimes i don't remember exactly the experience, i just knew that i was there, but the be present when i was there is kinda hard, and it worst with smartphone in your pocket. to admire, to appriciate what's in front of you, we need to do that and let our brain capture all of that experieces.


text:
package se.unlogic.standardutils.dao;

import se.unlogic.standardutils.populators.QueryParameterPopulator;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class SimpleColumn<BeanType,ColumnType> implements Column<BeanType,ColumnType> {

	private final Field beanField;
	private final Method queryMethod;
	private final QueryParameterPopulator<?> queryParameterPopulator;
	private final String columnName;
	private final boolean autoGenerated;

	public SimpleColumn(Field beanField, Method queryMethod, QueryParameterPopulator<?> queryPopulator, String columnName, boolean autoGenerated) {
		super();
		this.beanField = beanField;
		this.queryMethod = queryMethod;
		this.columnName = columnName;
		this.autoGenerated = autoGenerated;
		this.queryParameterPopulator = queryPopulator;
	}

	@SuppressWarnings("unchecked")
	public ColumnType getParamValue(Object paramValue) {

		return (ColumnType) paramValue;
	}

	@SuppressWarnings("unchecked")
	public ColumnType getBeanValue(BeanType bean) {

		try {
			return (ColumnType) beanField.get(bean);

		} catch (IllegalArgumentException e) {

			throw new RuntimeException(e);

		} catch (IllegalAccessException e) {

			throw new RuntimeException(e);
		}
	}

	public Field getBeanField(){

		return beanField;
	}

	public Class<?> getParamType(){

		return beanField.getType();
	}

	public Method getQueryMethod() {
		return queryMethod;
	}

	public String getColumnName() {
		return columnName;
	}

	public boolean isAutoGenerated() {
		return autoGenerated;
	}

	public QueryParameterPopulator<?> getQueryParameterPopulator() {
		return queryParameterPopulator;
	}

	public static <BT,CT> SimpleColumn<BT,CT> getGenericInstance(Class<BT> beanClass, Class<CT> fieldClass, Field beanField, Method queryMethod, QueryParameterPopulator<?> queryPopulator, String columnName, boolean autoGenerated) {

		return new SimpleColumn<BT, CT>(beanField, queryMethod, queryPopulator, columnName, autoGenerated);
	}
}


text:
var
	kind = require('enyo/kind'),
	utils = require('enyo/utils');

var
	FittableLayout = require('layout/FittableLayout'),
	FittableRows = require('layout/FittableRows'),
	Slideable = require('layout/Slideable'),
	FittableColumnsLayout = FittableLayout.Columns,
	FittableRowsLayout = FittableLayout.Rows,
	Control = require('enyo/Control');

var SlideableInfo = kind({
	kind: Control,
	published: {
		info: null
	},
	components: [
		{kind: FittableRows, classes: 'slideableinfo-sample', components: [
			{name: 'name'},
			{name: 'axis'},
			{name: 'unit'},
			{name: 'min'},
			{name: 'max'},
			{name: 'value'}
		]}
	],
	handlers: {
		onUpdateInfo: 'updateInfo'
	},
	create: kind.inherit(function (sup) {
		return function () {
			sup.apply(this, arguments);
			this.infoChanged();
		};
	}),
	infoChanged: function () {
		for (var p in this.info) {
			if (this.$[p]) {
				this.$[p].setContent(utils.cap(p) + ': ' + this.info[p]);
			}
		}
	},
	updateInfo: function (sender, ev) {
		this.setInfo(ev);
		return true;
	}
});

module.exports = kind({
	name: 'enyo.sample.SlideableSample',
	classes: 'enyo-unselectable enyo-fit',
	style: 'overflow: hidden; background-color: #000;',
	components: [
		{name: 'top', kind: Slideable, axis: 'v', unit: '%', min: -90, max: 0, classes: 'enyo-fit slideable-sample top', onChange: 'updateInfo'},
		{name: 'right', kind: Slideable, axis: 'h', unit: '%', min: 0, max: 90, classes: 'enyo-fit slideable-sample right', onChange: 'updateInfo'},
		{name: 'bottom', kind: Slideable, axis: 'v', unit: '%', min: 0, max: 90, classes: 'enyo-fit slideable-sample bottom', onChange: 'updateInfo'},
		{name: 'left', kind: Slideable, axis: 'h', unit: '%', min: -90, max: 0, classes: 'enyo-fit slideable-sample left', onChange: 'updateInfo'}
	],
	handlers: {
		ondragstart: 'suppressPanelDrag'
	},
	create: kind.inherit(function (sup) {
		return function () {
			sup.apply(this, arguments);
			var slideables = [];

			for (var c in this.$) {
				if (this.$[c].kind === 'Slideable') {
					slideables.push(this.$[c]);
				}
			}
			this.populate(slideables);
		};
	}),
	populate: function (slideables) {
		var slideable;
		for (var i = 0; i < slideables.length; i++) {
			slideable = slideables[i];
			slideable.createComponents([
				{style: slideable.axis === 'h' ? 'height: 38%;' : ''}, // cheating here for the horizontal Slideables to make everything nice and (almost) centered vertically
				{
					kind: SlideableInfo,
					layoutKind: (slideable.axis === 'v') ? FittableColumnsLayout : FittableRowsLayout,
					classes: 'enyo-center', // cheating here for the vertical Slideables to make everything nice and centered horizontally (no effect on horizontal Slideables)
					info: {
						name: slideable.name,
						axis: slideable.axis,
						unit: slideable.unit,
						min: slideable.min,
						max: slideable.max,
						value: slideable.value
					}
				}
			]);
		}
	},
	updateInfo: function (sender) {
		sender.waterfallDown('onUpdateInfo', {
			name: sender.name,
			axis: sender.axis,
			unit: sender.unit,
			min: sender.min,
			max: sender.max,
			value: Math.round(sender.value)
		});
		return true;
	},
	// keeps the view panel from moving in Sampler app while dragging the Slideable
	suppressPanelDrag: function () {
		return true;
	}
});


text:
using System;
using InRule.Repository;

namespace UndoExtension
{
    public class UndoHistoryItem
    {
        public Guid ParentGuid { get; set; }
        public int OriginalIndex { get; set; }
        public RuleRepositoryDefBase DefToUndo { get; set; }
        public Action<UndoHistoryItem> UndoAction { get; set; }
    }
}


text: Common Test functionality for all `fuel` modules.


text:
Article 1477
----
Celui des époux qui aurait détourné ou recelé quelques effets de la communauté
est privé de sa portion dans lesdits effets.

De même, celui qui aurait dissimulé sciemment l'existence d'une dette commune
doit l'assumer définitivement.


text:
import string
import natlink
from natlinkutils import *

class ThisGrammar(GrammarBase):

    gramSpec = """
        <dgndictation> imported;
        <dgnletters> imported;
        <ruleOne> exported = demo sample eight <dgndictation> [ stop ];
        <ruleTwo> exported = demo sample eight spell <dgnletters> [ stop ];
    """

    def gotResults_dgndictation(self,words,fullResults):
        words.reverse()
        text = string.join(words)
        natlink.playString(' ' + text)

    def gotResults_dgnletters(self,words,fullResults):
        words = map(lambda x: x[:1], words)
        text = string.join(words, '')
        natlink.playString(' ' + text)

    def initialize(self):
        self.load(self.gramSpec)
        self.activateAll()

thisGrammar = ThisGrammar()
thisGrammar.initialize()

def unload():
    global thisGrammar
    if thisGrammar: thisGrammar.unload()
    thisGrammar = None


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using PSDocs.Definitions;
using PSDocs.Pipeline;
using PSDocs.Resources;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Threading;

namespace PSDocs.Runtime
{
    internal sealed class LanguageAst : AstVisitor
    {
        private const string PARAMETER_NAME = "Name";
        private const string PARAMETER_BODY = "Body";
        private const string PARAMETER_ERRORACTION = "ErrorAction";
        private const string PARAMETER_WITH = "With";
        private const string DOCUMENT_KEYWORD = "Document";
        private const string ERRORID_PARAMETERNOTFOUND = "PSDocs.Parse.DefinitionParameterNotFound";
        private const string ERRORID_INVALIDDOCUMENTNESTING = "PSDocs.Parse.InvalidDocumentNesting";
        private const string ERRORID_INVALIDERRORACTION = "PSDocs.Parse.InvalidErrorAction";
        private const string ERRORID_SELECTORNOTFOUND = "PSDocs.Parse.SelectorNotFound";

        private readonly PipelineContext _Context;
        private readonly StringComparer _Comparer;

        internal List<ErrorRecord> Errors;

        internal LanguageAst(Pipeline.PipelineContext context)
        {
            _Context = context;
            _Comparer = StringComparer.OrdinalIgnoreCase;
        }

        private sealed class ParameterBindResult
        {
            public ParameterBindResult()
            {
                Bound = new Dictionary<string, CommandElementAst>(StringComparer.OrdinalIgnoreCase);
                Unbound = new List<CommandElementAst>();
                _Offset = 0;
            }

            public Dictionary<string, CommandElementAst> Bound;
            public List<CommandElementAst> Unbound;

            private int _Offset;

            public bool Has<TAst>(string parameterName, out TAst parameterValue) where TAst : CommandElementAst
            {
                var result = Bound.TryGetValue(parameterName, out CommandElementAst value) && value is TAst;
                parameterValue = result ? value as TAst : null;
                return result;
            }

            public bool Has<TAst>(string parameterName, int position, out TAst value) where TAst : CommandElementAst
            {
                // Try bound
                if (Has<TAst>(parameterName, out value))
                {
                    _Offset++;
                    return true;
                }
                int relative = position - _Offset;
                var result = Unbound.Count > relative && Unbound[relative] is TAst;
                value = result ? Unbound[relative] as TAst : null;
                return result;
            }
        }

        public override AstVisitAction VisitCommand(CommandAst commandAst)
        {
            if (IsDefinition(commandAst))
            {
                var valid = NotNested(commandAst) &&
                    HasValidErrorAction(commandAst) &&
                    HasRequiredParameters(commandAst) &&
                    HasValidSelector(commandAst);

                return valid ? base.VisitCommand(commandAst) : AstVisitAction.SkipChildren;
            }
            return base.VisitCommand(commandAst);
        }

        /// <summary>
        /// Determines if the definition has a Body parameter.
        /// </summary>
        private bool HasBodyParameter(CommandAst commandAst, ParameterBindResult bindResult)
        {
            if (bindResult.Has(PARAMETER_BODY, 1, out ScriptBlockExpressionAst _))
                return true;

            ReportError(ERRORID_PARAMETERNOTFOUND, PSDocsResources.DefinitionParameterNotFound, PARAMETER_BODY, ReportExtent(commandAst.Extent));
            return false;
        }

        /// <summary>
        /// Determines if the definition has a Name parameter.
        /// </summary>
        private bool HasNameParameter(CommandAst commandAst, ParameterBindResult bindResult)
        {
            if (bindResult.Has(PARAMETER_NAME, 0, out StringConstantExpressionAst value) && !string.IsNullOrEmpty(value.Value))
                return true;

            ReportError(ERRORID_PARAMETERNOTFOUND, PSDocsResources.DefinitionParameterNotFound, PARAMETER_NAME, ReportExtent(commandAst.Extent));
            return false;
        }

        /// <summary>
        /// Determines if the definition is nested in another definition.
        /// </summary>
        private bool NotNested(CommandAst commandAst)
        {
            if (GetParentBlock(commandAst)?.Parent == null)
                return true;

            ReportError(ERRORID_INVALIDDOCUMENTNESTING, PSDocsResources.InvalidDocumentNesting, ReportExtent(commandAst.Extent));
            return false;
        }

        /// <summary>
        /// Determines if the definition has required parameters.
        /// </summary>
        private bool HasRequiredParameters(CommandAst commandAst)
        {
            var bindResult = BindParameters(commandAst);
            return HasNameParameter(commandAst, bindResult) && HasBodyParameter(commandAst, bindResult);
        }

        /// <summary>
        /// Determine if the definition has allowed ErrorAction options.
        /// </summary>
        private bool HasValidErrorAction(CommandAst commandAst)
        {
            var bindResult = BindParameters(commandAst);
            if (!bindResult.Has(PARAMETER_ERRORACTION, 0, out StringConstantExpressionAst value))
                return true;

            if (!Enum.TryParse(value.Value, out ActionPreference result) || (result == ActionPreference.Ignore || result == ActionPreference.Stop))
                return true;

            ReportError(ERRORID_INVALIDERRORACTION, PSDocsResources.InvalidErrorAction, value.Value, ReportExtent(commandAst.Extent));
            return false;
        }

        private bool HasValidSelector(CommandAst commandAst)
        {
            var bindResult = BindParameters(commandAst);
            if (!bindResult.Has(PARAMETER_WITH, out StringConstantExpressionAst value))
                return true;

            var selectorId = ResourceHelper.GetId(RunspaceContext.CurrentThread.Source.File.ModuleName, value.Value);
            if (_Context.Selector.ContainsKey(selectorId))
                return true;

            ReportError(ERRORID_SELECTORNOTFOUND, PSDocsResources.SelectorNotFound, value.Value, ReportExtent(commandAst.Extent));
            return false;
        }

        /// <summary>
        /// Determines if the command is a document definition.
        /// </summary>
        private bool IsDefinition(CommandAst commandAst)
        {
            return _Comparer.Equals(commandAst.GetCommandName(), DOCUMENT_KEYWORD);
        }

        private static ParameterBindResult BindParameters(CommandAst commandAst)
        {
            var result = new ParameterBindResult();
            int i = 1;
            int next = 2;
            for (; i < commandAst.CommandElements.Count; i++, next++)
            {
                // Is named parameter
                if (commandAst.CommandElements[i] is CommandParameterAst parameter && next < commandAst.CommandElements.Count)
                {
                    result.Bound.Add(parameter.ParameterName, commandAst.CommandElements[next]);
                    i++;
                    next++;
                }
                else
                {
                    result.Unbound.Add(commandAst.CommandElements[i]);
                }
            }
            return result;
        }

        private void ReportError(string errorId, string message, params object[] args)
        {
            ReportError(new global::PSDocs.Pipeline.ParseException(
                message: string.Format(Thread.CurrentThread.CurrentCulture, message, args),
                errorId: errorId
            ));
        }

        private void ReportError(global::PSDocs.Pipeline.ParseException exception)
        {
            if (Errors == null)
            {
                Errors = new List<ErrorRecord>();
            }

            Errors.Add(new ErrorRecord(
                exception: exception,
                errorId: exception.ErrorId,
                errorCategory: ErrorCategory.InvalidOperation,
                targetObject: null
            ));
        }

        private static string ReportExtent(IScriptExtent extent)
        {
            return string.Concat(extent.File, " line ", extent.StartLineNumber);
        }

        private static ScriptBlockAst GetParentBlock(Ast ast)
        {
            var block = ast;
            while (block != null && !(block is ScriptBlockAst))
                block = block.Parent;

            return (ScriptBlockAst)block;
        }
    }
}


text:
/*
 * cromossomo.c
 *
 *  Created on: 06/05/2015
 *      Author: vitor
 */

#include "cromossomo.h"

cromossomo cromossomo_aleatorio(genetic_params params) {
	cromossomo resultado;
	resultado.fitness = 0;
	const int num_pinos = params.num_in + params.r * params.c;

	// Define cada LE.
	int i, j;
	for (i = 0; i < params.r; i++) {
		for (j = 0; j < params.c; j++) {
			const int current = i * params.c + j;
			resultado.logic_elements[current].function = _random_()
					% params.num_funcs;
			int k;
			for (k = 0; k <= params.le_num_in; k++) {
				const int num_pinos_ff = params.num_in + j * params.r;
				if (params.feed_forward) {
					resultado.logic_elements[current].inputs[k] = _random_()
							% num_pinos_ff;
				} else {
					resultado.logic_elements[current].inputs[k] = _random_()
							% num_pinos;
				}
			}
		}
	}

	// Define os outputs
	for (i = 0; i < params.num_out; i++) {
		resultado.outs[i] = _random_() % num_pinos;
	}

	return resultado;
}

void fitness(genetic_params params, cromossomo* individuo) {
	// Carrega o individuo no circuito
	// Amostra a saida
	// Faz a analise
	// Grava no individuo
}

// Cubra os olhos antes de entrar aqui.
cromossomo mutacao(genetic_params params, const cromossomo* a_mutar) {
	cromossomo resultado = *a_mutar;
	const int total_campos = params.r * params.c + params.num_out;
	const int total_pinos = params.r * params.c + params.num_in;

	int i, j;
	int campo_selecionado = _random_() % total_campos;
	int contador = 0;

	resultado.fitness = 0;
	for (i = 0; i < params.r; i++) {
		for (j = 0; j < params.c; j++) {
			const int current = i * params.c + j;
			if (contador == campo_selecionado) {
				int qual_campo = _random_() % (params.le_num_in + 1);
				if (qual_campo == 0) {
					resultado.logic_elements[current].function = _random_()
							% params.num_funcs;
				} else {
					qual_campo--;
					if (params.feed_forward) {
						const int num_pinos_ff = params.num_in + j * params.r;
						resultado.logic_elements[current].inputs[qual_campo] =
								_random_() % num_pinos_ff;
					} else {
						resultado.logic_elements[current].inputs[qual_campo] =
								_random_() % total_pinos;
					}
					return resultado;
				}
			}
			contador++;
		}
	}

	for (i = 0; i < params.num_out; i++) {
		if (contador == campo_selecionado) {
			resultado.outs[i] = _random_() % total_pinos;
			return resultado;
		}
		contador++;
	}

	// Nao deve chegar aqui.
	return resultado;
}


text:
module VagrantPlugins
  module Abiquo
    class Config < Vagrant.plugin('2', :config)
      attr_accessor :abiquo_api_user
      attr_accessor :abiquo_api_password
      attr_accessor :abiquo_api_uri
      attr_accessor :virtualdatacenter
      attr_accessor :virtualappliance
      attr_accessor :label
      attr_accessor :exposed_nic
      attr_accessor :template
      attr_accessor :setup

      alias_method :setup?, :setup

      def initialize
        @abiquo_api_user        = UNSET_VALUE
        @abiquo_api_password    = UNSET_VALUE
        @virtualdatacenter      = UNSET_VALUE
        @virtualappliance       = UNSET_VALUE
        @label                  = UNSET_VALUE
        @template               = UNSET_VALUE
        @setup                  = UNSET_VALUE
      end

      def finalize!
        @abiquo_api_user        = ENV['ABIQUO_API_USER'] if @abiquo_api_user == UNSET_VALUE
        @abiquo_api_password    = ENV['ABIQUO_API_PASSWORD'] if @abiquo_api_password == UNSET_VALUE
        @abiquo_api_uri         = ENV['ABIQUO_API_URI'] if @abiquo_api_uri == UNSET_VALUE
        @virtualdatacenter      = 'VagrantVDC' if @virtualdatacenter == UNSET_VALUE
        @virtualappliance       = 'VagrantVAPP' if @virtualappliance == UNSET_VALUE
        @label                  = 'VagrantVM' if @label == UNSET_VALUE
        @template               = 'TemplateImage' if @template == UNSET_VALUE
        @setup                  = true if @setup == UNSET_VALUE
      end

      def validate(machine)
        errors = []
        errors << I18n.t('vagrant_abiquo.config.abiquo_api_user') if !@abiquo_api_user
        errors << I18n.t('vagrant_abiquo.config.abiquo_api_password') if !@abiquo_api_password
        errors << I18n.t('vagrant_abiquo.config.abiquo_api_uri') if !@abiquo_api_uri
        errors << I18n.t('vagrant_abiquo.config.virtualdatacenter') if !@virtualdatacenter
        errors << I18n.t('vagrant_abiquo.config.template') if !@template

        { 'Abiquo Provider' => errors }
      end
    end
  end
end


text:
package cn.cerc.mis.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class StringList {
    private List<String> items = new ArrayList<>();
    private String message;

    public String getMessage() {
        return message;
    }

    public List<String> getItems() {
        return items;
    }

    // 按照行读取文件内容
    public boolean loadFromFile(String fileName) {
        items.clear();

        File f = new File(fileName);
        if (!f.exists()) {
            this.message = "file not exists";
            return false;
        }
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(f), StandardCharsets.UTF_8));
            try {
                String line;
                while ((line = br.readLine()) != null) {
                    items.add(line);
                }
            } finally {
                br.close();
            }
            return true;
        } catch (Exception e) {
            this.message = e.getMessage();
            e.printStackTrace();
            return false;
        }
    }

    public boolean saveToFile(String fileName) {
        File file = new File(fileName);
        try {
            file.createNewFile();
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            for (String line : items) {
                writer.write(line);
                writer.write(System.lineSeparator());
            }
            writer.close();
            return true;
        } catch (IOException e) {
            this.message = e.getMessage();
            e.printStackTrace();
            return false;
        }
    }

    public void add(String line) {
        items.add(line);
    }
}


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use AppBundle\Form\ActivityTagAddType;
use AppBundle\Form\ActivityTagDeleteType;
use AppBundle\Entity\Activity;

/**
 * Filter controller.
 *
 * @Route("/activity")
 */
class ActivityController extends Controller
{
    /**
     * @Route("/list", name="activity_list")
     */
    public function listAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $am = $this->get('app.manager.activity');
        $repo = $em->getRepository('AppBundle:Activity');

        $nbDays = $request->get('nbDays');
        $dateFrom = new \DateTime($request->get('dateFrom'));
        $dateTo = new \DateTime($request->get('dateTo'));
        if($request->get('dateFromQuery')) {
            $dateFromQuery = new \DateTime($request->get('dateFromQuery'));
        } else {
            $dateFromQuery = clone $dateFrom;
        }
        $query = $request->get('q');

        $activities = $repo->findByDatesIntervalByDays($dateFromQuery, $dateTo, $query, $nbDays);
        $activitiesByDates = $am->createView($activities);

        $dateNext = null;
        if(count($activitiesByDates) > 0) {
            end($activitiesByDates);
            $dateNext = new \DateTime(key($activitiesByDates));
            $dateNext->modify("-1 day");
            $dateNext = $dateNext->format('Y-m-d');
        }

        return $this->render('Activity/list.html.twig',
            array(
                'activitiesByDates' => $am->createView($activities),
                'dateNext' => $dateNext,
                'query' => $query,
                'dateTo' => $dateTo->format('Y-m-d'),
                'dateFrom' => $dateFrom->format('Y-m-d'),
                'nbDays' => $nbDays,
            )
        );
    }

    /**
     * @Route("/view/{id}", name="activity_view")
     * @ParamConverter("activity", class="AppBundle:Activity")
     */
    public function viewAction(Request $request, Activity $activity)
    {
        return $this->render('Activity/view.html.twig', array('activity' => $activity, 'query' => $request->get('query', null), 'dateTo' => $request->get('dateTo', null), 'dateFrom' => $request->get('dateFrom', null), 'nbDays' => $request->get('nbDays', null)));
    }

    /**
     * @Route("/tag_add", name="activity_tag_add")
     * @Method("POST")
     */
    public function tagAddAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $form = $this->createForm(ActivityTagAddType::class, array('method' => 'POST'));

        $form->handleRequest($request);

        if (!$form->isValid()) {
            return new Response();
        }

        $data = $form->getData();

        $activity = $em->getRepository('AppBundle:Activity')->find($data['activity_id']);
        $tag = $em->getRepository('AppBundle:Tag')->find($data['tag_id']);

        $activity->addTag($tag);
        $em->flush();

        return new Response();
    }

    /**
     * @Route("/tag_delete", name="activity_tag_delete")
     * @Method("POST")
     */
    public function tagDeleteAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $form = $this->createForm(ActivityTagDeleteType::class);

        $form->handleRequest($request);

        if (!$form->isValid()) {

            return new Response();
        }

        $data = $form->getData();

        $activity = $em->getRepository('AppBundle:Activity')->find($data['activity_id']);
        $tag = $em->getRepository('AppBundle:Tag')->find($data['tag_id']);

        $activity->removeTag($tag);
        $em->flush();

        return new Response();
    }
}


text:
python setup.py clean
python setup.py sdist
twine upload dist/*
python setup.py clean


text:
var exec = require("child_process").exec;
var querystring = require("querystring");
var fs = require("fs");
var url = require("url");

function start(request, response, pool) {
	console.log("Request handler 'start' was called.");
	response.writeHead(200, {
		"Content-Type" : "text/plain"
	});
	var method = request.method;
	var pathname = url.parse(request.url).pathname;
	pool.getConnection(function(err, conn) {
		if (err) {
			console.error('error connecting: ' + err.stack);
			return;
		}
		// Use the connection
		conn.query('SELECT bug_id FROM cert_records', function(err, rows) {

			for(var i = 0; i < rows.length; i++){
				console.log(rows[i]);
			}
			// And done with the connection.
			conn.release();
			// Don't use the connection here, it has been returned to the pool.
		});
	});
	if (method === "POST") {
		var postData = '';
		request.setEncoding("utf8");
		request.on("data", function(dataChunk) {
			postData += dataChunk;
		});
		request.on("end", function() {
			postData = querystring.parse(postData);
		});
		response.write("You've sent: " + method + " request for "
				+ querystring.parse(postData).text);
	} else {
		response.write("You've sent: " + method + " request for " + pathname);
	}
	response.end();
}

exports.start = start;


text:
package goryachev.common.io;
import goryachev.common.util.CKit;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.Charset;

public class CReader
	extends BufferedReader
{
	public CReader(File f, Charset cs) throws Exception
	{
		this(new FileInputStream(f), cs);
	}

	public CReader(String filename, Charset cs) throws Exception
	{
		this(new FileInputStream(filename), cs);
	}

	public CReader(InputStream in, Charset cs) throws Exception
	{
		super(new InputStreamReader(in, (cs == null ? CKit.CHARSET_UTF8 : cs)));
	}

	public CReader(File f) throws Exception
	{
		this(f, CKit.CHARSET_UTF8);
	}

	public CReader(String text)
	{
		super(text == null ? new StringReader("") : new StringReader(text));
	}

	public CReader(InputStream in) throws Exception
	{
		this(in, CKit.CHARSET_UTF8);
	}

	public CReader(byte[] b) throws Exception
	{
		this(new ByteArrayInputStream(b));
	}

	public CReader(Reader rd)
	{
		super(rd);
	}
}


text:
A repository containing example uses of tmhOAuth.

## Dependencies

These examples require [tmhOAuth](https://github.com/themattharris/tmhOAuth) version 0.8.0 or higher. They have been
tested with PHP 5.3+.

The easiest way to install tmhOAuth is to use [composer](http://getcomposer.org). if you prefer to do things the manual way
make sure you `git clone` tmhOAuth into the main tmhOAuthExamples directory (the same one this file is in).

## Usage

Edit `tmhOAuthExample.php` and enter your application and user values for:
- 'consumer_key'
- 'consumer_secret'
- 'user_token'
- 'user_secret'
- 'bearer'

If you're just trying things out it's recommended you use a test account instead of your real one as some examples do things
like tweet or follow.

To create an application, visit [dev.twitter.com/apps](https://dev.twitter.com/apps)

For command line examples, go into the `cli` directory and execute any of the examples using `php <filename>.php`. Remember
some examples make POST actions, and will tweet or follow on your behalf.

For web based examples add tmhOAuthExamples to a location on your webserver that you access via a URL.

## Change History
### 0.1 - 14 June 2013
- switched all examples to Twitter API v1.1
- removed redundant/confusing examples
- centralised examples as children of a master example configuration script (`tmhOAuthExample.php`)

## Community

License: Apache 2 (see [included LICENSE file](https://github.com/themattharris/tmhOAuth/blob/master/LICENSE))

Follow [@tmhOAuth](https://twitter.com/intent/follow?screen_name=tmhOAuth) to receive updates on releases, or ask for support
Follow me on Twitter: [@themattharris](https://twitter.com/intent/follow?screen_name=themattharris)
Check out the Twitter Developer Resources: <https://dev.twitter.com>

## To Do

- More streaming api examples
- Control Streams examples
- More Web request examples


text:
(function () {
  'use strict';

  var voicebaseTokensApi = function($http, $q, voicebaseUrl) {
    var baseUrl = voicebaseUrl.getBaseUrl();

    var tokens = null;
    var currentToken = null;
    var needRemember = localStorage.getItem('needRemember') || false;

    var setCurrentToken = function(_currentToken){
        currentToken = _currentToken;
    };

    var getCurrentToken = function(){
        return currentToken;
    };

    var isInLegacyHybridMode = function(){
        // currentToken does not contain a "." => isInLegacyHybridMode
        return ( !! currentToken ) &&
          ( !! currentToken.token ) &&
          ( 0 > currentToken.token.indexOf('.') );
    };

    var isSignedIn = function(){
      return !! currentToken;
    };

    var getTokens = function(credentials) {
      var deferred = $q.defer();

      var username = credentials.username;
      var password = credentials.password;

      jQuery.ajax({
        url: baseUrl + '/access/users/+' + username.toLowerCase() + '/tokens',
        type: 'GET',
        dataType: 'json',
        headers: {
          'Authorization': 'Basic ' + btoa(username + ':' + password)
        },
        success: function(_tokens) {
          if(!_tokens.tokens.length) {
            deferred.reject('There are no tokens!');
          }
          else {
            setTokensObj(_tokens);
            deferred.resolve(_tokens);
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown + ': Error ' + jqXHR.status);
          deferred.reject('Something goes wrong!');
        }
      });

      return deferred.promise;
    };

    var getToken = function(credentials) {
      var deferred = $q.defer();

      var username = credentials.username;
      var password = credentials.password;

      jQuery.ajax({
        url: baseUrl,
        type: 'GET',
        dataType: 'json',
        data: {
          apikey: username,
          password: password
        },
        success: function(_tokenData) {
          if(!_tokenData.success) {
            deferred.reject('Something goes wrong!');
          }
          else {
            var _tokens = {
              tokens: [{
                token: _tokenData.token
              }]
            };
            setTokensObj(_tokens);
            saveApiKey(username);
            deferred.resolve(_tokens);
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown + ': Error ' + jqXHR.status);
          deferred.reject('The API Key or Password you entered are incorrect. Please try again (make sure your caps lock is off).');
        }
      });

      return deferred.promise;
    };

    var saveApiKey = function (username) {
      if(needRemember && username) {
        localStorage.setItem('voicebaseApiKey', username);
      }
      else {
        localStorage.removeItem('voicebaseApiKey');
      }
    };

    var getApiKey = function () {
      return localStorage.getItem('voicebaseApiKey');
    };

    var setTokensObj = function(tokensObj) {
      var _tokensObj = (!tokensObj) ? null : tokensObj.tokens[0];
      setCurrentToken(_tokensObj);

      if(needRemember && _tokensObj && _tokensObj.token) {
        localStorage.setItem('voicebaseToken', _tokensObj.token);
      }
      else {
        localStorage.removeItem('voicebaseToken');
        saveApiKey(null);
      }

      tokens = tokensObj;
    };

    var setToken = function (_token) {
      setTokensObj({
        tokens: [{
          token: _token,
          type: 'Bearer'
        }]
      });
    };

    var getTokensObj = function() {
        return tokens;
    };

    var getTokenFromLocation = function() {
      var params = getParametersFromLocation();
      if(params.access_token) {
        setToken(params.access_token);
      }

      return getCurrentToken();
    };

    var getParametersFromLocation = function() {
      var urlSearch = location.search.substr(1);
      var params = urlSearch.split('&');
      var values = {};
      for (var i = 0; i < params.length; i++) {
        var param = params[i];
        if(param && param !== '') {
          var pair = param.split('=');
          values[pair[0]] = pair[1];
        }
      }
      return values;
    };

    var getTokenFromStorage = function() {
      var tokenFromStorage = localStorage.getItem('voicebaseToken');
      if(tokenFromStorage) {
        setToken(tokenFromStorage);
      }
      return tokenFromStorage;
    };

    var getNeedRemember = function() {
      return needRemember;
    };

    var setNeedRemember = function(value) {
      needRemember = value;
      if(needRemember) {
        localStorage.setItem('needRemember', needRemember);
      }
      else {
        localStorage.removeItem('needRemember');
      }
    };

    var tokenFromLocation = getTokenFromLocation();
    if(!tokenFromLocation) {
      getTokenFromStorage();
    }

    /* Key Manager*/
    var basicToken = null;

    var setBasicToken = function(_basicToken){
      basicToken = _basicToken;
    };

    var getBasicToken = function(){
      return basicToken;
    };

    var basicAuth = function (credentials) {
      var deferred = $q.defer();

      var username = credentials.username;
      var password = credentials.password;

      var token = 'Basic ' + btoa(username + ':' + password);

      jQuery.ajax({
        url: baseUrl + '/access/users/+' + username.toLowerCase() + '/tokens',
        type: 'GET',
        dataType: 'json',
        headers: {
          'Authorization': token
        },
        success: function(_tokens) {
          if(!_tokens.tokens.length) {
            deferred.reject('Can\'t authorize!');
          }
          else {
            setBasicToken(token);
            deferred.resolve();
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown + ': Error ' + jqXHR.status);
          deferred.reject('Something goes wrong!');
        }
      });

      return deferred.promise;
    };

    var getUsers = function() {
      var deferred = $q.defer();

      jQuery.ajax({
        url: baseUrl + '/access/users',
        type: 'GET',
        dataType: 'json',
        headers: {
          'Authorization': getBasicToken()
        },
        success: function(_users) {
          deferred.resolve(_users.users);
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown + ': Error ' + jqXHR.status);
          deferred.reject('Something goes wrong!');
        }
      });

      return deferred.promise;
    };

    var getUserTokens = function (userId) {
      var deferred = $q.defer();

      jQuery.ajax({
        url: baseUrl + '/access/users/+' + userId + '/tokens',
        type: 'GET',
        dataType: 'json',
        headers: {
          'Authorization': getBasicToken()
        },
        success: function(_tokens) {
          deferred.resolve(_tokens.tokens);
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown + ': Error ' + jqXHR.status);
          deferred.reject('Something goes wrong!');
        }
      });

      return deferred.promise;

    };

    var addUserToken = function (userId) {
      var deferred = $q.defer();

      var data = JSON.stringify({
        token: {}
      });

      jQuery.ajax({
        url: baseUrl + '/access/users/+' + userId + '/tokens',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        headers: {
          'Authorization': getBasicToken()
        },
        data: data,
        success: function(_token) {
          deferred.resolve({
            token: _token.token,
            type: _token.type
          });
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown + ': Error ' + jqXHR.status);
          deferred.reject('Something goes wrong!');
        }
      });

      return deferred.promise;

    };

    var deleteUserToken = function (userId, token) {
      var deferred = $q.defer();

      jQuery.ajax({
        url: baseUrl + '/access/users/+' + userId + '/tokens/' + token,
        type: 'DELETE',
        headers: {
          'Authorization': getBasicToken()
        },
        success: function() {
          deferred.resolve();
        },
        error: function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown + ': Error ' + jqXHR.status);
          deferred.reject('Something goes wrong!');
        }
      });

      return deferred.promise;

    };

    return {
      getTokens: getTokens,
      getToken: getToken,
      setTokensObj: setTokensObj,
      getTokensObj: getTokensObj,
      getCurrentToken: getCurrentToken,
      setCurrentToken: setCurrentToken,
      setToken: setToken,
      getTokenFromLocation: getTokenFromLocation,
      getNeedRemember: getNeedRemember,
      setNeedRemember: setNeedRemember,
      getTokenFromStorage: getTokenFromStorage,
      getBasicToken: getBasicToken,
      getApiKey: getApiKey,
      basicAuth: basicAuth,
      getUsers: getUsers,
      getUserTokens: getUserTokens,
      addUserToken: addUserToken,
      deleteUserToken: deleteUserToken,
      isInLegacyHybridMode: isInLegacyHybridMode,
      isSignedIn: isSignedIn
    };

  };

  angular.module('voicebaseTokensModule')
    .service('voicebaseTokensApi', voicebaseTokensApi);

})();


text:
ES5Harness.registerTest({
    id: "15.2.3.2-2-27",

    path: "TestCases/chapter15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-27.js",

    description: "Object.getPrototypeOf returns the [[Prototype]] of its parameter (Error object)",

    test: function testcase() {
        var obj = new Error();

        return Object.getPrototypeOf(obj) === Error.prototype;
    },

    precondition: function prereq() {
        return fnExists(Object.getPrototypeOf);
    }
});


text:
package org.apache.camel.component.atom;

import org.apache.camel.Endpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;

import static org.junit.jupiter.api.Assertions.assertThrows;

/**
 * Unit test for AtomProducer.
 */
@DisabledOnOs(OS.AIX)
public class AtomProducerTest extends CamelTestSupport {

    @Test
    void testNotYetImplemented() {
        Endpoint ep = context.getEndpoint("atom:file://target/out.atom");

        assertThrows(UnsupportedOperationException.class, () -> ep.createProducer());
    }

}


text:
<?php

namespace Coyote\Console\Commands;

use Coyote\Repositories\Contracts\NotificationRepositoryInterface;
use Illuminate\Console\Command;

class PurgeNotificationsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'notifications:purge';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Purge old notifications.';

    public function handle(NotificationRepositoryInterface $notification)
    {
        $affected = $notification->purge();

        $this->info("Done. Notifications removed: $affected.");
    }
}


text:
package org.ojai.beans.jackson;

import java.io.IOException;

import org.ojai.annotation.API;
import org.ojai.types.ODate;
import org.ojai.types.OInterval;
import org.ojai.types.OTime;
import org.ojai.types.OTimestamp;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.core.util.VersionUtil;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;

@API.Internal
public class JacksonHelper {
  public final static Version VERSION;

  public static final ObjectMapper MAPPER = new ObjectMapper();
  static {
    String version = JacksonHelper.class.getPackage().getImplementationVersion();
    String version_str = version == null ? "<unknown>" : version;
    VERSION = VersionUtil.parseVersion(version_str, "org.ojai", "core");

    SimpleModule module = new SimpleModule("OjaiSerializers", VERSION);
    ByteSerializer byteSerializer = new ByteSerializer();
    module.addSerializer(byte.class, byteSerializer);
    module.addSerializer(Byte.class, byteSerializer);

    module.addSerializer(OInterval.class, new IntervalSerializer());
    module.addDeserializer(OInterval.class, new IntervalDeserializer());

    module.addSerializer(ODate.class, new DateSerializer());
    module.addDeserializer(ODate.class, new DateDeserializer());

    module.addSerializer(OTime.class, new TimeSerializer());
    module.addDeserializer(OTime.class, new TimeDeserializer());

    module.addSerializer(OTimestamp.class, new TimestampSerializer());
    module.addDeserializer(OTimestamp.class, new TimestampDeserializer());

    MAPPER.registerModule(module);
  }

  public static class ByteSerializer extends JsonSerializer<Byte> {
    @Override
    public void serialize(Byte value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
      jgen.writeObject(value);
    }
  }

  public static class IntervalSerializer extends JsonSerializer<OInterval> {
    @Override
    public void serialize(OInterval value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
      jgen.writeObject(value);
    }
  }

  public static class IntervalDeserializer extends JsonDeserializer<OInterval> {
    @Override
    public OInterval deserialize(JsonParser p, DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
      return (OInterval) p.getEmbeddedObject();
    }
  }

  public static class DateSerializer extends JsonSerializer<ODate> {
    @Override
    public void serialize(ODate value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
      jgen.writeObject(value);
    }
  }

  public static class DateDeserializer extends JsonDeserializer<ODate> {
    @Override
    public ODate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
      return (ODate) p.getEmbeddedObject();
    }
  }

  public static class TimeSerializer extends JsonSerializer<OTime> {
    @Override
    public void serialize(OTime value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
      jgen.writeObject(value);
    }
  }

  public static class TimeDeserializer extends JsonDeserializer<OTime> {
    @Override
    public OTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
      return (OTime) p.getEmbeddedObject();
    }
  }

  public static class TimestampSerializer extends JsonSerializer<OTimestamp> {
    @Override
    public void serialize(OTimestamp value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
      jgen.writeObject(value);
    }
  }

  public static class TimestampDeserializer extends JsonDeserializer<OTimestamp> {
    @Override
    public OTimestamp deserialize(JsonParser p, DeserializationContext ctxt) throws IOException,
        JsonProcessingException {
      return (OTimestamp) p.getEmbeddedObject();
    }
  }

}


text:
namespace infobars {
class InfoBar;
}  // namespace infobars

namespace banners {

AppBannerDataFetcherDesktop::AppBannerDataFetcherDesktop(
    content::WebContents* web_contents,
    base::WeakPtr<Delegate> weak_delegate,
    int ideal_icon_size_in_dp,
    int minimum_icon_size_in_dp,
    bool is_debug_mode)
    : AppBannerDataFetcher(web_contents,
                           weak_delegate,
                           ideal_icon_size_in_dp,
                           minimum_icon_size_in_dp,
                           is_debug_mode) {}

AppBannerDataFetcherDesktop::~AppBannerDataFetcherDesktop() {
}

bool AppBannerDataFetcherDesktop::IsWebAppInstalled(
    content::BrowserContext* browser_context,
    const GURL& start_url) {
  return extensions::BookmarkAppHelper::BookmarkOrHostedAppInstalled(
      browser_context, start_url);
}

void AppBannerDataFetcherDesktop::ShowBanner(const SkBitmap* icon,
                                             const base::string16& title,
                                             const std::string& referrer) {
  content::WebContents* web_contents = GetWebContents();
  DCHECK(web_contents && !web_app_data().IsEmpty());

  Profile* profile =
      Profile::FromBrowserContext(web_contents->GetBrowserContext());
  WebApplicationInfo web_app_info;

  bookmark_app_helper_.reset(
      new extensions::BookmarkAppHelper(profile, web_app_info, web_contents));

  // This differs from the Android infobar creation, which has an explicit
  // InfoBarAndroid class interfacing with Java. On Android, the data fetcher
  // calls the InfoBarService to show the banner. On desktop, an InfoBar class
  // is not required, so the InfoBarService call is made within the delegate.
  infobars::InfoBar* infobar = AppBannerInfoBarDelegateDesktop::Create(
      make_scoped_refptr(this), web_contents, web_app_data(),
      bookmark_app_helper_.get(), event_request_id());
  if (infobar) {
    RecordDidShowBanner("AppBanner.WebApp.Shown");
    TrackDisplayEvent(DISPLAY_EVENT_WEB_APP_BANNER_CREATED);
  }
}

void AppBannerDataFetcherDesktop::FinishCreateBookmarkApp(
    const extensions::Extension* extension,
    const WebApplicationInfo& web_app_info) {
  content::WebContents* web_contents = GetWebContents();
  if (web_contents) {
    // A null extension pointer indicates that the bookmark app install was
    // not successful.
    if (extension == nullptr) {
      web_contents->GetMainFrame()->Send(
          new ChromeViewMsg_AppBannerDismissed(
              web_contents->GetMainFrame()->GetRoutingID(),
              event_request_id()));

      AppBannerSettingsHelper::RecordBannerDismissEvent(
          web_contents, web_app_data().start_url.spec(),
          AppBannerSettingsHelper::WEB);
    } else {
      web_contents->GetMainFrame()->Send(
          new ChromeViewMsg_AppBannerAccepted(
              web_contents->GetMainFrame()->GetRoutingID(),
              event_request_id(), "web"));

      AppBannerSettingsHelper::RecordBannerInstallEvent(
          web_contents, web_app_data().start_url.spec(),
          AppBannerSettingsHelper::WEB);
    }
  }
}

}  // namespace banners


text:
RAISERROR('Create table: [report].[htmlSkipRules]', 10, 1) WITH NOWAIT
GO
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[report].[htmlSkipRules]') AND type in (N'U'))
DROP TABLE [report].[htmlSkipRules]
GO

CREATE TABLE [report].[htmlSkipRules]
(
	[id]					[smallint] IDENTITY (1, 1)	NOT NULL,
	[module]				[varchar](32)	NOT NULL,
	[rule_id]				[int]			NOT NULL,
	[rule_name]				[sysname]		NOT NULL,
	[skip_value]			[sysname]		NULL,
	[skip_value2]			[sysname]		NULL,
	[active]				[bit]			NOT NULL CONSTRAINT [DF_htmlSkipRules_Active] DEFAULT (1),
	CONSTRAINT [PK_htmlSkipRules] PRIMARY KEY  CLUSTERED
	(
		[id]
	),
	CONSTRAINT [UK_htmlSkipRules_Name] UNIQUE  NONCLUSTERED
	(
		[module],
		[rule_id],
		[skip_value],
		[skip_value2]
	)
)
GO

-----------------------------------------------------------------------------------------------------
RAISERROR('		...insert default data', 10, 1) WITH NOWAIT
GO
SET NOCOUNT ON
GO
INSERT	INTO [report].[htmlSkipRules] ([module], [rule_id], [rule_name], [skip_value], [active])
		SELECT 'health-check',         1, 'Instances - Offline', NULL, 0 UNION ALL
		SELECT 'health-check',         2, 'Instances - Online', NULL, 0 UNION ALL
		SELECT 'health-check',         4, 'Databases Status - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',         8, 'Databases Status - Complete Details', NULL, 0 UNION ALL
		SELECT 'health-check',        16, 'SQL Server Agent Jobs - Job Failures', NULL, 0 UNION ALL
		SELECT 'health-check',        32, 'SQL Server Agent Jobs - Permissions errors', NULL, 0 UNION ALL
		SELECT 'health-check',        64, 'SQL Server Agent Jobs - Complete Details', NULL, 0 UNION ALL
		SELECT 'health-check',       128, 'Big Size for System Databases - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',       256, 'Databases Status - Permissions errors', NULL, 0 UNION ALL
		SELECT 'health-check',       512, 'Databases with Auto Close / Shrink - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',      1024, 'Big Size for Database Log files - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',      2048, 'Low Usage of Data Space - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',      4096, 'Log vs. Data - Allocated Size - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',      8192, 'Outdated Backup for Databases - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',     16384, 'Outdated DBCC CHECKDB Databases - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',     32768, 'High Usage of Log Space - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',     65536, 'Disk Space Information - Complete Detais', NULL, 0 UNION ALL
		SELECT 'health-check',    131072, 'Disk Space Information - Permission errors', NULL, 0 UNION ALL
		SELECT 'health-check',    262144, 'Low Free Disk Space - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',    524288, 'Errorlog messages - Permission errors', NULL, 0 UNION ALL
		SELECT 'health-check',   1048576, 'Errorlog messages - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',   2097152, 'Errorlog messages - Complete Details', NULL, 0 UNION ALL
		SELECT 'health-check',   4194304, 'Databases with Fixed File(s) Size - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',   8388608, 'Databases with (Page Verify not CHECKSUM) or (Page Verify is NONE)', NULL, 0 UNION ALL
		SELECT 'health-check',  16777216, 'Frequently Fragmented Indexes (consider lowering the fill-factor)', NULL, 0 UNION ALL
		SELECT 'health-check',  33554432, 'SQL Server Agent Jobs - Long Running SQL Agent Jobs', NULL, 0 UNION ALL
		SELECT 'health-check',  67108864, 'OS Event messages - Permission errors', NULL, 0 UNION ALL
		SELECT 'health-check', 134217728, 'OS Event messages - Complete Details', NULL, 0 UNION ALL
		SELECT 'health-check', 536870912, 'Failed Login Attempts - Issues Detected', NULL, 0 UNION ALL
		SELECT 'health-check',1073741824, 'Databases(s) Growth - Issues Detected', NULL, 0
GO


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

<TITLE>
CHPX (POI API Documentation)
</TITLE>

<META NAME="date" CONTENT="2010-10-29">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.hwpf.model

Class CHPX

java.lang.Object
  org.apache.poi.hwpf.model.PropertyNode
      org.apache.poi.hwpf.model.BytePropertyNode
          org.apache.poi.hwpf.model.CHPX

All Implemented Interfaces:
java.lang.Cloneable, java.lang.Comparable

public final class CHPX
extends BytePropertyNode

DANGER - works in bytes!

 Make sure you call getStart() / getEnd() when you want characters
  (normal use), but getStartByte() / getEndByte() when you're
  reading in / writing out!

Author:

Ryan Ackley

Field Summary

Fields inherited from class org.apache.poi.hwpf.model.PropertyNode

_buf

Constructor Summary

CHPX(int fcStart,
     int fcEnd,
     CharIndexTranslator translator,
     byte[] grpprl)

CHPX(int fcStart,
     int fcEnd,
     CharIndexTranslator translator,
     SprmBuffer buf)

Method Summary

 CharacterProperties
getCharacterProperties(StyleSheet ss,
                       short istd)

 byte[]
getGrpprl()

 SprmBuffer
getSprmBuf()

 java.lang.String
toString()

Methods inherited from class org.apache.poi.hwpf.model.BytePropertyNode

getEndBytes, getStartBytes

Methods inherited from class org.apache.poi.hwpf.model.PropertyNode

adjustForDelete, clone, compareTo, equals, getEnd, getStart, limitsAreEqual, setEnd, setStart

Methods inherited from class java.lang.Object

finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

CHPX

public CHPX(int fcStart,
            int fcEnd,
            CharIndexTranslator translator,
            byte[] grpprl)

CHPX

public CHPX(int fcStart,
            int fcEnd,
            CharIndexTranslator translator,
            SprmBuffer buf)

Method Detail

getGrpprl

public byte[] getGrpprl()

getSprmBuf

public SprmBuffer getSprmBuf()

getCharacterProperties

public CharacterProperties getCharacterProperties(StyleSheet ss,
                                                  short istd)

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2010 The Apache Software Foundation or
        its licensors, as applicable.


text:
<?php

namespace Yaoi\Cli;

class Exception extends \Yaoi\Command\Exception
{
    const NON_TAILING_VARIADIC_ARGUMENT = 10;
    const NON_TAILING_OPTIONAL_ARGUMENT = 11;
}


text:
import os
import time

from oslo_serialization import jsonutils as json

from tempest.lib.api_schema.response.volume import versions as schema
from tempest.lib.common import rest_client
from tempest.lib.services.volume import base_client

class VersionsClient(base_client.BaseClient):

    def list_versions(self):
        """List API versions

        For a full list of available parameters, please refer to the official
        API reference:
        https://docs.openstack.org/api-ref/block-storage/v3/#list-all-api-versions
        """
        version_url = self._get_base_version_url()

        start = time.time()
        resp, body = self.raw_request(version_url, 'GET')
        end = time.time()
        # NOTE: We need a raw_request() here instead of request() call because
        # "list API versions" API doesn't require an authentication and we can
        # skip it with raw_request() call.
        self._log_request('GET', version_url, resp, secs=(end - start),
                          resp_body=body)
        self._error_checker(resp, body)

        body = json.loads(body)
        self.validate_response(schema.list_versions, resp, body)
        return rest_client.ResponseBody(resp, body)

    def show_version(self, version):
        """Show API version details

        For a full list of available parameters, please refer to the official
        API reference:
        https://docs.openstack.org/api-ref/block-storage/v3/#show-api-v3-details
        """

        version_url = os.path.join(self._get_base_version_url(), version)
        resp, body = self.get(version_url)
        body = json.loads(body)
        self.validate_response(schema.volume_api_version_details, resp, body)
        return rest_client.ResponseBody(resp, body)