code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Prepare build type if platform is None: platform = Platform() target_platform = platform.gecko_platform is_namespace = False if cls.RE_DATE.match(build): task_urls = map(''.join, itertools.product(cls._pushdate_urls(...
def iterall(cls, build, branch, flags, platform=None)
Generator for all possible BuildTasks with these parameters
5.18319
5.160498
1.004397
url_base = cls.URL_BASE + '/namespaces/gecko.v2.mozilla-' + branch + '.pushdate.' + pushdate try: base = HTTP_SESSION.post(url_base, json={}) base.raise_for_status() except requests.exceptions.RequestException as exc: raise FetcherException(exc) ...
def _pushdate_urls(cls, pushdate, branch, target_platform)
Multiple entries exist per push date. Iterate over all until a working entry is found
5.509856
5.413981
1.017709
namespace = 'gecko.v2.mozilla-' + branch + '.revision.' + rev product = 'mobile' if 'android' in target_platform else 'firefox' return cls.URL_BASE + '/task/' + namespace + '.' + product + '.' + target_platform
def _revision_url(cls, rev, branch, target_platform)
Retrieve the URL for revision based builds
10.234418
9.69662
1.055462
flags = BuildFlags(*flags) for task in BuildTask.iterall(build, branch, flags, platform): yield cls(target, branch, task, flags, platform)
def iterall(cls, target, branch, build, flags, platform=None)
Return an iterable for all available builds matching a particular build type
5.021327
5.497277
0.913421
if '_artifacts' not in self._memo: json = _get_url(self._artifacts_url).json() self._memo['_artifacts'] = json['artifacts'] return self._memo['_artifacts']
def _artifacts(self)
Retrieve the artifacts json object
4.640844
3.764942
1.232647
if '_artifact_base' not in self._memo: for artifact in self._artifacts: if self.re_target.search(artifact['name']) is not None: artifact_base = os.path.splitext(artifact['name'])[0] break else: raise Fetcher...
def _artifact_base(self)
Build the artifact basename Builds are base.tar.bz2, info is base.json, shell is base.jsshell.zip...
3.827936
3.565206
1.073693
if 'build_info' not in self._memo: self._memo['build_info'] = _get_url(self.artifact_url('json')).json() return self._memo['build_info']
def build_info(self)
Return the build's info
5.335839
4.703879
1.134349
if 'moz_info' not in self._memo: self._memo['moz_info'] = _get_url(self.artifact_url('mozinfo.json')).json() return self._memo['moz_info']
def moz_info(self)
Return the build's mozinfo
4.436042
4.427849
1.00185
if self._target == 'js': self.extract_zip('jsshell.zip', path=os.path.join(path)) else: if self._platform.system == 'Linux': self.extract_tar('tar.bz2', path) elif self._platform.system == 'Darwin': self.extract_dmg(path) ...
def extract_build(self, path='.', tests=None, full_symbols=False)
Download and extract the build and requested extra artifacts @type path: @param path: @type tests: @param tests: @type full_symbols: @param full_symbols:
2.45464
2.478691
0.990297
old_dir = os.getcwd() os.chdir(os.path.join(path)) try: os.mkdir('dist') link_name = os.path.join('dist', 'bin') if self._platform.system == 'Darwin' and self._target == 'firefox': ff_loc = glob.glob('*.app/Contents/MacOS/firefox') ...
def _layout_for_domfuzz(self, path)
Update directory to work with DOMFuzz @type path: str @param path: A string representation of the fuzzmanager config path
2.970387
3.020174
0.983515
output = configparser.RawConfigParser() output.add_section('Main') output.set('Main', 'platform', self.moz_info['processor'].replace('_', '-')) output.set('Main', 'product', 'mozilla-' + self._branch) output.set('Main', 'product_version', '%.8s-%.12s' % (self.build_id, s...
def _write_fuzzmanagerconf(self, path)
Write fuzzmanager config file for selected build @type path: basestring @param path: A string representation of the fuzzmanager config path
2.957957
3.006968
0.983701
zip_fd, zip_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.zip') os.close(zip_fd) try: _download_url(self.artifact_url(suffix), zip_fn) LOG.info('.. extracting') with zipfile.ZipFile(zip_fn) as zip_fp: for info in zip_fp.infolist(...
def extract_zip(self, suffix, path='.')
Download and extract a zip artifact @type suffix: @param suffix: @type path: @param path:
3.223388
3.4723
0.928315
mode = suffix.split('.')[-1] tar_fd, tar_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.tar.%s' % mode) os.close(tar_fd) try: _download_url(self.artifact_url(suffix), tar_fn) LOG.info('.. extracting') with tarfile.open(tar_fn, mode='r:%s'...
def extract_tar(self, suffix, path='.')
Extract builds with .tar.(*) extension When unpacking a build archive, only extract the firefox directory @type suffix: @param suffix: @type path: @param path:
3.127978
3.26696
0.957458
apk_fd, apk_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.apk') os.close(apk_fd) try: _download_url(self.artifact_url('apk'), apk_fn) shutil.copy(apk_fn, os.path.join(path, 'target.apk')) finally: os.unlink(apk_fn)
def download_apk(self, path='.')
Download Android .apk @type path: @param path:
3.286765
3.823836
0.859547
dmg_fd, dmg_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.dmg') os.close(dmg_fd) out_tmp = tempfile.mkdtemp(prefix='fuzzfetch-', suffix='.tmp') try: _download_url(self.artifact_url('dmg'), dmg_fn) if std_platform.system() == 'Darwin': ...
def extract_dmg(self, path='.')
Extract builds with .dmg extension Will only work if `hdiutil` is available. @type path: @param path:
2.717948
2.862396
0.949536
log_level = logging.INFO log_fmt = '[%(asctime)s] %(message)s' if bool(os.getenv('DEBUG')): log_level = logging.DEBUG log_fmt = '%(levelname).1s %(name)s [%(asctime)s] %(message)s' logging.basicConfig(format=log_fmt, datefmt='%Y-%m-%d %H:%M:%S', level=log...
def main(cls)
fuzzfetch main entry point Run with --help for usage
3.115448
3.095746
1.006364
if 'json' in self.request: self.request['data'] = json.dumps(self.request.pop('json')).encode( self.encoding) r1 = self.req.request( retry=self.retry, timeout=self.timeout, **self.request) resp = r1.x assert resp, ValueError( '...
def init_original_response(self)
Get the original response for comparing, confirm ``is_cookie_necessary``
4.63892
4.498774
1.031152
no_cookie_resp = None self.is_cookie_necessary = True if 'json' in self.request: self.request['data'] = json.dumps(self.request.pop('json')).encode( self.encoding) r1 = self.req.request( retry=self.retry, timeout=self.timeout, **self.reque...
def init_original_response(self)
Get the original response for comparing, confirm is_cookie_necessary
3.49692
3.160436
1.106467
parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) return cls._join_url(parsed_url, sorted(qsl, **kwargs))
def sort_url_qsl(cls, raw_url, **kwargs)
Do nothing but sort the params of url. raw_url: the raw url to be sorted; kwargs: (optional) same kwargs for ``sorted``.
3.096795
3.375432
0.917451
raw_url = self.request['url'] parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) for qs in qsl: new_url = self._join_url(parsed_url, [i for i in qsl if i is not qs]) new_request = deepcopy(self.request) ...
def clean_url(self)
Only clean the url params and return self.
3.875043
3.538228
1.095193
data = self.request.get('data') if not (data and self.request['method'] == 'post'): return self # case of total_data new_request = deepcopy(self.request) new_request.pop('data') self._add_task('total_data', data, new_request) # case of form_d...
def clean_post_data(self)
Only clean the post-data and return self. Including form-data / bytes-data / json-data.
2.390336
2.218657
1.07738
if not self.is_cookie_necessary: return self headers = self.request.get('headers', {}) cookies = SimpleCookie(headers['Cookie']) for k, v in cookies.items(): new_cookie = '; '.join( [i.OutputString() for i in cookies.values() if i != v]) ...
def clean_cookie(self)
Only clean the cookie from headers and return self.
3.867903
3.485848
1.109602
if not isinstance(self.request.get('headers'), dict): return self headers = self.request['headers'] if 'Cookie' in headers: self.clean_cookie() for key in headers: # cookie will be checked in other methods. if key == 'Cookie': ...
def clean_headers(self)
Only clean the headers (cookie include) and return self.
3.561926
3.16948
1.12382
raw_url = self.new_request['url'] parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) new_url = self._join_url( parsed_url, [i for i in qsl if i not in self.ignore['qsl']]) self.new_request['url'] = new_url self.logger_function('ignore: %...
def reset_new_request(self)
Remove the non-sense args from the self.ignore, return self.new_request
2.598748
2.481313
1.047328
if not self.tasks: self.clean_all() tasks_length = len(self.tasks) self.logger_function( '%s tasks of request, will cost at least %s seconds.' % (tasks_length, round(self.req.interval / self.req.n * tasks_length, 2))) self.req.x ...
def result(self)
Whole task, clean_all + reset_new_request, return self.new_request.
11.094913
8.684017
1.277625
return json.dumps(self.as_dict, ensure_ascii=ensure_ascii)
def as_json(self, ensure_ascii=False)
Property return key-value json-string from __slots__.
3.331254
2.663154
1.250868
'''the main entry point for the HelpMe Command line application. Currently, the user can request help or set config values for a particular helper. ''' # Customize parser parser = get_parser() subparsers = get_subparsers(parser) def help(return_code=0): '''print help, including...
def main()
the main entry point for the HelpMe Command line application. Currently, the user can request help or set config values for a particular helper.
5.749902
4.426063
1.299101
val = self.get_or_none(key) if val is None: self.update(key, default_value) val = default_value return val
def get_or_save_default(self, key, default_value)
Get value stored in cache file or store there default value. :param key: :param default_value: :return:
3.012941
3.415916
0.88203
from . import datawriter as dwriter # import qmisc if not os.path.exists(output_dicom_dir): os.makedirs(output_dicom_dir) import imtools.image_manipulation # uncrop all overlays for key in overlays: overlays[key] = imtools.image_manipulation.uncrop(overlays[key], crinfo, o...
def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays, crinfo, orig_shape)
Save overlay to dicom.
4.128353
4.08058
1.011707
startpath, ext = os.path.splitext(path) segmentation_path = startpath + "_segmentation" + ext return segmentation_path
def __get_segmentation_path(self, path)
Create path with "_segmentation" suffix and keep extension. :param path: :return:
3.391704
3.443423
0.98498
self.orig_path = path path = os.path.expanduser(path) try: d3d = data3d.pop('data3d') metadata = data3d data3d = d3d except: pass if progress_callback is not None: self.progress_callback = progress_callback ...
def Write3DData(self, data3d, path, filetype='auto', metadata=None, progress_callback=None, sfin=True)
:param data3d: input ndarray data :param path: output path, to specify slice number advanced formatting options (like {:06d}) can be used Check function filename_format() for more details. :param metadata: {'voxelsize_mm': [1, 1, 1]} :param filetype: dcm, vtk, rawiv, image_stack ...
2.754673
2.567199
1.073027
ds = dicom.read_file(path) ds.SpacingBetweenSlices = str(metadata["voxelsize_mm"][0])[:16] dicom.write_file(path, ds)
def _fix_sitk_bug(self, path, metadata)
There is a bug in simple ITK for Z axis in 3D images. This is a fix :param path: :param metadata: :return:
4.881148
4.807014
1.015422
dcmlist = dcmfilelist # data3d = [] for i in range(len(dcmlist)): onefile = dcmlist[i] logger.info(onefile) data = dicom.read_file(onefile) for i_overlay in overlays.keys(): overlay3d = overlays[i_overlay] ...
def DataCopyWithOverlay(self, dcmfilelist, out_dir, overlays)
Function make 3D data from dicom file slices :dcmfilelist list of sorted .dcm files :overlays dictionary of binary overlays. {1:np.array([...]), 3:...} :out_dir output directory
3.855577
3.858063
0.999356
if filename_out is None: filename_out = filename filename = op.expanduser(filename) data = dicom.read_file(filename) data = self.encode_overlay_slice(data, overlay, i_overlay) data.save_as(filename_out)
def add_overlay_to_slice_file( self, filename, overlay, i_overlay, filename_out=None )
Function adds overlay to existing file.
3.115212
3.057243
1.018961
def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): message = 'Call to deprecated function {}. {}'.format(func.__name__, instructions) frame = inspect.currentframe().f_back ...
def deprecated(instructions)
Flags a method as deprecated. :param instructions: A human-friendly string of instructions, such as: 'Please migrate to add_proxy() ASAP.' :return: DeprecatedWarning
2.059962
2.080348
0.990201
if self.get_verbosity() >= Output.VERBOSITY_VERBOSE: self.writeln(message)
def log_verbose(self, message)
Logs a message only when logging level is verbose. :param str|list[str] message: The message.
5.665097
8.440578
0.671174
if self.get_verbosity() >= Output.VERBOSITY_VERY_VERBOSE: self.writeln(message)
def log_very_verbose(self, message)
Logs a message only when logging level is very verbose. :param str|list[str] message: The message.
5.016651
6.895633
0.727511
LOGGER.debug("++WAIT: cache get feed %s", url) previous = config.cache.get( 'feed', url, schema_version=SCHEMA_VERSION) if config.cache else None LOGGER.debug("++DONE: cache get feed %s", url) headers = previous.caching if previous else None LOGGER.debug("++WAIT: request get %s", url...
async def get_feed(config, url)
Get a feed Arguments: config -- the configuration url -- The URL of the feed retval -- a tuple of feed,previous_version,changed
3.443461
3.306986
1.041269
try: for ns_prefix, url in self.feed.namespaces.items(): if url == 'http://purl.org/syndication/history/1.0': return ns_prefix except AttributeError: pass return None
def archive_namespace(self)
Returns the known namespace of the RFC5005 extension, if any
6.044629
5.199661
1.162504
return {entry['link'] for entry in self.feed.entries if entry and entry.get('link')}
def entry_links(self)
Given a parsed feed, return the links to its entries, including ones which disappeared (as a quick-and-dirty way to support deletions)
7.091364
4.52556
1.566958
ns_prefix = self.archive_namespace if ns_prefix: if ns_prefix + '_archive' in self.feed.feed: # This is declared to be an archive view return True if ns_prefix + '_current' in self.feed.feed: # This is declared to be the c...
def is_archive(self)
Given a parsed feed, returns True if this is an archive feed
5.208103
4.135175
1.259464
try: LOGGER.debug("WebSub: Notifying %s of %s", hub, self.url) request = await utils.retry_post( config, hub, data={ 'hub.mode': 'publish', 'hub.url': self.url }) ...
async def update_websub(self, config, hub)
Update WebSub hub to know about this feed
3.503238
3.379757
1.036535
tags = list() for tag in self._tags: if tag[0] == name: tags.append(tag[1]) return tags
def get_tags(self, name)
Returns a list of tags. @param str name: The name of the tag. :rtype: list[str]
3.019298
4.225423
0.714555
tmp = list() empty = True for i in range(0, len(lines)): empty = empty and lines[i] == '' if not empty: tmp.append(lines[i]) return tmp
def __remove_leading_empty_lines(lines)
Removes leading empty lines from a list of lines. :param list[str] lines: The lines.
3.375729
3.390242
0.995719
lines.reverse() tmp = DocBlockReflection.__remove_leading_empty_lines(lines) lines.reverse() tmp.reverse() return tmp
def __remove_trailing_empty_lines(lines)
Removes leading empty lines from a list of lines. :param list[str] lines: The lines.
10.054539
11.074329
0.907914
# Return immediately if the DockBlock is empty. if not self._comment: return for i in range(1, len(self._comment) - 1): self._comment[i] = re.sub(r'^\s*\*', '', self._comment[i]) self._comment[0] = re.sub(r'^\s*/\*\*', '', self._comment[0]) sel...
def __clean_doc_block(self)
Cleans the DocBlock from leading and trailing white space and comment tokens.
2.368044
2.23374
1.060125
tmp = list() for line in self._comment: if len(line) >= 1 and line[0] == '@': break tmp.append(line) tmp = self.__remove_trailing_empty_lines(tmp) self._description = os.linesep.join(tmp)
def __extract_description(self)
Extracts the description from the DocBlock. The description start at the first line and stops at the first tag or the end of the DocBlock.
4.126106
3.622711
1.138955
tags = list() current = None for line in self._comment: parts = re.match(r'^@(\w+)', line) if parts: current = (parts.group(1), list()) tags.append(current) if current: if line == '': ...
def __extract_tags(self)
Extract tags from the DocBlock.
3.031073
2.721133
1.113901
self.output = PyStratumStyle(self.input, self.output) config_file = self.input.get_argument('config_file') self.run_command(config_file)
def handle(self)
Executes constants command when PyStratumCommand is activated.
11.209834
6.397408
1.752246
config = configparser.ConfigParser() config.read(config_file) rdbms = config.get('database', 'rdbms').lower() label_regex = config.get('constants', 'label_regex') constants = self.create_constants(rdbms) constants.main(config_file, label_regex)
def run_command(self, config_file)
:param str config_file: The name of config file.
4.941245
4.635352
1.065991
# Note: We load modules and classes dynamically such that on the end user's system only the required modules # and other dependencies for the targeted RDBMS must be installed (and required modules and other # dependencies for the other RDBMSs are not required). if r...
def create_constants(self, rdbms)
Factory for creating a Constants objects (i.e. objects for creating constants based on column widths, and auto increment columns and labels). :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystratum.Constants.Constants
4.503113
3.874319
1.162298
key_name = 'ld:{0}:{1}:features'.format( self.project_key, self.environment_key ) return key_name
def _format_key_name(self) -> str
Return formatted redis key name.
9.11392
5.763253
1.581385
redis_connections = [] raw_connections = uri.split(',') connections = [ connection for connection in raw_connections if len(connection) > 0 ] for connection in connections: raw_connection = connection.split(':') if len(raw_connection)...
def connection_string_parser(uri: str) -> list
Parse Connection string to extract host and port. :param uri: full URI for redis connection in the form of host:port :returns: list of RedisConnection objects
2.134128
2.06385
1.034052
key_name = self._format_key_name() flag = self.redis.hget(key_name, feature_key) if flag is None: raise KeyError('Redis key: {0} not found.'.format(key_name)) return flag
def get_flag_record(self, feature_key: str) -> str
Get feature flag record from redis. :param feature_key: key for feature flag :return: value of feature flag key in redis. :raises: KeyError if key is not found.
4.557466
3.85378
1.182596
key_name = self._format_key_name() try: parsed_flag = json.loads(self.get_flag_record(feature_key).decode('utf-8')) parsed_flag['on'] = state parsed_flag['version'] += 1 updated_flag = json.dumps(parsed_flag).encode('utf-8') except KeyErro...
def update_flag_record(self, state: str, feature_key: str) -> None
Update redis record with new state. :param state: state for feature flag. :param feature_key: key for feature flag.
3.121285
2.945654
1.059624
return coros(n, interval, default_callback, loop)(func)
def Asyncme(func, n=None, interval=0, default_callback=None, loop=None)
Wrap coro_function into the function return NewTask.
8.81778
7.03126
1.254083
submitter = Loop( n=n, interval=interval, default_callback=default_callback, loop=loop ).submitter return submitter
def coros(n=None, interval=0, default_callback=None, loop=None)
Decorator for wrap coro_function into the function return NewTask.
5.748372
4.801735
1.197145
@wraps(function) def wrapped(task): task._callback_result = function(task) return task._callback_result return wrapped
def wrap_callback(function)
Set the callback's result as self._callback_result.
5.459512
3.813571
1.431601
self.task_end_time = time.time() self.task_cost_time = self.task_end_time - self.task_start_time callbacks = self._callbacks[:] if not callbacks: return if clear_cb: self._callbacks[:] = [] for callback in callbacks: self._loop...
def _schedule_callbacks(self, clear_cb=False)
Recording the task_end_time and task_cost_time, and prevent super()._schedule_callbacks to clean self._callbacks.
2.997194
2.27553
1.317141
if self._state == self._PENDING: self._loop.run_until_complete(self) if self._callbacks: result = self._callback_result else: result = self.result() return result
def callback_result(self)
Blocking until the task finish and return the callback_result.until
5.119486
3.923822
1.304719
if self._state == self._PENDING: self._loop.run_until_complete(self) return self.result()
def x(self)
Blocking until the task finish and return the self.result()
7.451509
3.572691
2.085686
sem = self.frequency.sem interval = self.frequency.interval @wraps(coro_func) async def new_coro_func(*args, **kwargs): if sem: async with sem: result = await coro_func(*args, **kwargs) if interval: ...
def _wrap_coro_function_with_sem(self, coro_func)
Decorator set the coro_function has sem/interval control.
2.005304
1.739724
1.152656
return self.loop.run_in_executor(executor, func, *args)
def run_in_executor(self, executor=None, func=None, *args)
If `kwargs` needed, try like this: func=lambda: foo(*args, **kwargs)
3.366867
2.537258
1.326971
executor = Pool(pool_size) return self.loop.run_in_executor(executor, func, *args)
def run_in_thread_pool(self, pool_size=None, func=None, *args)
If `kwargs` needed, try like this: func=lambda: foo(*args, **kwargs)
4.704272
4.063136
1.157794
executor = ProcessPool(pool_size) return self.loop.run_in_executor(executor, func, *args)
def run_in_process_pool(self, pool_size=None, func=None, *args)
If `kwargs` needed, try like this: func=lambda: foo(*args, **kwargs)
4.593035
3.905318
1.176098
if not asyncio.iscoroutine(coro): raise TypeError("A await in coroutines. object is required") loop = loop or self.loop future = NewFuture(callback=callback) def callback_func(): try: asyncio.futures._chain_future(NewTask(coro, loop=loop)...
def run_coroutine_threadsafe(self, coro, loop=None, callback=None)
Be used when loop running in a single non-main thread.
4.549603
4.326257
1.051626
args = args or () kwargs = kwargs or {} coro = self._wrap_coro_function_with_sem(coro_function)(*args, **kwargs) return self.submit(coro, callback=callback)
def apply(self, coro_function, args=None, kwargs=None, callback=None)
Submit a coro_function(*args, **kwargs) as NewTask to self.loop with loop.frequncy control. :: from torequests.dummy import Loop import asyncio loop = Loop() async def test(i): result = await asyncio.sleep(1) return (loop.frequen...
3.434267
3.804087
0.902783
callback = callback or self.default_callback if self.async_running: return self.run_coroutine_threadsafe(coro, callback=callback) else: return NewTask(coro, loop=self.loop, callback=callback)
def submit(self, coro, callback=None)
Submit a coro as NewTask to self.loop without loop.frequncy control. :: from torequests.dummy import Loop import asyncio loop = Loop() async def test(i): result = await asyncio.sleep(1) return (loop.frequency, i) cor...
4.404026
4.397899
1.001393
f = self._wrap_coro_function_with_sem(f) @wraps(f) def wrapped(*args, **kwargs): return self.submit(f(*args, **kwargs)) return wrapped
def submitter(self, f)
Decorator to submit a coro-function as NewTask to self.loop with sem control. Use default_callback frequency of loop.
4.483452
3.206317
1.398319
tasks = [task for task in self.all_tasks if task._state == NewTask._PENDING] return tasks
def todo_tasks(self)
Return tasks in loop which its state is pending.
8.948382
5.826492
1.53581
tasks = [task for task in self.all_tasks if task._state != NewTask._PENDING] return tasks
def done_tasks(self)
Return tasks in loop which its state is not pending.
9.763687
6.16676
1.583277
timeout = self._timeout if timeout is None else timeout if self.async_running or self.loop.is_running(): return self.wait_all_tasks_done(timeout) else: tasks = tasks or self.todo_tasks return self.loop.run_until_complete(asyncio.gather(*tasks, loop=se...
def run(self, tasks=None, timeout=None)
Block, run loop until all tasks completed.
3.494952
3.382525
1.033238
timeout = self._timeout if timeout is None else timeout timeout = timeout or float("inf") start_time = time.time() time.sleep(delay) while 1: if not self.todo_tasks: return self.all_tasks if time.time() - start_time > timeout: ...
def wait_all_tasks_done(self, timeout=None, delay=0.5, interval=0.1)
Block, only be used while loop running in a single non-main thread.
3.281527
3.081672
1.064853
tasks = tasks or self.todo_tasks await asyncio.gather(*tasks, loop=self.loop)
async def pendings(self, tasks=None)
Used for await in coroutines. `await loop.pendings()` `await loop.pendings(tasks)`
5.864818
5.401324
1.085811
if not frequencies: return {} if not isinstance(frequencies, dict): raise ValueError("frequencies should be dict") frequencies = { host: Frequency.ensure_frequency(frequencies[host]) for host in frequencies } return frequencies
def ensure_frequencies(self, frequencies)
Ensure frequencies is dict of host-frequencies.
3.942581
3.011744
1.309069
# single sem or global sem sem = sem or self.sem interval = self.interval if interval is None else interval frequency = Frequency(sem, interval, host) frequencies = {host: frequency} self.update_frequency(frequencies) return frequency
def set_frequency(self, host, sem=None, interval=None)
Set frequency for host with sem and interval.
5.250643
5.000184
1.05009
try: if not self.session.closed: if self.session._connector_owner: self.session._connector.close() self.session._connector = None except Exception as e: Config.dummy_logger.error("can not close session for: %s" % e)
def close(self)
Should be closed[explicit] while using external session or connector, instead of close by self.__del__.
5.739146
5.228331
1.097701
''' Openstack exceptions decorator ''' async def wrap(*args, **kwargs): try: return await func(*args, **kwargs) except Exception as e: logging.error(e) raise IaasException return wrap
def openstack_exception(func)
Openstack exceptions decorator
4.760807
3.836715
1.240855
''' Initialize and refresh openstack connection ''' async def wrap(self, *args, **kwargs): if not hasattr(self, 'auth') or not self.auth.is_token_valid(): self.auth = AuthPassword(auth_url=self.config['auth_url'], ...
def initialize_openstack(func)
Initialize and refresh openstack connection
2.11774
2.004135
1.056685
''' Initialize static data like images and flavores and set it as object property ''' flavors = await self._list_flavors() images = await self._list_images() self.flavors_map = bidict() self.images_map = bidict() self.images_details = {} for fla...
async def initialize(self)
Initialize static data like images and flavores and set it as object property
4.55826
3.549504
1.284197
''' Create VM :arg preset_name: string :arg image: string image id :arg flavor: string flavor id :arg security_groups: list :arg userdata: string :arg key_name: string :arg availability_zone: string :arg subnets: list :r...
async def create_vm(self, preset_name, image, flavor, security_groups=None, userdata=None, key_name=None, availability_zone=None, subnets=None)
Create VM :arg preset_name: string :arg image: string image id :arg flavor: string flavor id :arg security_groups: list :arg userdata: string :arg key_name: string :arg availability_zone: string :arg subnets: list :returns list Vm objects...
2.545713
1.872746
1.359348
''' List VMs by preset name :arg present_name: string ''' response = await self.nova.servers.list(name=f'^{preset_name}$') result = [] for server in response['servers']: result.append(self._map_vm_structure(server)) return result
async def list_vms(self, preset_name)
List VMs by preset name :arg present_name: string
7.453743
4.902324
1.520451
''' Terminate VM :arg vm_id: string ''' try: await self.nova.servers.force_delete(vm_id) except JSONDecodeError as exc: logging.info("nova sent 'content-type: application/json' but no content appeared, whatever") pass except E...
async def terminate_vm(self, vm_id)
Terminate VM :arg vm_id: string
10.95715
8.600339
1.274037
''' Get VM :arg vm_id: string :returns vm: object ''' result = await self.nova.servers.get(vm_id) return self._map_vm_structure(result["server"])
async def get_vm(self, vm_id)
Get VM :arg vm_id: string :returns vm: object
8.681668
5.129453
1.692513
''' Vm unification :arg vm: object :returns object ''' ip = self._extract_ips(vm['addresses']) created = datetime.strptime(vm['created'], '%Y-%m-%dT%H:%M:%SZ') flavor = self.flavors_map.get(vm['flavor'].get('id')) image = self.images_map.get(vm['im...
def _map_vm_structure(self, vm)
Vm unification :arg vm: object :returns object
3.342579
2.824396
1.183467
''' Map openstack vm statuses to vmshepherd vm statuses openstack vm statuses: ACTIVE, BUILD, DELETED, ERROR, HARD_REBOOT, MIGRATING, PASSWORD, PAUSED, REBOOT, REBUILD, RESCUE, RESIZE, REVERT_RESIZE, SHELVED, SHELVED_OFFLOADED, SHUTOFF, SOFT_DELETED, SUSPENDED, UNKNOWN, VERIF...
def _map_vm_status(self, openstack_status, timed_shutdown_at=None)
Map openstack vm statuses to vmshepherd vm statuses openstack vm statuses: ACTIVE, BUILD, DELETED, ERROR, HARD_REBOOT, MIGRATING, PASSWORD, PAUSED, REBOOT, REBUILD, RESCUE, RESIZE, REVERT_RESIZE, SHELVED, SHELVED_OFFLOADED, SHUTOFF, SOFT_DELETED, SUSPENDED, UNKNOWN, VERIFY_RESIZE :a...
2.986929
2.051919
1.455676
''' Extract ip addressess from openstack structure { 'pl-krk-2-int-301-c2-int-1': [ { 'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:29:f1:bb', 'version': 4, 'addr': '10.185.138.36', 'OS-EXT-IPS:type': 'fixed' } ] ...
def _extract_ips(self, data)
Extract ip addressess from openstack structure { 'pl-krk-2-int-301-c2-int-1': [ { 'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:29:f1:bb', 'version': 4, 'addr': '10.185.138.36', 'OS-EXT-IPS:type': 'fixed' } ] } :arg...
5.165732
1.593291
3.242178
dlab = str(obj.text()) index_of_colon = dlab.find(': ') if index_of_colon == -1: index_of_colon = 0 else: index_of_colon += 2 if replace_all: index_of_colon = 0 obj.setText(dlab[:index_of_colon] + '%s' % text) if tooltip is not None: obj.setToolTip(toolti...
def _set_label_text(obj, text, tooltip=None, replace_all=False)
Keep text before first colon and replace the rest with new text. If there is no colon in the :param obj: :param text: :param tooltip: :param replace_all: No colon is searched and whole text is replaced :return:
2.747753
2.498396
1.099807
if self.cache is not None: cache_loadfiledir = self.cache.get_or_none('loadfiledir') self.loadfiledir = str(cache_loadfiledir) if self.loadfiledir is None: self.loadfiledir = '' directory = str(self.loadfiledir) from PyQt4.QtGui import QFile...
def __get_datafile(self, app=False)
Draw a dialog for directory selection.
3.845019
3.765354
1.021157
# if 'datadir' in self.oseg.cache.data.keys(): # if : # directory = self.oseg.input_datapath_start if self.cache is not None: cache_loaddir = self.cache.get_or_none('loaddir') self.loaddir = str(cache_loaddir) # self.loaddir = str(self.cac...
def __get_datadir(self, app=False)
Draw a dialog for directory selection.
4.231538
4.094563
1.033453
reader = datareader.DataReader() self.datap = reader.Get3DData(self.datapath, dataplus_format=True, gui=True, qt_app=self.qt_app) _set_label_text(self.text_dcm_dir, _make_text_short(self.datapath), self.datapath) _set_label_text(self.text_dcm_data, self.get_data_info(), repla...
def read_data_from_prepared_datapath(self)
Function is called in the end of process :return:
7.103635
7.304309
0.972527
self._read_configuration_file(config_filename) if self._wrapper_class_name: self._io.title('Wrapper') self.__generate_wrapper_class() else: self._io.log_verbose('Wrapper not enabled') return 0
def main(self, config_filename)
The "main" of the wrapper generator. Returns 0 on success, 1 if one or more errors occurred. :param str config_filename: The name of the configuration file. :rtype: int
7.773622
7.778109
0.999423
routines = self._read_routine_metadata() self._write_class_header() if routines: for routine_name in sorted(routines): if routines[routine_name]['designation'] != 'hidden': self._write_routine_function(routines[routine_name]) els...
def __generate_wrapper_class(self)
Generates the wrapper class.
6.349768
6.026704
1.053605
config = configparser.ConfigParser() config.read(config_filename) self._parent_class_name = config.get('wrapper', 'parent_class') self._parent_class_namespace = config.get('wrapper', 'parent_class_namespace') self._wrapper_class_name = config.get('wrapper', 'wrapper_cla...
def _read_configuration_file(self, config_filename)
Reads parameters from the configuration file. :param str config_filename: The name of the configuration file.
2.561214
2.798695
0.915146
metadata = {} if os.path.isfile(self._metadata_filename): with open(self._metadata_filename, 'r') as file: metadata = json.load(file) return metadata
def _read_routine_metadata(self)
Returns the metadata of stored routines. :rtype: dict
2.701496
3.068592
0.88037
self._write_line('from {0!s} import {1!s}'.format(self._parent_class_namespace, self._parent_class_name)) self._write_line() self._write_line() self._write_line('# ' + ('-' * 118)) self._write_line('class {0!s}({1!s}):'.format(self._wrapper_class_name, self._parent_class...
def _write_class_header(self)
Generate a class header for stored routine wrapper.
2.651378
2.456493
1.079335
if text: self._code += str(text) + "\n" else: self._code += "\n"
def _write_line(self, text='')
Writes a line with Python code to the generate code buffer. :param str text: The line with Python code.
4.277476
4.822808
0.886926
return threads(n=n, timeout=timeout)(f)
def Async(f, n=None, timeout=None)
Concise usage for pool.submit. Basic Usage Asnyc & threads :: from torequests.main import Async, threads import time def use_submit(i): time.sleep(i) result = 'use_submit: %s' % i print(result) return result @threads() def...
10.432039
15.043857
0.693442
try: # python2 not support yield from if sort_by_completed: for future in as_completed(future_list, timeout=timeout): yield future.x else: for future in future_list: yield future.x except TimeoutError: return
def get_results_generator(future_list, timeout=None, sort_by_completed=False)
Return as a generator of tasks order by completed sequence.
3.618956
3.339641
1.083636
t = Timer(seconds, func, args, kwargs) t.daemon = True t.start() return t
def run_after_async(seconds, func, *args, **kwargs)
Run the function after seconds asynchronously.
2.610532
2.704738
0.96517