code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if not isinstance(conf, collections.Mapping): raise ValueError("conf must be a collections.Mapping") self.zk.ensure_path(self.view_path) self._create( self._get_env_path(env), conf ) self._update_view(env)
def create_config(self, env, conf)
Set conf to env under service. pass None to env for root.
5.449057
4.779363
1.140122
if not isinstance(conf, collections.Mapping): raise ValueError("conf must be a collections.Mapping") self._set( self._get_env_path(env), conf, version ) path = self._get_env_path(env) for child in zkutil.walk(sel...
def set_config(self, env, conf, version)
Set conf to env under service. pass None to env for root.
5.786447
5.367836
1.077985
version, config = self._get( self.associations.get(hostname) ) return config
def get_config(self, hostname)
Returns a configuration for hostname.
14.832249
13.670325
1.084996
version, data = self._get(self._get_view_path(env)) return data
def get_view_by_env(self, env)
Returns the view of `env`.
9.620052
8.64979
1.112172
dest = self._get_view_path(env) self.associations.set(hostname, dest)
def assoc_host(self, hostname, env)
Associate a host with an environment. hostname is opaque to Jones. Any string which uniquely identifies a host is acceptable.
12.365517
16.285002
0.759319
if env.is_root: return None associations = self.associations.get_all() return [assoc for assoc in associations if associations[assoc] == self._get_view_path(env)]
def get_associations(self, env)
Get all the associations for this env. Root cannot have associations, so return None for root. returns a map of hostnames to environments.
7.482625
6.837462
1.094357
nodes = env.components # Path through the znode graph from root ('') to env path = [nodes[:n] for n in xrange(len(nodes) + 1)] # Expand path and map it to the root path = map( self._get_env_path, [Env('/'.join(p)) for p in path] ) ...
def _flatten_from_root(self, env)
Flatten values from root down in to new view.
8.121904
7.621629
1.065639
value = self.serialize(value) if self.encoding: value = value.encode(self.encoding) return value
def encode(self, value)
Encode value.
3.771071
3.582074
1.052762
if self.encoding: value = value.decode(self.encoding) return self.deserialize(value)
def decode(self, value)
Decode value.
4.211726
4.147035
1.015599
print('Installing ', packagename) print(sh_pip.install(packagename)) if not filename: filename = get_filename(save, save_dev, save_test) try: add_requirements(packagename, filename) except AssertionError: print('Package already pinned in ', filename)
def install(packagename, save, save_dev, save_test, filename)
Install the package via pip, pin the package only to requirements file. Use option to decide which file the package will be pinned to.
5.63459
4.66961
1.206651
print(sh_pip.uninstall(packagename, "-y")) if not filename: filename = get_filename(save, save_dev, save_test) remove_requirements(packagename, filename)
def remove(packagename, save, save_dev, save_test, filename)
Uninstall the package and remove it from requirements file.
5.599658
5.042844
1.110417
parts = [] while True: newpath, tail = os.path.split(path) if debug: print repr(path), (newpath, tail) if newpath == path: assert not tail if path: parts.append(path) break parts.append(tail) ...
def os_path_split_asunder(path, debug=False)
http://stackoverflow.com/a/4580931/171094
2.498799
2.296884
1.087908
def _get_normalized_parts(path): return DKCloudCommandRunner.os_path_split_asunder(os.path.realpath(os.path.abspath(os.path.normpath(path)))) # make absolute and handle symbolic links, split into components sub_parts = _get_normalized_parts(potential_subdirectory) ...
def is_subdirectory(potential_subdirectory, expected_parent_directory)
Is the first argument a sub-directory of the second argument? :param potential_subdirectory: :param expected_parent_directory: :return: True if the potential_subdirectory is a child of the expected parent directory
5.824569
5.837447
0.997794
rc = DKReturnCode() if kitchen is None or recipe_name is None or message is None: s = 'ERROR: DKCloudCommandRunner bad input parameters' rc.set(rc.DK_FAIL, s) return rc rc = dk_api.recipe_status(kitchen, recipe_name, recipe_dir) if not rc.ok(...
def update_all_files(dk_api, kitchen, recipe_name, recipe_dir, message, dryrun=False)
reutrns a string. :param dk_api: -- api object :param kitchen: string :param recipe_name: string -- kitchen name, string :param recipe_dir: string - path to the root of the directory :param message: string message -- commit message, string :rtype: DKReturnCode
2.1683
2.092851
1.036051
rc = DKReturnCode() if kitchen is None or recipe_name is None or message is None or files_to_update_param is None: s = 'ERROR: DKCloudCommandRunner bad input parameters' rc.set(rc.DK_FAIL, s) return rc # Take a simple string or an array if is...
def update_file(dk_api, kitchen, recipe_name, message, files_to_update_param)
reutrns a string. :param dk_api: -- api object :param kitchen: string :param recipe_name: string -- kitchen name, string :param message: string message -- commit message, string :param files_to_update_param: string -- file system directory where the recipe file lives :r...
2.208922
2.191826
1.0078
rc = DKReturnCode() if kitchen is None or recipe_name is None or message is None or api_file_key is None: s = 'ERROR: DKCloudCommandRunner bad input parameters' rc.set(rc.DK_FAIL, s) return rc ig = DKIgnore() if ig.ignore(api_file_key): ...
def add_file(dk_api, kitchen, recipe_name, message, api_file_key)
returns a string. :param dk_api: -- api object :param kitchen: string :param recipe_name: string :param message: string -- commit message, string :param api_file_key: string -- directory where the recipe file lives :rtype: DKReturnCode
2.499569
2.318186
1.078244
rc = DKReturnCode() if kitchen is None or recipe_name is None or message is None or files_to_delete_param is None: s = 'ERROR: DKCloudCommandRunner bad input parameters' rc.set(rc.DK_FAIL, s) return rc # Take a simple string or an array if is...
def delete_file(dk_api, kitchen, recipe_name, message, files_to_delete_param)
returns a string. :param dk_api: -- api object :param kitchen: string :param recipe_name: string -- kitchen name, string :param message: string message -- commit message, string :param files_to_delete_param: path to the files to delete :rtype: DKReturnCode
2.776087
2.590385
1.071689
print 'period', period # try: # p = int(period) # except ValueError: # return 'DKCloudCommand.watch_active_servings requires an integer for the period' if period <= 0: return 'DKCloudCommand.watch_active_servings requires a positive period' ...
def watch_active_servings(dk_api, kitchen, period)
returns a string. :param dk_api: -- api object :param kitchen: string :param period: integer :rtype: string
3.907497
3.731455
1.047178
rc = dk_api.get_compiled_serving(kitchen, recipe_name, variation_name) if rc.ok(): rs = 'DKCloudCommand.get_compiled_serving succeeded %s\n' % json.dumps(rc.get_payload(), indent=4) else: m = rc.get_message() e = m.split('the logfile errors are:nn') ...
def get_compiled_serving(dk_api, kitchen, recipe_name, variation_name)
returns a string. :param dk_api: -- api object :param kitchen: string :param recipe_name: string -- kitchen name, string :param variation_name: string -- name of the recipe variation_name to be used :rtype: DKReturnCode
4.768459
4.534374
1.051625
unresolved_conflicts = DKKitchenDisk.get_unresolved_conflicts(from_kitchen, to_kitchen) if unresolved_conflicts is not None and len(unresolved_conflicts) != 0: msg = DKCloudCommandRunner._print_unresolved_conflicts(unresolved_conflicts) rc = DKReturnCode() rc...
def merge_kitchens_improved(dk_api, from_kitchen, to_kitchen)
returns a string. :param dk_api: -- api object :param from_kitchen: string :param to_kitchen: string -- kitchen name, string :rtype: DKReturnCode
2.858665
2.76092
1.035403
rc = dk_api.create_order(kitchen, recipe_name, variation_name, node_name) if rc.ok(): s = 'Order ID is: %s' % rc.get_payload() else: m = rc.get_message().replace('\\n','\n') e = m.split('the logfile errors are:') if len(e) > 1: ...
def create_order(dk_api, kitchen, recipe_name, variation_name, node_name=None)
returns a string. :param dk_api: -- api object :param kitchen: string :param recipe_name: string -- kitchen name, string :param variation_name: string -- name of the recipe variation_name to be run :param node_name: string -- name of the single node to run :rtype: DKRetu...
4.937675
4.510401
1.094731
s = path.rsplit('/', 1) if len(s) == 1: return s[0], '' else: return tuple(s)
def _split_one_end(path)
Utility function for splitting off the very end part of a path.
3.374213
2.905351
1.161379
def get_system_config_directory(): if platform.system().lower() == 'windows': _cfg_directory = Path(os.getenv('APPDATA') or '~') elif platform.system().lower() == 'darwin': _cfg_directory = Path('~', 'Library', 'Preferences') else: _cfg_directory = Path(os.getenv('XDG_CON...
Return platform specific config directory.
null
null
null
def get_version_exec_mapping_from_path(path): version_executable = {} logger.debug('Getting exes from path: {}'.format(path)) for sub_dir in path.iterdir(): if not sub_dir.name.startswith(APPLICATION_NAME): continue release = sub_dir.name.split(APPLICATION_NAME)[-...
Find valid application version from given path object and return a mapping of version, executable.
null
null
null
def find_applications_on_system(): # First we collect maya versions from the Autodesk folder we presume # is addeed to the system environment "PATH" path_env = os.getenv('PATH').split(os.pathsep) versions = {} for each in path_env: path = Path(os.path.expandvars(each)) i...
Collect maya version from Autodesk PATH if exists, else try looking for custom executable paths from config file.
null
null
null
def build_config(config_file=get_system_config_directory()): config = Config(config_file, allow_no_value=True) application_versions = find_applications_on_system() # Add found versions to config if they don't exist. Versions found # in the config file takes precedence over versions found in ...
Construct the config object from necessary elements.
null
null
null
def get_environment_paths(config, env): if env is None: return config.get(Config.DEFAULTS, 'environment') # Config option takes precedence over environment key. if config.has_option(Config.ENVIRONMENTS, env): env = config.get(Config.ENVIRONMENTS, env).replace(' ', '').split(';')...
Get environment paths from given environment variable.
null
null
null
def build_maya_environment(config, env=None, arg_paths=None): maya_env = MayaEnvironment() maya_env.exclude_pattern = config.get_list(Config.PATTERNS, 'exclude') maya_env.icon_extensions = config.get_list(Config.PATTERNS, 'icon_ext') env = get_environment_paths(config, env) if not env a...
Construct maya environment.
null
null
null
def launch(exec_, args): if not exec_: raise RuntimeError( 'Mayalauncher could not find a maya executable, please specify' 'a path in the config file (-e) or add the {} directory location' 'to your PATH system environment.'.format(DEVELOPER_NAME) ) ...
Launches application.
null
null
null
def main(): config = build_config() parser = argparse.ArgumentParser( description= ) parser.add_argument( 'file', nargs='?', default=None, help=) parser.add_argument( '-v', '--version', type=str, choices=get_exe...
Main function of maya launcher. Parses the arguments and tries to launch maya with given them.
null
null
null
def _create_default_config_file(self): logger.info('Initialize Maya launcher, creating config file...\n') self.add_section(self.DEFAULTS) self.add_section(self.PATTERNS) self.add_section(self.ENVIRONMENTS) self.add_section(self.EXECUTABLES) self.set(self.D...
If config file does not exists create and set default values.
null
null
null
def get_list(self, section, option): if self.has_option(section, option): return self.get(section, option).replace(' ', '').split(',') else: raise KeyError('{} with {} does not exist.'.format(section, o...
Convert string value to list object.
null
null
null
def edit(self): if platform.system().lower() == 'windows': os.startfile(str(self.config_file)) else: if platform.system().lower() == 'darwin': call = 'open' else: call = 'xdg-open' subprocess.call([call, se...
Edit file with default os application.
null
null
null
def is_excluded(self, path, exclude=None): for pattern in (exclude or self.exclude_pattern): if path.match(pattern): return True else: return False
Return if path is in exclude pattern.
null
null
null
def get_directories_with_extensions(self, start, extensions=None): return set([p.parent for ext in extensions for p in start.rglob(ext)])
Look for directories with image extensions in given directory and return a list with found dirs. .. note:: In deep file structures this might get pretty slow.
null
null
null
def put_path(self, path): if self.is_package(path): logger.debug('PYTHON PACKAGE: {}'.format(path)) self.python_paths.append(path.parent) site.addsitedir(str(path.parent)) xbmdirs = self.get_directories_with_extensions( path, ...
Given path identify in which environment the path belong to and append it.
null
null
null
def traverse_path_for_valid_application_paths(self, top_path): self.put_path(Path(top_path)) for p in self._walk(top_path): self.put_path(p)
For every path beneath top path that does not contain the exclude pattern look for python, mel and images and place them in their corresponding system environments.
null
null
null
def check_correct_host(self): if self._host == 'knoema.com': return url = self._get_url('/api/1.0/frontend/tags') req = urllib.request.Request(url) try: resp = urllib.request.urlopen(req) except: raise ValueError('The specifie...
The method checks whether the host is correctly set and whether it can configure the connection to this host. Does not check the base host knoema.com
null
null
null
def get_dataset(self, datasetid): path = '/api/1.0/meta/dataset/{}' return self._api_get(definition.Dataset, path.format(datasetid))
The method is getting information about dataset byt it's id
null
null
null
def get_dimension(self, dataset, dimension): path = '/api/1.0/meta/dataset/{}/dimension/{}' return self._api_get(definition.Dimension, path.format(dataset, dimension))
The method is getting information about dimension with items
null
null
null
def get_daterange(self, dataset): path = '/api/1.0/meta/dataset/{}/daterange' return self._api_get(definition.DateRange, path.format(dataset))
The method is getting information about date range of dataset
null
null
null
def get_data(self, pivotrequest): path = '/api/1.0/data/pivot/' return self._api_post(definition.PivotResponse, path, pivotrequest)
The method is getting data by pivot request
null
null
null
def get_data_raw(self, request): path = '/api/1.0/data/raw/' res = self._api_post(definition.RawDataResponse, path, request) token = res.continuation_token while token is not None: res2 = self.get_data_raw_with_token(token) res.series += res2.series ...
The method is getting data by raw request
null
null
null
def get_mnemonics (self, mnemonics): path = '/api/1.0/data/mnemonics?mnemonics={0}' return self._api_get(definition.MnemonicsResponseList, path.format(mnemonics))
The method get series by mnemonics
null
null
null
def upload_file(self, file): url = self._get_url('/api/1.0/upload/post') fcontent = FileContent(file) binary_data = fcontent.get_binary() headers = self._get_request_headers() req = urllib.request.Request(url, binary_data, headers) req.add_header('Co...
The method is posting file to the remote server
null
null
null
def upload_verify(self, file_location, dataset=None): path = '/api/1.0/upload/verify' query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location) if dataset: query = 'doNotGenerateAdvanceReport=true&filePath={}&datasetId={}'.format(file_location, datas...
This method is verifiing posted file on server
null
null
null
def upload_submit(self, upload_request): path = '/api/1.0/upload/save' return self._api_post(definition.DatasetUploadResponse, path, upload_request)
The method is submitting dataset upload
null
null
null
def upload_status(self, upload_id): path = '/api/1.0/upload/status' query = 'id={}'.format(upload_id) return self._api_get(definition.DatasetUploadStatusResponse, path, query)
The method is checking status of uploaded dataset
null
null
null
def upload(self, file_path, dataset=None, public=False): upload_status = self.upload_file(file_path) err_msg = 'Dataset has not been uploaded to the remote host' if not upload_status.successful: msg = '{}, because of the following error: {}'.format(err_msg, upload_sta...
Use this function to upload data to Knoema dataset.
null
null
null
def delete(self, dataset): url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset)) json_data = '' binary_data = json_data.encode() headers = self._get_request_headers() req = urllib.request.Request(url, binary_data, headers) resp = url...
The method is deleting dataset by it's id
null
null
null
def verify(self, dataset, publication_date, source, refernce_url): path = '/api/1.0/meta/verifydataset' req = definition.DatasetVerifyRequest(dataset, publication_date, source, refernce_url) result = self._api_post(definition.DatasetVerifyResponse, path, req) if result.st...
The method is verifying dataset by it's id
null
null
null
def get_binary(self): content_disp = 'Content-Disposition: form-data; name="file"; filename="{}"' stream = io.BytesIO() stream.write(_string_to_binary('--{}'.format(self.boundary))) stream.write(_crlf()) stream.write(_string_to_binary(content_disp.format(self.f...
Return a binary buffer containing the file content
null
null
null
query_details = [ str(QueryCache.QUERY_CACHE_VERSION), str(self._bucket_width), binascii.b2a_hex(marshal.dumps(self._query_function.func_code)), str(self._query_function_args), str(self._query_function_kwargs), ] return hashlib.sha512('$'.join(query_details)).hexdigest()[:...
def _scratch_stream_name(self)
A unique cache stream name for this QueryCache. Hashes the necessary facts about this QueryCache to generate a unique cache stream name. Different `query_function` implementations at different `bucket_width` values will be cached to different streams. TODO(marcua): This approach won't work for dy...
5.812199
3.896616
1.491602
event_time = kronos_time_to_epoch_time(event_time) return event_time - (event_time % self._bucket_width)
def _bucket_time(self, event_time)
The seconds since epoch that represent a computed bucket. An event bucket is the time of the earliest possible event for that `bucket_width`. Example: if `bucket_width = timedelta(minutes=10)`, bucket times will be the number of seconds since epoch at 12:00, 12:10, ... on each day.
5.305173
5.338923
0.993679
current_bucket_time = None current_bucket_events = None for event in event_iterable: event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD]) if current_bucket_time is None or current_bucket_time < event_bucket_time: if current_bucket_events is not None: yield curren...
def _bucket_events(self, event_iterable)
Convert an iterable of events into an iterable of lists of events per bucket.
1.953513
1.798133
1.086412
cached_buckets = self._bucket_events( self._client.get(self._scratch_stream, start_time, end_time, namespace=self._scratch_namespace)) for bucket_events in cached_buckets: # If we have multiple cache entries for the same bucket, pretend # we have no results for that...
def _cached_results(self, start_time, end_time)
Retrieves cached results for any bucket that has a single cache entry. If a bucket has two cache entries, there is a chance that two different writers previously computed and cached a result since Kronos has no transaction semantics. While it might be safe to return one of the cached results if there ...
6.72843
5.333542
1.261531
if untrusted_time and not untrusted_time.tzinfo: untrusted_time = untrusted_time.replace(tzinfo=tzutc()) events = self._compute_buckets(start_time, end_time, compute_missing=True, cache=True, untrusted_time=untrusted_time, force_r...
def compute_and_cache_missing_buckets(self, start_time, end_time, untrusted_time, force_recompute=False)
Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to avoid recomputation. For any buckets where all events would have occurred before `untrusted_time`, cache the results. :param start_time: A datetim...
2.728553
3.446944
0.791586
events = self._compute_buckets(start_time, end_time, compute_missing=compute_missing) for event in events: yield event
def retrieve_interval(self, start_time, end_time, compute_missing=False)
Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to avoid recomputation. :param start_time: A datetime for the beginning of the range, aligned with `bucket_width`. :param end_time: A datetime for the...
5.553561
6.107591
0.909288
print "[%s] -- %s -- START" % (datetime.datetime.now(), task['id']) try: with get_app().app_context(): exec task['code'] in {}, {} print "[%s] -- %s -- COMPLETE" % (datetime.datetime.now(), task['id']) except Exception as e: if isinstance(e, PyCodeError): err_msg = "%s: %s\n%s" % (e.d...
def _execute(task)
A wrapper around exec This exists outside the Scheduler class because it is pickled after it is sent to the executor.
2.83082
2.798591
1.011516
results = set() while True: now = datetime.datetime.now() if self._task_queue and self._task_queue[0][0] <= now: task = heappop(self._task_queue)[1] if task['id'] not in self._pending_cancels: result = self._executor.submit(_execute, task) results.add(result...
def _loop(self, reader)
Main execution loop of the scheduler. The loop runs every second. Between iterations, the loop listens for schedule or cancel requests coming from Flask via over the gipc pipe (reader) and modifies the queue accordingly. When a task completes, it is rescheduled
3.282527
3.039046
1.080117
@wraps(function) def decorated(*args, **kwargs): auth_token = request.form.get('auth_token') if not auth_token: return json.dumps({ 'status': 'fail', 'reason': 'You must provide an auth_token', }) data = dict(request.form) del data['auth_token'] correct_token = cr...
def token_protected_endpoint(function)
Requires valid auth_token in POST to access An auth_token is built by sending a dictionary built from a Werkzeug.Request.form to the scheduler.auth.create_token function.
2.308738
2.188407
1.054986
d = ((df.values > noise) * df.columns).max(axis=1) return Trace(d, df.index, name='molmz')
def molmz(df, noise=10000)
The mz of the molecular ion.
9.171822
9.462661
0.969265
mol_ions = ((df.values > noise) * df.columns).max(axis=1) - minus mol_ions[np.abs(mol_ions) < 0] = 0 d = np.abs(np.ones(df.shape) * df.columns - (mol_ions[np.newaxis].T * np.ones(df.shape))) < 1 d = (df.values * d).sum(axis=1) return Trace(d, df.index, name='m-' + str(minus))
def mzminus(df, minus=0, noise=10000)
The abundances of ions which are minus below the molecular ion.
5.409459
5.1763
1.045044
# returns the d = np.array(df.columns)[df.values.argmax(axis=1)] return Trace(d, df.index, name='basemz')
def basemz(df)
The mz of the most abundant ion.
9.553642
9.663527
0.988629
# pull out the data d = df.values # smooth the data and standardize it smooth_data = movingaverage(d, df.index, window)[0] stand_data = (smooth_data - smooth_data.mean()) / smooth_data.std() # scale the data to have unit length scale_data = d / np.sqrt(np.sum(d ** 2, axis=0)) # c...
def coda(df, window, level)
CODA processing from Windig, Phalp, & Payne 1996 Anal Chem
4.486567
4.510152
0.994771
# automatically find any subclasses of TraceFile in the same # directory as me classes = {} mydir = op.dirname(op.abspath(inspect.getfile(get_mimetype))) tfcls = {"<class 'aston.tracefile.TraceFile'>", "<class 'aston.tracefile.ScanListFile'>"} for filename in glob(op.join(mydir...
def tfclasses()
A mapping of mimetypes to every class for reading data files.
4.258391
3.962797
1.074592
def find_side(y, loc=None): if loc is None: loc = y.argmax() ddy = np.diff(np.diff(y)) lft_loc, rgt_loc = loc - 2, loc + 1 while rgt_loc >= 0 and rgt_loc < len(ddy): if ddy[rgt_loc] < ddy[rgt_loc - 1]: break rgt_loc += 1 ...
def guess_initc(ts, f, rts=[])
ts - An AstonSeries that's being fitted with peaks f - The functional form of the peaks (e.g. gaussian) rts - peak maxima to fit; each number corresponds to one peak
2.789623
2.724519
1.023896
if fit_vars is None: fit_vars = [f._peakargs for f in fs] initc = [min(ts.values)] for f, peak_params, to_fit in zip(fs, all_params, fit_vars): if 'v' in to_fit: to_fit.remove('v') if make_bounded and hasattr(f, '_pbounds'): new_v = _to_unbnd_p({i: peak_...
def fit(ts, fs=[], all_params=[], fit_vars=None, alg='leastsq', make_bounded=True)
Use a minimization algorithm to fit a AstonSeries with analytical functions.
2.458451
2.476752
0.992611
global _GREENLET_EXECUTOR if _GREENLET_EXECUTOR is None: _GREENLET_EXECUTOR = GreenletExecutor( num_greenlets=settings.node.greenlet_pool_size) return _GREENLET_EXECUTOR.submit(func, *args, **kwargs)
def execute_greenlet_async(func, *args, **kwargs)
Executes `func` in a separate greenlet in the same process. Memory and other resources are available (e.g. TCP connections etc.) `args` and `kwargs` are passed to `func`.
3.099301
3.046177
1.01744
global _GIPC_EXECUTOR if _GIPC_EXECUTOR is None: _GIPC_EXECUTOR = GIPCExecutor( num_procs=settings.node.gipc_pool_size, num_greenlets=settings.node.greenlet_pool_size) return _GIPC_EXECUTOR.submit(func, *args, **kwargs)
def execute_process_async(func, *args, **kwargs)
Executes `func` in a separate process. Memory and other resources are not available. This gives true concurrency at the cost of losing access to these resources. `args` and `kwargs` are
3.745184
5.223392
0.717002
return AbstractExecutor.wait(results, num=num, timeout=timeout)
def wait(results, num=None, timeout=None)
Wait for results of async executions to become available/ready. `results`: List of AsyncResult instances returned by one of `execute_greenlet_async` or `execute_process_async`. `num`: Number of results to wait for. None implies wait for all results. `timeout`: Number of seconds to wait for `num` of ...
8.954597
15.969459
0.560733
message = [] def message_len(): return sum([len(w) + 1 for w in message]) while message_len() < max_message_length: message.append(self.a_random_word(message[-1] if message else None)) return ' '.join(message[:-1])
def create(self, mention, max_message_length)
Create a message :param mention: JSON object containing mention details from Twitter (or an empty dict {}) :param max_message_length: Maximum allowable length for created message :return: A random message created using a Markov chain generator
4.14153
4.63642
0.89326
if not self.validate_signature(signature, data_str): raise HelpScoutSecurityException( 'The signature provided by this request was invalid.', ) return HelpScoutWebHookEvent( event_type=event_type, record=json.loads(data_str), ...
def receive(self, event_type, signature, data_str)
Receive a web hook for the event and signature. Args: event_type (str): Name of the event that was received (from the request ``X-HelpScout-Event`` header). signature (str): The signature that was received, which serves as authentication (from the request...
6.44118
3.813464
1.689063
if isinstance(data, string_types): data = bytearray(data, encoding) if isinstance(signature, string_types): signature = bytearray(signature, encoding) secret_key = bytearray(self.secret_key, 'utf8') hashed = hmac.new(secret_key, data, sha1) enco...
def validate_signature(self, signature, data, encoding='utf8')
Validate the signature for the provided data. Args: signature (str or bytes or bytearray): Signature that was provided for the request. data (str or bytes or bytearray): Data string to validate against the signature. encoding (str, optional): ...
2.398438
2.453343
0.97762
def _hook(hook_func): return register_hook(name, hook_func=hook_func, priority=priority) return _hook
def hook(name=None, priority=-1)
Decorator
4.147049
4.132872
1.00343
kwargs = { 'size': 400, 'window': 8, 'min_count': 2, 'workers': 8 }.update(kwargs) n = 0 for path in paths: print('Counting lines for {0}...'.format(path)) n += sum(1 for line in open(path, 'r')) print('Processing {0} lines...'.format(n)) pr...
def train_doc2vec(paths, out='data/model.d2v', tokenizer=word_tokenize, sentences=False, **kwargs)
Train a doc2vec model on a list of files.
2.875524
2.788278
1.03129
i = 0 p = Progress() for path in paths: with open(path, 'r') as f: for line in f: i += 1 p.print_progress(i/n) # We do minimal pre-processing here so the model can learn # punctuation line = line.lower(...
def _doc2vec_doc_stream(paths, n, tokenizer=word_tokenize, sentences=True)
Generator to feed sentences to the dov2vec model.
3.125086
3.101389
1.007641
self._serial.port = self._port self._serial.baudrate = self._baud self._serial.timeout = self._timeout self._serial.open() self._serial.flushInput() self._serial.flushOutput()
def open(self)
Open the device.
2.234247
1.962146
1.138675
re_info = re.compile( r'\[(?P<name>\w+).(?P<ver>.*) ' + r'\((?P<rfm1name>\w+) (\w+):(?P<rfm1freq>\d+) ' + r'(?P<rfm1mode>.*)\)\]') info = { 'name': None, 'version': None, 'rfm1name': None, 'rfm1frequency': None...
def _parse_info(line)
The output can be: - [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)] - [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)]
2.350628
2.079949
1.130137
re_info = re.compile(r'\[.*\]') self._write_cmd('v') while True: line = self._serial.readline() try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') match = re_info....
def get_info(self)
Get current configuration info from 'v' command.
3.690977
2.865351
1.288141
cmds = {1: 'f', 2: 'F'} self._write_cmd('{}{}'.format(frequency, cmds[rfm]))
def set_frequency(self, frequency, rfm=1)
Set frequency in kHz. The frequency can be set in 5kHz steps.
8.201599
8.250512
0.994072
cmds = {1: 'r', 2: 'R'} self._write_cmd('{}{}'.format(rate, cmds[rfm]))
def set_datarate(self, rate, rfm=1)
Set datarate (baudrate).
8.125257
7.371964
1.102184
cmds = {1: 't', 2: 'T'} self._write_cmd('{}{}'.format(interval, cmds[rfm]))
def set_toggle_interval(self, interval, rfm=1)
Set the toggle interval.
9.777328
8.729173
1.120075
cmds = {1: 'm', 2: 'M'} self._write_cmd('{}{}'.format(mode_mask, cmds[rfm]))
def set_toggle_mask(self, mode_mask, rfm=1)
Set toggle baudrate mask. The baudrate mask values are: 1: 17.241 kbps 2 : 9.579 kbps 4 : 8.842 kbps These values can be or'ed.
8.345238
6.985474
1.194656
while not self._stopevent.isSet(): line = self._serial.readline() #this is for python2/python3 compatibility. Is there a better way? try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-...
def _refresh(self)
Background refreshing thread.
3.933263
3.730926
1.054232
if sensorid not in self._registry: self._registry[sensorid] = list() self._registry[sensorid].append((callback, user_data))
def register_callback(self, sensorid, callback, user_data=None)
Register a callback for the specified sensor id.
2.412891
2.460371
0.980702
self._callback = callback self._callback_data = user_data
def register_all(self, callback, user_data=None)
Register a callback for all sensors.
4.935251
4.339086
1.137394
@wraps(f) def check_if_complete(cls, *args, **kwargs): if cls.is_complete: raise FMBaseError('Transfer already completed.') return f(cls, *args, **kwargs) return check_if_complete
def not_completed(f)
Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in
4.260183
3.387545
1.257602
payload = { 'apikey': self.session.cookies.get('apikey'), 'source': self.session.cookies.get('source') } if self.fm_user.logged_in: payload['logintoken'] = self.session.cookies.get('logintoken') payload.update(self.transfer_info) ...
def _initialize(self)
Initialize transfer.
4.30693
3.971133
1.084559
if to is None: return None if isinstance(to, list): recipients = [] for recipient in to: if isinstance(recipient, dict): if 'contactgroupname' in recipient: recipients.append(recipient['contactgro...
def _parse_recipients(self, to)
Make sure we have a "," separated list of recipients :param to: Recipient(s) :type to: (str, list, :class:`pyfilemail.Contact`, :class:`pyfilemail.Group` ) :rtype: ``str``
2.444122
2.425051
1.007864
if isinstance(files, basestring): files = [files] zip_file = None if self.zip_: zip_filename = self._get_zip_filename() zip_file = ZipFile(zip_filename, 'w') for filename in files: if os.path.isdir(filename): for...
def add_files(self, files)
Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list
2.364087
2.342294
1.009304
path, filename = os.path.split(filepath) fileid = str(uuid4()).replace('-', '') if self.checksum: with open(filepath, 'rb') as f: md5hash = md5(f.read()).digest().encode('base64')[:-1] else: md5hash = None specs = { ...
def get_file_specs(self, filepath, keep_folders=False)
Gather information on files needed for valid transfer. :param filepath: Path to file in question :param keep_folders: Whether or not to maintain folder structure :type keep_folders: bool :type filepath: str, unicode :rtype: ``dict``
3.11856
3.071352
1.015371
method, url = get_URL('get') payload = { 'apikey': self.session.cookies.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, } res = getattr(self.session, method)(url, params=payload) ...
def get_files(self)
Get information on file in transfer from Filemail. :rtype: ``list`` of ``dict`` objects with info on files
4.160942
3.980758
1.045264
date = datetime.datetime.now().strftime('%Y_%m_%d-%H%M%S') zip_file = 'filemail_transfer_{date}.zip'.format(date=date) return zip_file
def _get_zip_filename(self)
Create a filename for zip file when :class:Transfer.compress is set to ``True`` :rtype: str
5.805585
4.927691
1.178155
tot = len(self.files) url = self.transfer_info['transferurl'] for index, fmfile in enumerate(self.files): msg = 'Uploading: "{filename}" ({cur}/{tot})' logger.debug( msg.format( filename=fmfile['thefilename'], ...
def send(self, auto_complete=True, callback=None)
Begin uploading file(s) and sending email(s). If `auto_complete` is set to ``False`` you will have to call the :func:`Transfer.complete` function at a later stage. :param auto_complete: Whether or not to mark transfer as complete and send emails to recipient(s) :param callback:...
4.115673
3.960737
1.039118
if 'status' in self.transfer_info: self._complete = self.transfer_info['status'] == 'STATUS_COMPLETE' return self._complete
def is_complete(self)
:rtype: ``bool`` ``True`` if transfer is complete
7.020806
4.85562
1.445913
method, url = get_URL('forward') payload = { 'apikey': self.session.cookies.get('apikey'), 'transferid': self.transfer_id, 'transferkey': self.transfer_info.get('transferkey'), 'to': self._parse_recipients(to) } res = getatt...
def forward(self, to)
Forward prior transfer to new recipient(s). :param to: new recipients to a previous transfer. Use ``list`` or comma seperatde ``str`` or ``unicode`` list :type to: ``list`` or ``str`` or ``unicode`` :rtype: ``bool``
5.706351
5.39357
1.057992
method, url = get_URL('share') payload = { 'apikey': self.session.cookies.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, 'to': self._parse_recipients(to), 'from': sender or self.f...
def share(self, to, sender=None, message=None)
Share transfer with new message to new people. :param to: receiver(s) :param sender: Alternate email address as sender :param message: Meggase to new recipients :type to: ``list`` or ``str`` or ``unicode`` :type sender: ``str`` or ``unicode`` :type message: ``str`` or ``...
4.421282
4.221427
1.047343
method, url = get_URL('cancel') payload = { 'apikey': self.config.get('apikey'), 'transferid': self.transfer_id, 'transferkey': self.transfer_info.get('transferkey') } res = getattr(self.session, method)(url, params=payload) if...
def cancel(self)
Cancel the current transfer. :rtype: ``bool``
5.49067
5.07757
1.081358
if not isinstance(fmfile, dict): raise FMBaseError('fmfile must be a <dict>') method, url = get_URL('file_rename') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'fileid': fmfile.g...
def rename_file(self, fmfile, newname)
Rename file in transfer. :param fmfile: file data from filemail containing fileid :param newname: new file name :type fmfile: ``dict`` :type newname: ``str`` or ``unicode`` :rtype: ``bool``
4.577248
4.361637
1.049433