index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
49,655 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/commands/worker.py | 44,45 | 28,52 | run | WorkerCommand | 45,52 | 45,52 | class WorkerCommand(Command):
def __init__(self):
self.logger = get_logger('cola_worker_command')
def add_arguments(self, parser):
ip = get_ip()
self.worker_parser = parser.add_parser('worker', help='worker commands')
self.worker_parser.add_argument('-m', '--master', me... | class WorkerCommand(Command):
def __init__(self):
self.logger = get_logger('cola_worker_command')
def add_arguments(self, parser):
ip = get_ip()
self.worker_parser = parser.add_parser('worker', help='worker commands')
self.worker_parser.add_argument('-m', '--master', me... | if args.start is not None and args.master is not None:
ctx = Context(master_addr=args.master, ip=args.start,
working_dir=args.working)
ctx.start_worker()
self.logger.info('start worker at: %s' % ctx.worker_addr)
else:
self.logger.... | if args.start is not None and args.master is not None:
ctx = Context(master_addr=args.master, ip=args.start,
working_dir=args.working)
ctx.start_worker()
self.logger.info('start worker at: %s' % ctx.worker_addr)
else:
self.logger.... | 26 | 279 | 99 | 378 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,656 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/counter.py | 65,66 | 44,70 | merge_val | AddAggregator | 66,70 | 66,70 | class AddAggregator(Aggregator):
"""
Just adding values.
>>> agg = AddAggregator()
>>> agg.create_combiner(0)
0
>>> agg.merge_combiner(0, 5)
5
>>> agg.merge_val(0, 5)
5
>>> agg.merge_val('0', '5')
'05'
"""
def create_combiner(self, val):
return val
d... | class AddAggregator(Aggregator):
"""
Just adding values.
>>> agg = AddAggregator()
>>> agg.create_combiner(0)
0
>>> agg.merge_combiner(0, 5)
5
>>> agg.merge_val(0, 5)
5
>>> agg.merge_val('0', '5')
'05'
"""
def create_combiner(self, val):
return val
d... | combiner += val
return combiner
| combiner += val
return combiner
| 5 | 187 | 17 | 204 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,657 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/counter.py | 40,41 | 27,44 | merge_val | Aggregator | 41,44 | 41,44 | class Aggregator(object):
"""
Aggregator which provide three abstract functions,
first is to create a ``combiner`` by given a value,
second is to merge two combiners,
the last one is to merge value to a given combiner.
"""
def create_combiner(self, val):
raise NotImplementedError
... | class Aggregator(object):
"""
Aggregator which provide three abstract functions,
first is to create a ``combiner`` by given a value,
second is to merge two combiners,
the last one is to merge value to a given combiner.
"""
def create_combiner(self, val):
raise NotImplementedError
... | raise NotImplementedError
| raise NotImplementedError
| 2 | 143 | 13 | 156 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,658 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/counter.py | 154,155 | 142,188 | inc | Counter | 155,165 | 155,165 | class Counter(object):
"""
A counter can have several groups, each group is a dict.
Besides, an instance of :class:`Aggregator` will decide
how each item in a group to aggregate.
"""
def __init__(self, agg=AddAggregator(), container=None):
self.container = container if container is not N... | class Counter(object):
"""
A counter can have several groups, each group is a dict.
Besides, an instance of :class:`Aggregator` will decide
how each item in a group to aggregate.
"""
def __init__(self, agg=AddAggregator(), container=None):
self.container = container if container is not N... | with self.lock:
if group not in self.container:
self.container[group] = {}
if item not in self.container[group]:
self.container[group][item] = self.agg.create_combiner(val)
else:
src_combiner = self.container[group][item]
... | with self.lock:
if group not in self.container:
self.container[group] = {}
if item not in self.container[group]:
self.container[group][item] = self.agg.create_combiner(val)
else:
src_combiner = self.container[group][item]
... | 27 | 391 | 124 | 515 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,659 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/counter.py | 82,83 | 70,94 | create_combiner | MergeAggregator | 83,85 | 83,85 | class MergeAggregator(Aggregator):
"""
Each combiner is a ``list``.
>>> agg = MergeAggregator()
>>> agg.create_combiner(0)
[0]
>>> agg.merge_combiner([0], [5])
[0, 5]
>>> agg.merge_val([0], 5)
[0, 5]
"""
def create_combiner(self, val):
FILL_FUNC_BODY def merge_combiner(se... | class MergeAggregator(Aggregator):
"""
Each combiner is a ``list``.
>>> agg = MergeAggregator()
>>> agg.create_combiner(0)
[0]
>>> agg.merge_combiner([0], [5])
[0, 5]
>>> agg.merge_val([0], 5)
[0, 5]
"""
def create_combiner(self, val):
FILL_FUNC_BODY def merge_combiner(se... | return [val, ]
| return [val, ]
| 3 | 199 | 11 | 210 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,660 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/counter.py | 137,138 | 129,142 | merge_val | OverwriteAggregator | 138,142 | 138,142 | class OverwriteAggregator(Aggregator):
def create_combiner(self, val):
return val
def merge_combiner(self, combiner1, combiner2):
combiner1 = combiner2
return combiner1
def merge_val(self, combiner, val):
FILL_FUNC_BODY | class OverwriteAggregator(Aggregator):
def create_combiner(self, val):
return val
def merge_combiner(self, combiner1, combiner2):
combiner1 = combiner2
return combiner1
def merge_val(self, combiner, val):
FILL_FUNC_BODY | combiner = val
return combiner
| combiner = val
return combiner
| 5 | 89 | 17 | 106 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,661 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/counter.py | 115,116 | 94,129 | create_combiner | UniqAggregator | 116,120 | 116,120 | class UniqAggregator(Aggregator):
"""
Each combiner is a ``set``.
>>> agg1 = agg.create_combiner(0)
>>> agg1
set([0])
>>> agg2 = agg.create_combiner([0, 5])
>>> agg2
set([0, 5])
>>> agg.merge_combiner(agg1, agg2)
set([0, 5])
>>> agg1
set([0, 5])
>>> agg2
set([0, ... | class UniqAggregator(Aggregator):
"""
Each combiner is a ``set``.
>>> agg1 = agg.create_combiner(0)
>>> agg1
set([0])
>>> agg2 = agg.create_combiner([0, 5])
>>> agg2
set([0, 5])
>>> agg.merge_combiner(agg1, agg2)
set([0, 5])
>>> agg1
set([0, 5])
>>> agg2
set([0, ... | if not iterable(val):
val = [val]
return set(val)
| if not iterable(val):
val = [val]
return set(val)
| 8 | 290 | 29 | 319 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,662 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/handlers.py | 24,25 | 23,26 | handle | ErrorHandler | 25,26 | 25,26 | class ErrorHandler(object):
def handle(self, error, obj):
FILL_FUNC_BODY | class ErrorHandler(object):
def handle(self, error, obj):
FILL_FUNC_BODY | raise NotImplementedError | raise NotImplementedError | 2 | 28 | 8 | 36 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,663 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/core/zip.py | 39,41 | 37,74 | compress | ZipHandler | 41,61 | 41,61 | class ZipHandler(object):
@classmethod
def compress(cls, zip_file, src_dir, type_filters=None):
FILL_FUNC_BODY @classmethod
def uncompress(cls, zip_file, dest_dir):
dir_name = None
with FixedZipFile(zip_file) as zf:
for f in zf.namelist():
zf.extract(f, de... | class ZipHandler(object):
@classmethod
def compress(cls, zip_file, src_dir, type_filters=None):
FILL_FUNC_BODY @classmethod
def uncompress(cls, zip_file, dest_dir):
dir_name = None
with FixedZipFile(zip_file) as zf:
for f in zf.namelist():
zf.extract(f, de... | root_len = len(os.path.abspath(src_dir))
dir_name = os.path.split(src_dir)[1].replace(' ', '_')
with FixedZipFile(zip_file, 'w') as zf:
if os.path.isfile(src_dir):
zf.write(src_dir, dir_name)
else:
for root, _, files in os.walk(src... | root_len = len(os.path.abspath(src_dir))
dir_name = os.path.split(src_dir)[1].replace(' ', '_')
with FixedZipFile(zip_file, 'w') as zf:
if os.path.isfile(src_dir):
zf.write(src_dir, dir_name)
else:
for root, _, files in os.walk(src... | 60 | 189 | 271 | 460 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,664 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/cola/settings.py | 50,51 | 30,57 | update | Settings | 51,57 | 51,57 | class Settings(object):
def __init__(self, user_conf=None, **user_defines):
self.main_conf = main_conf
if user_conf is not None:
if isinstance(user_conf, str):
self.user_conf = Config(user_conf)
else:
self.user_conf = user_conf
else:
... | class Settings(object):
def __init__(self, user_conf=None, **user_defines):
self.main_conf = main_conf
if user_conf is not None:
if isinstance(user_conf, str):
self.user_conf = Config(user_conf)
else:
self.user_conf = user_conf
else:
... | self.values.update(settings)
for k in self.values:
if not k.startswith('_'):
setattr(self, k, getattr(self.values, k))
| self.values.update(settings)
for k in self.values:
if not k.startswith('_'):
setattr(self, k, getattr(self.values, k))
| 12 | 235 | 58 | 293 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,665 | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola | /home/hieuvd/dung_repo/raw/stars_03/qinxuye_cola/cola/lab/weibosearch/login.py | 30,31 | 23,41 | login | WeiboLogin | 31,41 | 31,41 | class WeiboLogin(object):
def __init__(self, opener, username, passwd):
self.opener = opener
self.username = username
self.passwd = passwd
def login(self):
FILL_FUNC_BODY | class WeiboLogin(object):
def __init__(self, opener, username, passwd):
self.opener = opener
self.username = username
self.passwd = passwd
def login(self):
FILL_FUNC_BODY | br = self.opener.spynner_open('http://weibo.com')
self.opener.wait_for_selector('div.info_list')
br.wk_fill('input[name=username]', self.username)
br.wk_fill('input[name=password]', self.passwd)
br.click('a.W_btn_g')
try:
br.wait_for_content(lambda br: 'WB_fee... | br = self.opener.spynner_open('http://weibo.com')
self.opener.wait_for_selector('div.info_list')
br.wk_fill('input[name=username]', self.username)
br.wk_fill('input[name=password]', self.passwd)
br.click('a.W_btn_g')
try:
br.wait_for_content(lambda br: 'WB_fee... | 20 | 71 | 146 | 217 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless... |
49,666 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/api_config.py | 29,30 | 1,40 | read_key | 30,40 | 30,40 | import os
class ApiConfig:
api_key = None
api_protocol = 'https://'
api_base = '{}data.nasdaq.com/api/v3'.format(api_protocol)
api_version = None # This is not used but keeping for backwards compatibility
page_limit = 100
use_retries = True
number_of_retries = 5
retry_backoff_factor ... | import os
class ApiConfig:
api_key = None
api_protocol = 'https://'
api_base = '{}data.nasdaq.com/api/v3'.format(api_protocol)
api_version = None # This is not used but keeping for backwards compatibility
page_limit = 100
use_retries = True
number_of_retries = 5
retry_backoff_factor ... | if filename is None:
filename = os.path.join(os.path.expanduser('~'), '.quandl_apikey')
with open(filename, 'r') as f:
apikey = f.read()
if not apikey:
raise ValueError("File '{:s}' is empty.".format(filename))
ApiConfig.api_key = apikey
| if filename is None:
filename = os.path.join(os.path.expanduser('~'), '.quandl_apikey')
with open(filename, 'r') as f:
apikey = f.read()
if not apikey:
raise ValueError("File '{:s}' is empty.".format(filename))
ApiConfig.api_key = apikey
| 27 | 275 | 108 | 383 | import os
class ApiConfig:
api_key = None
api_protocol = 'https://'
api_base = '{}data.nasdaq.com/api/v3'.format(api_protocol)
api_version = None # This is not used but keeping for backwards compatibility
page_limit = 100
use_retries = True
number_of_retries = 5
retry_backoff_factor ... | import os
class ApiConfig:
api_key = None
api_protocol = 'https://'
api_base = '{}data.nasdaq.com/api/v3'.format(api_protocol)
api_version = None # This is not used but keeping for backwards compatibility
page_limit = 100
use_retries = True
number_of_retries = 5
retry_backoff_factor ... | |
49,667 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/bulkdownload.py | 7,8 | 1,25 | bulkdownload | 16,25 | 8,25 | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.database import Database
from .message import Message
def bulkdownload(database, **kwargs):
FILL_FUNC_BODY | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.database import Database
from .message import Message
def bulkdownload(database, **kwargs):
"""Downloads an entire database.
:param str database: The database code to download
:param str filen... |
# discourage users from using authtoken
if 'authtoken' in kwargs:
raise InvalidRequestError(Message.ERROR_AUTHTOKEN_NOT_SUPPORTED)
ApiKeyUtil.init_api_key_from_args(kwargs)
filename = kwargs.pop('filename', '.')
return Database(database).bulk_download_to_file(filename, params=kwargs)
| """Downloads an entire database.
:param str database: The database code to download
:param str filename: The filename for the download. \
If not specified, will download to the current working directory
:param str api_key: Most databases require api_key for bulk download
:param str download_type... | 20 | 175 | 114 | 289 | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.database import Database
from .message import Message
def bulkdownload(database, **kwargs):
FILL_FUNC_BODY | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.database import Database
from .message import Message
def bulkdownload(database, **kwargs):
"""Downloads an entire database.
:param str database: The database code to download
:param str filen... | |
49,668 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/export_table.py | 7,8 | 1,23 | export_table | 14,23 | 8,23 | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.datatable import Datatable
from .message import Message
def export_table(datatable_code, **kwargs):
FILL_FUNC_BODY | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.datatable import Datatable
from .message import Message
def export_table(datatable_code, **kwargs):
"""Downloads an entire table as a zip file.
:param str datatable_code: The datatable code to dow... |
# discourage users from using authtoken
if 'authtoken' in kwargs:
raise InvalidRequestError(Message.ERROR_AUTHTOKEN_NOT_SUPPORTED)
ApiKeyUtil.init_api_key_from_args(kwargs)
filename = kwargs.pop('filename', '.')
return Datatable(datatable_code).download_file(filename, **kwargs)
| """Downloads an entire table as a zip file.
:param str datatable_code: The datatable code to download, such as MER/F1
:param str filename: The filename for the download. \
If not specified, will download to the current working directory
:param str api_key: Most databases require api_key for bulk dow... | 20 | 159 | 112 | 271 | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.datatable import Datatable
from .message import Message
def export_table(datatable_code, **kwargs):
FILL_FUNC_BODY | from quandl.errors.quandl_error import InvalidRequestError
from .utils.api_key_util import ApiKeyUtil
from .model.datatable import Datatable
from .message import Message
def export_table(datatable_code, **kwargs):
"""Downloads an entire table as a zip file.
:param str datatable_code: The datatable code to dow... | |
49,669 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/get.py | 14,15 | 1,95 | get | 33,66 | 15,66 | from quandl.errors.quandl_error import InvalidRequestError
from .model.dataset import Dataset
from .model.merged_dataset import MergedDataset
from .utils.api_key_util import ApiKeyUtil
from .message import Message
from six import string_types
import warnings
OLD_TO_NEW_PARAMS = {'authtoken': 'api_key', 'trim_start': '... | from quandl.errors.quandl_error import InvalidRequestError
from .model.dataset import Dataset
from .model.merged_dataset import MergedDataset
from .utils.api_key_util import ApiKeyUtil
from .message import Message
from six import string_types
import warnings
OLD_TO_NEW_PARAMS = {'authtoken': 'api_key', 'trim_start': '... |
_convert_params_to_v3(kwargs)
data_format = kwargs.pop('returns', 'pandas')
ApiKeyUtil.init_api_key_from_args(kwargs)
# Check whether dataset is given as a string
# (for a single dataset) or an array (for a multiset call)
# Unicode String
if isinstance(dataset, string_types):
da... | """Return dataframe of requested dataset from Quandl.
:param dataset: str or list, depending on single dataset usage or multiset usage
Dataset codes are available on the Quandl website
:param str api_key: Downloads are limited to 50 unless api_key is specified
:param str start_date, end_date... | 96 | 802 | 391 | 1,193 | from quandl.errors.quandl_error import InvalidRequestError
from .model.dataset import Dataset
from .model.merged_dataset import MergedDataset
from .utils.api_key_util import ApiKeyUtil
from .message import Message
from six import string_types
import warnings
OLD_TO_NEW_PARAMS = {'authtoken': 'api_key', 'trim_start': '... | from quandl.errors.quandl_error import InvalidRequestError
from .model.dataset import Dataset
from .model.merged_dataset import MergedDataset
from .utils.api_key_util import ApiKeyUtil
from .message import Message
from six import string_types
import warnings
OLD_TO_NEW_PARAMS = {'authtoken': 'api_key', 'trim_start': '... | |
49,670 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/get_point_in_time.py | 55,56 | 1,65 | validate_pit_options | 56,65 | 56,65 | from quandl.model.point_in_time import PointInTime
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
from quandl.errors.quandl_error import InvalidRequestError
import warnings
import copy
def get_point_in_time(datatable_code, **options):
valid... | from quandl.model.point_in_time import PointInTime
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
from quandl.errors.quandl_error import InvalidRequestError
import warnings
import copy
def get_point_in_time(datatable_code, **options):
valid... | if 'interval' not in options.keys():
raise InvalidRequestError('option `interval` is required')
if options['interval'] not in ['asofdate', 'from', 'between']:
raise InvalidRequestError('option `interval` is invalid')
if options['interval'] in ['from', 'between']:
if 'start_date' no... | if 'interval' not in options.keys():
raise InvalidRequestError('option `interval` is required')
if options['interval'] not in ['asofdate', 'from', 'between']:
raise InvalidRequestError('option `interval` is invalid')
if options['interval'] in ['from', 'between']:
if 'start_date' no... | 44 | 515 | 135 | 650 | from quandl.model.point_in_time import PointInTime
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
from quandl.errors.quandl_error import InvalidRequestError
import warnings
import copy
def get_point_in_time(datatable_code, **options):
valid... | from quandl.model.point_in_time import PointInTime
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
from quandl.errors.quandl_error import InvalidRequestError
import warnings
import copy
def get_point_in_time(datatable_code, **options):
valid... | |
49,671 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/get_table.py | 9,10 | 1,44 | get_table | 10,44 | 10,44 | from quandl.model.datatable import Datatable
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
import warnings
import copy
def get_table(datatable_code, **options):
FILL_FUNC_BODY | from quandl.model.datatable import Datatable
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
import warnings
import copy
def get_table(datatable_code, **options):
FILL_FUNC_BODY | if 'paginate' in options.keys():
paginate = options.pop('paginate')
else:
paginate = None
data = None
page_count = 0
while True:
next_options = copy.deepcopy(options)
next_data = Datatable(datatable_code).data(params=next_options)
if data is None:
... | if 'paginate' in options.keys():
paginate = options.pop('paginate')
else:
paginate = None
data = None
page_count = 0
while True:
next_options = copy.deepcopy(options)
next_data = Datatable(datatable_code).data(params=next_options)
if data is None:
... | 77 | 81 | 338 | 419 | from quandl.model.datatable import Datatable
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
import warnings
import copy
def get_table(datatable_code, **options):
FILL_FUNC_BODY | from quandl.model.datatable import Datatable
from quandl.errors.quandl_error import LimitExceededError
from .api_config import ApiConfig
from .message import Message
import warnings
import copy
def get_table(datatable_code, **options):
FILL_FUNC_BODY | |
49,672 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/data.py | 20,21 | 7,35 | data_fields | Data | 21,26 | 21,26 | class Data(DataListOperation, DataMixin, ModelBase):
def __init__(self, data, **options):
self.meta = options['meta']
self._raw_data = Util.convert_to_dates(data)
# Optimization for when a list of data points are created from a
# dataset (via the model_list class)
if 'conve... | class Data(DataListOperation, DataMixin, ModelBase):
def __init__(self, data, **options):
self.meta = options['meta']
self._raw_data = Util.convert_to_dates(data)
# Optimization for when a list of data points are created from a
# dataset (via the model_list class)
if 'conve... | if not self._converted_column_names and self.meta:
self._converted_column_names = Util.convert_column_names(self.meta)
return self._converted_column_names
| if not self._converted_column_names and self.meta:
self._converted_column_names = Util.convert_column_names(self.meta)
return self._converted_column_names
| 10 | 301 | 58 | 359 | from quandl.operations.data_list import DataListOperation
from quandl.util import Util
from .model_base import ModelBase
from .data_mixin import DataMixin
class Data(DataListOperation, DataMixin, ModelBase):
def __init__(self, data, **options):
self.meta = options['meta']
self._raw_data = Util.co... | from quandl.operations.data_list import DataListOperation
from quandl.util import Util
from .model_base import ModelBase
from .data_mixin import DataMixin
class Data(DataListOperation, DataMixin, ModelBase):
def __init__(self, data, **options):
self.meta = options['meta']
self._raw_data = Util.co... |
49,673 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/data_mixin.py | 7,8 | 5,49 | to_pandas | DataMixin | 8,37 | 8,37 | class DataMixin(object):
# DataFrame will respect order of input list of list
def to_pandas(self, keep_column_indexes=[]):
FILL_FUNC_BODY def to_numpy(self):
return self.to_pandas().to_records()
def to_csv(self):
return self.to_pandas().to_csv()
def _validate_col_index(self, df, kee... | class DataMixin(object):
# DataFrame will respect order of input list of list
def to_pandas(self, keep_column_indexes=[]):
FILL_FUNC_BODY def to_numpy(self):
return self.to_pandas().to_records()
def to_csv(self):
return self.to_pandas().to_csv()
def _validate_col_index(self, df, kee... | data = self.to_list()
# ensure pandas gets a list of lists
if data and isinstance(data, list) and not isinstance(data[0], list):
data = [data]
if 'columns' in self.meta.keys():
df = pd.DataFrame(data=data, columns=self.columns)
for index, column_type ... | data = self.to_list()
# ensure pandas gets a list of lists
if data and isinstance(data, list) and not isinstance(data[0], list):
data = [data]
if 'columns' in self.meta.keys():
df = pd.DataFrame(data=data, columns=self.columns)
for index, column_type ... | 144 | 191 | 453 | 644 | import pandas as pd
from quandl.errors.quandl_error import ColumnNotFound
class DataMixin(object):
# DataFrame will respect order of input list of list
def to_pandas(self, keep_column_indexes=[]):
FILL_FUNC_BODY def to_numpy(self):
return self.to_pandas().to_records()
def to_csv(self):
... | import pandas as pd
from quandl.errors.quandl_error import ColumnNotFound
class DataMixin(object):
# DataFrame will respect order of input list of list
def to_pandas(self, keep_column_indexes=[]):
FILL_FUNC_BODY def to_numpy(self):
return self.to_pandas().to_records()
def to_csv(self):
... |
49,674 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/database.py | 61,62 | 16,65 | datasets | Database | 62,65 | 62,65 | class Database(GetOperation, ListOperation, ModelBase):
BULK_CHUNK_SIZE = 512
@classmethod
def get_code_from_meta(cls, metadata):
return metadata['database_code']
def bulk_download_url(self, **options):
url = self._bulk_download_path()
url = ApiConfig.api_base + '/' + url
... | class Database(GetOperation, ListOperation, ModelBase):
BULK_CHUNK_SIZE = 512
@classmethod
def get_code_from_meta(cls, metadata):
return metadata['database_code']
def bulk_download_url(self, **options):
url = self._bulk_download_path()
url = ApiConfig.api_base + '/' + url
... | params = {'database_code': self.code, 'query': '', 'page': 1}
options = Util.merge_options('params', params, **options)
return quandl.model.dataset.Dataset.all(**options)
| params = {'database_code': self.code, 'query': '', 'page': 1}
options = Util.merge_options('params', params, **options)
return quandl.model.dataset.Dataset.all(**options)
| 15 | 507 | 62 | 569 | import os
from six.moves.urllib.parse import urlencode, urlparse
import quandl.model.dataset
from quandl.api_config import ApiConfig
from quandl.connection import Connection
from quandl.errors.quandl_error import QuandlError
from quandl.message import Message
from quandl.operations.get import GetOperation
from quandl... | import os
from six.moves.urllib.parse import urlencode, urlparse
import quandl.model.dataset
from quandl.api_config import ApiConfig
from quandl.connection import Connection
from quandl.errors.quandl_error import QuandlError
from quandl.message import Message
from quandl.operations.get import GetOperation
from quandl... |
49,675 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/dataset.py | 34,35 | 13,59 | data | Dataset | 35,57 | 35,57 | class Dataset(GetOperation, ListOperation, ModelBase):
@classmethod
def get_path(cls):
return "%s/metadata" % cls.default_path()
@classmethod
def get_code_from_meta(cls, metadata):
return "%s/%s" % (metadata['database_code'], metadata['dataset_code'])
def __init__(self, code, raw_... | class Dataset(GetOperation, ListOperation, ModelBase):
@classmethod
def get_path(cls):
return "%s/metadata" % cls.default_path()
@classmethod
def get_code_from_meta(cls, metadata):
return "%s/%s" % (metadata['database_code'], metadata['dataset_code'])
def __init__(self, code, raw_... | # handle_not_found_error if set to True will add an empty DataFrame
# for a non-existent dataset instead of raising an error
handle_not_found_error = options.pop('handle_not_found_error', False)
handle_column_not_found = options.pop('handle_column_not_found', False)
# default ord... | # handle_not_found_error if set to True will add an empty DataFrame
# for a non-existent dataset instead of raising an error
handle_not_found_error = options.pop('handle_not_found_error', False)
handle_column_not_found = options.pop('handle_column_not_found', False)
# default ord... | 82 | 255 | 299 | 554 | from quandl.operations.get import GetOperation
from quandl.operations.list import ListOperation
from quandl.util import Util
from .model_base import ModelBase
from .data import Data
from .data_list import DataList
import quandl.model.database
import six
from quandl.errors.quandl_error import (NotFoundError, ColumnNotFo... | from quandl.operations.get import GetOperation
from quandl.operations.list import ListOperation
from quandl.util import Util
from .model_base import ModelBase
from .data import Data
from .data_list import DataList
import quandl.model.database
import six
from quandl.errors.quandl_error import (NotFoundError, ColumnNotFo... |
49,676 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/datatable.py | 45,46 | 20,94 | _request_file_info | Datatable | 46,69 | 46,69 | class Datatable(GetOperation, ListOperation, ModelBase):
BULK_CHUNK_SIZE = 16 * 1024
WAIT_GENERATION_INTERVAL = 30
@classmethod
def get_path(cls):
return "%s/metadata" % cls.default_path()
def data(self, **options):
if not options:
options = {'params': {}}
retur... | class Datatable(GetOperation, ListOperation, ModelBase):
BULK_CHUNK_SIZE = 16 * 1024
WAIT_GENERATION_INTERVAL = 30
@classmethod
def get_path(cls):
return "%s/metadata" % cls.default_path()
def data(self, **options):
if not options:
options = {'params': {}}
retur... | url = self._download_request_path()
code_name = self.code
options['params']['qopts.export'] = 'true'
request_type = RequestType.get_request_type(url, **options)
updated_options = Util.convert_options(request_type=request_type, **options)
r = Connection.request(request_... | url = self._download_request_path()
code_name = self.code
options['params']['qopts.export'] = 'true'
request_type = RequestType.get_request_type(url, **options)
updated_options = Util.convert_options(request_type=request_type, **options)
r = Connection.request(request_... | 46 | 555 | 230 | 785 | import os
from time import sleep
from six.moves.urllib.request import urlopen
from quandl.connection import Connection
from quandl.errors.quandl_error import QuandlError
from quandl.message import Message
from quandl.operations.get import GetOperation
from quandl.operations.list import ListOperation
from quandl.util ... | import os
from time import sleep
from six.moves.urllib.request import urlopen
from quandl.connection import Connection
from quandl.errors.quandl_error import QuandlError
from quandl.message import Message
from quandl.operations.get import GetOperation
from quandl.operations.list import ListOperation
from quandl.util ... |
49,677 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/merged_data_list.py | 20,21 | 5,35 | _initialize_raw_data | MergedDataList | 21,33 | 21,33 | class MergedDataList(DataList):
def __init__(self, klass, values, meta, ascending=True):
# values is a merged DataFrame
self.__data_frame = values
self.__ascending = ascending
raw_data = self._initialize_raw_data()
super(MergedDataList, self).__init__(klass, raw_data, meta)
... | class MergedDataList(DataList):
def __init__(self, klass, values, meta, ascending=True):
# values is a merged DataFrame
self.__data_frame = values
self.__ascending = ascending
raw_data = self._initialize_raw_data()
super(MergedDataList, self).__init__(klass, raw_data, meta)
... | numpy_results = self.to_numpy()
numpy_dtype_names = numpy_results.dtype.names
python_compatible_dtypes = []
for name in numpy_dtype_names:
if numpy_results.dtype[name].str == '<M8[ns]':
python_compatible_dtypes.append((str(name), np.dtype('<M8[ms]')))
... | numpy_results = self.to_numpy()
numpy_dtype_names = numpy_results.dtype.names
python_compatible_dtypes = []
for name in numpy_dtype_names:
if numpy_results.dtype[name].str == '<M8[ns]':
python_compatible_dtypes.append((str(name), np.dtype('<M8[ms]')))
... | 24 | 209 | 174 | 383 | from .data_list import DataList
import numpy as np
class MergedDataList(DataList):
def __init__(self, klass, values, meta, ascending=True):
# values is a merged DataFrame
self.__data_frame = values
self.__ascending = ascending
raw_data = self._initialize_raw_data()
super(M... | from .data_list import DataList
import numpy as np
class MergedDataList(DataList):
def __init__(self, klass, values, meta, ascending=True):
# values is a merged DataFrame
self.__data_frame = values
self.__ascending = ascending
raw_data = self._initialize_raw_data()
super(M... |
49,679 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/model_base.py | 7,8 | 1,28 | to_list | ModelBase | 8,12 | 8,12 | class ModelBase(object):
def __init__(self, code, raw_data=None, **options):
self.code = code
self._raw_data = raw_data
self.options = options
def to_list(self):
FILL_FUNC_BODY def __getattr__(self, k):
if k[0] == '_':
raise AttributeError(k)
elif k in sel... | class ModelBase(object):
def __init__(self, code, raw_data=None, **options):
self.code = code
self._raw_data = raw_data
self.options = options
def to_list(self):
FILL_FUNC_BODY def __getattr__(self, k):
if k[0] == '_':
raise AttributeError(k)
elif k in sel... | if isinstance(self.__get_raw_data__(), dict):
return list(self.__get_raw_data__().values())
return self.__get_raw_data__()
| if isinstance(self.__get_raw_data__(), dict):
return list(self.__get_raw_data__().values())
return self.__get_raw_data__()
| 7 | 217 | 50 | 267 | class ModelBase(object):
def __init__(self, code, raw_data=None, **options):
self.code = code
self._raw_data = raw_data
self.options = options
def to_list(self):
FILL_FUNC_BODY def __getattr__(self, k):
if k[0] == '_':
raise AttributeError(k)
elif k in sel... | class ModelBase(object):
def __init__(self, code, raw_data=None, **options):
self.code = code
self._raw_data = raw_data
self.options = options
def to_list(self):
FILL_FUNC_BODY def __getattr__(self, k):
if k[0] == '_':
raise AttributeError(k)
elif k in sel... |
49,680 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/model_list.py | 31,32 | 4,49 | to_list | ModelList | 32,34 | 32,34 | class ModelList(object):
def __init__(self, klass, values, meta):
self.klass = klass
if 'columns' in meta.keys():
meta['column_types'] = Util.convert_to_columns_list(meta['columns'], 'type')
meta['columns'] = Util.convert_to_columns_list(meta['columns'], 'name')
# S... | class ModelList(object):
def __init__(self, klass, values, meta):
self.klass = klass
if 'columns' in meta.keys():
meta['column_types'] = Util.convert_to_columns_list(meta['columns'], 'type')
meta['columns'] = Util.convert_to_columns_list(meta['columns'], 'name')
# S... | return list([x.to_list() for x in self.values])
| return list([x.to_list() for x in self.values])
| 6 | 432 | 21 | 453 | from quandl.util import Util
class ModelList(object):
def __init__(self, klass, values, meta):
self.klass = klass
if 'columns' in meta.keys():
meta['column_types'] = Util.convert_to_columns_list(meta['columns'], 'type')
meta['columns'] = Util.convert_to_columns_list(meta['... | from quandl.util import Util
class ModelList(object):
def __init__(self, klass, values, meta):
self.klass = klass
if 'columns' in meta.keys():
meta['column_types'] = Util.convert_to_columns_list(meta['columns'], 'type')
meta['columns'] = Util.convert_to_columns_list(meta['... |
49,681 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/paginated_list.py | 5,6 | 4,7 | has_more_results | PaginatedList | 6,7 | 6,7 | class PaginatedList(ModelList):
def has_more_results(self):
FILL_FUNC_BODY | class PaginatedList(ModelList):
def has_more_results(self):
FILL_FUNC_BODY | return self.meta['total_pages'] > self.meta['current_page']
| return self.meta['total_pages'] > self.meta['current_page']
| 4 | 31 | 21 | 52 | from .model_list import ModelList
class PaginatedList(ModelList):
def has_more_results(self):
FILL_FUNC_BODY | from .model_list import ModelList
class PaginatedList(ModelList):
def has_more_results(self):
FILL_FUNC_BODY |
49,682 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/model/point_in_time.py | 12,13 | 11,38 | data | PointInTime | 13,17 | 13,17 | class PointInTime(GetOperation, ListOperation, ModelBase):
def data(self, **options):
FILL_FUNC_BODY def default_path(self):
return "%s/:id/%s" % (self.lookup_key(), self.pit_url(),)
def lookup_key(self):
return 'pit'
def pit_url(self):
interval = self.options['pit']['interval']... | class PointInTime(GetOperation, ListOperation, ModelBase):
def data(self, **options):
FILL_FUNC_BODY def default_path(self):
return "%s/:id/%s" % (self.lookup_key(), self.pit_url(),)
def lookup_key(self):
return 'pit'
def pit_url(self):
interval = self.options['pit']['interval']... | if not options:
options = {'params': {}}
return Data.page(self, **options)
| if not options:
options = {'params': {}}
return Data.page(self, **options)
| 10 | 284 | 32 | 316 | from quandl.operations.get import GetOperation
from quandl.operations.list import ListOperation
from .data import Data
from .model_base import ModelBase
from datetime import date
import logging
log = logging.getLogger(__name__)
class PointInTime(GetOperation, ListOperation, ModelBase):
def data(self, **options):... | from quandl.operations.get import GetOperation
from quandl.operations.list import ListOperation
from .data import Data
from .model_base import ModelBase
from datetime import date
import logging
log = logging.getLogger(__name__)
class PointInTime(GetOperation, ListOperation, ModelBase):
def data(self, **options):... |
49,683 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/operations/data_list.py | 32,34 | 7,55 | validate_dataset_data_response | DataListOperation | 34,49 | 34,49 | class DataListOperation(ListOperation):
@classmethod
def create_list_from_response(cls, data):
cls.validate_dataset_data_response(data['dataset_data'])
values = data['dataset_data'].pop('data')
metadata = data['dataset_data']
return DataList(cls, values, metadata)
@classmeth... | class DataListOperation(ListOperation):
@classmethod
def create_list_from_response(cls, data):
cls.validate_dataset_data_response(data['dataset_data'])
values = data['dataset_data'].pop('data')
metadata = data['dataset_data']
return DataList(cls, values, metadata)
@classmeth... | if len(dataset_data['data']) > 0 \
and len(dataset_data['column_names']) != len(
dataset_data['data'][0]):
raise InvalidDataError(
Message.ERROR_COLUMNS_DATA_NOT_MATCHED,
response_data=dataset_data)
# if column index was req... | if len(dataset_data['data']) > 0 \
and len(dataset_data['column_names']) != len(
dataset_data['data'][0]):
raise InvalidDataError(
Message.ERROR_COLUMNS_DATA_NOT_MATCHED,
response_data=dataset_data)
# if column index was req... | 46 | 362 | 197 | 559 | from quandl.model.data_list import DataList
from .list import ListOperation
from quandl.errors.quandl_error import (InvalidDataError, ColumnNotFound)
from quandl.message import Message
class DataListOperation(ListOperation):
@classmethod
def create_list_from_response(cls, data):
cls.validate_dataset_d... | from quandl.model.data_list import DataList
from .list import ListOperation
from quandl.errors.quandl_error import (InvalidDataError, ColumnNotFound)
from quandl.message import Message
class DataListOperation(ListOperation):
@classmethod
def create_list_from_response(cls, data):
cls.validate_dataset_d... |
49,684 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/operations/operation.py | 5,7 | 4,12 | default_path | Operation | 7,9 | 7,9 | class Operation(object):
@classmethod
def default_path(cls):
FILL_FUNC_BODY @classmethod
def lookup_key(cls):
return underscore(pluralize(cls.__name__))
| class Operation(object):
@classmethod
def default_path(cls):
FILL_FUNC_BODY @classmethod
def lookup_key(cls):
return underscore(pluralize(cls.__name__))
| return "%s/:id" % cls.lookup_key()
| return "%s/:id" % cls.lookup_key()
| 4 | 59 | 21 | 80 | from inflection import (underscore, pluralize)
class Operation(object):
@classmethod
def default_path(cls):
FILL_FUNC_BODY @classmethod
def lookup_key(cls):
return underscore(pluralize(cls.__name__))
| from inflection import (underscore, pluralize)
class Operation(object):
@classmethod
def default_path(cls):
FILL_FUNC_BODY @classmethod
def lookup_key(cls):
return underscore(pluralize(cls.__name__))
|
49,685 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/util.py | 120,122 | 8,141 | convert_to_columns_list | Util | 122,127 | 122,127 | class Util(object):
@staticmethod
def constructed_path(path, params={}):
for key in list(params.copy().keys()):
modified_path = path.replace(":%s" % key, str(params[key]))
if modified_path != path:
params.pop(key, None)
path = modified_path
... | class Util(object):
@staticmethod
def constructed_path(path, params={}):
for key in list(params.copy().keys()):
modified_path = path.replace(":%s" % key, str(params[key]))
if modified_path != path:
params.pop(key, None)
path = modified_path
... | columns = []
for key in meta:
columns.extend([key[type]])
return columns
| columns = []
for key in meta:
columns.extend([key[type]])
return columns
| 10 | 1,277 | 33 | 1,310 | from inflection import parameterize
import dateutil.parser
import re
import pandas
from six import string_types
class Util(object):
@staticmethod
def constructed_path(path, params={}):
for key in list(params.copy().keys()):
modified_path = path.replace(":%s" % key, str(params[key]))
... | from inflection import parameterize
import dateutil.parser
import re
import pandas
from six import string_types
class Util(object):
@staticmethod
def constructed_path(path, params={}):
for key in list(params.copy().keys()):
modified_path = path.replace(":%s" % key, str(params[key]))
... |
49,686 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/utils/api_key_util.py | 5,7 | 4,10 | init_api_key_from_args | ApiKeyUtil | 7,10 | 7,10 | class ApiKeyUtil(object):
@staticmethod
def init_api_key_from_args(params):
FILL_FUNC_BODY | class ApiKeyUtil(object):
@staticmethod
def init_api_key_from_args(params):
FILL_FUNC_BODY | # set api key
if 'api_key' in params:
ApiConfig.api_key = params.pop('api_key')
| # set api key
if 'api_key' in params:
ApiConfig.api_key = params.pop('api_key')
| 11 | 39 | 38 | 77 | from quandl.api_config import ApiConfig
class ApiKeyUtil(object):
@staticmethod
def init_api_key_from_args(params):
FILL_FUNC_BODY | from quandl.api_config import ApiConfig
class ApiKeyUtil(object):
@staticmethod
def init_api_key_from_args(params):
FILL_FUNC_BODY |
49,687 | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python | /home/hieuvd/dung_repo/raw/stars_03/quandl_quandl-python/quandl-python/quandl/utils/request_type_util.py | 17,19 | 9,25 | get_request_type | RequestType | 19,25 | 19,25 | class RequestType(object):
""" Determines whether a request should be made using a GET or a POST request.
Default limit of 6300 is set here as it appears to be the maximum for many
webservers.
"""
MAX_URL_LENGTH_FOR_GET = 6300
USE_GET_REQUEST = True # This is used to simplify testing code
... | class RequestType(object):
""" Determines whether a request should be made using a GET or a POST request.
Default limit of 6300 is set here as it appears to be the maximum for many
webservers.
"""
MAX_URL_LENGTH_FOR_GET = 6300
USE_GET_REQUEST = True # This is used to simplify testing code
... | query_string = urlencode(params['params'])
request_url = '%s/%s/%s' % (ApiConfig.api_base, url, query_string)
if RequestType.USE_GET_REQUEST and (len(request_url) < cls.MAX_URL_LENGTH_FOR_GET):
return 'get'
else:
return 'post'
| query_string = urlencode(params['params'])
request_url = '%s/%s/%s' % (ApiConfig.api_base, url, query_string)
if RequestType.USE_GET_REQUEST and (len(request_url) < cls.MAX_URL_LENGTH_FOR_GET):
return 'get'
else:
return 'post'
| 21 | 123 | 99 | 222 | try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from quandl.api_config import ApiConfig
class RequestType(object):
""" Determines whether a request should be made using a GET or a POST request.
Default limit of 6300 is set here as it appears to be the maximum ... | try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from quandl.api_config import ApiConfig
class RequestType(object):
""" Determines whether a request should be made using a GET or a POST request.
Default limit of 6300 is set here as it appears to be the maximum ... |
49,761 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/avg_checkpoints.py | 49,50 | 1,123 | main | 50,121 | 50,121 | #!/usr/bin/env python
""" Checkpoint Averaging Script
This script averages all model weights for checkpoints in specified path that match
the specified filter wildcard. All checkpoints must be from the exact same model.
For any hope of decent results, the checkpoints should be from the same or child
(via resumes) tra... | #!/usr/bin/env python
""" Checkpoint Averaging Script
This script averages all model weights for checkpoints in specified path that match
the specified filter wildcard. All checkpoints must be from the exact same model.
For any hope of decent results, the checkpoints should be from the same or child
(via resumes) tra... | args = parser.parse_args()
# by default use the EMA weights (if present)
args.use_ema = not args.no_use_ema
# by default sort by checkpoint metric (if present) and avg top n checkpoints
args.sort = not args.no_sort
if os.path.exists(args.output):
print("Error: Output filename ({}) alrea... | args = parser.parse_args()
# by default use the EMA weights (if present)
args.use_ema = not args.no_use_ema
# by default sort by checkpoint metric (if present) and avg top n checkpoints
args.sort = not args.no_sort
if os.path.exists(args.output):
print("Error: Output filename ({}) alrea... | 233 | 642 | 950 | 1,592 | #!/usr/bin/env python
""" Checkpoint Averaging Script
This script averages all model weights for checkpoints in specified path that match
the specified filter wildcard. All checkpoints must be from the exact same model.
For any hope of decent results, the checkpoints should be from the same or child
(via resumes) tra... | #!/usr/bin/env python
""" Checkpoint Averaging Script
This script averages all model weights for checkpoints in specified path that match
the specified filter wildcard. All checkpoints must be from the exact same model.
For any hope of decent results, the checkpoints should be from the same or child
(via resumes) tra... | |
49,762 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/clean_checkpoint.py | 30,31 | 1,83 | main | 31,81 | 31,81 | #!/usr/bin/env python
""" Checkpoint Cleaning Script
Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc.
and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256
calculation for model zoo compatibility.
Hacked together by / Copyright 2020 Ross Wightman (https:/... | #!/usr/bin/env python
""" Checkpoint Cleaning Script
Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc.
and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256
calculation for model zoo compatibility.
Hacked together by / Copyright 2020 Ross Wightman (https:/... | args = parser.parse_args()
if os.path.exists(args.output):
print("Error: Output filename ({}) already exists.".format(args.output))
exit(1)
# Load an existing checkpoint to CPU, strip everything but the state_dict and re-save
if args.checkpoint and os.path.isfile(args.checkpoint):
... | args = parser.parse_args()
if os.path.exists(args.output):
print("Error: Output filename ({}) already exists.".format(args.output))
exit(1)
# Load an existing checkpoint to CPU, strip everything but the state_dict and re-save
if args.checkpoint and os.path.isfile(args.checkpoint):
... | 170 | 360 | 714 | 1,074 | #!/usr/bin/env python
""" Checkpoint Cleaning Script
Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc.
and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256
calculation for model zoo compatibility.
Hacked together by / Copyright 2020 Ross Wightman (https:/... | #!/usr/bin/env python
""" Checkpoint Cleaning Script
Takes training checkpoints with GPU tensors, optimizer state, extra dict keys, etc.
and outputs a CPU tensor checkpoint with only the `state_dict` along with SHA256
calculation for model zoo compatibility.
Hacked together by / Copyright 2020 Ross Wightman (https:/... | |
49,764 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/anchors.py | 364,365 | 285,410 | batch_label_anchors | AnchorLabeler | 365,410 | 365,410 | class AnchorLabeler(object):
"""Labeler for multiscale anchor boxes.
"""
def __init__(self, anchors, num_classes: int, match_threshold: float = 0.5):
"""Constructs anchor labeler to assign labels to anchors.
Args:
anchors: an instance of class Anchors.
num_classes:... | class AnchorLabeler(object):
"""Labeler for multiscale anchor boxes.
"""
def __init__(self, anchors, num_classes: int, match_threshold: float = 0.5):
"""Constructs anchor labeler to assign labels to anchors.
Args:
anchors: an instance of class Anchors.
num_classes:... | batch_size = len(gt_boxes)
assert batch_size == len(gt_classes)
num_levels = self.anchors.max_level - self.anchors.min_level + 1
cls_targets_out = [[] for _ in range(num_levels)]
box_targets_out = [[] for _ in range(num_levels)]
num_positives_out = []
anchor_box_... | batch_size = len(gt_boxes)
assert batch_size == len(gt_classes)
num_levels = self.anchors.max_level - self.anchors.min_level + 1
cls_targets_out = [[] for _ in range(num_levels)]
box_targets_out = [[] for _ in range(num_levels)]
num_positives_out = []
anchor_box_... | 168 | 1,081 | 766 | 1,847 | """ RetinaNet / EfficientDet Anchor Gen
Adapted for PyTorch from Tensorflow impl at
https://github.com/google/automl/blob/6f6694cec1a48cdb33d5d1551a2d5db8ad227798/efficientdet/anchors.py
Hacked together by Ross Wightman, original copyright below
"""
# Copyright 2020 Google Research. All Rights Reserved.
#
# Licen... | """ RetinaNet / EfficientDet Anchor Gen
Adapted for PyTorch from Tensorflow impl at
https://github.com/google/automl/blob/6f6694cec1a48cdb33d5d1551a2d5db8ad227798/efficientdet/anchors.py
Hacked together by Ross Wightman, original copyright below
"""
# Copyright 2020 Google Research. All Rights Reserved.
#
# Licen... |
49,765 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/anchors.py | 245,246 | 181,285 | _generate_boxes | Anchors | 247,281 | 246,281 | class Anchors(nn.Module):
"""RetinaNet Anchors class."""
def __init__(self, min_level, max_level, num_scales, aspect_ratios, anchor_scale, image_size: Tuple[int, int]):
"""Constructs multiscale RetinaNet anchors.
Args:
min_level: integer number of minimum level of the output featur... | class Anchors(nn.Module):
"""RetinaNet Anchors class."""
def __init__(self, min_level, max_level, num_scales, aspect_ratios, anchor_scale, image_size: Tuple[int, int]):
"""Constructs multiscale RetinaNet anchors.
Args:
min_level: integer number of minimum level of the output featur... | boxes_all = []
for _, configs in self.config.items():
boxes_level = []
for config in configs:
stride, octave_scale, aspect, anchor_scale = config
base_anchor_size_x = anchor_scale * stride[1] * 2 ** octave_scale
base_anchor_size_y =... | """Generates multi-scale anchor boxes."""
boxes_all = []
for _, configs in self.config.items():
boxes_level = []
for config in configs:
stride, octave_scale, aspect, anchor_scale = config
base_anchor_size_x = anchor_scale * stride[1] * 2 **... | 140 | 901 | 563 | 1,464 | """ RetinaNet / EfficientDet Anchor Gen
Adapted for PyTorch from Tensorflow impl at
https://github.com/google/automl/blob/6f6694cec1a48cdb33d5d1551a2d5db8ad227798/efficientdet/anchors.py
Hacked together by Ross Wightman, original copyright below
"""
# Copyright 2020 Google Research. All Rights Reserved.
#
# Licen... | """ RetinaNet / EfficientDet Anchor Gen
Adapted for PyTorch from Tensorflow impl at
https://github.com/google/automl/blob/6f6694cec1a48cdb33d5d1551a2d5db8ad227798/efficientdet/anchors.py
Hacked together by Ross Wightman, original copyright below
"""
# Copyright 2020 Google Research. All Rights Reserved.
#
# Licen... |
49,767 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/bench.py | 109,110 | 97,136 | forward | DetBenchPredict | 110,136 | 110,136 | class DetBenchPredict(nn.Module):
def __init__(self, model):
super(DetBenchPredict, self).__init__()
self.model = model
self.config = model.config # FIXME remove this when we can use @property (torchscript limitation)
self.num_levels = model.config.num_levels
self.num_classe... | class DetBenchPredict(nn.Module):
def __init__(self, model):
super(DetBenchPredict, self).__init__()
self.model = model
self.config = model.config # FIXME remove this when we can use @property (torchscript limitation)
self.num_levels = model.config.num_levels
self.num_classe... | class_out, box_out = self.model(x)
class_out, box_out, indices, classes = _post_process(
class_out,
box_out,
num_levels=self.num_levels,
num_classes=self.num_classes,
max_detection_points=self.max_detection_points,
)
if img_info... | class_out, box_out = self.model(x)
class_out, box_out, indices, classes = _post_process(
class_out,
box_out,
num_levels=self.num_levels,
num_classes=self.num_classes,
max_detection_points=self.max_detection_points,
)
if img_info... | 44 | 225 | 270 | 495 | """ PyTorch EfficientDet support benches
Hacked together by Ross Wightman
"""
from typing import Optional, Dict, List
import torch
import torch.nn as nn
from .anchors import Anchors, AnchorLabeler, generate_detections
from .loss import DetectionLoss
# try:
# torch.div(torch.ones(1), torch.ones(1), rounding_mode... | """ PyTorch EfficientDet support benches
Hacked together by Ross Wightman
"""
from typing import Optional, Dict, List
import torch
import torch.nn as nn
from .anchors import Anchors, AnchorLabeler, generate_detections
from .loss import DetectionLoss
# try:
# torch.div(torch.ones(1), torch.ones(1), rounding_mode... |
49,768 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/bench.py | 156,157 | 136,202 | forward | DetBenchTrain | 157,202 | 157,202 | class DetBenchTrain(nn.Module):
def __init__(self, model, create_labeler=True):
super(DetBenchTrain, self).__init__()
self.model = model
self.config = model.config # FIXME remove this when we can use @property (torchscript limitation)
self.num_levels = model.config.num_levels
... | class DetBenchTrain(nn.Module):
def __init__(self, model, create_labeler=True):
super(DetBenchTrain, self).__init__()
self.model = model
self.config = model.config # FIXME remove this when we can use @property (torchscript limitation)
self.num_levels = model.config.num_levels
... | class_out, box_out = self.model(x)
if self.anchor_labeler is None:
# target should contain pre-computed anchor labels if labeler not present in bench
assert 'label_num_positives' in target
cls_targets = [target[f'label_cls_{l}'] for l in range(self.num_levels)]
... | class_out, box_out = self.model(x)
if self.anchor_labeler is None:
# target should contain pre-computed anchor labels if labeler not present in bench
assert 'label_num_positives' in target
cls_targets = [target[f'label_cls_{l}'] for l in range(self.num_levels)]
... | 109 | 304 | 538 | 842 | """ PyTorch EfficientDet support benches
Hacked together by Ross Wightman
"""
from typing import Optional, Dict, List
import torch
import torch.nn as nn
from .anchors import Anchors, AnchorLabeler, generate_detections
from .loss import DetectionLoss
# try:
# torch.div(torch.ones(1), torch.ones(1), rounding_mode... | """ PyTorch EfficientDet support benches
Hacked together by Ross Wightman
"""
from typing import Optional, Dict, List
import torch
import torch.nn as nn
from .anchors import Anchors, AnchorLabeler, generate_detections
from .loss import DetectionLoss
# try:
# torch.div(torch.ones(1), torch.ones(1), rounding_mode... |
49,769 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/config/config_utils.py | 8,9 | 1,10 | set_config_writeable | 9,10 | 9,10 | from omegaconf import OmegaConf
def set_config_readonly(conf):
OmegaConf.set_readonly(conf, True)
def set_config_writeable(conf):
FILL_FUNC_BODY | from omegaconf import OmegaConf
def set_config_readonly(conf):
OmegaConf.set_readonly(conf, True)
def set_config_writeable(conf):
FILL_FUNC_BODY | OmegaConf.set_readonly(conf, False)
| OmegaConf.set_readonly(conf, False)
| 2 | 62 | 16 | 78 | from omegaconf import OmegaConf
def set_config_readonly(conf):
OmegaConf.set_readonly(conf, True)
def set_config_writeable(conf):
FILL_FUNC_BODY | from omegaconf import OmegaConf
def set_config_readonly(conf):
OmegaConf.set_readonly(conf, True)
def set_config_writeable(conf):
FILL_FUNC_BODY | |
49,772 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/config/train_config.py | 4,5 | 1,35 | default_detection_train_config | 5,35 | 5,35 | from omegaconf import OmegaConf
def default_detection_train_config():
FILL_FUNC_BODY | from omegaconf import OmegaConf
def default_detection_train_config():
FILL_FUNC_BODY | # FIXME currently using args for train config, will revisit, perhaps move to Hydra
h = OmegaConf.create()
# dataset
h.skip_crowd_during_training = True
# augmentation
h.input_rand_hflip = True
h.train_scale_min = 0.1
h.train_scale_max = 2.0
h.autoaugment_policy = None
# optimi... | # FIXME currently using args for train config, will revisit, perhaps move to Hydra
h = OmegaConf.create()
# dataset
h.skip_crowd_during_training = True
# augmentation
h.input_rand_hflip = True
h.train_scale_min = 0.1
h.train_scale_max = 2.0
h.autoaugment_policy = None
# optimi... | 80 | 34 | 342 | 376 | from omegaconf import OmegaConf
def default_detection_train_config():
FILL_FUNC_BODY | from omegaconf import OmegaConf
def default_detection_train_config():
FILL_FUNC_BODY | |
49,773 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/dataset_factory.py | 15,16 | 1,100 | create_dataset | 16,100 | 16,100 | """ Dataset factory
Copyright 2020 Ross Wightman
"""
import os
from collections import OrderedDict
from pathlib import Path
from .dataset_config import *
from .parsers import *
from .dataset import DetectionDatset
from .parsers import create_parser
def create_dataset(name, root, splits=('train', 'val')):
FILL_FUNC_... | """ Dataset factory
Copyright 2020 Ross Wightman
"""
import os
from collections import OrderedDict
from pathlib import Path
from .dataset_config import *
from .parsers import *
from .dataset import DetectionDatset
from .parsers import create_parser
def create_dataset(name, root, splits=('train', 'val')):
FILL_FUNC_... | if isinstance(splits, str):
splits = (splits,)
name = name.lower()
root = Path(root)
dataset_cls = DetectionDatset
datasets = OrderedDict()
if name.startswith('coco'):
if 'coco2014' in name:
dataset_cfg = Coco2014Cfg()
else:
dataset_cfg = Coco2017C... | if isinstance(splits, str):
splits = (splits,)
name = name.lower()
root = Path(root)
dataset_cls = DetectionDatset
datasets = OrderedDict()
if name.startswith('coco'):
if 'coco2014' in name:
dataset_cfg = Coco2014Cfg()
else:
dataset_cfg = Coco2017C... | 251 | 105 | 1,205 | 1,310 | """ Dataset factory
Copyright 2020 Ross Wightman
"""
import os
from collections import OrderedDict
from pathlib import Path
from .dataset_config import *
from .parsers import *
from .dataset import DetectionDatset
from .parsers import create_parser
def create_dataset(name, root, splits=('train', 'val')):
FILL_FUNC_... | """ Dataset factory
Copyright 2020 Ross Wightman
"""
import os
from collections import OrderedDict
from pathlib import Path
from .dataset_config import *
from .parsers import *
from .dataset import DetectionDatset
from .parsers import create_parser
def create_dataset(name, root, splits=('train', 'val')):
FILL_FUNC_... | |
49,774 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/input_config.py | 4,5 | 1,71 | resolve_input_config | 5,71 | 5,71 | from .transforms import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
def resolve_input_config(args, model_config=None, model=None):
FILL_FUNC_BODY | from .transforms import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
def resolve_input_config(args, model_config=None, model=None):
FILL_FUNC_BODY | if not isinstance(args, dict):
args = vars(args)
input_config = {}
if not model_config and model is not None and hasattr(model, 'config'):
model_config = model.config
# Resolve input/image size
in_chans = 3
# if 'chans' in args and args['chans'] is not None:
# in_chans =... | if not isinstance(args, dict):
args = vars(args)
input_config = {}
if not model_config and model is not None and hasattr(model, 'config'):
model_config = model.config
# Resolve input/image size
in_chans = 3
# if 'chans' in args and args['chans'] is not None:
# in_chans =... | 275 | 57 | 924 | 981 | from .transforms import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
def resolve_input_config(args, model_config=None, model=None):
FILL_FUNC_BODY | from .transforms import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
def resolve_input_config(args, model_config=None, model=None):
FILL_FUNC_BODY | |
49,775 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/parsers/parser.py | 76,78 | 5,83 | max_label | Parser | 78,83 | 78,83 | class Parser:
""" Parser base class.
The attributes listed below make up a public interface common to all parsers. They can be accessed directly
once the dataset is constructed and annotations are populated.
Attributes:
cat_names (list[str]):
list of category (class) names, with b... | class Parser:
""" Parser base class.
The attributes listed below make up a public interface common to all parsers. They can be accessed directly
once the dataset is constructed and annotations are populated.
Attributes:
cat_names (list[str]):
list of category (class) names, with b... | if self.cat_id_to_label:
return max(self.cat_id_to_label.values())
else:
assert len(self.cat_ids) and isinstance(self.cat_ids[0], Integral)
return max(self.cat_ids)
| if self.cat_id_to_label:
return max(self.cat_id_to_label.values())
else:
assert len(self.cat_ids) and isinstance(self.cat_ids[0], Integral)
return max(self.cat_ids)
| 12 | 896 | 76 | 972 | from numbers import Integral
from typing import List, Union, Dict, Any
class Parser:
""" Parser base class.
The attributes listed below make up a public interface common to all parsers. They can be accessed directly
once the dataset is constructed and annotations are populated.
Attributes:
... | from numbers import Integral
from typing import List, Union, Dict, Any
class Parser:
""" Parser base class.
The attributes listed below make up a public interface common to all parsers. They can be accessed directly
once the dataset is constructed and annotations are populated.
Attributes:
... |
49,776 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/parsers/parser_coco.py | 47,48 | 11,94 | _parse_img_ann | CocoParser | 48,94 | 48,94 | class CocoParser(Parser):
def __init__(self, cfg: CocoParserCfg):
super().__init__(
bbox_yxyx=cfg.bbox_yxyx,
has_labels=cfg.has_labels,
include_masks=cfg.include_masks,
include_bboxes_ignore=cfg.include_bboxes_ignore,
ignore_empty_gt=cfg.has_label... | class CocoParser(Parser):
def __init__(self, cfg: CocoParserCfg):
super().__init__(
bbox_yxyx=cfg.bbox_yxyx,
has_labels=cfg.has_labels,
include_masks=cfg.include_masks,
include_bboxes_ignore=cfg.include_bboxes_ignore,
ignore_empty_gt=cfg.has_label... | ann_ids = self.coco.getAnnIds(imgIds=[img_id])
ann_info = self.coco.loadAnns(ann_ids)
bboxes = []
bboxes_ignore = []
cls = []
for i, ann in enumerate(ann_info):
if ann.get('ignore', False):
continue
x1, y1, w, h = ann['bbox']
... | ann_ids = self.coco.getAnnIds(imgIds=[img_id])
ann_info = self.coco.loadAnns(ann_ids)
bboxes = []
bboxes_ignore = []
cls = []
for i, ann in enumerate(ann_info):
if ann.get('ignore', False):
continue
x1, y1, w, h = ann['bbox']
... | 129 | 565 | 589 | 1,154 | """ COCO dataset parser
Copyright 2020 Ross Wightman
"""
import numpy as np
from pycocotools.coco import COCO
from .parser import Parser
from .parser_config import CocoParserCfg
class CocoParser(Parser):
def __init__(self, cfg: CocoParserCfg):
super().__init__(
bbox_yxyx=cfg.bbox_yxyx,
... | """ COCO dataset parser
Copyright 2020 Ross Wightman
"""
import numpy as np
from pycocotools.coco import COCO
from .parser import Parser
from .parser_config import CocoParserCfg
class CocoParser(Parser):
def __init__(self, cfg: CocoParserCfg):
super().__init__(
bbox_yxyx=cfg.bbox_yxyx,
... |
49,777 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/parsers/parser_factory.py | 10,11 | 1,20 | create_parser | 11,20 | 11,20 | """ Parser factory
Copyright 2020 Ross Wightman
"""
from .parser_coco import CocoParser
from .parser_voc import VocParser
from .parser_open_images import OpenImagesParser
def create_parser(name, **kwargs):
FILL_FUNC_BODY | """ Parser factory
Copyright 2020 Ross Wightman
"""
from .parser_coco import CocoParser
from .parser_voc import VocParser
from .parser_open_images import OpenImagesParser
def create_parser(name, **kwargs):
FILL_FUNC_BODY | if name == 'coco':
parser = CocoParser(**kwargs)
elif name == 'voc':
parser = VocParser(**kwargs)
elif name == 'openimages':
parser = OpenImagesParser(**kwargs)
else:
assert False, f'Unknown dataset parser ({name})'
return parser
| if name == 'coco':
parser = CocoParser(**kwargs)
elif name == 'voc':
parser = VocParser(**kwargs)
elif name == 'openimages':
parser = OpenImagesParser(**kwargs)
else:
assert False, f'Unknown dataset parser ({name})'
return parser
| 30 | 76 | 92 | 168 | """ Parser factory
Copyright 2020 Ross Wightman
"""
from .parser_coco import CocoParser
from .parser_voc import VocParser
from .parser_open_images import OpenImagesParser
def create_parser(name, **kwargs):
FILL_FUNC_BODY | """ Parser factory
Copyright 2020 Ross Wightman
"""
from .parser_coco import CocoParser
from .parser_voc import VocParser
from .parser_open_images import OpenImagesParser
def create_parser(name, **kwargs):
FILL_FUNC_BODY | |
49,778 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/parsers/parser_voc.py | 42,49 | 14,149 | _load_annotations | VocParser | 49,91 | 49,91 | class VocParser(Parser):
DEFAULT_CLASSES = (
'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
def __init__(self, cfg: VocParserCfg):
... | class VocParser(Parser):
DEFAULT_CLASSES = (
'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant',
'sheep', 'sofa', 'train', 'tvmonitor')
def __init__(self, cfg: VocParserCfg):
... | classes = classes or self.DEFAULT_CLASSES
self.cat_names = list(classes)
self.cat_ids = self.cat_names
self.cat_id_to_label = {cat: i + self.label_offset for i, cat in enumerate(self.cat_ids)}
self.anns = []
with open(split_filename) as f:
ids = f.readlines(... | classes = classes or self.DEFAULT_CLASSES
self.cat_names = list(classes)
self.cat_ids = self.cat_names
self.cat_id_to_label = {cat: i + self.label_offset for i, cat in enumerate(self.cat_ids)}
self.anns = []
with open(split_filename) as f:
ids = f.readlines(... | 114 | 1,088 | 554 | 1,642 | """ Pascal VOC dataset parser
Copyright 2020 Ross Wightman
"""
import os
import xml.etree.ElementTree as ET
from collections import defaultdict
import numpy as np
from .parser import Parser
from .parser_config import VocParserCfg
class VocParser(Parser):
DEFAULT_CLASSES = (
'aeroplane', 'bicycle', 'bir... | """ Pascal VOC dataset parser
Copyright 2020 Ross Wightman
"""
import os
import xml.etree.ElementTree as ET
from collections import defaultdict
import numpy as np
from .parser import Parser
from .parser_config import VocParserCfg
class VocParser(Parser):
DEFAULT_CLASSES = (
'aeroplane', 'bicycle', 'bir... |
49,779 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/random_erasing.py | 10,11 | 1,95 | _get_pixels | 11,22 | 11,22 | """ Multi-Scale RandomErasing
Copyright 2020 Ross Wightman
"""
import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
FILL_FUNC_BODYclass RandomErasing:
""" Randomly selects a rectangle region in an image and erases its pixels.
'Rand... | """ Multi-Scale RandomErasing
Copyright 2020 Ross Wightman
"""
import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
FILL_FUNC_BODYclass RandomErasing:
""" Randomly selects a rectangle region in an image and erases its pixels.
'Rand... | # NOTE I've seen CUDA illegal memory access errors being caused by the normal_()
# paths, flip the order so normal is run on CPU if this becomes a problem
# Issue has been fixed in master https://github.com/pytorch/pytorch/issues/19508
if per_pixel:
return torch.empty(patch_size, dtype=dtype, de... | # NOTE I've seen CUDA illegal memory access errors being caused by the normal_()
# paths, flip the order so normal is run on CPU if this becomes a problem
# Issue has been fixed in master https://github.com/pytorch/pytorch/issues/19508
if per_pixel:
return torch.empty(patch_size, dtype=dtype, de... | 59 | 1,220 | 194 | 1,414 | """ Multi-Scale RandomErasing
Copyright 2020 Ross Wightman
"""
import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
FILL_FUNC_BODYclass RandomErasing:
""" Randomly selects a rectangle region in an image and erases its pixels.
'Rand... | """ Multi-Scale RandomErasing
Copyright 2020 Ross Wightman
"""
import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
FILL_FUNC_BODYclass RandomErasing:
""" Randomly selects a rectangle region in an image and erases its pixels.
'Rand... | |
49,780 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/data/random_erasing.py | 64,65 | 22,95 | _erase | RandomErasing | 65,84 | 65,84 | class RandomErasing:
""" Randomly selects a rectangle region in an image and erases its pixels.
'Random Erasing Data Augmentation' by Zhong et al.
See https://arxiv.org/pdf/1708.04896.pdf
This variant of RandomErasing is tweaked for multi-scale obj detection training.
Args:
pro... | class RandomErasing:
""" Randomly selects a rectangle region in an image and erases its pixels.
'Random Erasing Data Augmentation' by Zhong et al.
See https://arxiv.org/pdf/1708.04896.pdf
This variant of RandomErasing is tweaked for multi-scale obj detection training.
Args:
pro... | if random.random() > self.probability:
return
area = img_h * img_w
count = self.min_count if self.min_count == self.max_count else \
random.randint(self.min_count, self.max_count)
for _ in range(count):
for attempt in range(10):
target_... | if random.random() > self.probability:
return
area = img_h * img_w
count = self.min_count if self.min_count == self.max_count else \
random.randint(self.min_count, self.max_count)
for _ in range(count):
for attempt in range(10):
target_... | 87 | 855 | 310 | 1,165 | """ Multi-Scale RandomErasing
Copyright 2020 Ross Wightman
"""
import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
# NOTE I've seen CUDA illegal memory access errors being caused by the normal_()
# paths, flip the order so normal is r... | """ Multi-Scale RandomErasing
Copyright 2020 Ross Wightman
"""
import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32, device='cuda'):
# NOTE I've seen CUDA illegal memory access errors being caused by the normal_()
# paths, flip the order so normal is r... |
49,783 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/evaluation/detection_evaluator.py | 51,52 | 28,96 | observe_result_dict_for_single_example | DetectionEvaluator | 65,67 | 52,67 | class DetectionEvaluator(metaclass=ABCMeta):
"""Interface for object detection evalution classes.
Example usage of the Evaluator:
------------------------------
evaluator = DetectionEvaluator(categories)
# Detections and groundtruth for image 1.
evaluator.add_single_gt_image_info(...)
evalua... | class DetectionEvaluator(metaclass=ABCMeta):
"""Interface for object detection evalution classes.
Example usage of the Evaluator:
------------------------------
evaluator = DetectionEvaluator(categories)
# Detections and groundtruth for image 1.
evaluator.add_single_gt_image_info(...)
evalua... | raise NotImplementedError('Not implemented for this evaluator!')
| """Observes an evaluation result dict for a single example.
When executing eagerly, once all observations have been observed by this
method you can use `.evaluation()` to get the final metrics.
When using `tf.estimator.Estimator` for evaluation this function is used by
`get_estim... | 6 | 719 | 20 | 739 | from abc import ABCMeta
from abc import abstractmethod
#import collections
import logging
import unicodedata
import numpy as np
from .fields import InputDataFields, DetectionResultFields
from .object_detection_evaluation import ObjectDetectionEvaluation
def create_category_index(categories):
"""Creates dictionar... | from abc import ABCMeta
from abc import abstractmethod
#import collections
import logging
import unicodedata
import numpy as np
from .fields import InputDataFields, DetectionResultFields
from .object_detection_evaluation import ObjectDetectionEvaluation
def create_category_index(categories):
"""Creates dictionar... |
49,785 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/evaluation/detection_evaluator.py | 516,517 | 453,591 | add_single_ground_truth_image_info | OpenImagesChallengeEvaluator | 533,546 | 517,546 | class OpenImagesChallengeEvaluator(OpenImagesDetectionEvaluator):
"""A class implements Open Images Challenge metrics.
Both Detection and Instance Segmentation evaluation metrics are implemented.
Open Images Challenge Detection metric has two major changes in comparison
with Open Images V2 detecti... | class OpenImagesChallengeEvaluator(OpenImagesDetectionEvaluator):
"""A class implements Open Images Challenge metrics.
Both Detection and Instance Segmentation evaluation metrics are implemented.
Open Images Challenge Detection metric has two major changes in comparison
with Open Images V2 detecti... | super(OpenImagesChallengeEvaluator,
self).add_single_ground_truth_image_info(image_id, gt_dict)
input_fields = InputDataFields
gt_classes = gt_dict[input_fields.gt_classes] - self._label_id_offset
image_classes = np.array([], dtype=int)
if input_fields.gt_image_clas... | """Adds groundtruth for a single image to be used for evaluation.
Args:
image_id: A unique string/integer identifier for the image.
gt_dict: A dictionary containing -
InputDataFields.gt_boxes: float32 numpy array of shape [num_boxes, 4]
contain... | 37 | 1,627 | 234 | 1,861 | from abc import ABCMeta
from abc import abstractmethod
#import collections
import logging
import unicodedata
import numpy as np
from .fields import InputDataFields, DetectionResultFields
from .object_detection_evaluation import ObjectDetectionEvaluation
def create_category_index(categories):
"""Creates dictionar... | from abc import ABCMeta
from abc import abstractmethod
#import collections
import logging
import unicodedata
import numpy as np
from .fields import InputDataFields, DetectionResultFields
from .object_detection_evaluation import ObjectDetectionEvaluation
def create_category_index(categories):
"""Creates dictionar... |
49,786 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/evaluation/detection_evaluator.py | 408,409 | 368,453 | add_single_ground_truth_image_info | OpenImagesDetectionEvaluator | 423,453 | 409,453 | class OpenImagesDetectionEvaluator(ObjectDetectionEvaluator):
"""A class to evaluation detections using Open Images V2 metrics.
Open Images V2 introduce group_of type of bounding boxes and this metric
handles those boxes appropriately.
"""
def __init__(self,
categories,
... | class OpenImagesDetectionEvaluator(ObjectDetectionEvaluator):
"""A class to evaluation detections using Open Images V2 metrics.
Open Images V2 introduce group_of type of bounding boxes and this metric
handles those boxes appropriately.
"""
def __init__(self,
categories,
... | if image_id in self._image_ids:
return
gt_classes = (gt_dict[InputDataFields.gt_classes] - self._label_id_offset)
# If the key is not present in the gt_dict or the array is empty
# (unless there are no annotations for the groundtruth on this image)
# use values from ... | """Adds groundtruth for a single image to be used for evaluation.
Args:
image_id: A unique string/integer identifier for the image.
gt_dict: A dictionary containing -
InputDataFields.gt_boxes: float32 numpy array
of shape [num_boxes, 4] contain... | 108 | 723 | 434 | 1,157 | from abc import ABCMeta
from abc import abstractmethod
#import collections
import logging
import unicodedata
import numpy as np
from .fields import InputDataFields, DetectionResultFields
from .object_detection_evaluation import ObjectDetectionEvaluation
def create_category_index(categories):
"""Creates dictionar... | from abc import ABCMeta
from abc import abstractmethod
#import collections
import logging
import unicodedata
import numpy as np
from .fields import InputDataFields, DetectionResultFields
from .object_detection_evaluation import ObjectDetectionEvaluation
def create_category_index(categories):
"""Creates dictionar... |
49,787 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/evaluation/metrics.py | 47,48 | 1,149 | compute_average_precision | 60,92 | 48,92 | import numpy as np
def compute_precision_recall(scores, labels, num_gt):
"""Compute precision and recall.
Args:
scores: A float numpy array representing detection score
labels: A float numpy array representing weighted true/false positive labels
num_gt: Number of ground truth instances... | import numpy as np
def compute_precision_recall(scores, labels, num_gt):
"""Compute precision and recall.
Args:
scores: A float numpy array representing detection score
labels: A float numpy array representing weighted true/false positive labels
num_gt: Number of ground truth instances... | if precision is None:
if recall is not None:
raise ValueError("If precision is None, recall must also be None")
return np.NAN
if not isinstance(precision, np.ndarray) or not isinstance(recall, np.ndarray):
raise ValueError("precision and recall must be numpy array")
if p... | """Compute Average Precision according to the definition in VOCdevkit.
Precision is modified to ensure that it does not decrease as recall
decrease.
Args:
precision: A float [N, 1] numpy array of precisions
recall: A float [N, 1] numpy array of recalls
Raises:
ValueError: if ... | 177 | 1,528 | 509 | 2,037 | import numpy as np
def compute_precision_recall(scores, labels, num_gt):
"""Compute precision and recall.
Args:
scores: A float numpy array representing detection score
labels: A float numpy array representing weighted true/false positive labels
num_gt: Number of ground truth instances... | import numpy as np
def compute_precision_recall(scores, labels, num_gt):
"""Compute precision and recall.
Args:
scores: A float numpy array representing detection score
labels: A float numpy array representing weighted true/false positive labels
num_gt: Number of ground truth instances... | |
49,789 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/evaluation/np_box_list.py | 65,66 | 25,128 | add_field | BoxList | 75,81 | 66,81 | class BoxList(object):
"""Box collection.
BoxList represents a list of bounding boxes as numpy array, where each
bounding box is represented as a row of 4 numbers,
[y_min, x_min, y_max, x_max]. It is assumed that all bounding boxes within a
given list correspond to a single image.
Optionally, u... | class BoxList(object):
"""Box collection.
BoxList represents a list of bounding boxes as numpy array, where each
bounding box is represented as a row of 4 numbers,
[y_min, x_min, y_max, x_max]. It is assumed that all bounding boxes within a
given list correspond to a single image.
Optionally, u... | if self.has_field(field):
raise ValueError('Field ' + field + 'already exists')
if len(field_data.shape) < 1 or field_data.shape[0] != self.num_boxes():
raise ValueError('Invalid dimensions for field data')
self.data[field] = field_data
| """Add data to a specified field.
Args:
field: a string parameter used to speficy a related field to be accessed.
field_data: a numpy array of [N, ...] representing the data associated
with the field.
Raises:
ValueError: if the field is already exist o... | 27 | 1,100 | 88 | 1,188 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
49,792 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/factory.py | 17,20 | 1,56 | create_model_from_config | 20,56 | 20,56 | from .efficientdet import EfficientDet, HeadNet
from .bench import DetBenchTrain, DetBenchPredict
from .config import get_efficientdet_config
from .helpers import load_pretrained, load_checkpoint
def create_model(
model_name, bench_task='', num_classes=None, pretrained=False,
checkpoint_path='', check... | from .efficientdet import EfficientDet, HeadNet
from .bench import DetBenchTrain, DetBenchPredict
from .config import get_efficientdet_config
from .helpers import load_pretrained, load_checkpoint
def create_model(
model_name, bench_task='', num_classes=None, pretrained=False,
checkpoint_path='', check... |
pretrained_backbone = kwargs.pop('pretrained_backbone', True)
if pretrained or checkpoint_path:
pretrained_backbone = False # no point in loading backbone weights
# Config overrides, override some config values via kwargs.
overrides = (
'redundant_bias', 'label_smoothing', 'legacy_foc... |
pretrained_backbone = kwargs.pop('pretrained_backbone', True)
if pretrained or checkpoint_path:
pretrained_backbone = False # no point in loading backbone weights
# Config overrides, override some config values via kwargs.
overrides = (
'redundant_bias', 'label_smoothing', 'legacy_foc... | 145 | 240 | 463 | 703 | from .efficientdet import EfficientDet, HeadNet
from .bench import DetBenchTrain, DetBenchPredict
from .config import get_efficientdet_config
from .helpers import load_pretrained, load_checkpoint
def create_model(
model_name, bench_task='', num_classes=None, pretrained=False,
checkpoint_path='', check... | from .efficientdet import EfficientDet, HeadNet
from .bench import DetBenchTrain, DetBenchPredict
from .config import get_efficientdet_config
from .helpers import load_pretrained, load_checkpoint
def create_model(
model_name, bench_task='', num_classes=None, pretrained=False,
checkpoint_path='', check... | |
49,793 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/helpers.py | 14,15 | 1,23 | load_pretrained | 15,23 | 15,23 | import torch
import os
import logging
from collections import OrderedDict
from timm.models import load_checkpoint
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
def load_pretrained(model, url, filter_fn=None, str... | import torch
import os
import logging
from collections import OrderedDict
from timm.models import load_checkpoint
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
def load_pretrained(model, url, filter_fn=None, str... | if not url:
logging.warning("Pretrained model URL is empty, using random initialization. "
"Did you intend to use a `tf_` variant of the model?")
return
state_dict = load_state_dict_from_url(url, progress=False, map_location='cpu')
if filter_fn is not None:
st... | if not url:
logging.warning("Pretrained model URL is empty, using random initialization. "
"Did you intend to use a `tf_` variant of the model?")
return
state_dict = load_state_dict_from_url(url, progress=False, map_location='cpu')
if filter_fn is not None:
st... | 39 | 116 | 126 | 242 | import torch
import os
import logging
from collections import OrderedDict
from timm.models import load_checkpoint
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
def load_pretrained(model, url, filter_fn=None, str... | import torch
import os
import logging
from collections import OrderedDict
from timm.models import load_checkpoint
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
def load_pretrained(model, url, filter_fn=None, str... | |
49,795 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/loss.py | 242,249 | 226,260 | forward | DetectionLoss | 249,260 | 249,260 | class DetectionLoss(nn.Module):
__constants__ = ['num_classes']
def __init__(self, config):
super(DetectionLoss, self).__init__()
self.config = config
self.num_classes = config.num_classes
self.alpha = config.alpha
self.gamma = config.gamma
self.delta = config.d... | class DetectionLoss(nn.Module):
__constants__ = ['num_classes']
def __init__(self, config):
super(DetectionLoss, self).__init__()
self.config = config
self.num_classes = config.num_classes
self.alpha = config.alpha
self.gamma = config.gamma
self.delta = config.d... |
l_fn = loss_fn
if not torch.jit.is_scripting() and self.use_jit:
# This branch only active if parent / bench itself isn't being scripted
# NOTE: I haven't figured out what to do here wrt to tracing, is it an issue?
l_fn = loss_jit
return l_fn(
cl... |
l_fn = loss_fn
if not torch.jit.is_scripting() and self.use_jit:
# This branch only active if parent / bench itself isn't being scripted
# NOTE: I haven't figured out what to do here wrt to tracing, is it an issue?
l_fn = loss_jit
return l_fn(
cl... | 55 | 279 | 207 | 486 | """ EfficientDet Focal, Huber/Smooth L1 loss fns w/ jit support
Based on loss fn in Google's automl EfficientDet repository (Apache 2.0 license).
https://github.com/google/automl/tree/master/efficientdet
Copyright 2020 Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing i... | """ EfficientDet Focal, Huber/Smooth L1 loss fns w/ jit support
Based on loss fn in Google's automl EfficientDet repository (Apache 2.0 license).
https://github.com/google/automl/tree/master/efficientdet
Copyright 2020 Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing i... |
49,797 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/object_detection/argmax_matcher.py | 162,163 | 39,175 | _set_values_using_indicator | ArgMaxMatcher | 173,175 | 163,175 | @torch.jit.script
class ArgMaxMatcher(object): # cannot inherit with torchscript
"""Matcher based on highest value.
This class computes matches from a similarity matrix. Each column is matched
to a single row.
To support object detection target assignment this class enables setting both
matched_t... | @torch.jit.script
class ArgMaxMatcher(object): # cannot inherit with torchscript
"""Matcher based on highest value.
This class computes matches from a similarity matrix. Each column is matched
to a single row.
To support object detection target assignment this class enables setting both
matched_t... | indicator = indicator.to(dtype=x.dtype)
return x * (1 - indicator) + val * indicator
| """Set the indicated fields of x to val.
Args:
x: tensor.
indicator: boolean with same shape as x.
val: scalar with value to set.
Returns:
modified tensor.
"""
indicator = indicator.to(dtype=x.dtype)
return x * (1 - indica... | 13 | 1,806 | 32 | 1,838 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
49,798 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/object_detection/box_coder.py | 141,142 | 1,173 | batch_decode | 162,173 | 142,173 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | assert len(encoded_boxes.shape) == 3
if encoded_boxes.shape[1] != anchors.num_boxes():
raise ValueError('The number of anchors inferred from encoded_boxes'
' and anchors are inconsistent: shape[1] of encoded_boxes'
' %s should be equal to the number of a... | """Decode a batch of encoded boxes.
This op takes a batch of encoded bounding boxes and transforms
them to a batch of bounding boxes specified by their corners in
the order of [y_min, x_min, y_max, x_max].
Args:
encoded_boxes: a float32 tensor of shape [batch_size, num_anchors,
... | 50 | 1,817 | 181 | 1,998 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | |
49,799 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/object_detection/box_coder.py | 81,82 | 59,141 | encode | FasterRcnnBoxCoder | 91,112 | 82,112 | class FasterRcnnBoxCoder(object):
"""Faster RCNN box coder."""
def __init__(self, scale_factors: Optional[List[float]] = None, eps: float = EPS):
"""Constructor for FasterRcnnBoxCoder.
Args:
scale_factors: List of 4 positive scalars to scale ty, tx, th and tw.
If se... | class FasterRcnnBoxCoder(object):
"""Faster RCNN box coder."""
def __init__(self, scale_factors: Optional[List[float]] = None, eps: float = EPS):
"""Constructor for FasterRcnnBoxCoder.
Args:
scale_factors: List of 4 positive scalars to scale ty, tx, th and tw.
If se... | # Convert anchors to the center coordinate representation.
ycenter_a, xcenter_a, ha, wa = anchors.get_center_coordinates_and_sizes()
ycenter, xcenter, h, w = boxes.get_center_coordinates_and_sizes()
# Avoid NaN in division and log below.
ha += self.eps
wa += self.eps
... | """Encode a box collection with respect to anchor collection.
Args:
boxes: BoxList holding N boxes to be encoded.
anchors: BoxList of anchors.
Returns:
a tensor representing N anchor-encoded boxes of the format [ty, tx, th, tw].
"""
# Convert... | 97 | 671 | 292 | 963 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
49,800 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/object_detection/box_list.py | 80,81 | 39,198 | add_field | BoxList | 89,91 | 81,91 | @torch.jit.script
class BoxList(object):
"""Box collection."""
data: Dict[str, torch.Tensor]
def __init__(self, boxes):
"""Constructs box collection.
Args:
boxes: a tensor of shape [N, 4] representing box corners
Raises:
ValueError: if invalid dimensions fo... | @torch.jit.script
class BoxList(object):
"""Box collection."""
data: Dict[str, torch.Tensor]
def __init__(self, boxes):
"""Constructs box collection.
Args:
boxes: a tensor of shape [N, 4] representing box corners
Raises:
ValueError: if invalid dimensions fo... | self.data[field] = field_data
| """Add field to box list.
This method can be used to add related box data such as weights/labels, etc.
Args:
field: a string key to access the data via `get`
field_data: a tensor containing the data to store in the BoxList
"""
self.data[field] = field_da... | 3 | 1,502 | 15 | 1,517 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
49,801 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/object_detection/matcher.py | 128,129 | 36,180 | unmatched_or_ignored_column_indices | Match | 136,138 | 129,138 | @torch.jit.script
class Match(object):
"""Class to store results from the matcher.
This class is used to store the results from the matcher. It provides
convenient methods to query the matching results.
"""
def __init__(self, match_results: torch.Tensor):
"""Constructs a Match object.
... | @torch.jit.script
class Match(object):
"""Class to store results from the matcher.
This class is used to store the results from the matcher. It provides
convenient methods to query the matching results.
"""
def __init__(self, match_results: torch.Tensor):
"""Constructs a Match object.
... | return torch.nonzero(0 > self.match_results).flatten().long()
| """Returns column indices that are unmatched or ignored.
The indices returned by this op are always sorted in increasing order.
Returns:
column_indices: int32 tensor of shape [K] with column indices.
"""
return torch.nonzero(0 > self.match_results).flatten().long()
... | 4 | 1,619 | 25 | 1,644 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
49,802 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/object_detection/region_similarity_calculator.py | 59,60 | 1,102 | iou | 69,76 | 60,76 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | intersections = intersection(boxlist1, boxlist2)
areas1 = area(boxlist1)
areas2 = area(boxlist2)
unions = areas1.unsqueeze(1) + areas2.unsqueeze(0) - intersections
return torch.where(intersections == 0.0, torch.zeros_like(intersections), intersections / unions)
| """Computes pairwise intersection-over-union between box collections.
Args:
boxlist1: BoxList holding N boxes
boxlist2: BoxList holding M boxes
Returns:
a tensor with shape [N, M] representing pairwise iou scores.
"""
intersections = intersection(boxlist1, boxlist2)
are... | 25 | 1,051 | 107 | 1,158 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | |
49,803 | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch | /home/hieuvd/dung_repo/raw/stars_03/rwightman_efficientdet-pytorch/efficientdet-pytorch/effdet/object_detection/region_similarity_calculator.py | 85,86 | 76,102 | compare | IouSimilarity | 101,102 | 86,102 | @torch.jit.script
class IouSimilarity(object):
"""Class to compute similarity based on Intersection over Union (IOU) metric.
This class computes pairwise similarity between two BoxLists based on IOU.
"""
def __init__(self):
pass
def compare(self, boxlist1: BoxList, boxlist2: BoxList):
FILL... | @torch.jit.script
class IouSimilarity(object):
"""Class to compute similarity based on Intersection over Union (IOU) metric.
This class computes pairwise similarity between two BoxLists based on IOU.
"""
def __init__(self):
pass
def compare(self, boxlist1: BoxList, boxlist2: BoxList):
... | return iou(boxlist1, boxlist2)
| """Computes matrix of pairwise similarity between BoxLists.
This op (to be overridden) computes a measure of pairwise similarity between
the boxes in the given BoxLists. Higher values indicate more similarity.
Note that this method simply measures similarity and does not explicitly
... | 3 | 237 | 15 | 252 | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
49,883 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/examples/helpers/eventwebhook/eventwebhook_example.py | 3,4 | 1,15 | is_valid_signature | 4,15 | 4,15 | from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader
def is_valid_signature(request):
FILL_FUNC_BODY | from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader
def is_valid_signature(request):
FILL_FUNC_BODY | public_key = 'base64-encoded public key'
event_webhook = EventWebhook()
ec_public_key = event_webhook.convert_public_key_to_ecdsa(public_key)
return event_webhook.verify_signature(
request.text,
request.headers[EventWebhookHeader.SIGNATURE],
request.headers[EventWebhookHeader.T... | public_key = 'base64-encoded public key'
event_webhook = EventWebhook()
ec_public_key = event_webhook.convert_public_key_to_ecdsa(public_key)
return event_webhook.verify_signature(
request.text,
request.headers[EventWebhookHeader.SIGNATURE],
request.headers[EventWebhookHeader.T... | 18 | 41 | 128 | 169 | from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader
def is_valid_signature(request):
FILL_FUNC_BODY | from sendgrid.helpers.eventwebhook import EventWebhook, EventWebhookHeader
def is_valid_signature(request):
FILL_FUNC_BODY | |
49,884 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/examples/helpers/stats/stats_example.py | 65,66 | 1,102 | get_category_stats | 66,73 | 66,73 | import json
import os
from sendgrid.helpers.stats import *
from sendgrid import *
# NOTE: you will need to move this file to the root directory of this project to execute properly.
# Assumes you set your environment variable:
# See: https://github.com/sendgrid/sendgrid-python/blob/HEAD/TROUBLESHOOTING.md#environment-... | import json
import os
from sendgrid.helpers.stats import *
from sendgrid import *
# NOTE: you will need to move this file to the root directory of this project to execute properly.
# Assumes you set your environment variable:
# See: https://github.com/sendgrid/sendgrid-python/blob/HEAD/TROUBLESHOOTING.md#environment-... | stats_params = build_category_stats()
response = sg.client.categories.stats.get(query_params=stats_params)
print(response.status_code)
print(response.headers)
pprint_json(response.body)
| stats_params = build_category_stats()
response = sg.client.categories.stats.get(query_params=stats_params)
print(response.status_code)
print(response.headers)
pprint_json(response.body)
| 9 | 1,001 | 74 | 1,075 | import json
import os
from sendgrid.helpers.stats import *
from sendgrid import *
# NOTE: you will need to move this file to the root directory of this project to execute properly.
# Assumes you set your environment variable:
# See: https://github.com/sendgrid/sendgrid-python/blob/HEAD/TROUBLESHOOTING.md#environment-... | import json
import os
from sendgrid.helpers.stats import *
from sendgrid import *
# NOTE: you will need to move this file to the root directory of this project to execute properly.
# Assumes you set your environment variable:
# See: https://github.com/sendgrid/sendgrid-python/blob/HEAD/TROUBLESHOOTING.md#environment-... | |
49,885 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/base_interface.py | 36,38 | 5,84 | _default_headers | BaseInterface | 39,49 | 38,49 | class BaseInterface(object):
def __init__(self, auth, host, impersonate_subuser):
"""
Construct the Twilio SendGrid v3 API object.
Note that the underlying client is being set up during initialization,
therefore changing attributes in runtime will not affect HTTP client
behav... | class BaseInterface(object):
def __init__(self, auth, host, impersonate_subuser):
"""
Construct the Twilio SendGrid v3 API object.
Note that the underlying client is being set up during initialization,
therefore changing attributes in runtime will not affect HTTP client
behav... | headers = {
"Authorization": self.auth,
"User-Agent": self.useragent,
"Accept": 'application/json'
}
if self.impersonate_subuser:
headers['On-Behalf-Of'] = self.impersonate_subuser
return headers
| """Set the default header for a Twilio SendGrid v3 API call"""
headers = {
"Authorization": self.auth,
"User-Agent": self.useragent,
"Accept": 'application/json'
}
if self.impersonate_subuser:
headers['On-Behalf-Of'] = self.impersonate_subu... | 17 | 704 | 88 | 792 | import python_http_client
region_host_dict = {'eu':'https://api.eu.sendgrid.com','global':'https://api.sendgrid.com'}
class BaseInterface(object):
def __init__(self, auth, host, impersonate_subuser):
"""
Construct the Twilio SendGrid v3 API object.
Note that the underlying client is being ... | import python_http_client
region_host_dict = {'eu':'https://api.eu.sendgrid.com','global':'https://api.sendgrid.com'}
class BaseInterface(object):
def __init__(self, auth, host, impersonate_subuser):
"""
Construct the Twilio SendGrid v3 API object.
Note that the underlying client is being ... |
49,886 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/endpoints/ip/unassigned.py | 4,5 | 1,60 | format_ret | 7,18 | 5,18 | import json
def format_ret(return_set, as_json=False):
FILL_FUNC_BODYdef unassigned(data, as_json=False):
""" https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses
The /ips rest endpoint returns information about the IP addresses
and the usernames assigned to an IP
unassigned r... | import json
def format_ret(return_set, as_json=False):
""" decouple, allow for modifications to return type
returns a list of ip addresses in object or json form """
FILL_FUNC_BODYdef unassigned(data, as_json=False):
""" https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses
The /ips... | ret_list = list()
for item in return_set:
d = {"ip": item}
ret_list.append(d)
if as_json:
return json.dumps(ret_list)
return ret_list
| """ decouple, allow for modifications to return type
returns a list of ip addresses in object or json form """
ret_list = list()
for item in return_set:
d = {"ip": item}
ret_list.append(d)
if as_json:
return json.dumps(ret_list)
return ret_list
| 18 | 463 | 76 | 539 | import json
def format_ret(return_set, as_json=False):
FILL_FUNC_BODYdef unassigned(data, as_json=False):
""" https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses
The /ips rest endpoint returns information about the IP addresses
and the usernames assigned to an IP
unassigned r... | import json
def format_ret(return_set, as_json=False):
""" decouple, allow for modifications to return type
returns a list of ip addresses in object or json form """
FILL_FUNC_BODYdef unassigned(data, as_json=False):
""" https://sendgrid.com/docs/API_Reference/api_v3.html#ip-addresses
The /ips... | |
49,887 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/inbound/app.py | 29,31 | 1,46 | inbound_parse | 32,40 | 31,40 | """Receiver module for processing SendGrid Inbound Parse messages.
See README.txt for usage instructions."""
try:
from config import Config
except:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
try:
from parse import Parse
except:
# Python 3+, Travis
from sendgrid.help... | """Receiver module for processing SendGrid Inbound Parse messages.
See README.txt for usage instructions."""
try:
from config import Config
except:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
try:
from parse import Parse
except:
# Python 3+, Travis
from sendgrid.help... | parse = Parse(config, request)
# Sample processing action
print(parse.key_values())
# Tell SendGrid's Inbound Parse to stop sending POSTs
# Everything is 200 OK :)
return "OK"
| """Process POST from Inbound Parse and print received data."""
parse = Parse(config, request)
# Sample processing action
print(parse.key_values())
# Tell SendGrid's Inbound Parse to stop sending POSTs
# Everything is 200 OK :)
return "OK"
| 26 | 320 | 71 | 391 | """Receiver module for processing SendGrid Inbound Parse messages.
See README.txt for usage instructions."""
try:
from config import Config
except:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
try:
from parse import Parse
except:
# Python 3+, Travis
from sendgrid.help... | """Receiver module for processing SendGrid Inbound Parse messages.
See README.txt for usage instructions."""
try:
from config import Config
except:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
try:
from parse import Parse
except:
# Python 3+, Travis
from sendgrid.help... | |
49,888 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/inbound/config.py | 26,28 | 6,66 | init_environment | Config | 30,40 | 28,40 | class Config(object):
"""All configuration for this app is loaded here"""
def __init__(self, **opts):
if os.environ.get('ENV') != 'prod': # We are not in Heroku
self.init_environment()
"""Allow variables assigned in config.yml available the following variables
via prope... | class Config(object):
"""All configuration for this app is loaded here"""
def __init__(self, **opts):
if os.environ.get('ENV') != 'prod': # We are not in Heroku
self.init_environment()
"""Allow variables assigned in config.yml available the following variables
via prope... | base_path = os.path.abspath(os.path.dirname(__file__))
env_path = '{0}/.env'.format(base_path)
if os.path.exists(env_path):
with open(env_path) as f:
lines = f.readlines()
for line in lines:
var = line.strip().split('=')
... | """Allow variables assigned in .env available using
os.environ.get('VAR_NAME')"""
base_path = os.path.abspath(os.path.dirname(__file__))
env_path = '{0}/.env'.format(base_path)
if os.path.exists(env_path):
with open(env_path) as f:
lines = f.readlin... | 29 | 465 | 133 | 598 | """Set up credentials (.env) and application variables (config.yml)"""
import os
import yaml
class Config(object):
"""All configuration for this app is loaded here"""
def __init__(self, **opts):
if os.environ.get('ENV') != 'prod': # We are not in Heroku
self.init_environment()
"... | """Set up credentials (.env) and application variables (config.yml)"""
import os
import yaml
class Config(object):
"""All configuration for this app is loaded here"""
def __init__(self, **opts):
if os.environ.get('ENV') != 'prod': # We are not in Heroku
self.init_environment()
"... |
49,889 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/inbound/parse.py | 54,55 | 9,101 | _get_attachments | Parse | 55,66 | 55,66 | class Parse(object):
def __init__(self, config, request):
self._keys = config.keys
self._request = request
request.get_data(as_text=True)
self._payload = request.form
self._raw_payload = request.data
def key_values(self):
"""
Return a dictionary of key/v... | class Parse(object):
def __init__(self, config, request):
self._keys = config.keys
self._request = request
request.get_data(as_text=True)
self._payload = request.form
self._raw_payload = request.data
def key_values(self):
"""
Return a dictionary of key/v... | attachments = []
for _, filestorage in iteritems(request.files):
attachment = {}
if filestorage.filename not in (None, 'fdopen', '<fdopen>'):
filename = secure_filename(filestorage.filename)
attachment['type'] = filestorage.content_type
... | attachments = []
for _, filestorage in iteritems(request.files):
attachment = {}
if filestorage.filename not in (None, 'fdopen', '<fdopen>'):
filename = secure_filename(filestorage.filename)
attachment['type'] = filestorage.content_type
... | 33 | 719 | 137 | 856 | """Parse data received from the SendGrid Inbound Parse webhook"""
import base64
import email
import mimetypes
from six import iteritems
from werkzeug.utils import secure_filename
class Parse(object):
def __init__(self, config, request):
self._keys = config.keys
self._request = request
req... | """Parse data received from the SendGrid Inbound Parse webhook"""
import base64
import email
import mimetypes
from six import iteritems
from werkzeug.utils import secure_filename
class Parse(object):
def __init__(self, config, request):
self._keys = config.keys
self._request = request
req... |
49,890 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/inbound/send.py | 41,42 | 1,62 | main | 42,60 | 42,60 | """A module for sending test SendGrid Inbound Parse messages.
Usage: ./send.py [path to file containing test data]"""
import argparse
import sys
from io import open
try:
from config import Config
except ImportError:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
from python_http_clie... | """A module for sending test SendGrid Inbound Parse messages.
Usage: ./send.py [path to file containing test data]"""
import argparse
import sys
from io import open
try:
from config import Config
except ImportError:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
from python_http_clie... | config = Config()
parser = argparse.ArgumentParser(
description='Test data and optional host.')
parser.add_argument('data',
type=str,
help='path to the sample data')
parser.add_argument('-host',
type=str,
... | config = Config()
parser = argparse.ArgumentParser(
description='Test data and optional host.')
parser.add_argument('data',
type=str,
help='path to the sample data')
parser.add_argument('-host',
type=str,
... | 43 | 348 | 183 | 531 | """A module for sending test SendGrid Inbound Parse messages.
Usage: ./send.py [path to file containing test data]"""
import argparse
import sys
from io import open
try:
from config import Config
except ImportError:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
from python_http_clie... | """A module for sending test SendGrid Inbound Parse messages.
Usage: ./send.py [path to file containing test data]"""
import argparse
import sys
from io import open
try:
from config import Config
except ImportError:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
from python_http_clie... | |
49,891 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/inbound/send.py | 20,21 | 14,41 | test_payload | Send | 26,35 | 21,35 | class Send(object):
def __init__(self, url):
"""Create a Send object with target `url`."""
self._url = url
def test_payload(self, payload_filepath):
FILL_FUNC_BODY @property
def url(self):
"""URL to send to."""
return self._url
| class Send(object):
def __init__(self, url):
"""Create a Send object with target `url`."""
self._url = url
def test_payload(self, payload_filepath):
"""Send a test payload.
Load a payload from payload_filepath, apply headers, and POST self.url.
Return the response obje... | headers = {
"User-Agent": "SendGrid-Test",
"Content-Type": "multipart/form-data; boundary=xYzZY"
}
client = Client(host=self.url, request_headers=headers)
f = open(payload_filepath, 'r', encoding='utf-8')
data = f.read()
return client.post(request_... | """Send a test payload.
Load a payload from payload_filepath, apply headers, and POST self.url.
Return the response object.
"""
headers = {
"User-Agent": "SendGrid-Test",
"Content-Type": "multipart/form-data; boundary=xYzZY"
}
client = Cli... | 23 | 129 | 115 | 244 | """A module for sending test SendGrid Inbound Parse messages.
Usage: ./send.py [path to file containing test data]"""
import argparse
import sys
from io import open
try:
from config import Config
except ImportError:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
from python_http_clie... | """A module for sending test SendGrid Inbound Parse messages.
Usage: ./send.py [path to file containing test data]"""
import argparse
import sys
from io import open
try:
from config import Config
except ImportError:
# Python 3+, Travis
from sendgrid.helpers.inbound.config import Config
from python_http_clie... |
49,892 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/amp_html_content.py | 46,47 | 5,60 | get | AmpHtmlContent | 53,60 | 47,60 | class AmpHtmlContent(Content):
"""AMP HTML content to be included in your email."""
def __init__(self, content):
"""Create an AMP HTML Content with the specified MIME type and content.
:param content: The AMP HTML content.
:type content: string
"""
self._content = None
... | class AmpHtmlContent(Content):
"""AMP HTML content to be included in your email."""
def __init__(self, content):
"""Create an AMP HTML Content with the specified MIME type and content.
:param content: The AMP HTML content.
:type content: string
"""
self._content = None
... | content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is not None:
content["value"] = self.content
return content
| """
Get a JSON-ready representation of this AmpContent.
:returns: This AmpContent, ready for use in a request body.
:rtype: dict
"""
content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is not None:
... | 21 | 336 | 63 | 399 | from .content import Content
from .validators import ValidateApiKey
class AmpHtmlContent(Content):
"""AMP HTML content to be included in your email."""
def __init__(self, content):
"""Create an AMP HTML Content with the specified MIME type and content.
:param content: The AMP HTML content.
... | from .content import Content
from .validators import ValidateApiKey
class AmpHtmlContent(Content):
"""AMP HTML content to be included in your email."""
def __init__(self, content):
"""Create an AMP HTML Content with the specified MIME type and content.
:param content: The AMP HTML content.
... |
49,893 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/asm.py | 54,56 | 5,81 | groups_to_display | Asm | 62,67 | 56,67 | class Asm(object):
"""An object specifying unsubscribe behavior."""
def __init__(self, group_id, groups_to_display=None):
"""Create an ASM with the given group_id and groups_to_display.
:param group_id: ID of an unsubscribe group
:type group_id: GroupId, int, required
:param gr... | class Asm(object):
"""An object specifying unsubscribe behavior."""
def __init__(self, group_id, groups_to_display=None):
"""Create an ASM with the given group_id and groups_to_display.
:param group_id: ID of an unsubscribe group
:type group_id: GroupId, int, required
:param gr... | if isinstance(value, GroupsToDisplay):
self._groups_to_display = value
else:
self._groups_to_display = GroupsToDisplay(value)
| """An array containing the unsubscribe groups that you would like to
be displayed on the unsubscribe preferences page. Max of 25 groups.
:param groups_to_display: Unsubscribe groups to display
:type groups_to_display: GroupsToDisplay, list(int), optional
"""
if isinstanc... | 10 | 650 | 51 | 701 | from .group_id import GroupId
from .groups_to_display import GroupsToDisplay
class Asm(object):
"""An object specifying unsubscribe behavior."""
def __init__(self, group_id, groups_to_display=None):
"""Create an ASM with the given group_id and groups_to_display.
:param group_id: ID of an uns... | from .group_id import GroupId
from .groups_to_display import GroupsToDisplay
class Asm(object):
"""An object specifying unsubscribe behavior."""
def __init__(self, group_id, groups_to_display=None):
"""Create an ASM with the given group_id and groups_to_display.
:param group_id: ID of an uns... |
49,894 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/attachment.py | 167,169 | 8,219 | content_id | Attachment | 176,178 | 169,178 | class Attachment(object):
"""An attachment to be included with an email."""
def __init__(
self,
file_content=None,
file_name=None,
file_type=None,
disposition=None,
content_id=None):
"""Create an Attachment
:param file_con... | class Attachment(object):
"""An attachment to be included with an email."""
def __init__(
self,
file_content=None,
file_name=None,
file_type=None,
disposition=None,
content_id=None):
"""Create an Attachment
:param file_con... | return self._content_id
| """The content id for the attachment.
This is used when the disposition is set to "inline" and the attachment
is an image, allowing the file to be displayed within the email body.
:rtype: string
"""
return self._content_id
| 2 | 1,819 | 11 | 1,830 | from .file_content import FileContent
from .file_type import FileType
from .file_name import FileName
from .disposition import Disposition
from .content_id import ContentId
class Attachment(object):
"""An attachment to be included with an email."""
def __init__(
self,
file_content=Non... | from .file_content import FileContent
from .file_type import FileType
from .file_name import FileName
from .disposition import Disposition
from .content_id import ContentId
class Attachment(object):
"""An attachment to be included with an email."""
def __init__(
self,
file_content=Non... |
49,895 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/batch_id.py | 43,44 | 1,51 | get | BatchId | 50,51 | 44,51 | class BatchId(object):
"""This ID represents a batch of emails to be sent at the same time.
Including a batch_id in your request allows you include this email
in that batch, and also enables you to cancel or pause the delivery
of that batch. For more information, see
https://sendgrid.com... | class BatchId(object):
"""This ID represents a batch of emails to be sent at the same time.
Including a batch_id in your request allows you include this email
in that batch, and also enables you to cancel or pause the delivery
of that batch. For more information, see
https://sendgrid.com... | return self.batch_id
| """
Get a JSON-ready representation of this BatchId object.
:returns: The BatchId, ready for use in a request body.
:rtype: string
"""
return self.batch_id
| 2 | 380 | 9 | 389 | class BatchId(object):
"""This ID represents a batch of emails to be sent at the same time.
Including a batch_id in your request allows you include this email
in that batch, and also enables you to cancel or pause the delivery
of that batch. For more information, see
https://sendgrid.com... | class BatchId(object):
"""This ID represents a batch of emails to be sent at the same time.
Including a batch_id in your request allows you include this email
in that batch, and also enables you to cancel or pause the delivery
of that batch. For more information, see
https://sendgrid.com... |
49,896 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/bcc_settings.py | 59,60 | 1,73 | get | BccSettings | 66,73 | 60,73 | class BccSettings(object):
"""Settings object for automatic BCC.
This allows you to have a blind carbon copy automatically sent to the
specified email address for every email that is sent.
"""
def __init__(self, enable=None, email=None):
"""Create a BCCSettings.
:param enable: Whe... | class BccSettings(object):
"""Settings object for automatic BCC.
This allows you to have a blind carbon copy automatically sent to the
specified email address for every email that is sent.
"""
def __init__(self, enable=None, email=None):
"""Create a BCCSettings.
:param enable: Whe... | bcc_settings = {}
if self.enable is not None:
bcc_settings["enable"] = self.enable
if self.email is not None:
bcc_settings["email"] = self.email.get()
return bcc_settings
| """
Get a JSON-ready representation of this BCCSettings.
:returns: This BCCSettings, ready for use in a request body.
:rtype: dict
"""
bcc_settings = {}
if self.enable is not None:
bcc_settings["enable"] = self.enable
if self.email is not Non... | 21 | 458 | 72 | 530 | class BccSettings(object):
"""Settings object for automatic BCC.
This allows you to have a blind carbon copy automatically sent to the
specified email address for every email that is sent.
"""
def __init__(self, enable=None, email=None):
"""Create a BCCSettings.
:param enable: Whe... | class BccSettings(object):
"""Settings object for automatic BCC.
This allows you to have a blind carbon copy automatically sent to the
specified email address for every email that is sent.
"""
def __init__(self, enable=None, email=None):
"""Create a BCCSettings.
:param enable: Whe... |
49,897 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/bcc_settings_email.py | 24,26 | 1,41 | bcc_settings_email | BccSettingsEmail | 31,33 | 26,33 | class BccSettingsEmail(object):
"""The BccSettingsEmail of an Attachment."""
def __init__(self, bcc_settings_email=None):
"""Create a BccSettingsEmail object
:param bcc_settings_email: The email address that you would like to
receive the BCC
:type bcc... | class BccSettingsEmail(object):
"""The BccSettingsEmail of an Attachment."""
def __init__(self, bcc_settings_email=None):
"""Create a BccSettingsEmail object
:param bcc_settings_email: The email address that you would like to
receive the BCC
:type bcc... | self._bcc_settings_email = value
| """The email address that you would like to receive the BCC
:param value: The email address that you would like to receive the BCC
:type value: string
"""
self._bcc_settings_email = value
| 3 | 337 | 15 | 352 | class BccSettingsEmail(object):
"""The BccSettingsEmail of an Attachment."""
def __init__(self, bcc_settings_email=None):
"""Create a BccSettingsEmail object
:param bcc_settings_email: The email address that you would like to
receive the BCC
:type bcc... | class BccSettingsEmail(object):
"""The BccSettingsEmail of an Attachment."""
def __init__(self, bcc_settings_email=None):
"""Create a BccSettingsEmail object
:param bcc_settings_email: The email address that you would like to
receive the BCC
:type bcc... |
49,898 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/bypass_bounce_management.py | 38,39 | 1,49 | get | BypassBounceManagement | 45,49 | 39,49 | class BypassBounceManagement(object):
"""Setting for Bypass Bounce Management
Allows you to bypass the bounce list to ensure that the email is delivered to recipients.
Spam report and unsubscribe lists will still be checked; addresses on these other lists
will not receive the message. This filter cann... | class BypassBounceManagement(object):
"""Setting for Bypass Bounce Management
Allows you to bypass the bounce list to ensure that the email is delivered to recipients.
Spam report and unsubscribe lists will still be checked; addresses on these other lists
will not receive the message. This filter cann... | bypass_bounce_management = {}
if self.enable is not None:
bypass_bounce_management["enable"] = self.enable
return bypass_bounce_management
| """
Get a JSON-ready representation of this BypassBounceManagement.
:returns: This BypassBounceManagement, ready for use in a request body.
:rtype: dict
"""
bypass_bounce_management = {}
if self.enable is not None:
bypass_bounce_management["enable"] =... | 13 | 338 | 48 | 386 | class BypassBounceManagement(object):
"""Setting for Bypass Bounce Management
Allows you to bypass the bounce list to ensure that the email is delivered to recipients.
Spam report and unsubscribe lists will still be checked; addresses on these other lists
will not receive the message. This filter cann... | class BypassBounceManagement(object):
"""Setting for Bypass Bounce Management
Allows you to bypass the bounce list to ensure that the email is delivered to recipients.
Spam report and unsubscribe lists will still be checked; addresses on these other lists
will not receive the message. This filter cann... |
49,899 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/bypass_list_management.py | 21,23 | 1,49 | enable | BypassListManagement | 27,29 | 23,29 | class BypassListManagement(object):
"""Setting for Bypass List Management
Allows you to bypass all unsubscribe groups and suppressions to ensure that
the email is delivered to every single recipient. This should only be used
in emergencies when it is absolutely necessary that every recipient
receiv... | class BypassListManagement(object):
"""Setting for Bypass List Management
Allows you to bypass all unsubscribe groups and suppressions to ensure that
the email is delivered to every single recipient. This should only be used
in emergencies when it is absolutely necessary that every recipient
receiv... | return self._enable
| """Indicates if this setting is enabled.
:rtype: boolean
"""
return self._enable
| 2 | 354 | 9 | 363 | class BypassListManagement(object):
"""Setting for Bypass List Management
Allows you to bypass all unsubscribe groups and suppressions to ensure that
the email is delivered to every single recipient. This should only be used
in emergencies when it is absolutely necessary that every recipient
receiv... | class BypassListManagement(object):
"""Setting for Bypass List Management
Allows you to bypass all unsubscribe groups and suppressions to ensure that
the email is delivered to every single recipient. This should only be used
in emergencies when it is absolutely necessary that every recipient
receiv... |
49,900 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/bypass_spam_management.py | 37,38 | 1,48 | get | BypassSpamManagement | 44,48 | 38,48 | class BypassSpamManagement(object):
"""Setting for Bypass Spam Management
Allows you to bypass the spam report list to ensure that the email is delivered to recipients.
Bounce and unsubscribe lists will still be checked; addresses on these other lists will not
receive the message. This filter cannot be... | class BypassSpamManagement(object):
"""Setting for Bypass Spam Management
Allows you to bypass the spam report list to ensure that the email is delivered to recipients.
Bounce and unsubscribe lists will still be checked; addresses on these other lists will not
receive the message. This filter cannot be... | bypass_spam_management = {}
if self.enable is not None:
bypass_spam_management["enable"] = self.enable
return bypass_spam_management
| """
Get a JSON-ready representation of this BypassSpamManagement.
:returns: This BypassSpamManagement, ready for use in a request body.
:rtype: dict
"""
bypass_spam_management = {}
if self.enable is not None:
bypass_spam_management["enable"] = self.en... | 13 | 337 | 48 | 385 | class BypassSpamManagement(object):
"""Setting for Bypass Spam Management
Allows you to bypass the spam report list to ensure that the email is delivered to recipients.
Bounce and unsubscribe lists will still be checked; addresses on these other lists will not
receive the message. This filter cannot be... | class BypassSpamManagement(object):
"""Setting for Bypass Spam Management
Allows you to bypass the spam report list to ensure that the email is delivered to recipients.
Bounce and unsubscribe lists will still be checked; addresses on these other lists will not
receive the message. This filter cannot be... |
49,901 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/bypass_unsubscribe_management.py | 30,32 | 1,50 | enable | BypassUnsubscribeManagement | 37,39 | 32,39 | class BypassUnsubscribeManagement(object):
"""Setting for Bypass Unsubscribe Management
Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients.
Bounce and spam report lists will still be checked; addresses on these other lists will not receive
the message.... | class BypassUnsubscribeManagement(object):
"""Setting for Bypass Unsubscribe Management
Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients.
Bounce and spam report lists will still be checked; addresses on these other lists will not receive
the message.... | self._enable = value
| """Indicates if this setting is enabled.
:param value: Indicates if this setting is enabled.
:type value: boolean
"""
self._enable = value
| 3 | 399 | 10 | 409 | class BypassUnsubscribeManagement(object):
"""Setting for Bypass Unsubscribe Management
Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients.
Bounce and spam report lists will still be checked; addresses on these other lists will not receive
the message.... | class BypassUnsubscribeManagement(object):
"""Setting for Bypass Unsubscribe Management
Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients.
Bounce and spam report lists will still be checked; addresses on these other lists will not receive
the message.... |
49,902 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/category.py | 23,25 | 1,41 | name | Category | 31,33 | 25,33 | class Category(object):
"""A category name for this message."""
def __init__(self, name=None):
"""Create a Category.
:param name: The name of this category
:type name: string, optional
"""
self._name = None
if name is not None:
self.name = name
... | class Category(object):
"""A category name for this message."""
def __init__(self, name=None):
"""Create a Category.
:param name: The name of this category
:type name: string, optional
"""
self._name = None
if name is not None:
self.name = name
... | self._name = value
| """The name of this Category. Must be less than 255 characters.
:param value: The name of this Category. Must be less than 255
characters.
:type value: string
"""
self._name = value
| 3 | 267 | 10 | 277 | class Category(object):
"""A category name for this message."""
def __init__(self, name=None):
"""Create a Category.
:param name: The name of this category
:type name: string, optional
"""
self._name = None
if name is not None:
self.name = name
... | class Category(object):
"""A category name for this message."""
def __init__(self, name=None):
"""Create a Category.
:param name: The name of this category
:type name: string, optional
"""
self._name = None
if name is not None:
self.name = name
... |
49,903 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/click_tracking.py | 58,59 | 1,72 | get | ClickTracking | 65,72 | 59,72 | class ClickTracking(object):
"""Allows you to track whether a recipient clicked a link in your email."""
def __init__(self, enable=None, enable_text=None):
"""Create a ClickTracking to track clicked links in your email.
:param enable: Whether click tracking is enabled
:type enable: boo... | class ClickTracking(object):
"""Allows you to track whether a recipient clicked a link in your email."""
def __init__(self, enable=None, enable_text=None):
"""Create a ClickTracking to track clicked links in your email.
:param enable: Whether click tracking is enabled
:type enable: boo... | click_tracking = {}
if self.enable is not None:
click_tracking["enable"] = self.enable
if self.enable_text is not None:
click_tracking["enable_text"] = self.enable_text
return click_tracking
| """
Get a JSON-ready representation of this ClickTracking.
:returns: This ClickTracking, ready for use in a request body.
:rtype: dict
"""
click_tracking = {}
if self.enable is not None:
click_tracking["enable"] = self.enable
if self.enable_t... | 21 | 488 | 75 | 563 | class ClickTracking(object):
"""Allows you to track whether a recipient clicked a link in your email."""
def __init__(self, enable=None, enable_text=None):
"""Create a ClickTracking to track clicked links in your email.
:param enable: Whether click tracking is enabled
:type enable: boo... | class ClickTracking(object):
"""Allows you to track whether a recipient clicked a link in your email."""
def __init__(self, enable=None, enable_text=None):
"""Create a ClickTracking to track clicked links in your email.
:param enable: Whether click tracking is enabled
:type enable: boo... |
49,904 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/content.py | 68,69 | 5,82 | get | Content | 75,82 | 69,82 | class Content(object):
"""Content to be included in your email.
You must specify at least one mime type in the Contents of your email.
"""
def __init__(self, mime_type, content):
"""Create a Content with the specified MIME type and content.
:param mime_type: MIME type of this Content ... | class Content(object):
"""Content to be included in your email.
You must specify at least one mime type in the Contents of your email.
"""
def __init__(self, mime_type, content):
"""Create a Content with the specified MIME type and content.
:param mime_type: MIME type of this Content ... | content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is not None:
content["value"] = self.content
return content
| """
Get a JSON-ready representation of this Content.
:returns: This Content, ready for use in a request body.
:rtype: dict
"""
content = {}
if self.mime_type is not None:
content["type"] = self.mime_type
if self.content is not None:
... | 21 | 594 | 63 | 657 | from .validators import ValidateApiKey
class Content(object):
"""Content to be included in your email.
You must specify at least one mime type in the Contents of your email.
"""
def __init__(self, mime_type, content):
"""Create a Content with the specified MIME type and content.
:p... | from .validators import ValidateApiKey
class Content(object):
"""Content to be included in your email.
You must specify at least one mime type in the Contents of your email.
"""
def __init__(self, mime_type, content):
"""Create a Content with the specified MIME type and content.
:p... |
49,905 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/content_id.py | 18,20 | 1,51 | content_id | ContentId | 27,29 | 20,29 | class ContentId(object):
"""The ContentId of an Attachment."""
def __init__(self, content_id=None):
"""Create a ContentId object
:param content_id: The content id for the attachment.
This is used when the Disposition is set to "inline"
and ... | class ContentId(object):
"""The ContentId of an Attachment."""
def __init__(self, content_id=None):
"""Create a ContentId object
:param content_id: The content id for the attachment.
This is used when the Disposition is set to "inline"
and ... | return self._content_id
| """The content id for the attachment.
This is used when the Disposition is set to "inline" and the
attachment is an image, allowing the file to be displayed within
the email body.
:rtype: string
"""
return self._content_id
| 2 | 416 | 11 | 427 | class ContentId(object):
"""The ContentId of an Attachment."""
def __init__(self, content_id=None):
"""Create a ContentId object
:param content_id: The content id for the attachment.
This is used when the Disposition is set to "inline"
and ... | class ContentId(object):
"""The ContentId of an Attachment."""
def __init__(self, content_id=None):
"""Create a ContentId object
:param content_id: The content id for the attachment.
This is used when the Disposition is set to "inline"
and ... |
49,906 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/custom_arg.py | 32,34 | 1,95 | key | CustomArg | 38,40 | 34,40 | class CustomArg(object):
"""Values that will be carried along with the email and its activity data.
Substitutions will not be made on custom arguments, so any string entered
into this parameter will be assumed to be the custom argument that you
would like to be used. Top-level CustomArgs may be overrid... | class CustomArg(object):
"""Values that will be carried along with the email and its activity data.
Substitutions will not be made on custom arguments, so any string entered
into this parameter will be assumed to be the custom argument that you
would like to be used. Top-level CustomArgs may be overrid... | return self._key
| """Key for this CustomArg.
:rtype: string
"""
return self._key
| 2 | 682 | 9 | 691 | class CustomArg(object):
"""Values that will be carried along with the email and its activity data.
Substitutions will not be made on custom arguments, so any string entered
into this parameter will be assumed to be the custom argument that you
would like to be used. Top-level CustomArgs may be overrid... | class CustomArg(object):
"""Values that will be carried along with the email and its activity data.
Substitutions will not be made on custom arguments, so any string entered
into this parameter will be assumed to be the custom argument that you
would like to be used. Top-level CustomArgs may be overrid... |
49,907 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/disposition.py | 41,43 | 1,73 | disposition | Disposition | 63,65 | 43,65 | class Disposition(object):
"""The content-disposition of the Attachment specifying how you would like
the attachment to be displayed."""
def __init__(self, disposition=None):
"""Create a Disposition object
:param disposition: The content-disposition of the attachment,
... | class Disposition(object):
"""The content-disposition of the Attachment specifying how you would like
the attachment to be displayed."""
def __init__(self, disposition=None):
"""Create a Disposition object
:param disposition: The content-disposition of the attachment,
... | self._disposition = value
| """The content-disposition of the attachment, specifying display style.
Specifies how you would like the attachment to be displayed.
- "inline" results in the attached file being displayed
automatically within the message.
- "attachment" results in the attached file... | 3 | 653 | 11 | 664 | class Disposition(object):
"""The content-disposition of the Attachment specifying how you would like
the attachment to be displayed."""
def __init__(self, disposition=None):
"""Create a Disposition object
:param disposition: The content-disposition of the attachment,
... | class Disposition(object):
"""The content-disposition of the Attachment specifying how you would like
the attachment to be displayed."""
def __init__(self, disposition=None):
"""Create a Disposition object
:param disposition: The content-disposition of the attachment,
... |
49,908 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/dynamic_template_data.py | 41,43 | 1,74 | personalization | DynamicTemplateData | 47,49 | 43,49 | class DynamicTemplateData(object):
"""To send a dynamic template, specify the template ID with the
template_id parameter.
"""
def __init__(self, dynamic_template_data=None, p=0):
"""Data for a transactional template.
Should be JSON-serializable structure.
:param dynamic_temp... | class DynamicTemplateData(object):
"""To send a dynamic template, specify the template ID with the
template_id parameter.
"""
def __init__(self, dynamic_template_data=None, p=0):
"""Data for a transactional template.
Should be JSON-serializable structure.
:param dynamic_temp... | return self._personalization
| """The Personalization object or Personalization object index
:rtype: Personalization, integer
"""
return self._personalization
| 2 | 563 | 10 | 573 | class DynamicTemplateData(object):
"""To send a dynamic template, specify the template ID with the
template_id parameter.
"""
def __init__(self, dynamic_template_data=None, p=0):
"""Data for a transactional template.
Should be JSON-serializable structure.
:param dynamic_temp... | class DynamicTemplateData(object):
"""To send a dynamic template, specify the template ID with the
template_id parameter.
"""
def __init__(self, dynamic_template_data=None, p=0):
"""Data for a transactional template.
Should be JSON-serializable structure.
:param dynamic_temp... |
49,909 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/email.py | 82,84 | 13,229 | email | Email | 92,94 | 84,94 | class Email(object):
"""An email address with an optional name."""
def __init__(self,
email=None,
name=None,
substitutions=None,
subject=None,
p=0,
dynamic_template_data=None):
"""Create an Email with ... | class Email(object):
"""An email address with an optional name."""
def __init__(self,
email=None,
name=None,
substitutions=None,
subject=None,
p=0,
dynamic_template_data=None):
"""Create an Email with ... | return self._email
| """Email address.
See http://tools.ietf.org/html/rfc3696#section-3 and its errata
http://www.rfc-editor.org/errata_search.php?rfc=3696 for information
on valid email addresses.
:rtype: string
"""
return self._email
| 2 | 1,802 | 9 | 1,811 | try:
import rfc822
except ImportError:
import email.utils as rfc822
try:
basestring = basestring
except NameError:
# Define basestring when Python >= 3.0
basestring = str
class Email(object):
"""An email address with an optional name."""
def __init__(self,
email=None,
... | try:
import rfc822
except ImportError:
import email.utils as rfc822
try:
basestring = basestring
except NameError:
# Define basestring when Python >= 3.0
basestring = str
class Email(object):
"""An email address with an optional name."""
def __init__(self,
email=None,
... |
49,910 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/exceptions.py | 58,60 | 11,66 | message | ApiKeyIncludedException | 65,66 | 60,66 | class ApiKeyIncludedException(SendGridException):
"""Exception raised for when Twilio SendGrid API Key included in message text"""
def __init__(self,
expression="Email body",
message="Twilio SendGrid API Key detected"):
"""Create an exception for when Twilio SendGrid A... | class ApiKeyIncludedException(SendGridException):
"""Exception raised for when Twilio SendGrid API Key included in message text"""
def __init__(self,
expression="Email body",
message="Twilio SendGrid API Key detected"):
"""Create an exception for when Twilio SendGrid A... | self._message = value
| """Explanation of the error
:param value: Explanation of the error
:type value: string
"""
self._message = value
| 3 | 366 | 8 | 374 | ################################################################
# Various types of extensible Twilio SendGrid related exceptions
################################################################
class SendGridException(Exception):
"""Wrapper/default SendGrid-related exception"""
pass
class ApiKeyIncludedExc... | ################################################################
# Various types of extensible Twilio SendGrid related exceptions
################################################################
class SendGridException(Exception):
"""Wrapper/default SendGrid-related exception"""
pass
class ApiKeyIncludedExc... |
49,911 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/file_content.py | 32,33 | 1,40 | get | FileContent | 39,40 | 33,40 | class FileContent(object):
"""The Base64 encoded content of an Attachment."""
def __init__(self, file_content=None):
"""Create a FileContent object
:param file_content: The Base64 encoded content of the attachment
:type file_content: string, optional
"""
self._file_cont... | class FileContent(object):
"""The Base64 encoded content of an Attachment."""
def __init__(self, file_content=None):
"""Create a FileContent object
:param file_content: The Base64 encoded content of the attachment
:type file_content: string, optional
"""
self._file_cont... | return self.file_content
| """
Get a JSON-ready representation of this FileContent.
:returns: This FileContent, ready for use in a request body.
:rtype: string
"""
return self.file_content
| 2 | 285 | 9 | 294 | class FileContent(object):
"""The Base64 encoded content of an Attachment."""
def __init__(self, file_content=None):
"""Create a FileContent object
:param file_content: The Base64 encoded content of the attachment
:type file_content: string, optional
"""
self._file_cont... | class FileContent(object):
"""The Base64 encoded content of an Attachment."""
def __init__(self, file_content=None):
"""Create a FileContent object
:param file_content: The Base64 encoded content of the attachment
:type file_content: string, optional
"""
self._file_cont... |
49,912 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/file_name.py | 23,25 | 1,40 | file_name | FileName | 30,32 | 25,32 | class FileName(object):
"""The filename of an Attachment."""
def __init__(self, file_name=None):
"""Create a FileName object
:param file_name: The file name of the attachment
:type file_name: string, optional
"""
self._file_name = None
if file_name is not None:... | class FileName(object):
"""The filename of an Attachment."""
def __init__(self, file_name=None):
"""Create a FileName object
:param file_name: The file name of the attachment
:type file_name: string, optional
"""
self._file_name = None
if file_name is not None:... | self._file_name = value
| """The file name of the attachment.
:param value: The file name of the attachment.
:type value: string
"""
self._file_name = value
| 3 | 267 | 12 | 279 | class FileName(object):
"""The filename of an Attachment."""
def __init__(self, file_name=None):
"""Create a FileName object
:param file_name: The file name of the attachment
:type file_name: string, optional
"""
self._file_name = None
if file_name is not None:... | class FileName(object):
"""The filename of an Attachment."""
def __init__(self, file_name=None):
"""Create a FileName object
:param file_name: The file name of the attachment
:type file_name: string, optional
"""
self._file_name = None
if file_name is not None:... |
49,913 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/file_type.py | 23,25 | 1,40 | file_type | FileType | 30,32 | 25,32 | class FileType(object):
"""The MIME type of the content you are attaching to an Attachment."""
def __init__(self, file_type=None):
"""Create a FileType object
:param file_type: The MIME type of the content you are attaching
:type file_type: string, optional
"""
self._fi... | class FileType(object):
"""The MIME type of the content you are attaching to an Attachment."""
def __init__(self, file_type=None):
"""Create a FileType object
:param file_type: The MIME type of the content you are attaching
:type file_type: string, optional
"""
self._fi... | self._file_type = mime_type
| """The MIME type of the content you are attaching.
:param mime_type: The MIME type of the content you are attaching.
:rtype mime_type: string
"""
self._file_type = mime_type
| 3 | 306 | 15 | 321 | class FileType(object):
"""The MIME type of the content you are attaching to an Attachment."""
def __init__(self, file_type=None):
"""Create a FileType object
:param file_type: The MIME type of the content you are attaching
:type file_type: string, optional
"""
self._fi... | class FileType(object):
"""The MIME type of the content you are attaching to an Attachment."""
def __init__(self, file_type=None):
"""Create a FileType object
:param file_type: The MIME type of the content you are attaching
:type file_type: string, optional
"""
self._fi... |
49,914 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/footer_html.py | 15,17 | 1,40 | footer_html | FooterHtml | 21,23 | 17,23 | class FooterHtml(object):
"""The HTML in a Footer."""
def __init__(self, footer_html=None):
"""Create a FooterHtml object
:param footer_html: The html content of your footer.
:type footer_html: string, optional
"""
self._footer_html = None
if footer_html is not... | class FooterHtml(object):
"""The HTML in a Footer."""
def __init__(self, footer_html=None):
"""Create a FooterHtml object
:param footer_html: The html content of your footer.
:type footer_html: string, optional
"""
self._footer_html = None
if footer_html is not... | return self._footer_html
| """The html content of your footer.
:rtype: string
"""
return self._footer_html
| 2 | 284 | 11 | 295 | class FooterHtml(object):
"""The HTML in a Footer."""
def __init__(self, footer_html=None):
"""Create a FooterHtml object
:param footer_html: The html content of your footer.
:type footer_html: string, optional
"""
self._footer_html = None
if footer_html is not... | class FooterHtml(object):
"""The HTML in a Footer."""
def __init__(self, footer_html=None):
"""Create a FooterHtml object
:param footer_html: The html content of your footer.
:type footer_html: string, optional
"""
self._footer_html = None
if footer_html is not... |
49,915 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/footer_settings.py | 78,79 | 1,95 | get | FooterSettings | 85,95 | 79,95 | class FooterSettings(object):
"""The default footer that you would like included on every email."""
def __init__(self, enable=None, text=None, html=None):
"""Create a default footer.
:param enable: Whether this footer should be applied.
:type enable: boolean, optional
:param te... | class FooterSettings(object):
"""The default footer that you would like included on every email."""
def __init__(self, enable=None, text=None, html=None):
"""Create a default footer.
:param enable: Whether this footer should be applied.
:type enable: boolean, optional
:param te... | footer_settings = {}
if self.enable is not None:
footer_settings["enable"] = self.enable
if self.text is not None:
footer_settings["text"] = self.text.get()
if self.html is not None:
footer_settings["html"] = self.html.get()
return footer_set... | """
Get a JSON-ready representation of this FooterSettings.
:returns: This FooterSettings, ready for use in a request body.
:rtype: dict
"""
footer_settings = {}
if self.enable is not None:
footer_settings["enable"] = self.enable
if self.text... | 29 | 566 | 102 | 668 | class FooterSettings(object):
"""The default footer that you would like included on every email."""
def __init__(self, enable=None, text=None, html=None):
"""Create a default footer.
:param enable: Whether this footer should be applied.
:type enable: boolean, optional
:param te... | class FooterSettings(object):
"""The default footer that you would like included on every email."""
def __init__(self, enable=None, text=None, html=None):
"""Create a default footer.
:param enable: Whether this footer should be applied.
:type enable: boolean, optional
:param te... |
49,916 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/footer_text.py | 32,33 | 1,40 | get | FooterText | 39,40 | 33,40 | class FooterText(object):
"""The text in an Footer."""
def __init__(self, footer_text=None):
"""Create a FooterText object
:param footer_text: The plain text content of your footer.
:type footer_text: string, optional
"""
self._footer_text = None
if footer_text... | class FooterText(object):
"""The text in an Footer."""
def __init__(self, footer_text=None):
"""Create a FooterText object
:param footer_text: The plain text content of your footer.
:type footer_text: string, optional
"""
self._footer_text = None
if footer_text... | return self.footer_text
| """
Get a JSON-ready representation of this FooterText.
:returns: This FooterText, ready for use in a request body.
:rtype: string
"""
return self.footer_text
| 2 | 289 | 9 | 298 | class FooterText(object):
"""The text in an Footer."""
def __init__(self, footer_text=None):
"""Create a FooterText object
:param footer_text: The plain text content of your footer.
:type footer_text: string, optional
"""
self._footer_text = None
if footer_text... | class FooterText(object):
"""The text in an Footer."""
def __init__(self, footer_text=None):
"""Create a FooterText object
:param footer_text: The plain text content of your footer.
:type footer_text: string, optional
"""
self._footer_text = None
if footer_text... |
49,917 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/ganalytics.py | 156,157 | 1,177 | get | Ganalytics | 163,177 | 157,177 | class Ganalytics(object):
"""Allows you to enable tracking provided by Google Analytics."""
def __init__(self,
enable=None,
utm_source=None,
utm_medium=None,
utm_term=None,
utm_content=None,
utm_campaign=None)... | class Ganalytics(object):
"""Allows you to enable tracking provided by Google Analytics."""
def __init__(self,
enable=None,
utm_source=None,
utm_medium=None,
utm_term=None,
utm_content=None,
utm_campaign=None)... | keys = ["enable", "utm_source", "utm_medium", "utm_term",
"utm_content", "utm_campaign"]
ganalytics = {}
for key in keys:
value = getattr(self, key, None)
if value is not None:
if isinstance(value, bool) or isinstance(value, str):
... | """
Get a JSON-ready representation of this Ganalytics.
:returns: This Ganalytics, ready for use in a request body.
:rtype: dict
"""
keys = ["enable", "utm_source", "utm_medium", "utm_term",
"utm_content", "utm_campaign"]
ganalytics = {}
... | 40 | 1,329 | 143 | 1,472 | class Ganalytics(object):
"""Allows you to enable tracking provided by Google Analytics."""
def __init__(self,
enable=None,
utm_source=None,
utm_medium=None,
utm_term=None,
utm_content=None,
utm_campaign=None)... | class Ganalytics(object):
"""Allows you to enable tracking provided by Google Analytics."""
def __init__(self,
enable=None,
utm_source=None,
utm_medium=None,
utm_term=None,
utm_content=None,
utm_campaign=None)... |
49,918 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/group_id.py | 23,25 | 1,40 | group_id | GroupId | 30,32 | 25,32 | class GroupId(object):
"""The unsubscribe group ID to associate with this email."""
def __init__(self, group_id=None):
"""Create a GroupId object
:param group_id: The unsubscribe group to associate with this email.
:type group_id: integer, optional
"""
self._group_id = ... | class GroupId(object):
"""The unsubscribe group ID to associate with this email."""
def __init__(self, group_id=None):
"""Create a GroupId object
:param group_id: The unsubscribe group to associate with this email.
:type group_id: integer, optional
"""
self._group_id = ... | self._group_id = value
| """The unsubscribe group to associate with this email.
:param value: The unsubscribe group to associate with this email.
:type value: integer
"""
self._group_id = value
| 3 | 284 | 12 | 296 | class GroupId(object):
"""The unsubscribe group ID to associate with this email."""
def __init__(self, group_id=None):
"""Create a GroupId object
:param group_id: The unsubscribe group to associate with this email.
:type group_id: integer, optional
"""
self._group_id = ... | class GroupId(object):
"""The unsubscribe group ID to associate with this email."""
def __init__(self, group_id=None):
"""Create a GroupId object
:param group_id: The unsubscribe group to associate with this email.
:type group_id: integer, optional
"""
self._group_id = ... |
49,919 | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python | /home/hieuvd/dung_repo/raw/stars_03/sendgrid_sendgrid-python/sendgrid-python/sendgrid/helpers/mail/groups_to_display.py | 27,29 | 1,49 | groups_to_display | GroupsToDisplay | 37,41 | 29,41 | class GroupsToDisplay(object):
"""The unsubscribe groups that you would like to be displayed on the
unsubscribe preferences page.."""
def __init__(self, groups_to_display=None):
"""Create a GroupsToDisplay object
:param groups_to_display: An array containing the unsubscribe groups
... | class GroupsToDisplay(object):
"""The unsubscribe groups that you would like to be displayed on the
unsubscribe preferences page.."""
def __init__(self, groups_to_display=None):
"""Create a GroupsToDisplay object
:param groups_to_display: An array containing the unsubscribe groups
... | if value is not None and len(value) > 25:
raise ValueError("New groups_to_display exceeds max length of 25.")
self._groups_to_display = value
| """An array containing the unsubscribe groups that you would like to be
displayed on the unsubscribe preferences page.
:param value: An array containing the unsubscribe groups that you
would like to be displayed on the unsubscribe
preferences page.
... | 20 | 392 | 52 | 444 | class GroupsToDisplay(object):
"""The unsubscribe groups that you would like to be displayed on the
unsubscribe preferences page.."""
def __init__(self, groups_to_display=None):
"""Create a GroupsToDisplay object
:param groups_to_display: An array containing the unsubscribe groups
... | class GroupsToDisplay(object):
"""The unsubscribe groups that you would like to be displayed on the
unsubscribe preferences page.."""
def __init__(self, groups_to_display=None):
"""Create a GroupsToDisplay object
:param groups_to_display: An array containing the unsubscribe groups
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.