uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
edc057eec9e1933bb1d3777f | train | function | def clean_up_empty_output_blocks(input_blocks, output_blocks):
'''Some of the blocks do not generate output. We only want to have
input blocks that have outputs
'''
new_input_blocks = []
new_output_blocks = []
current_in_block = ''
for in_block, out_block in zip(input_blocks, output... | def clean_up_empty_output_blocks(input_blocks, output_blocks):
| '''Some of the blocks do not generate output. We only want to have
input blocks that have outputs
'''
new_input_blocks = []
new_output_blocks = []
current_in_block = ''
for in_block, out_block in zip(input_blocks, output_blocks):
if current_in_block and not current_in_block.... | _stop_indicators.append('print(">>>>>{}")\n'.format(input_block_number))
else:
src_with_out_start_stop_indicators.append(line)
input_block_number += 1
return ''.join(src_with_out_start_stop_indicators)
def clean_up_empty_output_blocks(input_blocks, output_blocks):
| 64 | 64 | 179 | 12 | 52 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | clean_up_empty_output_blocks | clean_up_empty_output_blocks | 510 | 532 | 510 | 510 | 11edb6034cbb2ccc8d6ed2877fcad4ca752753f7 | bigcode/the-stack | train |
1eff8ad05ccef3a655ad6696 | train | function | def get_method_body(method_code):
'''Using the RedBaron module, get the body of a method.
Do not want the definition signature line
'''
method_code = '\n' + method_code # For some reason RedBaron has problems with this if
# if it does not start ... | def get_method_body(method_code):
| '''Using the RedBaron module, get the body of a method.
Do not want the definition signature line
'''
method_code = '\n' + method_code # For some reason RedBaron has problems with this if
# if it does not start with an empty line
rb = RedBar... | _node(assert_node.value[1], -1) # remove the expected value
assert_node.value[0].replace("print")
source_code_with_prints = rb.dumps() # get back the string representation of the code
return source_code_with_prints
def get_method_body(method_code):
| 64 | 64 | 140 | 7 | 56 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | get_method_body | get_method_body | 139 | 150 | 139 | 139 | 9602a393bfe799feba7f61a8baaef341a2f9a333 | bigcode/the-stack | train |
a00d0c83c9ec3ffb3a4158ea | train | function | def split_source_into_input_blocks(src):
'''
'''
rb = RedBaron(src)
in_code_blocks = []
in_code_block = []
# group code until the first print, then repeat
for r in rb:
line = r.dumps()
if not line.endswith('\n'):
line += '\n'
in_code_block.append(line)
... | def split_source_into_input_blocks(src):
| '''
'''
rb = RedBaron(src)
in_code_blocks = []
in_code_block = []
# group code until the first print, then repeat
for r in rb:
line = r.dumps()
if not line.endswith('\n'):
line += '\n'
in_code_block.append(line)
if r.type == 'print' or \
... | _lines = []
for i, l in enumerate( lines ):
if l and not l.isspace():
non_whitespace_lines.append(i)
imin = min(non_whitespace_lines)
imax = max(non_whitespace_lines)
return '\n'.join(lines[imin: imax+1])
def split_source_into_input_blocks(src):
| 73 | 73 | 246 | 8 | 65 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | split_source_into_input_blocks | split_source_into_input_blocks | 454 | 480 | 454 | 454 | db7297859f6225d46eb4089087ba43fa807f8787 | bigcode/the-stack | train |
f020dfdb7a6d3506aa4d9cda | train | function | def get_skip_predicate_and_message(source, method_name):
'''
Look to see if the method has a unittest.skipUnless or unittest.skip
decorator.
If it has a unittest.skipUnless decorator, return the predicate and the message
If it has a unittest.skip decorator, return just the message ( set predicate t... | def get_skip_predicate_and_message(source, method_name):
| '''
Look to see if the method has a unittest.skipUnless or unittest.skip
decorator.
If it has a unittest.skipUnless decorator, return the predicate and the message
If it has a unittest.skip decorator, return just the message ( set predicate to None )
'''
rb = RedBaron(source)
def_nodes... | this feature name
for title, unit_test_source, run_outputs in all_rows:
# add to the list that will be returned
test_source_code_for_feature.append((title, unit_test_source, run_outputs))
return test_source_code_for_feature
def get_skip_predicate_and_message(source, method_name):
| 66 | 66 | 222 | 12 | 53 | hwangjt/blue | openmdao/docs/_utils/docutil.py | Python | get_skip_predicate_and_message | get_skip_predicate_and_message | 281 | 299 | 281 | 281 | 1567dfcf2f024c3c90bf30424bc8a4516452517e | bigcode/the-stack | train |
92f5386166e9e863950c62b9 | train | class | class Entry(models.Model):
STATUS_DRAFT = "draft"
STATUS_PUBLIC = "public"
STATUS_CLOSE = "close"
STATUS_BOT = "machine"
STATUS_SET = (
(STATUS_DRAFT, "下書き"),
(STATUS_PUBLIC, "公開中"),
(STATUS_CLOSE, '非公開'),
(STATUS_BOT, 'BOT')
)
status = models.CharField(
... | class Entry(models.Model):
| STATUS_DRAFT = "draft"
STATUS_PUBLIC = "public"
STATUS_CLOSE = "close"
STATUS_BOT = "machine"
STATUS_SET = (
(STATUS_DRAFT, "下書き"),
(STATUS_PUBLIC, "公開中"),
(STATUS_CLOSE, '非公開'),
(STATUS_BOT, 'BOT')
)
status = models.CharField(
choices=STATUS_SET, def... | "{}".format(self.user.username)
__str__ = __repr__
class Follow(models.Model):
follow_user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='follow_user')
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='user')
class Entry(models.Model):
| 68 | 68 | 227 | 5 | 63 | T-8723/copytter | app/api/copytter/models.py | Python | Entry | Entry | 76 | 103 | 76 | 76 | 45d1c9e0ccd6f553bcf551ad87feb3193c2c2267 | bigcode/the-stack | train |
d24c7023c94dead981ed6560 | train | function | @receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
| @receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
| if created:
Profile.objects.create(user=instance)
| .dispatch import receiver
def randomname(n):
randlst = [
random.choice(
string.ascii_letters +
string.digits) for i in range(n)]
return ''.join(randlst)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
| 64 | 64 | 34 | 22 | 42 | T-8723/copytter | app/api/copytter/models.py | Python | create_user_profile | create_user_profile | 17 | 20 | 17 | 18 | 9031d03a3ae0593eea4fb43b7a6855c862a7fb4c | bigcode/the-stack | train |
f806279fe70cecba9bbcb9a8 | train | function | def randomname(n):
randlst = [
random.choice(
string.ascii_letters +
string.digits) for i in range(n)]
return ''.join(randlst)
| def randomname(n):
| randlst = [
random.choice(
string.ascii_letters +
string.digits) for i in range(n)]
return ''.join(randlst)
| import random
import string
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
def randomname(n):
| 41 | 64 | 38 | 5 | 35 | T-8723/copytter | app/api/copytter/models.py | Python | randomname | randomname | 9 | 14 | 9 | 9 | 45cc61eb8db32a45aa59faa7c672438012e63361 | bigcode/the-stack | train |
440975210d7431c06c559d96 | train | class | class Media(models.Model):
media_type = models.CharField(max_length=8)
media_url = models.URLField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
| class Media(models.Model):
| media_type = models.CharField(max_length=8)
media_url = models.URLField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
| (default=0)
relation_id = models.CharField(max_length=8, blank=True)
updated_at = models.DateTimeField(auto_now=True)
def __repr__(self):
return "{}: {}".format(self.author, self.id)
__str__ = __repr__
class Media(models.Model):
| 63 | 64 | 38 | 5 | 58 | T-8723/copytter | app/api/copytter/models.py | Python | Media | Media | 106 | 109 | 106 | 106 | 8538382ad4e47b1a51a2487ed0f3b874fc9314ac | bigcode/the-stack | train |
85f15cc26e9e55e87ef41710 | train | function | @receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
| @receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
| instance.profile.save()
| range(n)]
return ''.join(randlst)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
| 64 | 64 | 25 | 20 | 44 | T-8723/copytter | app/api/copytter/models.py | Python | save_user_profile | save_user_profile | 23 | 25 | 23 | 24 | 1d02526165f072c391ea246edfbfb43f2c12fb93 | bigcode/the-stack | train |
d91d1cd66d2885e3bb5d5abd | train | class | class Follow(models.Model):
follow_user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='follow_user')
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='user')
| class Follow(models.Model):
| follow_user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='follow_user')
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='user')
| =300, blank=True)
sensitive_entry = models.BooleanField(default=False)
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True)
def __repr__(self):
return "{}".format(self.user.username)
__str__ = __repr__
class Follow(models.Model):
| 63 | 64 | 47 | 5 | 58 | T-8723/copytter | app/api/copytter/models.py | Python | Follow | Follow | 69 | 73 | 69 | 69 | ed6fd6f7bd844c205c007c7b69b3121f59fa582c | bigcode/the-stack | train |
141a6213760003f1de5400b3 | train | class | class Profile(models.Model):
STATUS_OFFICAL = "official"
STATUS_PUBLIC = "public"
STATUS_CLOSE = "close"
STATUS_BOT = "machine"
STATUS_BLOCK = "block"
ACCOUNTS_STATUS = {
(STATUS_OFFICAL, '公式'),
(STATUS_PUBLIC, '一般'),
(STATUS_CLOSE, '非公開'),
(STATUS_BOT, 'BOT'),
... | class Profile(models.Model):
| STATUS_OFFICAL = "official"
STATUS_PUBLIC = "public"
STATUS_CLOSE = "close"
STATUS_BOT = "machine"
STATUS_BLOCK = "block"
ACCOUNTS_STATUS = {
(STATUS_OFFICAL, '公式'),
(STATUS_PUBLIC, '一般'),
(STATUS_CLOSE, '非公開'),
(STATUS_BOT, 'BOT'),
(STATUS_BLOCK, '凍結')
... | [
random.choice(
string.ascii_letters +
string.digits) for i in range(n)]
return ''.join(randlst)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, se... | 93 | 93 | 312 | 5 | 88 | T-8723/copytter | app/api/copytter/models.py | Python | Profile | Profile | 28 | 66 | 28 | 28 | fc2d67fc8b66c7b6b74945193197134c843ccb53 | bigcode/the-stack | train |
eb70f3bd2c07ec49030b73ce | train | function | @click.command()
@click.argument('read_directory', type=click.Path(dir_okay=True),
default=dataset.DEFAULT_INTERIM_DATA_DIRECTORY)
@click.argument('save_directory', type=click.Path(writable=True, dir_okay=True),
default=dataset.DEFAULT_PROCESSED_TEXT_DATA_DIRECTORY)
@click.argument('enco... | @click.command()
@click.argument('read_directory', type=click.Path(dir_okay=True),
default=dataset.DEFAULT_INTERIM_DATA_DIRECTORY)
@click.argument('save_directory', type=click.Path(writable=True, dir_okay=True),
default=dataset.DEFAULT_PROCESSED_TEXT_DATA_DIRECTORY)
@click.argument('enco... | """Build text dataset from valid sentences in READ_DIRECTORY
READ_DIRECTORY is directory to read filtered/normalized data from.
Default: <project_root>/data/raw
SAVE_DIRECTORY is directory to store ready dataset csv file.
Default: <project_root>/data/interim
ENCODING is the encoding use... | @click.command()
@click.argument('read_directory', type=click.Path(dir_okay=True),
default=dataset.DEFAULT_INTERIM_DATA_DIRECTORY)
@click.argument('save_directory', type=click.Path(writable=True, dir_okay=True),
default=dataset.DEFAULT_PROCESSED_TEXT_DATA_DIRECTORY)
@click.argument('enco... | 86 | 64 | 191 | 86 | 0 | kwasnydam/animal_disambiguation | src/data/build_text_dataset.py | Python | filter_raw_data | filter_raw_data | 13 | 31 | 13 | 19 | a4864b4edde0ec6813b95abbee7b1113a7057da6 | bigcode/the-stack | train |
5d78b33a6a01ff43243148fb | train | function | def export(field_desc):
"""
:param field_desc:
:type field_desc: bitcoder.bitcoder.Encoded
:return:
"""
output = '// Automatically generated file, changes may be lost when file is regenerated\n'
output += '\n'
output += 'struct {}\n'.format(field_desc.__class__.__name__)
o... | def export(field_desc):
| """
:param field_desc:
:type field_desc: bitcoder.bitcoder.Encoded
:return:
"""
output = '// Automatically generated file, changes may be lost when file is regenerated\n'
output += '\n'
output += 'struct {}\n'.format(field_desc.__class__.__name__)
output += '{\n'
bit... | __author__ = 'Joe'
def export(field_desc):
| 12 | 64 | 193 | 5 | 7 | jemoster/bitcoder | bitcoder/c.py | Python | export | export | 4 | 29 | 4 | 4 | cf7f43585828cc004b975aa8439a7cf867753413 | bigcode/the-stack | train |
b32269f174360f6d88134955 | train | class | class CategoricalConverter(object):
def __init__(self, num_classes):
self.num_classes = num_classes
def __call__(self, probability_array):
prediction = np.argmax(probability_array, -1).astype(np.uint8)
return prediction.reshape(prediction.shape + (1,))
| class CategoricalConverter(object):
| def __init__(self, num_classes):
self.num_classes = num_classes
def __call__(self, probability_array):
prediction = np.argmax(probability_array, -1).astype(np.uint8)
return prediction.reshape(prediction.shape + (1,))
| :
log.warning("Non-Callable processor %s", processor)
return result
else:
log.debug("No valid post-processors found for: %s", self)
return result
return __postprocessor_handler
def identity_processor(arg):
return arg
class CategoricalConverter(o... | 64 | 64 | 62 | 6 | 57 | mneagul/hugin | src/hugin/engine/core.py | Python | CategoricalConverter | CategoricalConverter | 69 | 75 | 69 | 69 | 83e21a9b8c3bd988df125870ce7f418fc04448b3 | bigcode/the-stack | train |
a19de038f3049476ee38160b | train | function | def identity_metric(prediction, gti):
return 1
| def identity_metric(prediction, gti):
| return 1
| next(train_data)
for j in range(0, vdata):
data = next(validation_data)
def predict(self, batch, batch_size=None):
return batch
def save(self, destination=None):
# raise NotImplementedError()
pass
def identity_metric(prediction, gti):
| 64 | 64 | 14 | 9 | 54 | mneagul/hugin | src/hugin/engine/core.py | Python | identity_metric | identity_metric | 274 | 275 | 274 | 274 | 01d32ad080a57e500f389c6c58a1bf811e21abef | bigcode/the-stack | train |
6b44143ae47f5eb579bc3fc9 | train | class | class CloneComponentGenerator(RasterGenerator):
"""
Generator generating an clone of an existing component
"""
def __init__(self, base_component):
"""
Args:
base_component: the component we should use for detecting the size, etc
"""
self._base_component = bas... | class CloneComponentGenerator(RasterGenerator):
| """
Generator generating an clone of an existing component
"""
def __init__(self, base_component):
"""
Args:
base_component: the component we should use for detecting the size, etc
"""
self._base_component = base_component
def __call__(self, scene_compon... | handlers generating new data components
"""
def __call__(self, scene_components):
"""
Generate a new scene component
Args:
scene_components: existing scene components
Returns: Should return an rasterio dataset
"""
raise NotImplementedError()
class C... | 64 | 64 | 101 | 8 | 56 | mneagul/hugin | src/hugin/engine/core.py | Python | CloneComponentGenerator | CloneComponentGenerator | 293 | 308 | 293 | 293 | 6b720094cc825511c309098b59c23df80be9ed23 | bigcode/the-stack | train |
e8dae92b0bf37e5d4d88e5dd | train | function | def metric_processor(func):
def __metric_handler(self, scene, *args, **kwargs):
metrics = kwargs.pop('_metrics', {})
original_result = func(self, scene, *args, _metrics=metrics, **kwargs)
scene_id, scene_data = scene
my_metrics = {}
if self.name not in metrics:
me... | def metric_processor(func):
| def __metric_handler(self, scene, *args, **kwargs):
metrics = kwargs.pop('_metrics', {})
original_result = func(self, scene, *args, _metrics=metrics, **kwargs)
scene_id, scene_data = scene
my_metrics = {}
if self.name not in metrics:
metrics[self.name] = my_metric... | import os
import pickle
from logging import getLogger
import numpy as np
from sklearn.preprocessing import StandardScaler
log = getLogger(__name__)
def metric_processor(func):
| 36 | 64 | 186 | 5 | 31 | mneagul/hugin | src/hugin/engine/core.py | Python | metric_processor | metric_processor | 11 | 30 | 11 | 11 | 5d05b02b13a8b69b0d2ba1b097ab690ed979f471 | bigcode/the-stack | train |
0f8825d3dc77176e95a0220d | train | class | class PredictionMerger(object):
def __init__(self, height, width, depth, dtype):
self.height = height
self.width = width
self.depth = depth
self.dtype = dtype
def update(self, xstart, xend, ystart, yend, prediction):
raise NotImplementedError()
def get_prediction(se... | class PredictionMerger(object):
| def __init__(self, height, width, depth, dtype):
self.height = height
self.width = width
self.depth = depth
self.dtype = dtype
def update(self, xstart, xend, ystart, yend, prediction):
raise NotImplementedError()
def get_prediction(self):
raise NotImplemente... | : The input batch
:return: returns a prediction according to model configuration
"""
raise NotImplementedError()
def save(self, destination=None):
raise NotImplementedError()
def fit_generator(self, train_data, validation_data=None):
raise NotImplementedError()
class Pr... | 64 | 64 | 82 | 6 | 58 | mneagul/hugin | src/hugin/engine/core.py | Python | PredictionMerger | PredictionMerger | 121 | 132 | 121 | 121 | c1e389d4abc75ffb7e06b1f84b6281d3cd70528d | bigcode/the-stack | train |
174ceb52bbd85f4f8123132a | train | class | class NullMerger(PredictionMerger):
def __init__(self, *args, **kwargs):
super(NullMerger, self).__init__(*args, **kwargs)
self.tile_array = np.zeros((self.height, self.width, self.depth), dtype=self.dtype)
def update(self, xstart, xend, ystart, yend, prediction):
self.tile_array[xstart... | class NullMerger(PredictionMerger):
| def __init__(self, *args, **kwargs):
super(NullMerger, self).__init__(*args, **kwargs)
self.tile_array = np.zeros((self.height, self.width, self.depth), dtype=self.dtype)
def update(self, xstart, xend, ystart, yend, prediction):
self.tile_array[xstart: xend, ystart: yend] = prediction
... | self.width = width
self.depth = depth
self.dtype = dtype
def update(self, xstart, xend, ystart, yend, prediction):
raise NotImplementedError()
def get_prediction(self):
raise NotImplementedError()
class NullMerger(PredictionMerger):
| 64 | 64 | 110 | 10 | 54 | mneagul/hugin | src/hugin/engine/core.py | Python | NullMerger | NullMerger | 135 | 144 | 135 | 135 | 6d3e9f186d8f88ca59f49c8b2cbd863411601015 | bigcode/the-stack | train |
d7b42938358d61e526a48ff6 | train | function | def identity_processor(arg):
return arg
| def identity_processor(arg):
| return arg
| processor)
result = processor(result)
else:
log.warning("Non-Callable processor %s", processor)
return result
else:
log.debug("No valid post-processors found for: %s", self)
return result
return __postprocessor_han... | 64 | 64 | 9 | 5 | 58 | mneagul/hugin | src/hugin/engine/core.py | Python | identity_processor | identity_processor | 65 | 66 | 65 | 65 | 42ade0dac747bf67dfceff5a29f9b0ebbd310d94 | bigcode/the-stack | train |
5468a89ecb2d7445b0a467bf | train | class | class SkLearnStandardizer(RasterModel):
def __init__(self, model_path, with_gti = True, *args, copy=True, with_mean=True, with_std=True, **kw):
RasterModel.__init__(self, *args, **kw)
self.destination = model_path
self.copy = copy
self.with_mean = with_mean
self.with_std = wi... | class SkLearnStandardizer(RasterModel):
| def __init__(self, model_path, with_gti = True, *args, copy=True, with_mean=True, with_std=True, **kw):
RasterModel.__init__(self, *args, **kw)
self.destination = model_path
self.copy = copy
self.with_mean = with_mean
self.with_std = with_std
self._with_gti = with_gti... | args, **kwargs):
super(AverageMerger, self).__init__(*args, **kwargs)
self.tile_array = np.zeros((self.height, self.width, self.depth), dtype=self.dtype)
self.tile_freq_array = np.zeros((self.height, self.width), dtype=np.uint8)
def update(self, xstart, xend, ystart, yend, prediction):
... | 214 | 214 | 716 | 9 | 204 | mneagul/hugin | src/hugin/engine/core.py | Python | SkLearnStandardizer | SkLearnStandardizer | 168 | 247 | 168 | 168 | b080a6a37b0344639032cbee1bfc1cbbe846808d | bigcode/the-stack | train |
db4a685dea4647b412786b9b | train | class | class IdentityModel(RasterModel):
def __init__(self, *args, num_loops=1, **kwargs):
RasterModel.__init__(self, *args, **kwargs)
self.destination = None
self.num_loops = num_loops
def fit_generator(self, train_data, validation_data=None):
for i in range(self.num_loops):
... | class IdentityModel(RasterModel):
| def __init__(self, *args, num_loops=1, **kwargs):
RasterModel.__init__(self, *args, **kwargs)
self.destination = None
self.num_loops = num_loops
def fit_generator(self, train_data, validation_data=None):
for i in range(self.num_loops):
tdata = len(train_data)
... | i, mode in enumerate(['', '_gti']):
scaler_destination = os.path.join(destination, input_name + mode + '.pkl')
outs = pickle.dumps(scaler[i])
with open(scaler_destination, "wb") as f:
f.write(outs)
class IdentityModel(RasterModel):
| 64 | 64 | 174 | 7 | 57 | mneagul/hugin | src/hugin/engine/core.py | Python | IdentityModel | IdentityModel | 250 | 271 | 250 | 250 | eff731fb4fe66c05abe8ff13a825921f1245af6b | bigcode/the-stack | train |
a9dbad7d2601cd4fd512cc18 | train | class | class AverageMerger(PredictionMerger):
def __init__(self, *args, **kwargs):
super(AverageMerger, self).__init__(*args, **kwargs)
self.tile_array = np.zeros((self.height, self.width, self.depth), dtype=self.dtype)
self.tile_freq_array = np.zeros((self.height, self.width), dtype=np.uint8)
... | class AverageMerger(PredictionMerger):
| def __init__(self, *args, **kwargs):
super(AverageMerger, self).__init__(*args, **kwargs)
self.tile_array = np.zeros((self.height, self.width, self.depth), dtype=self.dtype)
self.tile_freq_array = np.zeros((self.height, self.width), dtype=np.uint8)
def update(self, xstart, xend, ystart,... | .depth), dtype=self.dtype)
def update(self, xstart, xend, ystart, yend, prediction):
self.tile_array[xstart: xend, ystart: yend] = prediction
def get_prediction(self):
return self.tile_array
class AverageMerger(PredictionMerger):
| 66 | 66 | 223 | 10 | 55 | mneagul/hugin | src/hugin/engine/core.py | Python | AverageMerger | AverageMerger | 148 | 165 | 148 | 148 | 35aa2b8fbdbe7d95e09064db16ef70d3ad8a4529 | bigcode/the-stack | train |
61b9942f79ee88d23f7feefd | train | function | def postprocessor(func):
def __postprocessor_handler(self, *args, **kwargs):
kwargs.pop("_metrics", None)
result = func(self, *args, **kwargs)
postprocessors = getattr(self, 'post_processors')
if not postprocessors:
log.debug("No post-processors found for: %s", self)
... | def postprocessor(func):
| def __postprocessor_handler(self, *args, **kwargs):
kwargs.pop("_metrics", None)
result = func(self, *args, **kwargs)
postprocessors = getattr(self, 'post_processors')
if not postprocessors:
log.debug("No post-processors found for: %s", self)
if callable(postproc... | .metrics.items():
my_metrics[metric_name] = metric_calculator(original_result, gti.read())
else:
log.warning("Missing GTI data for GTI component: %s", self.gti_component)
return (original_result, metrics)
return __metric_handler
def postprocessor(func):
| 64 | 64 | 195 | 5 | 58 | mneagul/hugin | src/hugin/engine/core.py | Python | postprocessor | postprocessor | 33 | 62 | 33 | 33 | daff3d924ca68b40ecf978debcab5bcce7c59c61 | bigcode/the-stack | train |
93257d88b13335ade51ce3f5 | train | class | class RasterGenerator(object):
"""
Base class used by handlers generating new data components
"""
def __call__(self, scene_components):
"""
Generate a new scene component
Args:
scene_components: existing scene components
Returns: Should return an rasterio dat... | class RasterGenerator(object):
| """
Base class used by handlers generating new data components
"""
def __call__(self, scene_components):
"""
Generate a new scene component
Args:
scene_components: existing scene components
Returns: Should return an rasterio dataset
"""
raise... | 0, vdata):
data = next(validation_data)
def predict(self, batch, batch_size=None):
return batch
def save(self, destination=None):
# raise NotImplementedError()
pass
def identity_metric(prediction, gti):
return 1
class RasterGenerator(object):
| 64 | 64 | 68 | 5 | 58 | mneagul/hugin | src/hugin/engine/core.py | Python | RasterGenerator | RasterGenerator | 277 | 290 | 277 | 277 | 28d88d4172b50aa938838eb0df6338d0f668d367 | bigcode/the-stack | train |
f3787db91c8b74cd6887278f | train | class | class RasterModel(object):
def __init__(self,
name=None,
batch_size=1,
swap_axes=True,
input_shapes=None,
output_shapes=None,
# input_shape=None,
# output_shape=None
):
"""... | class RasterModel(object):
| def __init__(self,
name=None,
batch_size=1,
swap_axes=True,
input_shapes=None,
output_shapes=None,
# input_shape=None,
# output_shape=None
):
"""Base model object handling ... | found for: %s", self)
return result
return __postprocessor_handler
def identity_processor(arg):
return arg
class CategoricalConverter(object):
def __init__(self, num_classes):
self.num_classes = num_classes
def __call__(self, probability_array):
prediction = np.argmax(... | 95 | 96 | 320 | 5 | 91 | mneagul/hugin | src/hugin/engine/core.py | Python | RasterModel | RasterModel | 78 | 118 | 78 | 78 | d1c4fc2ec3275cc62803aa7630c9fe1e28af1ac5 | bigcode/the-stack | train |
82ef9fdf4a308b8aec5a1ff6 | train | class | class PointNavRandomTask(PointNavFixedTask):
"""
Point Nav Random Task
The goal is to navigate to a random goal position
"""
def __init__(self, env):
super(PointNavRandomTask, self).__init__(env)
self.target_dist_min = self.config.get("target_dist_min", 1.0)
self.target_dist... | class PointNavRandomTask(PointNavFixedTask):
| """
Point Nav Random Task
The goal is to navigate to a random goal position
"""
def __init__(self, env):
super(PointNavRandomTask, self).__init__(env)
self.target_dist_min = self.config.get("target_dist_min", 1.0)
self.target_dist_max = self.config.get("target_dist_max", 10.... | import logging
import numpy as np
import pybullet as p
from igibson.tasks.point_nav_fixed_task import PointNavFixedTask
from igibson.utils.utils import l2_distance, restoreState
class PointNavRandomTask(PointNavFixedTask):
| 53 | 184 | 616 | 10 | 42 | Nick-AhSen/iGibson | igibson/tasks/point_nav_random_task.py | Python | PointNavRandomTask | PointNavRandomTask | 10 | 86 | 10 | 10 | 4049918d5dd99cb3b1558e8072f4daf04411b577 | bigcode/the-stack | train |
bc0554c03b2cbdefe32b63bb | train | class | @base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class WorkerPools(base.Group):
"""Manage worker pools for Google Cloud Build."""
| @base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class WorkerPools(base.Group):
| """Manage worker pools for Google Cloud Build."""
| .
"""The command group for Google Cloud Build's Workerpools."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class WorkerPools(base.Group):
| 64 | 64 | 27 | 17 | 46 | bshaffer/google-cloud-sdk | lib/surface/builds/worker_pools/__init__.py | Python | WorkerPools | WorkerPools | 24 | 26 | 24 | 25 | 1314070412cdd985c0b36b40f77be62470d4f922 | bigcode/the-stack | train |
80a098b4e1ae9b0d483b406a | train | class | class LinUCBLearner(Learner):
"""A learner using the LinUCB algorithm from "Contextual Bandits with Linear Payoff Functions" by Wei Chu et al."""
@property
def params(self) -> Dict[str, Any]:
"""The parameters of the learner.
See the base class for more information.
"""
dic... | class LinUCBLearner(Learner):
| """A learner using the LinUCB algorithm from "Contextual Bandits with Linear Payoff Functions" by Wei Chu et al."""
@property
def params(self) -> Dict[str, Any]:
"""The parameters of the learner.
See the base class for more information.
"""
dict = {'family': 'linUCB', 'alph... | import collections
import time
from typing import Any, Dict, Sequence
from coba.utilities import PackageChecker
from coba.environments import Context, Action
from coba.encodings import InteractionTermsEncoder
from coba.learners.core import Info, Learner
class LinUCBLearner(Learner):
| 61 | 256 | 988 | 10 | 50 | anrath/coba | coba/learners/linUCB.py | Python | LinUCBLearner | LinUCBLearner | 11 | 122 | 11 | 11 | 2703ecab81d92a4655072d41b63957725a8aa36a | bigcode/the-stack | train |
54c6918b72b91af1db623e72 | train | class | class FunctionVersionInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
class Visibility(object):
PUBLIC = "public"
... | class FunctionVersionInstance(InstanceResource):
| """ PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
class Visibility(object):
PUBLIC = "public"
PRIVATE = "private"
PROTECTED = "pr... | )
# Path Solution
self._solution = {'service_sid': service_sid, 'function_sid': function_sid, 'sid': sid, }
self._uri = '/Services/{service_sid}/Functions/{function_sid}/Versions/{sid}'.format(**self._solution)
def fetch(self):
"""
Fetch a FunctionVersionInstance
:... | 256 | 256 | 898 | 8 | 248 | nitinavasthi/twillio-whatsapp | twilio/rest/serverless/v1/service/function/function_version.py | Python | FunctionVersionInstance | FunctionVersionInstance | 292 | 439 | 292 | 292 | 130febffeb1da1ed618b8db8636d9540a5220842 | bigcode/the-stack | train |
d19a6b675ab9f7d0403a7925 | train | class | class FunctionVersionContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, service_sid, function_sid, s... | class FunctionVersionContext(InstanceContext):
| """ PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, service_sid, function_sid, sid):
"""
Initialize the Functio... | twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance
:rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance
"""
return FunctionVersionInstance(
self._version,
payload,
service_sid=self._solut... | 124 | 125 | 417 | 8 | 116 | nitinavasthi/twillio-whatsapp | twilio/rest/serverless/v1/service/function/function_version.py | Python | FunctionVersionContext | FunctionVersionContext | 235 | 289 | 235 | 235 | 105579a7a8c931c230e733e51a55067551b0c5c4 | bigcode/the-stack | train |
4ea67b74ce3442d5922a0867 | train | class | class FunctionVersionList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, service_sid, function_sid):
... | class FunctionVersionList(ListResource):
| """ PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, service_sid, function_sid):
"""
Initialize the FunctionVers... | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... | 109 | 256 | 1,367 | 7 | 101 | nitinavasthi/twillio-whatsapp | twilio/rest/serverless/v1/service/function/function_version.py | Python | FunctionVersionList | FunctionVersionList | 17 | 184 | 17 | 17 | 2155ea2893cbcfed5eeddad65dd673dcd1d20e81 | bigcode/the-stack | train |
662798fef33f214348f7da92 | train | class | class FunctionVersionPage(Page):
""" PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
I... | class FunctionVersionPage(Page):
| """ PLEASE NOTE that this class contains preview products that are subject
to change. Use them with caution. If you currently do not have developer
preview access, please contact help@twilio.com. """
def __init__(self, version, response, solution):
"""
Initialize the FunctionVersionPage... | .service.function.function_version.FunctionVersionContext
"""
return FunctionVersionContext(
self._version,
service_sid=self._solution['service_sid'],
function_sid=self._solution['function_sid'],
sid=sid,
)
def __repr__(self):
"""
... | 98 | 99 | 332 | 6 | 92 | nitinavasthi/twillio-whatsapp | twilio/rest/serverless/v1/service/function/function_version.py | Python | FunctionVersionPage | FunctionVersionPage | 187 | 232 | 187 | 187 | 80f3533a288be92284a706dad6b1057c7ea84b47 | bigcode/the-stack | train |
e43a4f808ecd7edbdac8f5da | train | function | def make_intermediates(mycc, t1, t2, eris):
imds = ccsd_lambda.make_intermediates(mycc, t1, t2, eris)
nocc, nvir = t1.shape
eris_ovvv = numpy.asarray(eris.get_ovvv())
eris_ovoo = numpy.asarray(eris.ovoo)
eris_ovov = numpy.asarray(eris.ovov)
mo_e = eris.fock.diagonal()
eia = lib.direct_sum(... | def make_intermediates(mycc, t1, t2, eris):
| imds = ccsd_lambda.make_intermediates(mycc, t1, t2, eris)
nocc, nvir = t1.shape
eris_ovvv = numpy.asarray(eris.get_ovvv())
eris_ovoo = numpy.asarray(eris.ovoo)
eris_ovov = numpy.asarray(eris.ovov)
mo_e = eris.fock.diagonal()
eia = lib.direct_sum('i-a->ia', mo_e[:nocc], mo_e[nocc:])
d3 ... | 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.
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''
Spin-free l... | 253 | 253 | 844 | 17 | 236 | fdmalone/pyscf | pyscf/cc/ccsd_t_lambda_slow.py | Python | make_intermediates | make_intermediates | 42 | 90 | 42 | 42 | a3438a17eec4a3903832d4f2e8a869862bdadb51 | bigcode/the-stack | train |
76b72a2167acda6798097f6c | train | function | def update_lambda(mycc, t1, t2, l1, l2, eris=None, imds=None):
if eris is None: eris = mycc.ao2mo()
if imds is None: imds = make_intermediates(mycc, t1, t2, eris)
l1, l2 = ccsd_lambda.update_lambda(mycc, t1, t2, l1, l2, eris, imds)
l1 += imds.l1_t
l2 += imds.l2_t
return l1, l2
| def update_lambda(mycc, t1, t2, l1, l2, eris=None, imds=None):
| if eris is None: eris = mycc.ao2mo()
if imds is None: imds = make_intermediates(mycc, t1, t2, eris)
l1, l2 = ccsd_lambda.update_lambda(mycc, t1, t2, l1, l2, eris, imds)
l1 += imds.l1_t
l2 += imds.l2_t
return l1, l2
| :], rw.conj())
imds.l2_t = joovv / lib.direct_sum('ia+jb->ijab', eia, eia)
return imds
def update_lambda(mycc, t1, t2, l1, l2, eris=None, imds=None):
| 64 | 64 | 131 | 26 | 37 | fdmalone/pyscf | pyscf/cc/ccsd_t_lambda_slow.py | Python | update_lambda | update_lambda | 92 | 98 | 92 | 92 | 4d681abc4ffbf89a42c656528e39ba812b25e06f | bigcode/the-stack | train |
29cb5453dd48d473e0abd634 | train | function | def kernel(mycc, eris=None, t1=None, t2=None, l1=None, l2=None,
max_cycle=50, tol=1e-8, verbose=logger.INFO):
return ccsd_lambda.kernel(mycc, eris, t1, t2, l1, l2, max_cycle, tol,
verbose, make_intermediates, update_lambda)
| def kernel(mycc, eris=None, t1=None, t2=None, l1=None, l2=None,
max_cycle=50, tol=1e-8, verbose=logger.INFO):
| return ccsd_lambda.kernel(mycc, eris, t1, t2, l1, l2, max_cycle, tol,
verbose, make_intermediates, update_lambda)
| from pyscf.cc import ccsd_lambda
# Note: not support fov != 0
def kernel(mycc, eris=None, t1=None, t2=None, l1=None, l2=None,
max_cycle=50, tol=1e-8, verbose=logger.INFO):
| 64 | 64 | 84 | 43 | 20 | fdmalone/pyscf | pyscf/cc/ccsd_t_lambda_slow.py | Python | kernel | kernel | 37 | 40 | 37 | 38 | f2e44323761fccade10ae1a8e42e57caaedaef52 | bigcode/the-stack | train |
77d85af634de116f869b52d9 | train | function | def merge_cookies_from_response(cookie_jar, http_response, url):
p = models.PreparedRequest()
p.prepare(url=url)
cookies.extract_cookies_to_jar(cookie_jar, p, http_response)
# cookie_list_str = http_response.info().getlist('set-cookie')
# cookie_jar._now = int(time.time())
# cookie_set = cookie... | def merge_cookies_from_response(cookie_jar, http_response, url):
| p = models.PreparedRequest()
p.prepare(url=url)
cookies.extract_cookies_to_jar(cookie_jar, p, http_response)
# cookie_list_str = http_response.info().getlist('set-cookie')
# cookie_jar._now = int(time.time())
# cookie_set = cookiejar.parse_ns_headers(cookie_list_str)
# cookie_tuples = cooki... | from http.cookiejar import CookieJar
from requests import cookies, models
from socketclient.log import logger
def merge_cookies_from_response(cookie_jar, http_response, url):
| 37 | 64 | 147 | 15 | 21 | TKaxv-7S/jd-assistant | src/socketclient/utils/http/cookie_util.py | Python | merge_cookies_from_response | merge_cookies_from_response | 8 | 23 | 8 | 8 | a82bde2d556ff166321bcb1bdf7f3d7623f22300 | bigcode/the-stack | train |
76240c2a56330f22c6defc97 | train | function | def get_cookies_str(cookie):
try:
if isinstance(cookie, CookieJar):
cookie_array = []
for _cookie in iter(cookie):
cookie_array.append(f'{_cookie.name}={_cookie.value};')
return ''.join(cookie_array)
elif isinstance(cookie, dict):
retur... | def get_cookies_str(cookie):
| try:
if isinstance(cookie, CookieJar):
cookie_array = []
for _cookie in iter(cookie):
cookie_array.append(f'{_cookie.name}={_cookie.value};')
return ''.join(cookie_array)
elif isinstance(cookie, dict):
return cookies.cookiejar_from_dict... | _tuples = cookie_jar._normalized_cookie_tuples(cookie_set)
#
# for tup in cookie_tuples:
# cookie = mark_cookie(tup)
# if cookie:
# cookie_jar.set_cookie(cookie)
return cookie_jar
def get_cookies_str(cookie):
| 64 | 64 | 127 | 7 | 56 | TKaxv-7S/jd-assistant | src/socketclient/utils/http/cookie_util.py | Python | get_cookies_str | get_cookies_str | 26 | 42 | 26 | 26 | a8f585a0431a7dad7ed8fc5690916f1c96dcf96a | bigcode/the-stack | train |
d41ee4e05bc3b0df204b1583 | train | function | def compute():
with open('instances_train2019.json') as fid:
data = json.load(fid)
images = {}
for x in data['images']:
images[x['id']] = x
annotations = {}
for x in data['annotations']:
annotations[images[x['image_id']]['file_name']] = x
object_paths = glob.glob(os.pat... | def compute():
| with open('instances_train2019.json') as fid:
data = json.load(fid)
images = {}
for x in data['images']:
images[x['id']] = x
annotations = {}
for x in data['annotations']:
annotations[images[x['image_id']]['file_name']] = x
object_paths = glob.glob(os.path.join('/data7/... | import glob
import json
import os
from collections import defaultdict
import numpy as np
from PIL import Image
from tqdm import tqdm
def compute():
| 32 | 98 | 327 | 3 | 28 | isrc-cas/ACM-MM-2019-ACO | toolboxes/compute_threshold.py | Python | compute | compute | 11 | 48 | 11 | 11 | 46b1cca4d7758d5bb43d037de71e9649859abe8f | bigcode/the-stack | train |
be95d74a17d6e1407a6f0d9d | train | class | class Migration(migrations.Migration):
dependencies = [
('feedbacks', '0034_auto_20190322_0837'),
]
operations = [
migrations.AddField(
model_name='survey',
name='featured',
field=models.BooleanField(default=False, verbose_name='featured'),
),
... | class Migration(migrations.Migration):
| dependencies = [
('feedbacks', '0034_auto_20190322_0837'),
]
operations = [
migrations.AddField(
model_name='survey',
name='featured',
field=models.BooleanField(default=False, verbose_name='featured'),
),
]
| # Generated by Django 2.0.8 on 2019-03-24 17:04
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 67 | 7 | 30 | flavoi/diven | diventi/feedbacks/migrations/0035_survey_featured.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | d898f92735c6c4af68c84c93874070d8c58ac19e | bigcode/the-stack | train |
2c43ca6da03ea5800019db09 | train | function | def __suprimirIntercambio(evento, intercambios):
"""
Funcion para suprimir los eventos de tipo intercambio
"""
for intercambio in intercambios:
time = util.__eventTimeSplit(evento["dtstart"].dt)
exdate = util.__fromOurDateToDatetime(intercambio["diaOriginal"], None) + datetime.timede... | def __suprimirIntercambio(evento, intercambios):
| """
Funcion para suprimir los eventos de tipo intercambio
"""
for intercambio in intercambios:
time = util.__eventTimeSplit(evento["dtstart"].dt)
exdate = util.__fromOurDateToDatetime(intercambio["diaOriginal"], None) + datetime.timedelta(hours=time[0], minutes=time[1])
event... | )
time = util.__eventTimeSplit(evento["dtstart"].dt)
for i in range(7):
evento.add('exdate', inicio + datetime.timedelta(days=i, hours=time[0], minutes=time[1]))
def __suprimirIntercambio(evento, intercambios):
| 63 | 64 | 96 | 14 | 49 | Hikasgai/HikasgaiSOAP | calendario/delete.py | Python | __suprimirIntercambio | __suprimirIntercambio | 34 | 41 | 34 | 34 | ee7433e1cd76545773c6efd5980782bf180a1810 | bigcode/the-stack | train |
98d2a5a405d3d54e33fd3e43 | train | function | def __suprimirSemanasExcluidas(evento, semanas):
for semana in semanas:
inicio = util.__fromOurDateToDatetime(semana["primerDiaSemana"], None)
time = util.__eventTimeSplit(evento["dtstart"].dt)
for i in range(7):
evento.add('exdate', inicio + datetime.timedelta(days=i, hours... | def __suprimirSemanasExcluidas(evento, semanas):
| for semana in semanas:
inicio = util.__fromOurDateToDatetime(semana["primerDiaSemana"], None)
time = util.__eventTimeSplit(evento["dtstart"].dt)
for i in range(7):
evento.add('exdate', inicio + datetime.timedelta(days=i, hours=time[0], minutes=time[1]))
| exdate', inicio)
evento.add('exdate', fin)
for i in range(delta.days + 1):
evento.add('exdate', inicio + datetime.timedelta(days=i, hours=time[0], minutes=time[1]))
def __suprimirSemanasExcluidas(evento, semanas):
| 64 | 64 | 89 | 15 | 49 | Hikasgai/HikasgaiSOAP | calendario/delete.py | Python | __suprimirSemanasExcluidas | __suprimirSemanasExcluidas | 25 | 31 | 25 | 26 | 21b4db12a07ce3f95834b5e0f55f79821fcfa393 | bigcode/the-stack | train |
05bdd3b381e14b9f6e635bd4 | train | function | def __suprimirPeriodosHorarioEspecial(evento, periodoEspecial):
for periodo in periodoEspecial:
inicio = util.__fromOurDateToDatetime(periodo["fechaInicio"], None)
fin = util.__fromOurDateToDatetime(periodo["fechaFin"], None)
delta = fin - inicio
time = util.__eventTimeSplit(evento["... | def __suprimirPeriodosHorarioEspecial(evento, periodoEspecial):
| for periodo in periodoEspecial:
inicio = util.__fromOurDateToDatetime(periodo["fechaInicio"], None)
fin = util.__fromOurDateToDatetime(periodo["fechaFin"], None)
delta = fin - inicio
time = util.__eventTimeSplit(evento["dtstart"].dt)
evento.add('exdate', inicio)
event... | Split(evento["dtstart"].dt)
exdate = util.__fromOurDateToDatetime(dia["fecha"], None) + datetime.timedelta(hours=time[0], minutes=time[1])
evento.add('exdate', exdate)
def __suprimirPeriodosHorarioEspecial(evento, periodoEspecial):
| 64 | 64 | 133 | 14 | 50 | Hikasgai/HikasgaiSOAP | calendario/delete.py | Python | __suprimirPeriodosHorarioEspecial | __suprimirPeriodosHorarioEspecial | 14 | 23 | 14 | 14 | 2401840ccea3295d9db458c1fc9c7c2f8a8937eb | bigcode/the-stack | train |
49224b89a679c26716e43b1e | train | function | def __suprimirFiestas(eventos, data):
"""
Elimina del evento los dias que hay fiestas
El algoritmo no es nada eficiente
"""
for evento in eventos:
__suprimirDiasSinClase(evento, data["diasSinClase"])
__suprimirPeriodosHorarioEspecial(evento, data["periodosHorarioEspecial"])
... | def __suprimirFiestas(eventos, data):
| """
Elimina del evento los dias que hay fiestas
El algoritmo no es nada eficiente
"""
for evento in eventos:
__suprimirDiasSinClase(evento, data["diasSinClase"])
__suprimirPeriodosHorarioEspecial(evento, data["periodosHorarioEspecial"])
__suprimirSemanasExcluidas(even... | TimeSplit(evento["dtstart"].dt)
exdate = util.__fromOurDateToDatetime(intercambio["diaOriginal"], None) + datetime.timedelta(hours=time[0], minutes=time[1])
evento.add('exdate', exdate)
def __suprimirFiestas(eventos, data):
| 64 | 64 | 116 | 11 | 53 | Hikasgai/HikasgaiSOAP | calendario/delete.py | Python | __suprimirFiestas | __suprimirFiestas | 44 | 55 | 44 | 44 | 7984b6171602e917718f0d35dfd4cf9d5cd67f73 | bigcode/the-stack | train |
e272b8b294491cc7e97dc139 | train | function | def __suprimirDiasSinClase(evento, diasSinClase):
for dia in diasSinClase:
time = util.__eventTimeSplit(evento["dtstart"].dt)
exdate = util.__fromOurDateToDatetime(dia["fecha"], None) + datetime.timedelta(hours=time[0], minutes=time[1])
evento.add('exdate', exdate)
| def __suprimirDiasSinClase(evento, diasSinClase):
| for dia in diasSinClase:
time = util.__eventTimeSplit(evento["dtstart"].dt)
exdate = util.__fromOurDateToDatetime(dia["fecha"], None) + datetime.timedelta(hours=time[0], minutes=time[1])
evento.add('exdate', exdate)
| import datetime
from icalendar import Event, vRecur
from calendario import util
def __suprimirDiasSinClase(evento, diasSinClase):
| 33 | 64 | 79 | 14 | 18 | Hikasgai/HikasgaiSOAP | calendario/delete.py | Python | __suprimirDiasSinClase | __suprimirDiasSinClase | 8 | 12 | 8 | 8 | f3650d30529cdd62ef78e0a0bcb1423198dbdf0b | bigcode/the-stack | train |
dcdb98dc2366628f1cbbb86d | train | class | class SearchByActress:
@staticmethod
def __guess_lang(text):
if all(map(lambda c: ord(c) < 128, text)):
lang = "en"
else:
if any(map(lambda c: 0x0800 <= ord(c) <= 0x4E00, text)):
lang = "jp"
else:
lang = "zh"
return la... | class SearchByActress:
@staticmethod
| def __guess_lang(text):
if all(map(lambda c: ord(c) < 128, text)):
lang = "en"
else:
if any(map(lambda c: 0x0800 <= ord(c) <= 0x4E00, text)):
lang = "jp"
else:
lang = "zh"
return lang
@classmethod
def search(cls, ... | import JavPy.sources
from JavPy.functions.sources import Sources
from JavPy.functions.actress_translate import ActressTranslate
from JavPy.functions.history_names import HistoryNames
from future.builtins import map
from JavPy.utils.requester import spawn, Task, spawn_many
class SearchByActress:
@staticmethod
| 66 | 70 | 234 | 10 | 55 | thosieucoi/JavPy | JavPy/functions/search_by_actress.py | Python | SearchByActress | SearchByActress | 9 | 42 | 9 | 10 | 52059a40bbce2644453b24f164efae9ed0f812bf | bigcode/the-stack | train |
d4ac0e23fa026faba0f7768e | train | function | def launch_app(path_of_app):
try:
subprocess.call([path_of_app])
return True
except Exception as e:
print(e)
return False | def launch_app(path_of_app):
| try:
subprocess.call([path_of_app])
return True
except Exception as e:
print(e)
return False | import subprocess
def launch_app(path_of_app):
| 10 | 64 | 35 | 7 | 2 | Akhandsaxena12/Jarvis_AI | JarvisAI/JarvisAI/features/launch_app/launch_app.py | Python | launch_app | launch_app | 4 | 10 | 4 | 4 | 895135cd2f39c19e8fd66cb8ee5ead5cbf0922a5 | bigcode/the-stack | train |
f599f2cd70d5722d9ca5842e | train | function | def redemptions_account():
return Account.objects.get(code=names.REDEMPTIONS_CODE)
| def redemptions_account():
| return Account.objects.get(code=names.REDEMPTIONS_CODE)
| from oscar.core.loading import get_model
from oscar_accounts import names
Account = get_model('oscar_accounts', 'Account')
def redemptions_account():
| 34 | 64 | 20 | 6 | 28 | amazy/django-oscar-accounts | src/oscar_accounts/core.py | Python | redemptions_account | redemptions_account | 8 | 9 | 8 | 8 | fbdddaa6e71bad4f08452cd50fe59467b2ba8450 | bigcode/the-stack | train |
001e0caf18c86cb6df140d85 | train | function | def lapsed_account():
return Account.objects.get(name=names.LAPSED)
| def lapsed_account():
| return Account.objects.get(name=names.LAPSED)
| from oscar.core.loading import get_model
from oscar_accounts import names
Account = get_model('oscar_accounts', 'Account')
def redemptions_account():
return Account.objects.get(code=names.REDEMPTIONS_CODE)
def lapsed_account():
| 53 | 64 | 17 | 5 | 48 | amazy/django-oscar-accounts | src/oscar_accounts/core.py | Python | lapsed_account | lapsed_account | 12 | 13 | 12 | 12 | 0e78755641b7690e377053be583289c2a76698c1 | bigcode/the-stack | train |
1cfdfd735ec0d8eebb3af979 | train | function | def sess_interest_division(sparse_embedding_dict, user_behavior_input_dict, sparse_fg_list, sess_feture_list,
sess_max_count,
bias_encoding=True):
tr_input = []
for i in range(sess_max_count):
sess_name = "sess_" + str(i)
keys_emb_list = get_... | def sess_interest_division(sparse_embedding_dict, user_behavior_input_dict, sparse_fg_list, sess_feture_list,
sess_max_count,
bias_encoding=True):
| tr_input = []
for i in range(sess_max_count):
sess_name = "sess_" + str(i)
keys_emb_list = get_embedding_vec_list(sparse_embedding_dict, user_behavior_input_dict[sess_name],
sparse_fg_list, sess_feture_list, sess_feture_list)
keys_emb = con... | _input_dict[sess_name]]))
model = Model(inputs=inputs_list + [user_sess_length], outputs=output)
return model
def sess_interest_division(sparse_embedding_dict, user_behavior_input_dict, sparse_fg_list, sess_feture_list,
sess_max_count,
bias_encoding=True):... | 64 | 64 | 139 | 34 | 29 | HCMY/DeepCTR | deepctr/models/dsin.py | Python | sess_interest_division | sess_interest_division | 146 | 159 | 146 | 148 | a04724a6b9c1c4528c153dcbad8b0fdc4ce18181 | bigcode/the-stack | train |
8ccfc9e2988e370bda45d939 | train | function | def sess_interest_extractor(tr_input, sess_max_count, TR):
tr_out = []
for i in range(sess_max_count):
tr_out.append(TR(
[tr_input[i], tr_input[i]]))
sess_fea = concat_func(tr_out, axis=1)
return sess_fea
| def sess_interest_extractor(tr_input, sess_max_count, TR):
| tr_out = []
for i in range(sess_max_count):
tr_out.append(TR(
[tr_input[i], tr_input[i]]))
sess_fea = concat_func(tr_out, axis=1)
return sess_fea
| _list, sess_feture_list)
keys_emb = concat_func(keys_emb_list, mask=True)
tr_input.append(keys_emb)
if bias_encoding:
tr_input = BiasEncoding(sess_max_count)(tr_input)
return tr_input
def sess_interest_extractor(tr_input, sess_max_count, TR):
| 64 | 64 | 65 | 14 | 49 | HCMY/DeepCTR | deepctr/models/dsin.py | Python | sess_interest_extractor | sess_interest_extractor | 162 | 168 | 162 | 162 | ac7464cd2e4da154877e988b4a946a6990e5f82c | bigcode/the-stack | train |
c533d378211612ccbae72fdb | train | function | def DSIN(dnn_feature_columns, sess_feature_list, sess_max_count=5, bias_encoding=False,
att_embedding_size=1, att_head_num=8, dnn_hidden_units=(200, 80), dnn_activation='sigmoid', dnn_dropout=0,
dnn_use_bn=False, l2_reg_dnn=0, l2_reg_embedding=1e-6, seed=1024, task='binary',
):
"""Instant... | def DSIN(dnn_feature_columns, sess_feature_list, sess_max_count=5, bias_encoding=False,
att_embedding_size=1, att_head_num=8, dnn_hidden_units=(200, 80), dnn_activation='sigmoid', dnn_dropout=0,
dnn_use_bn=False, l2_reg_dnn=0, l2_reg_embedding=1e-6, seed=1024, task='binary',
):
| """Instantiates the Deep Session Interest Network architecture.
:param dnn_feature_columns: An iterable containing all the features used by deep part of the model.
:param sess_feature_list: list,to indicate sequence sparse field
:param sess_max_count: positive int, to indicate the max number of sessio... | :1905.06482, 2019.(https://arxiv.org/abs/1905.06482)
"""
from collections import OrderedDict
import tensorflow as tf
from tensorflow.python.keras.layers import (Concatenate, Dense, Embedding,
Flatten, Input)
from tensorflow.python.keras.models import Model
from tensorflow.... | 256 | 256 | 1,380 | 94 | 161 | HCMY/DeepCTR | deepctr/models/dsin.py | Python | DSIN | DSIN | 27 | 143 | 27 | 30 | c9389e586fa2dac726a400cd3c7a5e19fce1ee07 | bigcode/the-stack | train |
5c6ae9affd7744cd70b280de | train | class | class KnowValues(unittest.TestCase):
def test_jk_single_kpt(self):
mf = mdf_jk.density_fit(mf0, auxbasis='weigend', mesh=(11,)*3)
mf.with_df.mesh = [11]*3
mf.with_df.eta = 0.3
dm = mf.get_init_guess()
vj, vk = mf.get_jk(cell, dm)
ej1 = numpy.einsum('ij,ji->', vj, dm)
... | class KnowValues(unittest.TestCase):
| def test_jk_single_kpt(self):
mf = mdf_jk.density_fit(mf0, auxbasis='weigend', mesh=(11,)*3)
mf.with_df.mesh = [11]*3
mf.with_df.eta = 0.3
dm = mf.get_init_guess()
vj, vk = mf.get_jk(cell, dm)
ej1 = numpy.einsum('ij,ji->', vj, dm)
ek1 = numpy.einsum('ij,ji->',... | .pbc import gto as pgto
from pyscf.pbc import scf as pscf
import pyscf.pbc
from pyscf.pbc.df import mdf
from pyscf.pbc.df import mdf_jk
#from mpi4pyscf.pbc.df import mdf
#from mpi4pyscf.pbc.df import mdf_jk
pyscf.pbc.DEBUG = False
mdf.df.LINEAR_DEP_THR = 1e-7
L = 5.
n = 11
cell = pgto.Cell()
cell.a = numpy.diag([L,L,L... | 256 | 256 | 2,477 | 7 | 249 | snsunx/pyscf | pyscf/pbc/df/test/test_mdf_jk.py | Python | KnowValues | KnowValues | 50 | 199 | 50 | 50 | 26ac163407cb8ae5583bd08cce243190a1f2e3c8 | bigcode/the-stack | train |
dee8654f0e57bf54a7cf1a07 | train | function | def finger(a):
w = numpy.cos(numpy.arange(a.size))
return numpy.dot(a.ravel(), w)
| def finger(a):
| w = numpy.cos(numpy.arange(a.size))
return numpy.dot(a.ravel(), w)
| 1. 1.'''
cell.basis = 'ccpvdz'
cell.verbose = 0
cell.max_memory = 0
cell.rcut = 28.3
cell.build()
mf0 = pscf.RHF(cell)
mf0.exxdiv = None
def finger(a):
| 64 | 64 | 25 | 4 | 59 | snsunx/pyscf | pyscf/pbc/df/test/test_mdf_jk.py | Python | finger | finger | 46 | 48 | 46 | 46 | 8d9c5485cde8341003acd9c8bec934c528dd3af5 | bigcode/the-stack | train |
0ae76470a4c83913e378b981 | train | function | def escape_url(url):
return url.replace('&', '&')
| def escape_url(url):
| return url.replace('&', '&')
| proto='mailto:')
# Prepare attrs
attr = ' {0!s}="{1!s}"'
attrs_text = ''.join(starmap(attr.format, attrs.items()))
# Make replaces
return re.sub(combined_re, repl, force_unicode(text))
def escape_url(url):
| 64 | 64 | 15 | 5 | 59 | hackatbrown/2015.hackatbrown.org | hack-at-brown-2015/autolink.py | Python | escape_url | escape_url | 99 | 100 | 99 | 99 | b719379881f4c2d5fde0bc2be399b39e53e47aae | bigcode/the-stack | train |
4a26f3b776f3ee71cf2366c5 | train | function | def re_find(regex, s):
m = re.search(regex, s)
if m:
return m.group()
| def re_find(regex, s):
| m = re.search(regex, s)
if m:
return m.group()
| We use .decode() here, instead of six.text_type(s,
# encoding, errors), so that if s is a SafeBytes, it ends up being
# a SafeText at the end.
s = s.decode(encoding, errors)
return s
def re_find(regex, s):
| 64 | 64 | 25 | 7 | 56 | hackatbrown/2015.hackatbrown.org | hack-at-brown-2015/autolink.py | Python | re_find | re_find | 128 | 131 | 128 | 128 | 32090921103f683bf50bafd69dc741ee0395ca0a | bigcode/the-stack | train |
70829bf2dceb79dd87a77f04 | train | function | def force_unicode(s, encoding='utf-8', errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
"""
# Handle the common case first, saves 30-40% when s is an instance of
# six.text_type. This function gets called often in ... | def force_unicode(s, encoding='utf-8', errors='strict'):
| """
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
"""
# Handle the common case first, saves 30-40% when s is an instance of
# six.text_type. This function gets called often in that setting.
if isinstance(s, six.text_type):
... | '
attrs_text = ''.join(starmap(attr.format, attrs.items()))
# Make replaces
return re.sub(combined_re, repl, force_unicode(text))
def escape_url(url):
return url.replace('&', '&')
def force_unicode(s, encoding='utf-8', errors='strict'):
| 65 | 65 | 219 | 15 | 50 | hackatbrown/2015.hackatbrown.org | hack-at-brown-2015/autolink.py | Python | force_unicode | force_unicode | 103 | 125 | 103 | 103 | bdf477be537500dafb87b4851b9560cf01f15dfd | bigcode/the-stack | train |
0af2a4b6050e98f67e8b0da7 | train | function | def linkify(text, attrs={}):
"""
Convert URL-like and email-like strings into links.
"""
def separate_parentheses(s):
start = re_find(r'^\(*', s)
end = re_find(r'\)*$', s)
n = min(len(start), len(end))
if n:
return s[:n], s[n:-n], s[-n:]
else:
... | def linkify(text, attrs={}):
| """
Convert URL-like and email-like strings into links.
"""
def separate_parentheses(s):
start = re_find(r'^\(*', s)
end = re_find(r'\)*$', s)
n = min(len(start), len(end))
if n:
return s[:n], s[n:-n], s[-n:]
else:
return '', s, ''
def... | -9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6})\.? # domain
"""
combined_re = re.compile("(?P<url>{0})|(?P<email>{1})".format(url_re, email_re),
re.IGNORECASE | re.MULTILINE | re.VERBOSE | re.UNICODE)
def linkify(text, attrs={}):
| 97 | 97 | 324 | 8 | 89 | hackatbrown/2015.hackatbrown.org | hack-at-brown-2015/autolink.py | Python | linkify | linkify | 53 | 96 | 53 | 53 | 6a672e3753050aae36ff50e16854b928ae470ab4 | bigcode/the-stack | train |
4f52cb9d31d8988be1581528 | train | class | class SupervisedGraphconsis(models.SampleAndAggregate):
"""Implementation of supervised GraphConsis."""
def __init__(self, num_classes,
placeholders, features, adj, degrees,
layer_infos, concat=True, aggregator_type="mean",
model_size="small", sigmoid_loss=False, identity_d... | class SupervisedGraphconsis(models.SampleAndAggregate):
| """Implementation of supervised GraphConsis."""
def __init__(self, num_classes,
placeholders, features, adj, degrees,
layer_infos, concat=True, aggregator_type="mean",
model_size="small", sigmoid_loss=False, identity_dim=0, num_re=3,
**kwargs):
'''
... | import tensorflow as tf
import models as models
import layers as layers
from aggregators import MeanAggregator, MaxPoolingAggregator, MeanPoolingAggregator, SeqAggregator, GCNAggregator
from inits import glorot, zeros
flags = tf.app.flags
FLAGS = flags.FLAGS
class SupervisedGraphconsis(models.SampleAndAggregate):
| 70 | 256 | 1,443 | 11 | 58 | YangLiangwei/DGFraud | algorithms/GraphConsis/supervised_models.py | Python | SupervisedGraphconsis | SupervisedGraphconsis | 11 | 144 | 11 | 11 | c5aa3b715359e025a958a090bc7728a36f407f5f | bigcode/the-stack | train |
cb6d71c07c7a274f1a056f41 | train | class | class TestCalculator(TestCase):
def test_add_one(self):
expected = 1
actual = Calculator.add(1)
self.assertEqual(actual, expected)
def test_add_one_and_three(self):
expected = 4
actual = Calculator.add(1, 3)
self.assertEqual(actual, expected)
| class TestCalculator(TestCase):
| def test_add_one(self):
expected = 1
actual = Calculator.add(1)
self.assertEqual(actual, expected)
def test_add_one_and_three(self):
expected = 4
actual = Calculator.add(1, 3)
self.assertEqual(actual, expected)
| from unittest import TestCase
from example import Calculator
class TestCalculator(TestCase):
| 17 | 64 | 69 | 6 | 10 | cmw278/python-template | tests/test_calculator.py | Python | TestCalculator | TestCalculator | 5 | 15 | 5 | 6 | 675de86aed3e377b2f250d8f203e04546b42484a | bigcode/the-stack | train |
34127c71621df9e73e2ef15e | train | class | class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'KitInfo', fields ['uid']
db.create_unique('rundb_kitinfo', ['uid'])
def backwards(self, orm):
# Removing unique constraint on 'KitInfo', fields ['uid']
db.delete_unique('rundb_kitinfo', [... | class Migration(SchemaMigration):
| def forwards(self, orm):
# Adding unique constraint on 'KitInfo', fields ['uid']
db.create_unique('rundb_kitinfo', ['uid'])
def backwards(self, orm):
# Removing unique constraint on 'KitInfo', fields ['uid']
db.delete_unique('rundb_kitinfo', ['uid'])
models = {
'a... | # Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| 55 | 256 | 19,880 | 6 | 48 | konradotto/TS | dbReports/iondb/rundb/migrations/0109_auto__add_unique_kitinfo_uid.py | Python | Migration | Migration | 9 | 962 | 9 | 10 | b7a883d4340a305d8cd0b945a404a11670a5d0f4 | bigcode/the-stack | train |
053e744ce5c2a1cc0fe82c10 | train | function | def TestDeclarations():
t = CT.SetUp(TEST_FILE)
for (i, description) in enumerate(test_descriptions):
ConvertDeclaration.description = "Test `%s`"%(description.strip())
yield ConvertDeclaration, t.ext[i]
| def TestDeclarations():
| t = CT.SetUp(TEST_FILE)
for (i, description) in enumerate(test_descriptions):
ConvertDeclaration.description = "Test `%s`"%(description.strip())
yield ConvertDeclaration, t.ext[i]
| correct (yet)."""
from __future__ import absolute_import
from . import c_test_utils as CT
TEST_FILE = "declarations.c"
test_descriptions = open("%s/%s"%(CT.RELATIVE_TEST_PATH, TEST_FILE)).readlines()
ConvertDeclaration = CT.ConvertTree
def TestDeclarations():
| 64 | 64 | 49 | 4 | 59 | spranesh/Redhawk | redhawk/test/test_c_declarations.py | Python | TestDeclarations | TestDeclarations | 18 | 22 | 18 | 18 | e2a67ad38abf7398c35d2954c9a288c76cddf941 | bigcode/the-stack | train |
f4070532a16dcc1ebfd6d58c | train | function | def date_format(date):
return date.strftime('%d/%m/%Y')
| def date_format(date):
| return date.strftime('%d/%m/%Y')
| def currency_format(num):
return f'R$ {num:,.2f}'. \
replace(",", ".", 1)[::-1]. \
replace(".", ",", 1)[::-1]
def date_format(date):
| 46 | 64 | 16 | 5 | 41 | JuanFariasGit/crm | ultils/ultils.py | Python | date_format | date_format | 7 | 8 | 7 | 7 | 1e84ae6ecb4110734d7d2269e9f5b4d4724b95a5 | bigcode/the-stack | train |
31c796c84ad6c09f4a43e9e3 | train | function | def porcent_format(num):
return f'{num*100:.2f}%'.replace('.', ',')
| def porcent_format(num):
| return f'{num*100:.2f}%'.replace('.', ',')
| def currency_format(num):
return f'R$ {num:,.2f}'. \
replace(",", ".", 1)[::-1]. \
replace(".", ",", 1)[::-1]
def date_format(date):
return date.strftime('%d/%m/%Y')
def porcent_format(num):
| 63 | 64 | 21 | 5 | 58 | JuanFariasGit/crm | ultils/ultils.py | Python | porcent_format | porcent_format | 11 | 12 | 11 | 11 | f5e3c3b8a32a945d3f0e747fbf7df3ef20f6eb96 | bigcode/the-stack | train |
5d4333686bcc6a83c61ec9da | train | function | def currency_format(num):
return f'R$ {num:,.2f}'. \
replace(",", ".", 1)[::-1]. \
replace(".", ",", 1)[::-1]
| def currency_format(num):
| return f'R$ {num:,.2f}'. \
replace(",", ".", 1)[::-1]. \
replace(".", ",", 1)[::-1]
| def currency_format(num):
| 5 | 64 | 41 | 5 | 0 | JuanFariasGit/crm | ultils/ultils.py | Python | currency_format | currency_format | 1 | 4 | 1 | 1 | de9d68de60a256b7332a067654800bd3216f2001 | bigcode/the-stack | train |
721a31bf829c2b23d9745374 | train | function | def FreeLocator():
import geopy
return geopy.Photon(user_agent='myGeocoder')
| def FreeLocator():
| import geopy
return geopy.Photon(user_agent='myGeocoder')
| /wiki/Geographic_coordinate_system) but we have difficulties remembering [latitudes]( https://en.wikipedia.org/wiki/Latitude) and [longitudes]( https://en.wikipedia.org/wiki/Longitude).
#
# We learn and remember the world better from addresses.
#
# In[6]:
def FreeLocator():
| 64 | 64 | 23 | 4 | 60 | jckantor/MO-book | _build/jupyter_execute/notebooks/04/shortest-path-on-road-networks.py | Python | FreeLocator | FreeLocator | 104 | 106 | 104 | 104 | 45d402be15ac0fc8248bfce9af04c02c6315046d | bigcode/the-stack | train |
0695826b2fdcf944ced85c7d | train | function | def Locate_geopy(description):
location = FreeLocator().geocode(description)
if location is not None:
return location.latitude, location.longitude
return None,None
| def Locate_geopy(description):
| location = FreeLocator().geocode(description)
if location is not None:
return location.latitude, location.longitude
return None,None
| Geocoder')
# In[7]:
Amsterdam = FreeLocator().geocode('Amsterdam,NL')
# # Visualization
# In[8]:
import folium
Map = folium.Map(location=(Amsterdam.latitude,Amsterdam.longitude), zoom_start=12)
Map
# In[9]:
def Locate_geopy(description):
| 64 | 64 | 36 | 6 | 58 | jckantor/MO-book | _build/jupyter_execute/notebooks/04/shortest-path-on-road-networks.py | Python | Locate_geopy | Locate_geopy | 128 | 132 | 128 | 128 | 82861e65a8628d08c549fe077cfdf1ec3e4c1ab7 | bigcode/the-stack | train |
267271b956cf6c07aa541ce8 | train | function | def GetListOfInstalledPackages():
import subprocess, sys
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
return [r.decode().split('==')[0] for r in reqs.split()]
| def GetListOfInstalledPackages():
| import subprocess, sys
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
return [r.decode().split('==')[0] for r in reqs.split()]
| Contraction_hierarchies).
#
# Finally, I mention [Fletcher Foti]( https://fletcherfoti.weebly.com/) who gave us [pandana]( http://udst.github.io/pandana/).
#
#
# In[2]:
def GetListOfInstalledPackages():
| 64 | 64 | 53 | 7 | 57 | jckantor/MO-book | _build/jupyter_execute/notebooks/04/shortest-path-on-road-networks.py | Python | GetListOfInstalledPackages | GetListOfInstalledPackages | 55 | 58 | 55 | 55 | dc70d2cf167d1616b8c7c271c93e19c1d856c625 | bigcode/the-stack | train |
6935769ab4fc5b2b7547f364 | train | class | class Migration(migrations.Migration):
dependencies = [
('contract_scanner', '0005_remove_contract_scanned'),
]
operations = [
migrations.RemoveField(
model_name='contract',
name='status',
),
migrations.AddField(
model_name='contract',
... | class Migration(migrations.Migration):
| dependencies = [
('contract_scanner', '0005_remove_contract_scanned'),
]
operations = [
migrations.RemoveField(
model_name='contract',
name='status',
),
migrations.AddField(
model_name='contract',
name='available',
... | # Generated by Django 2.0.5 on 2018-08-27 22:47
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 81 | 7 | 30 | kimnnmadsen/eve-abyssal-market | contract_scanner/migrations/0006_available_as_bool.py | Python | Migration | Migration | 6 | 22 | 6 | 7 | 787aea0e640950bf68ef81bfe011bcca02587448 | bigcode/the-stack | train |
13f17829bbf1990ba70bb996 | train | function | async def test_select_schedule_thermostats(hass, config_entry, caplog, netatmo_auth):
"""Test service for selecting Netatmo schedule with thermostats."""
with selected_platforms(["climate", "select"]):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done... | async def test_select_schedule_thermostats(hass, config_entry, caplog, netatmo_auth):
| """Test service for selecting Netatmo schedule with thermostats."""
with selected_platforms(["climate", "select"]):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
webhook_id = config_entry.data[CONF_WEBHOOK_ID]
select_entity = "select.ne... | """The tests for the Netatmo climate platform."""
from unittest.mock import patch
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
from homeassistant.components.select.const import ATTR_OPTION, ATTR_OPTIONS
from homeassistant.const import ATTR_ENTITY_ID, CONF_WEBHOOK_ID, SERVICE_SELECT_OPTION
from ... | 94 | 139 | 465 | 23 | 70 | MrDelik/core | tests/components/netatmo/test_select.py | Python | test_select_schedule_thermostats | test_select_schedule_thermostats | 11 | 66 | 11 | 11 | dc7c581fc5c413caa55bd106c873a20070909db5 | bigcode/the-stack | train |
da22b4274833ceab1d2fa01b | train | function | def api_inputmodel(api: str, model: BaseModel, servicename: str,
service_logger: logger) -> Callable:
"""
Decorator to be used in api-methods to convert the request-data
to an instance of the passed `model`. This instance is passed to the
decorated api-endpoint as the parameter `servi... | def api_inputmodel(api: str, model: BaseModel, servicename: str,
service_logger: logger) -> Callable:
| """
Decorator to be used in api-methods to convert the request-data
to an instance of the passed `model`. This instance is passed to the
decorated api-endpoint as the parameter `service_params`.
# Parameters
model (BaseModel): The pydantic-model to use to convert the
request-dat... | application/json',
description=out_description)
@wraps(func)
async def function_wrapper(request, *args, **kwargs):
return await func(request=request, *args, **kwargs)
return function_wrapper
return decorator
def api_inputmodel(api: str, model: BaseModel, s... | 77 | 77 | 257 | 27 | 49 | skallfass/scwoaservices_conda | scwoaservices/decorators.py | Python | api_inputmodel | api_inputmodel | 114 | 148 | 114 | 115 | 136cfb647d00b9b264ee8a442bc0d3579b61c172 | bigcode/the-stack | train |
4e4416d57b571186a5264b14 | train | function | def api_documentation(api: str, summary: str, in_model: BaseModel,
out_model: BaseModel, out_description: str) -> Callable:
"""
Decorator to be used in api-methods to serve the swagger-documentation for
this api.
# Parameters
api (str): the route to the api.
summar... | def api_documentation(api: str, summary: str, in_model: BaseModel,
out_model: BaseModel, out_description: str) -> Callable:
| """
Decorator to be used in api-methods to serve the swagger-documentation for
this api.
# Parameters
api (str): the route to the api.
summary (str): the summary-description for the api.
in_model (BaseModel): the InputModel to be used to transform the
request-data.
... | """
from dataclasses import make_dataclass
from functools import wraps
from typing import Callable
from typing import Optional
from pydantic import BaseModel
from pydantic import ValidationError
from sanic import response
from sanic.blueprints import Blueprint
from sanic.exceptions import ServerError
from sanic.log i... | 132 | 132 | 443 | 33 | 98 | skallfass/scwoaservices_conda | scwoaservices/decorators.py | Python | api_documentation | api_documentation | 57 | 111 | 57 | 58 | 279c0dda5eb730723dc98ea20d1c02de7c308b32 | bigcode/the-stack | train |
62b97750dc7fd5e2dae98680 | train | function | def api_outputmodel(api: str, model: BaseModel, servicename: str,
service_logger: logger) -> Callable:
"""
Decorator to be used in api-methods to convert the response-data of the
decorated api-method to a json based on the passed `model`.
# Parameters
model (BaseModel): The ... | def api_outputmodel(api: str, model: BaseModel, servicename: str,
service_logger: logger) -> Callable:
| """
Decorator to be used in api-methods to convert the response-data of the
decorated api-method to a json based on the passed `model`.
# Parameters
model (BaseModel): The pydantic-model to use to convert the
response data of the decorated api-method.
# Returns
decorato... | conditionFailed(msg, status_code=412)
result = await func(request=request,
service_params=service_params,
service_logger=service_logger,
*args,
**kwargs)
return result
... | 79 | 79 | 264 | 27 | 51 | skallfass/scwoaservices_conda | scwoaservices/decorators.py | Python | api_outputmodel | api_outputmodel | 151 | 186 | 151 | 152 | 1f2d594300e94893826fce1bdf3054beb61e0e13 | bigcode/the-stack | train |
265127a8de7a5b065a0d773f | train | function | def env_start(): # returns NumPy array
return this_reward_observation[1]
| def env_start(): # returns NumPy array
| return this_reward_observation[1]
| 0.0, 1.0) # set the means of reward value
local_observation = np.zeros(0) # An empty NumPy array
this_reward_observation = (0.0, local_observation, False)
def env_start(): # returns NumPy array
| 64 | 64 | 20 | 11 | 53 | yfe3/Intelligent-Systems | Dynamic Programming Agent/w1_env.py | Python | env_start | env_start | 43 | 44 | 43 | 43 | 5cb7d2a9a8415a32cd8118ce507b0bed5d63f65f | bigcode/the-stack | train |
666df7dc2351d199f51d9448 | train | function | def env_init():
global this_reward_observation
global bandit
# intialize the reward of each action here
bandit = np.zeros(10) # set the bandit to 10 armed
for loop_control in range(0, 10, 1):
bandit[loop_control] = rand_norm(0.0, 1.0) # set the means of reward value
local_observatio... | def env_init():
| global this_reward_observation
global bandit
# intialize the reward of each action here
bandit = np.zeros(10) # set the bandit to 10 armed
for loop_control in range(0, 10, 1):
bandit[loop_control] = rand_norm(0.0, 1.0) # set the means of reward value
local_observation = np.zeros(0) ... | , Boolean)
bandit = None
def find_optimal(bandit): #pass the test working properly
optimal = np.argmax(bandit) # find the optimal action
#print(optimal,"this is optimal") #for debuggging use
return optimal
def env_init():
| 64 | 64 | 126 | 4 | 59 | yfe3/Intelligent-Systems | Dynamic Programming Agent/w1_env.py | Python | env_init | env_init | 28 | 40 | 28 | 28 | f9b8282e94fd6d07e2d2583215005421586c0d85 | bigcode/the-stack | train |
997a528b962bc5b459ed82f6 | train | function | def env_step(this_action): # returns (floating point, NumPy array, Boolean), this_action: NumPy array
global this_reward_observation
global bandit
# the_reward = rand_norm(0.0, 1.0) # rewards drawn from (0, 1) Gaussian
# now we return reward according to the action
this_action_int = this_action.... | def env_step(this_action): # returns (floating point, NumPy array, Boolean), this_action: NumPy array
| global this_reward_observation
global bandit
# the_reward = rand_norm(0.0, 1.0) # rewards drawn from (0, 1) Gaussian
# now we return reward according to the action
this_action_int = this_action.tolist()
the_reward = rand_norm(bandit[this_action_int], 1.0) # set the reward value
this_r... |
this_reward_observation = (0.0, local_observation, False)
def env_start(): # returns NumPy array
return this_reward_observation[1]
def env_step(this_action): # returns (floating point, NumPy array, Boolean), this_action: NumPy array
| 64 | 64 | 139 | 26 | 38 | yfe3/Intelligent-Systems | Dynamic Programming Agent/w1_env.py | Python | env_step | env_step | 47 | 61 | 47 | 47 | eac1dffa2a85c9dc1caa7b80d4a2a4f5e4b237de | bigcode/the-stack | train |
977274a138c1740d5f8a59f4 | train | function | def env_cleanup():
#
return
| def env_cleanup():
#
| return
| _action_int = this_action.tolist()
the_reward = rand_norm(bandit[this_action_int], 1.0) # set the reward value
this_reward_observation = (the_reward, this_reward_observation[1], False)
return this_reward_observation
def env_cleanup():
#
| 64 | 64 | 9 | 6 | 57 | yfe3/Intelligent-Systems | Dynamic Programming Agent/w1_env.py | Python | env_cleanup | env_cleanup | 64 | 66 | 64 | 65 | 6b863fd7446795bb9fe57e63c6a0c42f8bbe75f7 | bigcode/the-stack | train |
13b51af0e602f08ae2b9ba4d | train | function | def find_optimal(bandit): #pass the test working properly
optimal = np.argmax(bandit) # find the optimal action
#print(optimal,"this is optimal") #for debuggging use
return optimal
| def find_optimal(bandit): #pass the test working properly
| optimal = np.argmax(bandit) # find the optimal action
#print(optimal,"this is optimal") #for debuggging use
return optimal
| rand_norm, rand_in_range, rand_un
import numpy as np
this_reward_observation = (None, None, None) # this_reward_observation: (floating point, NumPy array, Boolean)
bandit = None
def find_optimal(bandit): #pass the test working properly
| 64 | 64 | 52 | 15 | 48 | yfe3/Intelligent-Systems | Dynamic Programming Agent/w1_env.py | Python | find_optimal | find_optimal | 22 | 25 | 22 | 22 | 0e5e9aceec464e00f7d03fdc51b788f75246f50b | bigcode/the-stack | train |
373fb3aa4bdc5929f94d9dde | train | function | def env_message(inMessage): # returns string, inMessage: string
global bandit
if inMessage == "what is your name?":
return "my name is skeleton_environment!"
elif inMessage == "get optimal action":
global bandit
optimal = find_optimal(bandit)
return optimal
# action ... | def env_message(inMessage): # returns string, inMessage: string
| global bandit
if inMessage == "what is your name?":
return "my name is skeleton_environment!"
elif inMessage == "get optimal action":
global bandit
optimal = find_optimal(bandit)
return optimal
# action 3 gives the highest q* value; ie. argmax q*(a) = 3
# else
... | ], 1.0) # set the reward value
this_reward_observation = (the_reward, this_reward_observation[1], False)
return this_reward_observation
def env_cleanup():
#
return
def env_message(inMessage): # returns string, inMessage: string
| 64 | 64 | 112 | 16 | 47 | yfe3/Intelligent-Systems | Dynamic Programming Agent/w1_env.py | Python | env_message | env_message | 69 | 79 | 69 | 69 | 3a1770a56166c98b06b32cf2380d3693ebe2bf3c | bigcode/the-stack | train |
18935883bb16da21d4015bb9 | train | function | def main():
regression = False
size = int(1e6)
if len(sys.argv) > 1 and sys.argv[1] == "-P":
regression = True
size = 20
Qtrac.remove_if_exists(os.path.join(tempfile.gettempdir(), "point.db"))
start = time.clock()
points = []
for i in range(size):
points.append(Point(... | def main():
| regression = False
size = int(1e6)
if len(sys.argv) > 1 and sys.argv[1] == "-P":
regression = True
size = 20
Qtrac.remove_if_exists(os.path.join(tempfile.gettempdir(), "point.db"))
start = time.clock()
points = []
for i in range(size):
points.append(Point(i, i ** 2, i... | 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 atexit
import os
import shelve
import sys
import tempfile
import time
import Qtrac
def main():
| 64 | 64 | 173 | 3 | 60 | iceihehe/pipeg | python3/pointstore2.py | Python | main | main | 21 | 37 | 21 | 21 | 95ca35746533e205dbcdef82fec1737fcbfc8cea | bigcode/the-stack | train |
01c33d9b4493c22a84cf738e | train | class | class Point:
__slots__ = ()
__dbm = shelve.open(os.path.join(tempfile.gettempdir(), "point.db"))
def __init__(self, x=0, y=0, z=0, color=None):
self.x = x
self.y = y
self.z = z
self.color = color
def __key(self, name):
return "{:X}:{}".format(id(self), name)
... | class Point:
| __slots__ = ()
__dbm = shelve.open(os.path.join(tempfile.gettempdir(), "point.db"))
def __init__(self, x=0, y=0, z=0, color=None):
self.x = x
self.y = y
self.z = z
self.color = color
def __key(self, name):
return "{:X}:{}".format(id(self), name)
def __ge... | [size - 1].x == size - 1
print(len(points))
if not regression: # wait until we can see how much memory is used
print("took {} secs to create {:,} points".format(end, size))
input("press Enter to finish")
class Point:
| 64 | 64 | 194 | 3 | 61 | iceihehe/pipeg | python3/pointstore2.py | Python | Point | Point | 40 | 68 | 40 | 41 | 48feb212fed008157b61cf2b3652719a97715b80 | bigcode/the-stack | train |
1b07430c76e0c2044e769cd0 | train | class | class TestGroupOsError(TestUpper):
@classmethod
def setUpClass(self):
self._file_path = 'data/examples/example_group_constraint.yaml'
self._new_path = 'data/examples/example_group_constraint.'\
'completed.yaml'
self._mock_responces = {}
self._node_templa... | class TestGroupOsError(TestUpper):
@classmethod
| def setUpClass(self):
self._file_path = 'data/examples/example_group_constraint.yaml'
self._new_path = 'data/examples/example_group_constraint.'\
'completed.yaml'
self._mock_responces = {}
self._node_templates = yaml.load('')
# TODO: check the specific e... | import yaml
from toskeriser.exceptions import TkStackException
from .test_upper import TestUpper
class TestGroupOsError(TestUpper):
@classmethod
| 33 | 64 | 146 | 12 | 20 | Tosca-Projects/TosKeriser | tests/test_group_contraint.py | Python | TestGroupOsError | TestGroupOsError | 8 | 29 | 8 | 10 | a518eeeab2de629080e7b2fdf9512a926b5b72d2 | bigcode/the-stack | train |
7223695c550786e347df63dd | train | function | def main():
prev_line_no = None
for line in sys.stdin:
line = line[:-1]
match = re.match(r'^H-(\d+)', line)
if not match:
continue
tokens = line.split('\t')[2].split(' ')
text = ''.join(tokens)
text = join_jamos(text)
line_no = int(match.group(... | def main():
| prev_line_no = None
for line in sys.stdin:
line = line[:-1]
match = re.match(r'^H-(\d+)', line)
if not match:
continue
tokens = line.split('\t')[2].split(' ')
text = ''.join(tokens)
text = join_jamos(text)
line_no = int(match.group(1))
... | distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import sys
from hangul_utils import join_jamos
def main():
| 64 | 64 | 134 | 3 | 60 | paulhkim80/TKOrrector | src/format_fairseq_output.py | Python | main | main | 19 | 34 | 19 | 19 | acd6945ca0ac8071747714e143a132c6e72930a7 | bigcode/the-stack | train |
da2aed7e15e7c38e733e589d | train | class | class BenchmarkRunner:
def __init__(self, data: TestData, window_size: int, sampling_count: int, result_path: str, result_format: str):
self._data = data
self._window_size = window_size
self._sampling_count = sampling_count
self._result_path = result_path
self._result_format ... | class BenchmarkRunner:
| def __init__(self, data: TestData, window_size: int, sampling_count: int, result_path: str, result_format: str):
self._data = data
self._window_size = window_size
self._sampling_count = sampling_count
self._result_path = result_path
self._result_format = result_format
de... | from ndarray_access_benchmark.benchmarks.random_access import RandomAccess
from ndarray_access_benchmark.test_data import TestData
import csv
RANDOM_ACCESS = 'random_access'
CSV_HEADER = ['id', 'accessed_index', 'elapsed_time', 'read_data_size', 'throughput']
class BenchmarkRunner:
| 64 | 84 | 280 | 4 | 60 | serihiro/ndarray_access_benchmark | ndarray_access_benchmark/benchmark_runner.py | Python | BenchmarkRunner | BenchmarkRunner | 9 | 40 | 9 | 9 | 6b72db953b5099c609c95fe676bad6e453fb28a0 | bigcode/the-stack | train |
52f76d2efbf49e9ee771e5ff | train | function | def generateNuitkaLoaderCreationCode(to_name, expression, emit, context):
with withObjectCodeTemporaryAssignment(
to_name, "nuitka_loader_value", expression, emit, context
) as result_name:
emit("%s = Nuitka_Loader_New(loader_entry);" % result_name)
| def generateNuitkaLoaderCreationCode(to_name, expression, emit, context):
| with withObjectCodeTemporaryAssignment(
to_name, "nuitka_loader_value", expression, emit, context
) as result_name:
emit("%s = Nuitka_Loader_New(loader_entry);" % result_name)
| _name=to_name,
variable=expression.getVariable(),
variable_trace=None,
needs_check=False,
conversion_check=decideConversionCheckNeeded(to_name, expression),
emit=emit,
context=context,
)
def generateNuitkaLoaderCreationCode(to_name, expression, emit, context):
| 64 | 64 | 65 | 17 | 47 | kamgha/Nuitka | nuitka/codegen/ModuleCodes.py | Python | generateNuitkaLoaderCreationCode | generateNuitkaLoaderCreationCode | 175 | 179 | 175 | 175 | 5fe0ed836dc1b9cb95c33810108fa57692d677f7 | bigcode/the-stack | train |
9a3fefecea9016cc9eb52034 | train | function | def generateModuleAttributeFileCode(to_name, expression, emit, context):
# TODO: Special treatment justified?
with withObjectCodeTemporaryAssignment(
to_name, "module_fileattr_value", expression, emit, context
) as result_name:
emit("%s = module_filename_obj;" % result_name)
| def generateModuleAttributeFileCode(to_name, expression, emit, context):
# TODO: Special treatment justified?
| with withObjectCodeTemporaryAssignment(
to_name, "module_fileattr_value", expression, emit, context
) as result_name:
emit("%s = module_filename_obj;" % result_name)
| "module_code_objects_init": indented(module_code_objects_init, 1),
"constants_count": context.getConstantsCount(),
"module_const_blob_name": module_const_blob_name,
}
def generateModuleAttributeFileCode(to_name, expression, emit, context):
# TODO: Special treatment justified?
| 64 | 64 | 66 | 23 | 41 | kamgha/Nuitka | nuitka/codegen/ModuleCodes.py | Python | generateModuleAttributeFileCode | generateModuleAttributeFileCode | 155 | 160 | 155 | 156 | 2cc877400458c0986d51c326598286685912c3f4 | bigcode/the-stack | train |
5f3f4d365d32a64b363ccf7b | train | function | def generateModuleAttributeCode(to_name, expression, emit, context):
getVariableReferenceCode(
to_name=to_name,
variable=expression.getVariable(),
variable_trace=None,
needs_check=False,
conversion_check=decideConversionCheckNeeded(to_name, expression),
emit=emit,
... | def generateModuleAttributeCode(to_name, expression, emit, context):
| getVariableReferenceCode(
to_name=to_name,
variable=expression.getVariable(),
variable_trace=None,
needs_check=False,
conversion_check=decideConversionCheckNeeded(to_name, expression),
emit=emit,
context=context,
)
| # TODO: Special treatment justified?
with withObjectCodeTemporaryAssignment(
to_name, "module_fileattr_value", expression, emit, context
) as result_name:
emit("%s = module_filename_obj;" % result_name)
def generateModuleAttributeCode(to_name, expression, emit, context):
| 64 | 64 | 69 | 14 | 50 | kamgha/Nuitka | nuitka/codegen/ModuleCodes.py | Python | generateModuleAttributeCode | generateModuleAttributeCode | 163 | 172 | 163 | 163 | ff626568d260f7c8732cf2ceda2fbfc60fdab4e2 | bigcode/the-stack | train |
7fdc9292862f75337957c8b7 | train | function | def getModuleAccessCode(context):
return "module_%s" % context.getModuleCodeName()
| def getModuleAccessCode(context):
| return "module_%s" % context.getModuleCodeName()
| Indentation import indented
from .templates.CodeTemplatesModules import (
template_global_copyright,
template_module_body_template,
template_module_exception_exit,
template_module_external_entry_point,
template_module_no_exception_exit,
)
from .VariableCodes import getVariableReferenceCode
def getMo... | 64 | 64 | 21 | 7 | 56 | kamgha/Nuitka | nuitka/codegen/ModuleCodes.py | Python | getModuleAccessCode | getModuleAccessCode | 44 | 45 | 44 | 44 | 26572a00e4ae6500e132b5e99faf691879b785c1 | bigcode/the-stack | train |
4dda28954073f3896d7214b4 | train | function | def getModuleCode(
module, function_decl_codes, function_body_codes, module_const_blob_name, context
):
# For the module code, lots of arguments and attributes come together.
# pylint: disable=too-many-locals
# Temporary variable initializations
# TODO: Move that to a place outside of functions.
... | def getModuleCode(
module, function_decl_codes, function_body_codes, module_const_blob_name, context
):
# For the module code, lots of arguments and attributes come together.
# pylint: disable=too-many-locals
# Temporary variable initializations
# TODO: Move that to a place outside of functions.
| from .FunctionCodes import (
finalizeFunctionLocalVariables,
setupFunctionLocalVariables,
)
setupFunctionLocalVariables(
context=context,
parameters=None,
closure_variables=(),
user_variables=module.getOutlineLocalVariables(),
temp_variables=module.ge... | import Options
from nuitka.__past__ import iterItems
from nuitka.codegen import Emission
from nuitka.Version import getNuitkaVersion, getNuitkaVersionYear
from .CodeHelpers import (
decideConversionCheckNeeded,
generateStatementSequenceCode,
withObjectCodeTemporaryAssignment,
)
from .CodeObjectCodes impor... | 234 | 234 | 782 | 71 | 163 | kamgha/Nuitka | nuitka/codegen/ModuleCodes.py | Python | getModuleCode | getModuleCode | 48 | 152 | 48 | 56 | b7a6f18cb9c2f4217da6329703cab898e488fcc7 | bigcode/the-stack | train |
a7e2ca9807e16b7728fc446e | train | class | class TestEmail(unittest.TestCase):
def setUp(self):
frappe.db.sql("""update tabUser set unsubscribed=0""")
frappe.db.sql("""delete from `tabBulk Email`""")
def test_send(self):
from frappe.email import sendmail
#sendmail('test@example.com', subject='Test Mail', msg="Test Content")
def test_bulk(self):
f... | class TestEmail(unittest.TestCase):
| def setUp(self):
frappe.db.sql("""update tabUser set unsubscribed=0""")
frappe.db.sql("""delete from `tabBulk Email`""")
def test_send(self):
from frappe.email import sendmail
#sendmail('test@example.com', subject='Test Mail', msg="Test Content")
def test_bulk(self):
from frappe.email.bulk import send
... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import os, sys
import unittest, frappe
from frappe.test_runner import make_test_records
make_test_records("User")
make_test_records("Email Account")
class TestEmail(unittest.... | 74 | 191 | 637 | 7 | 67 | Steggur/frappe | frappe/tests/test_email.py | Python | TestEmail | TestEmail | 13 | 72 | 13 | 13 | 170fb992de897d9339a9c1bb2f84c02dfb0c16b5 | bigcode/the-stack | train |
9515263132965950776dc146 | train | class | class TxnMallTest(Mk2xTestFramework):
def set_test_params(self):
self.num_nodes = 4
def add_options(self, parser):
parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true",
help="Test double-spend of 1-confirmed transaction")
def setu... | class TxnMallTest(Mk2xTestFramework):
| def set_test_params(self):
self.num_nodes = 4
def add_options(self, parser):
parser.add_option("--mineblock", dest="mine_block", default=False, action="store_true",
help="Test double-spend of 1-confirmed transaction")
def setup_network(self):
# Start with ... | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet accounts properly when there are cloned transactions with malleated scriptsigs."""
fro... | 98 | 256 | 1,918 | 12 | 86 | mk2crypto/MK2 | test/functional/wallet_txn_clone.py | Python | TxnMallTest | TxnMallTest | 10 | 155 | 10 | 10 | 5babb495055d57ec65cf307e4b5b4ff07a27a0ad | bigcode/the-stack | train |
2ba9988db8ff982f36d50826 | train | function | def gradients(weights, X_batch, y_batch):
"""
勾配を計算する関数のダミー
"""
return np.random.randn(weights.shape[0])
| def gradients(weights, X_batch, y_batch):
| """
勾配を計算する関数のダミー
"""
return np.random.randn(weights.shape[0])
| import numpy as np
def gradients(weights, X_batch, y_batch):
| 15 | 64 | 40 | 10 | 4 | skillup-ai/tettei-engineer | chapter19/Q12.py | Python | gradients | gradients | 3 | 7 | 3 | 3 | 3a2c09b42c7a3e1be848a89d4ccf45516893a0c9 | bigcode/the-stack | train |
f343774f7c6ad977e2f44f44 | train | function | def main(X_train, y_train):
epoch = 100 # エポック数
batch_size = 32
learning_rate = 0.01
# 訓練データの数を取得
train_size = X_train.shape[0]
# 1エポックにおけるイテレーションの回数を計算
iter_per_epoch = max(train_size//batch_size, 1)
# パラメータの初期化
weights = np.random.randn(X_train.shape[1])
# 学習
for i in ... | def main(X_train, y_train):
| epoch = 100 # エポック数
batch_size = 32
learning_rate = 0.01
# 訓練データの数を取得
train_size = X_train.shape[0]
# 1エポックにおけるイテレーションの回数を計算
iter_per_epoch = max(train_size//batch_size, 1)
# パラメータの初期化
weights = np.random.randn(X_train.shape[1])
# 学習
for i in range(epoch):
# 訓練デー... | import numpy as np
def gradients(weights, X_batch, y_batch):
"""
勾配を計算する関数のダミー
"""
return np.random.randn(weights.shape[0])
def main(X_train, y_train):
| 52 | 100 | 335 | 8 | 44 | skillup-ai/tettei-engineer | chapter19/Q12.py | Python | main | main | 9 | 42 | 9 | 9 | e51df4dcea703d985e7352a4ce426d91b9020e80 | bigcode/the-stack | train |
ae6b9d15f7c4c1199f931ece | train | function | def contains(cat, key, container):
"""
Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``conta... | def contains(cat, key, container):
| """
Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``container``.
Parameters
-------... | # allow categorical vs object dtype array comparisons for equality
# these are only positional comparisons
if opname in ["__eq__", "__ne__"]:
return getattr(np.array(self), opname)(np.array(other))
raise TypeError(
f"Cannot compare a Categ... | 119 | 119 | 397 | 8 | 110 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | contains | contains | 144 | 192 | 144 | 144 | 614f30220483403d48186546c3ebfa13fd458402 | bigcode/the-stack | train |
d4286e75e7b81240768bd4f8 | train | function | def recode_for_categories(codes: np.ndarray, old_categories, new_categories):
"""
Convert a set of codes for to a new set of categories
Parameters
----------
codes : np.ndarray
old_categories, new_categories : Index
Returns
-------
new_codes : np.ndarray[np.int64]
Examples
... | def recode_for_categories(codes: np.ndarray, old_categories, new_categories):
| """
Convert a set of codes for to a new set of categories
Parameters
----------
codes : np.ndarray
old_categories, new_categories : Index
Returns
-------
new_codes : np.ndarray[np.int64]
Examples
--------
>>> old_cat = pd.Index(['b', 'a', 'c'])
>>> new_cat = pd.Ind... | )
categories = ensure_object(categories)
hash_klass, vals = _get_data_algo(values)
_, cats = _get_data_algo(categories)
t = hash_klass(len(cats))
t.map_locations(cats)
return coerce_indexer_dtype(t.lookup(vals), cats)
def recode_for_categories(codes: np.ndarray, old_categories, new_categori... | 78 | 78 | 261 | 17 | 61 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | recode_for_categories | recode_for_categories | 2,612 | 2,643 | 2,612 | 2,612 | afa3adee62578555a390d05d0d69aaa752cda32c | bigcode/the-stack | train |
f394c00aa1097df0b86280dc | train | function | def _get_codes_for_values(values, categories):
"""
utility routine to turn values into codes given the specified categories
"""
dtype_equal = is_dtype_equal(values.dtype, categories.dtype)
if is_extension_array_dtype(categories.dtype) and is_object_dtype(values):
# Support inferring the cor... | def _get_codes_for_values(values, categories):
| """
utility routine to turn values into codes given the specified categories
"""
dtype_equal = is_dtype_equal(values.dtype, categories.dtype)
if is_extension_array_dtype(categories.dtype) and is_object_dtype(values):
# Support inferring the correct extension dtype from an array of
#... | **kwargs):
from pandas import Series
method = getattr(self._parent, name)
res = method(*args, **kwargs)
if res is not None:
return Series(res, index=self._index, name=self._name)
# utility routines
def _get_codes_for_values(values, categories):
| 65 | 65 | 218 | 10 | 54 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | _get_codes_for_values | _get_codes_for_values | 2,585 | 2,609 | 2,585 | 2,585 | 8a4413762d11dc6b2cb72273aa8a12a637242b33 | bigcode/the-stack | train |
e0f7e58374aa244b8a759398 | train | function | def factorize_from_iterable(values):
"""
Factorize an input `values` into `categories` and `codes`. Preserves
categorical dtype in `categories`.
*This is an internal function*
Parameters
----------
values : list-like
Returns
-------
codes : ndarray
categories : Index
... | def factorize_from_iterable(values):
| """
Factorize an input `values` into `categories` and `codes`. Preserves
categorical dtype in `categories`.
*This is an internal function*
Parameters
----------
values : list-like
Returns
-------
codes : ndarray
categories : Index
If `values` has a categorical dtyp... | , "dtype"):
return list_like
if isinstance(list_like, list):
return list_like
if is_sequence(list_like) or isinstance(list_like, tuple) or is_iterator(list_like):
return list(list_like)
elif is_scalar(list_like):
return [list_like]
else:
# TODO: is this reached?
... | 86 | 86 | 289 | 8 | 78 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | factorize_from_iterable | factorize_from_iterable | 2,660 | 2,695 | 2,660 | 2,660 | fc57cf0044e8ad2565741d5cc39f45e4fac4575e | bigcode/the-stack | train |
499c829e993b690f733bd402 | train | class | class Categorical(NDArrayBackedExtensionArray, PandasObject):
"""
Represent a categorical variable in classic R / S-plus fashion.
`Categoricals` can only take on only a limited, and usually fixed, number
of possible values (`categories`). In contrast to statistical categorical
variables, a `Categor... | class Categorical(NDArrayBackedExtensionArray, PandasObject):
| """
Represent a categorical variable in classic R / S-plus fashion.
`Categoricals` can only take on only a limited, and usually fixed, number
of possible values (`categories`). In contrast to statistical categorical
variables, a `Categorical` might have an order, but numerical operations
(addit... | `` is in ``self.categories`` and location of
``key`` in ``categories`` is in ``container``, else False.
Notes
-----
This method does not check for NaN values. Do that separately
before calling this method.
"""
hash(key)
# get location of key in categories.
# If a KeyError, the ... | 256 | 256 | 16,170 | 15 | 241 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | Categorical | Categorical | 195 | 2,413 | 195 | 195 | a138fa85516d6ca0723e7aa8088651598383e85b | bigcode/the-stack | train |
a34702cd28fcd370a4f2f03f | train | function | def _convert_to_list_like(list_like):
if hasattr(list_like, "dtype"):
return list_like
if isinstance(list_like, list):
return list_like
if is_sequence(list_like) or isinstance(list_like, tuple) or is_iterator(list_like):
return list(list_like)
elif is_scalar(list_like):
r... | def _convert_to_list_like(list_like):
| if hasattr(list_like, "dtype"):
return list_like
if isinstance(list_like, list):
return list_like
if is_sequence(list_like) or isinstance(list_like, tuple) or is_iterator(list_like):
return list(list_like)
elif is_scalar(list_like):
return [list_like]
else:
# ... | ode
return codes.copy()
indexer = coerce_indexer_dtype(
new_categories.get_indexer(old_categories), new_categories
)
new_codes = take_1d(indexer, codes.copy(), fill_value=-1)
return new_codes
def _convert_to_list_like(list_like):
| 64 | 64 | 92 | 9 | 54 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | _convert_to_list_like | _convert_to_list_like | 2,646 | 2,657 | 2,646 | 2,646 | 7d657fc927cb9b11dfdd05dc8bc4bf8074a3418e | bigcode/the-stack | train |
5ab2fd41e4d40c4ae9e30778 | train | class | @delegate_names(
delegate=Categorical, accessors=["categories", "ordered"], typ="property"
)
@delegate_names(
delegate=Categorical,
accessors=[
"rename_categories",
"reorder_categories",
"add_categories",
"remove_categories",
"remove_unused_categories",
"set_c... | @delegate_names(
delegate=Categorical, accessors=["categories", "ordered"], typ="property"
)
@delegate_names(
delegate=Categorical,
accessors=[
"rename_categories",
"reorder_categories",
"add_categories",
"remove_categories",
"remove_unused_categories",
"set_c... | """
Accessor object for categorical properties of the Series values.
Be aware that assigning to `categories` is a inplace operation, while all
methods return new categorical data per default (but can be called with
`inplace=True`).
Parameters
----------
data : Series or CategoricalInde... | in NDFrame
for replace_value, new_value in replace_dict.items():
if new_value == replace_value:
continue
if replace_value in cat.categories:
if isna(new_value):
cat.remove_categories(replace_value, inplace=True)
con... | 256 | 256 | 1,054 | 106 | 149 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | CategoricalAccessor | CategoricalAccessor | 2,419 | 2,579 | 2,419 | 2,436 | 0fbbb232b3c5c9204fb32c812e6378272cb5b3fd | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.