body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def get_lbs_for_center_crop(crop_size, data_shape): '\n :param crop_size:\n :param data_shape: (b,c,x,y(,z)) must be the whole thing!\n :return:\n ' lbs = [] for i in range((len(data_shape) - 2)): lbs.append(((data_shape[(i + 2)] - crop_size[i]) // 2)) return lbs
5,384,268,792,373,000,000
:param crop_size: :param data_shape: (b,c,x,y(,z)) must be the whole thing! :return:
data/crop_and_pad_augmentations.py
get_lbs_for_center_crop
bowang-lab/shape-attentive-unet
python
def get_lbs_for_center_crop(crop_size, data_shape): '\n :param crop_size:\n :param data_shape: (b,c,x,y(,z)) must be the whole thing!\n :return:\n ' lbs = [] for i in range((len(data_shape) - 2)): lbs.append(((data_shape[(i + 2)] - crop_size[i]) // 2)) return lbs
def crop(data, seg=None, crop_size=128, margins=(0, 0, 0), crop_type='center', pad_mode='constant', pad_kwargs={'constant_values': 0}, pad_mode_seg='constant', pad_kwargs_seg={'constant_values': 0}): '\n crops data and seg (seg may be None) to crop_size. Whether this will be achieved via center or random crop is...
-4,820,768,818,868,650,000
crops data and seg (seg may be None) to crop_size. Whether this will be achieved via center or random crop is determined by crop_type. Margin will be respected only for random_crop and will prevent the crops form being closer than margin to the respective image border. crop_size can be larger than data_shape - margin -...
data/crop_and_pad_augmentations.py
crop
bowang-lab/shape-attentive-unet
python
def crop(data, seg=None, crop_size=128, margins=(0, 0, 0), crop_type='center', pad_mode='constant', pad_kwargs={'constant_values': 0}, pad_mode_seg='constant', pad_kwargs_seg={'constant_values': 0}): '\n crops data and seg (seg may be None) to crop_size. Whether this will be achieved via center or random crop is...
def pad_nd_image_and_seg(data, seg, new_shape=None, must_be_divisible_by=None, pad_mode_data='constant', np_pad_kwargs_data=None, pad_mode_seg='constant', np_pad_kwargs_seg=None): '\n Pads data and seg to new_shape. new_shape is thereby understood as min_shape (if data/seg is already larger then\n new_shape t...
-694,869,453,499,894,400
Pads data and seg to new_shape. new_shape is thereby understood as min_shape (if data/seg is already larger then new_shape the shape stays the same for the dimensions this applies) :param data: :param seg: :param new_shape: if none then only must_be_divisible_by is applied :param must_be_divisible_by: UNet like archite...
data/crop_and_pad_augmentations.py
pad_nd_image_and_seg
bowang-lab/shape-attentive-unet
python
def pad_nd_image_and_seg(data, seg, new_shape=None, must_be_divisible_by=None, pad_mode_data='constant', np_pad_kwargs_data=None, pad_mode_seg='constant', np_pad_kwargs_seg=None): '\n Pads data and seg to new_shape. new_shape is thereby understood as min_shape (if data/seg is already larger then\n new_shape t...
def extract_leegstand(self): 'Create a column indicating leegstand (no inhabitants on the address).' self.data['leegstand'] = (~ self.data.inwnrs.notnull()) self.version += '_leegstand' self.save()
-4,992,713,222,237,245,000
Create a column indicating leegstand (no inhabitants on the address).
codebase/datasets/adres_dataset.py
extract_leegstand
petercuret/woonfraude
python
def extract_leegstand(self): self.data['leegstand'] = (~ self.data.inwnrs.notnull()) self.version += '_leegstand' self.save()
def enrich_with_woning_id(self): 'Add woning ids to the adres dataframe.' adres_periodes = datasets.download_dataset('bwv_adres_periodes', 'bwv_adres_periodes') self.data = self.data.merge(adres_periodes[['ads_id', 'wng_id']], how='left', left_on='adres_id', right_on='ads_id') self.version += '_woningId...
9,146,979,939,905,093,000
Add woning ids to the adres dataframe.
codebase/datasets/adres_dataset.py
enrich_with_woning_id
petercuret/woonfraude
python
def enrich_with_woning_id(self): adres_periodes = datasets.download_dataset('bwv_adres_periodes', 'bwv_adres_periodes') self.data = self.data.merge(adres_periodes[['ads_id', 'wng_id']], how='left', left_on='adres_id', right_on='ads_id') self.version += '_woningId' self.save()
def impute_values_for_bagless_addresses(self, adres): 'Impute values for adresses where no BAG-match could be found.' clean.impute_missing_values(adres) adres.fillna(value={'huisnummer_nummeraanduiding': 0, 'huisletter_nummeraanduiding': 'None', '_openbare_ruimte_naam_nummeraanduiding': 'None', 'huisnummer_...
-5,799,213,507,536,765,000
Impute values for adresses where no BAG-match could be found.
codebase/datasets/adres_dataset.py
impute_values_for_bagless_addresses
petercuret/woonfraude
python
def impute_values_for_bagless_addresses(self, adres): clean.impute_missing_values(adres) adres.fillna(value={'huisnummer_nummeraanduiding': 0, 'huisletter_nummeraanduiding': 'None', '_openbare_ruimte_naam_nummeraanduiding': 'None', 'huisnummer_toevoeging_nummeraanduiding': 'None', 'type_woonobject_omschrij...
def enrich_with_bag(self, bag): 'Enrich the adres data with information from the BAG data. Uses the bag dataframe as input.' bag = self.prepare_bag(bag) self.data = self.prepare_adres(self.data) self.data = self.match_bwv_bag(self.data, bag) self.data = self.replace_string_nan_adres(self.data) s...
2,526,807,197,943,869,400
Enrich the adres data with information from the BAG data. Uses the bag dataframe as input.
codebase/datasets/adres_dataset.py
enrich_with_bag
petercuret/woonfraude
python
def enrich_with_bag(self, bag): bag = self.prepare_bag(bag) self.data = self.prepare_adres(self.data) self.data = self.match_bwv_bag(self.data, bag) self.data = self.replace_string_nan_adres(self.data) self.data = self.impute_values_for_bagless_addresses(self.data) self.version += '_bag' ...
def enrich_with_personen_features(self, personen): 'Add aggregated features relating to persons to the address dataframe. Uses the personen dataframe as input.' adres = self.data today = pd.to_datetime('today') personen['geboortedatum'] = pd.to_datetime(personen['geboortedatum'], errors='coerce') ge...
-7,579,026,273,688,002,000
Add aggregated features relating to persons to the address dataframe. Uses the personen dataframe as input.
codebase/datasets/adres_dataset.py
enrich_with_personen_features
petercuret/woonfraude
python
def enrich_with_personen_features(self, personen): adres = self.data today = pd.to_datetime('today') personen['geboortedatum'] = pd.to_datetime(personen['geboortedatum'], errors='coerce') geboortedatum_mode = personen['geboortedatum'].mode()[0] personen['leeftijd'] = (today - personen['geboorte...
def add_hotline_features(self, hotline): 'Add the hotline features to the adres dataframe.' merge = self.data.merge(hotline, on='wng_id', how='left') adres_groups = merge.groupby(by='adres_id') hotline_counts = adres_groups['id'].agg(['count']) hotline_counts.columns = ['aantal_hotline_meldingen'] ...
4,715,285,952,275,173,000
Add the hotline features to the adres dataframe.
codebase/datasets/adres_dataset.py
add_hotline_features
petercuret/woonfraude
python
def add_hotline_features(self, hotline): merge = self.data.merge(hotline, on='wng_id', how='left') adres_groups = merge.groupby(by='adres_id') hotline_counts = adres_groups['id'].agg(['count']) hotline_counts.columns = ['aantal_hotline_meldingen'] self.data = self.data.merge(hotline_counts, on=...
def SubPixel1D_v2(I, r): 'One-dimensional subpixel upsampling layer\n\n Based on https://github.com/Tetrachrome/subpixel/blob/master/subpixel.py\n ' with tf.compat.v1.name_scope('subpixel'): (bsize, a, r) = I.get_shape().as_list() bsize = tf.shape(input=I)[0] X = tf.split(1, a, I) ...
1,428,587,690,402,081,500
One-dimensional subpixel upsampling layer Based on https://github.com/Tetrachrome/subpixel/blob/master/subpixel.py
src/models/layers/subpixel.py
SubPixel1D_v2
Lootwig/audio-super-res
python
def SubPixel1D_v2(I, r): 'One-dimensional subpixel upsampling layer\n\n Based on https://github.com/Tetrachrome/subpixel/blob/master/subpixel.py\n ' with tf.compat.v1.name_scope('subpixel'): (bsize, a, r) = I.get_shape().as_list() bsize = tf.shape(input=I)[0] X = tf.split(1, a, I) ...
def SubPixel1D(I, r): 'One-dimensional subpixel upsampling layer\n\n Calls a tensorflow function that directly implements this functionality.\n We assume input has dim (batch, width, r)\n ' with tf.compat.v1.name_scope('subpixel'): X = tf.transpose(a=I, perm=[2, 1, 0]) X = tf.batch_to_space(X...
6,580,163,009,517,961,000
One-dimensional subpixel upsampling layer Calls a tensorflow function that directly implements this functionality. We assume input has dim (batch, width, r)
src/models/layers/subpixel.py
SubPixel1D
Lootwig/audio-super-res
python
def SubPixel1D(I, r): 'One-dimensional subpixel upsampling layer\n\n Calls a tensorflow function that directly implements this functionality.\n We assume input has dim (batch, width, r)\n ' with tf.compat.v1.name_scope('subpixel'): X = tf.transpose(a=I, perm=[2, 1, 0]) X = tf.batch_to_space(X...
def SubPixel1D_multichan(I, r): 'One-dimensional subpixel upsampling layer\n\n Calls a tensorflow function that directly implements this functionality.\n We assume input has dim (batch, width, r).\n\n Works with multiple channels: (B,L,rC) -> (B,rL,C)\n ' with tf.compat.v1.name_scope('subpixel'): (_...
-7,981,073,372,711,496,000
One-dimensional subpixel upsampling layer Calls a tensorflow function that directly implements this functionality. We assume input has dim (batch, width, r). Works with multiple channels: (B,L,rC) -> (B,rL,C)
src/models/layers/subpixel.py
SubPixel1D_multichan
Lootwig/audio-super-res
python
def SubPixel1D_multichan(I, r): 'One-dimensional subpixel upsampling layer\n\n Calls a tensorflow function that directly implements this functionality.\n We assume input has dim (batch, width, r).\n\n Works with multiple channels: (B,L,rC) -> (B,rL,C)\n ' with tf.compat.v1.name_scope('subpixel'): (_...
def dkim_sign(message, dkim_domain=None, dkim_key=None, dkim_selector=None, dkim_headers=None): 'Return signed email message if dkim package and settings are available.' try: import dkim except ImportError: pass else: if (dkim_domain and dkim_key): sig = dkim.sign(mes...
-6,159,254,177,365,536,000
Return signed email message if dkim package and settings are available.
django_ses/__init__.py
dkim_sign
mlissner/django-ses
python
def dkim_sign(message, dkim_domain=None, dkim_key=None, dkim_selector=None, dkim_headers=None): try: import dkim except ImportError: pass else: if (dkim_domain and dkim_key): sig = dkim.sign(message, dkim_selector, dkim_domain, dkim_key, include_headers=dkim_headers)...
def cast_nonzero_to_float(val): 'Cast nonzero number to float; on zero or None, return None' if (not val): return None return float(val)
6,612,048,108,139,969,000
Cast nonzero number to float; on zero or None, return None
django_ses/__init__.py
cast_nonzero_to_float
mlissner/django-ses
python
def cast_nonzero_to_float(val): if (not val): return None return float(val)
def open(self): 'Create a connection to the AWS API server. This can be reused for\n sending multiple emails.\n ' if self.connection: return False try: self.connection = boto3.client('ses', aws_access_key_id=self._access_key_id, aws_secret_access_key=self._access_key, region_na...
-3,722,438,059,502,486,000
Create a connection to the AWS API server. This can be reused for sending multiple emails.
django_ses/__init__.py
open
mlissner/django-ses
python
def open(self): 'Create a connection to the AWS API server. This can be reused for\n sending multiple emails.\n ' if self.connection: return False try: self.connection = boto3.client('ses', aws_access_key_id=self._access_key_id, aws_secret_access_key=self._access_key, region_na...
def close(self): 'Close any open HTTP connections to the API server.\n ' self.connection = None
3,509,590,564,129,190,400
Close any open HTTP connections to the API server.
django_ses/__init__.py
close
mlissner/django-ses
python
def close(self): '\n ' self.connection = None
def send_messages(self, email_messages): 'Sends one or more EmailMessage objects and returns the number of\n email messages sent.\n ' if (not email_messages): return new_conn_created = self.open() if (not self.connection): return num_sent = 0 source = settings.AWS_S...
-3,148,640,440,429,157,000
Sends one or more EmailMessage objects and returns the number of email messages sent.
django_ses/__init__.py
send_messages
mlissner/django-ses
python
def send_messages(self, email_messages): 'Sends one or more EmailMessage objects and returns the number of\n email messages sent.\n ' if (not email_messages): return new_conn_created = self.open() if (not self.connection): return num_sent = 0 source = settings.AWS_S...
def run_python_tests(): ' Runs the Python tests.\n Returns:\n True if the tests all succeed, False if there are failures. ' print('Starting tests...') loader = unittest.TestLoader() dir_path = os.path.dirname(os.path.realpath(__file__)) suite = loader.discover('rhodopsin/tests', top_level_dir=di...
6,912,438,203,725,193,000
Runs the Python tests. Returns: True if the tests all succeed, False if there are failures.
run_tests.py
run_python_tests
djpetti/rhodopsin
python
def run_python_tests(): ' Runs the Python tests.\n Returns:\n True if the tests all succeed, False if there are failures. ' print('Starting tests...') loader = unittest.TestLoader() dir_path = os.path.dirname(os.path.realpath(__file__)) suite = loader.discover('rhodopsin/tests', top_level_dir=di...
def upgrade(): 'Migrations for the upgrade.' op.execute("\n UPDATE db_dbnode SET type = 'data.bool.Bool.' WHERE type = 'data.base.Bool.';\n UPDATE db_dbnode SET type = 'data.float.Float.' WHERE type = 'data.base.Float.';\n UPDATE db_dbnode SET type = 'data.int.Int.' WHERE type =...
-5,629,107,005,712,645,000
Migrations for the upgrade.
aiida/storage/psql_dos/migrations/versions/django_0009_base_data_plugin_type_string.py
upgrade
mkrack/aiida-core
python
def upgrade(): op.execute("\n UPDATE db_dbnode SET type = 'data.bool.Bool.' WHERE type = 'data.base.Bool.';\n UPDATE db_dbnode SET type = 'data.float.Float.' WHERE type = 'data.base.Float.';\n UPDATE db_dbnode SET type = 'data.int.Int.' WHERE type = 'data.base.Int.';\n ...
def downgrade(): 'Migrations for the downgrade.' op.execute("\n UPDATE db_dbnode SET type = 'data.base.Bool.' WHERE type = 'data.bool.Bool.';\n UPDATE db_dbnode SET type = 'data.base.Float.' WHERE type = 'data.float.Float.';\n UPDATE db_dbnode SET type = 'data.base.Int.' WHERE t...
3,713,483,839,730,805,000
Migrations for the downgrade.
aiida/storage/psql_dos/migrations/versions/django_0009_base_data_plugin_type_string.py
downgrade
mkrack/aiida-core
python
def downgrade(): op.execute("\n UPDATE db_dbnode SET type = 'data.base.Bool.' WHERE type = 'data.bool.Bool.';\n UPDATE db_dbnode SET type = 'data.base.Float.' WHERE type = 'data.float.Float.';\n UPDATE db_dbnode SET type = 'data.base.Int.' WHERE type = 'data.int.Int.';\n ...
def VirtualMachineRuntimeInfo(vim, *args, **kwargs): 'The RuntimeInfo data object type provides information about the execution state\n and history of a virtual machine.' obj = vim.client.factory.create('{urn:vim25}VirtualMachineRuntimeInfo') if ((len(args) + len(kwargs)) < 7): raise IndexError((...
-7,396,303,371,140,011,000
The RuntimeInfo data object type provides information about the execution state and history of a virtual machine.
pyvisdk/do/virtual_machine_runtime_info.py
VirtualMachineRuntimeInfo
Infinidat/pyvisdk
python
def VirtualMachineRuntimeInfo(vim, *args, **kwargs): 'The RuntimeInfo data object type provides information about the execution state\n and history of a virtual machine.' obj = vim.client.factory.create('{urn:vim25}VirtualMachineRuntimeInfo') if ((len(args) + len(kwargs)) < 7): raise IndexError((...
def __init__(self, list=None): ' A list of particle ids and names can be given to the constructor.\n ' self._list = [] if (list != None): self._list = list
-4,374,892,717,127,874,000
A list of particle ids and names can be given to the constructor.
FWCore/GuiBrowsers/python/Vispa/Plugins/EdmBrowser/ParticleDataList.py
__init__
7quantumphysics/cmssw
python
def __init__(self, list=None): ' \n ' self._list = [] if (list != None): self._list = list
def addParticle(self, ids, names, particleData): ' Add a paricle with (multiple) ids and names to the list.\n ' if (not (isinstance(ids, list) and isinstance(names, list))): raise TypeError("addParticle needs to lists as input: e.g. [1,-1],['d','dbar']") self._list += [(ids, names, particleDa...
-4,326,403,141,763,996,700
Add a paricle with (multiple) ids and names to the list.
FWCore/GuiBrowsers/python/Vispa/Plugins/EdmBrowser/ParticleDataList.py
addParticle
7quantumphysics/cmssw
python
def addParticle(self, ids, names, particleData): ' \n ' if (not (isinstance(ids, list) and isinstance(names, list))): raise TypeError("addParticle needs to lists as input: e.g. [1,-1],['d','dbar']") self._list += [(ids, names, particleData)]
def getDefaultName(self, name): " Return the default (first in list) name given any of the particle's names.\n " for items in self._list: if (name in items[1]): return items[1][0] return name
-5,270,448,408,394,749,000
Return the default (first in list) name given any of the particle's names.
FWCore/GuiBrowsers/python/Vispa/Plugins/EdmBrowser/ParticleDataList.py
getDefaultName
7quantumphysics/cmssw
python
def getDefaultName(self, name): " \n " for items in self._list: if (name in items[1]): return items[1][0] return name
def getDefaultId(self, id): " Return the default (first in list) id given any of the particle's ids.\n " for items in self._list: if (id in items[0]): return items[0][0] return id
-8,276,303,927,237,939,000
Return the default (first in list) id given any of the particle's ids.
FWCore/GuiBrowsers/python/Vispa/Plugins/EdmBrowser/ParticleDataList.py
getDefaultId
7quantumphysics/cmssw
python
def getDefaultId(self, id): " \n " for items in self._list: if (id in items[0]): return items[0][0] return id
def getIdFromName(self, name): " Return the default (first in list) id given any of the particle's names.\n " for items in self._list: if (name in items[1]): return items[0][0] return 0
344,722,637,239,240,640
Return the default (first in list) id given any of the particle's names.
FWCore/GuiBrowsers/python/Vispa/Plugins/EdmBrowser/ParticleDataList.py
getIdFromName
7quantumphysics/cmssw
python
def getIdFromName(self, name): " \n " for items in self._list: if (name in items[1]): return items[0][0] return 0
def getNameFromId(self, id): " Return the default (first in list) name given any of the particle's ids.\n " for items in self._list: if (id in items[0]): return items[1][0] return 'unknown'
7,222,615,436,292,470,000
Return the default (first in list) name given any of the particle's ids.
FWCore/GuiBrowsers/python/Vispa/Plugins/EdmBrowser/ParticleDataList.py
getNameFromId
7quantumphysics/cmssw
python
def getNameFromId(self, id): " \n " for items in self._list: if (id in items[0]): return items[1][0] return 'unknown'
def __init__(self, channel): 'Constructor.\n\n Args:\n channel: A grpc.Channel.\n ' self.Predict = channel.unary_unary('/onnxruntime.server.PredictionService/Predict', request_serializer=predict__pb2.PredictRequest.SerializeToString, response_deserializer=predict__pb2.PredictResponse.Fr...
-8,563,973,921,117,573,000
Constructor. Args: channel: A grpc.Channel.
chapter2_training/cifar10/evaluate/src/proto/prediction_service_pb2_grpc.py
__init__
akiueno/ml-system-in-actions
python
def __init__(self, channel): 'Constructor.\n\n Args:\n channel: A grpc.Channel.\n ' self.Predict = channel.unary_unary('/onnxruntime.server.PredictionService/Predict', request_serializer=predict__pb2.PredictRequest.SerializeToString, response_deserializer=predict__pb2.PredictResponse.Fr...
def Predict(self, request, context): 'Missing associated documentation comment in .proto file.' context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
3,231,770,545,470,701,600
Missing associated documentation comment in .proto file.
chapter2_training/cifar10/evaluate/src/proto/prediction_service_pb2_grpc.py
Predict
akiueno/ml-system-in-actions
python
def Predict(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
def test_valid_distribution(self): 'Test for a valid distribution.' plugin = Plugin(distribution='norm') self.assertEqual(plugin.distribution, stats.norm) self.assertEqual(plugin.shape_parameters, [])
6,153,720,595,872,060,000
Test for a valid distribution.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_valid_distribution
LaurenceBeard/improver
python
def test_valid_distribution(self): plugin = Plugin(distribution='norm') self.assertEqual(plugin.distribution, stats.norm) self.assertEqual(plugin.shape_parameters, [])
def test_valid_distribution_with_shape_parameters(self): 'Test for a valid distribution with shape parameters.' plugin = Plugin(distribution='truncnorm', shape_parameters=[0, np.inf]) self.assertEqual(plugin.distribution, stats.truncnorm) self.assertEqual(plugin.shape_parameters, [0, np.inf])
8,800,657,711,953,296,000
Test for a valid distribution with shape parameters.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_valid_distribution_with_shape_parameters
LaurenceBeard/improver
python
def test_valid_distribution_with_shape_parameters(self): plugin = Plugin(distribution='truncnorm', shape_parameters=[0, np.inf]) self.assertEqual(plugin.distribution, stats.truncnorm) self.assertEqual(plugin.shape_parameters, [0, np.inf])
def test_invalid_distribution(self): 'Test for an invalid distribution.' msg = 'The distribution requested' with self.assertRaisesRegex(AttributeError, msg): Plugin(distribution='elephant')
-2,428,895,901,677,872,600
Test for an invalid distribution.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_invalid_distribution
LaurenceBeard/improver
python
def test_invalid_distribution(self): msg = 'The distribution requested' with self.assertRaisesRegex(AttributeError, msg): Plugin(distribution='elephant')
def test_basic(self): 'Test string representation' expected_string = '<ConvertLocationAndScaleParameters: distribution: norm; shape_parameters: []>' result = str(Plugin()) self.assertEqual(result, expected_string)
-7,172,860,046,943,809,000
Test string representation
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_basic
LaurenceBeard/improver
python
def test_basic(self): expected_string = '<ConvertLocationAndScaleParameters: distribution: norm; shape_parameters: []>' result = str(Plugin()) self.assertEqual(result, expected_string)
def setUp(self): 'Set up values for testing.' self.location_parameter = np.array([(- 1), 0, 1]) self.scale_parameter = np.array([1, 1.5, 2])
-2,617,334,872,451,485,000
Set up values for testing.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
setUp
LaurenceBeard/improver
python
def setUp(self): self.location_parameter = np.array([(- 1), 0, 1]) self.scale_parameter = np.array([1, 1.5, 2])
def test_truncated_at_zero(self): 'Test scaling shape parameters implying a truncation at zero.' expected = [np.array([1.0, 0, (- 0.5)]), np.array([np.inf, np.inf, np.inf])] shape_parameters = [0, np.inf] plugin = Plugin(distribution='truncnorm', shape_parameters=shape_parameters) plugin._rescale_sh...
5,019,037,578,939,496,000
Test scaling shape parameters implying a truncation at zero.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_truncated_at_zero
LaurenceBeard/improver
python
def test_truncated_at_zero(self): expected = [np.array([1.0, 0, (- 0.5)]), np.array([np.inf, np.inf, np.inf])] shape_parameters = [0, np.inf] plugin = Plugin(distribution='truncnorm', shape_parameters=shape_parameters) plugin._rescale_shape_parameters(self.location_parameter, self.scale_parameter) ...
def test_discrete_shape_parameters(self): 'Test scaling discrete shape parameters.' expected = [np.array([(- 3), (- 2.666667), (- 2.5)]), np.array([7, 4, 2.5])] shape_parameters = [(- 4), 6] plugin = Plugin(distribution='truncnorm', shape_parameters=shape_parameters) plugin._rescale_shape_parameters...
-8,064,486,279,954,355,000
Test scaling discrete shape parameters.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_discrete_shape_parameters
LaurenceBeard/improver
python
def test_discrete_shape_parameters(self): expected = [np.array([(- 3), (- 2.666667), (- 2.5)]), np.array([7, 4, 2.5])] shape_parameters = [(- 4), 6] plugin = Plugin(distribution='truncnorm', shape_parameters=shape_parameters) plugin._rescale_shape_parameters(self.location_parameter, self.scale_para...
def test_alternative_distribution(self): 'Test specifying a distribution other than truncated normal. In\n this instance, no rescaling is applied.' shape_parameters = [0, np.inf] plugin = Plugin(distribution='norm', shape_parameters=shape_parameters) plugin._rescale_shape_parameters(self.location...
-6,880,325,163,840,395,000
Test specifying a distribution other than truncated normal. In this instance, no rescaling is applied.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_alternative_distribution
LaurenceBeard/improver
python
def test_alternative_distribution(self): 'Test specifying a distribution other than truncated normal. In\n this instance, no rescaling is applied.' shape_parameters = [0, np.inf] plugin = Plugin(distribution='norm', shape_parameters=shape_parameters) plugin._rescale_shape_parameters(self.location...
def test_no_shape_parameters_exception(self): 'Test raising an exception when shape parameters are not specified\n for the truncated normal distribution.' plugin = Plugin(distribution='truncnorm') msg = 'For the truncated normal distribution' with self.assertRaisesRegex(ValueError, msg): ...
-1,700,685,026,259,694,600
Test raising an exception when shape parameters are not specified for the truncated normal distribution.
improver_tests/ensemble_copula_coupling/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py
test_no_shape_parameters_exception
LaurenceBeard/improver
python
def test_no_shape_parameters_exception(self): 'Test raising an exception when shape parameters are not specified\n for the truncated normal distribution.' plugin = Plugin(distribution='truncnorm') msg = 'For the truncated normal distribution' with self.assertRaisesRegex(ValueError, msg): ...
def harmonic_mean(x): '\n The `harmonic mean`_ is a kind of average that is calculated as\n the reciprocal_ of the arithmetic mean of the reciprocals.\n It is appropriate when calculating averages of rates_.\n\n .. _`harmonic mean`: https://en.wikipedia.org/wiki/Harmonic_mean\n .. _reciprocal: https:...
591,122,178,774,666,200
The `harmonic mean`_ is a kind of average that is calculated as the reciprocal_ of the arithmetic mean of the reciprocals. It is appropriate when calculating averages of rates_. .. _`harmonic mean`: https://en.wikipedia.org/wiki/Harmonic_mean .. _reciprocal: https://en.wikipedia.org/wiki/Multiplicative_inverse .. _rat...
simplestatistics/statistics/harmonic_mean.py
harmonic_mean
sheriferson/simple-statistics-py
python
def harmonic_mean(x): '\n The `harmonic mean`_ is a kind of average that is calculated as\n the reciprocal_ of the arithmetic mean of the reciprocals.\n It is appropriate when calculating averages of rates_.\n\n .. _`harmonic mean`: https://en.wikipedia.org/wiki/Harmonic_mean\n .. _reciprocal: https:...
@pytest.mark.regions(['ap-southeast-1']) @pytest.mark.instances(['c5.xlarge']) @pytest.mark.oss(['alinux2']) @pytest.mark.schedulers(['slurm', 'awsbatch']) @pytest.mark.usefixtures('region', 'instance') def test_tag_propagation(pcluster_config_reader, clusters_factory, scheduler, os): "\n Verify tags from variou...
-7,428,828,917,190,505,000
Verify tags from various sources are propagated to the expected resources. The following resources are checked for tags: - main CFN stack - head node - head node's root EBS volume - compute node (traditional schedulers) - compute node's root EBS volume (traditional schedulers) - shared EBS volume
tests/integration-tests/tests/tags/test_tag_propagation.py
test_tag_propagation
eshpc/aws-parallelcluster
python
@pytest.mark.regions(['ap-southeast-1']) @pytest.mark.instances(['c5.xlarge']) @pytest.mark.oss(['alinux2']) @pytest.mark.schedulers(['slurm', 'awsbatch']) @pytest.mark.usefixtures('region', 'instance') def test_tag_propagation(pcluster_config_reader, clusters_factory, scheduler, os): "\n Verify tags from variou...
def convert_tags_dicts_to_tags_list(tags_dicts): 'Convert dicts of the form {key: value} to a list like [{"Key": key, "Value": value}].' tags_list = [] for tags_dict in tags_dicts: tags_list.extend([{'Key': key, 'Value': value} for (key, value) in tags_dict.items()]) return tags_list
-4,554,017,946,200,980,000
Convert dicts of the form {key: value} to a list like [{"Key": key, "Value": value}].
tests/integration-tests/tests/tags/test_tag_propagation.py
convert_tags_dicts_to_tags_list
eshpc/aws-parallelcluster
python
def convert_tags_dicts_to_tags_list(tags_dicts): tags_list = [] for tags_dict in tags_dicts: tags_list.extend([{'Key': key, 'Value': value} for (key, value) in tags_dict.items()]) return tags_list
def get_cloudformation_tags(region, stack_name): "\n Return the tags for the CFN stack with the given name\n\n The returned values is a list like the following:\n [\n {'Key': 'Key2', 'Value': 'Value2'},\n {'Key': 'Key1', 'Value': 'Value1'},\n ]\n " cfn_client = boto3.client('cloudfo...
-6,683,868,679,622,842,000
Return the tags for the CFN stack with the given name The returned values is a list like the following: [ {'Key': 'Key2', 'Value': 'Value2'}, {'Key': 'Key1', 'Value': 'Value1'}, ]
tests/integration-tests/tests/tags/test_tag_propagation.py
get_cloudformation_tags
eshpc/aws-parallelcluster
python
def get_cloudformation_tags(region, stack_name): "\n Return the tags for the CFN stack with the given name\n\n The returned values is a list like the following:\n [\n {'Key': 'Key2', 'Value': 'Value2'},\n {'Key': 'Key1', 'Value': 'Value1'},\n ]\n " cfn_client = boto3.client('cloudfo...
def get_main_stack_tags(cluster): "Return the tags for the cluster's main CFN stack." return get_cloudformation_tags(cluster.region, cluster.cfn_name)
-7,796,513,982,243,440,000
Return the tags for the cluster's main CFN stack.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_main_stack_tags
eshpc/aws-parallelcluster
python
def get_main_stack_tags(cluster): return get_cloudformation_tags(cluster.region, cluster.cfn_name)
def get_head_node_instance_id(cluster): "Return the given cluster's head node's instance ID." return cluster.cfn_resources.get('HeadNode')
-6,527,855,288,032,906,000
Return the given cluster's head node's instance ID.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_head_node_instance_id
eshpc/aws-parallelcluster
python
def get_head_node_instance_id(cluster): return cluster.cfn_resources.get('HeadNode')
def get_ec2_instance_tags(instance_id, region): 'Return a list of tags associated with the given EC2 instance.' logging.info('Getting tags for instance %s', instance_id) return boto3.client('ec2', region_name=region).describe_instances(InstanceIds=[instance_id]).get('Reservations')[0].get('Instances')[0].ge...
9,049,807,806,296,432,000
Return a list of tags associated with the given EC2 instance.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_ec2_instance_tags
eshpc/aws-parallelcluster
python
def get_ec2_instance_tags(instance_id, region): logging.info('Getting tags for instance %s', instance_id) return boto3.client('ec2', region_name=region).describe_instances(InstanceIds=[instance_id]).get('Reservations')[0].get('Instances')[0].get('Tags')
def get_tags_for_volume(volume_id, region): 'Return the tags attached to the given EBS volume.' logging.info('Getting tags for volume %s', volume_id) return boto3.client('ec2', region_name=region).describe_volumes(VolumeIds=[volume_id]).get('Volumes')[0].get('Tags')
-1,241,565,648,266,099,700
Return the tags attached to the given EBS volume.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_tags_for_volume
eshpc/aws-parallelcluster
python
def get_tags_for_volume(volume_id, region): logging.info('Getting tags for volume %s', volume_id) return boto3.client('ec2', region_name=region).describe_volumes(VolumeIds=[volume_id]).get('Volumes')[0].get('Tags')
def get_head_node_root_volume_tags(cluster, os): "Return the given cluster's head node's root volume's tags." head_node_instance_id = get_head_node_instance_id(cluster) root_volume_id = get_root_volume_id(head_node_instance_id, cluster.region, os) return get_tags_for_volume(root_volume_id, cluster.regio...
1,240,287,457,644,547,000
Return the given cluster's head node's root volume's tags.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_head_node_root_volume_tags
eshpc/aws-parallelcluster
python
def get_head_node_root_volume_tags(cluster, os): head_node_instance_id = get_head_node_instance_id(cluster) root_volume_id = get_root_volume_id(head_node_instance_id, cluster.region, os) return get_tags_for_volume(root_volume_id, cluster.region)
def get_head_node_tags(cluster): "Return the given cluster's head node's tags." head_node_instance_id = get_head_node_instance_id(cluster) return get_ec2_instance_tags(head_node_instance_id, cluster.region)
-2,295,178,007,714,998,800
Return the given cluster's head node's tags.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_head_node_tags
eshpc/aws-parallelcluster
python
def get_head_node_tags(cluster): head_node_instance_id = get_head_node_instance_id(cluster) return get_ec2_instance_tags(head_node_instance_id, cluster.region)
def get_compute_node_root_volume_tags(cluster, os): "Return the given cluster's compute node's root volume's tags." compute_nodes = cluster.get_cluster_instance_ids(node_type='Compute') assert_that(compute_nodes).is_length(1) root_volume_id = get_root_volume_id(compute_nodes[0], cluster.region, os) ...
-3,110,508,624,131,773,400
Return the given cluster's compute node's root volume's tags.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_compute_node_root_volume_tags
eshpc/aws-parallelcluster
python
def get_compute_node_root_volume_tags(cluster, os): compute_nodes = cluster.get_cluster_instance_ids(node_type='Compute') assert_that(compute_nodes).is_length(1) root_volume_id = get_root_volume_id(compute_nodes[0], cluster.region, os) return get_tags_for_volume(root_volume_id, cluster.region)
def get_compute_node_tags(cluster): "Return the given cluster's compute node's tags." compute_nodes = cluster.get_cluster_instance_ids(node_type='Compute') assert_that(compute_nodes).is_length(1) return get_ec2_instance_tags(compute_nodes[0], cluster.region)
-1,093,552,564,996,228,600
Return the given cluster's compute node's tags.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_compute_node_tags
eshpc/aws-parallelcluster
python
def get_compute_node_tags(cluster): compute_nodes = cluster.get_cluster_instance_ids(node_type='Compute') assert_that(compute_nodes).is_length(1) return get_ec2_instance_tags(compute_nodes[0], cluster.region)
def get_ebs_volume_tags(volume_id, region): 'Return the tags associated with the given EBS volume.' return boto3.client('ec2', region_name=region).describe_volumes(VolumeIds=[volume_id]).get('Volumes')[0].get('Tags')
-2,903,476,295,029,446,000
Return the tags associated with the given EBS volume.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_ebs_volume_tags
eshpc/aws-parallelcluster
python
def get_ebs_volume_tags(volume_id, region): return boto3.client('ec2', region_name=region).describe_volumes(VolumeIds=[volume_id]).get('Volumes')[0].get('Tags')
def get_shared_volume_tags(cluster): "Return the given cluster's EBS volume's tags." shared_volume = cluster.cfn_resources.get('EBS0') return get_ebs_volume_tags(shared_volume, cluster.region)
-29,601,883,307,549,850
Return the given cluster's EBS volume's tags.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_shared_volume_tags
eshpc/aws-parallelcluster
python
def get_shared_volume_tags(cluster): shared_volume = cluster.cfn_resources.get('EBS0') return get_ebs_volume_tags(shared_volume, cluster.region)
def get_pcluster_version(): 'Return the installed version of the pclsuter CLI.' return json.loads(sp.check_output('pcluster version'.split()).decode().strip()).get('version')
-6,709,317,349,835,332,000
Return the installed version of the pclsuter CLI.
tests/integration-tests/tests/tags/test_tag_propagation.py
get_pcluster_version
eshpc/aws-parallelcluster
python
def get_pcluster_version(): return json.loads(sp.check_output('pcluster version'.split()).decode().strip()).get('version')
def make_deterministic(seed=0): "Make results deterministic. If seed == -1, do not make deterministic.\n Running your script in a deterministic way might slow it down.\n Note that for some packages (eg: sklearn's PCA) this function is not enough.\n " seed = int(seed) if (seed == (- 1)): ...
2,571,610,496,660,509,700
Make results deterministic. If seed == -1, do not make deterministic. Running your script in a deterministic way might slow it down. Note that for some packages (eg: sklearn's PCA) this function is not enough.
commons.py
make_deterministic
gmberton/CosPlace
python
def make_deterministic(seed=0): "Make results deterministic. If seed == -1, do not make deterministic.\n Running your script in a deterministic way might slow it down.\n Note that for some packages (eg: sklearn's PCA) this function is not enough.\n " seed = int(seed) if (seed == (- 1)): ...
def setup_logging(output_folder, exist_ok=False, console='debug', info_filename='info.log', debug_filename='debug.log'): 'Set up logging files and console output.\n Creates one file for INFO logs and one for DEBUG logs.\n Args:\n output_folder (str): creates the folder where to save the files.\n ...
3,354,185,008,153,865,000
Set up logging files and console output. Creates one file for INFO logs and one for DEBUG logs. Args: output_folder (str): creates the folder where to save the files. exist_ok (boolean): if False throw a FileExistsError if output_folder already exists debug (str): if == "debug" prints on console deb...
commons.py
setup_logging
gmberton/CosPlace
python
def setup_logging(output_folder, exist_ok=False, console='debug', info_filename='info.log', debug_filename='debug.log'): 'Set up logging files and console output.\n Creates one file for INFO logs and one for DEBUG logs.\n Args:\n output_folder (str): creates the folder where to save the files.\n ...
def donchian(high, low, lower_length=None, upper_length=None, offset=None, **kwargs): 'Indicator: Donchian Channels (DC)' high = verify_series(high) low = verify_series(low) lower_length = (int(lower_length) if (lower_length and (lower_length > 0)) else 20) upper_length = (int(upper_length) if (uppe...
-6,520,702,824,064,578,000
Indicator: Donchian Channels (DC)
pandas_ta/volatility/donchian.py
donchian
MyBourse/pandas-ta
python
def donchian(high, low, lower_length=None, upper_length=None, offset=None, **kwargs): high = verify_series(high) low = verify_series(low) lower_length = (int(lower_length) if (lower_length and (lower_length > 0)) else 20) upper_length = (int(upper_length) if (upper_length and (upper_length > 0)) el...
def as_create_table(self, table_name, overwrite=False): 'Reformats the query into the create table as query.\n\n Works only for the single select SQL statements, in all other cases\n the sql query is not modified.\n :param superset_query: string, sql query that will be executed\n :param ...
5,869,634,862,788,180,000
Reformats the query into the create table as query. Works only for the single select SQL statements, in all other cases the sql query is not modified. :param superset_query: string, sql query that will be executed :param table_name: string, will contain the results of the query execution :param overwrite, boolean,...
superset/sql_parse.py
as_create_table
AmberCa/incubator-superset
python
def as_create_table(self, table_name, overwrite=False): 'Reformats the query into the create table as query.\n\n Works only for the single select SQL statements, in all other cases\n the sql query is not modified.\n :param superset_query: string, sql query that will be executed\n :param ...
def display(request): 'Function view to display form in the standard manner.' if (request.method == 'POST'): form = FiboForm(request.POST) if form.is_valid(): fibo = form.save(commit=False) evensum = fibo.evenFiboSum() fibo.save() return render(req...
4,477,814,417,209,123,300
Function view to display form in the standard manner.
problem2/views.py
display
byteknacker/eulerapps
python
def display(request): if (request.method == 'POST'): form = FiboForm(request.POST) if form.is_valid(): fibo = form.save(commit=False) evensum = fibo.evenFiboSum() fibo.save() return render(request, 'problem2/solution2.html', {'evensum': evensum, '...
@staticmethod def _get_series(i=0): '\n\n :return:\n ' config = configparser.ConfigParser() config.read('config.ini') fourier_folder = config['Folder']['Output'] first_file = os.path.join(fourier_folder, os.listdir(fourier_folder)[i]) with open(first_file, 'r') as b: j = js...
8,986,104,419,332,724,000
:return:
test/test_b_plot.py
_get_series
cperales/Fourier-Clustering-song
python
@staticmethod def _get_series(i=0): '\n\n \n ' config = configparser.ConfigParser() config.read('config.ini') fourier_folder = config['Folder']['Output'] first_file = os.path.join(fourier_folder, os.listdir(fourier_folder)[i]) with open(first_file, 'r') as b: j = json.load(...
@staticmethod def _get_song(i=0): '\n\n :return:\n ' config = configparser.ConfigParser() config.read('config.ini') song_folder = config['Folder']['Temp'] first_song = os.listdir(song_folder)[i] (rate, aud_data) = read(os.path.join(song_folder, first_song)) if (len(aud_data) !=...
-8,418,300,708,451,570,000
:return:
test/test_b_plot.py
_get_song
cperales/Fourier-Clustering-song
python
@staticmethod def _get_song(i=0): '\n\n \n ' config = configparser.ConfigParser() config.read('config.ini') song_folder = config['Folder']['Temp'] first_song = os.listdir(song_folder)[i] (rate, aud_data) = read(os.path.join(song_folder, first_song)) if (len(aud_data) != len(aud...
def test_diff(self): '\n\n :return:\n ' config = configparser.ConfigParser() config.read('config.ini') image_folder = config['Folder']['Image'] (song_1, name_1) = self._get_series(i=0) (song_2, name_2) = self._get_series(i=1) diff_plot(song_1, song_2, filename=(name_1.split()[2...
1,652,916,689,913,852,700
:return:
test/test_b_plot.py
test_diff
cperales/Fourier-Clustering-song
python
def test_diff(self): '\n\n \n ' config = configparser.ConfigParser() config.read('config.ini') image_folder = config['Folder']['Image'] (song_1, name_1) = self._get_series(i=0) (song_2, name_2) = self._get_series(i=1) diff_plot(song_1, song_2, filename=(name_1.split()[2].split(...
def test_song(self): '\n\n :return:\n ' config = configparser.ConfigParser() config.read('config.ini') image_folder = config['Folder']['Image'] (aud_data, name) = self._get_song() song_plot(aud_data, filename=name.split('.')[0], folder=image_folder)
-8,779,366,337,030,944,000
:return:
test/test_b_plot.py
test_song
cperales/Fourier-Clustering-song
python
def test_song(self): '\n\n \n ' config = configparser.ConfigParser() config.read('config.ini') image_folder = config['Folder']['Image'] (aud_data, name) = self._get_song() song_plot(aud_data, filename=name.split('.')[0], folder=image_folder)
@staticmethod def get_supported_channels() -> list: 'List of supported channels.' return list(ChannelMap.channel_map.keys())
313,114,182,041,640,400
List of supported channels.
scripts/channel_map.py
get_supported_channels
artelk/performance
python
@staticmethod def get_supported_channels() -> list: return list(ChannelMap.channel_map.keys())
@staticmethod def get_supported_frameworks() -> list: 'List of supported frameworks' frameworks = [ChannelMap.channel_map[channel]['tfm'] for channel in ChannelMap.channel_map] return set(frameworks)
4,910,586,788,561,729,000
List of supported frameworks
scripts/channel_map.py
get_supported_frameworks
artelk/performance
python
@staticmethod def get_supported_frameworks() -> list: frameworks = [ChannelMap.channel_map[channel]['tfm'] for channel in ChannelMap.channel_map] return set(frameworks)
@staticmethod def get_target_framework_monikers(channels: list) -> list: '\n Translates channel names to Target Framework Monikers (TFMs).\n ' monikers = [ChannelMap.get_target_framework_moniker(channel) for channel in channels] return list(set(monikers))
-8,264,586,632,849,845,000
Translates channel names to Target Framework Monikers (TFMs).
scripts/channel_map.py
get_target_framework_monikers
artelk/performance
python
@staticmethod def get_target_framework_monikers(channels: list) -> list: '\n \n ' monikers = [ChannelMap.get_target_framework_moniker(channel) for channel in channels] return list(set(monikers))
@staticmethod def get_target_framework_moniker(channel: str) -> str: '\n Translate channel name to Target Framework Moniker (TFM)\n ' if (channel in ChannelMap.channel_map): return ChannelMap.channel_map[channel]['tfm'] else: raise Exception(('Channel %s is not supported. Suppo...
9,109,701,814,379,510,000
Translate channel name to Target Framework Moniker (TFM)
scripts/channel_map.py
get_target_framework_moniker
artelk/performance
python
@staticmethod def get_target_framework_moniker(channel: str) -> str: '\n \n ' if (channel in ChannelMap.channel_map): return ChannelMap.channel_map[channel]['tfm'] else: raise Exception(('Channel %s is not supported. Supported channels %s' % (channel, ChannelMap.get_supported_c...
@staticmethod def get_channel_from_target_framework_moniker(target_framework_moniker: str) -> str: 'Translate Target Framework Moniker (TFM) to channel name' for channel in ChannelMap.channel_map: if (ChannelMap.channel_map[channel]['tfm'] == target_framework_moniker): return channel rai...
6,853,412,562,388,000,000
Translate Target Framework Moniker (TFM) to channel name
scripts/channel_map.py
get_channel_from_target_framework_moniker
artelk/performance
python
@staticmethod def get_channel_from_target_framework_moniker(target_framework_moniker: str) -> str: for channel in ChannelMap.channel_map: if (ChannelMap.channel_map[channel]['tfm'] == target_framework_moniker): return channel raise Exception(('Framework %s is not supported. Supported fr...
def normalize_imagenet(x): ' Normalize input images according to ImageNet standards.\n Args:\n x (tensor): input images\n ' x = x.clone() x[:, 0] = ((x[:, 0] - 0.485) / 0.229) x[:, 1] = ((x[:, 1] - 0.456) / 0.224) x[:, 2] = ((x[:, 2] - 0.406) / 0.225) return x
-5,227,346,449,647,160,000
Normalize input images according to ImageNet standards. Args: x (tensor): input images
examples/ImageRecon/OccNet/architectures.py
normalize_imagenet
AOE-khkhan/kaolin
python
def normalize_imagenet(x): ' Normalize input images according to ImageNet standards.\n Args:\n x (tensor): input images\n ' x = x.clone() x[:, 0] = ((x[:, 0] - 0.485) / 0.229) x[:, 1] = ((x[:, 1] - 0.456) / 0.224) x[:, 2] = ((x[:, 2] - 0.406) / 0.225) return x
def get_prior_z(device): ' Returns prior distribution for latent code z.\n Args:\n cfg (dict): imported yaml config\n device (device): pytorch device\n ' z_dim = 0 p0_z = dist.Normal(torch.zeros(z_dim, device=device), torch.ones(z_dim, device=device)) return p0_z
8,228,995,010,554,023,000
Returns prior distribution for latent code z. Args: cfg (dict): imported yaml config device (device): pytorch device
examples/ImageRecon/OccNet/architectures.py
get_prior_z
AOE-khkhan/kaolin
python
def get_prior_z(device): ' Returns prior distribution for latent code z.\n Args:\n cfg (dict): imported yaml config\n device (device): pytorch device\n ' z_dim = 0 p0_z = dist.Normal(torch.zeros(z_dim, device=device), torch.ones(z_dim, device=device)) return p0_z
def forward(self, p, inputs, sample=True, **kwargs): ' Performs a forward pass through the network.\n Args:\n p (tensor): sampled points\n inputs (tensor): conditioning input\n sample (bool): whether to sample for z\n ' batch_size = p.size(0) c = self.encode_in...
-8,092,593,553,562,814,000
Performs a forward pass through the network. Args: p (tensor): sampled points inputs (tensor): conditioning input sample (bool): whether to sample for z
examples/ImageRecon/OccNet/architectures.py
forward
AOE-khkhan/kaolin
python
def forward(self, p, inputs, sample=True, **kwargs): ' Performs a forward pass through the network.\n Args:\n p (tensor): sampled points\n inputs (tensor): conditioning input\n sample (bool): whether to sample for z\n ' batch_size = p.size(0) c = self.encode_in...
def compute_elbo(self, p, occ, inputs, **kwargs): ' Computes the expectation lower bound.\n Args:\n p (tensor): sampled points\n occ (tensor): occupancy values for p\n inputs (tensor): conditioning input\n ' c = self.encode_inputs(inputs) q_z = self.infer_z(p, ...
-2,864,902,931,423,070,000
Computes the expectation lower bound. Args: p (tensor): sampled points occ (tensor): occupancy values for p inputs (tensor): conditioning input
examples/ImageRecon/OccNet/architectures.py
compute_elbo
AOE-khkhan/kaolin
python
def compute_elbo(self, p, occ, inputs, **kwargs): ' Computes the expectation lower bound.\n Args:\n p (tensor): sampled points\n occ (tensor): occupancy values for p\n inputs (tensor): conditioning input\n ' c = self.encode_inputs(inputs) q_z = self.infer_z(p, ...
def encode_inputs(self, inputs): ' Encodes the input.\n Args:\n input (tensor): the input\n ' c = self.encoder(inputs) return c
5,463,329,561,843,520,000
Encodes the input. Args: input (tensor): the input
examples/ImageRecon/OccNet/architectures.py
encode_inputs
AOE-khkhan/kaolin
python
def encode_inputs(self, inputs): ' Encodes the input.\n Args:\n input (tensor): the input\n ' c = self.encoder(inputs) return c
def decode(self, p, z, c, **kwargs): ' Returns occupancy probabilities for the sampled points.\n Args:\n p (tensor): points\n z (tensor): latent code z\n c (tensor): latent conditioned code c\n ' logits = self.decoder(p, z, c, **kwargs) p_r = dist.Bernoulli(log...
-400,121,044,428,680,000
Returns occupancy probabilities for the sampled points. Args: p (tensor): points z (tensor): latent code z c (tensor): latent conditioned code c
examples/ImageRecon/OccNet/architectures.py
decode
AOE-khkhan/kaolin
python
def decode(self, p, z, c, **kwargs): ' Returns occupancy probabilities for the sampled points.\n Args:\n p (tensor): points\n z (tensor): latent code z\n c (tensor): latent conditioned code c\n ' logits = self.decoder(p, z, c, **kwargs) p_r = dist.Bernoulli(log...
def infer_z(self, p, occ, c, **kwargs): ' Infers z.\n Args:\n p (tensor): points tensor\n occ (tensor): occupancy values for occ\n c (tensor): latent conditioned code c\n ' batch_size = p.size(0) mean_z = torch.empty(batch_size, 0).to(self.device) logstd_z ...
6,820,978,492,670,022,000
Infers z. Args: p (tensor): points tensor occ (tensor): occupancy values for occ c (tensor): latent conditioned code c
examples/ImageRecon/OccNet/architectures.py
infer_z
AOE-khkhan/kaolin
python
def infer_z(self, p, occ, c, **kwargs): ' Infers z.\n Args:\n p (tensor): points tensor\n occ (tensor): occupancy values for occ\n c (tensor): latent conditioned code c\n ' batch_size = p.size(0) mean_z = torch.empty(batch_size, 0).to(self.device) logstd_z ...
def get_z_from_prior(self, size=torch.Size([]), sample=True): ' Returns z from prior distribution.\n Args:\n size (Size): size of z\n sample (bool): whether to sample\n ' if sample: z = self.p0_z.sample(size).to(self.device) else: z = self.p0_z.mean.to(sel...
-7,939,061,773,836,317,000
Returns z from prior distribution. Args: size (Size): size of z sample (bool): whether to sample
examples/ImageRecon/OccNet/architectures.py
get_z_from_prior
AOE-khkhan/kaolin
python
def get_z_from_prior(self, size=torch.Size([]), sample=True): ' Returns z from prior distribution.\n Args:\n size (Size): size of z\n sample (bool): whether to sample\n ' if sample: z = self.p0_z.sample(size).to(self.device) else: z = self.p0_z.mean.to(sel...
def register(self, model, model_admin=None, **kwargs): '\n Registers the given model with the given admin class. Once a model is\n registered in self.registry, we also add it to app registries in\n self.apps.\n\n If no model_admin is passed, it will use ModelAdmin2. If keyword\n a...
1,695,026,397,503,695,600
Registers the given model with the given admin class. Once a model is registered in self.registry, we also add it to app registries in self.apps. If no model_admin is passed, it will use ModelAdmin2. If keyword arguments are given they will be passed to the admin class on instantiation. If a model is already register...
djadmin2/core.py
register
PowerOlive/django-admin2
python
def register(self, model, model_admin=None, **kwargs): '\n Registers the given model with the given admin class. Once a model is\n registered in self.registry, we also add it to app registries in\n self.apps.\n\n If no model_admin is passed, it will use ModelAdmin2. If keyword\n a...
def deregister(self, model): '\n Deregisters the given model. Remove the model from the self.app as well\n\n If the model is not already registered, this will raise\n ImproperlyConfigured.\n ' try: del self.registry[model] except KeyError: raise ImproperlyConfigur...
-226,734,680,756,163,400
Deregisters the given model. Remove the model from the self.app as well If the model is not already registered, this will raise ImproperlyConfigured.
djadmin2/core.py
deregister
PowerOlive/django-admin2
python
def deregister(self, model): '\n Deregisters the given model. Remove the model from the self.app as well\n\n If the model is not already registered, this will raise\n ImproperlyConfigured.\n ' try: del self.registry[model] except KeyError: raise ImproperlyConfigur...
def register_app_verbose_name(self, app_label, app_verbose_name): '\n Registers the given app label with the given app verbose name.\n\n If a app_label is already registered, this will raise\n ImproperlyConfigured.\n ' if (app_label in self.app_verbose_names): raise Improperl...
8,412,480,849,148,175,000
Registers the given app label with the given app verbose name. If a app_label is already registered, this will raise ImproperlyConfigured.
djadmin2/core.py
register_app_verbose_name
PowerOlive/django-admin2
python
def register_app_verbose_name(self, app_label, app_verbose_name): '\n Registers the given app label with the given app verbose name.\n\n If a app_label is already registered, this will raise\n ImproperlyConfigured.\n ' if (app_label in self.app_verbose_names): raise Improperl...
def deregister_app_verbose_name(self, app_label): '\n Deregisters the given app label. Remove the app label from the\n self.app_verbose_names as well.\n\n If the app label is not already registered, this will raise\n ImproperlyConfigured.\n ' try: del self.app_verbose_...
-2,633,586,113,666,253,300
Deregisters the given app label. Remove the app label from the self.app_verbose_names as well. If the app label is not already registered, this will raise ImproperlyConfigured.
djadmin2/core.py
deregister_app_verbose_name
PowerOlive/django-admin2
python
def deregister_app_verbose_name(self, app_label): '\n Deregisters the given app label. Remove the app label from the\n self.app_verbose_names as well.\n\n If the app label is not already registered, this will raise\n ImproperlyConfigured.\n ' try: del self.app_verbose_...
def autodiscover(self): '\n Autodiscovers all admin2.py modules for apps in INSTALLED_APPS by\n trying to import them.\n ' for app_name in [x for x in settings.INSTALLED_APPS]: try: import_module(('%s.admin2' % app_name)) except ImportError as e: if (...
4,519,707,043,250,492,400
Autodiscovers all admin2.py modules for apps in INSTALLED_APPS by trying to import them.
djadmin2/core.py
autodiscover
PowerOlive/django-admin2
python
def autodiscover(self): '\n Autodiscovers all admin2.py modules for apps in INSTALLED_APPS by\n trying to import them.\n ' for app_name in [x for x in settings.INSTALLED_APPS]: try: import_module(('%s.admin2' % app_name)) except ImportError as e: if (...
def get_admin_by_name(self, name): '\n Returns the admin instance that was registered with the passed in\n name.\n ' for object_admin in self.registry.values(): if (object_admin.name == name): return object_admin raise ValueError(u'No object admin found with name {}'...
1,111,493,410,733,876,500
Returns the admin instance that was registered with the passed in name.
djadmin2/core.py
get_admin_by_name
PowerOlive/django-admin2
python
def get_admin_by_name(self, name): '\n Returns the admin instance that was registered with the passed in\n name.\n ' for object_admin in self.registry.values(): if (object_admin.name == name): return object_admin raise ValueError(u'No object admin found with name {}'...
def save(query: List[str], save_path: str, downloader, m3u_file: Optional[str]=None) -> None: '\n Save metadata from spotify to the disk.\n\n ### Arguments\n - query: list of strings to search for.\n - save_path: Path to the file to save the metadata to.\n - threads: Number of threads to use.\n\n ...
1,037,826,605,912,516,600
Save metadata from spotify to the disk. ### Arguments - query: list of strings to search for. - save_path: Path to the file to save the metadata to. - threads: Number of threads to use. ### Notes - This function is multi-threaded.
spotdl/console/save.py
save
phcreery/spotdl-v4
python
def save(query: List[str], save_path: str, downloader, m3u_file: Optional[str]=None) -> None: '\n Save metadata from spotify to the disk.\n\n ### Arguments\n - query: list of strings to search for.\n - save_path: Path to the file to save the metadata to.\n - threads: Number of threads to use.\n\n ...
def get_arguments(): 'Parse all the arguments provided from the CLI.\n\n Returns:\n A list of parsed arguments.\n ' parser = argparse.ArgumentParser(description='DeepLab-ResNet Network') parser.add_argument('--model', type=str, default=MODEL, help='Model Choice (DeeplabMulti/DeeplabVGG/Oracle).')...
-3,601,046,404,071,038,000
Parse all the arguments provided from the CLI. Returns: A list of parsed arguments.
generate_plabel_dark_zurich.py
get_arguments
qimw/UACDA
python
def get_arguments(): 'Parse all the arguments provided from the CLI.\n\n Returns:\n A list of parsed arguments.\n ' parser = argparse.ArgumentParser(description='DeepLab-ResNet Network') parser.add_argument('--model', type=str, default=MODEL, help='Model Choice (DeeplabMulti/DeeplabVGG/Oracle).')...
def main(): 'Create the model and start the evaluation process.' args = get_arguments() (w, h) = map(int, args.input_size.split(',')) config_path = os.path.join(os.path.dirname(args.restore_from), 'opts.yaml') with open(config_path, 'r') as stream: config = yaml.load(stream) args.model =...
-2,165,387,849,207,418,400
Create the model and start the evaluation process.
generate_plabel_dark_zurich.py
main
qimw/UACDA
python
def main(): args = get_arguments() (w, h) = map(int, args.input_size.split(',')) config_path = os.path.join(os.path.dirname(args.restore_from), 'opts.yaml') with open(config_path, 'r') as stream: config = yaml.load(stream) args.model = config['model'] print(('ModelType:%s' % args.mo...
def __init__(self, runscontainer, marginal_threshold=0.05): 'Wrapper for parameter_importance to save the importance-object/ extract the results. We want to show the\n top X most important parameter-fanova-plots.\n\n Parameters\n ----------\n runscontainer: RunsContainer\n con...
-2,845,748,282,511,785,500
Wrapper for parameter_importance to save the importance-object/ extract the results. We want to show the top X most important parameter-fanova-plots. Parameters ---------- runscontainer: RunsContainer contains all important information about the configurator runs marginal_threshold: float parameter/s must be a...
cave/analyzer/parameter_importance/fanova.py
__init__
automl/CAVE
python
def __init__(self, runscontainer, marginal_threshold=0.05): 'Wrapper for parameter_importance to save the importance-object/ extract the results. We want to show the\n top X most important parameter-fanova-plots.\n\n Parameters\n ----------\n runscontainer: RunsContainer\n con...
def parse_pairwise(p): "parse pimp's way of having pairwise parameters as key as str and return list of individuals" res = [tmp.strip("' ") for tmp in p.strip('[]').split(',')] return res
8,489,956,221,889,464,000
parse pimp's way of having pairwise parameters as key as str and return list of individuals
cave/analyzer/parameter_importance/fanova.py
parse_pairwise
automl/CAVE
python
def parse_pairwise(p): res = [tmp.strip("' ") for tmp in p.strip('[]').split(',')] return res
def test_create_failure_recovery(self): 'Check that rollback still works with dynamic metadata.\n\n This test fails the second instance.\n ' tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'AResource': {'Type': 'OverwrittenFnGetRefIdType', 'Properties': {'Foo': 'abc'}}, 'BResource...
8,971,451,799,159,772,000
Check that rollback still works with dynamic metadata. This test fails the second instance.
heat/tests/test_stack.py
test_create_failure_recovery
openstack/heat
python
def test_create_failure_recovery(self): 'Check that rollback still works with dynamic metadata.\n\n This test fails the second instance.\n ' tmpl = {'HeatTemplateFormatVersion': '2012-12-12', 'Resources': {'AResource': {'Type': 'OverwrittenFnGetRefIdType', 'Properties': {'Foo': 'abc'}}, 'BResource...
def test_store_saves_owner(self): 'owner_id attribute of Store is saved to the database when stored.' self.stack = stack.Stack(self.ctx, 'owner_stack', self.tmpl) stack_ownee = stack.Stack(self.ctx, 'ownee_stack', self.tmpl, owner_id=self.stack.id) stack_ownee.store() db_stack = stack_object.Stack.g...
-2,445,248,347,015,333,400
owner_id attribute of Store is saved to the database when stored.
heat/tests/test_stack.py
test_store_saves_owner
openstack/heat
python
def test_store_saves_owner(self): self.stack = stack.Stack(self.ctx, 'owner_stack', self.tmpl) stack_ownee = stack.Stack(self.ctx, 'ownee_stack', self.tmpl, owner_id=self.stack.id) stack_ownee.store() db_stack = stack_object.Stack.get_by_id(self.ctx, stack_ownee.id) self.assertEqual(self.stack....
def test_store_saves_creds(self): 'A user_creds entry is created on first stack store.' cfg.CONF.set_default('deferred_auth_method', 'password') self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl) self.stack.store() db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id) user_c...
-9,213,545,049,745,668,000
A user_creds entry is created on first stack store.
heat/tests/test_stack.py
test_store_saves_creds
openstack/heat
python
def test_store_saves_creds(self): cfg.CONF.set_default('deferred_auth_method', 'password') self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl) self.stack.store() db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id) user_creds_id = db_stack.user_creds_id self.assertIsNot...
def test_store_saves_creds_trust(self): 'A user_creds entry is created on first stack store.' cfg.CONF.set_override('deferred_auth_method', 'trusts') self.patchobject(keystone.KeystoneClientPlugin, '_create', return_value=fake_ks.FakeKeystoneClient(user_id='auser123')) self.stack = stack.Stack(self.ctx,...
-2,844,117,463,037,988,400
A user_creds entry is created on first stack store.
heat/tests/test_stack.py
test_store_saves_creds_trust
openstack/heat
python
def test_store_saves_creds_trust(self): cfg.CONF.set_override('deferred_auth_method', 'trusts') self.patchobject(keystone.KeystoneClientPlugin, '_create', return_value=fake_ks.FakeKeystoneClient(user_id='auser123')) self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl) self.stack.store() ...
def test_stored_context_err(self): 'Test stored_context error path.' self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl) ex = self.assertRaises(exception.Error, self.stack.stored_context) expected_err = 'Attempt to use stored_context with no user_creds' self.assertEqual(expected_err, str(ex...
4,702,206,411,824,754,000
Test stored_context error path.
heat/tests/test_stack.py
test_stored_context_err
openstack/heat
python
def test_stored_context_err(self): self.stack = stack.Stack(self.ctx, 'creds_stack', self.tmpl) ex = self.assertRaises(exception.Error, self.stack.stored_context) expected_err = 'Attempt to use stored_context with no user_creds' self.assertEqual(expected_err, str(ex))
def test_load_honors_owner(self): 'Loading a stack from the database will set the owner_id.\n\n Loading a stack from the database will set the owner_id of the\n resultant stack appropriately.\n ' self.stack = stack.Stack(self.ctx, 'owner_stack', self.tmpl) stack_ownee = stack.Stack(self...
7,915,637,699,835,126,000
Loading a stack from the database will set the owner_id. Loading a stack from the database will set the owner_id of the resultant stack appropriately.
heat/tests/test_stack.py
test_load_honors_owner
openstack/heat
python
def test_load_honors_owner(self): 'Loading a stack from the database will set the owner_id.\n\n Loading a stack from the database will set the owner_id of the\n resultant stack appropriately.\n ' self.stack = stack.Stack(self.ctx, 'owner_stack', self.tmpl) stack_ownee = stack.Stack(self...
def test_stack_load_no_param_value_validation(self): 'Test stack loading with disabled parameter value validation.' tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n flavor:\n type: string\n description: A flavor.\n ...
3,320,778,543,385,687,000
Test stack loading with disabled parameter value validation.
heat/tests/test_stack.py
test_stack_load_no_param_value_validation
openstack/heat
python
def test_stack_load_no_param_value_validation(self): tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n flavor:\n type: string\n description: A flavor.\n constraints:\n - custom_constraint: ...
def test_encrypt_parameters_false_parameters_stored_plaintext(self): 'Test stack loading with disabled parameter value validation.' tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: valu...
1,876,205,515,915,799,000
Test stack loading with disabled parameter value validation.
heat/tests/test_stack.py
test_encrypt_parameters_false_parameters_stored_plaintext
openstack/heat
python
def test_encrypt_parameters_false_parameters_stored_plaintext(self): tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: value1.\n param2:\n type: string\n ...
def test_parameters_stored_encrypted_decrypted_on_load(self): 'Test stack loading with disabled parameter value validation.' tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: value1.\n ...
-1,018,863,454,073,504,000
Test stack loading with disabled parameter value validation.
heat/tests/test_stack.py
test_parameters_stored_encrypted_decrypted_on_load
openstack/heat
python
def test_parameters_stored_encrypted_decrypted_on_load(self): tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: value1.\n param2:\n type: string\n ...
def test_parameters_created_encrypted_updated_decrypted(self): 'Test stack loading with disabled parameter value validation.' tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: value1.\n ...
-1,445,745,818,561,343,700
Test stack loading with disabled parameter value validation.
heat/tests/test_stack.py
test_parameters_created_encrypted_updated_decrypted
openstack/heat
python
def test_parameters_created_encrypted_updated_decrypted(self): tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: value1.\n param2:\n type: string\n ...
def test_parameters_stored_decrypted_successful_load(self): 'Test stack loading with disabled parameter value validation.' tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: value1.\n ...
8,764,875,422,488,754,000
Test stack loading with disabled parameter value validation.
heat/tests/test_stack.py
test_parameters_stored_decrypted_successful_load
openstack/heat
python
def test_parameters_stored_decrypted_successful_load(self): tmpl = template_format.parse('\n heat_template_version: 2013-05-23\n parameters:\n param1:\n type: string\n description: value1.\n param2:\n type: string\n ...
def serve_paste(app, global_conf, **kw): 'pserve / paster serve / waitress replacement / integration\n\n You can pass as parameters:\n\n transports = websockets, xhr-multipart, xhr-longpolling, etc...\n policy_server = True\n ' serve(app, **kw) return 0
-5,353,821,925,766,461,000
pserve / paster serve / waitress replacement / integration You can pass as parameters: transports = websockets, xhr-multipart, xhr-longpolling, etc... policy_server = True
socketio/server.py
serve_paste
jykim16/gevent-socketio
python
def serve_paste(app, global_conf, **kw): 'pserve / paster serve / waitress replacement / integration\n\n You can pass as parameters:\n\n transports = websockets, xhr-multipart, xhr-longpolling, etc...\n policy_server = True\n ' serve(app, **kw) return 0
def __init__(self, *args, **kwargs): 'This is just like the standard WSGIServer __init__, except with a\n few additional ``kwargs``:\n\n :param resource: The URL which has to be identified as a\n socket.io request. Defaults to the /socket.io/ URL.\n\n :param transports: Optional lis...
2,082,469,375,877,520,000
This is just like the standard WSGIServer __init__, except with a few additional ``kwargs``: :param resource: The URL which has to be identified as a socket.io request. Defaults to the /socket.io/ URL. :param transports: Optional list of transports to allow. List of strings, each string should be one of ...
socketio/server.py
__init__
jykim16/gevent-socketio
python
def __init__(self, *args, **kwargs): 'This is just like the standard WSGIServer __init__, except with a\n few additional ``kwargs``:\n\n :param resource: The URL which has to be identified as a\n socket.io request. Defaults to the /socket.io/ URL.\n\n :param transports: Optional lis...
def get_socket(self, sessid=''): 'Return an existing or new client Socket.' socket = self.sockets.get(sessid) if (sessid and (not socket)): return None if (socket is None): socket = Socket(self, self.config) self.sockets[socket.sessid] = socket else: socket.incr_hits(...
537,170,999,850,106,900
Return an existing or new client Socket.
socketio/server.py
get_socket
jykim16/gevent-socketio
python
def get_socket(self, sessid=): socket = self.sockets.get(sessid) if (sessid and (not socket)): return None if (socket is None): socket = Socket(self, self.config) self.sockets[socket.sessid] = socket else: socket.incr_hits() return socket