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
32,863
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/task_parameters.py
9,10
1,154
_canonize_validator
18,30
10,30
import six import attr from attr import validators __all__ = ["range_validator", "param", "percent_param", "TaskParameters"] def _canonize_validator(current_validator): FILL_FUNC_BODYdef range_validator(min_value, max_value): """ A parameter validator that checks range constraint on a parameter. :param...
import six import attr from attr import validators __all__ = ["range_validator", "param", "percent_param", "TaskParameters"] def _canonize_validator(current_validator): """ Convert current_validator to a new list and return it. If current_validator is None return an empty list. If current_validator...
if not current_validator: return [] if isinstance(current_validator, (list, tuple)): current_validator = list(current_validator) else: current_validator = [current_validator] return current_validator
""" Convert current_validator to a new list and return it. If current_validator is None return an empty list. If current_validator is a list, return a copy of it. If current_validator is another type of iterable, return a list version of it. If current_validator is a single value, return a one...
18
1,256
85
1,341
import six import attr from attr import validators __all__ = ["range_validator", "param", "percent_param", "TaskParameters"] def _canonize_validator(current_validator): FILL_FUNC_BODYdef range_validator(min_value, max_value): """ A parameter validator that checks range constraint on a parameter. :param...
import six import attr from attr import validators __all__ = ["range_validator", "param", "percent_param", "TaskParameters"] def _canonize_validator(current_validator): """ Convert current_validator to a new list and return it. If current_validator is None return an empty list. If current_validator...
32,864
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/task_parameters.py
141,142
101,154
connect
TaskParameters
152,154
142,154
@six.add_metaclass(_AttrsMeta) class TaskParameters(object): """ Base class for task parameters. Inherit this class to create a parameter set to connect to a task. Usage Example: class MyParams(TaskParameters): iterations = param( type=int, desc="Number of iteration...
@six.add_metaclass(_AttrsMeta) class TaskParameters(object): """ Base class for task parameters. Inherit this class to create a parameter set to connect to a task. Usage Example: class MyParams(TaskParameters): iterations = param( type=int, desc="Number of iteration...
return task.connect(self)
""" Connect to a task. When running locally, the task will save the parameters from self. When running with a worker, self will be updated according to the task's saved parameters. :param task: The task to connect to. :type task: .Task """ retur...
2
395
12
407
import six import attr from attr import validators __all__ = ["range_validator", "param", "percent_param", "TaskParameters"] def _canonize_validator(current_validator): """ Convert current_validator to a new list and return it. If current_validator is None return an empty list. If current_validator...
import six import attr from attr import validators __all__ = ["range_validator", "param", "percent_param", "TaskParameters"] def _canonize_validator(current_validator): """ Convert current_validator to a new list and return it. If current_validator is None return an empty list. If current_validator...
32,865
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/async_manager.py
38,40
8,68
wait_for_results
AsyncManagerMixin
40,61
40,61
class AsyncManagerMixin(object): _async_results_lock = SingletonLock() # per pid (process) list of async jobs (support for sub-processes forking) _async_results = {} @classmethod def _add_async_result(cls, result, wait_on_max_results=None, wait_time=30, wait_cb=None): while True: ...
class AsyncManagerMixin(object): _async_results_lock = SingletonLock() # per pid (process) list of async jobs (support for sub-processes forking) _async_results = {} @classmethod def _add_async_result(cls, result, wait_on_max_results=None, wait_time=30, wait_cb=None): while True: ...
remaining = timeout count = 0 pid = os.getpid() for r in cls._async_results.get(pid, []): if r.ready(): continue t = time.time() # bugfix for python2.7 threading issues if six.PY2 and not remaining: while not...
remaining = timeout count = 0 pid = os.getpid() for r in cls._async_results.get(pid, []): if r.ready(): continue t = time.time() # bugfix for python2.7 threading issues if six.PY2 and not remaining: while not...
70
462
204
666
import os import time import six from .process.mp import SingletonLock class AsyncManagerMixin(object): _async_results_lock = SingletonLock() # per pid (process) list of async jobs (support for sub-processes forking) _async_results = {} @classmethod def _add_async_result(cls, result, wait_on_max...
import os import time import six from .process.mp import SingletonLock class AsyncManagerMixin(object): _async_results_lock = SingletonLock() # per pid (process) list of async jobs (support for sub-processes forking) _async_results = {} @classmethod def _add_async_result(cls, result, wait_on_max...
32,866
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/check_updates.py
17,19
14,76
check_new_package_available
CheckPackageUpdates
22,62
19,62
class CheckPackageUpdates(object): _package_version_checked = False @classmethod def check_new_package_available(cls, only_once=False): FILL_FUNC_BODY @staticmethod def get_version_from_updates_server(cur_version): """ Get the latest version for clearml from updates server :p...
class CheckPackageUpdates(object): _package_version_checked = False @classmethod def check_new_package_available(cls, only_once=False): """ :return: True, if there is a newer package in PyPI. """ FILL_FUNC_BODY @staticmethod def get_version_from_updates_server(cur_version): ...
if only_once and cls._package_version_checked: return None # noinspection PyBroadException try: cls._package_version_checked = True client, version = Session._client[0] version = Version(version) is_demo = 'https://demoapi.demo.clear.m...
""" :return: True, if there is a newer package in PyPI. """ if only_once and cls._package_version_checked: return None # noinspection PyBroadException try: cls._package_version_checked = True client, version = Session._client[0] ...
103
205
443
648
from __future__ import absolute_import, division, print_function import json import os import requests from ..backend_api.session import Session from ..backend_config import EnvEntry from .version import Version class CheckPackageUpdates(object): _package_version_checked = False @classmethod def chec...
from __future__ import absolute_import, division, print_function import json import os import requests from ..backend_api.session import Session from ..backend_config import EnvEntry from .version import Version class CheckPackageUpdates(object): _package_version_checked = False @classmethod def chec...
32,867
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/config.py
55,56
1,118
config_dict_to_text
56,94
56,94
from __future__ import division import json import six import pyparsing from .dicts import hocon_quote_key, hocon_unquote_key from .pyhocon import ConfigFactory, HOCONConverter from ..storage.util import parse_size def parse_human_size(value): if isinstance(value, six.string_types): return parse_size(v...
from __future__ import division import json import six import pyparsing from .dicts import hocon_quote_key, hocon_unquote_key from .pyhocon import ConfigFactory, HOCONConverter from ..storage.util import parse_size def parse_human_size(value): if isinstance(value, six.string_types): return parse_size(v...
# if already string return as is if isinstance(config, six.string_types): return config if not isinstance(config, (dict, list)): raise ValueError("Configuration only supports dictionary/list objects") try: # noinspection PyBroadException try: def raise_on_spec...
# if already string return as is if isinstance(config, six.string_types): return config if not isinstance(config, (dict, list)): raise ValueError("Configuration only supports dictionary/list objects") try: # noinspection PyBroadException try: def raise_on_spec...
125
716
423
1,139
from __future__ import division import json import six import pyparsing from .dicts import hocon_quote_key, hocon_unquote_key from .pyhocon import ConfigFactory, HOCONConverter from ..storage.util import parse_size def parse_human_size(value): if isinstance(value, six.string_types): return parse_size(v...
from __future__ import division import json import six import pyparsing from .dicts import hocon_quote_key, hocon_unquote_key from .pyhocon import ConfigFactory, HOCONConverter from ..storage.util import parse_size def parse_human_size(value): if isinstance(value, six.string_types): return parse_size(v...
32,868
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/deferred.py
107,108
51,121
apply_before
DeferredExecution
114,121
108,121
class DeferredExecution(object): def __init__(self, pool_cls=DeferredExecutionPool): self._pools = ParameterizedDefaultDict(pool_cls) def __get__(self, instance, owner): if not instance: return self return self._pools[instance] def defer_execution(self, condition_or_at...
class DeferredExecution(object): def __init__(self, pool_cls=DeferredExecutionPool): self._pools = ParameterizedDefaultDict(pool_cls) def __get__(self, instance, owner): if not instance: return self return self._pools[instance] def defer_execution(self, condition_or_at...
def decorator(func): @wraps(func) def wrapper(instance, *args, **kwargs): self._apply(instance, condition_or_attr_name) return func(instance, *args, **kwargs) return wrapper return decorator
""" Decorator for applying deferred execution pool before wrapped function is executed :param condition_or_attr_name: Condition controlling whether deferred pool should be applied. True by default. If a callable is provided, it will be called with the class instance (self) as first a...
17
747
74
821
import threading from functools import wraps import attr import six class DeferredExecutionPool(object): @attr.s class _DeferredAction(object): method = attr.ib() args = attr.ib() kwargs = attr.ib() def __init__(self, instance): self._instance = instance self._poo...
import threading from functools import wraps import attr import six class DeferredExecutionPool(object): @attr.s class _DeferredAction(object): method = attr.ib() args = attr.ib() kwargs = attr.ib() def __init__(self, instance): self._instance = instance self._poo...
32,869
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/deferred.py
34,35
8,41
copy_from
DeferredExecutionPool
35,41
35,41
class DeferredExecutionPool(object): @attr.s class _DeferredAction(object): method = attr.ib() args = attr.ib() kwargs = attr.ib() def __init__(self, instance): self._instance = instance self._pool = [] self._lock = threading.Lock() def add(self, callabl...
class DeferredExecutionPool(object): @attr.s class _DeferredAction(object): method = attr.ib() args = attr.ib() kwargs = attr.ib() def __init__(self, instance): self._instance = instance self._pool = [] self._lock = threading.Lock() def add(self, callabl...
if not isinstance(self._instance, type(other._instance)): raise ValueError("Copy deferred actions must be with the same instance type") self._pool = other._pool[:]
if not isinstance(self._instance, type(other._instance)): raise ValueError("Copy deferred actions must be with the same instance type") self._pool = other._pool[:]
18
225
56
281
import threading from functools import wraps import attr import six class DeferredExecutionPool(object): @attr.s class _DeferredAction(object): method = attr.ib() args = attr.ib() kwargs = attr.ib() def __init__(self, instance): self._instance = instance self._poo...
import threading from functools import wraps import attr import six class DeferredExecutionPool(object): @attr.s class _DeferredAction(object): method = attr.ib() args = attr.ib() kwargs = attr.ib() def __init__(self, instance): self._instance = instance self._poo...
32,870
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/dicts.py
164,165
1,203
hocon_unquote_key
166,190
165,190
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
if isinstance(a_obj, list): return [hocon_unquote_key(a) for a in a_obj] elif isinstance(a_obj, tuple): return tuple(hocon_unquote_key(a) for a in a_obj) elif not isinstance(a_obj, dict): return a_obj a_dict = a_obj # ConfigTree to dict if hasattr(a_dict, 'as_plain_ord...
""" Recursively unquote \"key\" with '.' to key """ if isinstance(a_obj, list): return [hocon_unquote_key(a) for a in a_obj] elif isinstance(a_obj, tuple): return tuple(hocon_unquote_key(a) for a in a_obj) elif not isinstance(a_obj, dict): return a_obj a_dict = a_obj #...
73
1,571
290
1,861
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
32,871
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/dicts.py
30,32
20,39
data
Logs
32,34
32,34
class Logs: _logs_instances = [] def __init__(self, data=None): self._data = data or {} self._logs_instances.append(self) def reset(self): self._data = {} @property def data(self): FILL_FUNC_BODY @classmethod def get_instances(cls): return cls._logs_instance...
class Logs: _logs_instances = [] def __init__(self, data=None): self._data = data or {} self._logs_instances.append(self) def reset(self): self._data = {} @property def data(self): FILL_FUNC_BODY @classmethod def get_instances(cls): return cls._logs_instance...
return self._data
return self._data
2
116
9
125
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
32,872
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/dicts.py
96,97
62,118
_keys
NestedBlobsDict
97,114
97,114
class NestedBlobsDict(BlobsDict): """A dictionary that applies an arbitrary key-altering function before accessing the keys.""" def __init__(self, *args, **kwargs): super(NestedBlobsDict, self).__init__(*args, **kwargs) def __getitem__(self, keys_str=''): if keys_str == '': ...
class NestedBlobsDict(BlobsDict): """A dictionary that applies an arbitrary key-altering function before accessing the keys.""" def __init__(self, *args, **kwargs): super(NestedBlobsDict, self).__init__(*args, **kwargs) def __getitem__(self, keys_str=''): if keys_str == '': ...
deep_keys = [] cur_keys = dict.keys(cur_dict) for key in cur_keys: if isinstance(cur_dict[key], dict): if len(path) > 0: deep_keys.extend(self._keys(cur_dict[key], path + '.' + key)) else: deep_keys.extend(self....
deep_keys = [] cur_keys = dict.keys(cur_dict) for key in cur_keys: if isinstance(cur_dict[key], dict): if len(path) > 0: deep_keys.extend(self._keys(cur_dict[key], path + '.' + key)) else: deep_keys.extend(self....
40
340
172
512
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
32,873
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/dicts.py
119,121
118,132
pip
RequirementsDict
121,123
121,123
class RequirementsDict(dict): @property def pip(self): FILL_FUNC_BODY @property def conda(self): return self.get("conda") @property def orig_pip(self): return self.get("orig_pip")
class RequirementsDict(dict): @property def pip(self): FILL_FUNC_BODY @property def conda(self): return self.get("conda") @property def orig_pip(self): return self.get("orig_pip")
return self.get("pip")
return self.get("pip")
2
80
12
92
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
""" Utilities """ from typing import Optional, Any _epsilon = 0.00001 class ReadOnlyDict(dict): def __readonly__(self, *args, **kwargs): raise ValueError("This is a read only dictionary") __setitem__ = __readonly__ __delitem__ = __readonly__ pop = __readonly__ popitem = __readonly__ c...
32,874
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/enum.py
8,10
4,21
values
EnumOptions
15,21
10,21
class EnumOptions(object): """ Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs """ __cache = None @classmethod def values(cls): FILL_FUNC_BODY
class EnumOptions(object): """ Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs """ __cache = None @classmethod def values(cls): """ Extract list of enum-like options based on the derived classes' attributes. Any class attr...
if cls.__cache is None: cls.__cache = [v for k, v in vars(cls).items() if not k.startswith('_') and not callable(v) and not isinstance(v, classmethod)] return cls.__cache
""" Extract list of enum-like options based on the derived classes' attributes. Any class attribute who's key doesn't start with an underscore and who's value is not a class method or callable is considered an option. Returns a list of attribute names representing the option...
24
133
75
208
""" Enum utilities """ class EnumOptions(object): """ Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs """ __cache = None @classmethod def values(cls): FILL_FUNC_BODYclass Options(object): @classmethod def _all(cls): return {...
""" Enum utilities """ class EnumOptions(object): """ Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs """ __cache = None @classmethod def values(cls): """ Extract list of enum-like options based on the derived classes' attributes. ...
32,875
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/enum.py
22,24
21,25
_all
Options
24,25
24,25
class Options(object): @classmethod def _all(cls): FILL_FUNC_BODY
class Options(object): @classmethod def _all(cls): FILL_FUNC_BODY
return {k: v for k, v in vars(cls) if not k.startswith('_')}
return {k: v for k, v in vars(cls) if not k.startswith('_')}
11
29
29
58
""" Enum utilities """ class EnumOptions(object): """ Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs """ __cache = None @classmethod def values(cls): """ Extract list of enum-like options based on the derived classes' attributes. ...
""" Enum utilities """ class EnumOptions(object): """ Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs """ __cache = None @classmethod def values(cls): """ Extract list of enum-like options based on the derived classes' attributes. ...
32,876
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/files.py
25,26
1,35
is_path_traversal
26,35
26,35
import os from sys import platform import pathlib2 import psutil def get_filename_max_length(dir_path): # type: (str) -> int try: dir_path = pathlib2.Path(os.path.abspath(dir_path)) if platform == "win32": dir_drive = dir_path.drive for drv in psutil.disk_partitions():...
import os from sys import platform import pathlib2 import psutil def get_filename_max_length(dir_path): # type: (str) -> int try: dir_path = pathlib2.Path(os.path.abspath(dir_path)) if platform == "win32": dir_drive = dir_path.drive for drv in psutil.disk_partitions():...
try: target_folder = pathlib2.Path(target_folder) relative_path = pathlib2.Path(relative_path) # returns the relative path starting from the target_folder, # or raise an ValueError if a directory traversal attack is tried target_folder.joinpath(relative_path).resolve().relati...
try: target_folder = pathlib2.Path(target_folder) relative_path = pathlib2.Path(relative_path) # returns the relative path starting from the target_folder, # or raise an ValueError if a directory traversal attack is tried target_folder.joinpath(relative_path).resolve().relati...
35
236
115
351
import os from sys import platform import pathlib2 import psutil def get_filename_max_length(dir_path): # type: (str) -> int try: dir_path = pathlib2.Path(os.path.abspath(dir_path)) if platform == "win32": dir_drive = dir_path.drive for drv in psutil.disk_partitions():...
import os from sys import platform import pathlib2 import psutil def get_filename_max_length(dir_path): # type: (str) -> int try: dir_path = pathlib2.Path(os.path.abspath(dir_path)) if platform == "win32": dir_drive = dir_path.drive for drv in psutil.disk_partitions():...
32,878
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/gpu/gpustat.py
120,122
29,173
fan_speed
GPUStat
126,129
122,129
class GPUStat(object): def __init__(self, entry): if not isinstance(entry, dict): raise TypeError( 'entry should be a dict, {} given'.format(type(entry)) ) self.entry = entry def keys(self): return self.entry.keys() def __getitem__(self, key...
class GPUStat(object): def __init__(self, entry): if not isinstance(entry, dict): raise TypeError( 'entry should be a dict, {} given'.format(type(entry)) ) self.entry = entry def keys(self): return self.entry.keys() def __getitem__(self, key...
v = self.entry['fan.speed'] return int(v) if v is not None else None
""" Returns the fan speed percentage (0-100) of maximum intended speed as an integer, or None if the information is not available. """ v = self.entry['fan.speed'] return int(v) if v is not None else None
12
1,111
30
1,141
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implementation of gpustat @author Jongwook Choi @url https://github.com/wookayin/gpustat @ copied from gpu-stat 0.6.0 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_liter...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implementation of gpustat @author Jongwook Choi @url https://github.com/wookayin/gpustat @ copied from gpu-stat 0.6.0 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_liter...
32,880
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/io_manager.py
17,18
1,32
remove_io_to_thread
IOCallsManager
18,25
18,25
class IOCallsManager(object): def __init__(self): self.threads_io = {} def add_io_to_thread(self, thread_id, io_object): if thread_id in self.threads_io: self.threads_io[thread_id].add(id(io_object)) else: self.threads_io[thread_id] = {id(io_object)} if ...
class IOCallsManager(object): def __init__(self): self.threads_io = {} def add_io_to_thread(self, thread_id, io_object): if thread_id in self.threads_io: self.threads_io[thread_id].add(id(io_object)) else: self.threads_io[thread_id] = {id(io_object)} if ...
try: self.threads_io[thread_id].remove(id(io_object)) if self._io_has_canvas_figure(io_object): self.threads_io[thread_id].remove(id(io_object.canvas.figure)) except Exception: pass
try: self.threads_io[thread_id].remove(id(io_object)) if self._io_has_canvas_figure(io_object): self.threads_io[thread_id].remove(id(io_object.canvas.figure)) except Exception: pass
8
318
83
401
class IOCallsManager(object): def __init__(self): self.threads_io = {} def add_io_to_thread(self, thread_id, io_object): if thread_id in self.threads_io: self.threads_io[thread_id].add(id(io_object)) else: self.threads_io[thread_id] = {id(io_object)} if ...
class IOCallsManager(object): def __init__(self): self.threads_io = {} def add_io_to_thread(self, thread_id, io_object): if thread_id in self.threads_io: self.threads_io[thread_id].add(id(io_object)) else: self.threads_io[thread_id] = {id(io_object)} if ...
32,882
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/locks/utils.py
182,183
68,238
delete_lock_file
Lock
183,198
183,198
class Lock(object): def __init__( self, filename, mode='a', timeout=DEFAULT_TIMEOUT, check_interval=DEFAULT_CHECK_INTERVAL, fail_when_locked=False, flags=LOCK_METHOD, **file_open_kwargs): '''Lock manager with build-in timeout filename -- filename mode --...
class Lock(object): def __init__( self, filename, mode='a', timeout=DEFAULT_TIMEOUT, check_interval=DEFAULT_CHECK_INTERVAL, fail_when_locked=False, flags=LOCK_METHOD, **file_open_kwargs): '''Lock manager with build-in timeout filename -- filename mode --...
# type: () -> bool """ Remove the local file used for locking (fail if file is locked) :return: True is successful """ if self.fh: return False # noinspection PyBroadException try: os.unlink(path=self.filename) except BaseE...
# type: () -> bool """ Remove the local file used for locking (fail if file is locked) :return: True is successful """ if self.fh: return False # noinspection PyBroadException try: os.unlink(path=self.filename) except BaseE...
38
1,300
110
1,410
import os import time import atexit import tempfile import contextlib from multiprocessing import RLock as ProcessRLock from . import exceptions from . import constants from . import portalocker current_time = getattr(time, "monotonic", time.time) DEFAULT_TIMEOUT = 10 ** 8 DEFAULT_CHECK_INTERVAL = 0.25 LOCK_METHOD = ...
import os import time import atexit import tempfile import contextlib from multiprocessing import RLock as ProcessRLock from . import exceptions from . import constants from . import portalocker current_time = getattr(time, "monotonic", time.time) DEFAULT_TIMEOUT = 10 ** 8 DEFAULT_CHECK_INTERVAL = 0.25 LOCK_METHOD = ...
32,883
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/locks/utils.py
255,256
238,329
acquire
RLock
256,295
256,295
class RLock(Lock): """ A reentrant lock, functions in a similar way to threading.RLock in that it can be acquired multiple times. When the corresponding number of release() calls are made the lock will finally release the underlying file lock. """ def __init__( self, filename, mode...
class RLock(Lock): """ A reentrant lock, functions in a similar way to threading.RLock in that it can be acquired multiple times. When the corresponding number of release() calls are made the lock will finally release the underlying file lock. """ def __init__( self, filename, mode...
if self._lock: # cleanup bad python behaviour when forking while lock is acquired # see Issue https://github.com/allegroai/clearml-agent/issues/73 # and https://bugs.python.org/issue6721 if self._pid != os.getpid(): # noinspection PyBroadException ...
if self._lock: # cleanup bad python behaviour when forking while lock is acquired # see Issue https://github.com/allegroai/clearml-agent/issues/73 # and https://bugs.python.org/issue6721 if self._pid != os.getpid(): # noinspection PyBroadException ...
118
446
420
866
import os import time import atexit import tempfile import contextlib from multiprocessing import RLock as ProcessRLock from . import exceptions from . import constants from . import portalocker current_time = getattr(time, "monotonic", time.time) DEFAULT_TIMEOUT = 10 ** 8 DEFAULT_CHECK_INTERVAL = 0.25 LOCK_METHOD = ...
import os import time import atexit import tempfile import contextlib from multiprocessing import RLock as ProcessRLock from . import exceptions from . import constants from . import portalocker current_time = getattr(time, "monotonic", time.time) DEFAULT_TIMEOUT = 10 ** 8 DEFAULT_CHECK_INTERVAL = 0.25 LOCK_METHOD = ...
32,884
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/locks/utils.py
340,341
329,344
release
TemporaryFileLock
341,344
341,344
class TemporaryFileLock(Lock): def __init__(self, filename='.lock', timeout=DEFAULT_TIMEOUT, check_interval=DEFAULT_CHECK_INTERVAL, fail_when_locked=True, flags=LOCK_METHOD): Lock.__init__(self, filename=filename, mode='w', timeout=timeout, check_int...
class TemporaryFileLock(Lock): def __init__(self, filename='.lock', timeout=DEFAULT_TIMEOUT, check_interval=DEFAULT_CHECK_INTERVAL, fail_when_locked=True, flags=LOCK_METHOD): Lock.__init__(self, filename=filename, mode='w', timeout=timeout, check_int...
Lock.release(self) if os.path.isfile(self.filename): # pragma: no branch os.unlink(self.filename)
Lock.release(self) if os.path.isfile(self.filename): # pragma: no branch os.unlink(self.filename)
8
141
43
184
import os import time import atexit import tempfile import contextlib from multiprocessing import RLock as ProcessRLock from . import exceptions from . import constants from . import portalocker current_time = getattr(time, "monotonic", time.time) DEFAULT_TIMEOUT = 10 ** 8 DEFAULT_CHECK_INTERVAL = 0.25 LOCK_METHOD = ...
import os import time import atexit import tempfile import contextlib from multiprocessing import RLock as ProcessRLock from . import exceptions from . import constants from . import portalocker current_time = getattr(time, "monotonic", time.time) DEFAULT_TIMEOUT = 10 ** 8 DEFAULT_CHECK_INTERVAL = 0.25 LOCK_METHOD = ...
32,885
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/lowlevel/distributed.py
52,53
1,97
get_torch_distributed_anchor_task_id
61,97
53,97
import os from logging import getLogger from time import sleep, time from pathlib2 import Path def get_torch_local_rank(): """ return the local rank of the process, notice local rank 0 does not mean global rank 0 return None if no torch distributed is running """ if os.environ.get("TORCHELASTIC_R...
import os from logging import getLogger from time import sleep, time from pathlib2 import Path def get_torch_local_rank(): """ return the local rank of the process, notice local rank 0 does not mean global rank 0 return None if no torch distributed is running """ if os.environ.get("TORCHELASTIC_R...
# check that we are not local rank 0 _local_rank = get_torch_local_rank() if not _local_rank: return local_file_name = ".clearml_torch_distributed_id" torch_dist_path = os.environ.get("TORCHELASTIC_ERROR_FILE") if not torch_dist_path: return task_id = None # noinspect...
""" This will wait until a temporary file appears and read the Task ID created by local_rank 0 of Only call when running locally (i.e. without an agent), if running remotely there is no need to pass Task ID, it will be passed externally :return Task ID of the local task to report to """ #...
118
569
381
950
import os from logging import getLogger from time import sleep, time from pathlib2 import Path def get_torch_local_rank(): """ return the local rank of the process, notice local rank 0 does not mean global rank 0 return None if no torch distributed is running """ if os.environ.get("TORCHELASTIC_R...
import os from logging import getLogger from time import sleep, time from pathlib2 import Path def get_torch_local_rank(): """ return the local rank of the process, notice local rank 0 does not mean global rank 0 return None if no torch distributed is running """ if os.environ.get("TORCHELASTIC_R...
32,886
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/matching.py
6,7
1,45
matches_any_wildcard
7,45
7,45
from pathlib2 import Path from fnmatch import fnmatch from typing import Union def matches_any_wildcard(path, wildcards, recursive=True): FILL_FUNC_BODY
from pathlib2 import Path from fnmatch import fnmatch from typing import Union def matches_any_wildcard(path, wildcards, recursive=True): FILL_FUNC_BODY
# type: (str, Union[str, list], bool) -> bool """ Checks if given pattern matches any supplied wildcard :param path: path to check :param wildcards: wildcards to check against :param recursive: whether or not the check is recursive. Default: True E.g. for path='directory/file.ext' and w...
# type: (str, Union[str, list], bool) -> bool """ Checks if given pattern matches any supplied wildcard :param path: path to check :param wildcards: wildcards to check against :param recursive: whether or not the check is recursive. Default: True E.g. for path='directory/file.ext' and w...
153
51
450
501
from pathlib2 import Path from fnmatch import fnmatch from typing import Union def matches_any_wildcard(path, wildcards, recursive=True): FILL_FUNC_BODY
from pathlib2 import Path from fnmatch import fnmatch from typing import Union def matches_any_wildcard(path, wildcards, recursive=True): FILL_FUNC_BODY
32,887
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/networking.py
29,30
1,89
get_public_ip
30,44
30,44
import requests import socket import subprocess from typing import Optional def get_private_ip(): # type: () -> str """ Get the private IP of this machine :return: A string representing the IP of this machine """ approaches = ( _get_private_ip_from_socket, _get_private_ip_from...
import requests import socket import subprocess from typing import Optional def get_private_ip(): # type: () -> str """ Get the private IP of this machine :return: A string representing the IP of this machine """ approaches = ( _get_private_ip_from_socket, _get_private_ip_from...
# type: () -> Optional[str] """ Get the public IP of this machine. External services such as `https://api.ipify.org` or `https://ident.me` are used to get the IP :return: A string representing the IP of this machine or `None` if getting the IP failed """ for external_service in ["https://ap...
# type: () -> Optional[str] """ Get the public IP of this machine. External services such as `https://api.ipify.org` or `https://ident.me` are used to get the IP :return: A string representing the IP of this machine or `None` if getting the IP failed """ for external_service in ["https://ap...
57
592
156
748
import requests import socket import subprocess from typing import Optional def get_private_ip(): # type: () -> str """ Get the private IP of this machine :return: A string representing the IP of this machine """ approaches = ( _get_private_ip_from_socket, _get_private_ip_from...
import requests import socket import subprocess from typing import Optional def get_private_ip(): # type: () -> str """ Get the private IP of this machine :return: A string representing the IP of this machine """ approaches = ( _get_private_ip_from_socket, _get_private_ip_from...
32,888
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/parallel.py
177,178
87,188
get_logger
FutureTaskCaller
178,188
178,188
class FutureTaskCaller(object): """ FutureTaskCaller is used to create a class via a functions async, in another thread. For example: .. code-block:: py future = FutureTaskCaller().call(func=max, func_cb=None, override_cls=None, 1, 2) print('Running other code') print(future.r...
class FutureTaskCaller(object): """ FutureTaskCaller is used to create a class via a functions async, in another thread. For example: .. code-block:: py future = FutureTaskCaller().call(func=max, func_cb=None, override_cls=None, 1, 2) print('Running other code') print(future.r...
if self.__object is not None: return self.__object.get_logger() if self.__deferred_bkg_class is None: # we are shutting down, wait until object is available return self.__result__().get_logger() return self.__deferred_bkg_class
if self.__object is not None: return self.__object.get_logger() if self.__deferred_bkg_class is None: # we are shutting down, wait until object is available return self.__result__().get_logger() return self.__deferred_bkg_class
25
954
88
1,042
import os from copy import deepcopy from time import sleep from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, Union, Generator, List, Type from zipfile import ZipFile, ZIP_DEFLATED from six.moves.queue import PriorityQueue, Queue, Empty from pathlib2 import Path from tempfile...
import os from copy import deepcopy from time import sleep from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, Union, Generator, List, Type from zipfile import ZipFile, ZIP_DEFLATED from six.moves.queue import PriorityQueue, Queue, Empty from pathlib2 import Path from tempfile...
32,890
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/parallel.py
245,246
192,335
zip
ZipperObject
246,282
246,282
class ZipperObject(object): def __init__( self, chunk_size, # int zipper_queue, # PriorityQueue[ParallelZipper.ZipperObject] zipper_results, # Queue[ParallelZipper.ZipperObject] allow_zip_64, # bool compression, # Any z...
class ZipperObject(object): def __init__( self, chunk_size, # int zipper_queue, # PriorityQueue[ParallelZipper.ZipperObject] zipper_results, # Queue[ParallelZipper.ZipperObject] allow_zip_64, # bool compression, # Any z...
# type: (Union[str, Path], str) -> () """ Zips a file into the ZipFile created by this instance. This instance will either add itself back to the PriorityQueue used to select the best zipping candidate or add itself to the result Queue after exceeding self.chu...
# type: (Union[str, Path], str) -> () """ Zips a file into the ZipFile created by this instance. This instance will either add itself back to the PriorityQueue used to select the best zipping candidate or add itself to the result Queue after exceeding self.chu...
113
1,332
456
1,788
import os from copy import deepcopy from time import sleep from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, Union, Generator, List, Type from zipfile import ZipFile, ZIP_DEFLATED from six.moves.queue import PriorityQueue, Queue, Empty from pathlib2 import Path from tempfile...
import os from copy import deepcopy from time import sleep from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, Union, Generator, List, Type from zipfile import ZipFile, ZIP_DEFLATED from six.moves.queue import PriorityQueue, Queue, Empty from pathlib2 import Path from tempfile...
32,891
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/parallel.py
67,68
18,87
_caller
_DeferredClass
68,84
68,84
class _DeferredClass(object): __slots__ = ('__queue', '__future_caller', '__future_func') def __init__(self, a_future_caller, future_func): self.__queue = Queue() self.__future_caller = a_future_caller self.__future_func = future_func def __nested_caller(self, item, args, kwargs): ...
class _DeferredClass(object): __slots__ = ('__queue', '__future_caller', '__future_func') def __init__(self, a_future_caller, future_func): self.__queue = Queue() self.__future_caller = a_future_caller self.__future_func = future_func def __nested_caller(self, item, args, kwargs): ...
# if we already completed the background initialization, call functions immediately # noinspection PyProtectedMember if not self.__queue or self.__future_caller._FutureTaskCaller__executor is None: return self.__nested_caller(item, args, kwargs) # noinspe...
# if we already completed the background initialization, call functions immediately # noinspection PyProtectedMember if not self.__queue or self.__future_caller._FutureTaskCaller__executor is None: return self.__nested_caller(item, args, kwargs) # noinspe...
82
586
210
796
import os from copy import deepcopy from time import sleep from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, Union, Generator, List, Type from zipfile import ZipFile, ZIP_DEFLATED from six.moves.queue import PriorityQueue, Queue, Empty from pathlib2 import Path from tempfile...
import os from copy import deepcopy from time import sleep from concurrent.futures import ThreadPoolExecutor from typing import Any, Callable, Optional, Union, Generator, List, Type from zipfile import ZipFile, ZIP_DEFLATED from six.moves.queue import PriorityQueue, Queue, Empty from pathlib2 import Path from tempfile...
32,893
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/pigar/modules.py
29,30
24,61
add
ImportedModules
30,53
30,53
class ImportedModules(Modules): def __init__(self): super(ImportedModules, self).__init__() def add(self, name, file, lineno): FILL_FUNC_BODY def __or__(self, obj): for name, locations in obj.items(): for file, linenos in locations.items(): for lineno in linenos:...
class ImportedModules(Modules): def __init__(self): super(ImportedModules, self).__init__() def add(self, name, file, lineno): FILL_FUNC_BODY def __or__(self, obj): for name, locations in obj.items(): for file, linenos in locations.items(): for lineno in linenos:...
if name is None: return names = list() special_name = '.'.join(name.split('.')[:2]) # Flask extension. if name.startswith('flask.ext.'): names.append('flask') names.append('flask_' + name.split('.')[2]) # Special cases.. elif s...
if name is None: return names = list() special_name = '.'.join(name.split('.')[:2]) # Flask extension. if name.startswith('flask.ext.'): names.append('flask') names.append('flask_' + name.split('.')[2]) # Special cases.. elif s...
54
120
230
350
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import collections # FIXME: Just a workaround, not a radical cure.. _special_cases = { "dogpile.cache": "dogpile.cache", "dogpile.core": "dogpile.core", "ruamel.yaml": "ruamel.yaml", "ruamel.ordereddict": "ruame...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import collections # FIXME: Just a workaround, not a radical cure.. _special_cases = { "dogpile.cache": "dogpile.cache", "dogpile.core": "dogpile.core", "ruamel.yaml": "ruamel.yaml", "ruamel.ordereddict": "ruame...
32,894
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/pigar/modules.py
69,70
61,87
add
ReqsModules
70,75
70,75
class ReqsModules(Modules): _Detail = collections.namedtuple('Detail', ['version', 'comments']) def __init__(self): super(ReqsModules, self).__init__() self._sorted = None def add(self, package, version, locations): FILL_FUNC_BODY def sorted_items(self): if self._sorted is None...
class ReqsModules(Modules): _Detail = collections.namedtuple('Detail', ['version', 'comments']) def __init__(self): super(ReqsModules, self).__init__() self._sorted = None def add(self, package, version, locations): FILL_FUNC_BODY def sorted_items(self): if self._sorted is None...
if package in self: self[package].comments.extend(locations) else: self[package] = self._Detail(version, locations)
if package in self: self[package].comments.extend(locations) else: self[package] = self._Detail(version, locations)
10
170
45
215
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import collections # FIXME: Just a workaround, not a radical cure.. _special_cases = { "dogpile.cache": "dogpile.cache", "dogpile.core": "dogpile.core", "ruamel.yaml": "ruamel.yaml", "ruamel.ordereddict": "ruame...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import collections # FIXME: Just a workaround, not a radical cure.. _special_cases = { "dogpile.cache": "dogpile.cache", "dogpile.core": "dogpile.core", "ruamel.yaml": "ruamel.yaml", "ruamel.ordereddict": "ruame...
32,895
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/pigar/modules.py
94,95
87,112
add
_Locations
95,100
95,100
class _Locations(dict): """_Locations store code locations(file, linenos).""" def __init__(self): super(_Locations, self).__init__() self._sorted = None def add(self, file, lineno): FILL_FUNC_BODY def extend(self, obj): for file, linenos in obj.items(): for lineno in...
class _Locations(dict): """_Locations store code locations(file, linenos).""" def __init__(self): super(_Locations, self).__init__() self._sorted = None def add(self, file, lineno): FILL_FUNC_BODY def extend(self, obj): for file, linenos in obj.items(): for lineno in...
if file in self and lineno not in self[file]: self[file].append(lineno) else: self[file] = [lineno]
if file in self and lineno not in self[file]: self[file].append(lineno) else: self[file] = [lineno]
14
200
47
247
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import collections # FIXME: Just a workaround, not a radical cure.. _special_cases = { "dogpile.cache": "dogpile.cache", "dogpile.core": "dogpile.core", "ruamel.yaml": "ruamel.yaml", "ruamel.ordereddict": "ruame...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import collections # FIXME: Just a workaround, not a radical cure.. _special_cases = { "dogpile.cache": "dogpile.cache", "dogpile.core": "dogpile.core", "ruamel.yaml": "ruamel.yaml", "ruamel.ordereddict": "ruame...
32,896
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/pigar/utils.py
97,98
1,145
_group_alnum
98,117
98,117
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import os import re import sys import difflib PY32 = sys.version_info[:2] == (3, 2) if sys.version_info[0] == 3: binary_type = bytes else: binary_type = str class Dict(dict): """Convert dict key object to attribu...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import os import re import sys import difflib PY32 = sys.version_info[:2] == (3, 2) if sys.version_info[0] == 3: binary_type = bytes else: binary_type = str class Dict(dict): """Convert dict key object to attribu...
tmp = list() flag = 1 if s[0].isdigit() else 0 for c in s: if c.isdigit(): if flag == 0: yield ''.join(tmp) tmp = list() flag = 1 tmp.append(c) elif c.isalpha(): if flag == 1: yield int(''.joi...
tmp = list() flag = 1 if s[0].isdigit() else 0 for c in s: if c.isdigit(): if flag == 0: yield ''.join(tmp) tmp = list() flag = 1 tmp.append(c) elif c.isalpha(): if flag == 1: yield int(''.joi...
53
1,036
162
1,198
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import os import re import sys import difflib PY32 = sys.version_info[:2] == (3, 2) if sys.version_info[0] == 3: binary_type = bytes else: binary_type = str class Dict(dict): """Convert dict key object to attribu...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import os import re import sys import difflib PY32 = sys.version_info[:2] == (3, 2) if sys.version_info[0] == 3: binary_type = bytes else: binary_type = str class Dict(dict): """Convert dict key object to attribu...
32,898
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/plotly_reporter.py
70,72
64,86
_validate_data
SeriesInfo
72,78
72,78
@attrs class SeriesInfo(object): name = attrib(type=str) data = attrib(type=np.ndarray, converter=_to_np_array) labels = attrib(default=None) @data.validator def _validate_data(self, _, value): FILL_FUNC_BODY def __attrs_post_init__(self): if (self.labels is not None) and (len(self.label...
@attrs class SeriesInfo(object): name = attrib(type=str) data = attrib(type=np.ndarray, converter=_to_np_array) labels = attrib(default=None) @data.validator def _validate_data(self, _, value): FILL_FUNC_BODY def __attrs_post_init__(self): if (self.labels is not None) and (len(self.label...
if value.ndim != 2: raise ValueError("Expected series data to be 2D numpy array") if value.shape[1] != 2: raise ValueError("Expected series data to have 2 columns")
if value.ndim != 2: raise ValueError("Expected series data to be 2D numpy array") if value.shape[1] != 2: raise ValueError("Expected series data to have 2 columns")
25
170
65
235
import json import numpy as np from ..errors import UsageError from ..utilities.dicts import merge_dicts try: import pandas as pd except ImportError: pd = None from attr import attrs, attrib def create_2d_histogram_plot(np_row_wise, labels, title=None, xtitle=None, ytitle=None, series=None, xlabels=None, ...
import json import numpy as np from ..errors import UsageError from ..utilities.dicts import merge_dicts try: import pandas as pd except ImportError: pd = None from attr import attrs, attrib def create_2d_histogram_plot(np_row_wise, labels, title=None, xtitle=None, ytitle=None, series=None, xlabels=None, ...
32,899
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/plotlympl/mplexporter/renderers/fake_renderer.py
23,24
4,50
close_figure
FakeRenderer
24,26
24,26
class FakeRenderer(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are free to do anything you wish...
class FakeRenderer(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are free to do anything you wish...
self.output += "closing figure\n"
self.output += "closing figure\n"
4
476
16
492
from .base import Renderer class FakeRenderer(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are fre...
from .base import Renderer class FakeRenderer(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are fre...
32,900
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/plotlympl/mplexporter/renderers/fake_renderer.py
58,59
50,69
draw_line
FullFakeRenderer
59,61
59,61
class FullFakeRenderer(FakeRenderer): """ Renderer with the full complement of methods. When the following are left undefined, they will be implemented via other methods in the class. They can be defined explicitly for more efficient or specialized use within the renderer implementation. """ ...
class FullFakeRenderer(FakeRenderer): """ Renderer with the full complement of methods. When the following are left undefined, they will be implemented via other methods in the class. They can be defined explicitly for more efficient or specialized use within the renderer implementation. """ ...
self.output += " draw line with {0} points\n".format(data.shape[0])
self.output += " draw line with {0} points\n".format(data.shape[0])
8
235
29
264
from .base import Renderer class FakeRenderer(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are fre...
from .base import Renderer class FakeRenderer(Renderer): """ Fake Renderer This is a fake renderer which simply outputs a text tree representing the elements found in the plot(s). This is used in the unit tests for the package. Below are the methods your renderer must implement. You are fre...
32,901
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/plotlympl/mplexporter/renderers/vega_renderer.py
110,111
1,139
fig_to_vega
116,125
111,125
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
renderer = VegaRenderer() Exporter(renderer).run(fig) vega_html = VegaHTML(renderer) if notebook: return vega_html else: return vega_html.html()
"""Convert a matplotlib figure to vega dictionary if notebook=True, then return an object which will display in a notebook otherwise, return an HTML string. """ renderer = VegaRenderer() Exporter(renderer).run(fig) vega_html = VegaHTML(renderer) if notebook: return vega_html ...
14
1,368
73
1,441
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
32,902
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/plotlympl/mplexporter/renderers/vega_renderer.py
97,98
88,110
html
VegaHTML
99,106
98,106
class VegaHTML(object): def __init__(self, renderer): self.specification = dict(width=renderer.figwidth, height=renderer.figheight, data=renderer.data, scales=renderer.scales, ...
class VegaHTML(object): def __init__(self, renderer): self.specification = dict(width=renderer.figwidth, height=renderer.figheight, data=renderer.data, scales=renderer.scales, ...
id = random.randint(0, 2 ** 16) html = '<div id="vis%d"></div>' % id html += '<script>\n' html += VEGA_TEMPLATE % (json.dumps(self.specification), id) html += '</script>\n' return html
"""Build the HTML representation for IPython.""" id = random.randint(0, 2 ** 16) html = '<div id="vis%d"></div>' % id html += '<script>\n' html += VEGA_TEMPLATE % (json.dumps(self.specification), id) html += '</script>\n' return html
26
134
100
234
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
32,903
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/plotlympl/mplexporter/renderers/vega_renderer.py
56,57
8,88
draw_markers
VegaRenderer
57,80
57,80
class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dpi']) self.data = [] self.scales = [] self.axes = [] self.marks = [] ...
class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dpi']) self.data = [] self.scales = [] self.axes = [] self.marks = [] ...
if coordinates != 'data': warnings.warn("Only data coordinates supported. Skipping this") dataname = "table{0:03d}".format(len(self.data) + 1) # TODO: respect the other style settings self.data.append({'name': dataname, 'values': [dict(x=d[0], y=d[1...
if coordinates != 'data': warnings.warn("Only data coordinates supported. Skipping this") dataname = "table{0:03d}".format(len(self.data) + 1) # TODO: respect the other style settings self.data.append({'name': dataname, 'values': [dict(x=d[0], y=d[1...
71
653
303
956
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
import warnings import json import random from .base import Renderer from ..exporter import Exporter class VegaRenderer(Renderer): def open_figure(self, fig, props): self.props = props self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dp...
32,904
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/plotlympl/mplexporter/tools.py
6,7
1,53
ipynb_vega_init
12,53
7,53
""" Tools for matplotlib plot exporting """ def ipynb_vega_init(): FILL_FUNC_BODY
""" Tools for matplotlib plot exporting """ def ipynb_vega_init(): """Initialize the IPython notebook display elements This function borrows heavily from the excellent vincent package: http://github.com/wrobstory/vincent """ FILL_FUNC_BODY
try: from IPython.core.display import display, HTML except ImportError: print('IPython Notebook could not be loaded.') require_js = ''' if (window['d3'] === undefined) {{ require.config({{ paths: {{d3: "http://d3js.org/d3.v3.min"}} }}); require(["d3"], function(d3) {{ ...
"""Initialize the IPython notebook display elements This function borrows heavily from the excellent vincent package: http://github.com/wrobstory/vincent """ try: from IPython.core.display import display, HTML except ImportError: print('IPython Notebook could not be loaded.') ...
101
81
570
651
""" Tools for matplotlib plot exporting """ def ipynb_vega_init(): FILL_FUNC_BODY
""" Tools for matplotlib plot exporting """ def ipynb_vega_init(): """Initialize the IPython notebook display elements This function borrows heavily from the excellent vincent package: http://github.com/wrobstory/vincent """ FILL_FUNC_BODY
32,907
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/process/exit_hooks.py
109,110
11,188
exc_handler
ExitHooks
110,146
110,146
class ExitHooks(object): _orig_exit = None _orig_exc_handler = None remote_user_aborted = False def __init__(self, callback): self.exit_code = None self.exception = None self.signal = None self._exit_callback = callback self._org_handlers = {} self._signa...
class ExitHooks(object): _orig_exit = None _orig_exc_handler = None remote_user_aborted = False def __init__(self, callback): self.exit_code = None self.exception = None self.signal = None self._exit_callback = callback self._org_handlers = {} self._signa...
if self._except_recursion_protection_flag or not self._orig_exc_handler: # noinspection PyArgumentList return sys.__excepthook__(exctype, value, traceback, *args, **kwargs) self._except_recursion_protection_flag = True self.exception = value try: # r...
if self._except_recursion_protection_flag or not self._orig_exc_handler: # noinspection PyArgumentList return sys.__excepthook__(exctype, value, traceback, *args, **kwargs) self._except_recursion_protection_flag = True self.exception = value try: # r...
124
1,300
421
1,721
import atexit import os import signal import sys import six from ...logger import Logger class ExitHooks(object): _orig_exit = None _orig_exc_handler = None remote_user_aborted = False def __init__(self, callback): self.exit_code = None self.exception = None self.signal = No...
import atexit import os import signal import sys import six from ...logger import Logger class ExitHooks(object): _orig_exit = None _orig_exc_handler = None remote_user_aborted = False def __init__(self, callback): self.exit_code = None self.exception = None self.signal = No...
32,909
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/proxy_object.py
404,406
352,412
trigger_all_remote_references
LazyEvalWrapper
406,412
406,412
class LazyEvalWrapper(six.with_metaclass(WrapperBase)): # This class acts as a proxy for the wrapped instance it is passed. All # access to its attributes are delegated to the wrapped class, except # those contained in __overrides__. __slots__ = ['_wrapped', '_callback', '_remote_reference', '__weakre...
class LazyEvalWrapper(six.with_metaclass(WrapperBase)): # This class acts as a proxy for the wrapped instance it is passed. All # access to its attributes are delegated to the wrapped class, except # those contained in __overrides__. __slots__ = ['_wrapped', '_callback', '_remote_reference', '__weakre...
for func in cls._remote_reference_calls: if callable(func): func() cls._remote_reference_calls = []
for func in cls._remote_reference_calls: if callable(func): func() cls._remote_reference_calls = []
10
582
48
630
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
32,910
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/proxy_object.py
45,46
10,57
update
ProxyDictPostWrite
46,50
46,50
class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(ProxyDictPostWrite, self).__init__(*args, **kwargs) self._update_obj = update_obj self._upd...
class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(ProxyDictPostWrite, self).__init__(*args, **kwargs) self._update_obj = update_obj self._upd...
res = self._do_update(E, **F) self._set_callback() return res
res = self._do_update(E, **F) self._set_callback() return res
7
487
32
519
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
32,911
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/proxy_object.py
77,78
57,93
_set_callback
ProxyDictPreWrite
78,89
78,89
class ProxyDictPreWrite(dict): """ Dictionary wrapper that prevents modifications to the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(ProxyDictPreWrite, self).__init__(*args, **kwargs) self._update_func = None for k, i in self.items(): i...
class ProxyDictPreWrite(dict): """ Dictionary wrapper that prevents modifications to the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(ProxyDictPreWrite, self).__init__(*args, **kwargs) self._update_func = None for k, i in self.items(): i...
if self._update_func is not None: if callable(self._update_func): res = self._update_func(self._update_obj, key_value) else: res = self._update_func if not res: return None return res return key_value
if self._update_func is not None: if callable(self._update_func): res = self._update_func(self._update_obj, key_value) else: res = self._update_func if not res: return None return res return key_value
24
305
90
395
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
32,912
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/proxy_object.py
321,322
293,352
method
WrapperBase
322,339
322,339
class WrapperBase(type): # This metaclass is heavily inspired by the Object Proxying python recipe # (http://code.activestate.com/recipes/496741/). It adds special methods # to the wrapper class so it can proxy the wrapped class. In addition, it # adds a field __overrides__ in the wrapper class diction...
class WrapperBase(type): # This metaclass is heavily inspired by the Object Proxying python recipe # (http://code.activestate.com/recipes/496741/). It adds special methods # to the wrapper class so it can proxy the wrapped class. In addition, it # adds a field __overrides__ in the wrapper class diction...
obj = object.__getattribute__(self, "_wrapped") if obj is None: cb = object.__getattribute__(self, "_callback") obj = cb() object.__setattr__(self, '_wrapped', obj) # we have to convert the instance to the real ...
obj = object.__getattribute__(self, "_wrapped") if obj is None: cb = object.__getattribute__(self, "_callback") obj = cb() object.__setattr__(self, '_wrapped', obj) # we have to convert the instance to the real ...
66
811
206
1,017
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
import itertools import json from copy import copy from logging import getLogger import six import yaml class ProxyDictPostWrite(dict): """ Dictionary wrapper that updates an arguments instance on any item set in the dictionary """ def __init__(self, update_obj, update_func, *args, **kwargs): super(...
32,913
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/decoder.py
30,31
1,157
_header_parser
31,41
31,41
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
major = sys.version_info[0] if major == 3: string = string.decode(encoding) headers = email.parser.HeaderParser().parsestr(string).items() return ( (encode_with(k, encoding), encode_with(v, encoding)) for k, v in headers )
major = sys.version_info[0] if major == 3: string = string.decode(encoding) headers = email.parser.HeaderParser().parsestr(string).items() return ( (encode_with(k, encoding), encode_with(v, encoding)) for k, v in headers )
25
1,332
95
1,427
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
32,914
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/decoder.py
68,70
41,74
text
BodyPart
71,74
70,74
class BodyPart(object): """ The ``BodyPart`` object is a ``Response``-like interface to an individual subpart of a multipart response. It is expected that these will generally be created by objects of the ``MultipartDecoder`` class. Like ``Response``, there is a ``CaseInsensitiveDict`` object name...
class BodyPart(object): """ The ``BodyPart`` object is a ``Response``-like interface to an individual subpart of a multipart response. It is expected that these will generally be created by objects of the ``MultipartDecoder`` class. Like ``Response``, there is a ``CaseInsensitiveDict`` object name...
return self.content.decode(self.encoding)
"""Content of the ``BodyPart`` in unicode.""" return self.content.decode(self.encoding)
2
313
18
331
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
32,915
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/decoder.py
113,114
74,157
_find_boundary
MultipartDecoder
114,128
114,128
class MultipartDecoder(object): """ The ``MultipartDecoder`` object parses the multipart payload of a bytestring into a tuple of ``Response``-like ``BodyPart`` objects. The basic usage is:: import requests from requests_toolbelt import MultipartDecoder response = requests.get...
class MultipartDecoder(object): """ The ``MultipartDecoder`` object parses the multipart payload of a bytestring into a tuple of ``Response``-like ``BodyPart`` objects. The basic usage is:: import requests from requests_toolbelt import MultipartDecoder response = requests.get...
ct_info = tuple(x.strip() for x in self.content_type.split(';')) mimetype = ct_info[0] if mimetype.split('/')[0].lower() != 'multipart': raise NonMultipartContentTypeException( "Unexpected mimetype in content-type: '{}'".format(mimetype) ) for item...
ct_info = tuple(x.strip() for x in self.content_type.split(';')) mimetype = ct_info[0] if mimetype.split('/')[0].lower() != 'multipart': raise NonMultipartContentTypeException( "Unexpected mimetype in content-type: '{}'".format(mimetype) ) for item...
41
679
183
862
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.decoder =================================== This holds all the implementation details of the MultipartDecoder """ import sys import email.parser from .encoder import encode_with from requests.structures import CaseInsensitiveDict def _split_on_find(content, ...
32,917
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/encoder.py
555,556
533,567
smart_truncate
CustomBytesIO
556,567
556,567
class CustomBytesIO(io.BytesIO): def __init__(self, buffer=None, encoding='utf-8'): buffer = encode_with(buffer, encoding) super(CustomBytesIO, self).__init__(buffer) def _get_end(self): current_pos = self.tell() self.seek(0, 2) length = self.tell() self.seek(cur...
class CustomBytesIO(io.BytesIO): def __init__(self, buffer=None, encoding='utf-8'): buffer = encode_with(buffer, encoding) super(CustomBytesIO, self).__init__(buffer) def _get_end(self): current_pos = self.tell() self.seek(0, 2) length = self.tell() self.seek(cur...
to_be_read = total_len(self) already_read = self._get_end() - to_be_read if already_read >= to_be_read: old_bytes = self.read() self.seek(0, 0) self.truncate() self.write(old_bytes) self.seek(0, 0) # We want to be at the beginning
to_be_read = total_len(self) already_read = self._get_end() - to_be_read if already_read >= to_be_read: old_bytes = self.read() self.seek(0, 0) self.truncate() self.write(old_bytes) self.seek(0, 0) # We want to be at the beginning
29
199
118
317
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
32,918
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/encoder.py
633,634
579,658
_request_for_file
FileFromURLWrapper
635,652
634,652
class FileFromURLWrapper(object): """File from URL wrapper. The :class:`FileFromURLWrapper` object gives you the ability to stream file from provided URL in chunks by :class:`MultipartEncoder`. Provide a stateless solution for streaming file from one server to another. You can use the :class:`FileF...
class FileFromURLWrapper(object): """File from URL wrapper. The :class:`FileFromURLWrapper` object gives you the ability to stream file from provided URL in chunks by :class:`MultipartEncoder`. Provide a stateless solution for streaming file from one server to another. You can use the :class:`FileF...
response = self.session.get(file_url, stream=True) content_length = response.headers.get('content-length', None) if content_length is None: error_msg = ( "Data from provided URL {url} is not supported. Lack of " "content-length Header in requested file...
"""Make call for file under provided URL.""" response = self.session.get(file_url, stream=True) content_length = response.headers.get('content-length', None) if content_length is None: error_msg = ( "Data from provided URL {url} is not supported. Lack of " ...
63
604
204
808
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
32,919
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/encoder.py
575,576
567,579
read
FileWrapper
576,579
576,579
class FileWrapper(object): def __init__(self, file_object): self.fd = file_object @property def len(self): return total_len(self.fd) - self.fd.tell() def read(self, length=-1): FILL_FUNC_BODY
class FileWrapper(object): def __init__(self, file_object): self.fd = file_object @property def len(self): return total_len(self.fd) - self.fd.tell() def read(self, length=-1): FILL_FUNC_BODY
return self.fd.read(length)
return self.fd.read(length)
2
81
16
97
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
32,921
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/encoder.py
387,390
322,407
from_fields
MultipartEncoderMonitor
390,393
390,393
class MultipartEncoderMonitor(object): """ An object used to monitor the progress of a :class:`MultipartEncoder`. The :class:`MultipartEncoder` should only be responsible for preparing and streaming the data. For anyone who wishes to monitor it, they shouldn't be using that instance to manage that...
class MultipartEncoderMonitor(object): """ An object used to monitor the progress of a :class:`MultipartEncoder`. The :class:`MultipartEncoder` should only be responsible for preparing and streaming the data. For anyone who wishes to monitor it, they shouldn't be using that instance to manage that...
encoder = MultipartEncoder(fields, boundary, encoding) return cls(encoder, callback)
encoder = MultipartEncoder(fields, boundary, encoding) return cls(encoder, callback)
8
687
30
717
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
32,922
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/requests_toolbelt/multipart/encoder.py
509,510
483,533
write_to
Part
519,533
510,533
class Part(object): def __init__(self, headers, body): self.headers = headers self.body = body self.headers_unread = True self.len = len(self.headers) + total_len(self.body) @classmethod def from_field(cls, field, encoding): """Create a part from a Request Field gene...
class Part(object): def __init__(self, headers, body): self.headers = headers self.body = body self.headers_unread = True self.len = len(self.headers) + total_len(self.body) @classmethod def from_field(cls, field, encoding): """Create a part from a Request Field gene...
written = 0 if self.headers_unread: written += buffer.append(self.headers) self.headers_unread = False while total_len(self.body) > 0 and (size == -1 or written < size): amount_to_read = size if size != -1: amount_to_read = size - ...
"""Write the requested amount of bytes to the buffer provided. The number of bytes written may exceed size on the first read since we load the headers ambitiously. :param CustomBytesIO buffer: buffer we want to write bytes to :param int size: number of bytes requested to be wri...
40
357
132
489
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
# -*- coding: utf-8 -*- """ requests_toolbelt.multipart.encoder =================================== This holds all of the implementation details of the MultipartEncoder """ import contextlib import io import os from uuid import uuid4 import requests from .._compat import fields class FileNotSupportedError(Except...
32,925
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/version.py
56,57
31,63
_compare
_BaseVersion
57,63
57,63
class _BaseVersion(object): def __init__(self, key): self._key = key def __hash__(self): return hash(self._key) def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def _...
class _BaseVersion(object): def __init__(self, key): self._key = key def __hash__(self): return hash(self._key) def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def _...
if not isinstance(other, _BaseVersion): return NotImplemented return method(self._key, other._key)
if not isinstance(other, _BaseVersion): return NotImplemented return method(self._key, other._key)
9
247
42
289
from __future__ import absolute_import, division, print_function from copy import deepcopy from attr import attrs, attrib import re import six if six.PY3: from math import inf else: inf = float('inf') class InvalidVersion(ValueError): """ An invalid version was found, users should refer to PEP 440....
from __future__ import absolute_import, division, print_function from copy import deepcopy from attr import attrs, attrib import re import six if six.PY3: from math import inf else: inf = float('inf') class InvalidVersion(ValueError): """ An invalid version was found, users should refer to PEP 440....
32,926
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/clearml/utilities/wizard/user_input.py
53,54
1,111
input_bool
54,74
54,74
from typing import Optional def get_input( key, # type: str description="", # type: str question="Enter", # type: str required=False, # type: bool default=None, # type: Optional[str] new_line=False, # type: bool ): # type: (...) -> Optional[str] if new_line: print() w...
from typing import Optional def get_input( key, # type: str description="", # type: str question="Enter", # type: str required=False, # type: bool default=None, # type: Optional[str] new_line=False, # type: bool ): # type: (...) -> Optional[str] if new_line: print() w...
# type: (str, bool) -> bool """ :param question: string to display :param default: default boolean value :return: return True if response is 'y'/'yes' 't'/'true' in input.lower() """ while True: try: response = input("{}: ".format(question)).lower() if not res...
# type: (str, bool) -> bool """ :param question: string to display :param default: default boolean value :return: return True if response is 'y'/'yes' 't'/'true' in input.lower() """ while True: try: response = input("{}: ".format(question)).lower() if not res...
63
714
199
913
from typing import Optional def get_input( key, # type: str description="", # type: str question="Enter", # type: str required=False, # type: bool default=None, # type: Optional[str] new_line=False, # type: bool ): # type: (...) -> Optional[str] if new_line: print() w...
from typing import Optional def get_input( key, # type: str description="", # type: str question="Enter", # type: str required=False, # type: bool default=None, # type: Optional[str] new_line=False, # type: bool ): # type: (...) -> Optional[str] if new_line: print() w...
32,927
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/cicd/check_remotely_runnable.py
6,7
1,36
check_task_status
8,34
7,34
import sys import time from clearml import Task def check_task_status(task_id, timeout=600): FILL_FUNC_BODYif __name__ == '__main__': check_task_status(sys.argv[1])
import sys import time from clearml import Task def check_task_status(task_id, timeout=600): """Make sure the task can run by checking for iteration reports.""" FILL_FUNC_BODYif __name__ == '__main__': check_task_status(sys.argv[1])
# Get the task object task = Task.get_task(task_id=task_id) start_time = time.time() if task: while time.time() - start_time < timeout: task_status = task.get_status() print(task_status) print(task.get_last_iteration()) if task_status == 'queued':...
"""Make sure the task can run by checking for iteration reports.""" # Get the task object task = Task.get_task(task_id=task_id) start_time = time.time() if task: while time.time() - start_time < timeout: task_status = task.get_status() print(task_status) p...
85
83
285
368
import sys import time from clearml import Task def check_task_status(task_id, timeout=600): FILL_FUNC_BODYif __name__ == '__main__': check_task_status(sys.argv[1])
import sys import time from clearml import Task def check_task_status(task_id, timeout=600): """Make sure the task can run by checking for iteration reports.""" FILL_FUNC_BODYif __name__ == '__main__': check_task_status(sys.argv[1])
32,928
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/cicd/compare_models.py
7,8
1,31
compare_and_tag_task
9,28
8,28
import os from clearml import Task from task_stats_to_comment import get_clearml_task_of_current_commit def compare_and_tag_task(commit_hash): FILL_FUNC_BODYif __name__ == '__main__': print(f"Running on commit hash: {os.getenv('COMMIT_ID')}") compare_and_tag_task(os.getenv('COMMIT_ID'))
import os from clearml import Task from task_stats_to_comment import get_clearml_task_of_current_commit def compare_and_tag_task(commit_hash): """Compare current performance to best previous performance and only allow equal or better.""" FILL_FUNC_BODYif __name__ == '__main__': print(f"Running on commit hash...
current_task = get_clearml_task_of_current_commit(commit_hash) best_task = Task.get_task(project_name='Github CICD Video', task_name='cicd_test', tags=['Best Performance']) if best_task: best_metric = max( best_task.get_reported_scalars().get('Performance Metric').get('Series 1').get('y'...
"""Compare current performance to best previous performance and only allow equal or better.""" current_task = get_clearml_task_of_current_commit(commit_hash) best_task = Task.get_task(project_name='Github CICD Video', task_name='cicd_test', tags=['Best Performance']) if best_task: best_metric = ...
68
130
282
412
import os from clearml import Task from task_stats_to_comment import get_clearml_task_of_current_commit def compare_and_tag_task(commit_hash): FILL_FUNC_BODYif __name__ == '__main__': print(f"Running on commit hash: {os.getenv('COMMIT_ID')}") compare_and_tag_task(os.getenv('COMMIT_ID'))
import os from clearml import Task from task_stats_to_comment import get_clearml_task_of_current_commit def compare_and_tag_task(commit_hash): """Compare current performance to best previous performance and only allow equal or better.""" FILL_FUNC_BODYif __name__ == '__main__': print(f"Running on commit hash...
32,929
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/datasets/csv_dataset_creation.py
4,5
1,28
main
5,26
5,26
from clearml import StorageManager, Dataset def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
from clearml import StorageManager, Dataset def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
manager = StorageManager() print("STEP1 : Downloading CSV dataset") csv_file_path = manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/Iris_Species.csv") print("STEP2 : Creating a dataset") # By default, clearml data uploads to the clearml fileserver. Ad...
manager = StorageManager() print("STEP1 : Downloading CSV dataset") csv_file_path = manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/Iris_Species.csv") print("STEP2 : Creating a dataset") # By default, clearml data uploads to the clearml fileserver. Ad...
78
41
278
319
from clearml import StorageManager, Dataset def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
from clearml import StorageManager, Dataset def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
32,930
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/datasets/dataset_folder_syncing.py
9,10
1,51
download_mnist_dataset
10,19
10,19
import shutil from uuid import uuid4 from pathlib2 import Path from clearml import Dataset, StorageManager def download_mnist_dataset(): FILL_FUNC_BODYdef main(): print("STEP1 : Downloading mnist dataset") mnist_dataset_train, mnist_dataset_test = download_mnist_dataset() print("STEP2 : Preparing mnist...
import shutil from uuid import uuid4 from pathlib2 import Path from clearml import Dataset, StorageManager def download_mnist_dataset(): FILL_FUNC_BODYdef main(): print("STEP1 : Downloading mnist dataset") mnist_dataset_train, mnist_dataset_test = download_mnist_dataset() print("STEP2 : Preparing mnist...
manager = StorageManager() mnist_dataset = Path(manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/MNIST.zip", name="MNIST")) mnist_dataset_train = mnist_dataset / "TRAIN" mnist_dataset_test = mnist_dataset / "TEST" return mnist_dataset_train, mnist_datas...
manager = StorageManager() mnist_dataset = Path(manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/MNIST.zip", name="MNIST")) mnist_dataset_train = mnist_dataset / "TRAIN" mnist_dataset_test = mnist_dataset / "TEST" return mnist_dataset_train, mnist_datas...
21
447
136
583
import shutil from uuid import uuid4 from pathlib2 import Path from clearml import Dataset, StorageManager def download_mnist_dataset(): FILL_FUNC_BODYdef main(): print("STEP1 : Downloading mnist dataset") mnist_dataset_train, mnist_dataset_test = download_mnist_dataset() print("STEP2 : Preparing mnist...
import shutil from uuid import uuid4 from pathlib2 import Path from clearml import Dataset, StorageManager def download_mnist_dataset(): FILL_FUNC_BODYdef main(): print("STEP1 : Downloading mnist dataset") mnist_dataset_train, mnist_dataset_test = download_mnist_dataset() print("STEP2 : Preparing mnist...
32,931
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/datasets/multi_parent_child_dataset.py
6,7
1,41
main
7,39
7,39
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
manager = StorageManager() print("STEP1 : Downloading mnist dataset") mnist_dataset = Path(manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/MNIST.zip", name="MNIST")) mnist_dataset_train = mnist_dataset / "TRAIN" mnist_dataset_test = mnist_dataset / "TE...
manager = StorageManager() print("STEP1 : Downloading mnist dataset") mnist_dataset = Path(manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/MNIST.zip", name="MNIST")) mnist_dataset_train = mnist_dataset / "TRAIN" mnist_dataset_test = mnist_dataset / "TE...
89
49
464
513
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == "__main__": main()
32,932
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/datasets/single_parent_child_dataset.py
6,7
1,34
main
7,32
7,32
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
manager = StorageManager() print("STEP1 : Downloading mnist dataset") mnist_dataset = Path(manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/MNIST.zip", name="MNIST")) mnist_dataset_train = mnist_dataset / "TRAIN" mnist_dataset_test = mnist_dataset / "TE...
manager = StorageManager() print("STEP1 : Downloading mnist dataset") mnist_dataset = Path(manager.get_local_copy( remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/MNIST.zip", name="MNIST")) mnist_dataset_train = mnist_dataset / "TRAIN" mnist_dataset_test = mnist_dataset / "TE...
72
49
380
429
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
32,933
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/optimization/hyper-parameter-optimization/hyper_parameter_optimizer.py
23,30
1,135
job_complete_callback
30,37
30,37
import logging from clearml import Task from clearml.automation import ( DiscreteParameterRange, HyperParameterOptimizer, RandomSearch, UniformIntegerParameterRange) # trying to load Bayesian optimizer package try: from clearml.automation.optuna import OptimizerOptuna # noqa aSearchStrategy = Optimiz...
import logging from clearml import Task from clearml.automation import ( DiscreteParameterRange, HyperParameterOptimizer, RandomSearch, UniformIntegerParameterRange) # trying to load Bayesian optimizer package try: from clearml.automation.optuna import OptimizerOptuna # noqa aSearchStrategy = Optimiz...
print('Job completed!', job_id, objective_value, objective_iteration, job_parameters) if job_id == top_performance_job_id: print('WOOT WOOT we broke the record! Objective reached {}'.format(objective_value)) # Connecting ClearML with the current process, # from here on everything is logged automatical...
print('Job completed!', job_id, objective_value, objective_iteration, job_parameters) if job_id == top_performance_job_id: print('WOOT WOOT we broke the record! Objective reached {}'.format(objective_value)) # Connecting ClearML with the current process, # from here on everything is logged automatical...
34
1,774
95
1,869
import logging from clearml import Task from clearml.automation import ( DiscreteParameterRange, HyperParameterOptimizer, RandomSearch, UniformIntegerParameterRange) # trying to load Bayesian optimizer package try: from clearml.automation.optuna import OptimizerOptuna # noqa aSearchStrategy = Optimiz...
import logging from clearml import Task from clearml.automation import ( DiscreteParameterRange, HyperParameterOptimizer, RandomSearch, UniformIntegerParameterRange) # trying to load Bayesian optimizer package try: from clearml.automation.optuna import OptimizerOptuna # noqa aSearchStrategy = Optimiz...
32,934
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/pipeline/decorated_pipeline_step_decorators.py
16,18
1,25
pipeline
18,22
18,22
from clearml import PipelineDecorator def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @PipelineDecorator.component() @our_decorator def step(): return 1 @PipelineDecorator.pipeline(name="test_decorated", project="test_dec...
from clearml import PipelineDecorator def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @PipelineDecorator.component() @our_decorator def step(): return 1 @PipelineDecorator.pipeline(name="test_decorated", project="test_dec...
result = step() assert result == 2
result = step() assert result == 2
7
149
18
167
from clearml import PipelineDecorator def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @PipelineDecorator.component() @our_decorator def step(): return 1 @PipelineDecorator.pipeline(name="test_decorated", project="test_dec...
from clearml import PipelineDecorator def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @PipelineDecorator.component() @our_decorator def step(): return 1 @PipelineDecorator.pipeline(name="test_decorated", project="test_dec...
32,935
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/pipeline/decorated_pipeline_step_functions.py
15,16
1,28
evaluate
16,19
16,19
from clearml import PipelineController def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @our_decorator def step(): return 1 def evaluate(step_return): FILL_FUNC_BODYif __name__ == "__main__": pipeline = PipelineControl...
from clearml import PipelineController def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @our_decorator def step(): return 1 def evaluate(step_return): FILL_FUNC_BODYif __name__ == "__main__": pipeline = PipelineControl...
assert step_return == 2
assert step_return == 2
4
221
13
234
from clearml import PipelineController def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @our_decorator def step(): return 1 def evaluate(step_return): FILL_FUNC_BODYif __name__ == "__main__": pipeline = PipelineControl...
from clearml import PipelineController def our_decorator(func): def function_wrapper(*args, **kwargs): return func(*args, **kwargs) + 1 return function_wrapper @our_decorator def step(): return 1 def evaluate(step_return): FILL_FUNC_BODYif __name__ == "__main__": pipeline = PipelineControl...
32,936
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/pipeline/pipeline_from_tasks.py
17,18
1,72
post_execute_callback_example
18,26
18,26
from clearml import Task from clearml.automation import PipelineController def pre_execute_callback_example(a_pipeline, a_node, current_param_override): # type (PipelineController, PipelineController.Node, dict) -> bool print( "Cloning Task id={} with parameters: {}".format( a_node.base_ta...
from clearml import Task from clearml.automation import PipelineController def pre_execute_callback_example(a_pipeline, a_node, current_param_override): # type (PipelineController, PipelineController.Node, dict) -> bool print( "Cloning Task id={} with parameters: {}".format( a_node.base_ta...
# type (PipelineController, PipelineController.Node) -> None print("Completed Task id={}".format(a_node.executed)) # if we need the actual executed Task: Task.get_task(task_id=a_node.executed) return # Connecting ClearML with the current pipeline, # from here on everything is logged automatically
# type (PipelineController, PipelineController.Node) -> None print("Completed Task id={}".format(a_node.executed)) # if we need the actual executed Task: Task.get_task(task_id=a_node.executed) return # Connecting ClearML with the current pipeline, # from here on everything is logged automatically
34
690
99
789
from clearml import Task from clearml.automation import PipelineController def pre_execute_callback_example(a_pipeline, a_node, current_param_override): # type (PipelineController, PipelineController.Node, dict) -> bool print( "Cloning Task id={} with parameters: {}".format( a_node.base_ta...
from clearml import Task from clearml.automation import PipelineController def pre_execute_callback_example(a_pipeline, a_node, current_param_override): # type (PipelineController, PipelineController.Node, dict) -> bool print( "Cloning Task id={} with parameters: {}".format( a_node.base_ta...
32,937
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/reporting/3d_plots_reporting.py
8,9
1,65
report_plots
9,41
9,41
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_na...
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_na...
# type: (Logger, int) -> () """ reporting plots to plots section :param logger: The task.logger to use for sending the plots :param iteration: The iteration number of the current reports """ # report 3d surface surface = np.random.randint(10, size=(10, 10)) logger.report_surface( ...
# type: (Logger, int) -> () """ reporting plots to plots section :param logger: The task.logger to use for sending the plots :param iteration: The iteration number of the current reports """ # report 3d surface surface = np.random.randint(10, size=(10, 10)) logger.report_surface( ...
75
254
300
554
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_na...
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_na...
32,938
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/reporting/artifacts_retrieval.py
9,10
1,69
main
10,67
10,67
# ClearML - example code, retrieve other task artifacts and print the artifacts # Please run examples/reporting/artifacts.py example before running this example # from pprint import pprint from clearml import Task def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
# ClearML - example code, retrieve other task artifacts and print the artifacts # Please run examples/reporting/artifacts.py example before running this example # from pprint import pprint from clearml import Task def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
# Getting the task we want to get the artifacts from artifacts_task = Task.get_task( project_name='examples', task_name='Artifacts example', task_filter={'status': ['completed']} ) # getting the numpy object back numpy_artifact = artifacts_task.artifacts['Numpy Eye'].get() ...
# Getting the task we want to get the artifacts from artifacts_task = Task.get_task( project_name='examples', task_name='Artifacts example', task_filter={'status': ['completed']} ) # getting the numpy object back numpy_artifact = artifacts_task.artifacts['Numpy Eye'].get() ...
242
83
882
965
# ClearML - example code, retrieve other task artifacts and print the artifacts # Please run examples/reporting/artifacts.py example before running this example # from pprint import pprint from clearml import Task def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
# ClearML - example code, retrieve other task artifacts and print the artifacts # Please run examples/reporting/artifacts.py example before running this example # from pprint import pprint from clearml import Task def main(): FILL_FUNC_BODYif __name__ == '__main__': main()
32,939
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/reporting/image_reporting.py
45,46
1,69
main
46,67
46,67
# ClearML - Example of manual graphs and statistics reporting # import os import numpy as np from PIL import Image from clearml import Task, Logger def report_debug_images(logger, iteration=0): # type: (Logger, int) -> () """ reporting images to debug samples section :param logger: The task.logger ...
# ClearML - Example of manual graphs and statistics reporting # import os import numpy as np from PIL import Image from clearml import Task, Logger def report_debug_images(logger, iteration=0): # type: (Logger, int) -> () """ reporting images to debug samples section :param logger: The task.logger ...
# Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Image reporting") print('reporting a few debug images') # Get the task logger, # You can also call Task.current_task().get_logger() from anywher...
# Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Image reporting") print('reporting a few debug images') # Get the task logger, # You can also call Task.current_task().get_logger() from anywher...
88
525
200
725
# ClearML - Example of manual graphs and statistics reporting # import os import numpy as np from PIL import Image from clearml import Task, Logger def report_debug_images(logger, iteration=0): # type: (Logger, int) -> () """ reporting images to debug samples section :param logger: The task.logger ...
# ClearML - Example of manual graphs and statistics reporting # import os import numpy as np from PIL import Image from clearml import Task, Logger def report_debug_images(logger, iteration=0): # type: (Logger, int) -> () """ reporting images to debug samples section :param logger: The task.logger ...
32,940
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/reporting/scalar_reporting.py
6,7
1,51
report_scalars
7,27
7,27
# ClearML - Example of manual graphs and statistics reporting # from clearml import Task, Logger def report_scalars(logger): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Scala...
# ClearML - Example of manual graphs and statistics reporting # from clearml import Task, Logger def report_scalars(logger): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Scala...
# type: (Logger) -> () """ reporting scalars to scalars section :param logger: The task.logger to use for sending the scalars """ # report two scalar series on the same graph for i in range(100): logger.report_scalar(title="unified graph", series="series A", iteration=i, value=1. / (...
# type: (Logger) -> () """ reporting scalars to scalars section :param logger: The task.logger to use for sending the scalars """ # report two scalar series on the same graph for i in range(100): logger.report_scalar(title="unified graph", series="series A", iteration=i, value=1. / (...
98
240
309
549
# ClearML - Example of manual graphs and statistics reporting # from clearml import Task, Logger def report_scalars(logger): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Scala...
# ClearML - Example of manual graphs and statistics reporting # from clearml import Task, Logger def report_scalars(logger): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Scala...
32,941
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/reporting/scatter_hist_confusion_mat_reporting.py
8,9
1,135
report_plots
9,111
9,111
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_n...
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_n...
# type: (Logger, int) -> () """ reporting plots to plots section :param logger: The task.logger to use for sending the plots :param iteration: The iteration number of the current reports """ # report a single histogram histogram = np.random.randint(10, size=10) logger.report_histogr...
# type: (Logger, int) -> () """ reporting plots to plots section :param logger: The task.logger to use for sending the plots :param iteration: The iteration number of the current reports """ # report a single histogram histogram = np.random.randint(10, size=10) logger.report_histogr...
214
252
1,035
1,287
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_n...
# ClearML - Example of manual graphs and statistics reporting # import numpy as np from clearml import Task, Logger def report_plots(logger, iteration=0): FILL_FUNC_BODYdef main(): # Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_n...
32,942
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/reporting/text_reporting.py
60,61
1,93
main
61,91
61,91
# ClearML - Example of manual graphs and statistics reporting # from __future__ import print_function import logging import sys import six from clearml import Logger, Task def report_logs(logger): # type: (Logger) -> () """ reporting text to logs section :param logger: The task.logger to use for s...
# ClearML - Example of manual graphs and statistics reporting # from __future__ import print_function import logging import sys import six from clearml import Logger, Task def report_logs(logger): # type: (Logger) -> () """ reporting text to logs section :param logger: The task.logger to use for s...
# Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Text reporting") print("reporting text logs") # report regular console print print("This is standard output test") # report stderr prin...
# Connecting ClearML with the current process, # from here on everything is logged automatically task = Task.init(project_name="examples", task_name="Text reporting") print("reporting text logs") # report regular console print print("This is standard output test") # report stderr prin...
113
640
268
908
# ClearML - Example of manual graphs and statistics reporting # from __future__ import print_function import logging import sys import six from clearml import Logger, Task def report_logs(logger): # type: (Logger) -> () """ reporting text to logs section :param logger: The task.logger to use for s...
# ClearML - Example of manual graphs and statistics reporting # from __future__ import print_function import logging import sys import six from clearml import Logger, Task def report_logs(logger): # type: (Logger) -> () """ reporting text to logs section :param logger: The task.logger to use for s...
32,943
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/scheduler/cron_example.py
5,6
1,62
simple_function
6,13
6,13
from clearml import Task from clearml.automation import TaskScheduler def simple_function(): FILL_FUNC_BODYscheduler = TaskScheduler() # Run the Task 'PyTorch MNIST train', every day at 10:30am scheduler.add_task( name='recurring pipeline job', schedule_task_id=Task.get_task(project_name='examples', task_nam...
from clearml import Task from clearml.automation import TaskScheduler def simple_function(): FILL_FUNC_BODYscheduler = TaskScheduler() # Run the Task 'PyTorch MNIST train', every day at 10:30am scheduler.add_task( name='recurring pipeline job', schedule_task_id=Task.get_task(project_name='examples', task_nam...
print('This code is executed in a background thread, ' 'on the same machine as the TaskScheduler process') # add some logic here print('done') # Create the scheduler controller
print('This code is executed in a background thread, ' 'on the same machine as the TaskScheduler process') # add some logic here print('done') # Create the scheduler controller
28
819
57
876
from clearml import Task from clearml.automation import TaskScheduler def simple_function(): FILL_FUNC_BODYscheduler = TaskScheduler() # Run the Task 'PyTorch MNIST train', every day at 10:30am scheduler.add_task( name='recurring pipeline job', schedule_task_id=Task.get_task(project_name='examples', task_nam...
from clearml import Task from clearml.automation import TaskScheduler def simple_function(): FILL_FUNC_BODYscheduler = TaskScheduler() # Run the Task 'PyTorch MNIST train', every day at 10:30am scheduler.add_task( name='recurring pipeline job', schedule_task_id=Task.get_task(project_name='examples', task_nam...
32,944
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/examples/scheduler/trigger_example.py
10,11
1,66
trigger_dataset_func
11,15
11,15
from clearml import Task, Dataset, Model from clearml.automation import TriggerScheduler def trigger_model_func(model_id): model = Model(model_id=model_id) print('model id {} modified'.format(model.id)) def trigger_dataset_func(dataset_id): FILL_FUNC_BODYdef trigger_task_func(task_id): task = Task.get_t...
from clearml import Task, Dataset, Model from clearml.automation import TriggerScheduler def trigger_model_func(model_id): model = Model(model_id=model_id) print('model id {} modified'.format(model.id)) def trigger_dataset_func(dataset_id): FILL_FUNC_BODYdef trigger_task_func(task_id): task = Task.get_t...
dataset = Dataset.get(dataset_id=dataset_id) print('dataset id {} created'.format(dataset.id))
dataset = Dataset.get(dataset_id=dataset_id) print('dataset id {} created'.format(dataset.id))
7
639
38
677
from clearml import Task, Dataset, Model from clearml.automation import TriggerScheduler def trigger_model_func(model_id): model = Model(model_id=model_id) print('model id {} modified'.format(model.id)) def trigger_dataset_func(dataset_id): FILL_FUNC_BODYdef trigger_task_func(task_id): task = Task.get_t...
from clearml import Task, Dataset, Model from clearml.automation import TriggerScheduler def trigger_model_func(model_id): model = Model(model_id=model_id) print('model id {} modified'.format(model.id)) def trigger_dataset_func(dataset_id): FILL_FUNC_BODYdef trigger_task_func(task_id): task = Task.get_t...
32,945
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml
/home/hieuvd/dung_repo/raw/stars_02/allegroai_clearml/clearml/setup.py
12,13
1,106
read_text
13,17
13,17
""" ClearML - Artificial Intelligence Version Control https://github.com/allegroai/clearml """ import os.path # Always prefer setuptools over distutils from setuptools import setup, find_packages import codecs def read_text(filepath): FILL_FUNC_BODYhere = os.path.dirname(__file__) # Get the long description from the...
""" ClearML - Artificial Intelligence Version Control https://github.com/allegroai/clearml """ import os.path # Always prefer setuptools over distutils from setuptools import setup, find_packages import codecs def read_text(filepath): FILL_FUNC_BODYhere = os.path.dirname(__file__) # Get the long description from the...
with codecs.open(filepath, "r", encoding="utf-8") as f: return f.read()
with codecs.open(filepath, "r", encoding="utf-8") as f: return f.read()
8
1,199
37
1,236
""" ClearML - Artificial Intelligence Version Control https://github.com/allegroai/clearml """ import os.path # Always prefer setuptools over distutils from setuptools import setup, find_packages import codecs def read_text(filepath): FILL_FUNC_BODYhere = os.path.dirname(__file__) # Get the long description from the...
""" ClearML - Artificial Intelligence Version Control https://github.com/allegroai/clearml """ import os.path # Always prefer setuptools over distutils from setuptools import setup, find_packages import codecs def read_text(filepath): FILL_FUNC_BODYhere = os.path.dirname(__file__) # Get the long description from the...
33,039
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/pipelines.py
10,11
9,12
process_item
CrawlerPipeline
11,12
11,12
class CrawlerPipeline(object): def process_item(self, item, spider): FILL_FUNC_BODY
class CrawlerPipeline(object): def process_item(self, item, spider): FILL_FUNC_BODY
return item
return item
2
34
5
39
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class CrawlerPipeline(object): def process_item(self, item, spider): FILL_FUNC_BODY
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class CrawlerPipeline(object): def process_item(self, item, spider): FILL_FUNC_BODY
33,040
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/data5u.py
31,32
8,53
parse_page
Data5uSpider
32,53
32,53
class Data5uSpider(BaseSpider): name = 'data5u' def __init__(self, *a, **kw): # 在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法 # 但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法了,可通过使用 super 来实现,比如: super(Data5uSpider, self).__init__(*a, **kw) self.urls = [ 'http://www.data5u.com/' ] ...
class Data5uSpider(BaseSpider): name = 'data5u' def __init__(self, *a, **kw): # 在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法 # 但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法了,可通过使用 super 来实现,比如: super(Data5uSpider, self).__init__(*a, **kw) self.urls = [ 'http://www.data5u.com/' ] ...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//ul[@class="l2"]').extract() for i, info in enumerate(infos): val = Selector(text=info) ip = val.xpath('//ul[@class="l2"]/span[1]/li/text()').extract_first() port = val.xpath('//ul...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//ul[@class="l2"]').extract() for i, info in enumerate(infos): val = Selector(text=info) ip = val.xpath('//ul[@class="l2"]/span[1]/li/text()').extract_first() port = val.xpath('//ul...
41
386
335
721
# -*- coding: utf-8 -*- from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class Data5uSpider(BaseSpider): name = 'data5u' def __init__(self, *a, **kw): # 在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法 # 但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法了,可通过使用 super 来实现,比如: supe...
# -*- coding: utf-8 -*- from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class Data5uSpider(BaseSpider): name = 'data5u' def __init__(self, *a, **kw): # 在类的继承中,如果重定义某个方法,该方法会覆盖父类的同名方法 # 但有时,我们希望能同时实现父类的功能,这时,我们就需要调用父类的方法了,可通过使用 super 来实现,比如: supe...
33,041
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/gatherproxy.py
56,57
12,74
get_proxy
GatherproxySpider
57,74
57,74
class GatherproxySpider(BaseSpider): name = 'gatherproxy' def __init__(self, *a, **kwargs): super(GatherproxySpider, self).__init__(*a, **kwargs) self.urls = [ 'http://gatherproxy.com/', 'http://www.gatherproxy.com/proxylist/anonymity/?t=Anonymous', 'http://g...
class GatherproxySpider(BaseSpider): name = 'gatherproxy' def __init__(self, *a, **kwargs): super(GatherproxySpider, self).__init__(*a, **kwargs) self.urls = [ 'http://gatherproxy.com/', 'http://www.gatherproxy.com/proxylist/anonymity/?t=Anonymous', 'http://g...
try: url = 'http://127.0.0.1:8000/?name={0}'.format(self.name) r = requests.get(url = url) if r.text != None and r.text != '': data = json.loads(r.text) if len(data) > 0: proxy = random.choice(data) ip = ...
try: url = 'http://127.0.0.1:8000/?name={0}'.format(self.name) r = requests.get(url = url) if r.text != None and r.text != '': data = json.loads(r.text) if len(data) > 0: proxy = random.choice(data) ip = ...
52
541
192
733
# coding=utf-8 import json import random import re import requests from proxy import Proxy from .basespider import BaseSpider class GatherproxySpider(BaseSpider): name = 'gatherproxy' def __init__(self, *a, **kwargs): super(GatherproxySpider, self).__init__(*a, **kwargs) self.urls = [ ...
# coding=utf-8 import json import random import re import requests from proxy import Proxy from .basespider import BaseSpider class GatherproxySpider(BaseSpider): name = 'gatherproxy' def __init__(self, *a, **kwargs): super(GatherproxySpider, self).__init__(*a, **kwargs) self.urls = [ ...
33,042
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/hidemy.py
30,31
10,55
parse_page
HidemySpider
31,55
31,55
class HidemySpider(BaseSpider): name = 'hidemy' def __init__(self, *a, **kw): super(HidemySpider, self).__init__(*a, **kw) self.urls = ['https://hidemy.name/en/proxy-list/?start=%s' % n for n in range(0, 5 * 64, 64)] self.headers = { 'Accept': 'text/html,application/xhtml+x...
class HidemySpider(BaseSpider): name = 'hidemy' def __init__(self, *a, **kw): super(HidemySpider, self).__init__(*a, **kw) self.urls = ['https://hidemy.name/en/proxy-list/?start=%s' % n for n in range(0, 5 * 64, 64)] self.headers = { 'Accept': 'text/html,application/xhtml+x...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//tbody/tr').extract() for i, info in enumerate(infos): if i == 0: continue val = Selector(text = info) ip = val.xpath('//td[1]/text()').extract_first() ...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//tbody/tr').extract() for i, info in enumerate(infos): if i == 0: continue val = Selector(text = info) ip = val.xpath('//td[1]/text()').extract_first() ...
57
340
261
601
#-*- coding: utf-8 -*- import utils from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class HidemySpider(BaseSpider): name = 'hidemy' def __init__(self, *a, **kw): super(HidemySpider, self).__init__(*a, **kw) self.urls = ['https://hidemy.name/en/proxy-l...
#-*- coding: utf-8 -*- import utils from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class HidemySpider(BaseSpider): name = 'hidemy' def __init__(self, *a, **kw): super(HidemySpider, self).__init__(*a, **kw) self.urls = ['https://hidemy.name/en/proxy-l...
33,043
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/ip181.py
27,28
8,53
parse_page
IpOneEightOneSpider
28,53
28,53
class IpOneEightOneSpider(BaseSpider): name = 'ip181' def __init__(self, *a, **kw): super(IpOneEightOneSpider, self).__init__(*a, **kw) self.urls = ['http://www.ip181.com/'] self.headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', ...
class IpOneEightOneSpider(BaseSpider): name = 'ip181' def __init__(self, *a, **kw): super(IpOneEightOneSpider, self).__init__(*a, **kw) self.urls = ['http://www.ip181.com/'] self.headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', ...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//tbody/tr').extract() for i, info in enumerate(infos): if i == 0: continue val = Selector(text = info) ip = val.xpath('//td[1]/text()').extract_first() ...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//tbody/tr').extract() for i, info in enumerate(infos): if i == 0: continue val = Selector(text = info) ip = val.xpath('//td[1]/text()').extract_first() ...
60
292
283
575
#-*- coding: utf-8 -*- from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class IpOneEightOneSpider(BaseSpider): name = 'ip181' def __init__(self, *a, **kw): super(IpOneEightOneSpider, self).__init__(*a, **kw) self.urls = ['http://www.ip181.com/'] ...
#-*- coding: utf-8 -*- from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class IpOneEightOneSpider(BaseSpider): name = 'ip181' def __init__(self, *a, **kw): super(IpOneEightOneSpider, self).__init__(*a, **kw) self.urls = ['http://www.ip181.com/'] ...
33,044
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/kuaidaili.py
27,28
9,45
parse_page
KuaiDaiLiSpider
28,45
28,45
class KuaiDaiLiSpider(BaseSpider): name = 'kuaidaili' def __init__(self, *a, **kwargs): super(KuaiDaiLiSpider, self).__init__(*a, **kwargs) self.urls = ['https://www.kuaidaili.com/free/inha/%s/' % i for i in range(1, 5)] self.headers = { 'Accept':'text/html,application/xht...
class KuaiDaiLiSpider(BaseSpider): name = 'kuaidaili' def __init__(self, *a, **kwargs): super(KuaiDaiLiSpider, self).__init__(*a, **kwargs) self.urls = ['https://www.kuaidaili.com/free/inha/%s/' % i for i in range(1, 5)] self.headers = { 'Accept':'text/html,application/xht...
pattern = re.compile( '<tr>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(' '.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?</tr>', re.S) items = re.findall(pattern, response.body.decode()) ...
pattern = re.compile( '<tr>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(' '.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?<td.*?>(.*?)</td>\s.*?</tr>', re.S) items = re.findall(pattern, response.body.decode()) ...
35
306
257
563
#-*- coding: utf-8 -*- import re from proxy import Proxy from .basespider import BaseSpider class KuaiDaiLiSpider(BaseSpider): name = 'kuaidaili' def __init__(self, *a, **kwargs): super(KuaiDaiLiSpider, self).__init__(*a, **kwargs) self.urls = ['https://www.kuaidaili.com/free/inha/%s/' % i...
#-*- coding: utf-8 -*- import re from proxy import Proxy from .basespider import BaseSpider class KuaiDaiLiSpider(BaseSpider): name = 'kuaidaili' def __init__(self, *a, **kwargs): super(KuaiDaiLiSpider, self).__init__(*a, **kwargs) self.urls = ['https://www.kuaidaili.com/free/inha/%s/' % i...
33,045
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/proxydb.py
41,42
9,49
parse_ip
ProxyDBSpider
42,49
42,49
class ProxyDBSpider(BaseSpider): name = 'proxydb' def __init__(self, *a, **kwargs): super(ProxyDBSpider, self).__init__(*a, **kwargs) self.urls = ['http://proxydb.net/?protocol=http&protocol=https&offset=%s' % n for n in range(1, 500, 50)] self.headers = { 'Accept':'text/htm...
class ProxyDBSpider(BaseSpider): name = 'proxydb' def __init__(self, *a, **kwargs): super(ProxyDBSpider, self).__init__(*a, **kwargs) self.urls = ['http://proxydb.net/?protocol=http&protocol=https&offset=%s' % n for n in range(1, 500, 50)] self.headers = { 'Accept':'text/htm...
ip_part1 = re.search(r'\'(.*)\'\.split',page).group(1)[::-1] ip_part2= ''.join([chr(int(x,16)) for x in re.findall(r'\\x([0-9A-Fa-f]{2})', page)]) ip_part2= b64decode(ip_part2).decode('utf-8') port = re.search(r'pp = -(\d+) \+ (\d+);',page).groups() port = -int(port[0]) + int(por...
ip_part1 = re.search(r'\'(.*)\'\.split',page).group(1)[::-1] ip_part2= ''.join([chr(int(x,16)) for x in re.findall(r'\\x([0-9A-Fa-f]{2})', page)]) ip_part2= b64decode(ip_part2).decode('utf-8') port = re.search(r'pp = -(\d+) \+ (\d+);',page).groups() port = -int(port[0]) + int(por...
26
502
179
681
# coding=utf-8 from proxy import Proxy from .basespider import BaseSpider from scrapy.selector import Selector import re from base64 import b64decode class ProxyDBSpider(BaseSpider): name = 'proxydb' def __init__(self, *a, **kwargs): super(ProxyDBSpider, self).__init__(*a, **kwargs) self.urls...
# coding=utf-8 from proxy import Proxy from .basespider import BaseSpider from scrapy.selector import Selector import re from base64 import b64decode class ProxyDBSpider(BaseSpider): name = 'proxydb' def __init__(self, *a, **kwargs): super(ProxyDBSpider, self).__init__(*a, **kwargs) self.urls...
33,046
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/proxylistplus.py
32,33
8,56
parse_page
ProxylistplusSpider
33,56
33,56
class ProxylistplusSpider(BaseSpider): name = 'proxylistplus' def __init__(self, *a, **kw): super(ProxylistplusSpider, self).__init__(*a, **kw) self.urls = ['https://list.proxylistplus.com/Fresh-HTTP-Proxy-List-%s' % n for n in range(1, 3)] self.headers = { 'Accept': 'text/...
class ProxylistplusSpider(BaseSpider): name = 'proxylistplus' def __init__(self, *a, **kw): super(ProxylistplusSpider, self).__init__(*a, **kw) self.urls = ['https://list.proxylistplus.com/Fresh-HTTP-Proxy-List-%s' % n for n in range(1, 3)] self.headers = { 'Accept': 'text/...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//tr[@class="cells"]').extract() for i, info in enumerate(infos): self.log(info) val = Selector(text = info) ip = val.xpath('//td[2]/text()').extract_first() port = val...
self.write(response.body) sel = Selector(response) infos = sel.xpath('//tr[@class="cells"]').extract() for i, info in enumerate(infos): self.log(info) val = Selector(text = info) ip = val.xpath('//td[2]/text()').extract_first() port = val...
53
418
262
680
#-*- coding: utf-8 -*- from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class ProxylistplusSpider(BaseSpider): name = 'proxylistplus' def __init__(self, *a, **kw): super(ProxylistplusSpider, self).__init__(*a, **kw) self.urls = ['https://list.proxylistp...
#-*- coding: utf-8 -*- from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class ProxylistplusSpider(BaseSpider): name = 'proxylistplus' def __init__(self, *a, **kw): super(ProxylistplusSpider, self).__init__(*a, **kw) self.urls = ['https://list.proxylistp...
33,047
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/sixsixip.py
29,30
9,45
parse_page
SixSixIpSpider
30,45
30,45
class SixSixIpSpider(BaseSpider): name = 'sixsixip' def __init__(self, *a, **kwargs): super(SixSixIpSpider, self).__init__(*a, **kwargs) self.urls = ['http://m.66ip.cn/%s.html' % n for n in range(1, 10)] self.headers = { 'Accept': 'text/html,application/xhtml+xml,applicatio...
class SixSixIpSpider(BaseSpider): name = 'sixsixip' def __init__(self, *a, **kwargs): super(SixSixIpSpider, self).__init__(*a, **kwargs) self.urls = ['http://m.66ip.cn/%s.html' % n for n in range(1, 10)] self.headers = { 'Accept': 'text/html,application/xhtml+xml,applicatio...
pattern = re.compile('<tr><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td></tr>', re.S) items = re.findall(pattern, response.body.decode()) for i, item in enumerate(items): if i >= 1: proxy = Proxy() p...
pattern = re.compile('<tr><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td></tr>', re.S) items = re.findall(pattern, response.body.decode()) for i, item in enumerate(items): if i >= 1: proxy = Proxy() p...
40
319
189
508
# coding=utf-8 import re from proxy import Proxy from .basespider import BaseSpider class SixSixIpSpider(BaseSpider): name = 'sixsixip' def __init__(self, *a, **kwargs): super(SixSixIpSpider, self).__init__(*a, **kwargs) self.urls = ['http://m.66ip.cn/%s.html' % n for n in range(1, 10)] ...
# coding=utf-8 import re from proxy import Proxy from .basespider import BaseSpider class SixSixIpSpider(BaseSpider): name = 'sixsixip' def __init__(self, *a, **kwargs): super(SixSixIpSpider, self).__init__(*a, **kwargs) self.urls = ['http://m.66ip.cn/%s.html' % n for n in range(1, 10)] ...
33,048
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/usproxy.py
36,37
9,54
parse_page
UsProxySpider
37,54
37,54
class UsProxySpider(BaseSpider): name = 'usproxy' def __init__(self, *a, **kwargs): super(UsProxySpider, self).__init__(*a, **kwargs) self.urls = [ 'http://www.sslproxies.org/', 'http://www.us-proxy.org/', 'http://free-proxy-list.net/uk-proxy.html', ...
class UsProxySpider(BaseSpider): name = 'usproxy' def __init__(self, *a, **kwargs): super(UsProxySpider, self).__init__(*a, **kwargs) self.urls = [ 'http://www.sslproxies.org/', 'http://www.us-proxy.org/', 'http://free-proxy-list.net/uk-proxy.html', ...
pattern = re.compile( '<tr><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td.+?>(.*?)</td><td>(.*?)</td><td.+?>(.*?)</td><td.+?>(.*?)</td><td.+?>(.*?)</td></tr>', re.S) items = re.findall(pattern, response.body.decode()) if items is not None: for item in items: ...
pattern = re.compile( '<tr><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td.+?>(.*?)</td><td>(.*?)</td><td.+?>(.*?)</td><td.+?>(.*?)</td><td.+?>(.*?)</td></tr>', re.S) items = re.findall(pattern, response.body.decode()) if items is not None: for item in items: ...
39
403
229
632
# coding=utf-8 import re from proxy import Proxy from .basespider import BaseSpider class UsProxySpider(BaseSpider): name = 'usproxy' def __init__(self, *a, **kwargs): super(UsProxySpider, self).__init__(*a, **kwargs) self.urls = [ 'http://www.sslproxies.org/', 'htt...
# coding=utf-8 import re from proxy import Proxy from .basespider import BaseSpider class UsProxySpider(BaseSpider): name = 'usproxy' def __init__(self, *a, **kwargs): super(UsProxySpider, self).__init__(*a, **kwargs) self.urls = [ 'http://www.sslproxies.org/', 'htt...
33,049
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/proxy/xicidaili.py
29,30
8,49
parse_page
XiCiDaiLiSpider
30,49
30,49
class XiCiDaiLiSpider(BaseSpider): name = 'xici' def __init__(self, *a, **kw): super(XiCiDaiLiSpider, self).__init__(*a, **kw) self.urls = ['http://www.xicidaili.com/nn/%s' % n for n in range(1, 10)] self.headers = { 'Accept': 'text/html,application/xhtml+xml,application/xm...
class XiCiDaiLiSpider(BaseSpider): name = 'xici' def __init__(self, *a, **kw): super(XiCiDaiLiSpider, self).__init__(*a, **kw) self.urls = ['http://www.xicidaili.com/nn/%s' % n for n in range(1, 10)] self.headers = { 'Accept': 'text/html,application/xhtml+xml,application/xm...
sel = Selector(text = response.body) infos = sel.xpath('//tr[@class="odd"]').extract() for info in infos: val = Selector(text = info) ip = val.xpath('//td[2]/text()').extract_first() port = val.xpath('//td[3]/text()').extract_first() country = val....
sel = Selector(text = response.body) infos = sel.xpath('//tr[@class="odd"]').extract() for info in infos: val = Selector(text = info) ip = val.xpath('//td[2]/text()').extract_first() port = val.xpath('//td[3]/text()').extract_first() country = val....
52
364
238
602
#-*- coding: utf-8 -*- from proxy import Proxy from .basespider import BaseSpider from scrapy.selector import Selector class XiCiDaiLiSpider(BaseSpider): name = 'xici' def __init__(self, *a, **kw): super(XiCiDaiLiSpider, self).__init__(*a, **kw) self.urls = ['http://www.xicidaili.com/nn/%s'...
#-*- coding: utf-8 -*- from proxy import Proxy from .basespider import BaseSpider from scrapy.selector import Selector class XiCiDaiLiSpider(BaseSpider): name = 'xici' def __init__(self, *a, **kw): super(XiCiDaiLiSpider, self).__init__(*a, **kw) self.urls = ['http://www.xicidaili.com/nn/%s'...
33,050
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/amazoncn.py
33,34
6,41
success_content_parse
AmazonCnSpider
34,41
34,41
class AmazonCnSpider(Validator): name = 'amazoncn' def __init__(self, name = None, **kwargs): super(AmazonCnSpider, self).__init__(name, **kwargs) self.timeout = 5 self.urls = [ 'https://www.amazon.cn/dp/B00ID363S4', 'https://www.amazon.cn/gp/product/B01BDBJ71W...
class AmazonCnSpider(Validator): name = 'amazoncn' def __init__(self, name = None, **kwargs): super(AmazonCnSpider, self).__init__(name, **kwargs) self.timeout = 5 self.urls = [ 'https://www.amazon.cn/dp/B00ID363S4', 'https://www.amazon.cn/gp/product/B01BDBJ71W...
if 'Amazon CAPTCHA' in response.text: return False return True
if 'Amazon CAPTCHA' in response.text: return False return True
9
361
39
400
#-*- coding: utf-8 -*- from .validator import Validator class AmazonCnSpider(Validator): name = 'amazoncn' def __init__(self, name = None, **kwargs): super(AmazonCnSpider, self).__init__(name, **kwargs) self.timeout = 5 self.urls = [ 'https://www.amazon.cn/dp/B00ID363S4...
#-*- coding: utf-8 -*- from .validator import Validator class AmazonCnSpider(Validator): name = 'amazoncn' def __init__(self, name = None, **kwargs): super(AmazonCnSpider, self).__init__(name, **kwargs) self.timeout = 5 self.urls = [ 'https://www.amazon.cn/dp/B00ID363S4...
33,052
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/assetstore.py
21,22
11,95
start_requests
AssetStoreSpider
22,46
22,46
class AssetStoreSpider(Validator): name = 'assetstore' def __init__(self, *a, **kwargs): super(AssetStoreSpider, self).__init__(*a, **kwargs) self.timeout = 10 self.init() def start_requests(self): FILL_FUNC_BODY def get_unity_version(self, response): content = json.lo...
class AssetStoreSpider(Validator): name = 'assetstore' def __init__(self, *a, **kwargs): super(AssetStoreSpider, self).__init__(*a, **kwargs) self.timeout = 10 self.init() def start_requests(self): FILL_FUNC_BODY def get_unity_version(self, response): content = json.lo...
url = 'https://www.assetstore.unity3d.com/login' yield Request( url = url, headers = { 'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3...
url = 'https://www.assetstore.unity3d.com/login' yield Request( url = url, headers = { 'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3...
61
767
394
1,161
#-*- coding: utf-8 -*- import json import time import config from scrapy.http import Request from .validator import Validator class AssetStoreSpider(Validator): name = 'assetstore' def __init__(self, *a, **kwargs): super(AssetStoreSpider, self).__init__(*a, **kwargs) self.timeout = 10 ...
#-*- coding: utf-8 -*- import json import time import config from scrapy.http import Request from .validator import Validator class AssetStoreSpider(Validator): name = 'assetstore' def __init__(self, *a, **kwargs): super(AssetStoreSpider, self).__init__(*a, **kwargs) self.timeout = 10 ...
33,053
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/bbs.py
35,36
6,39
success_content_parse
BBSSpider
36,39
36,39
class BBSSpider(Validator): name = 'bbs' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BBSSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.autohome.com.cn/beijing/', 'http://club.autohome.com.cn/bbs/thread-c-2098-64053713-1...
class BBSSpider(Validator): name = 'bbs' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BBSSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.autohome.com.cn/beijing/', 'http://club.autohome.com.cn/bbs/thread-c-2098-64053713-1...
if 'conmain' in response.text: return True return False
if 'conmain' in response.text: return True return False
8
607
23
630
# -*- coding: utf-8 -*- from .validator import Validator class BBSSpider(Validator): name = 'bbs' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BBSSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.autohome.com.cn/beijing/', ...
# -*- coding: utf-8 -*- from .validator import Validator class BBSSpider(Validator): name = 'bbs' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BBSSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.autohome.com.cn/beijing/', ...
33,054
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/boss.py
31,32
6,35
success_content_parse
BossSpider
32,35
32,35
class BossSpider(Validator): name = 'boss' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BossSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.zhipin.com/c101010100/h_101010100/?query=java&page=1&ka=page-1' ] self.head...
class BossSpider(Validator): name = 'boss' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BossSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.zhipin.com/c101010100/h_101010100/?query=java&page=1&ka=page-1' ] self.head...
if '<!DOCTYPE html>' in response.text: return True return False
if '<!DOCTYPE html>' in response.text: return True return False
9
358
25
383
#-*- coding: utf-8 -*- from .validator import Validator class BossSpider(Validator): name = 'boss' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BossSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.zhipin.com/c101010100/h_101010100...
#-*- coding: utf-8 -*- from .validator import Validator class BossSpider(Validator): name = 'boss' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(BossSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.zhipin.com/c101010100/h_101010100...
33,055
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/httpbin.py
120,121
12,133
error_parse
HttpBinSpider
121,133
121,133
class HttpBinSpider(Validator): name = 'httpbin' concurrent_requests = 16 def __init__(self, name=None, **kwargs): super(HttpBinSpider, self).__init__(name, **kwargs) self.timeout = 20 self.urls = [ 'http://httpbin.org/get?show_env=1', 'https://httpbin.org/ge...
class HttpBinSpider(Validator): name = 'httpbin' concurrent_requests = 16 def __init__(self, name=None, **kwargs): super(HttpBinSpider, self).__init__(name, **kwargs) self.timeout = 20 self.urls = [ 'http://httpbin.org/get?show_env=1', 'https://httpbin.org/ge...
request = failure.request self.log('error_parse value:%s url:%s meta:%s' % (failure.value, request.url, request.meta)) https = request.meta.get('https') if https == 'no': table = request.meta.get('table') proxy = request.meta.get('proxy_info') if tabl...
request = failure.request self.log('error_parse value:%s url:%s meta:%s' % (failure.value, request.url, request.meta)) https = request.meta.get('https') if https == 'no': table = request.meta.get('table') proxy = request.meta.get('proxy_info') if tabl...
37
1,242
166
1,408
# -*- coding: utf-8 -*- import json import time import requests import config from scrapy import Request from .validator import Validator class HttpBinSpider(Validator): name = 'httpbin' concurrent_requests = 16 def __init__(self, name=None, **kwargs): super(HttpBinSpider, self).__init__(name, ...
# -*- coding: utf-8 -*- import json import time import requests import config from scrapy import Request from .validator import Validator class HttpBinSpider(Validator): name = 'httpbin' concurrent_requests = 16 def __init__(self, name=None, **kwargs): super(HttpBinSpider, self).__init__(name, ...
33,056
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/jd.py
52,53
12,126
start_requests
JDSpider
53,88
53,88
class JDSpider(Validator): name = 'jd' def __init__(self, name = None, **kwargs): super(JDSpider, self).__init__(name, **kwargs) self.urls = [ 'https://item.jd.com/11478178241.html', 'https://item.jd.com/4142680.html', 'https://item.jd.com/3133859.html', ...
class JDSpider(Validator): name = 'jd' def __init__(self, name = None, **kwargs): super(JDSpider, self).__init__(name, **kwargs) self.urls = [ 'https://item.jd.com/11478178241.html', 'https://item.jd.com/4142680.html', 'https://item.jd.com/3133859.html', ...
count = self.sql.get_proxy_count(self.name) count_httpbin = self.sql.get_proxy_count(config.httpbin_table) ids = self.sql.get_proxy_ids(self.name) ids_httpbin = self.sql.get_proxy_ids(config.httpbin_table) for i in range(0, count + count_httpbin): table = self.name ...
count = self.sql.get_proxy_count(self.name) count_httpbin = self.sql.get_proxy_count(config.httpbin_table) ids = self.sql.get_proxy_ids(self.name) ids_httpbin = self.sql.get_proxy_ids(config.httpbin_table) for i in range(0, count + count_httpbin): table = self.name ...
99
1,160
408
1,568
#-*- coding: utf-8 -*- import random import time import re import config from scrapy import Request from .validator import Validator class JDSpider(Validator): name = 'jd' def __init__(self, name = None, **kwargs): super(JDSpider, self).__init__(name, **kwargs) self.urls = [ 'h...
#-*- coding: utf-8 -*- import random import time import re import config from scrapy import Request from .validator import Validator class JDSpider(Validator): name = 'jd' def __init__(self, name = None, **kwargs): super(JDSpider, self).__init__(name, **kwargs) self.urls = [ 'h...
33,057
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/lagou.py
41,42
11,93
start_requests
LagouSpider
42,93
42,93
class LagouSpider(Validator): name = 'lagou' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LagouSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false' ...
class LagouSpider(Validator): name = 'lagou' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LagouSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false' ...
count = self.sql.get_proxy_count(self.name) count_httpbin = self.sql.get_proxy_count(config.httpbin_table) ids = self.sql.get_proxy_ids(self.name) ids_httpbin = self.sql.get_proxy_ids(config.httpbin_table) for i in range(0, count + count_httpbin): table = self.name ...
count = self.sql.get_proxy_count(self.name) count_httpbin = self.sql.get_proxy_count(config.httpbin_table) ids = self.sql.get_proxy_ids(self.name) ids_httpbin = self.sql.get_proxy_ids(config.httpbin_table) for i in range(0, count + count_httpbin): table = self.name ...
133
387
959
1,346
#-*- coding: utf-8 -*- import time import config import utils from .validator import Validator from scrapy.http import FormRequest class LagouSpider(Validator): name = 'lagou' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LagouSpider, self).__init__(name, **kwargs) ...
#-*- coding: utf-8 -*- import time import config import utils from .validator import Validator from scrapy.http import FormRequest class LagouSpider(Validator): name = 'lagou' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LagouSpider, self).__init__(name, **kwargs) ...
33,058
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/liepin.py
33,34
6,38
success_content_parse
LiepinSpider
34,38
34,38
class LiepinSpider(Validator): name = 'liepin' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LiepinSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.liepin.com/zhaopin/?pubTime=&ckid=17c370b0a0111aa5&fromSearchBtn=2&compkind' \ ...
class LiepinSpider(Validator): name = 'liepin' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LiepinSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.liepin.com/zhaopin/?pubTime=&ckid=17c370b0a0111aa5&fromSearchBtn=2&compkind' \ ...
if 'sojob-list' in response.text: return True return False
if 'sojob-list' in response.text: return True return False
8
469
27
496
#-*- coding: utf-8 -*- from .validator import Validator class LiepinSpider(Validator): name = 'liepin' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LiepinSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.liepin.com/zhaopin/?pubTime...
#-*- coding: utf-8 -*- from .validator import Validator class LiepinSpider(Validator): name = 'liepin' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(LiepinSpider, self).__init__(name, **kwargs) self.urls = [ 'https://www.liepin.com/zhaopin/?pubTime...
33,059
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/crawler/spiders/validator/zhilian.py
30,31
6,34
success_content_parse
ZhiLianSpider
31,34
31,34
class ZhiLianSpider(Validator): name = 'zhilian' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(ZhiLianSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.zhaopin.com/' ] self.headers = { # 'Accept': 'text/html...
class ZhiLianSpider(Validator): name = 'zhilian' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(ZhiLianSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.zhaopin.com/' ] self.headers = { # 'Accept': 'text/html...
if '<!DOCTYPE html>' in response.text: return True return False
if '<!DOCTYPE html>' in response.text: return True return False
9
339
26
365
#-*- coding: utf-8 -*- from .validator import Validator class ZhiLianSpider(Validator): name = 'zhilian' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(ZhiLianSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.zhaopin.com/' ] ...
#-*- coding: utf-8 -*- from .validator import Validator class ZhiLianSpider(Validator): name = 'zhilian' concurrent_requests = 8 def __init__(self, name = None, **kwargs): super(ZhiLianSpider, self).__init__(name, **kwargs) self.urls = [ 'http://www.zhaopin.com/' ] ...
33,060
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/proxy.py
44,45
4,86
get_dict
Proxy
45,58
45,58
class Proxy(object): def __init__(self): self.id = 1 self.ip = '' self.port = '' self.country = '' self.anonymity = '' self.https = '' self.speed = '' self.source = '' self.vali_count = 0 def __str__(self): data = { 'ip...
class Proxy(object): def __init__(self): self.id = 1 self.ip = '' self.port = '' self.country = '' self.anonymity = '' self.https = '' self.speed = '' self.source = '' self.vali_count = 0 def __str__(self): data = { 'ip...
data = { 'ip': self.ip, 'port': self.port, 'country': self.country, 'anonymity': self.anonymity, 'https': self.https, 'speed': self.speed, 'source': self.source, 'vali_count': self.vali_count, } retu...
data = { 'ip': self.ip, 'port': self.port, 'country': self.country, 'anonymity': self.anonymity, 'https': self.https, 'speed': self.speed, 'source': self.source, 'vali_count': self.vali_count, } retu...
22
734
109
843
# -*- coding: utf-8 -*- class Proxy(object): def __init__(self): self.id = 1 self.ip = '' self.port = '' self.country = '' self.anonymity = '' self.https = '' self.speed = '' self.source = '' self.vali_count = 0 def __str__(self): ...
# -*- coding: utf-8 -*- class Proxy(object): def __init__(self): self.id = 1 self.ip = '' self.port = '' self.country = '' self.anonymity = '' self.https = '' self.speed = '' self.source = '' self.vali_count = 0 def __str__(self): ...
33,061
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/run_spider.py
12,13
1,36
runspider
13,30
13,30
# -*- coding: utf-8 -*- import os import logging import sys from scrapy.crawler import CrawlerProcess from scrapy.utils.log import configure_logging from scrapy.utils.project import get_project_settings def runspider(name): FILL_FUNC_BODYif __name__ == '__main__': try: name = sys.argv[1] or 'base' ...
# -*- coding: utf-8 -*- import os import logging import sys from scrapy.crawler import CrawlerProcess from scrapy.utils.log import configure_logging from scrapy.utils.project import get_project_settings def runspider(name): FILL_FUNC_BODYif __name__ == '__main__': try: name = sys.argv[1] or 'base' ...
configure_logging(install_root_handler=False) logging.basicConfig( filename='log/%s.log' % name, format='%(levelname)s %(asctime)s: %(message)s', level=logging.DEBUG ) process = CrawlerProcess(get_project_settings()) try: logging.info('runspider start spider:%s' % nam...
configure_logging(install_root_handler=False) logging.basicConfig( filename='log/%s.log' % name, format='%(levelname)s %(asctime)s: %(message)s', level=logging.DEBUG ) process = CrawlerProcess(get_project_settings()) try: logging.info('runspider start spider:%s' % nam...
36
148
199
347
# -*- coding: utf-8 -*- import os import logging import sys from scrapy.crawler import CrawlerProcess from scrapy.utils.log import configure_logging from scrapy.utils.project import get_project_settings def runspider(name): FILL_FUNC_BODYif __name__ == '__main__': try: name = sys.argv[1] or 'base' ...
# -*- coding: utf-8 -*- import os import logging import sys from scrapy.crawler import CrawlerProcess from scrapy.utils.log import configure_logging from scrapy.utils.project import get_project_settings def runspider(name): FILL_FUNC_BODYif __name__ == '__main__': try: name = sys.argv[1] or 'base' ...
33,062
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/run_validator.py
31,32
1,77
validator
32,64
32,64
# -*- coding: utf-8 -*- import logging import os import subprocess import sys import time import scrapydo import utils from importlib import import_module VALIDATORS = { 'HttpBinSpider': 'crawler.spiders.validator.httpbin', # 'DoubanSpider':'ipproxytool.spiders.validator.douban', # 'AssetStoreSpider':'ipp...
# -*- coding: utf-8 -*- import logging import os import subprocess import sys import time import scrapydo import utils from importlib import import_module VALIDATORS = { 'HttpBinSpider': 'crawler.spiders.validator.httpbin', # 'DoubanSpider':'ipproxytool.spiders.validator.douban', # 'AssetStoreSpider':'ipp...
process_list = [] for item, path in VALIDATORS.items(): module = import_module(path) validator = getattr(module, item) popen = subprocess.Popen(['python', 'run_spider.py', validator.name], shell=False) data = { 'name': validator.name, 'popen': popen, ...
process_list = [] for item, path in VALIDATORS.items(): module = import_module(path) validator = getattr(module, item) popen = subprocess.Popen(['python', 'run_spider.py', validator.name], shell=False) data = { 'name': validator.name, 'popen': popen, ...
83
504
364
868
# -*- coding: utf-8 -*- import logging import os import subprocess import sys import time import scrapydo import utils from importlib import import_module VALIDATORS = { 'HttpBinSpider': 'crawler.spiders.validator.httpbin', # 'DoubanSpider':'ipproxytool.spiders.validator.douban', # 'AssetStoreSpider':'ipp...
# -*- coding: utf-8 -*- import logging import os import subprocess import sys import time import scrapydo import utils from importlib import import_module VALIDATORS = { 'HttpBinSpider': 'crawler.spiders.validator.httpbin', # 'DoubanSpider':'ipproxytool.spiders.validator.douban', # 'AssetStoreSpider':'ipp...
33,063
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/run_validator_async.py
42,43
1,84
async_validator
43,72
43,72
# -*- coding: utf-8 -*- import logging import os import sys import time import utils import aiohttp from aiohttp import ClientSession from sql.sql_manager import SqlManager import config import asyncio TEST_URL='http://httpbin.org/ip' async def test_connect(proxy,operator,mode=None): conn = aiohttp.TCPConnector(...
# -*- coding: utf-8 -*- import logging import os import sys import time import utils import aiohttp from aiohttp import ClientSession from sql.sql_manager import SqlManager import config import asyncio TEST_URL='http://httpbin.org/ip' async def test_connect(proxy,operator,mode=None): conn = aiohttp.TCPConnector(...
utils.log('[INFO]#Loading ip proxies....60 sec left') time.sleep(60) proxy_factory = SqlManager() loop = asyncio.get_event_loop() def test_process(table_name,mode=None,limit=50): id_list = proxy_factory.get_proxy_ids(table_name) if len(id_list) > 0: task_len = len(id_lis...
utils.log('[INFO]#Loading ip proxies....60 sec left') time.sleep(60) proxy_factory = SqlManager() loop = asyncio.get_event_loop() def test_process(table_name,mode=None,limit=50): id_list = proxy_factory.get_proxy_ids(table_name) if len(id_list) > 0: task_len = len(id_lis...
78
566
436
1,002
# -*- coding: utf-8 -*- import logging import os import sys import time import utils import aiohttp from aiohttp import ClientSession from sql.sql_manager import SqlManager import config import asyncio TEST_URL='http://httpbin.org/ip' async def test_connect(proxy,operator,mode=None): conn = aiohttp.TCPConnector(...
# -*- coding: utf-8 -*- import logging import os import sys import time import utils import aiohttp from aiohttp import ClientSession from sql.sql_manager import SqlManager import config import asyncio TEST_URL='http://httpbin.org/ip' async def test_connect(proxy,operator,mode=None): conn = aiohttp.TCPConnector(...
33,064
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/server/dataserver.py
70,72
1,92
delete
72,80
72,80
# -*- coding: utf-8 -*- import json import logging import sys import config from proxy import Proxy from sql import SqlManager from flask import Flask from flask import request app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!' @app.route('/insert') def insert(): sql = SqlManager()...
# -*- coding: utf-8 -*- import json import logging import sys import config from proxy import Proxy from sql import SqlManager from flask import Flask from flask import request app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!' @app.route('/insert') def insert(): sql = SqlManager()...
sql = SqlManager() name = request.args.get('name') ip = request.args.get('ip') result = sql.del_proxy_with_ip(name, ip) data = {'result': result} return json.dumps(data, indent=4)
sql = SqlManager() name = request.args.get('name') ip = request.args.get('ip') result = sql.del_proxy_with_ip(name, ip) data = {'result': result} return json.dumps(data, indent=4)
20
725
83
808
# -*- coding: utf-8 -*- import json import logging import sys import config from proxy import Proxy from sql import SqlManager from flask import Flask from flask import request app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!' @app.route('/insert') def insert(): sql = SqlManager()...
# -*- coding: utf-8 -*- import json import logging import sys import config from proxy import Proxy from sql import SqlManager from flask import Flask from flask import request app = Flask(__name__) @app.route('/') def index(): return 'Hello, World!' @app.route('/insert') def insert(): sql = SqlManager()...
33,065
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/sql/mongodb.py
55,56
13,92
get_proxy_count
Mongodb
56,60
56,60
class Mongodb(SqlBase): def __init__(self, **kwargs): super(Mongodb, self).__init__(**kwargs) self.client = pymongo.MongoClient(**kwargs) self.db = self.client[config.database] def init_database(self, database_name): pass def init_proxy_table(self, table_name): pass...
class Mongodb(SqlBase): def __init__(self, **kwargs): super(Mongodb, self).__init__(**kwargs) self.client = pymongo.MongoClient(**kwargs) self.db = self.client[config.database] def init_database(self, database_name): pass def init_proxy_table(self, table_name): pass...
count = self.db[table_name].find().count() logging.debug('count:%s' % count) return count
count = self.db[table_name].find().count() logging.debug('count:%s' % count) return count
8
812
39
851
# -*- coding: utf-8 -*- import logging import pymongo import config import json import datetime from proxy import Proxy from sql.sql_base import SqlBase class Mongodb(SqlBase): def __init__(self, **kwargs): super(Mongodb, self).__init__(**kwargs) self.client = pymongo.MongoClient(**kwargs) ...
# -*- coding: utf-8 -*- import logging import pymongo import config import json import datetime from proxy import Proxy from sql.sql_base import SqlBase class Mongodb(SqlBase): def __init__(self, **kwargs): super(Mongodb, self).__init__(**kwargs) self.client = pymongo.MongoClient(**kwargs) ...
33,067
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/sql/sql_manager.py
63,64
8,74
del_proxy_with_id
SqlManager
64,66
64,66
class SqlManager(object): def __init__(self): db_type = config.DB_config.get('db_type', 'mysql') db_config = config.DB_config.get(db_type) if db_type == 'mysql': from sql.mysql import MySql self.sql = MySql(**db_config) elif db_type == 'redis': pa...
class SqlManager(object): def __init__(self): db_type = config.DB_config.get('db_type', 'mysql') db_config = config.DB_config.get(db_type) if db_type == 'mysql': from sql.mysql import MySql self.sql = MySql(**db_config) elif db_type == 'redis': pa...
return self.sql.del_proxy_with_id(table_name = table_name, id = id)
return self.sql.del_proxy_with_id(table_name = table_name, id = id)
7
753
30
783
# -*- coding: utf-8 -*- import config from sql.sql_base import SqlBase class SqlManager(object): def __init__(self): db_type = config.DB_config.get('db_type', 'mysql') db_config = config.DB_config.get(db_type) if db_type == 'mysql': from sql.mysql import MySql se...
# -*- coding: utf-8 -*- import config from sql.sql_base import SqlBase class SqlManager(object): def __init__(self): db_type = config.DB_config.get('db_type', 'mysql') db_config = config.DB_config.get(db_type) if db_type == 'mysql': from sql.mysql import MySql se...
33,068
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool
/home/hieuvd/dung_repo/raw/stars_02/awolfly9_IPProxyTool/IPProxyTool/utils.py
26,27
1,58
kill_ports
27,54
27,54
# -*- coding: utf-8 -*- import logging import os import re import subprocess import traceback import time import datetime # 自定义的日志输出 def log(msg, level=logging.DEBUG): logging.log(level, msg) print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg)) if level == loggi...
# -*- coding: utf-8 -*- import logging import os import re import subprocess import traceback import time import datetime # 自定义的日志输出 def log(msg, level=logging.DEBUG): logging.log(level, msg) print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg)) if level == loggi...
for port in ports: log('kill %s start' % port) popen = subprocess.Popen('lsof -i:%s' % port, shell=True, stdout=subprocess.PIPE) (data, err) = popen.communicate() log('data:\n%s \nerr:\n%s' % (data, err)) pattern = re.compile(r'\b\d+\b', re.S) pids = re.findall(patt...
for port in ports: log('kill %s start' % port) popen = subprocess.Popen('lsof -i:%s' % port, shell=True, stdout=subprocess.PIPE) (data, err) = popen.communicate() log('data:\n%s \nerr:\n%s' % (data, err)) pattern = re.compile(r'\b\d+\b', re.S) pids = re.findall(patt...
87
255
336
591
# -*- coding: utf-8 -*- import logging import os import re import subprocess import traceback import time import datetime # 自定义的日志输出 def log(msg, level=logging.DEBUG): logging.log(level, msg) print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg)) if level == loggi...
# -*- coding: utf-8 -*- import logging import os import re import subprocess import traceback import time import datetime # 自定义的日志输出 def log(msg, level=logging.DEBUG): logging.log(level, msg) print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg)) if level == loggi...
33,069
/home/hieuvd/dung_repo/raw/stars_02/baidu_Senta/Senta
/home/hieuvd/dung_repo/raw/stars_02/baidu_Senta/Senta/infer.py
16,17
1,68
dataset_reader_from_params
21,27
17,27
# -*- coding: utf-8 -* """import""" import os import sys from senta.inference.inference import Inference from senta.common.register import RegisterSet from senta.common import register from senta.data.data_set import DataSet import logging from senta.utils import args from senta.utils import params from senta.utils im...
# -*- coding: utf-8 -* """import""" import os import sys from senta.inference.inference import Inference from senta.common.register import RegisterSet from senta.common import register from senta.data.data_set import DataSet import logging from senta.utils import args from senta.utils import params from senta.utils im...
dataset_reader = DataSet(params_dict) dataset_reader.build() return dataset_reader
""" :param params_dict: :return: """ dataset_reader = DataSet(params_dict) dataset_reader.build() return dataset_reader
6
516
36
552
# -*- coding: utf-8 -* """import""" import os import sys from senta.inference.inference import Inference from senta.common.register import RegisterSet from senta.common import register from senta.data.data_set import DataSet import logging from senta.utils import args from senta.utils import params from senta.utils im...
# -*- coding: utf-8 -* """import""" import os import sys from senta.inference.inference import Inference from senta.common.register import RegisterSet from senta.common import register from senta.data.data_set import DataSet import logging from senta.utils import args from senta.utils import params from senta.utils im...
33,070
/home/hieuvd/dung_repo/raw/stars_02/baidu_Senta/Senta
/home/hieuvd/dung_repo/raw/stars_02/baidu_Senta/Senta/lanch.py
39,40
1,131
start_procs
41,119
40,119
"""lanch.py""" import argparse import copy import logging import os import subprocess import sys from senta.utils.args import ArgumentGroup, print_arguments from senta.utils import log # yapf: disable parser = argparse.ArgumentParser(__doc__) multip_g = ArgumentGroup(parser, "multiprocessing", "start paddle ...
"""lanch.py""" import argparse import copy import logging import os import subprocess import sys from senta.utils.args import ArgumentGroup, print_arguments from senta.utils import log # yapf: disable parser = argparse.ArgumentParser(__doc__) multip_g = ArgumentGroup(parser, "multiprocessing", "start paddle ...
procs = [] log_fns = [] default_env = os.environ.copy() node_id = args.node_id node_ips = [x.strip() for x in args.node_ips.split(',')] current_ip = args.current_node_ip num_nodes = len(node_ips) selected_gpus = [x.strip() for x in args.selected_gpus.split(',')] selected_gpu_num = ...
"""start process""" procs = [] log_fns = [] default_env = os.environ.copy() node_id = args.node_id node_ips = [x.strip() for x in args.node_ips.split(',')] current_ip = args.current_node_ip num_nodes = len(node_ips) selected_gpus = [x.strip() for x in args.selected_gpus.split(',')]...
248
608
1,176
1,784
"""lanch.py""" import argparse import copy import logging import os import subprocess import sys from senta.utils.args import ArgumentGroup, print_arguments from senta.utils import log # yapf: disable parser = argparse.ArgumentParser(__doc__) multip_g = ArgumentGroup(parser, "multiprocessing", "start paddle ...
"""lanch.py""" import argparse import copy import logging import os import subprocess import sys from senta.utils.args import ArgumentGroup, print_arguments from senta.utils import log # yapf: disable parser = argparse.ArgumentParser(__doc__) multip_g = ArgumentGroup(parser, "multiprocessing", "start paddle ...