max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,284
# nuScenes dev-kit. # Code written by <NAME>, 2020. import itertools import os import unittest from collections import defaultdict from typing import List, Dict, Any from nuimages.nuimages import NuImages class TestForeignKeys(unittest.TestCase): def __init__(self, _: Any = None, version: str = 'v1.0-mini', dataroot: str = None): """ Initialize TestForeignKeys. Note: The second parameter is a dummy parameter required by the TestCase class. :param version: The NuImages version. :param dataroot: The root folder where the dataset is installed. """ super().__init__() self.version = version if dataroot is None: self.dataroot = os.environ['NUIMAGES'] else: self.dataroot = dataroot self.nuim = NuImages(version=self.version, dataroot=self.dataroot, verbose=False) def runTest(self) -> None: """ Dummy function required by the TestCase class. """ pass def test_foreign_keys(self) -> None: """ Test that every foreign key points to a valid token. """ # Index the tokens of all tables. index = dict() for table_name in self.nuim.table_names: print('Indexing table %s...' % table_name) table: list = self.nuim.__getattr__(table_name) tokens = [row['token'] for row in table] index[table_name] = set(tokens) # Go through each table and check the foreign_keys. for table_name in self.nuim.table_names: table: List[Dict[str, Any]] = self.nuim.__getattr__(table_name) if self.version.endswith('-test') and len(table) == 0: # Skip test annotations. continue keys = table[0].keys() # Check 1-to-1 link. one_to_one_names = [k for k in keys if k.endswith('_token') and not k.startswith('key_')] for foreign_key_name in one_to_one_names: print('Checking one-to-one key %s in table %s...' % (foreign_key_name, table_name)) foreign_table_name = foreign_key_name.replace('_token', '') foreign_tokens = set([row[foreign_key_name] for row in table]) # Check all tokens are valid. if self.version.endswith('-mini') and foreign_table_name == 'category': continue # Mini does not cover all categories. foreign_index = index[foreign_table_name] self.assertTrue(foreign_tokens.issubset(foreign_index)) # Check all tokens are covered. # By default we check that all tokens are covered. Exceptions are listed below. if table_name == 'object_ann': if foreign_table_name == 'category': remove = set([cat['token'] for cat in self.nuim.category if cat['name'] in ['vehicle.ego', 'flat.driveable_surface']]) foreign_index = foreign_index.difference(remove) elif foreign_table_name == 'sample_data': foreign_index = None # Skip as sample_datas may have no object_ann. elif table_name == 'surface_ann': if foreign_table_name == 'category': remove = set([cat['token'] for cat in self.nuim.category if cat['name'] not in ['vehicle.ego', 'flat.driveable_surface']]) foreign_index = foreign_index.difference(remove) elif foreign_table_name == 'sample_data': foreign_index = None # Skip as sample_datas may have no surface_ann. if foreign_index is not None: self.assertEqual(foreign_tokens, foreign_index) # Check 1-to-many link. one_to_many_names = [k for k in keys if k.endswith('_tokens')] for foreign_key_name in one_to_many_names: print('Checking one-to-many key %s in table %s...' % (foreign_key_name, table_name)) foreign_table_name = foreign_key_name.replace('_tokens', '') foreign_tokens_nested = [row[foreign_key_name] for row in table] foreign_tokens = set(itertools.chain(*foreign_tokens_nested)) # Check that all tokens are valid. foreign_index = index[foreign_table_name] self.assertTrue(foreign_tokens.issubset(foreign_index)) # Check all tokens are covered. if self.version.endswith('-mini') and foreign_table_name == 'attribute': continue # Mini does not cover all categories. if foreign_index is not None: self.assertEqual(foreign_tokens, foreign_index) # Check prev and next. prev_next_names = [k for k in keys if k in ['previous', 'next']] for foreign_key_name in prev_next_names: print('Checking prev-next key %s in table %s...' % (foreign_key_name, table_name)) foreign_table_name = table_name foreign_tokens = set([row[foreign_key_name] for row in table if len(row[foreign_key_name]) > 0]) # Check that all tokens are valid. foreign_index = index[foreign_table_name] self.assertTrue(foreign_tokens.issubset(foreign_index)) def test_prev_next(self) -> None: """ Test that the prev and next points in sample_data cover all entries and have the correct ordering. """ # Register all sample_datas. sample_to_sample_datas = defaultdict(lambda: []) for sample_data in self.nuim.sample_data: sample_to_sample_datas[sample_data['sample_token']].append(sample_data['token']) print('Checking prev-next pointers for completeness and correct ordering...') for sample in self.nuim.sample: # Compare the above sample_datas against those retrieved by using prev and next pointers. sd_tokens_pointers = self.nuim.get_sample_content(sample['token']) sd_tokens_all = sample_to_sample_datas[sample['token']] self.assertTrue(set(sd_tokens_pointers) == set(sd_tokens_all), 'Error: Inconsistency in prev/next pointers!') timestamps = [] for sd_token in sd_tokens_pointers: sample_data = self.nuim.get('sample_data', sd_token) timestamps.append(sample_data['timestamp']) self.assertTrue(sorted(timestamps) == timestamps, 'Error: Timestamps not properly sorted!') if __name__ == '__main__': # Runs the tests without aborting on error. for nuim_version in ['v1.0-train', 'v1.0-val', 'v1.0-test', 'v1.0-mini']: print('Running TestForeignKeys for version %s...' % nuim_version) test = TestForeignKeys(version=nuim_version) test.test_foreign_keys() test.test_prev_next() print()
3,256
3,861
<filename>MdePkg/Include/Protocol/PlatformToDriverConfiguration.h /** @file UEFI Platform to Driver Configuration Protocol is defined in UEFI specification. This is a protocol that is optionally produced by the platform and optionally consumed by a UEFI Driver in its Start() function. This protocol allows the driver to receive configuration information as part of being started. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __PLATFORM_TO_DRIVER_CONFIGUARTION_H__ #define __PLATFORM_TO_DRIVER_CONFIGUARTION_H__ #define EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL_GUID \ { 0x642cd590, 0x8059, 0x4c0a, { 0xa9, 0x58, 0xc5, 0xec, 0x7, 0xd2, 0x3c, 0x4b } } typedef struct _EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL; /** The UEFI driver must call Query early in the Start() function before any time consuming operations are performed. If ChildHandle is NULL the driver is requesting information from the platform about the ControllerHandle that is being started. Information returned from Query may lead to the drivers Start() function failing. If the UEFI driver is a bus driver and producing a ChildHandle, the driver must call Query after the child handle has been created and an EFI_DEVICE_PATH_PROTOCOL has been placed on that handle, but before any time consuming operation is performed. If information return by Query may lead the driver to decide to not create the ChildHandle. The driver must then cleanup and remove the ChildHandle from the system. The UEFI driver repeatedly calls Query, processes the information returned by the platform, and calls Response passing in the arguments returned from Query. The Instance value passed into Response must be the same value passed into the corresponding call to Query. The UEFI driver must continuously call Query and Response until EFI_NOT_FOUND is returned by Query. If the UEFI driver does not recognize the ParameterTypeGuid, it calls Response with a ConfigurationAction of EfiPlatformConfigurationActionUnsupportedGuid. The UEFI driver must then continue calling Query and Response until EFI_NOT_FOUND is returned by Query. This gives the platform an opportunity to pass additional configuration settings using a different ParameterTypeGuid that may be supported by the driver. An Instance value of zero means return the first ParameterBlock in the set of unprocessed parameter blocks. The driver should increment the Instance value by one for each successive call to Query. @param This A pointer to the EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL instance. @param ControllerHandle The handle the platform will return configuration information about. @param ChildHandle The handle of the child controller to return information on. This is an optional parameter that may be NULL. It will be NULL for device drivers and for bus drivers that attempt to get options for the bus controller. It will not be NULL for a bus driver that attempts to get options for one of its child controllers. @param Instance Pointer to the Instance value. Zero means return the first query data. The caller should increment this value by one each time to retrieve successive data. @param ParameterTypeGuid An EFI_GUID that defines the contents of ParameterBlock. UEFI drivers must use the ParameterTypeGuid to determine how to parse the ParameterBlock. The caller should not attempt to free ParameterTypeGuid. @param ParameterBlock The platform returns a pointer to the ParameterBlock structure which contains details about the configuration parameters specific to the ParameterTypeGuid. This structure is defined based on the protocol and may be different for different protocols. UEFI driver decodes this structure and its contents based on ParameterTypeGuid. ParameterBlock is allocated by the platform and the platform is responsible for freeing the ParameterBlock after Result is called. @param ParameterBlockSize The platform returns the size of the ParameterBlock in bytes. @retval EFI_SUCCESS The platform return parameter information for ControllerHandle. @retval EFI_NOT_FOUND No more unread Instance exists. @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. @retval EFI_INVALID_PARAMETER Instance is NULL. @retval EFI_DEVICE_ERROR A device error occurred while attempting to return parameter block information for the controller specified by ControllerHandle and ChildHandle. @retval EFI_OUT_RESOURCES There are not enough resources available to set the configuration options for the controller specified by ControllerHandle and ChildHandle. **/ typedef EFI_STATUS (EFIAPI *EFI_PLATFORM_TO_DRIVER_CONFIGURATION_QUERY)( IN CONST EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL *This, IN CONST EFI_HANDLE ControllerHandle, IN CONST EFI_HANDLE ChildHandle OPTIONAL, IN CONST UINTN *Instance, OUT EFI_GUID **ParameterTypeGuid, OUT VOID **ParameterBlock, OUT UINTN *ParameterBlockSize ); typedef enum { /// /// The controller specified by ControllerHandle is still /// in a usable state, and its configuration has been updated /// via parsing the ParameterBlock. If required by the /// parameter block, and the module supports an NVRAM store, /// the configuration information from PB was successfully /// saved to the NVRAM. No actions are required before /// this controller can be used again with the updated /// configuration settings. /// EfiPlatformConfigurationActionNone = 0, /// /// The driver has detected that the controller specified /// by ControllerHandle is not in a usable state and /// needs to be stopped. The calling agent can use the /// DisconnectControservice to perform this operation, and /// it should be performed as soon as possible. /// EfiPlatformConfigurationActionStopController = 1, /// /// This controller specified by ControllerHandle needs to /// be stopped and restarted before it can be used again. /// The calling agent can use the DisconnectController() /// and ConnectController() services to perform this /// operation. The restart operation can be delayed until /// all of the configuration options have been set. /// EfiPlatformConfigurationActionRestartController = 2, /// /// A configuration change has been made that requires the /// platform to be restarted before the controller /// specified by ControllerHandle can be used again. The /// calling agent can use the ResetSystem() services to /// perform this operation. The restart operation can be /// delayed until all of the configuration options have /// been set. /// EfiPlatformConfigurationActionRestartPlatform = 3, /// /// The controller specified by ControllerHandle is still /// in a usable state; its configuration has been updated /// via parsing the ParameterBlock. The driver tried to /// update the driver's private NVRAM store with /// information from ParameterBlock and failed. No actions /// are required before this controller can be used again /// with the updated configuration settings, but these /// configuration settings are not guaranteed to persist /// after ControllerHandle is stopped. /// EfiPlatformConfigurationActionNvramFailed = 4, /// /// The controller specified by ControllerHandle is still /// in a usable state; its configuration has not been updated /// via parsing the ParameterBlock. The driver did not support /// the ParameterBlock format identified by ParameterTypeGuid. /// No actions are required before this controller can be used /// again. On additional Query calls from this ControllerHandle, /// the platform should stop returning a ParameterBlock /// qualified by this same ParameterTypeGuid. If no other /// ParameterTypeGuid is supported by the platform, Query /// should return EFI_NOT_FOUND. /// EfiPlatformConfigurationActionUnsupportedGuid = 5, EfiPlatformConfigurationActionMaximum } EFI_PLATFORM_CONFIGURATION_ACTION; /** The UEFI driver repeatedly calls Query, processes the information returned by the platform, and calls Response passing in the arguments returned from Query. The UEFI driver must continuously call Query until EFI_NOT_FOUND is returned. For every call to Query that returns EFI_SUCCESS a corrisponding call to Response is required passing in the same ContollerHandle, ChildHandle, Instance, ParameterTypeGuid, ParameterBlock, and ParameterBlockSize. The UEFI driver may update values in ParameterBlock based on rules defined by ParameterTypeGuid. The platform is responsible for freeing ParameterBlock and the UEFI driver must not try to free it. @param This A pointer to the EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL instance. @param ControllerHandle The handle the driver is returning configuration information about. @param ChildHandle The handle of the child controller to return information on. This is an optional parameter that may be NULL. It will be NULL for device drivers, and for bus drivers that attempt to get options for the bus controller. It will not be NULL for a bus driver that attempts to get options for one of its child controllers. Instance Instance data returned from Query(). @param Instance Instance data passed to Query(). @param ParameterTypeGuid ParameterTypeGuid returned from Query. @param ParameterBlock ParameterBlock returned from Query. @param ParameterBlockSize The ParameterBlock size returned from Query. @param ConfigurationAction The driver tells the platform what action is required for ParameterBlock to take effect. @retval EFI_SUCCESS The platform return parameter information for ControllerHandle. @retval EFI_NOT_FOUND Instance was not found. @retval EFI_INVALID_PARAMETER ControllerHandle is NULL. @retval EFI_INVALID_PARAMETER Instance is zero. **/ typedef EFI_STATUS (EFIAPI *EFI_PLATFORM_TO_DRIVER_CONFIGURATION_RESPONSE)( IN CONST EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL *This, IN CONST EFI_HANDLE ControllerHandle, IN CONST EFI_HANDLE ChildHandle OPTIONAL, IN CONST UINTN *Instance, IN CONST EFI_GUID *ParameterTypeGuid, IN CONST VOID *ParameterBlock, IN CONST UINTN ParameterBlockSize , IN CONST EFI_PLATFORM_CONFIGURATION_ACTION ConfigurationAction ); /// /// The EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL is used by the /// UEFI driver to query the platform for configuration information. /// The UEFI driver calls Query() multiple times to get /// configuration information from the platform. For every call to /// Query() there must be a matching call to Response() so the /// UEFI driver can inform the platform how it used the /// information passed in from Query(). It's legal for a UEFI /// driver to use Response() to inform the platform it does not /// understand the data returned via Query() and thus no action was /// taken. /// struct _EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL { EFI_PLATFORM_TO_DRIVER_CONFIGURATION_QUERY Query; EFI_PLATFORM_TO_DRIVER_CONFIGURATION_RESPONSE Response; }; #define EFI_PLATFORM_TO_DRIVER_CONFIGURATION_CLP_GUID \ {0x345ecc0e, 0xcb6, 0x4b75, { 0xbb, 0x57, 0x1b, 0x12, 0x9c, 0x47, 0x33,0x3e } } /** ParameterTypeGuid provides the support for parameters communicated through the DMTF SM CLP Specification 1.0 Final Standard to be used to configure the UEFI driver. In this section the producer of the EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL is platform firmware and the consumer is the UEFI driver. Note: if future versions of the DMTF SM CLP Specification require changes to the parameter block definition, a newer ParameterTypeGuid will be used. **/ typedef struct { CHAR8 *CLPCommand; ///< A pointer to the null-terminated UTF-8 string that specifies the DMTF SM CLP command ///< line that the driver is required to parse and process when this function is called. ///< See the DMTF SM CLP Specification 1.0 Final Standard for details on the ///< format and syntax of the CLP command line string. CLPCommand buffer ///< is allocated by the producer of the EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOOL. UINT32 CLPCommandLength; ///< The length of the CLP Command in bytes. CHAR8 *CLPReturnString; ///< A pointer to the null-terminated UTF-8 string that indicates the CLP return status ///< that the driver is required to provide to the calling agent. ///< The calling agent may parse and/ or pass ///< this for processing and user feedback. The SM CLP Command Response string ///< buffer is filled in by the UEFI driver in the "keyword=value" format ///< described in the SM CLP Specification, unless otherwise requested via the SM ///< CLP Coutput option in the Command Line string buffer. UEFI driver's support ///< for this default "keyword=value" output format is required if the UEFI ///< driver supports this protocol, while support for other SM CLP output ///< formats is optional (the UEFI Driver should return an EFI_UNSUPPORTED if ///< the SM CLP Coutput option requested by the caller is not supported by the ///< UEFI Driver). CLPReturnString buffer is allocated by the consumer of the ///< EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOC OL and undefined prior to the call to ///< Response(). UINT32 CLPReturnStringLength; ///< The length of the CLP return status string in bytes. UINT8 CLPCmdStatus; ///< SM CLP Command Status (see DMTF SM CLP Specification 1.0 Final Standard - ///< Table 4) CLPErrorValue SM CLP Processing Error Value (see DMTF SM ///< CLP Specification 1.0 Final Standard - Table 6). This field is filled in by ///< the consumer of the EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOC ///< OL and undefined prior to the call to Response(). UINT8 CLPErrorValue; ///< SM CLP Processing Error Value (see DMTF SM CLP Specification 1.0 Final Standard - Table 6). ///< This field is filled in by the consumer of the EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOCOL and undefined prior to the call to Response(). UINT16 CLPMsgCode; ///< Bit 15: OEM Message Code Flag 0 = Message Code is an SM CLP Probable ///< Cause Value. (see SM CLP Specification Table 11) 1 = Message Code is OEM ///< Specific Bits 14-0: Message Code This field is filled in by the consumer of ///< the EFI_PLATFORM_TO_DRIVER_CONFIGURATION_PROTOC OL and undefined prior to the call to ///< Response(). } EFI_CONFIGURE_CLP_PARAMETER_BLK; extern EFI_GUID gEfiPlatformToDriverConfigurationClpGuid; extern EFI_GUID gEfiPlatformToDriverConfigurationProtocolGuid; #endif
6,941
640
<filename>server/www/packages/packages-windows/x86/ldap3/protocol/rfc3062.py """ """ # Created on 2014.04.28 # # Author: <NAME> # # Copyright 2014 - 2020 <NAME> # # This file is part of ldap3. # # ldap3 is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ldap3 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with ldap3 in the COPYING and COPYING.LESSER files. # If not, see <http://www.gnu.org/licenses/>. from pyasn1.type.univ import OctetString, Sequence from pyasn1.type.namedtype import NamedTypes, OptionalNamedType from pyasn1.type.tag import Tag, tagClassContext, tagFormatSimple # Modify password extended operation # passwdModifyOID OBJECT IDENTIFIER ::= 1.3.6.1.4.1.4203.1.11.1 # PasswdModifyRequestValue ::= SEQUENCE { # userIdentity [0] OCTET STRING OPTIONAL # oldPasswd [1] OCTET STRING OPTIONAL # newPasswd [2] OCTET STRING OPTIONAL } # # PasswdModifyResponseValue ::= SEQUENCE { # genPasswd [0] OCTET STRING OPTIONAL } class UserIdentity(OctetString): """ userIdentity [0] OCTET STRING OPTIONAL """ tagSet = OctetString.tagSet.tagImplicitly(Tag(tagClassContext, tagFormatSimple, 0)) encoding = 'utf-8' class OldPasswd(OctetString): """ oldPasswd [1] OCTET STRING OPTIONAL """ tagSet = OctetString.tagSet.tagImplicitly(Tag(tagClassContext, tagFormatSimple, 1)) encoding = 'utf-8' class NewPasswd(OctetString): """ newPasswd [2] OCTET STRING OPTIONAL """ tagSet = OctetString.tagSet.tagImplicitly(Tag(tagClassContext, tagFormatSimple, 2)) encoding = 'utf-8' class GenPasswd(OctetString): """ newPasswd [2] OCTET STRING OPTIONAL """ tagSet = OctetString.tagSet.tagImplicitly(Tag(tagClassContext, tagFormatSimple, 0)) encoding = 'utf-8' class PasswdModifyRequestValue(Sequence): """ PasswdModifyRequestValue ::= SEQUENCE { userIdentity [0] OCTET STRING OPTIONAL oldPasswd [1] OCTET STRING OPTIONAL newPasswd [2] OCTET STRING OPTIONAL } """ componentType = NamedTypes(OptionalNamedType('userIdentity', UserIdentity()), OptionalNamedType('oldPasswd', OldPasswd()), OptionalNamedType('newPasswd', NewPasswd())) class PasswdModifyResponseValue(Sequence): """ PasswdModifyResponseValue ::= SEQUENCE { genPasswd [0] OCTET STRING OPTIONAL } """ componentType = NamedTypes(OptionalNamedType('genPasswd', GenPasswd()))
1,192
937
{ "connector.class": "io.debezium.connector.postgresql.PostgresConnector", "tasks.max": "1", "database.hostname": "payment-db", "database.port": "5432", "database.user": "paymentuser", "database.password": "<PASSWORD>", "database.dbname" : "paymentdb", "database.server.name": "dbserver2", "schema.include.list": "payment", "table.include.list" : "payment.outboxevent", "tombstones.on.delete" : "false", "key.converter": "org.apache.kafka.connect.storage.StringConverter", "value.converter": "org.apache.kafka.connect.storage.StringConverter", "transforms" : "outbox", "transforms.outbox.type" : "io.debezium.transforms.outbox.EventRouter", "transforms.outbox.route.topic.replacement" : "${routedByValue}.response", "poll.interval.ms": "100" }
331
310
<reponame>dreeves/usesthis<filename>gear/hardware/t/ts-420.json { "name": "TS-420", "description": "A four-bay NAS.", "url": "https://www.amazon.com/QNAP-TS-420-All-one-4-bay/dp/B00D2Y1EHE" }
94
1,374
package def.js; import jsweet.util.function.Function4; @jsweet.lang.SyntacticIterable public class Array<T> extends Iterable<T> implements java.lang.Iterable<T> { public native T[] toArray(); /** * Gets or sets the length of the array. This is a number one higher than the * highest element defined in an array. */ public int length; /** * Appends new elements to an array, and returns the new length of the array. * * @param items * New elements of the Array. */ native public double push(@SuppressWarnings("unchecked") T... items); /** * Removes the last element from an array and returns it. */ native public T pop(); /** * Combines two or more arrays. * * @param items * Additional items to add to the end of array1. */ native public Array<T> concat(@SuppressWarnings("unchecked") T... items); /** * Combines two or more arrays. * * @param items * Additional items to add to the end of array1. */ native public <U extends T> Array<T> concat(@SuppressWarnings("unchecked") ItemsUs<U>... items); /** * Combines two or more arrays. * * @param items * Additional items to add to the end of array1. */ native public Array<T> concat(@SuppressWarnings("unchecked") ItemsTs<T>... items); /** * Adds all the elements of an array separated by the specified separator * string. * * @param separator * A string used to separate one element of an array from the next in * the resulting String. If omitted, the array elements are separated * with a comma. */ native public String join(java.lang.String separator); /** * Adds all the elements of an array separated by the specified separator * string. * * @param separator * A string used to separate one element of an array from the next in * the resulting String. If omitted, the array elements are separated * with a comma. */ native public String join(String separator); /** * Reverses the elements in an Array. */ native public Array<T> reverse(); /** * Removes the first element from an array and returns it. */ native public T shift(); /** * Returns a section of an array. * * @param start * The beginning of the specified portion of the array. * @param end * The end of the specified portion of the array. */ native public Array<T> slice(int start, int end); /** * Sorts an array. * * @param compareFn * The name of the function used to determine the order of the * elements. If omitted, the elements are sorted in ascending, ASCII * character order. */ native public Array<T> sort(java.util.function.BiFunction<T, T, Integer> compareFn); /** * Removes elements from an array and, if necessary, inserts new elements in * their place, returning the deleted elements. * * @param start * The zero-based location in the array from which to start removing * elements. */ native public Array<T> splice(int start); /** * Removes elements from an array and, if necessary, inserts new elements in * their place, returning the deleted elements. * * @param start * The zero-based location in the array from which to start removing * elements. * @param deleteCount * The number of elements to remove. * @param items * Elements to insert into the array in place of the deleted * elements. */ native public Array<T> splice(int start, int deleteCount, @SuppressWarnings("unchecked") T... items); /** * Inserts new elements at the start of an array. * * @param items * Elements to insert at the start of the Array. */ native public int unshift(@SuppressWarnings("unchecked") T... items); /** * Returns the index of the first occurrence of a value in an array. * * @param searchElement * The value to locate in the array. * @param fromIndex * The array index at which to begin the search. If fromIndex is * omitted, the search starts at index 0. */ native public int indexOf(T searchElement, int fromIndex); /** * Returns the index of the last occurrence of a specified value in an array. * * @param searchElement * The value to locate in the array. * @param fromIndex * The array index at which to begin the search. If fromIndex is * omitted, the search starts at the last index in the array. */ native public int lastIndexOf(T searchElement, int fromIndex); /** * Determines whether all the members of an array satisfy the specified test. * * @param callbackfn * A function that accepts up to three arguments. The every method * calls the callbackfn function for each element in array1 until the * callbackfn returns false, or until the end of the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public java.lang.Boolean every( jsweet.util.function.TriFunction<T, Double, Array<T>, java.lang.Boolean> callbackfn, java.lang.Object thisArg); /** * Determines whether all the members of an array satisfy the specified test. * * @param callbackfn * A function that accepts up to three arguments. The every method * calls the callbackfn function for each element in array1 until the * callbackfn returns false, or until the end of the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public java.lang.Boolean every(java.util.function.Function<T, java.lang.Boolean> callbackfn, java.lang.Object thisArg); /** * Determines whether the specified callback function returns true for any * element of an array. * * @param callbackfn * A function that accepts up to three arguments. The some method * calls the callbackfn function for each element in array1 until the * callbackfn returns true, or until the end of the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public java.lang.Boolean some( jsweet.util.function.TriFunction<T, Double, Array<T>, java.lang.Boolean> callbackfn, java.lang.Object thisArg); /** * Determines whether the specified callback function returns true for any * element of an array. * * @param callbackfn * A function that accepts up to three arguments. The some method * calls the callbackfn function for each element in array1 until the * callbackfn returns true, or until the end of the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public java.lang.Boolean some(java.util.function.Function<T, java.lang.Boolean> callbackfn, java.lang.Object thisArg); /** * Performs the specified action for each element in an array. * * @param callbackfn * A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public void forEach(jsweet.util.function.TriConsumer<T, Integer, Array<T>> callbackfn, java.lang.Object thisArg); /** * Performs the specified action for each element in an array. * * @param callbackfn * A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public void forEach(java.util.function.Consumer<T> callbackfn, java.lang.Object thisArg); /** * Calls a defined callback function on each element of an array, and returns an * array that contains the results. * * @param callbackfn * A function that accepts up to three arguments. The map method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public <U> Array<U> map(jsweet.util.function.TriFunction<T, Integer, Array<T>, U> callbackfn, java.lang.Object thisArg); /** * Calls a defined callback function on each element of an array, and returns an * array that contains the results. * * @param callbackfn * A function that accepts up to three arguments. The map method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public <U> Array<U> map(java.util.function.Function<T, U> callbackfn, java.lang.Object thisArg); /** * Returns the elements of an array that meet the condition specified in a * callback function. * * @param callbackfn * A function that accepts up to three arguments. The filter method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public Array<T> filter(jsweet.util.function.TriFunction<T, Integer, Array<T>, java.lang.Boolean> callbackfn, java.lang.Object thisArg); /** * Returns the elements of an array that meet the condition specified in a * callback function. * * @param callbackfn * A function that accepts up to three arguments. The filter method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public Array<T> filter(java.util.function.Function<T, java.lang.Boolean> callbackfn, java.lang.Object thisArg); /** * Calls the specified callback function for all the elements in an array. The * return value of the callback function is the accumulated result, and is * provided as an argument in the next call to the callback function. * * @param callbackfn * A function that accepts up to four arguments. The reduce method * calls the callbackfn function one time for each element in the * array. * @param initialValue * If initialValue is specified, it is used as the initial value to * start the accumulation. The first call to the callbackfn function * provides this value as an argument instead of an array value. */ @jsweet.lang.Name("reduce") native public T reduceCallbackfnFunction4(Function4<T, T, Double, Array<T>, T> callbackfn, InitialValueT<T> initialValue); /** * Calls the specified callback function for all the elements in an array. The * return value of the callback function is the accumulated result, and is * provided as an argument in the next call to the callback function. * * @param callbackfn * A function that accepts up to four arguments. The reduce method * calls the callbackfn function one time for each element in the * array. * @param initialValue * If initialValue is specified, it is used as the initial value to * start the accumulation. The first call to the callbackfn function * provides this value as an argument instead of an array value. */ @jsweet.lang.Name("reduce") native public <U> U reduceCallbackfnUUFunction4(Function4<U, T, Double, Array<T>, U> callbackfn, U initialValue); /** * Calls the specified callback function for all the elements in an array, in * descending order. The return value of the callback function is the * accumulated result, and is provided as an argument in the next call to the * callback function. * * @param callbackfn * A function that accepts up to four arguments. The reduceRight * method calls the callbackfn function one time for each element in * the array. * @param initialValue * If initialValue is specified, it is used as the initial value to * start the accumulation. The first call to the callbackfn function * provides this value as an argument instead of an array value. */ @jsweet.lang.Name("reduceRight") native public T reduceRightCallbackfnFunction4(Function4<T, T, Double, Array<T>, T> callbackfn, InitialValueT<T> initialValue); /** * Calls the specified callback function for all the elements in an array, in * descending order. The return value of the callback function is the * accumulated result, and is provided as an argument in the next call to the * callback function. * * @param callbackfn * A function that accepts up to four arguments. The reduceRight * method calls the callbackfn function one time for each element in * the array. * @param initialValue * If initialValue is specified, it is used as the initial value to * start the accumulation. The first call to the callbackfn function * provides this value as an argument instead of an array value. */ @jsweet.lang.Name("reduceRight") native public <U> U reduceRightCallbackfnUUFunction4(Function4<U, T, Double, Array<T>, U> callbackfn, U initialValue); native public T $get(int n); native public T $set(int n, T value); public Array(int arrayLength) { } public Array(@SuppressWarnings("unchecked") T... items) { } native public static Array<Object> $applyStatic(int arrayLength); native public static <T> T[] $applyStatic(@SuppressWarnings("unchecked") T... items); native public static java.lang.Boolean isArray(java.lang.Object arg); public static Array<?> prototype; /** * Returns an array of key, value pairs for every entry in the array */ native public IterableIterator<jsweet.util.tuple.Tuple2<Double, T>> entries(); /** * Returns an list of keys in the array */ native public IterableIterator<Double> keys(); /** * Returns an list of values in the array */ native public IterableIterator<T> values(); /** * Returns the value of the first element in the array where predicate is true, * and undefined otherwise. * * @param predicate * find calls predicate once for each element of the array, in * ascending order, until it finds one where predicate returns true. * If such an element is found, find immediately returns that element * value. Otherwise, find returns undefined. * @param thisArg * If provided, it will be used as the this value for each invocation * of predicate. If it is not provided, undefined is used instead. */ native public T find(jsweet.util.function.TriFunction<T, Integer, Array<T>, java.lang.Boolean> predicate, java.lang.Object thisArg); /** * Returns the value of the first element in the array where predicate is true, * and undefined otherwise. * * @param predicate * find calls predicate once for each element of the array, in * ascending order, until it finds one where predicate returns true. * If such an element is found, find immediately returns that element * value. Otherwise, find returns undefined. * @param thisArg * If provided, it will be used as the this value for each invocation * of predicate. If it is not provided, undefined is used instead. */ native public T find(java.util.function.Function<T, java.lang.Boolean> predicate, java.lang.Object thisArg); /** * Returns the index of the first element in the array where predicate is true, * and undefined otherwise. * * @param predicate * find calls predicate once for each element of the array, in * ascending order, until it finds one where predicate returns true. * If such an element is found, find immediately returns that element * value. Otherwise, find returns undefined. * @param thisArg * If provided, it will be used as the this value for each invocation * of predicate. If it is not provided, undefined is used instead. */ native public int findIndex(java.util.function.Function<T, java.lang.Boolean> predicate, java.lang.Object thisArg); /** * Returns the this object after filling the section identified by start and end * with value * * @param value * value to fill array section with * @param start * index to start filling the array at. If start is negative, it is * treated as length+start where length is the length of the array. * @param end * index to stop filling the array at. If end is negative, it is * treated as length+end. */ native public Array<T> fill(T value, int start, int end); /** * Returns the this object after copying a section of the array identified by * start and end to the same array starting at position target * * @param target * If target is negative, it is treated as length+target where length * is the length of the array. * @param start * If start is negative, it is treated as length+start. If end is * negative, it is treated as length+end. * @param end * If not specified, length of the this object is used as its default * value. */ native public Array<T> copyWithin(int target, int start, int end); /** * Adds all the elements of an array separated by the specified separator * string. * * @param separator * A string used to separate one element of an array from the next in * the resulting String. If omitted, the array elements are separated * with a comma. */ native public String join(); /** * Returns a section of an array. * * @param start * The beginning of the specified portion of the array. * @param end * The end of the specified portion of the array. */ native public Array<T> slice(int start); /** * Returns a section of an array. * * @param start * The beginning of the specified portion of the array. * @param end * The end of the specified portion of the array. */ native public Array<T> slice(); /** * Sorts an array. * * @param compareFn * The name of the function used to determine the order of the * elements. If omitted, the elements are sorted in ascending, ASCII * character order. */ native public Array<T> sort(); /** * Returns the index of the first occurrence of a value in an array. * * @param searchElement * The value to locate in the array. * @param fromIndex * The array index at which to begin the search. If fromIndex is * omitted, the search starts at index 0. */ native public int indexOf(T searchElement); /** * Returns the index of the last occurrence of a specified value in an array. * * @param searchElement * The value to locate in the array. * @param fromIndex * The array index at which to begin the search. If fromIndex is * omitted, the search starts at the last index in the array. */ native public int lastIndexOf(T searchElement); /** * Determines whether all the members of an array satisfy the specified test. * * @param callbackfn * A function that accepts up to three arguments. The every method * calls the callbackfn function for each element in array1 until the * callbackfn returns false, or until the end of the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public java.lang.Boolean every( jsweet.util.function.TriFunction<T, Integer, Array<T>, java.lang.Boolean> callbackfn); /** * Determines whether the specified callback function returns true for any * element of an array. * * @param callbackfn * A function that accepts up to three arguments. The some method * calls the callbackfn function for each element in array1 until the * callbackfn returns true, or until the end of the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public java.lang.Boolean some( jsweet.util.function.TriFunction<T, Integer, Array<T>, java.lang.Boolean> callbackfn); /** * Performs the specified action for each element in an array. * * @param callbackfn * A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public void forEach(jsweet.util.function.TriConsumer<T, Integer, Array<T>> callbackfn); /** * Calls a defined callback function on each element of an array, and returns an * array that contains the results. * * @param callbackfn * A function that accepts up to three arguments. The map method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public <U> Array<U> map(jsweet.util.function.TriFunction<T, Integer, Array<T>, U> callbackfn); /** * Calls a defined callback function on each element of an array, and returns an * array that contains the results. * * @param callbackfn * A function that accepts up to three arguments. The map method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public <U> Array<U> map(java.util.function.Function<T, U> callbackfn); /** * Returns the elements of an array that meet the condition specified in a * callback function. * * @param callbackfn * A function that accepts up to three arguments. The filter method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public Array<T> filter(jsweet.util.function.TriFunction<T, Integer, Array<T>, java.lang.Boolean> callbackfn); /** * Returns the elements of an array that meet the condition specified in a * callback function. * * @param callbackfn * A function that accepts up to three arguments. The filter method * calls the callbackfn function one time for each element in the * array. * @param thisArg * An object to which the this keyword can refer in the callbackfn * function. If thisArg is omitted, undefined is used as the this * value. */ native public Array<T> filter(java.util.function.Function<T, java.lang.Boolean> callbackfn); /** * Calls the specified callback function for all the elements in an array. The * return value of the callback function is the accumulated result, and is * provided as an argument in the next call to the callback function. * * @param callbackfn * A function that accepts up to four arguments. The reduce method * calls the callbackfn function one time for each element in the * array. * @param initialValue * If initialValue is specified, it is used as the initial value to * start the accumulation. The first call to the callbackfn function * provides this value as an argument instead of an array value. */ native public T reduce(Function4<T, T, Integer, Array<T>, T> callbackfn); /** * Calls the specified callback function for all the elements in an array, in * descending order. The return value of the callback function is the * accumulated result, and is provided as an argument in the next call to the * callback function. * * @param callbackfn * A function that accepts up to four arguments. The reduceRight * method calls the callbackfn function one time for each element in * the array. * @param initialValue * If initialValue is specified, it is used as the initial value to * start the accumulation. The first call to the callbackfn function * provides this value as an argument instead of an array value. */ native public T reduceRight(Function4<T, T, Integer, Array<T>, T> callbackfn); public Array() { } native public static Array<Object> $applyStatic(); /** * Returns the value of the first element in the array where predicate is true, * and undefined otherwise. * * @param predicate * find calls predicate once for each element of the array, in * ascending order, until it finds one where predicate returns true. * If such an element is found, find immediately returns that element * value. Otherwise, find returns undefined. * @param thisArg * If provided, it will be used as the this value for each invocation * of predicate. If it is not provided, undefined is used instead. */ native public T find(jsweet.util.function.TriFunction<T, Integer, Array<T>, java.lang.Boolean> predicate); /** * Returns the index of the first element in the array where predicate is true, * and undefined otherwise. * * @param predicate * find calls predicate once for each element of the array, in * ascending order, until it finds one where predicate returns true. * If such an element is found, find immediately returns that element * value. Otherwise, find returns undefined. * @param thisArg * If provided, it will be used as the this value for each invocation * of predicate. If it is not provided, undefined is used instead. */ native public int findIndex(java.util.function.Function<T, java.lang.Boolean> predicate); /** * Returns the this object after filling the section identified by start and end * with value * * @param value * value to fill array section with * @param start * index to start filling the array at. If start is negative, it is * treated as length+start where length is the length of the array. * @param end * index to stop filling the array at. If end is negative, it is * treated as length+end. */ native public Array<T> fill(T value, int start); /** * Returns the this object after filling the section identified by start and end * with value * * @param value * value to fill array section with * @param start * index to start filling the array at. If start is negative, it is * treated as length+start where length is the length of the array. * @param end * index to stop filling the array at. If end is negative, it is * treated as length+end. */ native public Array<T> fill(T value); /** * Returns the this object after copying a section of the array identified by * start and end to the same array starting at position target * * @param target * If target is negative, it is treated as length+target where length * is the length of the array. * @param start * If start is negative, it is treated as length+start. If end is * negative, it is treated as length+end. * @param end * If not specified, length of the this object is used as its default * value. */ native public Array<T> copyWithin(int target, int start); /** From Iterable, to allow foreach loop (do not use directly). */ @jsweet.lang.Erased native public java.util.Iterator<T> iterator(); /** * This class was automatically generated for disambiguating erased method * signatures. */ @jsweet.lang.Erased public static class ItemsTs<T> extends def.js.Object { public ItemsTs(@SuppressWarnings("unchecked") T... items) { } } /** * This class was automatically generated for disambiguating erased method * signatures. */ @jsweet.lang.Erased public static class ItemsUs<U> extends def.js.Object { public ItemsUs(@SuppressWarnings("unchecked") U... items) { } } /** * This class was automatically generated for disambiguating erased method * signatures. */ @jsweet.lang.Erased public static class InitialValueU<U> extends def.js.Object { public InitialValueU(U initialValue) { } } /** * This class was automatically generated for disambiguating erased method * signatures. */ @jsweet.lang.Erased public static class InitialValueT<T> extends def.js.Object { public InitialValueT(T initialValue) { } } public static native <T> Array<T> from(java.lang.Object arrayLike); }
10,619
581
# coding: utf8 from multiprocessing import Pool, cpu_count from pathlib import Path import sys from typing import Generator, Iterable, Optional, List import plac from . import force_using_normalized_form_as_lemma from .analyzer import Analyzer MINI_BATCH_SIZE = 100 class _OutputWrapper: def __init__(self, output_path, output_format): self.output = None self.output_path = output_path self.output_format = output_format self.output_json_opened = False @property def is_json(self): return self.output_format in ["3", "json"] def open(self): if self.output_path: self.output = open(self.output_path, "w") else: self.output = sys.stdout def close(self): if self.is_json and self.output_json_opened: print("]", file=self.output) self.output_json_opened = False if self.output_path: self.output.close() else: pass def write(self, *args, **kwargs): if self.is_json and not self.output_json_opened: print("[", file=self.output) self.output_json_opened = True elif self.is_json: print(" ,", file=self.output) print(*args, **kwargs, file=self.output) def run( model_path: Optional[str] = None, ensure_model: Optional[str] = None, split_mode: Optional[str] = "C", hash_comment: str = "print", output_path: Optional[Path] = None, output_format: str = "0", require_gpu: bool = False, disable_sentencizer: bool = False, use_normalized_form: bool = False, parallel: int = 1, files: List[str] = None, ): if require_gpu: print("GPU enabled", file=sys.stderr) if use_normalized_form: print("overriding Token.lemma_ by normalized_form of SudachiPy", file=sys.stderr) force_using_normalized_form_as_lemma(True) assert model_path is None or ensure_model is None analyzer = Analyzer( model_path, ensure_model, split_mode, hash_comment, output_format, require_gpu, disable_sentencizer, ) if parallel <= 0: parallel = max(1, cpu_count() + parallel) output = _OutputWrapper(output_path, output_format) output.open() try: if not files: if sys.stdin.isatty(): parallel = 1 _analyze_tty(analyzer, output) else: _analyze_single(analyzer, output, files=[0]) elif parallel == 1: _analyze_single(analyzer, output, files) else: _analyze_parallel(analyzer, output, files, parallel) finally: output.close() def _analyze_tty(analyzer: Analyzer, output: _OutputWrapper) -> None: try: analyzer.set_nlp() while True: line = input() for sent in analyzer.analyze_line(line): for ol in sent: output.write(ol) except EOFError: pass except KeyboardInterrupt: pass def _analyze_single(analyzer: Analyzer, output: _OutputWrapper, files: Iterable[str]) -> None: try: analyzer.set_nlp() for path in files: with open(path, "r") as f: for line in f: for sent in analyzer.analyze_line(line): for ol in sent: output.write(ol) except KeyboardInterrupt: pass def _data_loader( files: List[str], batch_size: int ) -> Generator[List[str], None, None]: mini_batch = [] for path in files: with open(path, "r") as f: for line in f: mini_batch.append(line) if len(mini_batch) == batch_size: yield mini_batch mini_batch = [] if mini_batch: yield mini_batch def _analyze_parallel(analyzer: Analyzer, output: _OutputWrapper, files: Iterable[str], parallel: int) -> None: pool = None try: first_batch = True mini_batches = [] for mini_batch in _data_loader(files, MINI_BATCH_SIZE): if first_batch: if len(mini_batch) < MINI_BATCH_SIZE: analyzer.set_nlp() for line in mini_batch: for sent in analyzer.analyze_line(line): for ol in sent: output.write(ol) return else: first_batch = False mini_batches.append(mini_batch) if len(mini_batches) == parallel: if not pool: pool = Pool(parallel) for mini_batch_result in pool.map(analyzer.analyze_lines_mp, mini_batches): for sents in mini_batch_result: for lines in sents: for ol in lines: output.write(ol) mini_batches = [] if not pool: parallel = len(mini_batches) pool = Pool(parallel) for mini_batch_result in pool.map(analyzer.analyze_lines_mp, mini_batches): for sents in mini_batch_result: for lines in sents: for ol in lines: output.write(ol) except KeyboardInterrupt: pass finally: if pool: try: pool.close() except: pass @plac.annotations( model_path=("model directory path", "option", "b", str), split_mode=("split mode", "option", "s", str, ["A", "B", "C"]), hash_comment=("hash comment", "option", "c", str, ["print", "skip", "analyze"]), output_path=("output path", "option", "o", Path), use_normalized_form=("overriding Token.lemma_ by normalized_form of SudachiPy", "flag", "n"), parallel=("parallel level (default=-1, all_cpus=0)", "option", "p", int), files=("input files", "positional"), ) def run_ginzame( model_path=None, split_mode="C", hash_comment="print", output_path=None, use_normalized_form=False, parallel=-1, *files, ): run( model_path=model_path, ensure_model="ja_ginza", split_mode=split_mode, hash_comment=hash_comment, output_path=output_path, output_format="mecab", require_gpu=False, use_normalized_form=use_normalized_form, parallel=parallel, disable_sentencizer=False, files=files, ) def main_ginzame(): plac.call(run_ginzame) @plac.annotations( model_path=("model directory path", "option", "b", str), ensure_model=("select model either ja_ginza or ja_ginza_electra", "option", "m", str, ["ja_ginza", "ja-ginza", "ja_ginza_electra", "ja-ginza-electra", None]), split_mode=("split mode", "option", "s", str, ["A", "B", "C"]), hash_comment=("hash comment", "option", "c", str, ["print", "skip", "analyze"]), output_path=("output path", "option", "o", Path), output_format=("output format", "option", "f", str, ["0", "conllu", "1", "cabocha", "2", "mecab", "3", "json"]), require_gpu=("enable require_gpu", "flag", "g"), use_normalized_form=("overriding Token.lemma_ by normalized_form of SudachiPy", "flag", "n"), disable_sentencizer=("disable spaCy's sentence separator", "flag", "d"), parallel=("parallel level (default=1, all_cpus=0)", "option", "p", int), files=("input files", "positional"), ) def run_ginza( model_path=None, ensure_model=None, split_mode="C", hash_comment="print", output_path=None, output_format="conllu", require_gpu=False, use_normalized_form=False, disable_sentencizer=False, parallel=1, *files, ): run( model_path=model_path, ensure_model=ensure_model, split_mode=split_mode, hash_comment=hash_comment, output_path=output_path, output_format=output_format, require_gpu=require_gpu, use_normalized_form=use_normalized_form, disable_sentencizer=disable_sentencizer, parallel=parallel, files=files, ) def main_ginza(): plac.call(run_ginza) if __name__ == "__main__": plac.call(run_ginza)
3,986
654
/* * Copyright (c) 2015-2021 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Attribution Notice under the terms of the Apache License 2.0 * * This work was created by the collective efforts of the openCypher community. * Without limiting the terms of Section 6, any Derivative Work that is not * approved by the public consensus process of the openCypher Implementers Group * should not be described as “Cypher” (and Cypher® is a registered trademark of * Neo4j Inc.) or as "openCypher". Extensions by implementers or prototypes or * proposals for change that have been documented or implemented should only be * described as "implementation extensions to Cypher" or as "proposed changes to * Cypher that are not yet approved by the openCypher community". */ package org.opencypher.grammar; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; class Dependencies { private Map<String, Set<ProductionNode>> missingProductions; private final Map<String, Set<ProductionNode>> dependencies = new LinkedHashMap<>(); public void missingProduction( String name, ProductionNode origin ) { if ( missingProductions == null ) { missingProductions = new LinkedHashMap<>(); } update( missingProductions, name, origin ); } public void usedFrom( String name, ProductionNode origin ) { update( dependencies, name, origin ); } private static void update( Map<String, Set<ProductionNode>> productions, String name, ProductionNode origin ) { Set<ProductionNode> origins = productions.get( name ); if ( origins == null ) { productions.put( name, origins = Collections.newSetFromMap( new LinkedHashMap<>() ) ); } origins.add( origin ); } public void reportMissingProductions() { if ( missingProductions != null && !missingProductions.isEmpty() ) { StringBuilder message = new StringBuilder() .append( "Productions used in non-terminals have not been defined:" ); for ( Map.Entry<String, Set<ProductionNode>> entry : missingProductions.entrySet() ) { message.append( "\n " ).append( entry.getKey() ); String sep = " used from: "; for ( ProductionNode origin : entry.getValue() ) { message.append( sep ); if ( origin.name == null ) { message.append( "The root of the '" ).append( origin.vocabulary ).append( "' grammar" ); } else { message.append( '\'' ).append( origin.name ) .append( "' in '" ).append( origin.vocabulary ).append( '\'' ); } sep = ", "; } } throw new IllegalArgumentException( message.toString() ); } } public void invalidCharacterSet( String name, ProductionNode origin ) { throw new IllegalArgumentException( "Invalid character set: '" + name + "', a production exists with that name." ); } }
1,459
12,278
/* Copyright (c) <NAME> 2011-2012. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) For more information, see http://www.boost.org */ #include <iostream> #include <boost/config.hpp> #include <boost/algorithm/cxx11/is_partitioned.hpp> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <string> #include <vector> #include <list> namespace ba = boost::algorithm; // namespace ba = boost; template <typename T> struct less_than { public: BOOST_CXX14_CONSTEXPR less_than ( T foo ) : val ( foo ) {} BOOST_CXX14_CONSTEXPR less_than ( const less_than &rhs ) : val ( rhs.val ) {} BOOST_CXX14_CONSTEXPR bool operator () ( const T &v ) const { return v < val; } private: less_than (); less_than operator = ( const less_than &rhs ); T val; }; BOOST_CXX14_CONSTEXPR bool test_constexpr() { int v[] = { 4, 5, 6, 7, 8, 9, 10 }; bool res = true; res = ( res && ba::is_partitioned ( v, less_than<int>(3))); // no elements res = ( res && ba::is_partitioned ( v, less_than<int>(5))); // only the first element res = ( res && ba::is_partitioned ( v, less_than<int>(8))); // in the middle somewhere res = ( res && ba::is_partitioned ( v, less_than<int>(99))); // all elements return res; } void test_sequence1 () { std::vector<int> v; v.clear (); for ( int i = 5; i < 15; ++i ) v.push_back ( i ); BOOST_CHECK ( ba::is_partitioned ( v, less_than<int>(3))); // no elements BOOST_CHECK ( ba::is_partitioned ( v, less_than<int>(6))); // only the first element BOOST_CHECK ( ba::is_partitioned ( v, less_than<int>(10))); // in the middle somewhere BOOST_CHECK ( ba::is_partitioned ( v, less_than<int>(99))); // all elements satisfy // With bidirectional iterators. std::list<int> l; for ( int i = 5; i < 15; ++i ) l.push_back ( i ); BOOST_CHECK ( ba::is_partitioned ( l.begin (), l.end (), less_than<int>(3))); // no elements BOOST_CHECK ( ba::is_partitioned ( l.begin (), l.end (), less_than<int>(6))); // only the first element BOOST_CHECK ( ba::is_partitioned ( l.begin (), l.end (), less_than<int>(10))); // in the middle somewhere BOOST_CHECK ( ba::is_partitioned ( l.begin (), l.end (), less_than<int>(99))); // all elements satisfy } BOOST_AUTO_TEST_CASE( test_main ) { test_sequence1 (); BOOST_CXX14_CONSTEXPR bool constexpr_res = test_constexpr (); BOOST_CHECK ( constexpr_res ); }
1,076
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"<NAME>","circ":"3ème circonscription","dpt":"Ardennes","inscrits":123,"abs":70,"votants":53,"blancs":3,"nuls":0,"exp":50,"res":[{"nuance":"LR","nom":"<NAME>","voix":42},{"nuance":"FN","nom":"<NAME>","voix":8}]}
108
348
{"nom":"Serra-di-Fiumorbo","circ":"2ème circonscription","dpt":"Haute-Corse","inscrits":368,"abs":129,"votants":239,"blancs":1,"nuls":0,"exp":238,"res":[{"nuance":"REG","nom":"<NAME>","voix":135},{"nuance":"REM","nom":"<NAME>","voix":103}]}
97
3,172
<reponame>lp2333/PARL # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import threading from collections import defaultdict class JobCenter(object): """The job center deals with everythin related to jobs. Attributes: job_pool (set): A set to store the job address of vacant cpu. worker_dict (dict): A dict to store connected workers. worker_hostname (dict): A dict to record worker hostname. worker_vacant_jobs (dict): Record how many vacant jobs does each worker has. master_ip (str): IP address of the master node. """ def __init__(self, master_ip): self.job_pool = dict() self.worker_dict = {} self.worker_hostname = defaultdict(int) self.worker_vacant_jobs = {} self.lock = threading.Lock() self.master_ip = master_ip @property def cpu_num(self): """"Return vacant cpu number.""" return len(self.job_pool) @property def worker_num(self): """Return connected worker number.""" return len(self.worker_dict) def add_worker(self, worker): """When a new worker connects, add its hostname to worker_hostname. Args: worker (InitializedWorker): New worker with initialized jobs. """ self.lock.acquire() self.worker_dict[worker.worker_address] = worker for job in worker.initialized_jobs: self.job_pool[job.job_address] = job self.worker_vacant_jobs[worker.worker_address] = len( worker.initialized_jobs) if self.master_ip and worker.worker_address.split( ':')[0] == self.master_ip: self.worker_hostname[worker.worker_address] = "Master" self.master_ip = None else: self.worker_hostname[worker.hostname] += 1 self.worker_hostname[worker.worker_address] = "{}:{}".format( worker.hostname, self.worker_hostname[worker.hostname]) self.lock.release() def drop_worker(self, worker_address): """Remove jobs from job_pool when a worker dies. Args: worker_address (str): the worker_address of a worker to be removed from the job center. """ self.lock.acquire() worker = self.worker_dict[worker_address] for job in worker.initialized_jobs: if job.job_address in self.job_pool: self.job_pool.pop(job.job_address) self.worker_dict.pop(worker_address) self.worker_vacant_jobs.pop(worker_address) self.lock.release() def request_job(self): """Return a job_address when the client submits a job. If there is no vacant CPU in the cluster, this will return None. Return: An ``InitializedJob`` that has information about available job address. """ self.lock.acquire() job = None if len(self.job_pool): job_address, job = self.job_pool.popitem() self.worker_vacant_jobs[job.worker_address] -= 1 assert self.worker_vacant_jobs[job.worker_address] >= 0 self.lock.release() return job def reset_job(self, job): """Reset a job and add the job_address to the job_pool. Args: job(``InitializedJob``): The job information of the restarted job. """ self.lock.acquire() self.job_pool[job.job_address] = job self.lock.release() def update_job(self, killed_job_address, new_job, worker_address): """When worker kill an old job, it will start a new job. Args: killed_job_address (str): The job address of the killed job. new_job(``InitializedJob``): Information of the new job. worker_address (str): The worker which kills an old job. """ self.lock.acquire() self.job_pool[new_job.job_address] = new_job self.worker_vacant_jobs[worker_address] += 1 if killed_job_address in self.job_pool: self.worker_vacant_jobs[worker_address] -= 1 self.job_pool.pop(killed_job_address) to_del_idx = None for i, job in enumerate( self.worker_dict[worker_address].initialized_jobs): if job.job_address == killed_job_address: to_del_idx = i break del self.worker_dict[worker_address].initialized_jobs[to_del_idx] self.worker_dict[worker_address].initialized_jobs.append(new_job) self.lock.release() def get_vacant_cpu(self, worker_address): """Return vacant cpu number of a worker.""" return self.worker_vacant_jobs[worker_address] def get_total_cpu(self, worker_address): """Return total cpu number of a worker.""" return len(self.worker_dict[worker_address].initialized_jobs) def get_hostname(self, worker_address): """Return the hostname of a worker.""" return self.worker_hostname[worker_address]
2,354
739
<reponame>tchudyk/RichTextFX package org.fxmisc.richtext.demo; import java.time.Duration; import javafx.application.Application; import javafx.geometry.Point2D; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.stage.Popup; import javafx.stage.Stage; import org.fxmisc.richtext.event.MouseOverTextEvent; import org.fxmisc.richtext.StyleClassedTextArea; public class TooltipDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { StyleClassedTextArea area = new StyleClassedTextArea(); area.setWrapText(true); area.appendText("Pause the mouse over the text for 1 second."); Popup popup = new Popup(); Label popupMsg = new Label(); popupMsg.setStyle( "-fx-background-color: black;" + "-fx-text-fill: white;" + "-fx-padding: 5;"); popup.getContent().add(popupMsg); area.setMouseOverTextDelay(Duration.ofSeconds(1)); area.addEventHandler(MouseOverTextEvent.MOUSE_OVER_TEXT_BEGIN, e -> { int chIdx = e.getCharacterIndex(); Point2D pos = e.getScreenPosition(); popupMsg.setText("Character '" + area.getText(chIdx, chIdx+1) + "' at " + pos); popup.show(area, pos.getX(), pos.getY() + 10); }); area.addEventHandler(MouseOverTextEvent.MOUSE_OVER_TEXT_END, e -> { popup.hide(); }); Scene scene = new Scene(area, 600, 400); stage.setScene(scene); stage.setTitle("Tooltip Demo"); stage.show(); } }
721
431
/* Copyright 2017 <NAME> and <NAME> Distributed under MIT license, or public domain if desired and recognized in your jurisdiction. See file LICENSE for detail. */ #include "usermodel.h" UserModel::UserModel(QObject *parent) : QObject(parent) { } QString UserModel::getName() const { return name; } void UserModel::setName(const QString &value) { name = value; } QString UserModel::getCategory() const { return category; } double UserModel::getMass() const { return mass; } void UserModel::setMass(double value) { mass = value; } double UserModel::getHeight() const { return height; } void UserModel::setHeight(double value) { height = value; } double UserModel::getBmi() { bmi = height != 0 ? mass / (height * height) : 0; if(bmi <= 15) { category = "Very severely underweight"; } else if(bmi > 15 && bmi <= 16) { category = "Severely underweight"; } else if(bmi > 16 && bmi <= 18.5) { category = "Underweight"; } else if(bmi > 18.5 && bmi <= 25) { category = "Normal (healthy weight)"; } else if(bmi > 25 && bmi <= 30) { category = "Overweight"; } else if(bmi > 30 && bmi <= 35) { category = "Obese Class I (Moderately obese)"; } else if(bmi > 35 && bmi <= 40) { category = "Obese Class II (Severely obese)"; } else { category = "Obese Class III (Very severely obese)"; } return bmi; }
714
711
package com.java110.goods.smo.impl; import com.java110.core.base.smo.BaseServiceSMO; import com.java110.dto.PageDto; import com.java110.dto.product.ProductDto; import com.java110.dto.productLabel.ProductLabelDto; import com.java110.dto.productSpecValue.ProductSpecValueDto; import com.java110.goods.dao.IProductLabelServiceDao; import com.java110.intf.goods.IProductLabelInnerServiceSMO; import com.java110.po.productLabel.ProductLabelPo; import com.java110.utils.util.BeanConvertUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @ClassName FloorInnerServiceSMOImpl * @Description 产品标签内部服务实现类 * @Author wuxw * @Date 2019/4/24 9:20 * @Version 1.0 * add by wuxw 2019/4/24 **/ @RestController public class ProductLabelInnerServiceSMOImpl extends BaseServiceSMO implements IProductLabelInnerServiceSMO { @Autowired private IProductLabelServiceDao productLabelServiceDaoImpl; @Override public int saveProductLabel(@RequestBody ProductLabelPo productLabelPo) { int saveFlag = 1; productLabelServiceDaoImpl.saveProductLabelInfo(BeanConvertUtil.beanCovertMap(productLabelPo)); return saveFlag; } @Override public int updateProductLabel(@RequestBody ProductLabelPo productLabelPo) { int saveFlag = 1; productLabelServiceDaoImpl.updateProductLabelInfo(BeanConvertUtil.beanCovertMap(productLabelPo)); return saveFlag; } @Override public int deleteProductLabel(@RequestBody ProductLabelPo productLabelPo) { int saveFlag = 1; productLabelPo.setStatusCd("1"); productLabelServiceDaoImpl.updateProductLabelInfo(BeanConvertUtil.beanCovertMap(productLabelPo)); return saveFlag; } @Override public List<ProductLabelDto> queryProductLabels(@RequestBody ProductLabelDto productLabelDto) { //校验是否传了 分页信息 int page = productLabelDto.getPage(); if (page != PageDto.DEFAULT_PAGE) { productLabelDto.setPage((page - 1) * productLabelDto.getRow()); } List<ProductLabelDto> products = new ArrayList<>(); List<Map> prods = productLabelServiceDaoImpl.getProductLabelInfo(BeanConvertUtil.beanCovertMap(productLabelDto)); ProductLabelDto tmpProductDto = null; ProductSpecValueDto productSpecValueDto = null; for (Map prod : prods) { tmpProductDto = BeanConvertUtil.covertBean(prod, ProductLabelDto.class); productSpecValueDto = BeanConvertUtil.covertBean(prod, ProductSpecValueDto.class); tmpProductDto.setDefaultSpecValue(productSpecValueDto); products.add(tmpProductDto); } return products; } @Override public int queryProductLabelsCount(@RequestBody ProductLabelDto productLabelDto) { return productLabelServiceDaoImpl.queryProductLabelsCount(BeanConvertUtil.beanCovertMap(productLabelDto)); } public IProductLabelServiceDao getProductLabelServiceDaoImpl() { return productLabelServiceDaoImpl; } public void setProductLabelServiceDaoImpl(IProductLabelServiceDao productLabelServiceDaoImpl) { this.productLabelServiceDaoImpl = productLabelServiceDaoImpl; } }
1,313
1,398
from skimage.transform import resize heatmap_1_r = resize(heatmap_1, (50,80), mode='reflect', preserve_range=True, anti_aliasing=True) heatmap_2_r = resize(heatmap_2, (50,80), mode='reflect', preserve_range=True, anti_aliasing=True) heatmap_3_r = resize(heatmap_3, (50,80), mode='reflect', preserve_range=True, anti_aliasing=True) heatmap_geom_avg = np.power(heatmap_1_r * heatmap_2_r * heatmap_3_r, 0.333) display_img_and_heatmap("dog.jpg", heatmap_geom_avg)
245
1,472
<gh_stars>1000+ package org.muses.jeeplatform.cas.user.service; import org.muses.jeeplatform.cas.user.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * <pre> * * </pre> * * <pre> * @author mazq * 修改记录 * 修改后版本: 修改人: 修改日期: 2020/04/26 15:26 修改内容: * </pre> */ @Service public class UserService { @Autowired @Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate; /** * 通过用户名查询用户信息 * @param username * @return */ @Transactional(readOnly=true) //@RedisCache(nameSpace = RedisCacheNamespace.SYS_USER) public User findByUsername(String username){ String sql = "SELECT * FROM sys_user WHERE username = ?"; User info = null; try { info = (User) jdbcTemplate.queryForObject(sql, new Object[]{username}, new BeanPropertyRowMapper(User.class)); } catch (Exception e) { e.printStackTrace(); } return info; } }
569
4,538
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <memory> #include <atomic> #include <mutex> #include <condition_variable> #include <alibabacloud/oss/http/HttpRequest.h> #include <alibabacloud/oss/http/HttpResponse.h> namespace AlibabaCloud { namespace OSS { class ALIBABACLOUD_OSS_EXPORT HttpClient { public: HttpClient(); virtual ~HttpClient(); virtual std::shared_ptr<HttpResponse> makeRequest(const std::shared_ptr<HttpRequest> &request) = 0; bool isEnable(); void disable(); void enable(); void waitForRetry(long milliseconds); protected: std::atomic<bool> disable_; std::mutex requestLock_; std::condition_variable requestSignal_; }; } }
523
571
/* * Copyright (c) 2020-2021 <NAME> <EMAIL> * zlib License, see LICENSE file. */ /* * Copyright 2005-2009 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BN_UTF8_CHARACTER_H #define BN_UTF8_CHARACTER_H /** * @file * bn::utf8_character header file. * * @ingroup text */ #include "bn_assert.h" namespace bn { /** * @brief Decodes a single UTF-8 character from a string. * * See utf8_decode_char() function in https://github.com/devkitPro/libtonc/blob/master/src/tte/tte_main.c. * * @ingroup text */ class utf8_character { public: /** * @brief Constructor. * @param text_ptr Non null pointer to the string to decode. */ constexpr explicit utf8_character(const char* text_ptr) { BN_ASSERT(text_ptr, "Text is null"); *this = utf8_character(*text_ptr); } /** * @brief Constructor. * @param text_ref Reference to the string to decode. */ constexpr explicit utf8_character(const char& text_ref) { const char* src = &text_ref; auto ch8 = unsigned(*src); if(ch8 < 0x80) { // 7bit _data = int(ch8); } else if(0xC0 <= ch8 && ch8 < 0xE0) { // 11bit _data = (*src++ & 0x1F) << 6; BN_ASSERT((*src >> 6) == 2, "Invalid UTF-8 character"); _data |= (*src++ & 0x3F) << 0; } else if(0xE0 <= ch8 && ch8 < 0xF0) { // 16bit _data = (*src++ & 0x0F) << 12; BN_ASSERT((*src >> 6) == 2, "Invalid UTF-8 character"); _data |= (*src++ & 0x3F) << 6; BN_ASSERT((*src >> 6) == 2, "Invalid UTF-8 character"); _data |= (*src++ & 0x3F) << 0; } else if(0xF0 <= ch8 && ch8 < 0xF8) { // 21bit _data = (*src++ & 0x0F) << 18; BN_ASSERT((*src >> 6) == 2, "Invalid UTF-8 character"); _data |= (*src++ & 0x3F) << 12; BN_ASSERT((*src >> 6) == 2, "Invalid UTF-8 character"); _data |= (*src++ & 0x3F) << 6; BN_ASSERT((*src >> 6) == 2, "Invalid UTF-8 character"); _data |= (*src++ & 0x3F) << 0; } else { BN_ERROR("Invalid UTF-8 character"); } _size = src - &text_ref; } /** * @brief Returns the decoded UTF-8 character. */ [[nodiscard]] constexpr int data() const { return _data; } /** * @brief Returns the size in bytes of the decoded UTF-8 character. */ [[nodiscard]] constexpr int size() const { return _size; } private: int _data = 0; int _size = 0; }; } #endif
1,650
336
#include "midi_app.h" #include "midi_desc.h" #include "midi_conf.h" typedef union { struct { u32 ALL; }; struct { u8 cin_cable; u8 evnt0; u8 evnt1; u8 evnt2; }; struct { u8 type:4; u8 cable:4; u8 chn:4; // mios32_midi_chn_t u8 event:4; // mios32_midi_event_t u8 value1; u8 value2; }; // C++ doesn't allow to redefine names in anonymous unions // as a simple workaround, we rename these redundant names struct { u8 cin:4; u8 dummy1_cable:4; u8 dummy1_chn:4; // mios32_midi_chn_t u8 dummy1_event:4; // mios32_midi_event_t u8 note:8; u8 velocity:8; }; struct { u8 dummy2_cin:4; u8 dummy2_cable:4; u8 dummy2_chn:4; // mios32_midi_chn_t u8 dummy2_event:4; // mios32_midi_event_t u8 cc_number:8; u8 value:8; }; struct { u8 dummy3_cin:4; u8 dummy3_cable:4; u8 dummy3_chn:4; // mios32_midi_chn_t u8 dummy3_event:4; // mios32_midi_event_t u8 program_change:8; u8 dummy3:8; }; } mios32_midi_package_t; typedef enum { USB0 = 0x10 } mios32_midi_port_t; const u8 mios32_midi_pcktype_num_bytes[16] = { 0, // 0: invalid/reserved event 0, // 1: invalid/reserved event 2, // 2: two-byte system common messages like MTC, Song Select, etc. 3, // 3: three-byte system common messages like SPP, etc. 3, // 4: SysEx starts or continues 1, // 5: Single-byte system common message or sysex sends with following single byte 2, // 6: SysEx sends with following two bytes 3, // 7: SysEx sends with following three bytes 3, // 8: Note Off 3, // 9: Note On 3, // a: Poly-Key Press 3, // b: Control Change 2, // c: Program Change 2, // d: Channel Pressure 3, // e: PitchBend Change 1 // f: single byte }; char* _tohex(int); char* _tox(int, int, int); /* s32 MIOS32_MIDI_SendPackageToRxCallback(mios32_midi_port_t port, mios32_midi_package_t midi_package) { dbgPrint("send: "); u8 buffer[3] = {midi_package.evnt0, midi_package.evnt1, midi_package.evnt2}; int len = mios32_midi_pcktype_num_bytes[midi_package.cin]; for(int i=0; i<len; ++i) { dbgHex(buffer[i]); } return 0; } */ DEVICE_STATE bDeviceState; void MIOS32_USB_MIDI_TxBufferHandler(void); void MIOS32_USB_MIDI_RxBufferHandler(void); void onReceive(uint_fast8_t); bool onReceiveAvailable(int); int onTransmitAvailable(); uint_fast8_t onTransmitPeek(); uint_fast8_t onTransmitGet(); //RingBuffer<uint32_t, 32> bufferReceive; /* // Rx buffer u32 rx_buffer[MIOS32_USB_MIDI_RX_BUFFER_SIZE]; volatile u16 rx_buffer_tail = 0; volatile u16 rx_buffer_head = 0; volatile u16 rx_buffer_size = 0; volatile u8 rx_buffer_new_data = 0; // Tx buffer u32 tx_buffer[MIOS32_USB_MIDI_TX_BUFFER_SIZE]; volatile u16 tx_buffer_tail = 0; volatile u16 tx_buffer_head = 0; volatile u16 tx_buffer_size = 0; */ // transfer possible? static u8 transfer_possible = 0; volatile u8 rx_buffer_new_data = 0; volatile u8 tx_buffer_busy = 1; s32 MIOS32_USB_MIDI_ChangeConnectionState(u8 connected) { // in all cases: re-initialize USB MIDI driver // clear buffer counters and busy/wait signals again (e.g., so that no invalid data will be sent out) // rx_buffer_tail = rx_buffer_head = rx_buffer_size = 0; rx_buffer_new_data = 0; // no data received yet // tx_buffer_tail = tx_buffer_head = tx_buffer_size = 0; if( connected ) { dbgPrint("[connected]"); transfer_possible = 1; tx_buffer_busy = 0; // buffer not busy anymore } else { dbgPrint("[disconnected]"); // cable disconnected: disable transfers transfer_possible = 0; tx_buffer_busy = 1; // buffer busy } return 0; // no error } s32 MIOS32_USB_MIDI_CheckAvailable(void) { return transfer_possible ? 1 : 0; } #define MEM8(addr) (*((volatile u8 *)(addr))) s32 MIOS32_SYS_SerialNumberGet(char *str) { int i; // stored in the so called "electronic signature" for(i=0; i<24; ++i) { u8 b = MEM8(0x1ffff7e8 + (i/2)); if( !(i & 1) ) b >>= 4; b &= 0x0f; str[i] = ((b > 9) ? ('A'-10) : '0') + b; } str[i] = 0; return 0; // no error } static u32 nested_ctr; static u32 prev_primask; s32 MIOS32_IRQ_Disable(void) { // get current priority if nested level == 0 if( !nested_ctr ) { __asm volatile ( \ " mrs %0, primask\n" \ : "=r" (prev_primask) \ ); } // disable interrupts __asm volatile ( \ " mov r0, #1 \n" \ " msr primask, r0\n" \ :::"r0" \ ); ++nested_ctr; return 0; // no error } s32 MIOS32_IRQ_Enable(void) { // check for nesting error if( nested_ctr == 0 ) return -1; // nesting error // decrease nesting level --nested_ctr; // set back previous priority once nested level reached 0 again if( nested_ctr == 0 ) { __asm volatile ( \ " msr primask, %0\n" \ :: "r" (prev_primask) \ ); } return 0; // no error } void MIOS32_USB_MIDI_TxBufferHandler(void) { // send buffered packages if // - last transfer finished // - new packages are in the buffer // - the device is configured // atomic operation to avoid conflict with other interrupts MIOS32_IRQ_Disable(); if( !tx_buffer_busy && onTransmitAvailable() && transfer_possible ) { // if( onTransmitAvailable() ) { u32 *pma_addr = (u32 *)(PMAAddr + (MIOS32_USB_ENDP1_TXADDR<<1)); // notify that new package is sent // copy into PMA buffer (16bit word with, only 32bit addressable) int sentSize = 0; do { while (onTransmitAvailable() && (onTransmitPeek() & 0xf0) == 0) onTransmitGet(); // ignore all if (!onTransmitAvailable()) break; mios32_midi_package_t package; package.ALL = 0; package.evnt0 = onTransmitPeek(); package.cin = package.evnt0 >> 4; int required = mios32_midi_pcktype_num_bytes[package.cin]; if (onTransmitAvailable() < required) break; // dbgPrint("["); package.evnt0 = onTransmitGet(); // dbgHex(package.evnt0); if (required >= 2) { package.evnt1 = onTransmitGet(); // dbgHex(package.evnt1); } if (required >= 3) { package.evnt2 = onTransmitGet(); // dbgHex(package.evnt2); } // dbgPrint("]"); // package.cin_cable = package.evnt0 >> 4; *pma_addr++ = package.ALL & 0xffff; *pma_addr++ = (package.ALL>>16) & 0xffff; sentSize += 4; } while( sentSize < MIOS32_USB_MIDI_DATA_IN_SIZE - 4); if (sentSize > 0) { // send to IN pipe SetEPTxCount(ENDP1, sentSize); // send buffer SetEPTxValid(ENDP1); tx_buffer_busy = 1; } } MIOS32_IRQ_Enable(); } void MIOS32_USB_MIDI_RxBufferHandler(void) { s16 count; // atomic operation to avoid conflict with other interrupts MIOS32_IRQ_Disable(); if( rx_buffer_new_data && (count=GetEPRxCount(ENDP2)/4) ) { // check if buffer is free if( onReceiveAvailable(count) ) { u32 *pma_addr = (u32 *)(PMAAddr + (MIOS32_USB_ENDP2_RXADDR<<1)); // copy received packages into receive buffer // this operation should be atomic do { u16 pl = *pma_addr++; u16 ph = *pma_addr++; mios32_midi_package_t package; package.ALL = (ph << 16) | pl; u8 buffer[3] = {package.evnt0, package.evnt1, package.evnt2}; int len = mios32_midi_pcktype_num_bytes[package.cin]; for(int i=0; i<len; ++i) onReceive(buffer[i]); } while( --count > 0 ); // notify, that data has been put into buffer rx_buffer_new_data = 0; // release OUT pipe SetEPRxValid(ENDP2); } } MIOS32_IRQ_Enable(); } s32 MIOS32_USB_ForceSingleUSB(void) { return 0; }
3,392
778
<gh_stars>100-1000 //------------------------------------------------------------- // ___ _ _ // KRATOS / __|___ _ _| |_ __ _ __| |_ // | (__/ _ \ ' \ _/ _` / _| _| // \___\___/_||_\__\__,_\__|\__|MECHANICS // // License:(BSD) ContactMechanicsApplication/license.txt // // Main authors: <NAME> // ... // //------------------------------------------------------------- // // Project Name: KratosContactMechanicsApplication $ // Created by: $Author: JMCarbonell $ // Last modified by: $Co-Author: $ // Date: $Date: July 2016 $ // Revision: $Revision: 0.0 $ // // #if !defined(KRATOS_CONTACT_MECHANICS_APPLICATION_H_INCLUDED ) #define KRATOS_CONTACT_MECHANICS_APPLICATION_H_INCLUDED // System includes #include <string> #include <iostream> // External includes // Project includes #include "includes/define.h" #include "includes/kratos_application.h" #include "includes/variables.h" // elements #include "custom_elements/rigid_body_segregated_V_element.hpp" #include "custom_elements/translatory_rigid_body_segregated_V_element.hpp" // conditions #include "custom_conditions/deformable_contact/contact_domain_condition.hpp" #include "custom_conditions/deformable_contact/contact_domain_LM_3D_condition.hpp" #include "custom_conditions/deformable_contact/contact_domain_LM_2D_condition.hpp" #include "custom_conditions/deformable_contact/contact_domain_penalty_2D_condition.hpp" #include "custom_conditions/deformable_contact/axisym_contact_domain_LM_2D_condition.hpp" #include "custom_conditions/deformable_contact/axisym_contact_domain_penalty_2D_condition.hpp" #include "custom_conditions/thermal_contact/thermal_contact_domain_penalty_2D_condition.hpp" #include "custom_conditions/thermal_contact/axisym_thermal_contact_domain_penalty_2D_condition.hpp" #include "custom_conditions/rigid_contact/point_rigid_contact_condition.hpp" #include "custom_conditions/rigid_contact/point_rigid_contact_penalty_3D_condition.hpp" #include "custom_conditions/rigid_contact/point_rigid_contact_penalty_2D_condition.hpp" #include "custom_conditions/rigid_contact/axisym_point_rigid_contact_penalty_2D_condition.hpp" #include "custom_conditions/rigid_contact/EP_point_rigid_contact_penalty_3D_condition.hpp" #include "custom_conditions/rigid_contact/EP_point_rigid_contact_penalty_2D_condition.hpp" #include "custom_conditions/rigid_contact/EP_axisym_point_rigid_contact_penalty_2D_condition.hpp" #include "custom_conditions/hydraulic_contact/hydraulic_rigid_contact_penalty_3D_condition.hpp" #include "custom_conditions/hydraulic_contact/hydraulic_axisym_rigid_contact_penalty_2D_condition.hpp" // friction laws #include "custom_friction/friction_law.hpp" #include "custom_friction/coulomb_adhesion_friction_law.hpp" #include "custom_friction/hardening_coulomb_friction_law.hpp" // rigid body links #include "custom_conditions/rigid_body_links/rigid_body_point_link_segregated_V_condition.hpp" // Core applications #include "contact_mechanics_application_variables.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ class KRATOS_API(CONTACT_MECHANICS_APPLICATION) KratosContactMechanicsApplication : public KratosApplication { public: ///@name Type Definitions ///@{ /// Pointer definition of KratosContactMechanicsApplication KRATOS_CLASS_POINTER_DEFINITION(KratosContactMechanicsApplication); ///@} ///@name Life Cycle ///@{ /// Default constructor. KratosContactMechanicsApplication(); /// Destructor. virtual ~KratosContactMechanicsApplication(){} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ void Register() override; ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "KratosContactMechanicsApplication"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); PrintData(rOStream); } ///// Print object's data. void PrintData(std::ostream& rOStream) const override { KRATOS_WATCH("in my application"); KRATOS_WATCH(KratosComponents<VariableData>::GetComponents().size() ); rOStream << "Variables:" << std::endl; KratosComponents<VariableData>().PrintData(rOStream); rOStream << std::endl; rOStream << "Elements:" << std::endl; KratosComponents<Element>().PrintData(rOStream); rOStream << std::endl; rOStream << "Conditions:" << std::endl; KratosComponents<Condition>().PrintData(rOStream); } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ // static const ApplicationCondition msApplicationCondition; ///@} ///@name Member Variables ///@{ //elements const RigidBodyElement mRigidBodyElement; const RigidBodySegregatedVElement mRigidBodySegregatedVElement; const TranslatoryRigidBodyElement mTranslatoryRigidBodyElement; const TranslatoryRigidBodyElement mTranslatoryRigidBodySegregatedVElement; //conditions const ContactDomainLM3DCondition mContactDomainLMCondition3D4N; const ContactDomainLM2DCondition mContactDomainLMCondition2D3N; const ContactDomainPenalty2DCondition mContactDomainPenaltyCondition2D3N; const AxisymContactDomainLM2DCondition mAxisymContactDomainLMCondition2D3N; const AxisymContactDomainPenalty2DCondition mAxisymContactDomainPenaltyCondition2D3N; const ThermalContactDomainPenalty2DCondition mThermalContactDomainPenaltyCondition2D3N; const AxisymThermalContactDomainPenalty2DCondition mAxisymThermalContactDomainPenaltyCondition2D3N; const PointRigidContactPenalty2DCondition mPointRigidContactPenalty2DCondition; const PointRigidContactPenalty3DCondition mPointRigidContactPenalty3DCondition; const AxisymPointRigidContactPenalty2DCondition mAxisymPointRigidContactPenalty2DCondition; const EPPointRigidContactPenalty2DCondition mEPPointRigidContactPenalty2DCondition; const EPPointRigidContactPenalty3DCondition mEPPointRigidContactPenalty3DCondition; const EPAxisymPointRigidContactPenalty2DCondition mEPAxisymPointRigidContactPenalty2DCondition; const HydraulicRigidContactPenalty3DCondition mHydraulicRigidContactPenalty3DCondition; const HydraulicAxisymRigidContactPenalty2DCondition mHydraulicAxisymRigidContactPenalty2DCondition; //friction laws const FrictionLaw mFrictionLaw; const CoulombAdhesionFrictionLaw mCoulombAdhesionFrictionLaw; const HardeningCoulombFrictionLaw mHardeningCoulombFrictionLaw; const RigidBodyPointLinkCondition mRigidBodyPointLinkCondition2D1N; const RigidBodyPointLinkCondition mRigidBodyPointLinkCondition3D1N; const RigidBodyPointLinkSegregatedVCondition mRigidBodyPointLinkSegregatedVCondition2D1N; const RigidBodyPointLinkSegregatedVCondition mRigidBodyPointLinkSegregatedVCondition3D1N; ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. KratosContactMechanicsApplication& operator=(KratosContactMechanicsApplication const& rOther); /// Copy constructor. KratosContactMechanicsApplication(KratosContactMechanicsApplication const& rOther); ///@} }; // Class KratosContactMechanicsApplication ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ ///@} } // namespace Kratos. #endif // KRATOS_CONTACT_MECHANICS_APPLICATION_H_INCLUDED defined
3,473
1,909
<filename>xchange-examples/src/main/java/org/knowm/xchange/examples/bithumb/marketdata/BithumbMarketDataDemo.java package org.knowm.xchange.examples.bithumb.marketdata; import java.io.IOException; import org.knowm.xchange.Exchange; import org.knowm.xchange.bithumb.service.BithumbMarketDataServiceRaw; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.examples.bithumb.BithumbDemoUtils; import org.knowm.xchange.service.marketdata.MarketDataService; public class BithumbMarketDataDemo { private static final CurrencyPair BTC_KRW = CurrencyPair.BTC_KRW; public static void main(String[] args) throws IOException { Exchange exchange = BithumbDemoUtils.createExchange(); MarketDataService marketDataService = exchange.getMarketDataService(); generic(marketDataService); raw((BithumbMarketDataServiceRaw) marketDataService); } private static void generic(MarketDataService marketDataService) throws IOException { System.out.println("----------GENERIC----------"); System.out.println(marketDataService.getTicker(BTC_KRW)); System.out.println(marketDataService.getTickers(null)); System.out.println(marketDataService.getOrderBook(BTC_KRW)); System.out.println(marketDataService.getTrades(BTC_KRW)); } private static void raw(BithumbMarketDataServiceRaw marketDataServiceRaw) throws IOException { System.out.println("----------RAW----------"); System.out.println(marketDataServiceRaw.getBithumbTicker(BTC_KRW)); System.out.println(marketDataServiceRaw.getBithumbTickers()); System.out.println(marketDataServiceRaw.getBithumbOrderBook(BTC_KRW)); System.out.println(marketDataServiceRaw.getBithumbTrades(BTC_KRW)); } }
559
776
package act.util; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import act.app.event.SysEventId; import java.lang.annotation.*; /** * The annotation is used on a certain method to mark it * as a callback method when a certain method has been found * by annotation class specified */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AnnotatedMethodFinder { /** * Specify the "What" to find the class, i.e. the annotation * class that has been used to tag the target class * * @return the annotation class used to find the target classes */ Class<? extends Annotation> value(); /** * Should I collect only public method? * * default value is `true` * * @return `true` if only public class shall be collected, `false` otherwise */ boolean publicOnly() default true; /** * Should I collect abstract classes? * * default value is `false` * * @return `true` if abstract classes shall be excluded, `false` otherwise */ boolean noAbstract() default true; /** * Specify when to execute the call back for a certain found class. * * By default the value of `callOn` is {@link SysEventId#DEPENDENCY_INJECTOR_PROVISIONED} * * @return the "When" to execute the callback logic */ SysEventId callOn() default SysEventId.DEPENDENCY_INJECTOR_PROVISIONED; }
656
8,772
package org.apereo.cas.util.ssl; import org.apereo.cas.configuration.model.core.util.ClientCertificateProperties; import org.apereo.cas.util.RandomUtils; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; import lombok.val; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.KeyStore; /** * An SSL utility class. * * @author <NAME> * @since 6.4.0 */ @UtilityClass public class SSLUtils { /** * Build keystore key manager factory. * * @param properties the properties * @return the key manager factory */ @SneakyThrows public static KeyManagerFactory buildKeystore(final ClientCertificateProperties properties) { try (val keyInput = properties.getCertificate().getLocation().getInputStream()) { val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); val keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(keyInput, properties.getPassphrase().toCharArray()); keyManagerFactory.init(keyStore, properties.getPassphrase().toCharArray()); return keyManagerFactory; } } /** * Build ssl context. * * @param clientCertificate the client certificate * @return the ssl context */ @SneakyThrows public static SSLContext buildSSLContext(final ClientCertificateProperties clientCertificate) { val keyManagerFactory = SSLUtils.buildKeystore(clientCertificate); val context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), null, RandomUtils.getNativeInstance()); return context; } }
614
701
#pragma once #include <brutal/io.h> #include <cc/parse.h> // FIXME: get ride of thoses ugly macros. #define ctx_lex(lexer_name, str) \ Scan _scan = {}; \ scan_init(&_scan, str); \ Lex lexer_name = clex(&_scan, test_alloc()); \ scan_assert_no_error(&_scan) #define ctx_lex_proc(lexer_name, str) \ Scan _scan = {}; \ scan_init(&_scan, str); \ Lex _source_lex = clex(&_scan, test_alloc()); \ scan_assert_no_error(&_scan); \ Lex lexer_name = cproc_file(&_source_lex, str$("test.c"), test_alloc()); \ lex_assert_no_error(&_source_lex) bool assert_lex_eq(Lex *first, Str left);
546
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.autofill_assistant; import android.support.test.InstrumentationRegistry; import org.chromium.chrome.browser.customtabs.CustomTabActivityTestRule; import org.chromium.chrome.browser.customtabs.CustomTabsTestUtils; class AutofillAssistantCustomTabTestRule extends AutofillAssistantTestRule<CustomTabActivityTestRule> { private static final String HTML_DIRECTORY = "/components/test/data/autofill_assistant/html/"; private final String mTestPage; AutofillAssistantCustomTabTestRule(CustomTabActivityTestRule testRule, String testPage) { super(testRule); mTestPage = testPage; } @Override public void startActivity() { getTestRule().startCustomTabActivityWithIntent( CustomTabsTestUtils.createMinimalCustomTabIntent( InstrumentationRegistry.getTargetContext(), getTestRule().getTestServer().getURL(HTML_DIRECTORY + mTestPage))); } @Override public void cleanupAfterTest() {} }
425
354
/* Disclaimer: This solution does not contain any header file or driver code, this only contains the class and the algorithm used in this problem. You're probably learning DS and Algo because you want to get into Competitive Programming or crack and interview, you should be acquainted with this kind of solution. TL;DR This is not the complete solution */ class Solution { public: int minTimeToVisitAllPoints(vector<vector<int>> &points) { int steps = 0; for (int i = 0; i < points.size() - 1; i++) { steps += max(abs(points[i + 1][0] - points[i][0]), abs(points[i + 1][1] - points[i][1])); } return steps; } };
239
1,861
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #import <Foundation/Foundation.h> #import <UIKit/UIImage.h> NS_ASSUME_NONNULL_BEGIN #ifdef __cplusplus extern "C" { #endif CGFloat FSPComputeSSIMFactorBetween(UIImage *left, UIImage *right); #ifdef __cplusplus } #endif NS_ASSUME_NONNULL_END
152
1,056
<reponame>Antholoj/netbeans<filename>ide/project.ant/test/unit/src/org/netbeans/spi/project/support/ant/GlobFileBuiltQueryTest.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.spi.project.support.ant; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.netbeans.api.project.ProjectManager; import org.netbeans.api.project.TestUtil; import org.netbeans.api.queries.FileBuiltQuery; import org.netbeans.junit.NbTestCase; import org.netbeans.junit.RandomlyFails; import org.netbeans.spi.queries.FileBuiltQueryImplementation; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; // XXX testChangesFromAntPropertyChanges import org.openide.util.test.MockChangeListener; import org.openide.util.test.MockLookup; /** * Test functionality of GlobFileBuiltQuery. * @author <NAME> */ public class GlobFileBuiltQueryTest extends NbTestCase { static { MockLookup.setInstances(AntBasedTestUtil.testAntBasedProjectType()); } public GlobFileBuiltQueryTest(String name) { super(name); } private FileObject scratch; private FileObject prj; private FileObject extsrc; private FileObject extbuild; private AntProjectHelper h; private FileBuiltQueryImplementation fbqi; private FileObject foo, bar, fooTest, baz, nonsense; private FileBuiltQuery.Status fooStatus, barStatus, fooTestStatus, bazStatus; protected void setUp() throws Exception { super.setUp(); scratch = TestUtil.makeScratchDir(this); prj = scratch.createFolder("prj"); h = ProjectGenerator.createProject(prj, "test"); extsrc = scratch.createFolder("extsrc"); extbuild = scratch.createFolder("extbuild"); EditableProperties ep = h.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH); ep.setProperty("src.dir", "src"); ep.setProperty("test.src.dir", "test/src"); ep.setProperty("ext.src.dir", "../extsrc"); ep.setProperty("build.classes.dir", "build/classes"); ep.setProperty("test.build.classes.dir", "build/test/classes"); ep.setProperty("ext.build.classes.dir", "../extbuild/classes"); h.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep); ProjectManager.getDefault().saveProject(ProjectManager.getDefault().findProject(prj)); foo = TestUtil.createFileFromContent(null, prj, "src/pkg/Foo.java"); bar = TestUtil.createFileFromContent(null, prj, "src/pkg/Bar.java"); fooTest = TestUtil.createFileFromContent(null, prj, "test/src/pkg/FooTest.java"); baz = TestUtil.createFileFromContent(null, extsrc, "pkg2/Baz.java"); nonsense = TestUtil.createFileFromContent(null, prj, "misc-src/whatever/Nonsense.java"); fbqi = h.createGlobFileBuiltQuery(h.getStandardPropertyEvaluator(), new String[] { "${src.dir}/*.java", "${test.src.dir}/*.java", "${ext.src.dir}/*.java", }, new String[] { "${build.classes.dir}/*.class", "${test.build.classes.dir}/*.class", "${ext.build.classes.dir}/*.class", }); fooStatus = fbqi.getStatus(foo); barStatus = fbqi.getStatus(bar); fooTestStatus = fbqi.getStatus(fooTest); bazStatus = fbqi.getStatus(baz); } /** Enough time (millisec) for file timestamps to be different. */ private static final long PAUSE = 1500; public void testBasicFunctionality() throws Exception { assertNotNull("have status for Foo.java", fooStatus); assertNotNull("have status for Bar.java", barStatus); assertNotNull("have status for FooTest.java", fooTestStatus); assertNull("non-matching file ignored", fbqi.getStatus(nonsense)); assertFalse("Foo.java not built", fooStatus.isBuilt()); assertFalse("Bar.java not built", barStatus.isBuilt()); assertFalse("FooTest.java not built", fooTestStatus.isBuilt()); FileObject fooClass = TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo.class"); assertTrue("Foo.java now built", fooStatus.isBuilt()); Thread.sleep(PAUSE); TestUtil.createFileFromContent(null, prj, "src/pkg/Foo.java"); assertFalse("Foo.class out of date", fooStatus.isBuilt()); TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo.class"); assertTrue("Foo.class rebuilt", fooStatus.isBuilt()); fooClass.delete(); assertFalse("Foo.class deleted", fooStatus.isBuilt()); TestUtil.createFileFromContent(null, prj, "build/test/classes/pkg/FooTest.class"); assertTrue("FooTest.java now built", fooTestStatus.isBuilt()); assertFalse("Bar.java still not built", barStatus.isBuilt()); TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo.class"); assertTrue("Foo.java built again", fooStatus.isBuilt()); DataObject.find(foo).setModified(true); assertFalse("Foo.java modified", fooStatus.isBuilt()); DataObject.find(foo).setModified(false); assertTrue("Foo.java unmodified again", fooStatus.isBuilt()); FileObject buildDir = prj.getFileObject("build"); assertNotNull("build dir exists", buildDir); buildDir.delete(); assertFalse("Foo.java not built (build dir gone)", fooStatus.isBuilt()); assertFalse("Bar.java still not built", barStatus.isBuilt()); assertFalse("FooTest.java not built (build dir gone)", fooTestStatus.isBuilt()); // Just to check that you can delete a source file safely: bar.delete(); barStatus.isBuilt(); } /** Maximum amount of time (in milliseconds) to wait for expected changes. */ private static final long WAIT = 10000; /** Maximum amount of time (in milliseconds) to wait for unexpected changes. */ private static final long QUICK_WAIT = 500; @RandomlyFails // NB-Core-Build #1755 public void testChangeFiring() throws Exception { MockChangeListener fooL = new MockChangeListener(); fooStatus.addChangeListener(fooL); MockChangeListener barL = new MockChangeListener(); barStatus.addChangeListener(barL); MockChangeListener fooTestL = new MockChangeListener(); fooTestStatus.addChangeListener(fooTestL); assertFalse("Foo.java not built", fooStatus.isBuilt()); FileObject fooClass = TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo.class"); fooL.msg("change in Foo.java").expectEvent(WAIT); assertTrue("Foo.java now built", fooStatus.isBuilt()); fooL.msg("no more changes in Foo.java").expectNoEvents(QUICK_WAIT); fooClass.delete(); fooL.msg("change in Foo.java").expectEvent(WAIT); assertFalse("Foo.java no longer built", fooStatus.isBuilt()); fooTestL.msg("no changes yet in FooTest.java").expectNoEvents(QUICK_WAIT); assertFalse("FooTest.java not yet built", fooTestStatus.isBuilt()); FileObject fooTestClass = TestUtil.createFileFromContent(null, prj, "build/test/classes/pkg/FooTest.class"); fooTestL.msg("change in FooTest.java").expectEvent(WAIT); assertTrue("FooTest.java now built", fooTestStatus.isBuilt()); FileObject buildDir = prj.getFileObject("build"); assertNotNull("build dir exists", buildDir); buildDir.delete(); fooL.msg("no change in Foo.java (still not built)").expectNoEvents(QUICK_WAIT); assertFalse("Foo.java not built (build dir gone)", fooStatus.isBuilt()); fooTestL.msg("got change in FooTest.java (build dir gone)").expectEvent(WAIT); assertFalse("FooTest.java not built (build dir gone)", fooTestStatus.isBuilt()); barL.msg("never got changes in Bar.java (never built)").expectNoEvents(QUICK_WAIT); TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo.class"); fooL.msg("change in Foo.class").expectEvent(WAIT); assertTrue("Foo.class created", fooStatus.isBuilt()); Thread.sleep(PAUSE); TestUtil.createFileFromContent(null, prj, "src/pkg/Foo.java"); fooL.msg("change in Foo.java").expectEvent(WAIT); assertFalse("Foo.class out of date", fooStatus.isBuilt()); TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo.class"); fooL.msg("touched Foo.class").expectEvent(WAIT); assertTrue("Foo.class touched", fooStatus.isBuilt()); DataObject.find(foo).setModified(true); fooL.msg("Foo.java modified in memory").expectEvent(WAIT); assertFalse("Foo.java modified in memory", fooStatus.isBuilt()); DataObject.find(foo).setModified(false); fooL.msg("Foo.java unmodified in memory").expectEvent(WAIT); assertTrue("Foo.java unmodified again", fooStatus.isBuilt()); File buildF = new File(FileUtil.toFile(prj), "build"); assertTrue("build dir exists", buildF.isDirectory()); TestUtil.deleteRec(buildF); assertFalse(buildF.getAbsolutePath() + " is gone", buildF.exists()); prj.getFileSystem().refresh(false); fooL.msg("build dir deleted").expectEvent(WAIT); assertFalse("Foo.class gone (no build dir)", fooStatus.isBuilt()); File pkg = new File(buildF, "classes/pkg".replace('/', File.separatorChar)); File fooClassF = new File(pkg, "Foo.class"); //System.err.println("--> going to make " + fooClassF); assertTrue("created " + pkg, pkg.mkdirs()); assertFalse("no such file yet: " + fooClassF, fooClassF.exists()); OutputStream os = new FileOutputStream(fooClassF); os.close(); prj.getFileSystem().refresh(false); fooL.msg(fooClassF.getAbsolutePath() + " created on disk").expectEvent(WAIT); assertTrue("Foo.class back", fooStatus.isBuilt()); Thread.sleep(PAUSE); TestUtil.createFileFromContent(null, prj, "src/pkg/Foo.java"); fooL.msg("change in Foo.java").expectEvent(WAIT); assertFalse("Foo.class out of date", fooStatus.isBuilt()); os = new FileOutputStream(fooClassF); os.write(69); // force Mac OS X to update timestamp os.close(); prj.getFileSystem().refresh(false); fooL.msg("Foo.class recreated on disk").expectEvent(WAIT); assertTrue("Foo.class touched", fooStatus.isBuilt()); } public void testExternalSourceRoots() throws Exception { // Cf. #43609. assertNotNull("have status for Baz.java", bazStatus); MockChangeListener bazL = new MockChangeListener(); bazStatus.addChangeListener(bazL); assertFalse("Baz.java not built", bazStatus.isBuilt()); FileObject bazClass = TestUtil.createFileFromContent(null, extbuild, "classes/pkg2/Baz.class"); bazL.msg("got change").expectEvent(WAIT); assertTrue("Baz.java now built", bazStatus.isBuilt()); Thread.sleep(PAUSE); TestUtil.createFileFromContent(null, extsrc, "pkg2/Baz.java"); bazL.msg("got change").expectEvent(WAIT); assertFalse("Baz.class out of date", bazStatus.isBuilt()); TestUtil.createFileFromContent(null, extbuild, "classes/pkg2/Baz.class"); bazL.msg("got change").expectEvent(WAIT); assertTrue("Baz.class rebuilt", bazStatus.isBuilt()); bazClass.delete(); bazL.msg("got change").expectEvent(WAIT); assertFalse("Baz.class deleted", bazStatus.isBuilt()); TestUtil.createFileFromContent(null, extbuild, "classes/pkg2/Baz.class"); bazL.msg("got change").expectEvent(WAIT); assertTrue("Baz.java built again", bazStatus.isBuilt()); DataObject.find(baz).setModified(true); bazL.msg("got change").expectEvent(WAIT); assertFalse("Baz.java modified", bazStatus.isBuilt()); DataObject.find(baz).setModified(false); bazL.msg("got change").expectEvent(WAIT); assertTrue("Baz.java unmodified again", bazStatus.isBuilt()); extbuild.delete(); bazL.msg("got change").expectEvent(WAIT); assertFalse("Baz.java not built (build dir gone)", bazStatus.isBuilt()); } public void testFileRenames() throws Exception { // Cf. #45694. assertNotNull("have status for Foo.java", fooStatus); MockChangeListener fooL = new MockChangeListener(); fooStatus.addChangeListener(fooL); assertFalse("Foo.java not built", fooStatus.isBuilt()); FileObject fooClass = TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo.class"); fooL.msg("got change").expectEvent(WAIT); assertTrue("Foo.java now built", fooStatus.isBuilt()); FileLock lock = foo.lock(); try { foo.rename(lock, "Foo2", "java"); } finally { lock.releaseLock(); } fooL.msg("got change").expectEvent(WAIT); assertFalse("Foo2.java no longer built", fooStatus.isBuilt()); fooClass = TestUtil.createFileFromContent(null, prj, "build/classes/pkg/Foo2.class"); fooL.msg("got change").expectEvent(WAIT); assertTrue("Now Foo2.java is built", fooStatus.isBuilt()); } /**See issue #66713. */ public void testInvalidFile() throws Exception { FileObject baz = TestUtil.createFileFromContent(null, prj, "src/pkg/Baz.java"); baz.delete(); assertNull(fbqi.getStatus(baz)); } }
5,590
778
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: <NAME> // // System includes // External includes // Project includes #include "includes/gid_io.h" namespace Kratos { GidIOBase& GidIOBase::GetInstance() { if (mpInstance == nullptr) { Create(); } return *mpInstance; } void GidIOBase::Create() { static GidIOBase gid_io_base; mpInstance = &gid_io_base; } int GidIOBase::GetData() { return this -> data; } void GidIOBase::SetData(int data) { this -> data = data; } GidIOBase* GidIOBase::mpInstance = nullptr; // GidIO default instantiation template class GidIO<GidGaussPointsContainer,GidMeshContainer>; } // namespace Kratos.
467
14,668
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_APPS_PLATFORM_APPS_API_WEBSTORE_WIDGET_PRIVATE_WEBSTORE_WIDGET_PRIVATE_API_H_ #define CHROME_BROWSER_APPS_PLATFORM_APPS_API_WEBSTORE_WIDGET_PRIVATE_WEBSTORE_WIDGET_PRIVATE_API_H_ #include <string> #include "chrome/common/extensions/webstore_install_result.h" #include "extensions/browser/extension_function.h" namespace chrome_apps { namespace api { class WebstoreWidgetPrivateInstallWebstoreItemFunction : public ExtensionFunction { public: WebstoreWidgetPrivateInstallWebstoreItemFunction(); WebstoreWidgetPrivateInstallWebstoreItemFunction( const WebstoreWidgetPrivateInstallWebstoreItemFunction&) = delete; WebstoreWidgetPrivateInstallWebstoreItemFunction& operator=( const WebstoreWidgetPrivateInstallWebstoreItemFunction&) = delete; DECLARE_EXTENSION_FUNCTION("webstoreWidgetPrivate.installWebstoreItem", WEBSTOREWIDGETPRIVATE_INSTALLWEBSTOREITEM) protected: ~WebstoreWidgetPrivateInstallWebstoreItemFunction() override; // ExtensionFunction overrides. ResponseAction Run() override; private: void OnInstallComplete(bool success, const std::string& error, extensions::webstore_install::Result result); }; } // namespace api } // namespace chrome_apps #endif // CHROME_BROWSER_APPS_PLATFORM_APPS_API_WEBSTORE_WIDGET_PRIVATE_WEBSTORE_WIDGET_PRIVATE_API_H_
568
2,389
{ "compilerOptions": { "composite": true }, "files": [ "package/addon/comment/comment.js", "package/addon/edit/closebrackets.js", "package/addon/edit/matchbrackets.js", "package/addon/fold/brace-fold.js", "package/addon/fold/foldcode.js", "package/addon/fold/foldgutter.js", "package/addon/mode/multiplex.js", "package/addon/mode/overlay.js", "package/addon/mode/simple.js", "package/addon/runmode/runmode-standalone.js", "package/addon/selection/active-line.js", "package/addon/selection/mark-selection.js", "package/lib/codemirror.js", "package/mode/clike/clike.js", "package/mode/clojure/clojure.js", "package/mode/coffeescript/coffeescript.js", "package/mode/css/css.js", "package/mode/htmlembedded/htmlembedded.js", "package/mode/htmlmixed/htmlmixed.js", "package/mode/javascript/javascript.js", "package/mode/jsx/jsx.js", "package/mode/livescript/livescript.js", "package/mode/markdown/markdown.js", "package/mode/php/php.js", "package/mode/python/python.js", "package/mode/shell/shell.js", "package/mode/wast/wast.js", "package/mode/xml/xml.js" ] }
504
6,098
package water.jdbc; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.math.BigDecimal; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.concurrent.TimeUnit; import water.fvec.NewChunk; import water.parser.BufferedString; /** * Chunk access patterns benchmark */ @State(Scope.Thread) //@Fork(value = 1, jvmArgsAppend = "-XX:+PrintCompilation") @Fork(value = 1, jvmArgsAppend = "-Xmx12g") @Warmup(iterations = 5) @Measurement(iterations = 10) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) public class SQLManagerBench { @Param({"100", "10000"}) private int rows; @Param({"true", "false"}) private boolean useRef; private NewChunk nc; private Double[] doubles; private String[] strings; @Setup public void setup() { nc = new NewChunk(new double[0]) { @Override public void addNum(double d) { // do nothing } @Override public void addStr(Object str) { // do nothing } }; doubles = new Double[rows]; strings = new String[rows]; for (int i = 0; i < rows; i++) { doubles[i] = i / (double) rows; strings[i] = doubles[i].toString(); } } @Benchmark public double writeItem_double() { Double sum = 0.0; for (Double d : doubles) { writeItem(d, nc); sum += d; } return sum; } @Benchmark public String writeItem_string() { String result = null; for (String s : strings) { writeItem(s, nc); result = s; } return result; } @Benchmark public double writeItem_mix() { Double sum = 0.0; for (int i = 0; i < doubles.length; i++) { writeItem(doubles[i], nc); writeItem(strings[i], nc); sum += doubles[i]; } return sum; } private void writeItem(Object res, NewChunk nc) { if (useRef) { writeItem_ref(res, nc); } else { SQLManager.SqlTableToH2OFrame.writeItem(res, nc); } } // old, "reference" implementation private static void writeItem_ref(Object res, NewChunk nc) { if (res == null) nc.addNA(); else { switch (res.getClass().getSimpleName()) { case "Double": nc.addNum((double) res); break; case "Integer": nc.addNum((long) (int) res, 0); break; case "Long": nc.addNum((long) res, 0); break; case "Float": nc.addNum((double) (float) res); break; case "Short": nc.addNum((long) (short) res, 0); break; case "Byte": nc.addNum((long) (byte) res, 0); break; case "BigDecimal": nc.addNum(((BigDecimal) res).doubleValue()); break; case "Boolean": nc.addNum(((boolean) res ? 1 : 0), 0); break; case "String": nc.addStr(new BufferedString((String) res)); break; case "Date": nc.addNum(((Date) res).getTime(), 0); break; case "Time": nc.addNum(((Time) res).getTime(), 0); break; case "Timestamp": nc.addNum(((Timestamp) res).getTime(), 0); break; default: nc.addNA(); } } } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(SQLManagerBench.class.getSimpleName()) .addProfiler(StackProfiler.class) // .addProfiler(GCProfiler.class) .build(); new Runner(opt).run(); } }
1,935
432
int Bar(int value);
7
372
<reponame>noisecode3/DPF<gh_stars>100-1000 /* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2021 <NAME> <<EMAIL>> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "tests.hpp" #define DPF_TEST_POINT_CPP #include "dgl/src/Geometry.cpp" // -------------------------------------------------------------------------------------------------------------------- template <typename T> static int runTestsPerType() { USE_NAMESPACE_DGL; // basic usage { Point<T> p; DISTRHO_ASSERT_EQUAL(p.getX(), 0, "point start X value is 0"); DISTRHO_ASSERT_EQUAL(p.getY(), 0, "point start Y value is 0"); DISTRHO_ASSERT_EQUAL(p.isZero(), true, "point start is zero"); DISTRHO_ASSERT_EQUAL(p.isNotZero(), false, "point start is for sure zero"); p.setX(5); DISTRHO_ASSERT_EQUAL(p.getX(), 5, "point X value changed to 5"); DISTRHO_ASSERT_EQUAL(p.getY(), 0, "point start Y value remains 0"); DISTRHO_ASSERT_EQUAL(p.isZero(), false, "point after custom X is not zero"); DISTRHO_ASSERT_EQUAL(p.isNotZero(), true, "point after custom X is for sure not zero"); p.setY(7); DISTRHO_ASSERT_EQUAL(p.getX(), 5, "point X value remains 5"); DISTRHO_ASSERT_EQUAL(p.getY(), 7, "point Y value changed to 7"); DISTRHO_ASSERT_EQUAL(p.isZero(), false, "point after custom X and Y is not zero"); DISTRHO_ASSERT_EQUAL(p.isNotZero(), true, "point after custom X and Y is for sure not zero"); // TODO everything else } return 0; } int main() { if (const int ret = runTestsPerType<double>()) return ret; if (const int ret = runTestsPerType<float>()) return ret; if (const int ret = runTestsPerType<int>()) return ret; if (const int ret = runTestsPerType<uint>()) return ret; if (const int ret = runTestsPerType<short>()) return ret; if (const int ret = runTestsPerType<ushort>()) return ret; if (const int ret = runTestsPerType<long>()) return ret; if (const int ret = runTestsPerType<ulong>()) return ret; if (const int ret = runTestsPerType<long long>()) return ret; if (const int ret = runTestsPerType<unsigned long long>()) return ret; return 0; } // --------------------------------------------------------------------------------------------------------------------
1,149
14,499
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "Bicycle.h" int ProtocolProcdescMain() { Bicycle* bike = [Bicycle alloc]; [bike signalStop]; return 0; }
93
601
<reponame>ZhongFuCheng3y/austin<filename>austin-common/src/main/java/com/java3y/austin/common/enums/SendMessageType.java package com.java3y.austin.common.enums; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.ToString; /** * 微信应用消息/钉钉/服务号均有多种的消息类型下发 * * @author 3y */ @Getter @ToString @AllArgsConstructor public enum SendMessageType { TEXT("10", "文本", "text"), VOICE("20", "语音", null), VIDEO("30", "视频", null), NEWS("40", "图文", "feedCard"), TEXT_CARD("50", "文本卡片", null), FILE("60", "文件", null), MINI_PROGRAM_NOTICE("70", "小程序通知", null), MARKDOWN("80", "markdown", "markdown"), TEMPLATE_CARD("90", "模板卡片", null), IMAGE("100", "图片", null), LINK("110", "链接消息", "link"), ACTION_CARD("120", "跳转卡片消息", "actionCard"), ; private String code; private String description; private String dingDingRobotType; /** * 通过code获取钉钉的Type值 * * @param code * @return */ public static String getDingDingRobotTypeByCode(String code) { for (SendMessageType value : SendMessageType.values()) { if (value.getCode().equals(code)) { return value.getDingDingRobotType(); } } return null; } }
688
707
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #ifndef WPIUTIL_WPI_HOSTNAME_H_ #define WPIUTIL_WPI_HOSTNAME_H_ #include <string> #include <string_view> namespace wpi { template <typename T> class SmallVectorImpl; std::string GetHostname(); std::string_view GetHostname(SmallVectorImpl<char>& name); } // namespace wpi #endif // WPIUTIL_WPI_HOSTNAME_H_
178
1,508
<gh_stars>1000+ package org.knowm.xchange.ascendex.dto.account; import com.fasterxml.jackson.annotation.JsonProperty; import java.math.BigDecimal; public class AscendexCashAccountBalanceDto { private final String asset; private final BigDecimal totalBalance; private final BigDecimal availableBalance; public AscendexCashAccountBalanceDto( @JsonProperty("asset") String asset, @JsonProperty("totalBalance") BigDecimal totalBalance, @JsonProperty("availableBalance") BigDecimal availableBalance) { this.asset = asset; this.totalBalance = totalBalance; this.availableBalance = availableBalance; } public String getAsset() { return asset; } public BigDecimal getTotalBalance() { return totalBalance; } public BigDecimal getAvailableBalance() { return availableBalance; } @Override public String toString() { return "AscendexCashAccountBalanceDto{" + "asset='" + asset + '\'' + ", totalBalance=" + totalBalance + ", availableBalance=" + availableBalance + '}'; } }
394
648
{"resourceType":"DataElement","id":"instant","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00"},"url":"http://hl7.org/fhir/DataElement/instant","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"id":"instant","path":"instant","short":"Primitive Type instant","definition":"An instant in time - known at least to the second","comment":"Note: This is intended for precisely observed times, typically system logs etc., and not human-reported times - for them, see date and dateTime below. Time zone is always required","min":0,"max":"*","constraint":[{"key":"ele-1","severity":"error","human":"All FHIR elements must have a @value or children","expression":"hasValue() | (children().count() > id.count())","xpath":"@value|f:*|h:div","source":"Element"}]}]}
218
7,782
package com.baidu.paddledetection.detection; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.baidu.paddledetection.common.Utils; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.io.File; import java.io.IOException; import java.io.InputStream; import static android.app.Activity.RESULT_OK; public class PhotoFragment extends Fragment implements View.OnClickListener{ private static final String TAG = PhotoFragment.class.getSimpleName(); public static final int OPEN_GALLERY_REQUEST_CODE = 0; public static final int TAKE_PHOTO_REQUEST_CODE = 1; public static final int REQUEST_LOAD_MODEL = 0; public static final int REQUEST_RUN_MODEL = 1; public static final int RESPONSE_LOAD_MODEL_SUCCESSED = 0; public static final int RESPONSE_LOAD_MODEL_FAILED = 1; public static final int RESPONSE_RUN_MODEL_SUCCESSED = 2; public static final int RESPONSE_RUN_MODEL_FAILED = 3; protected ProgressDialog pbLoadModel = null; protected ProgressDialog pbRunModel = null; public Handler receiver = null; // Receive messages from worker thread protected Handler sender = null; // Send command to worker thread protected HandlerThread worker = null; // Worker thread to load&run model // UI components of object detection protected TextView tvInputSetting; protected ImageView ivInputImage; protected TextView tvOutputResult; protected TextView tvInferenceTime; // Model settings of object detection protected String modelPath = ""; protected String labelPath = ""; protected String imagePath = ""; protected int cpuThreadNum = 1; protected String cpuPowerMode = ""; protected String inputColorFormat = ""; protected long[] inputShape = new long[]{}; protected float[] inputMean = new float[]{}; protected float[] inputStd = new float[]{}; protected float scoreThreshold = 0.5f; protected Predictor predictor = new Predictor(); @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_photo, container, false); } public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Prepare the worker thread for mode loading and inference receiver = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESPONSE_LOAD_MODEL_SUCCESSED: pbLoadModel.dismiss(); onLoadModelSuccessed(); break; case RESPONSE_LOAD_MODEL_FAILED: pbLoadModel.dismiss(); Toast.makeText(getActivity(), "Load model failed!", Toast.LENGTH_SHORT).show(); onLoadModelFailed(); break; case RESPONSE_RUN_MODEL_SUCCESSED: pbRunModel.dismiss(); onRunModelSuccessed(); break; case RESPONSE_RUN_MODEL_FAILED: pbRunModel.dismiss(); Toast.makeText(getActivity(), "Run model failed!", Toast.LENGTH_SHORT).show(); onRunModelFailed(); break; default: break; } } }; worker = new HandlerThread("Predictor Worker"); worker.start(); sender = new Handler(worker.getLooper()) { public void handleMessage(Message msg) { switch (msg.what) { case REQUEST_LOAD_MODEL: // Load model and reload test image if (onLoadModel()) { receiver.sendEmptyMessage(RESPONSE_LOAD_MODEL_SUCCESSED); } else { receiver.sendEmptyMessage(RESPONSE_LOAD_MODEL_FAILED); } break; case REQUEST_RUN_MODEL: // Run model if model is loaded if (onRunModel()) { receiver.sendEmptyMessage(RESPONSE_RUN_MODEL_SUCCESSED); } else { receiver.sendEmptyMessage(RESPONSE_RUN_MODEL_FAILED); } break; default: break; } } }; initView(view); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_input_image: break; } } public void initView(@NonNull View view) { // Setup the UI components tvInputSetting = view.findViewById(R.id.tv_input_setting); ivInputImage = view.findViewById(R.id.iv_input_image); ivInputImage.setOnClickListener(this); tvInferenceTime = view.findViewById(R.id.tv_inference_time); tvOutputResult = view.findViewById(R.id.tv_output_result); tvInputSetting.setMovementMethod(ScrollingMovementMethod.getInstance()); tvOutputResult.setMovementMethod(ScrollingMovementMethod.getInstance()); FloatingActionButton fab = view.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openGallery(); // You can take photo // takePhoto(); } }); } public void loadModel() { pbLoadModel = ProgressDialog.show(getActivity(), "", "Loading model...", false, false); sender.sendEmptyMessage(REQUEST_LOAD_MODEL); } public void runModel() { pbRunModel = ProgressDialog.show(getActivity(), "", "Running model...", false, false); sender.sendEmptyMessage(REQUEST_RUN_MODEL); Log.i(TAG, "开始运行模型5555555555555"); } public boolean onLoadModel() { return predictor.init(getActivity(), modelPath, labelPath, cpuThreadNum, cpuPowerMode, inputColorFormat, inputShape, inputMean, inputStd, scoreThreshold); } public boolean onRunModel() { return predictor.isLoaded() && predictor.runModel(); } public void onLoadModelSuccessed() { // Load test image from path and run model try { if (imagePath.isEmpty()) { return; } Bitmap image = null; // Read test image file from custom path if the first character of mode path is '/', otherwise read test // image file from assets if (!imagePath.substring(0, 1).equals("/")) { InputStream imageStream = getActivity().getAssets().open(imagePath); image = BitmapFactory.decodeStream(imageStream); } else { if (!new File(imagePath).exists()) { return; } image = BitmapFactory.decodeFile(imagePath); } if (image != null && predictor.isLoaded()) { predictor.setInputImage(image); runModel(); } } catch (IOException e) { Toast.makeText(getActivity(), "Load image failed!", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } public void onLoadModelFailed() { } public void onRunModelSuccessed() { // Obtain results and update UI tvInferenceTime.setText("Inference time: " + predictor.inferenceTime() + " ms"); Bitmap outputImage = predictor.outputImage(); if (outputImage != null) { ivInputImage.setImageBitmap(outputImage); } tvOutputResult.setText(predictor.outputResult()); tvOutputResult.scrollTo(0, 0); } public void onRunModelFailed() {} public void onImageChanged(Bitmap image) { // Rerun model if users pick test image from gallery or camera if (image != null && predictor.isLoaded()) { predictor.setInputImage(image); runModel(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && data != null) { switch (requestCode) { case OPEN_GALLERY_REQUEST_CODE: try { ContentResolver resolver = getActivity().getContentResolver(); Uri uri = data.getData(); Bitmap image = MediaStore.Images.Media.getBitmap(resolver, uri); String[] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = getActivity().managedQuery(uri, proj, null, null, null); cursor.moveToFirst(); onImageChanged(image); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case TAKE_PHOTO_REQUEST_CODE: Bundle extras = data.getExtras(); Bitmap image = (Bitmap) extras.get("data"); onImageChanged(image); break; default: break; } } } private void openGallery() { Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, OPEN_GALLERY_REQUEST_CODE); } private void takePhoto() { Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePhotoIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST_CODE); } } @Override public void onResume() { super.onResume(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); boolean settingsChanged = false; String model_path = sharedPreferences.getString("NULL", getString(R.string.MODEL_PATH_DEFAULT)); String label_path = sharedPreferences.getString(getString(R.string.LABEL_PATH_KEY), getString(R.string.SSD_LABEL_PATH_DEFAULT)); String image_path = sharedPreferences.getString("NULL", getString(R.string.IMAGE_PATH_DEFAULT)); settingsChanged |= !model_path.equalsIgnoreCase(modelPath); settingsChanged |= !label_path.equalsIgnoreCase(labelPath); settingsChanged |= !image_path.equalsIgnoreCase(imagePath); int cpu_thread_num = Integer.parseInt(sharedPreferences.getString(getString(R.string.CPU_THREAD_NUM_KEY), getString(R.string.CPU_THREAD_NUM_DEFAULT))); settingsChanged |= cpu_thread_num != cpuThreadNum; String cpu_power_mode = sharedPreferences.getString(getString(R.string.CPU_POWER_MODE_KEY), getString(R.string.CPU_POWER_MODE_DEFAULT)); settingsChanged |= !cpu_power_mode.equalsIgnoreCase(cpuPowerMode); String input_color_format = sharedPreferences.getString("NULL", getString(R.string.INPUT_COLOR_FORMAT_DEFAULT)); settingsChanged |= !input_color_format.equalsIgnoreCase(inputColorFormat); long[] input_shape = Utils.parseLongsFromString(sharedPreferences.getString("NULL", getString(R.string.INPUT_SHAPE_DEFAULT)), ","); float[] input_mean = Utils.parseFloatsFromString(sharedPreferences.getString(getString(R.string.INPUT_MEAN_KEY), getString(R.string.INPUT_MEAN_DEFAULT)), ","); float[] input_std = Utils.parseFloatsFromString(sharedPreferences.getString(getString(R.string.INPUT_STD_KEY) , getString(R.string.INPUT_STD_DEFAULT)), ","); settingsChanged |= input_shape.length != inputShape.length; settingsChanged |= input_mean.length != inputMean.length; settingsChanged |= input_std.length != inputStd.length; if (!settingsChanged) { for (int i = 0; i < input_shape.length; i++) { settingsChanged |= input_shape[i] != inputShape[i]; } for (int i = 0; i < input_mean.length; i++) { settingsChanged |= input_mean[i] != inputMean[i]; } for (int i = 0; i < input_std.length; i++) { settingsChanged |= input_std[i] != inputStd[i]; } } float score_threshold = Float.parseFloat(sharedPreferences.getString(getString(R.string.SCORE_THRESHOLD_KEY), getString(R.string.SSD_SCORE_THRESHOLD_DEFAULT))); settingsChanged |= scoreThreshold != score_threshold; if (settingsChanged) { modelPath = model_path; labelPath = label_path; imagePath = image_path; cpuThreadNum = cpu_thread_num; cpuPowerMode = cpu_power_mode; inputColorFormat = input_color_format; inputShape = input_shape; inputMean = input_mean; inputStd = input_std; scoreThreshold = score_threshold; // Update UI tvInputSetting.setText("Model: " + modelPath.substring(modelPath.lastIndexOf("/") + 1) + "\n" + "CPU" + " Thread Num: " + Integer.toString(cpuThreadNum) + "\n" + "CPU Power Mode: " + cpuPowerMode); tvInputSetting.scrollTo(0, 0); // Reload model if configure has been changed loadModel(); } } @Override public void onDestroy() { if (predictor != null) { predictor.releaseModel(); } worker.quit(); super.onDestroy(); } }
6,998
892
<filename>advisories/unreviewed/2022/03/GHSA-qh5r-mghj-xj6g/GHSA-qh5r-mghj-xj6g.json<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-qh5r-mghj-xj6g", "modified": "2022-04-05T00:00:46Z", "published": "2022-03-29T00:01:08Z", "aliases": [ "CVE-2017-20012" ], "details": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability classified as problematic has been found in WEKA INTEREST Security Scanner up to 1.8. Affected is Stresstest Scheme Handler which leads to a denial of service. The attack needs to be approached locally. The exploit has been disclosed to the public and may be used. NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-20012" }, { "type": "WEB", "url": "https://vuldb.com/?id.101969" }, { "type": "WEB", "url": "https://vuldb.com/?id.101970" }, { "type": "WEB", "url": "http://www.computec.ch/news.php?item.117" } ], "database_specific": { "cwe_ids": [ "CWE-404" ], "severity": "MODERATE", "github_reviewed": false } }
621
1,391
<gh_stars>1000+ #include <u.h> #include <libc.h> #include <bio.h> #include <ndb.h> #include <ip.h> #include "dat.h" extern char *binddir; long now; char *blog = "ipboot"; int minlease = MinLease; void main(void) { Dir *all; int i, nall, fd; Binding b; fmtinstall('E', eipfmt); fmtinstall('I', eipfmt); fmtinstall('V', eipfmt); fmtinstall('M', eipfmt); fd = open(binddir, OREAD); if(fd < 0) sysfatal("opening %s: %r", binddir); nall = dirreadall(fd, &all); if(nall < 0) sysfatal("reading %s: %r", binddir); close(fd); b.boundto = 0; b.lease = b.offer = 0; now = time(0); for(i = 0; i < nall; i++){ parseip(b.ip, all[i].name); if(syncbinding(&b, 0) < 0) continue; if(b.lease > now) print("%I leased by %s until %s", b.ip, b.boundto, ctime(b.lease)); } }
392
3,756
<reponame>LeoTafti/darts """Downloading data from the M4 competition """ import os import requests def download(datapath, url, name, split=None): os.makedirs(datapath, exist_ok=True) if split is not None: namesplit = split + "/" + name else: namesplit = name url = url.format(namesplit) file_path = os.path.join(datapath, name) + ".csv" if os.path.exists(file_path): print(name+" already exists") return print('Downloading ' + url) r = requests.get(url, stream=True) with open(file_path, 'wb') as f: for chunk in r.iter_content(chunk_size=16 * 1024 ** 2): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return if __name__ == "__main__": data_frequencies = ['Yearly', 'Quarterly', 'Monthly', 'Weekly', 'Daily', 'Hourly'] datapath = "./dataset/" url = "https://github.com/Mcompetitions/M4-methods/raw/master/Dataset/{}.csv" download(datapath, url, 'M4-info') for freq in data_frequencies: for split in ['train', 'test']: download(datapath+split, url, '{}-{}'.format(freq, split), split.capitalize())
539
14,668
<reponame>zealoussnow/chromium // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include "ash/public/cpp/test/test_image_downloader.h" #include "base/bind.h" #include "base/callback.h" #include "base/threading/sequenced_task_runner_handle.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_unittest_util.h" namespace ash { TestImageDownloader::TestImageDownloader() = default; TestImageDownloader::~TestImageDownloader() = default; void TestImageDownloader::Download( const GURL& url, const net::NetworkTrafficAnnotationTag& annotation_tag, DownloadCallback callback) { Download(url, annotation_tag, /*additional_headers=*/{}, std::move(callback)); } void TestImageDownloader::Download( const GURL& url, const net::NetworkTrafficAnnotationTag& annotation_tag, const net::HttpRequestHeaders& additional_headers, DownloadCallback callback) { last_request_headers_ = additional_headers; // Pretend to respond asynchronously. base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), should_fail_ ? gfx::ImageSkia() : gfx::test::CreateImageSkia( /*width=*/10, /*height=*/20))); } } // namespace ash
545
4,772
<filename>jpa/deferred/src/main/java/example/repo/Customer1627Repository.java<gh_stars>1000+ package example.repo; import example.model.Customer1627; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1627Repository extends CrudRepository<Customer1627, Long> { List<Customer1627> findByLastName(String lastName); }
122
696
<reponame>hwang-pku/Strata<gh_stars>100-1000 /* * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.collect.array; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleUnaryOperator; import java.util.function.IntToDoubleFunction; import java.util.stream.DoubleStream; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.ImmutableBean; import org.joda.beans.MetaBean; import org.joda.beans.MetaProperty; import org.joda.beans.PropertyStyle; import org.joda.beans.impl.BasicImmutableBeanBuilder; import org.joda.beans.impl.BasicMetaBean; import org.joda.beans.impl.BasicMetaProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.primitives.Doubles; import com.opengamma.strata.collect.ArgChecker; import com.opengamma.strata.collect.DoubleArrayMath; import com.opengamma.strata.collect.function.DoubleTernaryOperator; import com.opengamma.strata.collect.function.IntDoubleConsumer; import com.opengamma.strata.collect.function.IntDoubleToDoubleFunction; /** * An immutable array of {@code double} values. * <p> * This provides functionality similar to {@link List} but for {@code double[]}. * <p> * In mathematical terms, this is a vector, or one-dimensional matrix. */ public final class DoubleArray implements Matrix, ImmutableBean, Serializable { /** * An empty array. */ public static final DoubleArray EMPTY = new DoubleArray(new double[0]); /** * Serialization version. */ private static final long serialVersionUID = 1L; static { MetaBean.register(Meta.META); } /** * The underlying array of doubles. */ private final double[] array; //------------------------------------------------------------------------- /** * Obtains an empty immutable array. * * @return the empty immutable array */ public static DoubleArray of() { return EMPTY; } /** * Obtains an immutable array with a single value. * * @param value the single value * @return an array containing the specified value */ public static DoubleArray of(double value) { return new DoubleArray(new double[] {value}); } /** * Obtains an immutable array with two values. * * @param value1 the first value * @param value2 the second value * @return an array containing the specified values */ public static DoubleArray of(double value1, double value2) { return new DoubleArray(new double[] {value1, value2}); } /** * Obtains an immutable array with three values. * * @param value1 the first value * @param value2 the second value * @param value3 the third value * @return an array containing the specified values */ public static DoubleArray of(double value1, double value2, double value3) { return new DoubleArray(new double[] {value1, value2, value3}); } /** * Obtains an immutable array with four values. * * @param value1 the first value * @param value2 the second value * @param value3 the third value * @param value4 the fourth value * @return an array containing the specified values */ public static DoubleArray of(double value1, double value2, double value3, double value4) { return new DoubleArray(new double[] {value1, value2, value3, value4}); } /** * Obtains an immutable array with five values. * * @param value1 the first value * @param value2 the second value * @param value3 the third value * @param value4 the fourth value * @param value5 the fifth value * @return an array containing the specified values */ public static DoubleArray of( double value1, double value2, double value3, double value4, double value5) { return new DoubleArray(new double[] {value1, value2, value3, value4, value5}); } /** * Obtains an immutable array with six values. * * @param value1 the first value * @param value2 the second value * @param value3 the third value * @param value4 the fourth value * @param value5 the fifth value * @param value6 the sixth value * @return an array containing the specified values */ public static DoubleArray of( double value1, double value2, double value3, double value4, double value5, double value6) { return new DoubleArray(new double[] {value1, value2, value3, value4, value5, value6}); } /** * Obtains an immutable array with seven values. * * @param value1 the first value * @param value2 the second value * @param value3 the third value * @param value4 the fourth value * @param value5 the fifth value * @param value6 the sixth value * @param value7 the seventh value * @return an array containing the specified values */ public static DoubleArray of( double value1, double value2, double value3, double value4, double value5, double value6, double value7) { return new DoubleArray(new double[] {value1, value2, value3, value4, value5, value6, value7}); } /** * Obtains an immutable array with eight values. * * @param value1 the first value * @param value2 the second value * @param value3 the third value * @param value4 the fourth value * @param value5 the fifth value * @param value6 the sixth value * @param value7 the seventh value * @param value8 the eighth value * @return an array containing the specified values */ public static DoubleArray of( double value1, double value2, double value3, double value4, double value5, double value6, double value7, double value8) { return new DoubleArray(new double[] {value1, value2, value3, value4, value5, value6, value7, value8}); } /** * Obtains an immutable array with more than eight values. * * @param value1 the first value * @param value2 the second value * @param value3 the third value * @param value4 the fourth value * @param value5 the fifth value * @param value6 the sixth value * @param value7 the seventh value * @param value8 the eighth value * @param otherValues the other values * @return an array containing the specified values */ public static DoubleArray of( double value1, double value2, double value3, double value4, double value5, double value6, double value7, double value8, double... otherValues) { double[] base = new double[otherValues.length + 8]; base[0] = value1; base[1] = value2; base[2] = value3; base[3] = value4; base[4] = value5; base[5] = value6; base[6] = value7; base[7] = value8; System.arraycopy(otherValues, 0, base, 8, otherValues.length); return new DoubleArray(base); } //------------------------------------------------------------------------- /** * Obtains an instance with entries filled using a function. * <p> * The function is passed the array index and returns the value for that index. * * @param size the number of elements * @param valueFunction the function used to populate the value * @return an array initialized using the function */ public static DoubleArray of(int size, IntToDoubleFunction valueFunction) { if (size == 0) { return EMPTY; } double[] array = new double[size]; Arrays.setAll(array, valueFunction); return new DoubleArray(array); } /** * Obtains an instance with entries filled from a stream. * <p> * The stream is converted to an array using {@link DoubleStream#toArray()}. * * @param stream the stream of elements * @return an array initialized using the stream */ public static DoubleArray of(DoubleStream stream) { return ofUnsafe(stream.toArray()); } /** * Obtains an instance by wrapping an array. * <p> * This method is inherently unsafe as it relies on good behavior by callers. * Callers must never make any changes to the passed in array after calling this method. * Doing so would violate the immutability of this class. * * @param array the array to assign * @return an array instance wrapping the specified array */ public static DoubleArray ofUnsafe(double[] array) { if (array.length == 0) { return EMPTY; } return new DoubleArray(array); } //----------------------------------------------------------------------- /** * Obtains an instance from a collection of {@code Double}. * <p> * The order of the values in the returned array is the order in which elements are returned * from the iterator of the collection. * * @param collection the collection to initialize from * @return an array containing the values from the collection in iteration order */ public static DoubleArray copyOf(Collection<Double> collection) { if (collection.size() == 0) { return EMPTY; } if (collection instanceof ImmList) { return ((ImmList) collection).underlying; } return new DoubleArray(Doubles.toArray(collection)); } /** * Obtains an instance from an array of {@code double}. * <p> * The input array is copied and not mutated. * * @param array the array to copy, cloned * @return an array containing the specified values */ public static DoubleArray copyOf(double[] array) { if (array.length == 0) { return EMPTY; } return new DoubleArray(array.clone()); } /** * Obtains an instance by copying part of an array. * <p> * The input array is copied and not mutated. * * @param array the array to copy * @param fromIndex the offset from the start of the array * @return an array containing the specified values * @throws IndexOutOfBoundsException if the index is invalid */ public static DoubleArray copyOf(double[] array, int fromIndex) { return copyOf(array, fromIndex, array.length); } /** * Obtains an instance by copying part of an array. * <p> * The input array is copied and not mutated. * * @param array the array to copy * @param fromIndexInclusive the start index of the input array to copy from * @param toIndexExclusive the end index of the input array to copy to * @return an array containing the specified values * @throws IndexOutOfBoundsException if the index is invalid */ public static DoubleArray copyOf(double[] array, int fromIndexInclusive, int toIndexExclusive) { if (fromIndexInclusive > array.length) { throw new IndexOutOfBoundsException("Array index out of bounds: " + fromIndexInclusive + " > " + array.length); } if (toIndexExclusive > array.length) { throw new IndexOutOfBoundsException("Array index out of bounds: " + toIndexExclusive + " > " + array.length); } if ((toIndexExclusive - fromIndexInclusive) == 0) { return EMPTY; } return new DoubleArray(Arrays.copyOfRange(array, fromIndexInclusive, toIndexExclusive)); } //------------------------------------------------------------------------- /** * Obtains an instance with all entries equal to the zero. * * @param size the number of elements * @return an array filled with zeroes */ public static DoubleArray filled(int size) { if (size == 0) { return EMPTY; } return new DoubleArray(new double[size]); } /** * Obtains an instance with all entries equal to the same value. * * @param size the number of elements * @param value the value of all the elements * @return an array filled with the specified value */ public static DoubleArray filled(int size, double value) { if (size == 0) { return EMPTY; } double[] array = new double[size]; Arrays.fill(array, value); return new DoubleArray(array); } //------------------------------------------------------------------------- /** * Creates an instance from a {@code double[}. * * @param array the array, assigned not cloned */ private DoubleArray(double[] array) { this.array = array; } //------------------------------------------------------------------------- /** * Gets the number of dimensions of this array. * * @return one */ @Override public int dimensions() { return 1; } /** * Gets the size of this array. * * @return the array size, zero or greater */ @Override public int size() { return array.length; } /** * Checks if this array is empty. * * @return true if empty */ public boolean isEmpty() { return array.length == 0; } //------------------------------------------------------------------------- /** * Gets the value at the specified index in this array. * * @param index the zero-based index to retrieve * @return the value at the index * @throws IndexOutOfBoundsException if the index is invalid */ public double get(int index) { return array[index]; } /** * Checks if this array contains the specified value. * <p> * The value is checked using {@code Double.doubleToLongBits} in order to match {@code equals}. * This also allow this method to be used to find any occurrences of NaN. * * @param value the value to find * @return true if the value is contained in this array */ public boolean contains(double value) { if (array.length > 0) { long bits = Double.doubleToLongBits(value); for (int i = 0; i < array.length; i++) { if (Double.doubleToLongBits(array[i]) == bits) { return true; } } } return false; } /** * Find the index of the first occurrence of the specified value. * <p> * The value is checked using {@code Double.doubleToLongBits} in order to match {@code equals}. * This also allow this method to be used to find any occurrences of NaN. * * @param value the value to find * @return the index of the value, -1 if not found */ public int indexOf(double value) { if (array.length > 0) { long bits = Double.doubleToLongBits(value); for (int i = 0; i < array.length; i++) { if (Double.doubleToLongBits(array[i]) == bits) { return i; } } } return -1; } /** * Find the index of the first occurrence of the specified value. * <p> * The value is checked using {@code Double.doubleToLongBits} in order to match {@code equals}. * This also allow this method to be used to find any occurrences of NaN. * * @param value the value to find * @return the index of the value, -1 if not found */ public int lastIndexOf(double value) { if (array.length > 0) { long bits = Double.doubleToLongBits(value); for (int i = array.length - 1; i >= 0; i--) { if (Double.doubleToLongBits(array[i]) == bits) { return i; } } } return -1; } //------------------------------------------------------------------------- /** * Copies this array into the specified array. * <p> * The specified array must be at least as large as this array. * If it is larger, then the remainder of the array will be untouched. * * @param destination the array to copy into * @param offset the offset in the destination array to start from * @throws IndexOutOfBoundsException if the destination array is not large enough * or the offset is negative */ public void copyInto(double[] destination, int offset) { if (destination.length < array.length + offset) { throw new IndexOutOfBoundsException("Destination array is not large enough"); } System.arraycopy(array, 0, destination, offset, array.length); } /** * Returns an array holding the values from the specified index onwards. * * @param fromIndexInclusive the start index of the array to copy from * @return an array instance with the specified bounds * @throws IndexOutOfBoundsException if the index is invalid */ public DoubleArray subArray(int fromIndexInclusive) { return subArray(fromIndexInclusive, array.length); } /** * Returns an array holding the values between the specified from and to indices. * * @param fromIndexInclusive the start index of the array to copy from * @param toIndexExclusive the end index of the array to copy to * @return an array instance with the specified bounds * @throws IndexOutOfBoundsException if the index is invalid */ public DoubleArray subArray(int fromIndexInclusive, int toIndexExclusive) { return copyOf(array, fromIndexInclusive, toIndexExclusive); } //------------------------------------------------------------------------- /** * Converts this instance to an independent {@code double[]}. * * @return a copy of the underlying array */ public double[] toArray() { return array.clone(); } /** * Returns the underlying array. * <p> * This method is inherently unsafe as it relies on good behavior by callers. * Callers must never make any changes to the array returned by this method. * Doing so would violate the immutability of this class. * * @return the raw array */ public double[] toArrayUnsafe() { return array; } //------------------------------------------------------------------------- /** * Returns a list equivalent to this array. * * @return a list wrapping this array */ public List<Double> toList() { return new ImmList(this); } /** * Returns a stream over the array values. * * @return a stream over the values in the array */ public DoubleStream stream() { return DoubleStream.of(array); } //------------------------------------------------------------------------- /** * Applies an action to each value in the array. * <p> * This is used to perform an action on the contents of this array. * The action receives both the index and the value. * For example, the action could print out the array. * <pre> * base.forEach((index, value) -&gt; System.out.println(index + ": " + value)); * </pre> * <p> * This instance is immutable and unaffected by this method. * * @param action the action to be applied */ public void forEach(IntDoubleConsumer action) { for (int i = 0; i < array.length; i++) { action.accept(i, array[i]); } } //----------------------------------------------------------------------- /** * Returns an instance with the value at the specified index changed. * <p> * This instance is immutable and unaffected by this method. * * @param index the zero-based index to set * @param newValue the new value to store * @return a copy of this array with the value at the index changed * @throws IndexOutOfBoundsException if the index is invalid */ public DoubleArray with(int index, double newValue) { if (Double.doubleToLongBits(array[index]) == Double.doubleToLongBits(newValue)) { return this; } double[] result = array.clone(); result[index] = newValue; return new DoubleArray(result); } //------------------------------------------------------------------------- /** * Returns an instance with the specified amount added to each value. * <p> * This is used to add to the contents of this array, returning a new array. * <p> * This is a special case of {@link #map(DoubleUnaryOperator)}. * This instance is immutable and unaffected by this method. * * @param amount the amount to add, may be negative * @return a copy of this array with the amount added to each value */ public DoubleArray plus(double amount) { if (amount == 0d) { return this; } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] + amount; } return new DoubleArray(result); } /** * Returns an instance with the specified amount subtracted from each value. * <p> * This is used to subtract from the contents of this array, returning a new array. * <p> * This is a special case of {@link #map(DoubleUnaryOperator)}. * This instance is immutable and unaffected by this method. * * @param amount the amount to subtract, may be negative * @return a copy of this array with the amount subtracted from each value */ public DoubleArray minus(double amount) { if (amount == 0d) { return this; } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] - amount; } return new DoubleArray(result); } /** * Returns an instance with each value multiplied by the specified factor. * <p> * This is used to multiply the contents of this array, returning a new array. * <p> * This is a special case of {@link #map(DoubleUnaryOperator)}. * This instance is immutable and unaffected by this method. * * @param factor the multiplicative factor * @return a copy of this array with the each value multiplied by the factor */ public DoubleArray multipliedBy(double factor) { if (factor == 1d) { return this; } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] * factor; } return new DoubleArray(result); } /** * Returns an instance with each value divided by the specified divisor. * <p> * This is used to divide the contents of this array, returning a new array. * <p> * This is a special case of {@link #map(DoubleUnaryOperator)}. * This instance is immutable and unaffected by this method. * * @param divisor the value by which the array values are divided * @return a copy of this array with the each value divided by the divisor */ public DoubleArray dividedBy(double divisor) { if (divisor == 1d) { return this; } // multiplication is cheaper than division so it is more efficient to do the division once and multiply each element double factor = 1 / divisor; double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] * factor; } return new DoubleArray(result); } /** * Returns an instance with an operation applied to each value in the array. * <p> * This is used to perform an operation on the contents of this array, returning a new array. * The operator only receives the value. * For example, the operator could take the inverse of each element. * <pre> * result = base.map(value -&gt; 1 / value); * </pre> * <p> * This instance is immutable and unaffected by this method. * * @param operator the operator to be applied * @return a copy of this array with the operator applied to the original values */ public DoubleArray map(DoubleUnaryOperator operator) { double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = operator.applyAsDouble(array[i]); } return new DoubleArray(result); } /** * Returns an instance with an operation applied to each indexed value in the array. * <p> * This is used to perform an operation on the contents of this array, returning a new array. * The function receives both the index and the value. * For example, the operator could multiply the value by the index. * <pre> * result = base.mapWithIndex((index, value) -&gt; index * value); * </pre> * <p> * This instance is immutable and unaffected by this method. * * @param function the function to be applied * @return a copy of this array with the operator applied to the original values */ public DoubleArray mapWithIndex(IntDoubleToDoubleFunction function) { double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = function.applyAsDouble(i, array[i]); } return new DoubleArray(result); } //------------------------------------------------------------------------- /** * Returns an instance where each element is the sum of the matching values * in this array and the other array. * <p> * This is used to add two arrays, returning a new array. * Element {@code n} in the resulting array is equal to element {@code n} in this array * plus element {@code n} in the other array. * The arrays must be of the same size. * <p> * This is a special case of {@link #combine(DoubleArray, DoubleBinaryOperator)}. * This instance is immutable and unaffected by this method. * * @param other the other array * @return a copy of this array with matching elements added * @throws IllegalArgumentException if the arrays have different sizes */ public DoubleArray plus(DoubleArray other) { if (array.length != other.array.length) { throw new IllegalArgumentException("Arrays have different sizes"); } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] + other.array[i]; } return new DoubleArray(result); } /** * Returns an instance where each element is equal to the difference between the * matching values in this array and the other array. * <p> * This is used to subtract the second array from the first, returning a new array. * Element {@code n} in the resulting array is equal to element {@code n} in this array * minus element {@code n} in the other array. * The arrays must be of the same size. * <p> * This is a special case of {@link #combine(DoubleArray, DoubleBinaryOperator)}. * This instance is immutable and unaffected by this method. * * @param other the other array * @return a copy of this array with matching elements subtracted * @throws IllegalArgumentException if the arrays have different sizes */ public DoubleArray minus(DoubleArray other) { if (array.length != other.array.length) { throw new IllegalArgumentException("Arrays have different sizes"); } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] - other.array[i]; } return new DoubleArray(result); } /** * Returns an instance where each element is equal to the product of the * matching values in this array and the other array. * <p> * This is used to multiply each value in this array by the corresponding value in the other array, * returning a new array. * <p> * Element {@code n} in the resulting array is equal to element {@code n} in this array * multiplied by element {@code n} in the other array. * The arrays must be of the same size. * <p> * This is a special case of {@link #combine(DoubleArray, DoubleBinaryOperator)}. * This instance is immutable and unaffected by this method. * * @param other the other array * @return a copy of this array with matching elements multiplied * @throws IllegalArgumentException if the arrays have different sizes */ public DoubleArray multipliedBy(DoubleArray other) { if (array.length != other.array.length) { throw new IllegalArgumentException("Arrays have different sizes"); } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] * other.array[i]; } return new DoubleArray(result); } /** * Returns an instance where each element is calculated by dividing values in this array by values in the other array. * <p> * This is used to divide each value in this array by the corresponding value in the other array, * returning a new array. * <p> * Element {@code n} in the resulting array is equal to element {@code n} in this array * divided by element {@code n} in the other array. * The arrays must be of the same size. * <p> * This is a special case of {@link #combine(DoubleArray, DoubleBinaryOperator)}. * This instance is immutable and unaffected by this method. * * @param other the other array * @return a copy of this array with matching elements divided * @throws IllegalArgumentException if the arrays have different sizes */ public DoubleArray dividedBy(DoubleArray other) { if (array.length != other.array.length) { throw new IllegalArgumentException("Arrays have different sizes"); } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i] / other.array[i]; } return new DoubleArray(result); } /** * Returns an instance where each element is formed by some combination of the matching * values in this array and the other array. * <p> * This is used to combine two arrays, returning a new array. * Element {@code n} in the resulting array is equal to the result of the operator * when applied to element {@code n} in this array and element {@code n} in the other array. * The arrays must be of the same size. * <p> * This instance is immutable and unaffected by this method. * * @param other the other array * @param operator the operator used to combine each pair of values * @return a copy of this array combined with the specified array * @throws IllegalArgumentException if the arrays have different sizes */ public DoubleArray combine(DoubleArray other, DoubleBinaryOperator operator) { if (array.length != other.array.length) { throw new IllegalArgumentException("Arrays have different sizes"); } double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = operator.applyAsDouble(array[i], other.array[i]); } return new DoubleArray(result); } /** * Combines this array and the other array returning a reduced value. * <p> * This is used to combine two arrays, returning a single reduced value. * The operator is called once for each element in the arrays. * The arrays must be of the same size. * <p> * The first argument to the operator is the running total of the reduction, starting from zero. * The second argument to the operator is the element from this array. * The third argument to the operator is the element from the other array. * <p> * This instance is immutable and unaffected by this method. * * @param other the other array * @param operator the operator used to combine each pair of values with the current total * @return the result of the reduction * @throws IllegalArgumentException if the arrays have different sizes */ public double combineReduce(DoubleArray other, DoubleTernaryOperator operator) { if (array.length != other.array.length) { throw new IllegalArgumentException("Arrays have different sizes"); } double result = 0; for (int i = 0; i < array.length; i++) { result = operator.applyAsDouble(result, array[i], other.array[i]); } return result; } //------------------------------------------------------------------------- /** * Returns an array that combines this array and the specified array. * <p> * The result will have a length equal to {@code this.size() + arrayToConcat.length}. * <p> * This instance is immutable and unaffected by this method. * * @param arrayToConcat the array to add to the end of this array * @return a copy of this array with the specified array added at the end * @throws IndexOutOfBoundsException if the index is invalid */ public DoubleArray concat(double... arrayToConcat) { if (array.length == 0) { return copyOf(arrayToConcat); } if (arrayToConcat.length == 0) { return this; } double[] result = new double[array.length + arrayToConcat.length]; System.arraycopy(array, 0, result, 0, array.length); System.arraycopy(arrayToConcat, 0, result, array.length, arrayToConcat.length); return new DoubleArray(result); } /** * Returns an array that combines this array and the specified array. * <p> * The result will have a length equal to {@code this.size() + newArray.length}. * <p> * This instance is immutable and unaffected by this method. * * @param arrayToConcat the new array to add to the end of this array * @return a copy of this array with the specified array added at the end * @throws IndexOutOfBoundsException if the index is invalid */ public DoubleArray concat(DoubleArray arrayToConcat) { if (array.length == 0) { return arrayToConcat; } if (arrayToConcat.array.length == 0) { return this; } return concat(arrayToConcat.array); } //----------------------------------------------------------------------- /** * Returns a sorted copy of this array. * <p> * This uses {@link Arrays#sort(double[])}. * <p> * This instance is immutable and unaffected by this method. * * @return a sorted copy of this array */ public DoubleArray sorted() { if (array.length < 2) { return this; } double[] result = array.clone(); Arrays.sort(result); return new DoubleArray(result); } /** * Returns the minimum value held in the array. * <p> * If the array is empty, then an exception is thrown. * If the array contains NaN, then the result is NaN. * * @return the minimum value * @throws IllegalStateException if the array is empty */ public double min() { if (array.length == 0) { throw new IllegalStateException("Unable to find minimum of an empty array"); } if (array.length == 1) { return array[0]; } double min = Double.POSITIVE_INFINITY; for (int i = 0; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the minimum value held in the array. * <p> * If the array is empty, then an exception is thrown. * If the array contains NaN, then the result is NaN. * * @return the maximum value * @throws IllegalStateException if the array is empty */ public double max() { if (array.length == 0) { throw new IllegalStateException("Unable to find maximum of an empty array"); } if (array.length == 1) { return array[0]; } double max = Double.NEGATIVE_INFINITY; for (int i = 0; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the sum of all the values in the array. * <p> * This is a special case of {@link #reduce(double, DoubleBinaryOperator)}. * * @return the total of all the values */ public double sum() { double total = 0; for (int i = 0; i < array.length; i++) { total += array[i]; } return total; } /** * Reduces this array returning a single value. * <p> * This is used to reduce the values in this array to a single value. * The operator is called once for each element in the arrays. * The first argument to the operator is the running total of the reduction, starting from zero. * The second argument to the operator is the element. * <p> * This instance is immutable and unaffected by this method. * * @param identity the identity value to start from * @param operator the operator used to combine the value with the current total * @return the result of the reduction */ public double reduce(double identity, DoubleBinaryOperator operator) { double result = identity; for (int i = 0; i < array.length; i++) { result = operator.applyAsDouble(result, array[i]); } return result; } //------------------------------------------------------------------------- @Override public MetaBean metaBean() { return Meta.META; } //------------------------------------------------------------------------- /** * Checks if this array equals another within the specified tolerance. * <p> * This returns true if the two instances have {@code double} values that are * equal within the specified tolerance. * * @param other the other array * @param tolerance the tolerance * @return true if equal up to the tolerance */ public boolean equalWithTolerance(DoubleArray other, double tolerance) { return DoubleArrayMath.fuzzyEquals(array, other.array, tolerance); } /** * Checks if this array equals zero within the specified tolerance. * <p> * This returns true if all the {@code double} values equal zero within the specified tolerance. * * @param tolerance the tolerance * @return true if equal up to the tolerance */ public boolean equalZeroWithTolerance(double tolerance) { return DoubleArrayMath.fuzzyEqualsZero(array, tolerance); } //------------------------------------------------------------------------- @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DoubleArray) { DoubleArray other = (DoubleArray) obj; return Arrays.equals(array, other.array); } return false; } @Override public int hashCode() { return Arrays.hashCode(array); } @Override public String toString() { return Arrays.toString(array); } //----------------------------------------------------------------------- /** * Immutable {@code Iterator} representation of the array. */ static class ImmIterator implements ListIterator<Double> { private final double[] array; private int index; public ImmIterator(double[] array) { this.array = array; } @Override public boolean hasNext() { return index < array.length; } @Override public boolean hasPrevious() { return index > 0; } @Override public Double next() { if (hasNext()) { return array[index++]; } throw new NoSuchElementException("Iteration has reached the last element"); } @Override public Double previous() { if (hasPrevious()) { return array[--index]; } throw new NoSuchElementException("Iteration has reached the first element"); } @Override public int nextIndex() { return index; } @Override public int previousIndex() { return index - 1; } @Override public void remove() { throw new UnsupportedOperationException("Unable to remove from DoubleArray"); } @Override public void set(Double value) { throw new UnsupportedOperationException("Unable to set value in DoubleArray"); } @Override public void add(Double value) { throw new UnsupportedOperationException("Unable to add value to DoubleArray"); } } //----------------------------------------------------------------------- /** * Immutable {@code List} representation of the array. */ static class ImmList extends AbstractList<Double> implements RandomAccess, Serializable { private static final long serialVersionUID = 1L; private final DoubleArray underlying; ImmList(DoubleArray underlying) { this.underlying = underlying; } @Override public int size() { return underlying.size(); } @Override public Double get(int index) { return underlying.get(index); } @Override public boolean contains(Object obj) { return (obj instanceof Double ? underlying.contains((Double) obj) : false); } @Override public int indexOf(Object obj) { return (obj instanceof Double ? underlying.indexOf((Double) obj) : -1); } @Override public int lastIndexOf(Object obj) { return (obj instanceof Double ? underlying.lastIndexOf((Double) obj) : -1); } @Override public ListIterator<Double> iterator() { return listIterator(); } @Override public ListIterator<Double> listIterator() { return new ImmIterator(underlying.array); } @Override protected void removeRange(int fromIndex, int toIndex) { throw new UnsupportedOperationException("Unable to remove range from DoubleArray"); } } //------------------------------------------------------------------------- /** * Meta bean. */ static final class Meta extends BasicMetaBean { private static final MetaBean META = new Meta(); private static final MetaProperty<double[]> ARRAY = new BasicMetaProperty<double[]>("array") { @Override public MetaBean metaBean() { return META; } @Override public Class<?> declaringType() { return DoubleArray.class; } @Override public Class<double[]> propertyType() { return double[].class; } @Override public Type propertyGenericType() { return double[].class; } @Override public PropertyStyle style() { return PropertyStyle.IMMUTABLE; } @Override public List<Annotation> annotations() { return ImmutableList.of(); } @Override public double[] get(Bean bean) { return ((DoubleArray) bean).toArray(); } @Override public void set(Bean bean, Object value) { throw new UnsupportedOperationException("Property cannot be written: " + name()); } }; private static final ImmutableMap<String, MetaProperty<?>> MAP = ImmutableMap.of("array", ARRAY); private Meta() { } @Override public boolean isBuildable() { return true; } @Override public BeanBuilder<DoubleArray> builder() { return new BasicImmutableBeanBuilder<DoubleArray>(this) { private double[] array = DoubleArrayMath.EMPTY_DOUBLE_ARRAY; @Override public Object get(String propertyName) { if (propertyName.equals(ARRAY.name())) { return array.clone(); } else { throw new NoSuchElementException("Unknown property: " + propertyName); } } @Override public BeanBuilder<DoubleArray> set(String propertyName, Object value) { if (propertyName.equals(ARRAY.name())) { this.array = ((double[]) ArgChecker.notNull(value, "value")).clone(); } else { throw new NoSuchElementException("Unknown property: " + propertyName); } return this; } @Override public DoubleArray build() { return new DoubleArray(array); } }; } @Override public Class<? extends Bean> beanType() { return DoubleArray.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return MAP; } } }
14,032
474
// // PLSTimelineMediaInfo.h // PLVideoEditor // // Created by suntongmian on 2018/5/24. // Copyright © 2018年 Pili Engineering, Qiniu Inc. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #define UIColorFromRGB(R,G,B) [UIColor colorWithRed:(R * 1.0) / 255.0 green:(G * 1.0) / 255.0 blue:(B * 1.0) / 255.0 alpha:1.0] #define rgba(R,G,B,A) [UIColor colorWithRed:(R * 1.0) / 255.0 green:(G * 1.0) / 255.0 blue:(B * 1.0) / 255.0 alpha:A] @interface PLSTimelineMediaInfo : NSObject @property (nonatomic, strong) AVAsset *asset; //媒体资源 @property (nonatomic, copy) NSString *path; //媒体资源路径 @property (nonatomic, assign) CGFloat duration; //媒体持续时长 @property (nonatomic, assign) CGFloat startTime; //媒体开始时间 @property (nonatomic, assign) int rotate;//旋转角度 @end
395
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ #import <OfficeImport/OfficeImport-Structs.h> #import <OfficeImport/OADColor.h> __attribute__((visibility("hidden"))) @interface OADIndexedColor : OADColor { @private int mIndex; // 8 = 0x8 } + (id)indexedColorWithIndex:(int)index; // 0x163b8d - (id)initWithIndex:(int)index; // 0x163bd9 - (id)copyWithZone:(NSZone *)zone; // 0x16ac2d - (int)index; // 0x177d89 - (id)colorFromPalette:(id)palette; // 0x29ff05 - (unsigned)hash; // 0x29fec9 - (BOOL)isEqual:(id)equal; // 0x29fe25 @end
253
1,968
<filename>platform/windows/Corona.Component.Library/CoronaLabs/Corona/WinRT/Interop/UI/PageProxy.h ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef CORONALABS_CORONA_API_EXPORT # error This header file cannot be included by an external library. #endif #include "IPage.h" #include "PageOrientation.h" #include "PageOrientationEventArgs.h" #include "CoronaLabs\WinRT\CancelEventArgs.h" #include "CoronaLabs\WinRT\EmptyEventArgs.h" namespace CoronaLabs { namespace Corona { namespace WinRT { namespace Interop { namespace UI { /// <summary> /// Proxy which passes through all events, commands, and property accessors to an actual application page /// used to host UI controls. /// </summary> /// <remarks> /// The main intention of this proxy is to safely handle the case where a UI control can be removed from a page /// and then added to the page (or a different page) later. In this case, the control's page reference would be /// be null, meaning the system should no longer attempt to access that lost page's properties and should unsubsribe /// from it events. However, with this class, the system can always safely/easily access the page's properties /// through this proxy which serves as a pass-through and will provide default values when the page reference has /// been lost. /// </remarks> [Windows::Foundation::Metadata::WebHostHidden] public ref class PageProxy sealed : public IPage { public: #pragma region Events /// <summary>Raised when the application page's orientation has changed.</summary> virtual event Windows::Foundation::TypedEventHandler<IPage^, PageOrientationEventArgs^>^ OrientationChanged; /// <summary>Raised when the end-user attempts to back out of the page.</summary> /// <remarks> /// If you want to prevent the end-user from navigating back, then you should set the event argument's /// Cancel property to true. /// </remarks> virtual event Windows::Foundation::TypedEventHandler<IPage^, CoronaLabs::WinRT::CancelEventArgs^>^ NavigatingBack; /// <summary>Raised when this proxy has been assigned a page.</summary> event Windows::Foundation::TypedEventHandler<PageProxy^, CoronaLabs::WinRT::EmptyEventArgs^>^ ReceivedPage; /// <summary>Raised when this proxy's assigned page is about to be lost.</summary> event Windows::Foundation::TypedEventHandler<PageProxy^, CoronaLabs::WinRT::EmptyEventArgs^>^ LosingPage; #pragma endregion #pragma region Constructors/Destructors /// <summary>Creates a new proxy used to safely reference one page.</summary> PageProxy(); #pragma endregion #pragma region Public Methods/Properties /// <summary>Gets or sets the application page that this proxy references.</summary> /// <value> /// <para>The application page that this proxy references.</para> /// <para>Set to null if the proxy does not currently reference a page.</para> /// </value> property IPage^ Page { IPage^ get(); void set(IPage^ page); } /// <summary>Gets the application page's current orientation.</summary> /// <value>The application page's current orientation such as portrait, landscape, etc.</value> virtual property PageOrientation^ Orientation { PageOrientation^ get(); } /// <summary>Commands the page to navigate back to the previous page.</summary> /// <remarks>This method is expected to be called when Corona's native.requestExit() function gets called in Lua.</remarks> virtual void NavigateBack(); /// <summary> /// <para>Navigates to the application page that the given URI's scheme applies to.</para> /// <para> /// For example, an "http://" URI will launch the browser app and a "mailto://" scheme will launch the mail app. /// </para> /// </summary> /// <remarks>This method is called by Corona's system.openURL() Lua function.</remarks> /// <param name="uri">The URI/URL of the application page to navigate to.</param> /// <returns> /// <para>Returns true if able to display an application page for the given URI.</para> /// <para>Returns false if the given URI was not recognized and has failed to navigate to another page.</para> /// </returns> virtual bool NavigateTo(Windows::Foundation::Uri^ uri); /// <summary>Determines if the given URI will work when passed to the NavigateTo() method.</summary> /// <remarks>This method is called by Corona's system.canOpenURL() Lua function.</remarks> /// <param name="uri">The URI/URL of the application page to navigate to.</param> /// <returns> /// <para>Returns true if able to display an application page for the given URI.</para> /// <para>Returns false if the given URI cannot open a page or is invalid.</para> /// </returns> virtual bool CanNavigateTo(Windows::Foundation::Uri^ uri); #pragma endregion private: #pragma region Private Methods /// <summary>Subscribes to the "fPage" member variable's events.</summary> void AddEventHandlers(); /// <summary>Unsubscribes from the "fPage" member variable's events.</summary> void RemoveEventHandlers(); /// <summary> /// <para>Called when this proxy's assigned page raises an "OrientationChanged" event.</para> /// <para>Relays the event to the handlers assigned to this proxy.</para> /// </summary> /// <param name="sender">The page that raised this event.</param> /// <param name="args">Provides the page's newly assigned orientation.</param> void OnOrientationChanged(IPage^ sender, PageOrientationEventArgs^ args); /// <summary> /// <para>Called when this proxy's assigned page raises a "NavigatingBack" event.</para> /// <para>Relays the event to the handlers assigned to this proxy.</para> /// </summary> /// <param name="sender">The page that raised this event.</param> /// <param name="args">Provides a Cancel argument that the event handler can set true to block navigation.</param> void OnNavigatingBack(IPage^ sender, CoronaLabs::WinRT::CancelEventArgs^ args); #pragma endregion #pragma region Private Member Variables. /// <summary>The page that this proxy currently references.</summary> IPage^ fPage; /// <summary>Last orientation received from the page.</summary> PageOrientation^ fLastOrientation; /// <summary>Token received when subscribing to the referenced page's "OrientationChanged" event.</summary> Windows::Foundation::EventRegistrationToken fOrientationChangedEventToken; /// <summary>Token received when subscribing to the referenced page's "NavigatingBack" event.</summary> Windows::Foundation::EventRegistrationToken fNavigatingBackEventToken; #pragma endregion }; } } } } } // namespace CoronaLabs::Corona::WinRT::Interop::UI
2,023
3,482
#include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <math.h> // gamma correction cv::Mat gamma_correction(cv::Mat img, double gamma_c, double gamma_g){ // get height and width int width = img.cols; int height = img.rows; int channel = img.channels(); // output image cv::Mat out = cv::Mat::zeros(height, width, CV_8UC3); double val; // gamma correction for (int y = 0; y< height; y++){ for (int x = 0; x < width; x++){ for (int c = 0; c < channel; c++){ val = (double)img.at<cv::Vec3b>(y, x)[c] / 255; out.at<cv::Vec3b>(y, x)[c] = (uchar)(pow(val / gamma_c, 1 / gamma_g) * 255); } } } return out; } int main(int argc, const char* argv[]){ // read image cv::Mat img = cv::imread("imori_gamma.jpg", cv::IMREAD_COLOR); // gamma correction cv::Mat out = gamma_correction(img, 1, 2.2); //cv::imwrite("out.jpg", out); cv::imshow("answer", out); cv::waitKey(0); cv::destroyAllWindows(); return 0; }
439
1,056
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.xml.schema.model.visitor; import org.netbeans.modules.xml.schema.model.*; /** * This interface represents a way for * @author <NAME> */ public interface SchemaVisitor { void visit(All all); void visit(Annotation ann); void visit(AnyElement any); void visit(AnyAttribute anyAttr); void visit(AppInfo appinfo); void visit(AttributeReference reference); void visit(AttributeGroupReference agr); void visit(Choice choice); void visit(ComplexContent cc); void visit(ComplexContentRestriction ccr); void visit(ComplexExtension ce); void visit(Documentation d); void visit(ElementReference er); void visit(Enumeration e); void visit(Field f); void visit(FractionDigits fd); void visit(GlobalAttribute ga); void visit(GlobalAttributeGroup gag); void visit(GlobalComplexType gct); void visit(GlobalElement ge); void visit(GlobalSimpleType gst); void visit(GlobalGroup gd); void visit(GroupReference gr); void visit(Import im); void visit(Include include); void visit(Key key); void visit(KeyRef kr); void visit(Length length); void visit(List l); void visit(LocalAttribute la); void visit(LocalComplexType type); void visit(LocalElement le); void visit(LocalSimpleType type); void visit(MaxExclusive me); void visit(MaxInclusive mi); void visit(MaxLength ml); void visit(MinInclusive mi); void visit(MinExclusive me); void visit(MinLength ml); void visit(Notation notation); void visit(Pattern p); void visit(Redefine rd); void visit(Schema s); void visit(Selector s); void visit(Sequence s); void visit(SimpleContent sc); void visit(SimpleContentRestriction scr); void visit(SimpleExtension se); void visit(SimpleTypeRestriction str); void visit(TotalDigits td); void visit(Union u); void visit(Unique u); void visit(Whitespace ws); }
798
566
/** * This file is part of dvo. * * Copyright 2013 <NAME> <<EMAIL>> (Technical University of Munich) * For more information see <http://vision.in.tum.de/data/software/dvo>. * * dvo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * dvo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with dvo. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CONSTRAINT_PROPOSAL_VOTER_H_ #define CONSTRAINT_PROPOSAL_VOTER_H_ #include <dvo_slam/constraints/constraint_proposal.h> namespace dvo_slam { namespace constraints { struct ConstraintProposalVoter { virtual ~ConstraintProposalVoter() {}; /** * These methods allow voters to get tracking results for additional proposals, which they might need for their * decision. */ virtual void createAdditionalProposals(ConstraintProposalVector& proposals) {} virtual void removeAdditionalProposals(ConstraintProposalVector& proposals) {} /** * Vote for the proposal. Has to set the decision. * If asked for reason provide detailed explanation of decision. */ virtual ConstraintProposal::Vote vote(const ConstraintProposal& proposal, bool provide_reason) = 0; }; typedef boost::shared_ptr<ConstraintProposalVoter> ConstraintProposalVoterPtr; typedef std::vector<ConstraintProposalVoterPtr> ConstraintProposalVoterVector; struct CrossValidationVoter : public ConstraintProposalVoter { double TranslationThreshold; CrossValidationVoter(double threshold); CrossValidationVoter(const CrossValidationVoter& other); virtual ~CrossValidationVoter(); virtual void createAdditionalProposals(ConstraintProposalVector& proposals); virtual void removeAdditionalProposals(ConstraintProposalVector& proposals); virtual ConstraintProposal::Vote vote(const ConstraintProposal& proposal, bool provide_reason); private: typedef std::vector<std::pair<ConstraintProposal*, ConstraintProposal*> > ProposalPairVector; ProposalPairVector pairs_; ConstraintProposal* findInverse(const ConstraintProposal *proposal); }; struct TrackingResultEvaluationVoter : public ConstraintProposalVoter { double RatioThreshold; TrackingResultEvaluationVoter(double threshold); virtual ~TrackingResultEvaluationVoter(); virtual ConstraintProposal::Vote vote(const ConstraintProposal& proposal, bool provide_reason); }; struct ConstraintRatioVoter : public ConstraintProposalVoter { double RatioThreshold; ConstraintRatioVoter(double threshold); virtual ~ConstraintRatioVoter(); virtual ConstraintProposal::Vote vote(const ConstraintProposal& proposal, bool provide_reason); }; struct NaNResultVoter : public ConstraintProposalVoter { NaNResultVoter(); virtual ~NaNResultVoter(); virtual ConstraintProposal::Vote vote(const ConstraintProposal& proposal, bool provide_reason); }; struct OdometryConstraintVoter : public ConstraintProposalVoter { OdometryConstraintVoter(); virtual ~OdometryConstraintVoter(); virtual ConstraintProposal::Vote vote(const ConstraintProposal& proposal, bool provide_reason); }; } /* namespace constraints */ } /* namespace dvo_slam */ #endif /* CONSTRAINT_PROPOSAL_VOTER_H_ */
1,073
335
/* Copyright 2016 <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "loss_func_pairwise.h" #include <functional> #include <numeric> #include <vector> #include "gtest/gtest.h" #include "loss_func_math.h" #include "loss_func_pairwise_logloss.h" #include "src/data_store/data_store.h" namespace gbdt { class PairwiseTest : public ::testing::Test { protected: void SetUp() { data_store_.Add(Column::CreateStringColumn("group0", {"1", "1", "1", "1"})); data_store_.Add(Column::CreateStringColumn("group1", {"0", "0", "1", "1"})); config_.set_pair_sampling_rate(kSamplingRate_); } void ExpectGradientEqual(const vector<GradientData>& expected, const vector<GradientData>& gradient_data_vec) { for (int i = 0; i < expected.size(); ++i) { double avg_g = gradient_data_vec[i].g / kSamplingRate_; double avg_h = gradient_data_vec[i].h / kSamplingRate_; EXPECT_LT(fabs(expected[i].g - avg_g), 5e-2) << " at " << i << " actual " << avg_g << " vs " << expected[i].g; EXPECT_LT(fabs(expected[i].h - avg_h), 5e-2) << " at " << i << " actual " << avg_h << " vs " << expected[i].h; } } unique_ptr<Pairwise> CreateAndInitPairwiseLoss(const string& group_name) { unique_ptr<Pairwise> pairwise(new PairwiseLogLoss(config_)); pairwise->Init(data_store_.num_rows(), w_, y_, data_store_.GetStringColumn(group_name)); return pairwise; } DataStore data_store_; FloatVector w_ = [](int) { return 1.0; }; FloatVector y_ = [](int i) { return i; }; vector<double> f_ = { 0, 0, 0, 0}; // Set sampleing_rate to 10000 so that g and h are more stable. const int kSamplingRate_ = 100000; Config config_; }; // All instances are in one group. TEST_F(PairwiseTest, TestComputeFunctionalGradientsAndHessiansOneGroup) { vector<GradientData> gradient_data_vec; double c; unique_ptr<Pairwise> pairwise = CreateAndInitPairwiseLoss("group0"); pairwise->ComputeFunctionalGradientsAndHessians(f_, &c, &gradient_data_vec, nullptr); // c is zero for all pairwise losses. EXPECT_FLOAT_EQ(0, c); // The gradients reflect the relative order of the original targets. vector<GradientData> expected = { {-0.5, 0.5}, {-0.5/3, 0.5}, {0.5/3, 0.5}, {0.5, 0.5} }; ExpectGradientEqual(expected, gradient_data_vec); } // When on group_columnis specified, every instance is put in one group. TEST_F(PairwiseTest, TestComputeFunctionalGradientsAndHessiansNoGroup) { // When no group specified, every instance is put in one group. vector<GradientData> gradient_data_vec; unique_ptr<Pairwise> pairwise = CreateAndInitPairwiseLoss(""); double c; pairwise->ComputeFunctionalGradientsAndHessians(f_, &c, &gradient_data_vec, nullptr); // c is zero for all pairwise losses. EXPECT_FLOAT_EQ(0, c); // The gradients reflect the relative order of the original targets. vector<GradientData> expected = { {-0.5, 0.5}, {-0.5/3, 0.5}, {0.5/3, 0.5}, {0.5, 0.5} }; ExpectGradientEqual(expected, gradient_data_vec); } // All instances are in two group. TEST_F(PairwiseTest, TestComputeFunctionalGradientsAndHessiansTwoGroups) { vector<GradientData> gradient_data_vec; unique_ptr<Pairwise> pairwise = CreateAndInitPairwiseLoss("group1"); double c; pairwise->ComputeFunctionalGradientsAndHessians(f_, &c, &gradient_data_vec, nullptr); // c is zero for all pairwise losses. EXPECT_FLOAT_EQ(0, c); // Because of the grouping, the gradients of the two groups {0, 1} and {2, 3} // are similar in the magnitude since the targets are not compared // across groups. vector<GradientData> expected = { {-0.5, 0.5}, {0.5, 0.5}, {-0.5, 0.5}, {0.5, 0.5} }; ExpectGradientEqual(expected, gradient_data_vec); } TEST_F(PairwiseTest, TestComputeFunctionalGradientsAndHessiansWeightByDeltaTarget) { vector<GradientData> gradient_data_vec; config_.set_pair_weight_by_delta_target(true); unique_ptr<Pairwise> pairwise = CreateAndInitPairwiseLoss("group0"); double c; pairwise->ComputeFunctionalGradientsAndHessians(f_, &c, &gradient_data_vec, nullptr); // c is zero for all pairwise losses. EXPECT_FLOAT_EQ(0, c); // More weights are put on higher target separation. vector<GradientData> expected = { {-1, 1}, {-1.0/3, 2.0/3}, {1.0/3, 2.0/3}, {1, 1} }; ExpectGradientEqual(expected, gradient_data_vec); } } // namespace gbdt
1,809
324
from django.utils.translation import ugettext_lazy as _ from waliki.plugins import BasePlugin, register class PdfPlugin(BasePlugin): slug = 'pdf' urls_page = ['waliki.pdf.urls'] extra_page_actions = {'reStructuredText': [('waliki_pdf', _('Get as PDF'))]} register(PdfPlugin)
105
420
package com.kevin.delegationadapter.sample.bean; import java.util.List; /** * Chat * * @author <EMAIL>, Created on 2018-06-09 10:30:25 * Major Function:<b></b> * <p/> * 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!! * @author mender,Modified Date Modify Content: */ public class Chat { public List<TalkMsg> msgs; public static class TalkMsg { public int type; public User user; public String text; public String pic; } public static class User { public int type; public String avatar; } }
327
854
<filename>Java/812.java<gh_stars>100-1000 __________________________________________________________________________________________________ sample 2 ms submission class Solution { public double largestTriangleArea(int[][] p) { double max = 0; int length = p.length; for (int i = 0 ; i < length ; ++i) for (int j = i+1 ; j < length ; ++j) for (int k = j+1 ; k < length ; ++k) { double area = calcArea(p[i], p[j], p[k]); if (area > max) max = area; } return max; } private double calcArea(int[] a, int[] b, int[] c) { return 0.5 * Math.abs(a[0]*b[1] - a[1]*b[0] +b[0]*c[1] - b[1]*c[0] +c[0]*a[1] - c[1]*a[0]); } } __________________________________________________________________________________________________ sample 35724 kb submission class Solution { public double largestTriangleArea(int[][] points) { double max = Double.MIN_VALUE; int n = points.length; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { for(int k = j + 1; k < n; k++) { max = Math.max(max, Math.abs(area(points[i], points[j], points[k]))); } } } return max; } public double area(int[] a, int[] b, int[] c) { double sum = a[0] * b[1] + b[0] * c[1] + c[0] * a[1] - a[0] * c[1] - c[0] * b[1] - b[0] * a[1]; return sum / 2.0; } } __________________________________________________________________________________________________
795
743
import re from config.Config import Config from engine.component.TemplateModuleComponent import TemplateModuleComponent from enums.Language import Language class UsingComponent(TemplateModuleComponent): def __init__(self, code=None, language=Language.CSHARP): placeholder = Config().get("PLACEHOLDERS", "USING") super().__init__(code, placeholder) self.__code = code self.language = language @property def code(self): if self.language == Language.CSHARP: return f"using {self.__code};" elif self.language == Language.CPP: return f"#include {self.__code}" elif self.language == Language.POWERSHELL: if re.search(r"^(http|ftp)", self.__code): return f'iex (([System.Net.WebClient]::new()).DownloadString("{self.__code}"));' else: return f'iex ([System.IO.File]::ReadAllBytes("{self.__code}"));' else: return self.__code
415
350
<filename>src/main.py<gh_stars>100-1000 #!/usr/bin/python # -*- coding: utf-8 -*- import argparse, logging import numpy as np import struc2vec from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence from time import time import graph logging.basicConfig(filename='struc2vec.log',filemode='w',level=logging.DEBUG,format='%(asctime)s %(message)s') def parse_args(): ''' Parses the struc2vec arguments. ''' parser = argparse.ArgumentParser(description="Run struc2vec.") parser.add_argument('--input', nargs='?', default='graph/karate.edgelist', help='Input graph path') parser.add_argument('--output', nargs='?', default='emb/karate.emb', help='Embeddings path') parser.add_argument('--dimensions', type=int, default=128, help='Number of dimensions. Default is 128.') parser.add_argument('--walk-length', type=int, default=80, help='Length of walk per source. Default is 80.') parser.add_argument('--num-walks', type=int, default=10, help='Number of walks per source. Default is 10.') parser.add_argument('--window-size', type=int, default=10, help='Context size for optimization. Default is 10.') parser.add_argument('--until-layer', type=int, default=None, help='Calculation until the layer.') parser.add_argument('--iter', default=5, type=int, help='Number of epochs in SGD') parser.add_argument('--workers', type=int, default=4, help='Number of parallel workers. Default is 8.') parser.add_argument('--weighted', dest='weighted', action='store_true', help='Boolean specifying (un)weighted. Default is unweighted.') parser.add_argument('--unweighted', dest='unweighted', action='store_false') parser.set_defaults(weighted=False) parser.add_argument('--directed', dest='directed', action='store_true', help='Graph is (un)directed. Default is undirected.') parser.add_argument('--undirected', dest='undirected', action='store_false') parser.set_defaults(directed=False) parser.add_argument('--OPT1', default=False, type=bool, help='optimization 1') parser.add_argument('--OPT2', default=False, type=bool, help='optimization 2') parser.add_argument('--OPT3', default=False, type=bool, help='optimization 3') return parser.parse_args() def read_graph(): ''' Reads the input network. ''' logging.info(" - Loading graph...") G = graph.load_edgelist(args.input,undirected=True) logging.info(" - Graph loaded.") return G def learn_embeddings(): ''' Learn embeddings by optimizing the Skipgram objective using SGD. ''' logging.info("Initializing creation of the representations...") walks = LineSentence('random_walks.txt') model = Word2Vec(walks, size=args.dimensions, window=args.window_size, min_count=0, hs=1, sg=1, workers=args.workers, iter=args.iter) model.wv.save_word2vec_format(args.output) logging.info("Representations created.") return def exec_struc2vec(args): ''' Pipeline for representational learning for all nodes in a graph. ''' if(args.OPT3): until_layer = args.until_layer else: until_layer = None G = read_graph() G = struc2vec.Graph(G, args.directed, args.workers, untilLayer = until_layer) if(args.OPT1): G.preprocess_neighbors_with_bfs_compact() else: G.preprocess_neighbors_with_bfs() if(args.OPT2): G.create_vectors() G.calc_distances(compactDegree = args.OPT1) else: G.calc_distances_all_vertices(compactDegree = args.OPT1) G.create_distances_network() G.preprocess_parameters_random_walk() G.simulate_walks(args.num_walks, args.walk_length) return G def main(args): G = exec_struc2vec(args) learn_embeddings() if __name__ == "__main__": args = parse_args() main(args)
1,584
732
<gh_stars>100-1000 /* Copyright 2019 Adobe. All Rights Reserved. This software is licensed as OpenSource, under the Apache License, Version 2.0. This license is available at: http://opensource.org/licenses/Apache-2.0. */ #ifndef SAFETIME_H #define SAFETIME_H #ifdef _WIN32 #define SAFE_LOCALTIME(x, y) localtime_s(y, x) #define LOCALTIME_FAILURE(x) (x != 0) #define SAFE_CTIME(x, y) ctime_s(y, sizeof(y), x) #define SAFE_GMTIME(x, y) gmtime_s(y, x) #else #define SAFE_LOCALTIME(x, y) localtime_r(x, y) #define LOCALTIME_FAILURE(x) (x == NULL) #define SAFE_CTIME(x, y) ctime_r(x, y) #define SAFE_GMTIME(x, y) gmtime_r(x, y) #endif /* WIN32 */ #endif /* SAFETIME_H */
327
685
// eventpp library // Copyright (C) 2018 <NAME> (wqking) // Github: https://github.com/wqking/eventpp // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test.h" #include "eventpp/utilities/conditionalfunctor.h" #include "eventpp/callbacklist.h" #include <vector> TEST_CASE("ConditionalFunctor, lambda") { eventpp::CallbackList<void(int)> callbackList; std::vector<int> dataList(3); callbackList.append( eventpp::conditionalFunctor( [&dataList](const int index) { ++dataList[index]; }, [](const int index) { return index == 0; } ) ); callbackList.append( eventpp::conditionalFunctor( [&dataList](const int index) { ++dataList[index]; }, [](const int index) { return index == 1; } ) ); callbackList.append( eventpp::conditionalFunctor( [&dataList](const int index) { ++dataList[index]; }, [](const int index) { return index == 2; } ) ); REQUIRE(dataList == std::vector<int>{ 0, 0, 0 }); callbackList(2); REQUIRE(dataList == std::vector<int>{ 0, 0, 1 }); callbackList(0); REQUIRE(dataList == std::vector<int>{ 1, 0, 1 }); callbackList(1); REQUIRE(dataList == std::vector<int>{ 1, 1, 1 }); } void conditionalFunctorIncreaseOne(std::vector<int> & dataList, const int index) { ++dataList[index]; } TEST_CASE("ConditionalFunctor, free function") { eventpp::CallbackList<void(std::vector<int> &, int)> callbackList; std::vector<int> dataList(3); callbackList.append( eventpp::conditionalFunctor(&conditionalFunctorIncreaseOne, [](std::vector<int> &, const int index) { return index == 0; } ) ); callbackList.append( eventpp::conditionalFunctor(&conditionalFunctorIncreaseOne, [](std::vector<int> &, const int index) { return index == 1; } ) ); callbackList.append( eventpp::conditionalFunctor(&conditionalFunctorIncreaseOne, [](std::vector<int> &, const int index) { return index == 2; } ) ); REQUIRE(dataList == std::vector<int>{ 0, 0, 0 }); callbackList(dataList, 2); REQUIRE(dataList == std::vector<int>{ 0, 0, 1 }); callbackList(dataList, 0); REQUIRE(dataList == std::vector<int>{ 1, 0, 1 }); callbackList(dataList, 1); REQUIRE(dataList == std::vector<int>{ 1, 1, 1 }); }
1,021
661
<reponame>apjagdale/sxrsdk<filename>SXR/Extensions/sxr-physics/src/main/jni/bullet3/include/Bullet3Collision/BroadPhaseCollision/shared/b3Aabb.h #ifndef B3_AABB_H #define B3_AABB_H #include "Bullet3Common/shared/b3Float4.h" #include "Bullet3Common/shared/b3Mat3x3.h" typedef struct b3Aabb b3Aabb_t; struct b3Aabb { union { float m_min[4]; b3Float4 m_minVec; int m_minIndices[4]; }; union { float m_max[4]; b3Float4 m_maxVec; int m_signedMaxIndices[4]; }; }; inline void b3TransformAabb2(b3Float4ConstArg localAabbMin,b3Float4ConstArg localAabbMax, float margin, b3Float4ConstArg pos, b3QuatConstArg orn, b3Float4* aabbMinOut,b3Float4* aabbMaxOut) { b3Float4 localHalfExtents = 0.5f*(localAabbMax-localAabbMin); localHalfExtents+=b3MakeFloat4(margin,margin,margin,0.f); b3Float4 localCenter = 0.5f*(localAabbMax+localAabbMin); b3Mat3x3 m; m = b3QuatGetRotationMatrix(orn); b3Mat3x3 abs_b = b3AbsoluteMat3x3(m); b3Float4 center = b3TransformPoint(localCenter,pos,orn); b3Float4 extent = b3MakeFloat4(b3Dot3F4(localHalfExtents,b3GetRow(abs_b,0)), b3Dot3F4(localHalfExtents,b3GetRow(abs_b,1)), b3Dot3F4(localHalfExtents,b3GetRow(abs_b,2)), 0.f); *aabbMinOut = center-extent; *aabbMaxOut = center+extent; } /// conservative test for overlap between two aabbs inline bool b3TestAabbAgainstAabb(b3Float4ConstArg aabbMin1,b3Float4ConstArg aabbMax1, b3Float4ConstArg aabbMin2, b3Float4ConstArg aabbMax2) { bool overlap = true; overlap = (aabbMin1.x > aabbMax2.x || aabbMax1.x < aabbMin2.x) ? false : overlap; overlap = (aabbMin1.z > aabbMax2.z || aabbMax1.z < aabbMin2.z) ? false : overlap; overlap = (aabbMin1.y > aabbMax2.y || aabbMax1.y < aabbMin2.y) ? false : overlap; return overlap; } #endif //B3_AABB_H
868
1,831
<filename>logdevice/common/ZookeeperClient.h /** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <chrono> #include <memory> #include <mutex> #include <unordered_map> #include <unordered_set> #include <boost/noncopyable.hpp> #include <folly/futures/Future.h> #include <folly/small_vector.h> #include <zookeeper/zookeeper.h> #include "logdevice/common/UpdateableSharedPtr.h" #include "logdevice/common/ZookeeperClientBase.h" #include "logdevice/common/debug.h" namespace facebook { namespace logdevice { /** * Production Zookeper factory used to create ZookeeperClient instances, * which connect to Zookeeper servers. */ std::unique_ptr<ZookeeperClientBase> zkFactoryProd(const configuration::ZookeeperConfig& config); class ZookeeperClient : public ZookeeperClientBase { public: /** * Attempts to establish a ZK session and create a ZK handle. * * @param quorum comma-separated ip:port strings describing * the Zookeeper quorum to use * @param session_timeout ZK session timeout * * @throws ConstructorFailed() if zookeeper_init() failed because the quorum * string was invalid (sets err to INVALID_PARAM) or the * file descriptor limit was reached (sets err to SYSLIMIT). */ ZookeeperClient(std::string quorum, std::chrono::milliseconds session_timeout); std::shared_ptr<zhandle_t> getHandle() const { return zh_.get(); } /** * Get the state of the zookeeper connection. */ int state() override; /** * Converts a ZK *_STATE constant into a human-readable string. */ static std::string stateString(int state); /** * Sets Zookeeper process-wide debug level to a value corresponding to * the given LogDevice debug level. */ static void setDebugLevel(dbg::Level loglevel); ~ZookeeperClient() override; private: std::chrono::milliseconds session_timeout_; // ZK session timeout UpdateableSharedPtr<zhandle_t> zh_; std::mutex mutex_; // reconnect() checks and replaces zh_ under this lock /** * (re)-establish a session * * @prev previous session, must be in EXPIRED_SESSION_STATE, or nullptr * if we are in constructor and no prior session exists. * * @return 0 on success, -1 if zookeeper_init() failed. err is set to * STALE if prev is not nullptr and does not match zh_, * SYSLIMIT if process is out of fds, INTERNAL if zookeeper_init() * reports an unexpected status (debug build asserts) */ int reconnect(zhandle_t* prev); // ZK session state watcher function, used to track session state // transitions static void sessionWatcher(zhandle_t* zh, int type, int state, const char* path, void* watcherCtx); //////// New API //////// public: void getData(std::string path, data_callback_t cb) override; void exists(std::string path, stat_callback_t cb) override; void setData(std::string path, std::string data, stat_callback_t cb, zk::version_t base_version) override; void create(std::string path, std::string data, create_callback_t cb, std::vector<zk::ACL> acl = zk::openACL_UNSAFE(), int32_t flags = 0) override; void multiOp(std::vector<zk::Op> ops, multi_op_callback_t cb) override; void sync(sync_callback_t cb) override; void createWithAncestors(std::string path, std::string data, create_callback_t cb, std::vector<zk::ACL> acl = zk::openACL_UNSAFE(), int32_t flags = 0) override; private: using c_acl_vector_data_t = folly::small_vector<::ACL, 4>; static zk::Stat toStat(const struct Stat* stat); static void getDataCompletion(int rc, const char* value, int value_len, const struct Stat* stat, const void* context); static void setDataCompletion(int rc, const struct Stat* stat, const void* context); static void existsCompletion(int rc, const struct Stat* stat, const void* context); static void createCompletion(int rc, const char* value, const void* context); static void multiOpCompletion(int rc, const void* context); static void syncCompletion(int rc, const char* value, const void* context); static void setCACL(const std::vector<zk::ACL>& src, ::ACL_vector* c_acl_vector, c_acl_vector_data_t* c_acl_vector_data); static int preparePathBuffer(const std::string& path, int32_t flags, std::string* path_buffer); struct CreateResult { int rc_; std::string path_; }; struct CreateContext { explicit CreateContext(create_callback_t cb, std::vector<zk::ACL> acl) : cb_(std::move(cb)), acl_(std::move(acl)) {} create_callback_t cb_; std::vector<zk::ACL> acl_; ::ACL_vector c_acl_vector_{}; c_acl_vector_data_t c_acl_vector_data_{}; std::string path_buffer_{}; }; // Helpers for createWithAncestors // Returns a stack of znode paths, which are all ancestors of the target path // (i.e., the input param). The immediate parent znode is at the bottom of the // stack (front of the vector). The vector does not contain the target path // itself. // // E.g., if path is /a/b/c/d/e/f, the returned vector would be: // /a/b/c/d/e, /a/b/c/d, ..., /a // front ... back static std::vector<std::string> getAncestorPaths(const std::string& path); // Returns a Zookeeper rc. Considers create ancestors successful and returns // ZOK if every ancestor either already exists or was created. Returns // ZAPIERROR if any of the Try-s contains an exception. (These would be // Future-related exceptions since there are no exceptions in C.) static int aggregateCreateAncestorResults( folly::Try<std::vector<folly::Try<CreateResult>>>&& t); struct MultiOpContext { static constexpr size_t kInlineOps = 4; public: static zk::OpResponse toOpResponse(const zoo_op_result_t& op_result); static std::vector<zk::OpResponse> toOpResponses( const folly::small_vector<zoo_op_result_t, kInlineOps>& op_results); explicit MultiOpContext(std::vector<zk::Op> ops, multi_op_callback_t cb) : ops_(std::move(ops)), cb_(std::move(cb)), // Note: space efficiency here could be improved, but for simplicity, // we resize everything even if some ops don't need some of these // fields. c_acl_vectors_(ops_.size()), c_acl_vector_data_(ops_.size()), path_buffers_(ops_.size()), c_stats_(ops_.size()), c_results_(ops_.size()) { c_ops_.resize(ops_.size()); for (size_t i = 0; i < ops_.size(); ++i) { addCOp(ops_.at(i), i); } } private: // The context object needs to stay in the same memory location so that the // pointers captured by ZK remain valid, should not be moved or copied. MultiOpContext(const MultiOpContext&) = delete; MultiOpContext& operator=(const MultiOpContext&) = delete; MultiOpContext(MultiOpContext&&) = delete; MultiOpContext& operator=(MultiOpContext&&) = delete; void addCCreateOp(const zk::Op& op, size_t index); void addCDeleteOp(const zk::Op& op, size_t index); void addCSetOp(const zk::Op& op, size_t index); void addCCheckOp(const zk::Op& op, size_t index); void addCOp(const zk::Op& op, size_t index); public: std::vector<zk::Op> ops_; multi_op_callback_t cb_; // could be empty folly::small_vector<::ACL_vector, kInlineOps> c_acl_vectors_; folly::small_vector<c_acl_vector_data_t, kInlineOps> c_acl_vector_data_; folly::small_vector<std::string, kInlineOps> path_buffers_; folly::small_vector<struct ::Stat, kInlineOps> c_stats_; folly::small_vector<zoo_op_t, kInlineOps> c_ops_; folly::small_vector<zoo_op_result_t, kInlineOps> c_results_; }; // MultiOpContext friend class ZookeeperClientInMemory; }; }} // namespace facebook::logdevice
3,588
9,959
//CONF: lombok.log.fieldName = myLogger //CONF: lombok.log.fieldIsStatic = false @lombok.extern.slf4j.Slf4j class LoggerWithConfig { }
60
4,262
<filename>components/camel-google/camel-google-functions/src/main/java/org/apache/camel/component/google/functions/GoogleCloudFunctionsClientFactory.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.google.functions; import java.io.FileInputStream; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.Credentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.functions.v1.CloudFunctionsServiceClient; import com.google.cloud.functions.v1.CloudFunctionsServiceSettings; import com.google.common.base.Strings; import org.apache.camel.CamelContext; public final class GoogleCloudFunctionsClientFactory { /** * Prevent instantiation. */ private GoogleCloudFunctionsClientFactory() { } public static CloudFunctionsServiceClient create( CamelContext context, GoogleCloudFunctionsConfiguration configuration) throws Exception { CloudFunctionsServiceClient cloudFunctionsClient = null; if (!Strings.isNullOrEmpty(configuration.getServiceAccountKey())) { Credentials myCredentials = ServiceAccountCredentials .fromStream(new FileInputStream(configuration.getServiceAccountKey())); CloudFunctionsServiceSettings settings = CloudFunctionsServiceSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)).build(); cloudFunctionsClient = CloudFunctionsServiceClient.create(settings); } else { // it needs to define the environment variable GOOGLE_APPLICATION_CREDENTIALS // with the service account file // more info at https://cloud.google.com/docs/authentication/production CloudFunctionsServiceSettings settings = CloudFunctionsServiceSettings.newBuilder().build(); cloudFunctionsClient = CloudFunctionsServiceClient.create(settings); } return cloudFunctionsClient; } }
886
1,481
<filename>docs/asciidoc/modules/ROOT/examples/data/exportJSON/query.json<gh_stars>1000+ {"u.age":42,"u.name":"Adam","u.male":true,"u.kids":["Sam","Anna","Grace"],"labels(u)":["User"]} {"u.age":42,"u.name":"Jim","u.male":null,"u.kids":null,"labels(u)":["User"]} {"u.age":12,"u.name":null,"u.male":null,"u.kids":null,"labels(u)":["User"]}
143
60,067
<filename>aten/src/THC/THCGenerateHalfType.h #ifndef THC_GENERIC_FILE #error "You must define THC_GENERIC_FILE before including THGenerateHalfType.h" #endif #include <TH/THHalf.h> #define scalar_t THHalf #define accreal float #define Real Half #define CReal CudaHalf #define THC_REAL_IS_HALF #line 1 THC_GENERIC_FILE #include THC_GENERIC_FILE #undef scalar_t #undef accreal #undef Real #undef CReal #undef THC_REAL_IS_HALF #ifndef THCGenerateAllTypes #ifndef THCGenerateFloatTypes #undef THC_GENERIC_FILE #endif #endif
214
10,225
package io.quarkus.security.test; import java.io.IOException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Basic secured servlet test target */ @ServletSecurity(@HttpConstraint(rolesAllowed = { "user" })) @WebServlet(name = "MySecureServlet", urlPatterns = "/secure-test", initParams = { @WebInitParam(name = "message", value = "A secured message") }) public class TestSecureServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getWriter().write(getInitParameter("message")); } }
300
714
<gh_stars>100-1000 // // CommonItemModel.h // ZYSideSlipFilter // // Created by lzy on 16/10/16. // Copyright © 2016年 zhiyi. All rights reserved. // #import <Foundation/Foundation.h> @interface CommonItemModel : NSObject @property (copy, nonatomic) NSString *itemId; @property (copy, nonatomic) NSString *itemName; @property (assign, nonatomic) BOOL selected; @end
132
1,136
<reponame>liyichao/kids #include "gtest/gtest.h" #include "kids.h" #include "util.h" TEST(TestParseMessage, Test1) { char str[] = "nginx|[Tue, 22 Nov 2011 08:43:41] r6z4exqgaft5ruhrd6jy8gvahpamg6xjhr5hpojdfysa7ijgh4chn8qezti2k4k6ckzzlpf07x8b6fxpfnr07gl1ls431qwgc6"; Message *msg = ParseMessage(str, sizeof(str) - 1); EXPECT_STREQ("nginx", msg->topic); EXPECT_STREQ("[Tue, 22 Nov 2011 08:43:41] r6z4exqgaft5ruhrd6jy8gvahpamg6xjhr5hpojdfysa7ijgh4chn8qezti2k4k6ckzzlpf07x8b6fxpfnr07gl1ls431qwgc6", msg->content); } TEST(TestParseMessage, Test2) { char str[] = "[Tue, 22 Nov 2011 08:43:41] r6z4exqgaft5ruhrd6jy8gvahpamg6xjhr5hpojdfysa7ijgh4chn8qezti2k4k6ckzzlpf07x8b6fxpfnr07gl1ls431qwgc6"; Message *msg = ParseMessage(str, sizeof(str) - 1); EXPECT_STREQ("zhihu.notopic", msg->topic); EXPECT_STREQ("[Tue, 22 Nov 2011 08:43:41] r6z4exqgaft5ruhrd6jy8gvahpamg6xjhr5hpojdfysa7ijgh4chn8qezti2k4k6ckzzlpf07x8b6fxpfnr07gl1ls431qwgc6", msg->content); } TEST(TestParseMessage, Test3) { char str[] = "tornado|"; Message *msg = ParseMessage(str, sizeof(str) - 1); EXPECT_STREQ("tornado", msg->topic); EXPECT_STREQ("", msg->content); } TEST(TestParseMessage, Test4) { char str[] = "tornado|nginx|log details"; Message *msg = ParseMessage(str, sizeof(str) - 1); EXPECT_STREQ("tornado", msg->topic); EXPECT_STREQ("nginx|log details", msg->content); }
708
5,169
<filename>Specs/7/b/1/SDKService/1.0.0/SDKService.podspec.json { "name": "SDKService", "version": "1.0.0", "summary": "SDKService", "description": "this is SDKService", "homepage": "https://github.com/acv-ninhnm/SDKService", "license": "MIT", "authors": { "acv-ninhnm": "<EMAIL>" }, "platforms": { "ios": "5.0" }, "source": { "git": "https://github.com/acv-ninhnm/SDKService.git", "tag": "1.0.0" }, "source_files": [ "SDKService", "SDKService/**/*.{h,m}" ] }
243
575
<filename>chrome/browser/predictors/navigation_id.h<gh_stars>100-1000 // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_PREDICTORS_NAVIGATION_ID_H_ #define CHROME_BROWSER_PREDICTORS_NAVIGATION_ID_H_ #include <stddef.h> #include "base/feature_list.h" #include "base/time/time.h" #include "components/sessions/core/session_id.h" #include "services/metrics/public/cpp/ukm_source_id.h" #include "url/gurl.h" namespace content { class WebContents; } namespace predictors { // Represents a single navigation for a render frame. struct NavigationID { NavigationID(); explicit NavigationID(content::WebContents* web_contents); NavigationID(content::WebContents* web_contents, ukm::SourceId ukm_source_id, const GURL& main_frame_url, const base::TimeTicks& creation_time); NavigationID(const NavigationID& other); bool operator<(const NavigationID& rhs) const; bool operator==(const NavigationID& rhs) const; bool operator!=(const NavigationID& rhs) const; // Returns true iff the tab_id is valid and the Main frame URL is set. bool is_valid() const; SessionID tab_id; ukm::SourceId ukm_source_id; GURL main_frame_url; // NOTE: Even though we store the creation time here, it is not used during // comparison of two NavigationIDs because it cannot always be determined // correctly. base::TimeTicks creation_time; }; } // namespace predictors #endif // CHROME_BROWSER_PREDICTORS_NAVIGATION_ID_H_
561
372
<filename>lsass/tests/test_LsaAllocSecurityIdentifierFromBinary/main.c /* Editor Settings: expandtabs and use 4 spaces for indentation * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: * * -*- mode: c, c-basic-offset: 4 -*- */ /* * Copyright © BeyondTrust Software 2004 - 2019 * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Copyright (C) BeyondTrust Software. All rights reserved. * * Module Name: * * main.c * * Abstract: * * BeyondTrust Security and Authentication Subsystem (LSASS) * * Test Program for exercising LsaAllocSecurityIdentifierFromBinary * * Authors: <NAME> (<EMAIL>) * */ #define _POSIX_PTHREAD_SEMANTICS 1 #include "config.h" #include "lsasystem.h" #include "lsadef.h" #include "lsa/lsa.h" #include "lwmem.h" #include "lwstr.h" #include "lwsecurityidentifier.h" #include "lsautils.h" DWORD ParseArgs( int argc, char* argv[], PSTR* ppszSIDHexStr ); VOID ShowUsage(); int main( int argc, char* argv[] ) { DWORD dwError = 0; PSTR pszSIDHexStr = NULL; PSTR pszSIDStr = NULL; UCHAR* pucSIDByteArr = NULL; DWORD dwSIDByteCount = 0; PLSA_SECURITY_IDENTIFIER pSID = NULL; dwError = ParseArgs(argc, argv, &pszSIDHexStr); BAIL_ON_LSA_ERROR(dwError); printf("Converting hex SID string: \"%s\"\n", pszSIDHexStr); dwError = LsaHexStrToByteArray( pszSIDHexStr, NULL, &pucSIDByteArr, &dwSIDByteCount); BAIL_ON_LSA_ERROR(dwError); dwError = LsaAllocSecurityIdentifierFromBinary( pucSIDByteArr, dwSIDByteCount, &pSID); BAIL_ON_LSA_ERROR(dwError); printf("LsaAllocSecurityIdentifierFromBinary() successful\n"); dwError = LsaGetSecurityIdentifierString(pSID, &pszSIDStr); BAIL_ON_LSA_ERROR(dwError); printf("LsaGetSecurityIdentifierString() returns: \"%s\"\n", pszSIDStr); cleanup: LW_SAFE_FREE_STRING(pszSIDHexStr); LW_SAFE_FREE_STRING(pszSIDStr); LW_SAFE_FREE_MEMORY(pucSIDByteArr); if (pSID) { LsaFreeSecurityIdentifier(pSID); } return (dwError); error: fprintf(stderr, "Failed to convert SID. Error code [%u]\n", dwError); goto cleanup; } DWORD ParseArgs( int argc, char* argv[], PSTR* ppszSIDHexStr ) { typedef enum { PARSE_MODE_OPEN = 0 } ParseMode; DWORD dwError = 0; int iArg = 1; PSTR pszArg = NULL; PSTR pszSIDHexStr = NULL; ParseMode parseMode = PARSE_MODE_OPEN; do { pszArg = argv[iArg++]; if (pszArg == NULL || *pszArg == '\0') { break; } switch (parseMode) { case PARSE_MODE_OPEN: if ((strcmp(pszArg, "--help") == 0) || (strcmp(pszArg, "-h") == 0)) { ShowUsage(); exit(0); } else { dwError = LwAllocateString(pszArg, &pszSIDHexStr); BAIL_ON_LSA_ERROR(dwError); } break; } } while (iArg < argc); if (LW_IS_NULL_OR_EMPTY_STR(pszSIDHexStr)) { fprintf(stderr, "Please specify a hex string, i.e. 01FA020101.\n"); ShowUsage(); exit(1); } *ppszSIDHexStr = pszSIDHexStr; cleanup: return dwError; error: LW_SAFE_FREE_STRING(pszSIDHexStr); *ppszSIDHexStr = NULL; goto cleanup; } void ShowUsage() { printf("Usage: test-lsa_alloc_security_identifier_from_binary <hex_value_of_sid>\n"); }
2,112
1,835
<reponame>elan17/GamestonkTerminal # flake8: noqa # pylint: disable=unused-import from .stocks import stocks_api as stocks
45
334
<filename>watch-library/hardware/hal/src/hal_rand_sync.c /** * \file * * \brief Generic Random Number Generator (RNG) functionality declaration. * * Copyright (c) 2015-2018 Microchip Technology Inc. and its subsidiaries. * * \asf_license_start * * \page License * * Subject to your compliance with these terms, you may use Microchip * software and any derivatives exclusively with Microchip products. * It is your responsibility to comply with third party license terms applicable * to your use of third party software (including open source software) that * may accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, * WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, * INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE * LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL * LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE * SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE * POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT * ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY * RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. * * \asf_license_stop * */ #include <utils.h> #include "hal_rand_sync.h" #define HAL_RNG_SYNC_VERSION 0x00000001u int32_t rand_sync_init(struct rand_sync_desc *const desc, void *const hw) { ASSERT(desc); return _rand_sync_init(&desc->dev, hw); } void rand_sync_deinit(struct rand_sync_desc *const desc) { ASSERT(desc); _rand_sync_deinit(&desc->dev); } int32_t rand_sync_enable(struct rand_sync_desc *const desc) { ASSERT(desc); return _rand_sync_enable(&desc->dev); } void rand_sync_disable(struct rand_sync_desc *const desc) { ASSERT(desc); _rand_sync_disable(&desc->dev); } int32_t rand_sync_set_seed(struct rand_sync_desc *const desc, const uint32_t seed) { ASSERT(desc); return _rand_sync_set_seed(&desc->dev, seed); } /** * \brief Read data bits */ static uint32_t _rand_sync_read_data(const struct _rand_sync_dev *dev, const uint8_t n_bits) { uint8_t r_bits = (dev->n_bits < 1) ? 32 : dev->n_bits; if (r_bits < n_bits) { uint8_t i; uint32_t d = 0; /* Join read bits */ for (i = 0; i < n_bits; i += r_bits) { d |= (uint32_t)(_rand_sync_read_one(dev) << i); } return d; } else { return _rand_sync_read_one(dev); } } uint8_t rand_sync_read8(const struct rand_sync_desc *const desc) { ASSERT(desc); return (uint8_t)_rand_sync_read_data(&desc->dev, 8); } uint32_t rand_sync_read32(const struct rand_sync_desc *const desc) { ASSERT(desc); return (uint32_t)_rand_sync_read_data(&desc->dev, 32); } void rand_sync_read_buf8(const struct rand_sync_desc *const desc, uint8_t *buf, uint32_t len) { uint32_t i; ASSERT(desc && (buf && len)); for (i = 0; i < len; i++) { buf[i] = (uint8_t)_rand_sync_read_data(&desc->dev, 8); } } void rand_sync_read_buf32(const struct rand_sync_desc *const desc, uint32_t *buf, uint32_t len) { uint32_t i; ASSERT(desc && (buf && len)); for (i = 0; i < len; i++) { buf[i] = (uint32_t)_rand_sync_read_data(&desc->dev, 32); } } uint32_t rand_sync_get_version(void) { return HAL_RNG_SYNC_VERSION; }
1,277
5,169
{ "name": "ColorMaskingButton", "version": "0.1.0", "summary": "A color masking effect for UIButton.", "description": "Dynamically pan the color of a button to the offset of another view's frame.", "homepage": "https://github.com/lawrnce/ColorMaskingButton", "license": "MIT", "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/lawrnce/ColorMaskingButton.git", "tag": "0.1.0" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "Pod/Classes/**/*", "resource_bundles": { "ColorMaskingButton": [ "Pod/Assets/*.png" ] }, "frameworks": "UIKit" }
265
1,062
/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __MR4C_DIMENSION_CATALOG_H__ #define __MR4C_DIMENSION_CATALOG_H__ #include <string> #include "keys/keys_api.h" namespace MR4C { /** * Catalog of standard dimensions */ class DimensionCatalog { public : enum Type { ANCHOR, FRAME, SENSOR, IMAGE_TYPE, DATA_SOURCE }; /** * Parses the string equivalent of the enum. * For example: "FRAME" --> FRAME */ static Type enumFromString(std::string strType); /** * Returns the string equivalent of the enum. * For example: FRAME --> "FRAME" */ static std::string enumToString(Type type); /** * Returns true if the specified dimension type exists in * the keyspace */ static bool hasDimension(Keyspace keyspace, Type type); /** * Finds the KeyspaceDimension for the dimension type. * Will throw an exception if it is not found */ static KeyspaceDimension findDimension(Keyspace keyspace, Type type); /** * Create KeyDimension object for the dimension type */ static DataKeyDimension toDimension(Type type); }; } #endif
574
2,406
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <vector> #include "split.hpp" #include "ngraph/node.hpp" namespace ngraph { namespace pass { namespace low_precision { class LP_TRANSFORMATIONS_API VariadicSplitTransformation : public SplitTransformation { public: NGRAPH_RTTI_DECLARATION; VariadicSplitTransformation(const Params& params = Params()); }; } // namespace low_precision } // namespace pass } // namespace ngraph
166
308
#ifndef __INC_OCTOWS2811_CONTROLLER_H #define __INC_OCTOWS2811_CONTROLLER_H #ifdef USE_OCTOWS2811 // #include "OctoWS2811.h" FASTLED_NAMESPACE_BEGIN template<EOrder RGB_ORDER = GRB, uint8_t CHIP = WS2811_800kHz> class COctoWS2811Controller : public CPixelLEDController<RGB_ORDER, 8, 0xFF> { OctoWS2811 *pocto; uint8_t *drawbuffer,*framebuffer; void _init(int nLeds) { if(pocto == NULL) { drawbuffer = (uint8_t*)malloc(nLeds * 8 * 3); framebuffer = (uint8_t*)malloc(nLeds * 8 * 3); // byte ordering is handled in show by the pixel controller int config = WS2811_RGB; config |= CHIP; pocto = new OctoWS2811(nLeds, framebuffer, drawbuffer, config); pocto->begin(); } } public: COctoWS2811Controller() { pocto = NULL; } virtual void init() { /* do nothing yet */ } typedef union { uint8_t bytes[8]; uint32_t raw[2]; } Lines; virtual void showPixels(PixelController<RGB_ORDER, 8, 0xFF> & pixels) { _init(pixels.size()); uint8_t *pData = drawbuffer; while(pixels.has(1)) { Lines b; for(int i = 0; i < 8; i++) { b.bytes[i] = pixels.loadAndScale0(i); } transpose8x1_MSB(b.bytes,pData); pData += 8; for(int i = 0; i < 8; i++) { b.bytes[i] = pixels.loadAndScale1(i); } transpose8x1_MSB(b.bytes,pData); pData += 8; for(int i = 0; i < 8; i++) { b.bytes[i] = pixels.loadAndScale2(i); } transpose8x1_MSB(b.bytes,pData); pData += 8; pixels.stepDithering(); pixels.advanceData(); } pocto->show(); } }; FASTLED_NAMESPACE_END #endif #endif
736
335
{ "word": "Kalong", "definitions": [ "A flying fox found in SE Asia and Indonesia." ], "parts-of-speech": "Noun" }
62
14,668
<filename>ui/views/test/widget_test_api.h // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_VIEWS_TEST_WIDGET_TEST_API_H_ #define UI_VIEWS_TEST_WIDGET_TEST_API_H_ namespace views { // Makes Widget::OnNativeWidgetActivationChanged return false, which prevents // handling of the corresponding event (if the native widget implementation // takes this into account). void DisableActivationChangeHandlingForTests(); } // namespace views #endif // UI_VIEWS_TEST_WIDGET_TEST_API_H_
193
346
class EmptyDicomSeriesException(Exception): """ Exception that is raised when the given folder does not contain dcm-files. """ def __init__(self, *args): if not args: args = ('The specified path does not contain dcm-files. Please ensure that ' 'the path points to a folder containing a DICOM-series.', ) Exception.__init__(self, *args)
153
32,544
package com.baeldung.vertxspring.repository; import com.baeldung.vertxspring.entity.Article; import org.springframework.data.jpa.repository.JpaRepository; public interface ArticleRepository extends JpaRepository<Article, Long> { }
76
1,611
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2019-present Datadog, Inc. #include "_util.h" #include "cgo_free.h" #include "rtloader_mem.h" #include "stringutils.h" #include <stdio.h> // must be set by the caller static cb_get_subprocess_output_t cb_get_subprocess_output = NULL; static PyObject *subprocess_output(PyObject *self, PyObject *args, PyObject *kw); // Exceptions /*! \fn void addSubprocessException(PyObject *m) \brief Adds a custom SubprocessOutputEmptyError exception to the module passed as parameter. \param m A PyObject* pointer to the module we wish to register the exception with. */ void addSubprocessException(PyObject *m) { PyObject *SubprocessOutputEmptyError = PyErr_NewException(_SUBPROCESS_OUTPUT_ERROR_NS_NAME, NULL, NULL); PyModule_AddObject(m, _SUBPROCESS_OUTPUT_ERROR_NAME, SubprocessOutputEmptyError); } static PyMethodDef methods[] = { { "subprocess_output", (PyCFunction)subprocess_output, METH_VARARGS | METH_KEYWORDS, "Exec a process and return the output." }, { "get_subprocess_output", (PyCFunction)subprocess_output, METH_VARARGS | METH_KEYWORDS, "Exec a process and return the output." }, { NULL, NULL } // guards }; #ifdef DATADOG_AGENT_THREE static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, _UTIL_MODULE_NAME, NULL, -1, methods }; PyMODINIT_FUNC PyInit__util(void) { PyObject *m = PyModule_Create(&module_def); addSubprocessException(m); return m; } #elif defined(DATADOG_AGENT_TWO) // in Python2 keep the object alive for the program lifetime static PyObject *module; void Py2_init__util() { module = Py_InitModule(_UTIL_MODULE_NAME, methods); addSubprocessException(module); } #endif void _set_get_subprocess_output_cb(cb_get_subprocess_output_t cb) { cb_get_subprocess_output = cb; } /*! \fn void raiseEmptyOutputError() \brief sets the SubprocessOutputEmptyError exception as the interpreter error. If everything goes well the exception error will be set in the interpreter. Otherwise, if the module or the exception class are not found, the relevant error will be set in the interpreter instead. */ static void raiseEmptyOutputError() { PyObject *utilModule = PyImport_ImportModule(_UTIL_MODULE_NAME); if (utilModule == NULL) { PyErr_SetString(PyExc_TypeError, "error: no module '" _UTIL_MODULE_NAME "'"); return; } PyObject *excClass = PyObject_GetAttrString(utilModule, _SUBPROCESS_OUTPUT_ERROR_NAME); if (excClass == NULL) { Py_DecRef(utilModule); PyErr_SetString(PyExc_TypeError, "no attribute '" _SUBPROCESS_OUTPUT_ERROR_NS_NAME "' found"); return; } PyErr_SetString(excClass, "get_subprocess_output expected output but had none."); Py_DecRef(excClass); Py_DecRef(utilModule); } /*! \fn PyObject *subprocess_output(PyObject *self, PyObject *args) \brief This function implements the `_util.subprocess_output` _and_ `_util.get_subprocess_output` python method, allowing to execute a subprocess and collect its output. \param self A PyObject* pointer to the _util module. \param args A PyObject* pointer to the args tuple with the desired subprocess commands, and optionally a boolean raise_on_empty flag. \param kw A PyObject* pointer to the kw dict with optionally an env dict. \return a PyObject * pointer to a python tuple with the stdout, stderr output and the command exit code. This function is callable as the `_util.subprocess_output` or `_util.get_subprocess_output` python methods. The command arguments list is fed to the CGO callback, where the command is executed in go-land. The stdout, stderr and exit codes for the command are returned by the callback; these are then converted into python strings and integer respectively and returned in a tuple. If the optional `raise_on_empty` boolean flag is set, and the command output is empty an exception will be raised: the error will be set in the interpreter and NULL will be returned. */ PyObject *subprocess_output(PyObject *self, PyObject *args, PyObject *kw) { int i; int raise = 0; int ret_code = 0; int subprocess_args_sz = 0; int subprocess_env_sz = 0; char **subprocess_args = NULL; char **subprocess_env = NULL; char *c_stdout = NULL; char *c_stderr = NULL; char *exception = NULL; PyObject *cmd_args = NULL; PyObject *cmd_raise_on_empty = NULL; PyObject *cmd_env = NULL; PyObject *pyResult = NULL; if (!cb_get_subprocess_output) { Py_RETURN_NONE; } PyGILState_STATE gstate = PyGILState_Ensure(); static char *keywords[] = { "command", "raise_on_empty", "env", NULL }; // `cmd_args` is mandatory and should be a list, `cmd_raise_on_empty` is an optional // boolean. The string after the ':' is used as the function name in error messages. if (!PyArg_ParseTupleAndKeywords(args, kw, "O|O" PY_ARG_PARSE_TUPLE_KEYWORD_ONLY "O:get_subprocess_output", keywords, &cmd_args, &cmd_raise_on_empty, &cmd_env)) { goto cleanup; } if (!PyList_Check(cmd_args)) { PyErr_SetString(PyExc_TypeError, "command args is not a list"); goto cleanup; } // We already PyList_Check cmd_args, so PyList_Size won't fail and return -1 subprocess_args_sz = PyList_Size(cmd_args); if (subprocess_args_sz == 0) { PyErr_SetString(PyExc_TypeError, "invalid command: empty list"); goto cleanup; } if (!(subprocess_args = (char **)_malloc(sizeof(*subprocess_args) * (subprocess_args_sz + 1)))) { PyErr_SetString(PyExc_MemoryError, "unable to allocate memory, bailing out"); goto cleanup; } // init to NULL for safety - could use memset, but this is safer. for (i = 0; i <= subprocess_args_sz; i++) { subprocess_args[i] = NULL; } for (i = 0; i < subprocess_args_sz; i++) { char *subprocess_arg = as_string(PyList_GetItem(cmd_args, i)); if (subprocess_arg == NULL) { PyErr_SetString(PyExc_TypeError, "command argument must be valid strings"); goto cleanup; } subprocess_args[i] = subprocess_arg; } if (cmd_env != NULL && cmd_env != Py_None) { if (!PyDict_Check(cmd_env)) { PyErr_SetString(PyExc_TypeError, "env is not a dict"); goto cleanup; } subprocess_env_sz = PyDict_Size(cmd_env); if (subprocess_env_sz != 0) { if (!(subprocess_env = (char **)_malloc(sizeof(*subprocess_env) * (subprocess_env_sz + 1)))) { PyErr_SetString(PyExc_MemoryError, "unable to allocate memory, bailing out"); goto cleanup; } for (i = 0; i <= subprocess_env_sz; i++) { subprocess_env[i] = NULL; } Py_ssize_t pos = 0; PyObject *key = NULL, *value = NULL; for (i = 0; i < subprocess_env_sz && PyDict_Next(cmd_env, &pos, &key, &value); i++) { char *env_key = as_string(key); if (env_key == NULL) { PyErr_SetString(PyExc_TypeError, "env key is not a string"); goto cleanup; } char *env_value = as_string(value); if (env_value == NULL) { PyErr_SetString(PyExc_TypeError, "env value is not a string"); _free(env_key); goto cleanup; } char *env = (char *)_malloc((strlen(env_key) + 1 + strlen(env_value) + 1) * sizeof(*env)); if (env == NULL) { PyErr_SetString(PyExc_MemoryError, "unable to allocate memory, bailing out"); _free(env_key); _free(env_value); goto cleanup; } strcpy(env, env_key); strcat(env, "="); strcat(env, env_value); _free(env_key); _free(env_value); subprocess_env[i] = env; } } } if (cmd_raise_on_empty != NULL && !PyBool_Check(cmd_raise_on_empty)) { PyErr_SetString(PyExc_TypeError, "bad raise_on_empty argument: should be bool"); goto cleanup; } if (cmd_raise_on_empty == Py_True) { raise = 1; } // Release the GIL so Python can execute other checks while Go runs the subprocess PyGILState_Release(gstate); PyThreadState *Tstate = PyEval_SaveThread(); cb_get_subprocess_output(subprocess_args, subprocess_env, &c_stdout, &c_stderr, &ret_code, &exception); // Acquire the GIL now that Go is done PyEval_RestoreThread(Tstate); gstate = PyGILState_Ensure(); if (raise && strlen(c_stdout) == 0) { raiseEmptyOutputError(); goto cleanup; } if (exception) { PyErr_SetString(PyExc_Exception, exception); goto cleanup; } PyObject *pyStdout = NULL; if (c_stdout) { pyStdout = PyStringFromCString(c_stdout); } else { Py_INCREF(Py_None); pyStdout = Py_None; } PyObject *pyStderr = NULL; if (c_stderr) { pyStderr = PyStringFromCString(c_stderr); } else { Py_INCREF(Py_None); pyStderr = Py_None; } pyResult = PyTuple_New(3); PyTuple_SetItem(pyResult, 0, pyStdout); PyTuple_SetItem(pyResult, 1, pyStderr); #ifdef DATADOG_AGENT_THREE PyTuple_SetItem(pyResult, 2, PyLong_FromLong(ret_code)); #else PyTuple_SetItem(pyResult, 2, PyInt_FromLong(ret_code)); #endif cleanup: if (c_stdout) { cgo_free(c_stdout); } if (c_stderr) { cgo_free(c_stderr); } if (exception) { cgo_free(exception); } if (subprocess_args) { for (i = 0; i <= subprocess_args_sz && subprocess_args[i]; i++) { _free(subprocess_args[i]); } _free(subprocess_args); } if (subprocess_env) { for (i = 0; i <= subprocess_env_sz && subprocess_env[i]; i++) { _free(subprocess_env[i]); } _free(subprocess_env); } // Please note that if we get here we have a matching PyGILState_Ensure above, so we're safe. PyGILState_Release(gstate); // pyResult will be NULL in the face of error to raise the exception set by PyErr_SetString return pyResult; }
4,543
754
<gh_stars>100-1000 # Generated by the Protocol Buffers compiler. DO NOT EDIT! # source: multiproc/primes.proto # plugin: grpclib.plugin.main import abc import typing import grpclib.const import grpclib.client if typing.TYPE_CHECKING: import grpclib.server import google.protobuf.wrappers_pb2 import multiproc.primes_pb2 class PrimesBase(abc.ABC): @abc.abstractmethod async def Check(self, stream: 'grpclib.server.Stream[multiproc.primes_pb2.Request, multiproc.primes_pb2.Reply]') -> None: pass def __mapping__(self) -> typing.Dict[str, grpclib.const.Handler]: return { '/primes.Primes/Check': grpclib.const.Handler( self.Check, grpclib.const.Cardinality.UNARY_UNARY, multiproc.primes_pb2.Request, multiproc.primes_pb2.Reply, ), } class PrimesStub: def __init__(self, channel: grpclib.client.Channel) -> None: self.Check = grpclib.client.UnaryUnaryMethod( channel, '/primes.Primes/Check', multiproc.primes_pb2.Request, multiproc.primes_pb2.Reply, )
541
400
import os import json import shutil import numpy as np from typing import Any from typing import Dict from typing import List from typing import Type from typing import Tuple from typing import Union from typing import Callable from typing import Optional from typing import NamedTuple from tqdm.autonotebook import tqdm from cfdata.tabular import TabularData from cftool.ml import ModelPattern from cftool.ml import EnsemblePattern from cftool.dist import Parallel from cftool.misc import update_dict from cftool.misc import shallow_copy_dict from cftool.ml.utils import patterns_type from cftool.ml.utils import Comparer from cftool.ml.utils import Estimator from .pipeline import SimplePipeline from .pipeline import CarefreePipeline from ...data import MLData from ...data import MLInferenceData from ...trainer import get_sorted_checkpoints from ...constants import SCORES_FILE from ...constants import WARNING_PREFIX from ...constants import CHECKPOINTS_FOLDER from ...constants import ML_PIPELINE_SAVE_NAME from ...dist.ml import Experiment from ...dist.ml import ExperimentResults from ...misc.toolkit import to_2d from ...misc.toolkit import get_latest_workplace from ...models.ml.protocol import MLCoreProtocol def register_core(name: str) -> Callable[[Type], Type]: return MLCoreProtocol.register(name) pipelines_type = Dict[str, List[SimplePipeline]] various_pipelines_type = Union[ SimplePipeline, List[SimplePipeline], Dict[str, SimplePipeline], pipelines_type, ] def _to_pipelines(pipelines: various_pipelines_type) -> pipelines_type: if isinstance(pipelines, dict): pipeline_dict = {} for key, value in pipelines.items(): if isinstance(value, list): pipeline_dict[key] = value else: pipeline_dict[key] = [value] else: if not isinstance(pipelines, list): pipelines = [pipelines] pipeline_dict = {} for pipeline in pipelines: assert pipeline.model is not None key = pipeline.model.__identifier__ pipeline_dict.setdefault(key, []).append(pipeline) return pipeline_dict def evaluate( data: Union[MLData, MLInferenceData], *, metrics: Union[str, List[str]], metric_configs: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, contains_labels: bool = True, pipelines: Optional[various_pipelines_type] = None, predict_config: Optional[Dict[str, Any]] = None, other_patterns: Optional[Dict[str, patterns_type]] = None, comparer_verbose_level: Optional[int] = 1, ) -> Comparer: if not contains_labels: err_msg = "`cflearn.evaluate` must be called with `contains_labels = True`" raise ValueError(err_msg) if metric_configs is None: metric_configs = [{} for _ in range(len(metrics))] patterns = {} x, y = data.x_train, data.y_train if pipelines is None: msg = None if y is None: msg = "either `pipelines` or `y` should be provided" if other_patterns is None: msg = "either `pipelines` or `other_patterns` should be provided" if msg is not None: raise ValueError(msg) else: pipelines = _to_pipelines(pipelines) # get data # TODO : different pipelines may have different labels if y is not None: y = to_2d(y) else: if not isinstance(x, str): raise ValueError("`x` should be str when `y` is not provided") data_pipeline = list(pipelines.values())[0][0] if not isinstance(data_pipeline, CarefreePipeline): raise ValueError("only `CarefreePipeline` can handle file inputs") cf_data = data_pipeline.cf_data assert cf_data is not None x, y = cf_data.read_file(x, contains_labels=contains_labels) y = cf_data.transform(x, y).y # get metrics if predict_config is None: predict_config = {} predict_config.setdefault("contains_labels", contains_labels) for name, pipeline_list in pipelines.items(): patterns[name] = [ pipeline.to_pattern(**predict_config) for pipeline in pipeline_list ] if other_patterns is not None: for other_name in other_patterns.keys(): if other_name in patterns: print( f"{WARNING_PREFIX}'{other_name}' is found in " "`other_patterns`, it will be overwritten" ) update_dict(other_patterns, patterns) if isinstance(metrics, list): metrics_list = metrics else: assert isinstance(metrics, str) metrics_list = [metrics] if isinstance(metric_configs, list): metric_configs_list = metric_configs else: assert isinstance(metric_configs, dict) metric_configs_list = [metric_configs] estimators = [ Estimator(metric, metric_config=metric_config) for metric, metric_config in zip(metrics_list, metric_configs_list) ] comparer = Comparer(patterns, estimators) comparer.compare(data, y, verbose_level=comparer_verbose_level) return comparer def task_loader( workplace: str, pipeline_base: Type[SimplePipeline] = CarefreePipeline, compress: bool = True, ) -> SimplePipeline: export_folder = os.path.join(workplace, ML_PIPELINE_SAVE_NAME) m = pipeline_base.load(export_folder=export_folder, compress=compress) assert isinstance(m, SimplePipeline) return m def load_experiment_results( results: ExperimentResults, pipeline_base: Type[SimplePipeline], ) -> pipelines_type: pipelines_dict: Dict[str, Dict[int, SimplePipeline]] = {} iterator = list(zip(results.workplaces, results.workplace_keys)) for workplace, workplace_key in tqdm(iterator, desc="load"): pipeline = task_loader(workplace, pipeline_base) model, str_i = workplace_key pipelines_dict.setdefault(model, {})[int(str_i)] = pipeline return {k: [v[i] for i in sorted(v)] for k, v in pipelines_dict.items()} class RepeatResult(NamedTuple): data: Optional[TabularData] experiment: Optional[Experiment] pipelines: Optional[Dict[str, List[SimplePipeline]]] patterns: Optional[Dict[str, List[ModelPattern]]] def repeat_with( data: MLData, *, pipeline_base: Type[SimplePipeline] = CarefreePipeline, workplace: str = "_repeat", models: Union[str, List[str]] = "fcnn", model_configs: Optional[Dict[str, Dict[str, Any]]] = None, predict_config: Optional[Dict[str, Any]] = None, sequential: Optional[bool] = None, num_jobs: int = 1, num_repeat: int = 5, return_patterns: bool = True, compress: bool = True, use_tqdm: bool = True, available_cuda_list: Optional[List[int]] = None, resource_config: Optional[Dict[str, Any]] = None, task_meta_kwargs: Optional[Dict[str, Any]] = None, is_fix: bool = False, **kwargs: Any, ) -> RepeatResult: if os.path.isdir(workplace) and not is_fix: print(f"{WARNING_PREFIX}'{workplace}' already exists, it will be erased") shutil.rmtree(workplace) kwargs = shallow_copy_dict(kwargs) if isinstance(models, str): models = [models] if sequential is None: sequential = num_jobs <= 1 if model_configs is None: model_configs = {} def is_buggy(i_: int, model_: str) -> bool: i_workplace = os.path.join(workplace, model_, str(i_)) i_latest_workplace = get_latest_workplace(i_workplace) if i_latest_workplace is None: return True checkpoint_folder = os.path.join(i_latest_workplace, CHECKPOINTS_FOLDER) if not os.path.isfile(os.path.join(checkpoint_folder, SCORES_FILE)): return True if not get_sorted_checkpoints(checkpoint_folder): return True return False def fetch_config(core_name: str) -> Dict[str, Any]: local_kwargs = shallow_copy_dict(kwargs) assert model_configs is not None local_core_config = model_configs.setdefault(core_name, {}) local_kwargs["core_name"] = core_name local_kwargs["core_config"] = shallow_copy_dict(local_core_config) return shallow_copy_dict(local_kwargs) pipelines_dict: Optional[Dict[str, List[SimplePipeline]]] = None if sequential: cuda = kwargs.pop("cuda", None) experiment = None tqdm_settings = kwargs.setdefault("tqdm_settings", {}) tqdm_settings["tqdm_position"] = 2 if not return_patterns: print( f"{WARNING_PREFIX}`return_patterns` should be " "True when `sequential` is True, because patterns " "will always be generated" ) return_patterns = True pipelines_dict = {} if not use_tqdm: iterator = models else: iterator = tqdm(models, total=len(models), position=0) for model in iterator: local_pipelines = [] sub_iterator = range(num_repeat) if use_tqdm: sub_iterator = tqdm( sub_iterator, total=num_repeat, position=1, leave=False, ) for i in sub_iterator: if is_fix and not is_buggy(i, model): continue local_config = fetch_config(model) local_workplace = os.path.join(workplace, model, str(i)) local_config.setdefault("workplace", local_workplace) m = pipeline_base(**local_config) m.fit(data, cuda=cuda) local_pipelines.append(m) pipelines_dict[model] = local_pipelines else: if num_jobs <= 1: print( f"{WARNING_PREFIX}we suggest setting `sequential` " f"to True when `num_jobs` is {num_jobs}" ) # data data_folder = Experiment.dump_data_bundle( data.x_train, data.y_train, data.x_valid, data.y_valid, workplace=workplace, ) # experiment experiment = Experiment( num_jobs=num_jobs, available_cuda_list=available_cuda_list, resource_config=resource_config, ) for model in models: for i in range(num_repeat): if is_fix and not is_buggy(i, model): continue local_config = fetch_config(model) experiment.add_task( model=model, compress=compress, root_workplace=workplace, workplace_key=(model, str(i)), config=local_config, data_folder=data_folder, **(task_meta_kwargs or {}), ) # finalize results = experiment.run_tasks(use_tqdm=use_tqdm) if return_patterns: pipelines_dict = load_experiment_results(results, pipeline_base) patterns = None if return_patterns: assert pipelines_dict is not None if predict_config is None: predict_config = {} patterns = { model: [m.to_pattern(**predict_config) for m in pipelines] for model, pipelines in pipelines_dict.items() } cf_data = None if patterns is not None: m = patterns[models[0]][0].model if isinstance(m, CarefreePipeline): cf_data = m.cf_data return RepeatResult(cf_data, experiment, pipelines_dict, patterns) def pack_repeat( workplace: str, pipeline_base: Type[SimplePipeline], *, num_jobs: int = 1, ) -> List[str]: sub_workplaces = [] for stuff in sorted(os.listdir(workplace)): stuff_path = os.path.join(workplace, stuff) if not os.path.isdir(stuff_path): continue sub_workplaces.append(get_latest_workplace(stuff_path)) rs = Parallel(num_jobs).grouped(pipeline_base.pack, sub_workplaces).ordered_results return sum(rs, []) def pick_from_repeat_and_pack( workplace: str, pipeline_base: Type[SimplePipeline], *, num_pick: int, num_jobs: int = 1, ) -> List[str]: score_workplace_pairs = [] for stuff in sorted(os.listdir(workplace)): stuff_path = os.path.join(workplace, stuff) if not os.path.isdir(stuff_path): continue sub_workplace = get_latest_workplace(stuff_path) assert sub_workplace is not None, "internal error occurred" score_path = os.path.join(sub_workplace, CHECKPOINTS_FOLDER, SCORES_FILE) with open(score_path, "r") as f: score = float(max(json.load(f).values())) score_workplace_pairs.append((score, sub_workplace)) score_workplace_pairs = sorted(score_workplace_pairs)[::-1] sub_workplaces = [pair[1] for pair in score_workplace_pairs[:num_pick]] rs = Parallel(num_jobs).grouped(pipeline_base.pack, sub_workplaces).ordered_results return sum(rs, []) def make_toy_model( model: str = "fcnn", config: Optional[Dict[str, Any]] = None, *, pipeline_type: str = "ml.carefree", is_classification: bool = False, cf_data_config: Optional[Dict[str, Any]] = None, data_tuple: Optional[Tuple[np.ndarray, np.ndarray]] = None, cuda: Optional[str] = None, ) -> SimplePipeline: if config is None: config = {} if data_tuple is not None: x_np, y_np = data_tuple else: if not is_classification: x, y = [[0]], [[1.0]] else: x, y = [[0], [1]], [[1], [0]] x_np, y_np = map(np.array, [x, y]) model_config = {} if model in ("fcnn", "tree_dnn"): model_config = { "hidden_units": [100], "batch_norm": False, "dropout": 0.0, } base_config = { "core_name": model, "core_config": model_config, "output_dim": 1 + int(is_classification), "num_epoch": 2, "max_epoch": 4, } updated = update_dict(config, base_config) m = SimplePipeline.make(pipeline_type, updated) assert isinstance(m, SimplePipeline) if cf_data_config is None: cf_data_config = {} cf_data_config = update_dict( cf_data_config, dict( valid_columns=list(range(x_np.shape[1])), label_process_method="identical", ), ) data = MLData.with_cf_data( x_np, y_np, is_classification=is_classification, cf_data_config=cf_data_config, valid_split=0.0, ) m.fit(data, cuda=cuda) return m __all__ = [ "register_core", "evaluate", "task_loader", "load_experiment_results", "repeat_with", "pack_repeat", "pick_from_repeat_and_pack", "make_toy_model", "ModelPattern", "EnsemblePattern", ]
6,808
852
#include "CondFormats/AlignmentRecord/interface/EEAlignmentErrorExtendedRcd.h" #include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h" EVENTSETUP_RECORD_REG(EEAlignmentErrorExtendedRcd);
70
839
# Generated from BaserowFormulaLexer.g4 by ANTLR 4.8 from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2T") buf.write("\u028a\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r") buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23") buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30") buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36") buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%") buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.") buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64") buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:") buf.write("\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\t") buf.write("C\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\tJ\4K\tK\4L\t") buf.write("L\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S\tS\4T\tT\4U\t") buf.write("U\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\4\\\t\\\4]\t]\4") buf.write("^\t^\4_\t_\4`\t`\4a\ta\4b\tb\4c\tc\4d\td\4e\te\4f\tf\4") buf.write("g\tg\4h\th\4i\ti\4j\tj\4k\tk\4l\tl\4m\tm\4n\tn\4o\to\4") buf.write("p\tp\4q\tq\4r\tr\4s\ts\3\2\6\2\u00e9\n\2\r\2\16\2\u00ea") buf.write("\3\2\3\2\3\3\3\3\3\3\3\3\7\3\u00f3\n\3\f\3\16\3\u00f6") buf.write("\13\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\7\4\u0101\n") buf.write("\4\f\4\16\4\u0104\13\4\3\4\3\4\3\4\3\4\3\5\3\5\3\6\3\6") buf.write("\3\7\3\7\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\r") buf.write("\3\r\3\16\3\16\3\17\3\17\3\20\3\20\3\21\3\21\3\22\3\22") buf.write("\3\23\3\23\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\30") buf.write("\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\34\3\34\3\35\3\35") buf.write("\3\36\3\36\3\37\3\37\3 \3 \3!\3!\3\"\3\"\3\"\3\"\7\"\u0148") buf.write("\n\"\f\"\16\"\u014b\13\"\3\"\3\"\3#\3#\3#\3#\7#\u0153") buf.write("\n#\f#\16#\u0156\13#\3#\3#\3$\3$\3$\3$\3$\3$\7$\u0160") buf.write("\n$\f$\16$\u0163\13$\3$\3$\3%\3%\3%\3%\3%\3&\3&\3&\3&") buf.write("\3&\3&\3\'\3\'\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3(\3(\3(\3") buf.write("(\3(\3(\3(\3(\3)\3)\3*\3*\3+\3+\3+\3,\3,\3-\3-\3-\3.\3") buf.write(".\3/\3/\3\60\3\60\3\61\3\61\3\62\3\62\3\63\3\63\3\63\7") buf.write("\63\u019d\n\63\f\63\16\63\u01a0\13\63\3\63\3\63\3\64\3") buf.write("\64\3\64\3\65\5\65\u01a8\n\65\3\65\6\65\u01ab\n\65\r\65") buf.write("\16\65\u01ac\3\65\3\65\6\65\u01b1\n\65\r\65\16\65\u01b2") buf.write("\3\65\3\65\7\65\u01b7\n\65\f\65\16\65\u01ba\13\65\3\65") buf.write("\6\65\u01bd\n\65\r\65\16\65\u01be\5\65\u01c1\n\65\3\66") buf.write("\5\66\u01c4\n\66\3\66\6\66\u01c7\n\66\r\66\16\66\u01c8") buf.write("\3\66\3\66\6\66\u01cd\n\66\r\66\16\66\u01ce\5\66\u01d1") buf.write("\n\66\3\67\3\67\3\67\38\38\39\39\3:\3:\3;\3;\7;\u01de") buf.write("\n;\f;\16;\u01e1\13;\3<\3<\7<\u01e5\n<\f<\16<\u01e8\13") buf.write("<\3=\3=\3>\3>\3>\3?\3?\3?\3@\3@\3@\3A\3A\3A\3B\3B\3C\3") buf.write("C\3D\3D\3D\3E\3E\3E\3F\3F\3G\3G\3H\3H\3H\3I\3I\3J\3J\3") buf.write("J\3K\3K\3K\3L\3L\3M\3M\3M\3N\3N\3N\3O\3O\3O\3O\3P\3P\3") buf.write("P\3Q\3Q\3Q\3R\3R\3R\3R\3S\3S\3S\3S\3T\3T\3U\3U\3U\3V\3") buf.write("V\3V\3W\3W\3W\3X\3X\3X\3Y\3Y\3Y\3Y\3Z\3Z\3Z\3[\3[\3[\3") buf.write("[\3\\\3\\\3\\\3\\\3]\3]\3^\3^\3_\3_\3`\3`\3`\3a\3a\3a") buf.write("\3a\3b\3b\3b\3c\3c\3d\3d\3e\3e\3e\3f\3f\3f\3g\3g\3g\3") buf.write("h\3h\3h\3i\3i\3j\3j\3k\3k\3k\3l\3l\3l\3l\3l\3m\3m\3m\3") buf.write("m\3n\3n\3n\3n\3n\3o\3o\3o\3o\3p\3p\3p\3q\3q\3q\3r\3r\3") buf.write("s\3s\4\u00f4\u0102\2t\3\3\5\4\7\5\t\2\13\2\r\2\17\2\21") buf.write("\2\23\2\25\2\27\2\31\2\33\2\35\2\37\2!\2#\2%\2\'\2)\2") buf.write("+\2-\2/\2\61\2\63\2\65\2\67\29\2;\2=\2?\2A\2C\2E\2G\2") buf.write("I\6K\7M\bO\tQ\nS\13U\fW\rY\16[\17]\20_\21a\22c\23e\24") buf.write("g\25i\26k\27m\30o\31q\32s\33u\34w\35y\36{\37} \177!\u0081") buf.write("\"\u0083#\u0085$\u0087%\u0089&\u008b\'\u008d(\u008f)\u0091") buf.write("*\u0093+\u0095,\u0097-\u0099.\u009b/\u009d\60\u009f\61") buf.write("\u00a1\62\u00a3\63\u00a5\64\u00a7\65\u00a9\66\u00ab\67") buf.write("\u00ad8\u00af9\u00b1:\u00b3;\u00b5<\u00b7=\u00b9>\u00bb") buf.write("?\u00bd@\u00bfA\u00c1B\u00c3C\u00c5D\u00c7E\u00c9F\u00cb") buf.write("G\u00cdH\u00cfI\u00d1J\u00d3K\u00d5L\u00d7M\u00d9N\u00db") buf.write("O\u00ddP\u00dfQ\u00e1R\u00e3S\u00e5T\3\2&\5\2\13\f\17") buf.write("\17\"\"\4\2CCcc\4\2DDdd\4\2EEee\4\2FFff\4\2GGgg\4\2HH") buf.write("hh\4\2IIii\4\2JJjj\4\2KKkk\4\2LLll\4\2MMmm\4\2NNnn\4\2") buf.write("OOoo\4\2PPpp\4\2QQqq\4\2RRrr\4\2SSss\4\2TTtt\4\2UUuu\4") buf.write("\2VVvv\4\2WWww\4\2XXxx\4\2YYyy\4\2ZZzz\4\2[[{{\4\2\\\\") buf.write("||\4\2\62;CH\3\2\62;\4\2$$^^\4\2))^^\4\2^^bb\5\2C\\aa") buf.write("c|\6\2\62;C\\aac|\6\2C\\aac|\u00a3\1\7\2\62;C\\aac|\u00a3") buf.write("\1\2\u0280\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2I\3\2") buf.write("\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3") buf.write("\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]") buf.write("\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2\2e\3\2\2\2\2") buf.write("g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2\2\2o\3\2\2\2") buf.write("\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2\2\2\2y\3\2\2") buf.write("\2\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2\u0081\3\2\2\2") buf.write("\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087\3\2\2\2\2\u0089") buf.write("\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2\2\2\u008f\3\2\2") buf.write("\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2\u0095\3\2\2\2\2\u0097") buf.write("\3\2\2\2\2\u0099\3\2\2\2\2\u009b\3\2\2\2\2\u009d\3\2\2") buf.write("\2\2\u009f\3\2\2\2\2\u00a1\3\2\2\2\2\u00a3\3\2\2\2\2\u00a5") buf.write("\3\2\2\2\2\u00a7\3\2\2\2\2\u00a9\3\2\2\2\2\u00ab\3\2\2") buf.write("\2\2\u00ad\3\2\2\2\2\u00af\3\2\2\2\2\u00b1\3\2\2\2\2\u00b3") buf.write("\3\2\2\2\2\u00b5\3\2\2\2\2\u00b7\3\2\2\2\2\u00b9\3\2\2") buf.write("\2\2\u00bb\3\2\2\2\2\u00bd\3\2\2\2\2\u00bf\3\2\2\2\2\u00c1") buf.write("\3\2\2\2\2\u00c3\3\2\2\2\2\u00c5\3\2\2\2\2\u00c7\3\2\2") buf.write("\2\2\u00c9\3\2\2\2\2\u00cb\3\2\2\2\2\u00cd\3\2\2\2\2\u00cf") buf.write("\3\2\2\2\2\u00d1\3\2\2\2\2\u00d3\3\2\2\2\2\u00d5\3\2\2") buf.write("\2\2\u00d7\3\2\2\2\2\u00d9\3\2\2\2\2\u00db\3\2\2\2\2\u00dd") buf.write("\3\2\2\2\2\u00df\3\2\2\2\2\u00e1\3\2\2\2\2\u00e3\3\2\2") buf.write("\2\2\u00e5\3\2\2\2\3\u00e8\3\2\2\2\5\u00ee\3\2\2\2\7\u00fc") buf.write("\3\2\2\2\t\u0109\3\2\2\2\13\u010b\3\2\2\2\r\u010d\3\2") buf.write("\2\2\17\u010f\3\2\2\2\21\u0111\3\2\2\2\23\u0113\3\2\2") buf.write("\2\25\u0115\3\2\2\2\27\u0117\3\2\2\2\31\u0119\3\2\2\2") buf.write("\33\u011b\3\2\2\2\35\u011d\3\2\2\2\37\u011f\3\2\2\2!\u0121") buf.write("\3\2\2\2#\u0123\3\2\2\2%\u0125\3\2\2\2\'\u0127\3\2\2\2") buf.write(")\u0129\3\2\2\2+\u012b\3\2\2\2-\u012d\3\2\2\2/\u012f\3") buf.write("\2\2\2\61\u0131\3\2\2\2\63\u0133\3\2\2\2\65\u0135\3\2") buf.write("\2\2\67\u0137\3\2\2\29\u0139\3\2\2\2;\u013b\3\2\2\2=\u013d") buf.write("\3\2\2\2?\u013f\3\2\2\2A\u0141\3\2\2\2C\u0143\3\2\2\2") buf.write("E\u014e\3\2\2\2G\u0159\3\2\2\2I\u0166\3\2\2\2K\u016b\3") buf.write("\2\2\2M\u0171\3\2\2\2O\u0177\3\2\2\2Q\u0183\3\2\2\2S\u0185") buf.write("\3\2\2\2U\u0187\3\2\2\2W\u018a\3\2\2\2Y\u018c\3\2\2\2") buf.write("[\u018f\3\2\2\2]\u0191\3\2\2\2_\u0193\3\2\2\2a\u0195\3") buf.write("\2\2\2c\u0197\3\2\2\2e\u0199\3\2\2\2g\u01a3\3\2\2\2i\u01a7") buf.write("\3\2\2\2k\u01c3\3\2\2\2m\u01d2\3\2\2\2o\u01d5\3\2\2\2") buf.write("q\u01d7\3\2\2\2s\u01d9\3\2\2\2u\u01db\3\2\2\2w\u01e2\3") buf.write("\2\2\2y\u01e9\3\2\2\2{\u01eb\3\2\2\2}\u01ee\3\2\2\2\177") buf.write("\u01f1\3\2\2\2\u0081\u01f4\3\2\2\2\u0083\u01f7\3\2\2\2") buf.write("\u0085\u01f9\3\2\2\2\u0087\u01fb\3\2\2\2\u0089\u01fe\3") buf.write("\2\2\2\u008b\u0201\3\2\2\2\u008d\u0203\3\2\2\2\u008f\u0205") buf.write("\3\2\2\2\u0091\u0208\3\2\2\2\u0093\u020a\3\2\2\2\u0095") buf.write("\u020d\3\2\2\2\u0097\u0210\3\2\2\2\u0099\u0212\3\2\2\2") buf.write("\u009b\u0215\3\2\2\2\u009d\u0218\3\2\2\2\u009f\u021c\3") buf.write("\2\2\2\u00a1\u021f\3\2\2\2\u00a3\u0222\3\2\2\2\u00a5\u0226") buf.write("\3\2\2\2\u00a7\u022a\3\2\2\2\u00a9\u022c\3\2\2\2\u00ab") buf.write("\u022f\3\2\2\2\u00ad\u0232\3\2\2\2\u00af\u0235\3\2\2\2") buf.write("\u00b1\u0238\3\2\2\2\u00b3\u023c\3\2\2\2\u00b5\u023f\3") buf.write("\2\2\2\u00b7\u0243\3\2\2\2\u00b9\u0247\3\2\2\2\u00bb\u0249") buf.write("\3\2\2\2\u00bd\u024b\3\2\2\2\u00bf\u024d\3\2\2\2\u00c1") buf.write("\u0250\3\2\2\2\u00c3\u0254\3\2\2\2\u00c5\u0257\3\2\2\2") buf.write("\u00c7\u0259\3\2\2\2\u00c9\u025b\3\2\2\2\u00cb\u025e\3") buf.write("\2\2\2\u00cd\u0261\3\2\2\2\u00cf\u0264\3\2\2\2\u00d1\u0267") buf.write("\3\2\2\2\u00d3\u0269\3\2\2\2\u00d5\u026b\3\2\2\2\u00d7") buf.write("\u026e\3\2\2\2\u00d9\u0273\3\2\2\2\u00db\u0277\3\2\2\2") buf.write("\u00dd\u027c\3\2\2\2\u00df\u0280\3\2\2\2\u00e1\u0283\3") buf.write("\2\2\2\u00e3\u0286\3\2\2\2\u00e5\u0288\3\2\2\2\u00e7\u00e9") buf.write("\t\2\2\2\u00e8\u00e7\3\2\2\2\u00e9\u00ea\3\2\2\2\u00ea") buf.write("\u00e8\3\2\2\2\u00ea\u00eb\3\2\2\2\u00eb\u00ec\3\2\2\2") buf.write("\u00ec\u00ed\b\2\2\2\u00ed\4\3\2\2\2\u00ee\u00ef\7\61") buf.write("\2\2\u00ef\u00f0\7,\2\2\u00f0\u00f4\3\2\2\2\u00f1\u00f3") buf.write("\13\2\2\2\u00f2\u00f1\3\2\2\2\u00f3\u00f6\3\2\2\2\u00f4") buf.write("\u00f5\3\2\2\2\u00f4\u00f2\3\2\2\2\u00f5\u00f7\3\2\2\2") buf.write("\u00f6\u00f4\3\2\2\2\u00f7\u00f8\7,\2\2\u00f8\u00f9\7") buf.write("\61\2\2\u00f9\u00fa\3\2\2\2\u00fa\u00fb\b\3\2\2\u00fb") buf.write("\6\3\2\2\2\u00fc\u00fd\7\61\2\2\u00fd\u00fe\7\61\2\2\u00fe") buf.write("\u0102\3\2\2\2\u00ff\u0101\13\2\2\2\u0100\u00ff\3\2\2") buf.write("\2\u0101\u0104\3\2\2\2\u0102\u0103\3\2\2\2\u0102\u0100") buf.write("\3\2\2\2\u0103\u0105\3\2\2\2\u0104\u0102\3\2\2\2\u0105") buf.write("\u0106\7\f\2\2\u0106\u0107\3\2\2\2\u0107\u0108\b\4\2\2") buf.write("\u0108\b\3\2\2\2\u0109\u010a\t\3\2\2\u010a\n\3\2\2\2\u010b") buf.write("\u010c\t\4\2\2\u010c\f\3\2\2\2\u010d\u010e\t\5\2\2\u010e") buf.write("\16\3\2\2\2\u010f\u0110\t\6\2\2\u0110\20\3\2\2\2\u0111") buf.write("\u0112\t\7\2\2\u0112\22\3\2\2\2\u0113\u0114\t\b\2\2\u0114") buf.write("\24\3\2\2\2\u0115\u0116\t\t\2\2\u0116\26\3\2\2\2\u0117") buf.write("\u0118\t\n\2\2\u0118\30\3\2\2\2\u0119\u011a\t\13\2\2\u011a") buf.write("\32\3\2\2\2\u011b\u011c\t\f\2\2\u011c\34\3\2\2\2\u011d") buf.write("\u011e\t\r\2\2\u011e\36\3\2\2\2\u011f\u0120\t\16\2\2\u0120") buf.write(" \3\2\2\2\u0121\u0122\t\17\2\2\u0122\"\3\2\2\2\u0123\u0124") buf.write("\t\20\2\2\u0124$\3\2\2\2\u0125\u0126\t\21\2\2\u0126&\3") buf.write("\2\2\2\u0127\u0128\t\22\2\2\u0128(\3\2\2\2\u0129\u012a") buf.write("\t\23\2\2\u012a*\3\2\2\2\u012b\u012c\t\24\2\2\u012c,\3") buf.write("\2\2\2\u012d\u012e\t\25\2\2\u012e.\3\2\2\2\u012f\u0130") buf.write("\t\26\2\2\u0130\60\3\2\2\2\u0131\u0132\t\27\2\2\u0132") buf.write("\62\3\2\2\2\u0133\u0134\t\30\2\2\u0134\64\3\2\2\2\u0135") buf.write("\u0136\t\31\2\2\u0136\66\3\2\2\2\u0137\u0138\t\32\2\2") buf.write("\u01388\3\2\2\2\u0139\u013a\t\33\2\2\u013a:\3\2\2\2\u013b") buf.write("\u013c\t\34\2\2\u013c<\3\2\2\2\u013d\u013e\7a\2\2\u013e") buf.write(">\3\2\2\2\u013f\u0140\t\35\2\2\u0140@\3\2\2\2\u0141\u0142") buf.write("\t\36\2\2\u0142B\3\2\2\2\u0143\u0149\7$\2\2\u0144\u0145") buf.write("\7^\2\2\u0145\u0148\13\2\2\2\u0146\u0148\n\37\2\2\u0147") buf.write("\u0144\3\2\2\2\u0147\u0146\3\2\2\2\u0148\u014b\3\2\2\2") buf.write("\u0149\u0147\3\2\2\2\u0149\u014a\3\2\2\2\u014a\u014c\3") buf.write("\2\2\2\u014b\u0149\3\2\2\2\u014c\u014d\7$\2\2\u014dD\3") buf.write("\2\2\2\u014e\u0154\7)\2\2\u014f\u0150\7^\2\2\u0150\u0153") buf.write("\13\2\2\2\u0151\u0153\n \2\2\u0152\u014f\3\2\2\2\u0152") buf.write("\u0151\3\2\2\2\u0153\u0156\3\2\2\2\u0154\u0152\3\2\2\2") buf.write("\u0154\u0155\3\2\2\2\u0155\u0157\3\2\2\2\u0156\u0154\3") buf.write("\2\2\2\u0157\u0158\7)\2\2\u0158F\3\2\2\2\u0159\u0161\7") buf.write("b\2\2\u015a\u015b\7^\2\2\u015b\u0160\13\2\2\2\u015c\u015d") buf.write("\7b\2\2\u015d\u0160\7b\2\2\u015e\u0160\n!\2\2\u015f\u015a") buf.write("\3\2\2\2\u015f\u015c\3\2\2\2\u015f\u015e\3\2\2\2\u0160") buf.write("\u0163\3\2\2\2\u0161\u015f\3\2\2\2\u0161\u0162\3\2\2\2") buf.write("\u0162\u0164\3\2\2\2\u0163\u0161\3\2\2\2\u0164\u0165\7") buf.write("b\2\2\u0165H\3\2\2\2\u0166\u0167\5/\30\2\u0167\u0168\5") buf.write("+\26\2\u0168\u0169\5\61\31\2\u0169\u016a\5\21\t\2\u016a") buf.write("J\3\2\2\2\u016b\u016c\5\23\n\2\u016c\u016d\5\t\5\2\u016d") buf.write("\u016e\5\37\20\2\u016e\u016f\5-\27\2\u016f\u0170\5\21") buf.write("\t\2\u0170L\3\2\2\2\u0171\u0172\5\23\n\2\u0172\u0173\5") buf.write("\31\r\2\u0173\u0174\5\21\t\2\u0174\u0175\5\37\20\2\u0175") buf.write("\u0176\5\17\b\2\u0176N\3\2\2\2\u0177\u0178\5\23\n\2\u0178") buf.write("\u0179\5\31\r\2\u0179\u017a\5\21\t\2\u017a\u017b\5\37") buf.write("\20\2\u017b\u017c\5\17\b\2\u017c\u017d\5=\37\2\u017d\u017e") buf.write("\5\13\6\2\u017e\u017f\59\35\2\u017f\u0180\5=\37\2\u0180") buf.write("\u0181\5\31\r\2\u0181\u0182\5\17\b\2\u0182P\3\2\2\2\u0183") buf.write("\u0184\7.\2\2\u0184R\3\2\2\2\u0185\u0186\7<\2\2\u0186") buf.write("T\3\2\2\2\u0187\u0188\7<\2\2\u0188\u0189\7<\2\2\u0189") buf.write("V\3\2\2\2\u018a\u018b\7&\2\2\u018bX\3\2\2\2\u018c\u018d") buf.write("\7&\2\2\u018d\u018e\7&\2\2\u018eZ\3\2\2\2\u018f\u0190") buf.write("\7,\2\2\u0190\\\3\2\2\2\u0191\u0192\7*\2\2\u0192^\3\2") buf.write("\2\2\u0193\u0194\7+\2\2\u0194`\3\2\2\2\u0195\u0196\7]") buf.write("\2\2\u0196b\3\2\2\2\u0197\u0198\7_\2\2\u0198d\3\2\2\2") buf.write("\u0199\u019a\5\13\6\2\u019a\u019e\7)\2\2\u019b\u019d\4") buf.write("\62\63\2\u019c\u019b\3\2\2\2\u019d\u01a0\3\2\2\2\u019e") buf.write("\u019c\3\2\2\2\u019e\u019f\3\2\2\2\u019f\u01a1\3\2\2\2") buf.write("\u01a0\u019e\3\2\2\2\u01a1\u01a2\7)\2\2\u01a2f\3\2\2\2") buf.write("\u01a3\u01a4\5\21\t\2\u01a4\u01a5\5E#\2\u01a5h\3\2\2\2") buf.write("\u01a6\u01a8\7/\2\2\u01a7\u01a6\3\2\2\2\u01a7\u01a8\3") buf.write("\2\2\2\u01a8\u01aa\3\2\2\2\u01a9\u01ab\5A!\2\u01aa\u01a9") buf.write("\3\2\2\2\u01ab\u01ac\3\2\2\2\u01ac\u01aa\3\2\2\2\u01ac") buf.write("\u01ad\3\2\2\2\u01ad\u01ae\3\2\2\2\u01ae\u01b0\7\60\2") buf.write("\2\u01af\u01b1\5A!\2\u01b0\u01af\3\2\2\2\u01b1\u01b2\3") buf.write("\2\2\2\u01b2\u01b0\3\2\2\2\u01b2\u01b3\3\2\2\2\u01b3\u01c0") buf.write("\3\2\2\2\u01b4\u01b8\5\21\t\2\u01b5\u01b7\7/\2\2\u01b6") buf.write("\u01b5\3\2\2\2\u01b7\u01ba\3\2\2\2\u01b8\u01b6\3\2\2\2") buf.write("\u01b8\u01b9\3\2\2\2\u01b9\u01bc\3\2\2\2\u01ba\u01b8\3") buf.write("\2\2\2\u01bb\u01bd\5A!\2\u01bc\u01bb\3\2\2\2\u01bd\u01be") buf.write("\3\2\2\2\u01be\u01bc\3\2\2\2\u01be\u01bf\3\2\2\2\u01bf") buf.write("\u01c1\3\2\2\2\u01c0\u01b4\3\2\2\2\u01c0\u01c1\3\2\2\2") buf.write("\u01c1j\3\2\2\2\u01c2\u01c4\7/\2\2\u01c3\u01c2\3\2\2\2") buf.write("\u01c3\u01c4\3\2\2\2\u01c4\u01c6\3\2\2\2\u01c5\u01c7\5") buf.write("A!\2\u01c6\u01c5\3\2\2\2\u01c7\u01c8\3\2\2\2\u01c8\u01c6") buf.write("\3\2\2\2\u01c8\u01c9\3\2\2\2\u01c9\u01d0\3\2\2\2\u01ca") buf.write("\u01cc\5\21\t\2\u01cb\u01cd\5A!\2\u01cc\u01cb\3\2\2\2") buf.write("\u01cd\u01ce\3\2\2\2\u01ce\u01cc\3\2\2\2\u01ce\u01cf\3") buf.write("\2\2\2\u01cf\u01d1\3\2\2\2\u01d0\u01ca\3\2\2\2\u01d0\u01d1") buf.write("\3\2\2\2\u01d1l\3\2\2\2\u01d2\u01d3\7z\2\2\u01d3\u01d4") buf.write("\5E#\2\u01d4n\3\2\2\2\u01d5\u01d6\7\60\2\2\u01d6p\3\2") buf.write("\2\2\u01d7\u01d8\5E#\2\u01d8r\3\2\2\2\u01d9\u01da\5C\"") buf.write("\2\u01dat\3\2\2\2\u01db\u01df\t\"\2\2\u01dc\u01de\t#\2") buf.write("\2\u01dd\u01dc\3\2\2\2\u01de\u01e1\3\2\2\2\u01df\u01dd") buf.write("\3\2\2\2\u01df\u01e0\3\2\2\2\u01e0v\3\2\2\2\u01e1\u01df") buf.write("\3\2\2\2\u01e2\u01e6\t$\2\2\u01e3\u01e5\t%\2\2\u01e4\u01e3") buf.write("\3\2\2\2\u01e5\u01e8\3\2\2\2\u01e6\u01e4\3\2\2\2\u01e6") buf.write("\u01e7\3\2\2\2\u01e7x\3\2\2\2\u01e8\u01e6\3\2\2\2\u01e9") buf.write("\u01ea\7(\2\2\u01eaz\3\2\2\2\u01eb\u01ec\7(\2\2\u01ec") buf.write("\u01ed\7(\2\2\u01ed|\3\2\2\2\u01ee\u01ef\7(\2\2\u01ef") buf.write("\u01f0\7>\2\2\u01f0~\3\2\2\2\u01f1\u01f2\7B\2\2\u01f2") buf.write("\u01f3\7B\2\2\u01f3\u0080\3\2\2\2\u01f4\u01f5\7B\2\2\u01f5") buf.write("\u01f6\7@\2\2\u01f6\u0082\3\2\2\2\u01f7\u01f8\7B\2\2\u01f8") buf.write("\u0084\3\2\2\2\u01f9\u01fa\7#\2\2\u01fa\u0086\3\2\2\2") buf.write("\u01fb\u01fc\7#\2\2\u01fc\u01fd\7#\2\2\u01fd\u0088\3\2") buf.write("\2\2\u01fe\u01ff\7#\2\2\u01ff\u0200\7?\2\2\u0200\u008a") buf.write("\3\2\2\2\u0201\u0202\7`\2\2\u0202\u008c\3\2\2\2\u0203") buf.write("\u0204\7?\2\2\u0204\u008e\3\2\2\2\u0205\u0206\7?\2\2\u0206") buf.write("\u0207\7@\2\2\u0207\u0090\3\2\2\2\u0208\u0209\7@\2\2\u0209") buf.write("\u0092\3\2\2\2\u020a\u020b\7@\2\2\u020b\u020c\7?\2\2\u020c") buf.write("\u0094\3\2\2\2\u020d\u020e\7@\2\2\u020e\u020f\7@\2\2\u020f") buf.write("\u0096\3\2\2\2\u0210\u0211\7%\2\2\u0211\u0098\3\2\2\2") buf.write("\u0212\u0213\7%\2\2\u0213\u0214\7?\2\2\u0214\u009a\3\2") buf.write("\2\2\u0215\u0216\7%\2\2\u0216\u0217\7@\2\2\u0217\u009c") buf.write("\3\2\2\2\u0218\u0219\7%\2\2\u0219\u021a\7@\2\2\u021a\u021b") buf.write("\7@\2\2\u021b\u009e\3\2\2\2\u021c\u021d\7%\2\2\u021d\u021e") buf.write("\7%\2\2\u021e\u00a0\3\2\2\2\u021f\u0220\7/\2\2\u0220\u0221") buf.write("\7@\2\2\u0221\u00a2\3\2\2\2\u0222\u0223\7/\2\2\u0223\u0224") buf.write("\7@\2\2\u0224\u0225\7@\2\2\u0225\u00a4\3\2\2\2\u0226\u0227") buf.write("\7/\2\2\u0227\u0228\7~\2\2\u0228\u0229\7/\2\2\u0229\u00a6") buf.write("\3\2\2\2\u022a\u022b\7>\2\2\u022b\u00a8\3\2\2\2\u022c") buf.write("\u022d\7>\2\2\u022d\u022e\7?\2\2\u022e\u00aa\3\2\2\2\u022f") buf.write("\u0230\7>\2\2\u0230\u0231\7B\2\2\u0231\u00ac\3\2\2\2\u0232") buf.write("\u0233\7>\2\2\u0233\u0234\7`\2\2\u0234\u00ae\3\2\2\2\u0235") buf.write("\u0236\7>\2\2\u0236\u0237\7@\2\2\u0237\u00b0\3\2\2\2\u0238") buf.write("\u0239\7>\2\2\u0239\u023a\7/\2\2\u023a\u023b\7@\2\2\u023b") buf.write("\u00b2\3\2\2\2\u023c\u023d\7>\2\2\u023d\u023e\7>\2\2\u023e") buf.write("\u00b4\3\2\2\2\u023f\u0240\7>\2\2\u0240\u0241\7>\2\2\u0241") buf.write("\u0242\7?\2\2\u0242\u00b6\3\2\2\2\u0243\u0244\7>\2\2\u0244") buf.write("\u0245\7A\2\2\u0245\u0246\7@\2\2\u0246\u00b8\3\2\2\2\u0247") buf.write("\u0248\7/\2\2\u0248\u00ba\3\2\2\2\u0249\u024a\7\'\2\2") buf.write("\u024a\u00bc\3\2\2\2\u024b\u024c\7~\2\2\u024c\u00be\3") buf.write("\2\2\2\u024d\u024e\7~\2\2\u024e\u024f\7~\2\2\u024f\u00c0") buf.write("\3\2\2\2\u0250\u0251\7~\2\2\u0251\u0252\7~\2\2\u0252\u0253") buf.write("\7\61\2\2\u0253\u00c2\3\2\2\2\u0254\u0255\7~\2\2\u0255") buf.write("\u0256\7\61\2\2\u0256\u00c4\3\2\2\2\u0257\u0258\7-\2\2") buf.write("\u0258\u00c6\3\2\2\2\u0259\u025a\7A\2\2\u025a\u00c8\3") buf.write("\2\2\2\u025b\u025c\7A\2\2\u025c\u025d\7(\2\2\u025d\u00ca") buf.write("\3\2\2\2\u025e\u025f\7A\2\2\u025f\u0260\7%\2\2\u0260\u00cc") buf.write("\3\2\2\2\u0261\u0262\7A\2\2\u0262\u0263\7/\2\2\u0263\u00ce") buf.write("\3\2\2\2\u0264\u0265\7A\2\2\u0265\u0266\7~\2\2\u0266\u00d0") buf.write("\3\2\2\2\u0267\u0268\7\61\2\2\u0268\u00d2\3\2\2\2\u0269") buf.write("\u026a\7\u0080\2\2\u026a\u00d4\3\2\2\2\u026b\u026c\7\u0080") buf.write("\2\2\u026c\u026d\7?\2\2\u026d\u00d6\3\2\2\2\u026e\u026f") buf.write("\7\u0080\2\2\u026f\u0270\7@\2\2\u0270\u0271\7?\2\2\u0271") buf.write("\u0272\7\u0080\2\2\u0272\u00d8\3\2\2\2\u0273\u0274\7\u0080") buf.write("\2\2\u0274\u0275\7@\2\2\u0275\u0276\7\u0080\2\2\u0276") buf.write("\u00da\3\2\2\2\u0277\u0278\7\u0080\2\2\u0278\u0279\7>") buf.write("\2\2\u0279\u027a\7?\2\2\u027a\u027b\7\u0080\2\2\u027b") buf.write("\u00dc\3\2\2\2\u027c\u027d\7\u0080\2\2\u027d\u027e\7>") buf.write("\2\2\u027e\u027f\7\u0080\2\2\u027f\u00de\3\2\2\2\u0280") buf.write("\u0281\7\u0080\2\2\u0281\u0282\7,\2\2\u0282\u00e0\3\2") buf.write("\2\2\u0283\u0284\7\u0080\2\2\u0284\u0285\7\u0080\2\2\u0285") buf.write("\u00e2\3\2\2\2\u0286\u0287\7=\2\2\u0287\u00e4\3\2\2\2") buf.write("\u0288\u0289\13\2\2\2\u0289\u00e6\3\2\2\2\31\2\u00ea\u00f4") buf.write("\u0102\u0147\u0149\u0152\u0154\u015f\u0161\u019e\u01a7") buf.write("\u01ac\u01b2\u01b8\u01be\u01c0\u01c3\u01c8\u01ce\u01d0") buf.write("\u01df\u01e6\3\2\3\2") return buf.getvalue() class BaserowFormulaLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] WHITESPACE = 1 BLOCK_COMMENT = 2 LINE_COMMENT = 3 TRUE = 4 FALSE = 5 FIELD = 6 FIELDBYID = 7 COMMA = 8 COLON = 9 COLON_COLON = 10 DOLLAR = 11 DOLLAR_DOLLAR = 12 STAR = 13 OPEN_PAREN = 14 CLOSE_PAREN = 15 OPEN_BRACKET = 16 CLOSE_BRACKET = 17 BIT_STRING = 18 REGEX_STRING = 19 NUMERIC_LITERAL = 20 INTEGER_LITERAL = 21 HEX_INTEGER_LITERAL = 22 DOT = 23 SINGLEQ_STRING_LITERAL = 24 DOUBLEQ_STRING_LITERAL = 25 IDENTIFIER = 26 IDENTIFIER_UNICODE = 27 AMP = 28 AMP_AMP = 29 AMP_LT = 30 AT_AT = 31 AT_GT = 32 AT_SIGN = 33 BANG = 34 BANG_BANG = 35 BANG_EQUAL = 36 CARET = 37 EQUAL = 38 EQUAL_GT = 39 GT = 40 GTE = 41 GT_GT = 42 HASH = 43 HASH_EQ = 44 HASH_GT = 45 HASH_GT_GT = 46 HASH_HASH = 47 HYPHEN_GT = 48 HYPHEN_GT_GT = 49 HYPHEN_PIPE_HYPHEN = 50 LT = 51 LTE = 52 LT_AT = 53 LT_CARET = 54 LT_GT = 55 LT_HYPHEN_GT = 56 LT_LT = 57 LT_LT_EQ = 58 LT_QMARK_GT = 59 MINUS = 60 PERCENT = 61 PIPE = 62 PIPE_PIPE = 63 PIPE_PIPE_SLASH = 64 PIPE_SLASH = 65 PLUS = 66 QMARK = 67 QMARK_AMP = 68 QMARK_HASH = 69 QMARK_HYPHEN = 70 QMARK_PIPE = 71 SLASH = 72 TIL = 73 TIL_EQ = 74 TIL_GTE_TIL = 75 TIL_GT_TIL = 76 TIL_LTE_TIL = 77 TIL_LT_TIL = 78 TIL_STAR = 79 TIL_TIL = 80 SEMI = 81 ErrorCharacter = 82 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ "DEFAULT_MODE" ] literalNames = [ "<INVALID>", "','", "':'", "'::'", "'$'", "'$$'", "'*'", "'('", "')'", "'['", "']'", "'.'", "'&'", "'&&'", "'&<'", "'@@'", "'@>'", "'@'", "'!'", "'!!'", "'!='", "'^'", "'='", "'=>'", "'>'", "'>='", "'>>'", "'#'", "'#='", "'#>'", "'#>>'", "'##'", "'->'", "'->>'", "'-|-'", "'<'", "'<='", "'<@'", "'<^'", "'<>'", "'<->'", "'<<'", "'<<='", "'<?>'", "'-'", "'%'", "'|'", "'||'", "'||/'", "'|/'", "'+'", "'?'", "'?&'", "'?#'", "'?-'", "'?|'", "'/'", "'~'", "'~='", "'~>=~'", "'~>~'", "'~<=~'", "'~<~'", "'~*'", "'~~'", "';'" ] symbolicNames = [ "<INVALID>", "WHITESPACE", "BLOCK_COMMENT", "LINE_COMMENT", "TRUE", "FALSE", "FIELD", "FIELDBYID", "COMMA", "COLON", "COLON_COLON", "DOLLAR", "DOLLAR_DOLLAR", "STAR", "OPEN_PAREN", "CLOSE_PAREN", "OPEN_BRACKET", "CLOSE_BRACKET", "BIT_STRING", "REGEX_STRING", "NUMERIC_LITERAL", "INTEGER_LITERAL", "HEX_INTEGER_LITERAL", "DOT", "SINGLEQ_STRING_LITERAL", "DOUBLEQ_STRING_LITERAL", "IDENTIFIER", "IDENTIFIER_UNICODE", "AMP", "AMP_AMP", "AMP_LT", "AT_AT", "AT_GT", "AT_SIGN", "BANG", "BANG_BANG", "BANG_EQUAL", "CARET", "EQUAL", "EQUAL_GT", "GT", "GTE", "GT_GT", "HASH", "HASH_EQ", "HASH_GT", "HASH_GT_GT", "HASH_HASH", "HYPHEN_GT", "HYPHEN_GT_GT", "HYPHEN_PIPE_HYPHEN", "LT", "LTE", "LT_AT", "LT_CARET", "LT_GT", "LT_HYPHEN_GT", "LT_LT", "LT_LT_EQ", "LT_QMARK_GT", "MINUS", "PERCENT", "PIPE", "PIPE_PIPE", "PIPE_PIPE_SLASH", "PIPE_SLASH", "PLUS", "QMARK", "QMARK_AMP", "QMARK_HASH", "QMARK_HYPHEN", "QMARK_PIPE", "SLASH", "TIL", "TIL_EQ", "TIL_GTE_TIL", "TIL_GT_TIL", "TIL_LTE_TIL", "TIL_LT_TIL", "TIL_STAR", "TIL_TIL", "SEMI", "ErrorCharacter" ] ruleNames = [ "WHITESPACE", "BLOCK_COMMENT", "LINE_COMMENT", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "UNDERSCORE", "HEX_DIGIT", "DEC_DIGIT", "DQUOTA_STRING", "SQUOTA_STRING", "BQUOTA_STRING", "TRUE", "FALSE", "FIELD", "FIELDBYID", "COMMA", "COLON", "COLON_COLON", "DOLLAR", "DOLLAR_DOLLAR", "STAR", "OPEN_PAREN", "CLOSE_PAREN", "OPEN_BRACKET", "CLOSE_BRACKET", "BIT_STRING", "REGEX_STRING", "NUMERIC_LITERAL", "INTEGER_LITERAL", "HEX_INTEGER_LITERAL", "DOT", "SINGLEQ_STRING_LITERAL", "DOUBLEQ_STRING_LITERAL", "IDENTIFIER", "IDENTIFIER_UNICODE", "AMP", "AMP_AMP", "AMP_LT", "AT_AT", "AT_GT", "AT_SIGN", "BANG", "BANG_BANG", "BANG_EQUAL", "CARET", "EQUAL", "EQUAL_GT", "GT", "GTE", "GT_GT", "HASH", "HASH_EQ", "HASH_GT", "HASH_GT_GT", "HASH_HASH", "HYPHEN_GT", "HYPHEN_GT_GT", "HYPHEN_PIPE_HYPHEN", "LT", "LTE", "LT_AT", "LT_CARET", "LT_GT", "LT_HYPHEN_GT", "LT_LT", "LT_LT_EQ", "LT_QMARK_GT", "MINUS", "PERCENT", "PIPE", "PIPE_PIPE", "PIPE_PIPE_SLASH", "PIPE_SLASH", "PLUS", "QMARK", "QMARK_AMP", "QMARK_HASH", "QMARK_HYPHEN", "QMARK_PIPE", "SLASH", "TIL", "TIL_EQ", "TIL_GTE_TIL", "TIL_GT_TIL", "TIL_LTE_TIL", "TIL_LT_TIL", "TIL_STAR", "TIL_TIL", "SEMI", "ErrorCharacter" ] grammarFileName = "BaserowFormulaLexer.g4" def __init__(self, input=None, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.8") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
20,012
746
package org.protege.editor.owl.ui.renderer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.vocab.OWLRDFVocabulary; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; /** * @author <NAME>, Stanford University, Bio-Medical Informatics Research Group, Date: 12/06/2014 */ @RunWith(MockitoJUnitRunner.class) public class OWLEntityRendererImpl_TestCase { @Mock private OWLEntity entity; private IRI iri; private OWLEntityRendererImpl renderer; @Before public void setUp() { renderer = new OWLEntityRendererImpl(); renderer.initialise(); } @Test public void shouldProvideFragment() { iri = IRI.create("http://www.semanticweb.org/test/ontology#Abc"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("Abc")); } @Test public void shouldProviderFragmentContainingBrackets() { iri = IRI.create("http://www.semanticweb.org/test/ontology#Abc(xyz)"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("'Abc(xyz)'")); } @Test public void shouldProvideLastPathElementIfThereIsNotFragment() { iri = IRI.create("http://www.semanticweb.org/test/ontology/Abc"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("Abc")); } @Test public void shouldProvideLastPathElementContainingBracketsIfThereIsNotFragment() { iri = IRI.create("http://www.semanticweb.org/test/ontology/Abc(xyz)"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("'Abc(xyz)'")); } @Test public void shouldRenderOWLThingWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_THING.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:Thing")); } @Test public void shouldRenderOWLNothingWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_NOTHING.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:Nothing")); } @Test public void shouldRenderOWLTopObjectPropertyWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_TOP_OBJECT_PROPERTY.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:topObjectProperty")); } @Test public void shouldRenderOWLBottomObjectPropertyWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_BOTTOM_OBJECT_PROPERTY.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:bottomObjectProperty")); } @Test public void shouldRenderOWLTopDataPropertyWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_TOP_DATA_PROPERTY.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:topDataProperty")); } @Test public void shouldRenderOWLBottomDataPropertyWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_BOTTOM_DATA_PROPERTY.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:bottomDataProperty")); } @Test public void shouldRenderRDFSLabelWithRDFSPrefixName() { iri = OWLRDFVocabulary.RDFS_LABEL.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("rdfs:label")); } @Test public void shouldRenderRDFSCommentWithRDFSPrefixName() { iri = OWLRDFVocabulary.RDFS_COMMENT.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("rdfs:comment")); } @Test public void shouldRenderRDFSSeeAlsoWithRDFSPrefixName() { iri = OWLRDFVocabulary.RDFS_SEE_ALSO.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("rdfs:seeAlso")); } @Test public void shouldRenderRDFSIsDefinedByWithRDFSPrefixName() { iri = OWLRDFVocabulary.RDFS_IS_DEFINED_BY.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("rdfs:isDefinedBy")); } @Test public void shouldRenderOWLBackwardCompatibleWithWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_BACKWARD_COMPATIBLE_WITH.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:backwardCompatibleWith")); } @Test public void shouldRenderOWLDeprecatedWithOWLPrefixName() { iri = OWLRDFVocabulary.OWL_DEPRECATED.getIRI(); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:deprecated")); } @Test public void shouldRender_XMLLiteral_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("rdf:XMLLiteral")); } @Test public void shouldRender_RDFSLiteral_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2000/01/rdf-schema#Literal"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("rdfs:Literal")); } @Test public void shouldRender_PlainLiteral_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("rdf:PlainLiteral")); } @Test public void shouldRender_real_WithOWLPrefixName() { iri = IRI.create("http://www.w3.org/2002/07/owl#real"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:real")); } @Test public void shouldRender_rational_WithOWLPrefixName() { iri = IRI.create("http://www.w3.org/2002/07/owl#rational"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("owl:rational")); } @Test public void shouldRender_string_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#string"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:string")); } @Test public void shouldRender_normalizedString_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#normalizedString"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:normalizedString")); } @Test public void shouldRender_token_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#token"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:token")); } @Test public void shouldRender_language_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#language"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:language")); } @Test public void shouldRender_Name_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#Name"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:Name")); } @Test public void shouldRender_NCName_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#NCName"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:NCName")); } @Test public void shouldRender_NMTOKEN_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#NMTOKEN"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:NMTOKEN")); } @Test public void shouldRender_decimal_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#decimal"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:decimal")); } @Test public void shouldRender_integer_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#integer"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:integer")); } @Test public void shouldRender_nonNegativeInteger_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#nonNegativeInteger"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:nonNegativeInteger")); } @Test public void shouldRender_nonPositiveInteger_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#nonPositiveInteger"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:nonPositiveInteger")); } @Test public void shouldRender_positiveInteger_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#positiveInteger"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:positiveInteger")); } @Test public void shouldRender_negativeInteger_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#negativeInteger"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:negativeInteger")); } @Test public void shouldRender_long_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#long"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:long")); } @Test public void shouldRender_int_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#int"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:int")); } @Test public void shouldRender_short_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#short"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:short")); } @Test public void shouldRender_byte_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#byte"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:byte")); } @Test public void shouldRender_unsignedLong_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#unsignedLong"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:unsignedLong")); } @Test public void shouldRender_unsignedInt_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#unsignedInt"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:unsignedInt")); } @Test public void shouldRender_unsignedShort_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#unsignedShort"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:unsignedShort")); } @Test public void shouldRender_unsignedByte_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#unsignedByte"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:unsignedByte")); } @Test public void shouldRender_double_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#double"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:double")); } @Test public void shouldRender_float_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#float"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:float")); } @Test public void shouldRender_boolean_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#boolean"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:boolean")); } @Test public void shouldRender_hexBinary_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#hexBinary"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:hexBinary")); } @Test public void shouldRender_base64Binary_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#base64Binary"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:base64Binary")); } @Test public void shouldRender_anyURI_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#anyURI"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:anyURI")); } @Test public void shouldRender_dateTime_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#dateTime"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:dateTime")); } @Test public void shouldRender_dateTimeStamp_WithXSDPrefixName() { iri = IRI.create("http://www.w3.org/2001/XMLSchema#dateTimeStamp"); when(entity.getIRI()).thenReturn(iri); assertThat(renderer.getShortForm(entity), is("xsd:dateTimeStamp")); } }
6,257
525
<gh_stars>100-1000 """ LinkedIn Authentication """ from xml.etree import ElementTree from django.conf import settings from .oauthclient import client API_KEY = settings.LINKEDIN_API_KEY API_SECRET = settings.LINKEDIN_API_SECRET # some parameters to indicate that status updating is possible STATUS_UPDATES = False STATUS_UPDATE_WORDING_TEMPLATE = "Tweet %s" OAUTH_PARAMS = { 'root_url' : 'https://api.linkedin.com/uas', 'request_token_path' : '/oauth/requestToken', 'authorize_path' : '/oauth/authorize', 'authenticate_path' : '/oauth/authenticate', 'access_token_path': '/oauth/accessToken' } def _get_new_client(token=None, token_secret=None): if token: return client.LoginOAuthClient(API_KEY, API_SECRET, OAUTH_PARAMS, token, token_secret) else: return client.LoginOAuthClient(API_KEY, API_SECRET, OAUTH_PARAMS) def _get_client_by_token(token): return _get_new_client(token['oauth_token'], token['oauth_token_secret']) def get_auth_url(request, redirect_url): client = _get_new_client() try: tok = client.get_request_token() except: return None request.session['request_token'] = tok url = client.get_authenticate_url(tok['oauth_token']) return url def get_user_info_after_auth(request): tok = request.session['request_token'] login_client = _get_client_by_token(tok) access_token = login_client.get_access_token(verifier = request.GET.get('oauth_verifier', None)) request.session['access_token'] = access_token user_info_xml = ElementTree.fromstring(login_client.oauth_request('http://api.linkedin.com/v1/people/~:(id,first-name,last-name)', args={}, method='GET')) user_id = user_info_xml.findtext('id') first_name = user_info_xml.findtext('first-name') last_name = user_info_xml.findtext('last-name') return {'type': 'linkedin', 'user_id' : user_id, 'name': "%s %s" % (first_name, last_name), 'info': {}, 'token': access_token} def user_needs_intervention(user_id, user_info, token): """ check to see if user is following the users we need """ return None def _get_client_by_request(request): access_token = request.session['access_token'] return _get_client_by_token(access_token) def update_status(user_id, user_info, token, message): """ post a message to the auth system's update stream, e.g. twitter stream """ return #twitter_client = _get_client_by_token(token) #result = twitter_client.oauth_request('http://api.twitter.com/1/statuses/update.json', args={'status': message}, method='POST') def send_message(user_id, user_name, user_info, subject, body): pass def send_notification(user_id, user_info, message): pass # # Election Creation # def can_create_election(user_id, user_info): return True
994
602
<filename>infrastructure/src/main/java/org/corfudb/infrastructure/logreplication/replication/fsm/EmptySnapshotReader.java package org.corfudb.infrastructure.logreplication.replication.fsm; import org.corfudb.infrastructure.logreplication.replication.send.logreader.SnapshotReadMessage; import org.corfudb.infrastructure.logreplication.replication.send.logreader.SnapshotReader; import java.util.ArrayList; import java.util.UUID; /** * Empty Implementation of Snapshot Reader - used for state machine transition testing (no logic) */ public class EmptySnapshotReader implements SnapshotReader { @Override public SnapshotReadMessage read(UUID snapshotRequestId) { return new SnapshotReadMessage(new ArrayList<>(), true); } @Override public void reset(long snapshotTimestamp) { } @Override public void setTopologyConfigId(long topologyConfigId) { } }
283
17,703
#include "contrib/sxg/filters/http/source/filter_config.h" #include <string> #include "envoy/http/codes.h" #include "envoy/server/filter_config.h" #include "envoy/stats/scope.h" #include "source/common/common/utility.h" #include "source/common/http/headers.h" #include "source/common/stats/utility.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace SXG { template <class T> const std::vector<std::string> initializeHeaderPrefixFilters(const T& filters_proto) { std::vector<std::string> filters; filters.reserve(filters_proto.size()); for (const auto& filter : filters_proto) { filters.emplace_back(filter); } return filters; } FilterConfig::FilterConfig(const envoy::extensions::filters::http::sxg::v3alpha::SXG& proto_config, TimeSource& time_source, std::shared_ptr<SecretReader> secret_reader, const std::string& stat_prefix, Stats::Scope& scope) : stats_(generateStats(stat_prefix + "sxg.", scope)), duration_(proto_config.has_duration() ? proto_config.duration().seconds() : 604800UL), cbor_url_(proto_config.cbor_url()), validity_url_(proto_config.validity_url()), mi_record_size_(proto_config.mi_record_size() ? proto_config.mi_record_size() : 4096L), client_can_accept_sxg_header_(proto_config.client_can_accept_sxg_header().length() > 0 ? proto_config.client_can_accept_sxg_header() : "x-client-can-accept-sxg"), should_encode_sxg_header_(proto_config.should_encode_sxg_header().length() > 0 ? proto_config.should_encode_sxg_header() : "x-should-encode-sxg"), header_prefix_filters_(initializeHeaderPrefixFilters(proto_config.header_prefix_filters())), time_source_(time_source), secret_reader_(secret_reader) {} } // namespace SXG } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
866
2,151
<reponame>zipated/src // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_DISPLAY_ASH_DISPLAY_CONTROLLER_H_ #define ASH_DISPLAY_ASH_DISPLAY_CONTROLLER_H_ #include "ash/public/interfaces/ash_display_controller.mojom.h" #include "base/macros.h" #include "mojo/public/cpp/bindings/binding_set.h" namespace ash { class AshDisplayController : public mojom::AshDisplayController { public: AshDisplayController(); ~AshDisplayController() override; void BindRequest(mojom::AshDisplayControllerRequest request); // mojom::AshDisplayController: void TakeDisplayControl(TakeDisplayControlCallback callback) override; void RelinquishDisplayControl( RelinquishDisplayControlCallback callback) override; private: mojo::BindingSet<mojom::AshDisplayController> bindings_; DISALLOW_COPY_AND_ASSIGN(AshDisplayController); }; } // namespace ash #endif // ASH_DISPLAY_ASH_DISPLAY_CONTROLLER_H_
336
677
<reponame>cristigr/macrobase<gh_stars>100-1000 package edu.stanford.futuredata.macrobase.integration; import edu.stanford.futuredata.macrobase.StreamingSummarizationTest; import edu.stanford.futuredata.macrobase.analysis.summary.Explanation; import edu.stanford.futuredata.macrobase.analysis.summary.fpg.FPGExplanation; import edu.stanford.futuredata.macrobase.analysis.summary.fpg.IncrementalSummarizer; import edu.stanford.futuredata.macrobase.analysis.summary.fpg.FPGrowthSummarizer; import edu.stanford.futuredata.macrobase.analysis.summary.fpg.result.FPGAttributeSet; import edu.stanford.futuredata.macrobase.datamodel.DataFrame; import edu.stanford.futuredata.macrobase.operator.WindowedOperator; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertTrue; /** * Compare the performance of sliding window summarization with repeated batch summarization. * The incremental sliding window operator should be noticeably faster. */ public class StreamingSummarizationBenchmark { public static void testWindowedPerformance() throws Exception { // Increase these numbers for more rigorous, slower performance testing int n = 100000; int k = 3; int C = 4; int d = 10; double p = 0.005; int eventIdx = 40000; int eventEndIdx = 100000; int windowSize = 50000; int slideSize = 1000; DataFrame df = StreamingSummarizationTest.generateAnomalyDataset(n, k, C, d, p, eventIdx, eventEndIdx); List<String> attributes = StreamingSummarizationTest.getAttributes(d, false); List<String> buggyAttributeValues = StreamingSummarizationTest.getAttributes(k, true); IncrementalSummarizer outlierSummarizer = new IncrementalSummarizer(); outlierSummarizer.setAttributes(attributes); outlierSummarizer.setOutlierColumn("outlier"); outlierSummarizer.setMinSupport(.3); WindowedOperator<FPGExplanation> windowedSummarizer = new WindowedOperator<>(outlierSummarizer); windowedSummarizer.setWindowLength(windowSize); windowedSummarizer.setTimeColumn("time"); windowedSummarizer.setSlideLength(slideSize); windowedSummarizer.initialize(); FPGrowthSummarizer bsumm = new FPGrowthSummarizer(); bsumm.setAttributes(attributes); bsumm.setOutlierColumn("outlier"); bsumm.setMinSupport(.3); int miniBatchSize = slideSize; double totalStreamingTime = 0.0; double totalBatchTime = 0.0; double startTime = 0.0; int nRows = df.getNumRows(); while (startTime < nRows) { double endTime = startTime + miniBatchSize; double ls = startTime; DataFrame curBatch = df.filter( "time", (double t) -> t >= ls && t < endTime ); long timerStart = System.currentTimeMillis(); windowedSummarizer.process(curBatch); windowedSummarizer.flushBuffer(); if (endTime >= windowSize) { FPGExplanation curExplanation = windowedSummarizer .getResults() .prune(); long timerElapsed = System.currentTimeMillis() - timerStart; totalStreamingTime += timerElapsed; DataFrame curWindow = df.filter( "time", (double t) -> t >= (endTime - windowSize) && t < endTime ); timerStart = System.currentTimeMillis(); bsumm.process(curWindow); FPGExplanation batchExplanation = bsumm.getResults().prune(); timerElapsed = System.currentTimeMillis() - timerStart; totalBatchTime += timerElapsed; // make sure that the known anomalous attribute combination has the highest risk ratio if (curExplanation.getItemsets().size() > 0) { FPGAttributeSet streamTopRankedExplanation = curExplanation.getItemsets().get(0); FPGAttributeSet batchTopRankedExplanation = batchExplanation.getItemsets().get(0); assertTrue(streamTopRankedExplanation.getItems().values().containsAll(buggyAttributeValues)); assertTrue(batchTopRankedExplanation.getItems().values().containsAll(buggyAttributeValues)); } } else { long timerElapsed = System.currentTimeMillis() - timerStart; totalStreamingTime += timerElapsed; } startTime = endTime; } System.out.println(String.format("window size: %d, slide size: %d", windowSize, slideSize)); System.out.println("Streaming Time: "+totalStreamingTime); System.out.println("Batch Time: "+totalBatchTime); } public static void main(String[] args) throws Exception { testWindowedPerformance(); } }
2,125
1,442
<filename>delta/data/task/kws_cls_task_test.py # Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== ''' kws task unittest''' import os from pathlib import Path import delta.compat as tf from absl import logging from delta import utils from delta.utils.register import registers from delta.utils.register import import_all_modules_for_register class KwsClsTaskTest(tf.test.TestCase): ''' kws task test''' def setUp(self): super().setUp() import_all_modules_for_register() ''' package_root = Path(PACKAGE_ROOT_DIR) config_file = main_root.joinpath('delta/config/kws-cls/kws_speech_cls.yml') config = utils.load_config(config_file) solver_name = config['solver']['name'] self.solver = registers.solver[solver_name](config) # config after process self.config = self.solver.config self.mode = utils.EVAL task_name = self.config['data']['task']['name'] self.task = registers.task[task_name](self.config, self.mode) self.dataset = self.task.dataset(self.mode, 25, 0) self.iterator = self.dataset.make_one_shot_iterator() self.one_element = self.iterator.get_next() ''' def tearDown(self): ''' tear down ''' def test_dataset(self): ''' dataset unittest''' pass ''' with self.cached_session(use_gpu=False, force_gpu=False) as sess: for _ in range(2): output = sess.run(self.one_element) logging.info(output) logging.info("output: {} {}".format(output.shape, output.dtype)) ''' if __name__ == '__main__': logging.set_verbosity(logging.DEBUG) tf.test.main()
786
3,182
<filename>test-manual/src/main/java/de/plushnikov/constructor/DataAndOtherConstructor.java package de.plushnikov.constructor; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import java.util.Timer; @Data @NoArgsConstructor public class DataAndOtherConstructor { int test1; int test2; public void test() { DataAndOtherConstructor test = new DataAndOtherConstructor(); System.out.println(test); DataAndAllArgsConstructor test2 = new DataAndAllArgsConstructor(1, 2); System.out.println(test2); DataAndRequiredArgsConstructor test3 = new DataAndRequiredArgsConstructor(); System.out.println(test3); SomeClass someClass = new SomeClass(); } @Data @AllArgsConstructor class DataAndAllArgsConstructor { int test1; int test2; } @Data @RequiredArgsConstructor class DataAndRequiredArgsConstructor { int test1; int test2; } public static void main(String[] args) { new DataAndOtherConstructor().test(); } @EqualsAndHashCode(callSuper = false) @Data class SomeClass extends Timer { final int x; SomeClass() { super(); x = 3; } } }
439
712
/* * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.gcp.vision; import com.google.cloud.storage.Blob; import com.google.protobuf.InvalidProtocolBufferException; import org.junit.Test; import org.mockito.Mockito; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class OcrPageRangeTests { private static final byte[] SINGLE_JSON_OUTPUT_PAGE = "{'responses':[{'fullTextAnnotation': {'text': 'hello_world'}}]}" .getBytes(); @Test public void testParseCorrectPageRange() { Blob blob = Mockito.mock(Blob.class); when(blob.getName()).thenReturn("blob-output-8-to-12.json"); when(blob.getContent()).thenReturn(SINGLE_JSON_OUTPUT_PAGE); OcrPageRange ocrPageRange = new OcrPageRange(blob); assertThat(ocrPageRange.getStartPage()).isEqualTo(8); assertThat(ocrPageRange.getEndPage()).isEqualTo(12); } @Test public void testBlobCaching() throws InvalidProtocolBufferException { Blob blob = Mockito.mock(Blob.class); when(blob.getName()).thenReturn("blob-output-1-to-1.json"); when(blob.getContent()).thenReturn(SINGLE_JSON_OUTPUT_PAGE); OcrPageRange ocrPageRange = new OcrPageRange(blob); assertThat(ocrPageRange.getPage(1).getText()).isEqualTo("hello_world"); assertThat(ocrPageRange.getPage(1).getText()).isEqualTo("hello_world"); assertThat(ocrPageRange.getPages()).hasSize(1); /* Retrieved content of blob 3 times, but getContent() only called once due to caching. */ verify(blob, times(1)).getContent(); } }
748
683
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.jaxws.jws.v1_1; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ProxyInvocationHandler implements InvocationHandler { final WebServiceDefinitionInterface target; public ProxyInvocationHandler(WebServiceFromInterface webServiceFromInterface) { target = webServiceFromInterface; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(target, args); } }
175
513
<reponame>trajano/google-fonts { "family": "Vollkorn", "variants": [ "regular", "500", "600", "700", "800", "900", "italic", "500italic", "600italic", "700italic", "800italic", "900italic" ], "subsets": ["cyrillic", "cyrillic-ext", "greek", "latin", "latin-ext", "vietnamese"], "version": "v13", "lastModified": "2021-01-30", "files": { "500": "http://fonts.gstatic.com/s/vollkorn/v13/0ybgGDoxxrvAnPhYGzMlQLzuMasz6Df2AnGuGWOdEbD63w.ttf", "600": "http://fonts.gstatic.com/s/vollkorn/v13/0ybgGDoxxrvAnPhYGzMlQLzuMasz6Df27nauGWOdEbD63w.ttf", "700": "http://fonts.gstatic.com/s/vollkorn/v13/0ybgGDoxxrvAnPhYGzMlQLzuMasz6Df213auGWOdEbD63w.ttf", "800": "http://fonts.gstatic.com/s/vollkorn/v13/0ybgGDoxxrvAnPhYGzMlQLzuMasz6Df2sHauGWOdEbD63w.ttf", "900": "http://fonts.gstatic.com/s/vollkorn/v13/0ybgGDoxxrvAnPhYGzMlQLzuMasz6Df2mXauGWOdEbD63w.ttf", "regular": "http://fonts.gstatic.com/s/vollkorn/v13/0ybgGDoxxrvAnPhYGzMlQLzuMasz6Df2MHGuGWOdEbD63w.ttf", "italic": "http://fonts.gstatic.com/s/vollkorn/v13/0ybuGDoxxrvAnPhYGxksckM2WMCpRjDj-DJGWmmZM7Xq34g9.ttf", "500italic": "http://fonts.gstatic.com/s/vollkorn/v13/0ybuGDoxxrvAnPhYGxksckM2WMCpRjDj-DJ0WmmZM7Xq34g9.ttf", "600italic": "http://fonts.gstatic.com/s/vollkorn/v13/0ybuGDoxxrvAnPhYGxksckM2WMCpRjDj-DKYXWmZM7Xq34g9.ttf", "700italic": "http://fonts.gstatic.com/s/vollkorn/v13/0ybuGDoxxrvAnPhYGxksckM2WMCpRjDj-DKhXWmZM7Xq34g9.ttf", "800italic": "http://fonts.gstatic.com/s/vollkorn/v13/0ybuGDoxxrvAnPhYGxksckM2WMCpRjDj-DLGXWmZM7Xq34g9.ttf", "900italic": "http://fonts.gstatic.com/s/vollkorn/v13/0ybuGDoxxrvAnPhYGxksckM2WMCpRjDj-DLvXWmZM7Xq34g9.ttf" }, "category": "serif", "kind": "webfonts#webfont" }
1,045
964
[ { "queryName": "Deployment Has No PodAntiAffinity", "severity": "LOW", "line": 19 }, { "queryName": "Deployment Has No PodAntiAffinity", "severity": "LOW", "line": 39 } ]
86