code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
with open(yaml_file, 'r') as file: return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)
def load_yaml(yaml_file: str) -> Any
Load YAML from file. :param yaml_file: path to YAML file :return: content of the YAML as dict/list
2.611892
3.041967
0.85862
dumped_config_f = path.join(output_dir, name) with open(dumped_config_f, 'w') as file: yaml.dump(data, file, Dumper=ruamel.yaml.RoundTripDumper) return dumped_config_f
def yaml_to_file(data: Mapping, output_dir: str, name: str) -> str
Save the given object to the given path in YAML. :param data: dict/list to be dumped :param output_dir: target output directory :param name: target filename :return: target path
3.061754
3.019099
1.014129
return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper)
def yaml_to_str(data: Mapping) -> str
Return the given given config as YAML str. :param data: configuration dict :return: given configuration as yaml str
4.682037
5.583017
0.838621
return yaml.load(yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper), Loader=ruamel.yaml.Loader)
def make_simple(data: Any) -> Any
Substitute all the references in the given data (typically a mapping or sequence) with the actual values. This is useful, if you loaded a yaml with RoundTripLoader and you need to dump part of it safely. :param data: data to be made simple (dict instead of CommentedMap etc.) :return: simplified data
4.411144
4.895161
0.901123
return yaml.load(yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper), Loader=ruamel.yaml.RoundTripLoader)
def reload(data: Any) -> Any
Dump and load yaml data. This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure the changes are propagated to anchor expansions. :param data: data to be reloaded :return: reloaded data
3.539309
3.721967
0.950924
super().after_epoch(epoch_id=epoch_id, epoch_data=epoch_data) self._saved_loss.append(epoch_data[self._stream][self._variable][OnPlateau._AGGREGATION]) long_mean = np.mean(self._saved_loss[-self._long_term:]) short_mean = np.mean(self._saved_loss[-self._short_term:]) ...
def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None
Call :py:meth:`_on_plateau_action` if the ``long_term`` variable mean is lower/greater than the ``short_term`` mean.
2.854112
2.222464
1.284211
if isinstance(data, np.ndarray) or isinstance(data, list): return any(np.isnan(data)) or (self._stop_on_inf and any(np.isinf(data))) elif np.isscalar(data): return np.isnan(data) or (self._stop_on_inf and np.isinf(data)) elif isinstance(data, dict): r...
def _is_nan(self, variable: str, data) -> bool
Recursively search passed data and find NaNs. :param variable: name of variable to be checked :param data: data object (dict, list, scalar) :return: `True` if there is a NaN value in the data; `False` otherwise. :raise ValueError: if the variable value is of unsupported type and ``on_un...
2.334921
2.099444
1.112162
for stream_name in epoch_data.keys(): stream_data = epoch_data[stream_name] variables = self._variables if self._variables is not None else stream_data.keys() for variable in variables: if variable not in stream_data: raise KeyErro...
def _check_nan(self, epoch_data: EpochData) -> None
Raise an exception when some of the monitored data is NaN. :param epoch_data: epoch data checked :raise KeyError: if the specified variable is not found in the stream :raise ValueError: if the variable value is of unsupported type and ``self._on_unknown_type`` is set to ``error``
3.21966
2.843143
1.13243
if self._after_epoch: self._check_nan(epoch_data)
def after_epoch(self, epoch_data: EpochData, **kwargs) -> None
If initialized to check after each epoch, stop the training once the epoch data contains a monitored variable equal to NaN. :param epoch_data: epoch data to be checked
12.838044
7.177675
1.788608
if self._after_batch: self._check_nan({stream_name: batch_data})
def after_batch(self, stream_name: str, batch_data) -> None
If initialized to check after each batch, stop the training once the batch data contains a monitored variable equal to NaN. :param stream_name: name of the stream to be checked :param batch_data: batch data to be checked
14.460238
7.72884
1.870945
if epoch_id % self._n_epochs == 0: self._after_n_epoch(epoch_id=epoch_id, **kwargs)
def after_epoch(self, epoch_id: int, **kwargs) -> None
Call ``_after_n_epoch`` method every ``n_epochs`` epoch. :param epoch_id: number of the processed epoch
4.799046
3.152905
1.522103
if path.isfile(path_): return path.getsize(path_) total_size = 0 for root_dir, _, files in os.walk(path_): for file_ in files: total_size += path.getsize(path.join(root_dir, file_)) return total_size
def path_total_size(path_: str) -> int
Compute total size of the given file/dir.
1.993232
1.73125
1.151326
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if filesize < 1024.0: return '{:3.1f}'.format(filesize), unit+'B' filesize /= 1024.0
def humanize_filesize(filesize: int) -> Tuple[str, str]
Return human readable pair of size and unit from the given filesize in bytes.
2.034435
1.883043
1.080398
return path.exists(path.join(dir_, CXF_CONFIG_FILE)) and \ path.exists(path.join(dir_, CXF_TRACE_FILE)) and \ path.exists(path.join(dir_, CXF_LOG_FILE))
def is_train_dir(dir_: str) -> bool
Test if the given dir contains training artifacts.
3.248046
2.676156
1.213698
if is_train_dir(root_dir): yield '', [root_dir] return for dir_, subdirs, _ in os.walk(root_dir, topdown=True): # filter train sub-dirs train_subdirs = [subdir for subdir in subdirs if is_train_dir(path.join(dir_, subdir))] # stop the recursion at the train sub-dirs...
def walk_train_dirs(root_dir: str) -> Iterable[Tuple[str, Iterable[str]]]
Modify os.walk with the following: - return only root_dir and sub-dirs - return only training sub-dirs - stop recursion at training dirs :param root_dir: root dir to be walked :return: generator of (root_dir, training sub-dirs) pairs
2.91886
2.975712
0.980895
long_table = [] for train_dir, config, trace in trainings: start_datetime, end_datetime = trace[TrainingTraceKeys.TRAIN_BEGIN], trace[TrainingTraceKeys.TRAIN_END] if start_datetime: age = format_timedelta(datetime.now() - start_datetime) + ' ago' if end_datetime: ...
def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None
Print a plain table with the details of the given trainings. :param trainings: iterable of tuples (train_dir, configuration dict, trace)
3.232498
3.031741
1.066218
all_trainings = [] for root_dir, train_dirs in walk_train_dirs(dir_): if train_dirs: if recursive: print(root_dir + ':') trainings = [(train_dir, load_config(path.join(train_dir, CXF_CONFIG_FILE), []), Train...
def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]
Print names of the train dirs contained in the given dir. :param dir_: dir to be listed :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option) :param all_: include train dirs with no epochs done (--all option) :param long: list more details including model name, ...
3.102056
2.92047
1.062177
counts_by_name = defaultdict(int) counts_by_classes = defaultdict(int) for _, config, _ in all_trainings: counts_by_name[get_model_name(config)] += 1 counts_by_classes[get_classes(config)] += 1 print_boxed('summary') print() counts_table = [[name, count] for name, count in...
def _ls_print_summary(all_trainings: List[Tuple[str, dict, TrainingTrace]]) -> None
Print trainings summary. In particular print tables summarizing the number of trainings with - particular model names - particular combinations of models and datasets :param all_trainings: a list of training tuples (train_dir, configuration dict, trace)
2.316856
2.223503
1.041985
train_dir, config, _ = training print_boxed('config') print(yaml_to_str(config)) print() print_boxed('artifacts') _, dirs, files = next(os.walk(train_dir)) artifacts = [('d', dir) for dir in dirs] + \ [('-', file_) for file_ in files if file_ not in [CXF_CONFIG_FILE, CX...
def _ls_print_verbose(training: Tuple[str, dict, str]) -> None
Print config and artifacts info from the given training tuple (train_dir, configuration dict, trace). :param training: training tuple (train_dir, configuration dict, trace)
4.582941
4.217027
1.08677
if verbose: long = True if dir_ == CXF_DEFAULT_LOG_DIR and not path.exists(CXF_DEFAULT_LOG_DIR): print('The default log directory `{}` does not exist.\n' 'Consider specifying the directory to be listed as an argument.'.format(CXF_DEFAULT_LOG_DIR)) quit(1) if not ...
def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None
List training dirs contained in the given dir with options and outputs similar to the regular `ls` command. The function is accessible through cxflow CLI `cxflow ls`. :param dir_: dir to be listed :param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option) :param all_...
3.472214
2.981399
1.164626
for variable in self._variables: if variable in batch_data: value = batch_data[variable] if not hasattr(value, '__iter__'): raise TypeError('Variable `{}` to be accumulated is not iterable.'.format(variable)) self._accumula...
def after_batch(self, stream_name: str, batch_data: Batch)
Extend the accumulated variables with the given batch data. :param stream_name: stream name; e.g. ``train`` or any other... :param batch_data: batch data = stream sources + model outputs :raise KeyError: if the variables to be aggregated are missing :raise TypeError: if the variable val...
3.265063
2.477293
1.317996
config = dataset = method = output_dir = None try: config_path = find_config(config_path) config = load_config(config_file=config_path, additional_args=cl_arguments) assert 'dataset' in config, '`dataset` section not present in the config' logging.debug('\tLoaded config: %...
def invoke_dataset_method(config_path: str, method_name: str, output_root: str, cl_arguments: Iterable[str]) -> None
Create the specified dataset and invoke its specified method. :param config_path: path to the config file or the directory in which it is stored :param method_name: name of the method to be invoked on the specified dataset :param cl_arguments: additional command line arguments which will update the configu...
2.721755
2.680265
1.01548
if self._num_signals == 0: logging.warning('Interrupt signal caught - training will be terminated') logging.warning('Another interrupt signal will terminate the program immediately') self._num_signals += 1 else: logging.error('Another interrupt si...
def _signal_handler(self, *_) -> None
On the first signal, increase the ``self._num_signals`` counter. Call ``sys.exit`` on any subsequent signal.
6.211443
4.458033
1.393315
logging.info('Creating output dir') # create output dir model_name = default_model_name if 'name' not in config['model']: logging.warning('\tmodel.name not found in config, defaulting to: %s', model_name) else: model_name = config['model']['name'] if not os.path.exists(out...
def create_output_dir(config: dict, output_root: str, default_model_name: str='Unnamed') -> str
Create output_dir under the given ``output_root`` and - dump the given config to YAML file under this dir - register a file logger logging to a file under this dir :param config: config to be dumped :param output_root: dir wherein output_dir shall be created :param default_model_name: name ...
2.599987
2.55605
1.017189
logging.info('Creating dataset') dataset_config = make_simple(config)['dataset'] assert 'class' in dataset_config, '`dataset.class` not present in the config' dataset_module, dataset_class = parse_fully_qualified_name(dataset_config['class']) if 'output_dir' in dataset_config: raise V...
def create_dataset(config: dict, output_dir: Optional[str]=None) -> AbstractDataset
Create a dataset object according to the given config. Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string. :param config: config dict with dataset config :param output_dir: path to the training output dir or None :return: dataset object
4.025305
3.896024
1.033183
logging.info('Creating a model') model_config = config['model'] # workaround for ruamel.yaml expansion bug; see #222 model_config = dict(model_config.items()) assert 'class' in model_config, '`model.class` not present in the config' model_module, model_class = parse_fully_qualified_name...
def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset, restore_from: Optional[str]=None) -> AbstractModel
Create a model object either from scratch of from the checkpoint in ``resume_dir``. Cxflow allows the following scenarios 1. Create model: leave ``restore_from=None`` and specify ``class``; 2. Restore model: specify ``restore_from`` which is a backend-specific path to (a directory with) the saved model. ...
3.11024
3.166408
0.982261
logging.info('Creating hooks') hooks = [] if 'hooks' in config: for hook_config in config['hooks']: if isinstance(hook_config, str): hook_config = {hook_config: {}} assert len(hook_config) == 1, 'Hook configuration must have exactly one key (fully qualifi...
def create_hooks(config: dict, model: AbstractModel, dataset: AbstractDataset, output_dir: str) -> Iterable[AbstractHook]
Create hooks specified in ``config['hooks']`` list. Hook config entries may be one of the following types: .. code-block:: yaml :caption: A hook with default args specified only by its name as a string; e.g. hooks: - LogVariables - cxflow_tensorflow.WriteTensorBoard ....
3.109516
3.090311
1.006215
output_dir = dataset = model = hooks = main_loop = None try: output_dir = create_output_dir(config=config, output_root=output_root) except Exception as ex: # pylint: disable=broad-except fallback('Failed to create output dir', ex) try: dataset = create_dataset(config=con...
def run(config: dict, output_root: str, restore_from: str=None, eval: Optional[str]=None) -> None
Run **cxflow** training configured by the passed `config`. Unique ``output_dir`` for this training is created under the given ``output_root`` dir wherein all the training outputs are saved. The output dir name will be roughly ``[model.name]_[time]``. The training procedure consists of the following steps:...
2.266219
2.105311
1.07643
try: rmtree(dir_) except OSError: logging.warning('\t\t Skipping %s due to OSError', dir_) else: logging.debug('\t\t Deleted %s', dir_)
def _safe_rmtree(dir_: str)
Wrap ``shutil.rmtree`` to inform user about (un)success.
4.033348
3.672024
1.098399
for logdir in [path.join(dir_, f) for f in listdir(dir_) if is_train_dir(path.join(dir_, f))]: for subdir in [path.join(logdir, f) for f in listdir(logdir) if path.isdir(path.join(logdir, f))]: _safe_rmtree(subdir)
def _prune_subdirs(dir_: str) -> None
Delete all subdirs in training log dirs. :param dir_: dir with training log dirs
2.808103
2.519232
1.114666
for logdir in [path.join(dir_, f) for f in listdir(dir_) if path.isdir(path.join(dir_, f))]: if not is_train_dir(logdir): _safe_rmtree(logdir) else: trace_path = path.join(logdir, CXF_TRACE_FILE) try: epochs_done = TrainingTrace.from_file(trac...
def _prune(dir_: str, epochs: int) -> None
Delete all training dirs with incomplete training artifacts or with less than specified epochs done. :param dir_: dir with training log dirs :param epochs: minimum number of finished epochs to keep the training logs :return: number of log dirs pruned
3.365507
3.093907
1.087785
if dir_ == CXF_DEFAULT_LOG_DIR and not path.exists(CXF_DEFAULT_LOG_DIR): print('The default log directory `{}` does not exist.\n' 'Consider specifying the directory to be listed as an argument.'.format(CXF_DEFAULT_LOG_DIR)) quit(1) if not path.exists(dir_): print('Sp...
def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None
Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`. :param dir_: dir to be pruned :param epochs: minimum number of finished epochs to keep the training logs :param subdirs: delete subdirs in training log dirs
3.763792
3.426805
1.098339
self._load_models() return chain.from_iterable(map(lambda m: m.output_names, self._models))
def output_names(self) -> Iterable[str]
List of model output names.
4.666651
4.359523
1.07045
if train: raise ValueError('Ensemble model cannot be trained.') self._load_models() # run all the models in-order current_batch = dict(copy.deepcopy(batch)) for model in self._models: current_batch.update(model.run(current_batch, False, None)) ...
def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch
Run all the models in-order and return accumulated outputs. N-th model is fed with the original inputs and outputs of all the models that were run before it. .. warning:: :py:class:`Sequence` model can not be trained. :param batch: batch to be processed :param train: ``Tru...
4.676033
4.386025
1.066121
for stream_name in epoch_data.keys(): stream_data = epoch_data[stream_name] variables = self._variables if self._variables is not None else stream_data.keys() for variable in variables: if variable not in stream_data: raise KeyErro...
def _log_variables(self, epoch_data: EpochData)
Log variables from the epoch data. .. warning:: At the moment, only scalars and dicts of scalars are properly formatted and logged. Other value types are ignored by default. One may set ``on_unknown_type`` to ``str`` in order to log all the variables anyways. :param ep...
1.972462
1.791961
1.100728
''' This returns the coordinate just past the last aligned base. This matches the behavior of pysam's reference_end method ''' reference_end = reference_start # iterate through cigartuple for i in xrange(len(cigar)): k, n = cigar[i] ...
def get_reference_end_from_cigar(reference_start, cigar)
This returns the coordinate just past the last aligned base. This matches the behavior of pysam's reference_end method
5.201782
3.103361
1.676177
''' Determine which SplitPiece is the leftmost based on the side of the longest clipping operation ''' if self.is_left_clip(a.cigar): self.query_left = b self.query_right = a else: self.query_left = a self.query_right = b
def set_order_by_clip(self, a, b)
Determine which SplitPiece is the leftmost based on the side of the longest clipping operation
8.365683
3.150931
2.654987
''' whether the left side of the read (w/ respect to reference) is clipped. Clipping side is determined as the side with the longest clip. Adjacent clipping operations are not considered ''' left_tuple = cigar[0] right_tuple = cigar[-1] left_clipped = self...
def is_left_clip(self, cigar)
whether the left side of the read (w/ respect to reference) is clipped. Clipping side is determined as the side with the longest clip. Adjacent clipping operations are not considered
3.714971
1.965673
1.889923
arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays. med = np.median(arr) return np.median(np.abs(arr - med))
def mad(arr)
Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation
3.609717
4.087406
0.883132
arg2 = self.argstreams[1] arg3 = self.argstreams[2] return not (isinstance(arg2, InMemStream) and isinstance(arg3, InMemStream) and ((arg2.auto_close and arg3.auto_close) or ( arg2.state == StreamState.completed and ...
def _is_streaming_request(self)
check request is stream request or not
4.397078
3.928567
1.119257
if self.is_streaming_request: # not retry for streaming request return False retry_flag = self.headers.get('re', retry.DEFAULT) if retry_flag == retry.NEVER: return False if isinstance(error, StreamClosedError): return True ...
def should_retry_on_error(self, error)
rules for retry :param error: ProtocolException that returns from Server
4.737093
4.589998
1.032047
assert service_module, 'service_module is required' service = service or '' # may be blank for non-hyperbahn use cases if not thrift_service_name: thrift_service_name = service_module.__name__.rsplit('.', 1)[-1] method_names = get_service_methods(service_module.Iface) def init( ...
def client_for(service, service_module, thrift_service_name=None)
Build a synchronous client class for the given Thrift service. The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registered with Hyperbahn under the name "comment", here's how this might be ...
3.187078
3.086388
1.032624
def call(self, *args, **kwargs): if not self.threadloop.is_ready(): self.threadloop.start() return self.threadloop.submit( getattr(self.async_thrift, method_name), *args, **kwargs ) return call
def generate_method(method_name)
Generate a method for a given Thrift service. Uses the provided TChannelSyncClient's threadloop in order to convert RPC calls to concurrent.futures :param method_name: Method being called. :return: A method that invokes the RPC using TChannelSyncClient
4.848136
3.807741
1.273231
assert stream, "stream is required" chunks = [] chunk = yield stream.read() while chunk: chunks.append(chunk) chunk = yield stream.read() raise tornado.gen.Return(b''.join(chunks))
def read_full(stream)
Read the full contents of the given stream into memory. :return: A future containing the complete stream contents.
3.502685
3.588741
0.976021
if isinstance(s, Stream): return s if s is None: stream = InMemStream() stream.close() # we don't intend to write anything return stream if isinstance(s, unicode): s = s.encode('utf-8') if isinstance(s, bytearray): s = bytes(s) if isinstance(s...
def maybe_stream(s)
Ensure that the given argument is a stream.
3.476686
3.33568
1.042272
message = ErrorMessage( id=protocol_exception.id, code=protocol_exception.code, tracing=protocol_exception.tracing, description=protocol_exception.description, ) return message
def build_raw_error_message(protocol_exception)
build protocol level error message based on Error object
3.584432
3.539193
1.012782
request.flags = FlagsType.none if is_completed else FlagsType.fragment # TODO decide what need to pass from request if request.state == StreamState.init: message = CallRequestMessage( flags=request.flags, ttl=request.ttl * 1000, ...
def build_raw_request_message(self, request, args, is_completed=False)
build protocol level message based on request and args. request object contains meta information about outgoing request. args are the currently chunk data from argstreams is_completed tells the flags of the message :param request: Request :param args: array of arg streams ...
3.827713
3.551501
1.077773
response.flags = FlagsType.none if is_completed else FlagsType.fragment # TODO decide what need to pass from request if response.state == StreamState.init: message = CallResponseMessage( flags=response.flags, code=response.code, ...
def build_raw_response_message(self, response, args, is_completed=False)
build protocol level message based on response and args. response object contains meta information about outgoing response. args are the currently chunk data from argstreams is_completed tells the flags of the message :param response: Response :param args: array of arg streams ...
3.809896
3.488093
1.092257
args = self.prepare_args(message) # TODO decide what to pass to Request from message req = Request( flags=message.flags, ttl=message.ttl / 1000.0, tracing=message.tracing, service=message.service, headers=message.headers, ...
def build_request(self, message)
Build inbound request object from protocol level message info. It is allowed to take incompleted CallRequestMessage. Therefore the created request may not contain whole three arguments. :param message: CallRequestMessage :return: request object
5.971936
5.877263
1.016108
args = self.prepare_args(message) # TODO decide what to pass to Response from message res = Response( flags=message.flags, code=message.code, headers=message.headers, checksum=message.checksum, argstreams=args, id...
def build_response(self, message)
Build response object from protocol level message info It is allowed to take incompleted CallResponseMessage. Therefore the created request may not contain whole three arguments. :param message: CallResponseMessage :return: response object
6.945457
6.60809
1.051054
context = None if message.message_type in [Types.CALL_REQ, Types.CALL_RES]: self.verify_message(message) context = self.build_context(message) # streaming message if message.flags == common.FlagsType.fragment:...
def build(self, message)
buffer all the streaming messages based on the message id. Reconstruct all fragments together. :param message: incoming message :return: next complete message or None if streaming is not done
3.858809
3.795999
1.016547
if message.message_type in [Types.CALL_RES, Types.CALL_REQ, Types.CALL_REQ_CONTINUE, Types.CALL_RES_CONTINUE]: rw = RW[message.message_type] payload_space = (common.MAX_PA...
def fragment(self, message)
Fragment message based on max payload size note: if the message doesn't need to fragment, it will return a list which only contains original message itself. :param message: raw message :return: list of messages whose sizes <= max payload size
4.614045
4.533188
1.017837
if verify_checksum( message, self.in_checksum.get(message.id, 0), ): self.in_checksum[message.id] = message.checksum[1] if message.flags == FlagsType.none: self.in_checksum.pop(message.id) else: self.in...
def verify_message(self, message)
Verify the checksum of the message.
4.384924
4.111405
1.066527
assert rws is not None if len(rws) == 1 and isinstance(rws[0], list): # In case someone does chain([l0, l1, ...]) rws = rws[0] return ChainReadWriter(rws)
def chain(*rws)
Build a ReadWriter from the given list of ReadWriters. .. code-block:: python chain( number(1), number(8), len_prefixed_string(number(2)), ) # == n1:1 n2:8 s~2 Reads/writes from the given ReadWriters in-order. Returns lists of values in the same order ...
4.431909
5.19194
0.853613
s = stream.read(num) slen = len(s) if slen != num: raise ReadError( "Expected %d bytes but got %d bytes." % (num, slen) ) return s
def take(self, stream, num)
Read the given number of bytes from the stream. :param stream: stream to read from :param num: number of bytes to read :raises ReadError: if the stream did not yield the exact number of bytes expected
3.164449
2.841121
1.113803
methods = inspect.getmembers(iface, predicate=inspect.ismethod) return set( name for (name, method) in methods if not name.startswith('__') )
def get_service_methods(iface)
Get a list of methods defined in the interface for a Thrift service. :param iface: The Thrift-generated Iface class defining the interface for the service. :returns: A set containing names of the methods defined for the service.
3.15468
4.706827
0.670235
warnings.simplefilter('default') warnings.warn(message, category=DeprecationWarning) warnings.resetwarnings()
def deprecate(message)
Loudly prints warning.
3.51654
3.720855
0.945089
def decorator(fn): @functools.wraps(fn) def new_fn(*args, **kwargs): deprecate(message) return fn(*args, **kwargs) return new_fn return decorator
def deprecated(message)
Warn every time a fn is called.
2.191399
2.036007
1.076322
# TODO replace with more specific exceptions # assert service, 'service is required' # assert path, 'path is required' # Backwards compatibility for callers passing in service name as first arg. if not path.endswith('.thrift'): service, path = path, service module = thriftrw.load(...
def load(path, service=None, hostport=None, module_name=None)
Loads the Thrift file at the specified path. The file is compiled in-memory and a Python module containing the result is returned. It may be used with ``TChannel.thrift``. For example, .. code-block:: python from tchannel import TChannel, thrift # Load our server's interface definition. ...
6.559212
6.156335
1.065441
def decorator(method, handler): if not method: method = handler.__name__ function = getattr(service, method, None) assert function, ( 'Service "%s" does not define method "%s"' % (service.name, method) ) assert not function.oneway dispa...
def register(dispatcher, service, handler=None, method=None)
:param dispatcher: RequestDispatcher against which the new endpoint will be registered. :param Service service: Service object representing the service whose endpoint is being registered. :param handler: A function implementing the given Thrift function. :param method: ...
4.368715
3.9775
1.098357
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl( sock.fileno(), 0x8915, struct.pack('256s', interface[:15]) )[20:24] )
def interface_ip(interface)
Determine the IP assigned to us by the given network interface.
1.635522
1.626305
1.005667
ip = socket.gethostbyname(socket.gethostname()) if ip.startswith('127.'): # Check eth0, eth1, eth2, en0, ... interfaces = [ i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3) ] # :( for interface in interfaces: try: ip = int...
def local_ip()
Get the local network IP of this machine
3.630116
3.581563
1.013557
assert service_module, 'service_module is required' service = service or '' # may be blank for non-hyperbahn use cases if not thrift_service_name: thrift_service_name = service_module.__name__.rsplit('.', 1)[-1] method_names = get_service_methods(service_module.Iface) def new(cls, tc...
def client_for(service, service_module, thrift_service_name=None)
Build a client class for the given Thrift service. The generated class accepts a TChannel and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registered with Hyperbahn under the name "comment", here's how this may be used: .. code-block...
3.581818
3.47062
1.03204
assert service_module assert service_name assert method_name args_type = getattr(service_module, method_name + '_args') result_type = getattr(service_module, method_name + '_result', None) serializer = ThriftSerializer(result_type) # oneway not currently supported # TODO - write te...
def generate_method(service_module, service_name, method_name)
Generate a method for the given Thrift service. :param service_module: Thrift-generated service module :param service_name: Name of the Thrift service :param method_name: Method being called
4.22488
4.205515
1.004605
# Prefer incoming connections over outgoing connections. if self.connections: # First value is an incoming connection future = gen.Future() future.set_result(self.connections[0]) return future if self._connecting: # If we're i...
def connect(self)
Get a connection to this peer. If an connection to the peer already exists (either incoming or outgoing), that's returned. Otherwise, a new outgoing connection to this peer is created. :return: A future containing a connection to this host.
4.667859
4.420701
1.055909
assert conn, "conn is required" conn.set_outbound_pending_change_callback(self._on_conn_change) self.connections.append(conn) self._set_on_close_cb(conn) self._on_conn_change()
def register_outgoing_conn(self, conn)
Add outgoing connection into the heap.
5.324296
5.236023
1.016859
assert conn, "conn is required" conn.set_outbound_pending_change_callback(self._on_conn_change) self.connections.appendleft(conn) self._set_on_close_cb(conn) self._on_conn_change()
def register_incoming_conn(self, conn)
Add incoming connection into the heap.
5.856437
5.531306
1.05878
# Outgoing connections are on the right return list( dropwhile(lambda c: c.direction != OUTGOING, self.connections) )
def outgoing_connections(self)
Returns a list of all outgoing connections for this peer.
10.960436
9.210374
1.19001
# Incoming connections are on the left. return list( takewhile(lambda c: c.direction == INCOMING, self.connections) )
def incoming_connections(self)
Returns a list of all incoming connections for this peer.
8.675994
6.824643
1.271274
blacklist = blacklist or set() peer = None connection = None while connection is None: peer = self._choose(blacklist) if not peer: raise NoAvailablePeerError( "Can't find an available peer for '%s'" % self.service ...
def _get_peer_connection(self, blacklist=None)
Find a peer and connect to it. Returns a ``(peer, connection)`` tuple. Raises ``NoAvailablePeerError`` if no healthy peers are found. :param blacklist: If given, a set of hostports for peers that we must not try.
3.615108
3.237301
1.116705
# find a peer connection # If we can't find available peer at the first time, we throw # NoAvailablePeerError. Later during retry, if we can't find available # peer, we throw exceptions from retry not NoAvailablePeerError. peer, connection = yield self._get_peer_connect...
def send( self, arg1, arg2, arg3, headers=None, retry_limit=None, ttl=None, )
Make a request to the Peer. :param arg1: String or Stream containing the contents of arg1. If None, an empty stream is used. :param arg2: String or Stream containing the contents of arg2. If None, an empty stream is used. :param arg3: ...
5.204395
5.11831
1.016819
try: for peer in self._peers.values(): peer.close() finally: self._peers = {} self._resetting = False
def clear(self)
Reset this PeerGroup. This closes all connections to all known peers and forgets about these peers. :returns: A Future that resolves with a value of None when the operation has finished
5.387828
5.168099
1.042516
assert hostport, "hostport is required" peer = self._peers.pop(hostport, None) peer_in_heap = peer and peer.index != -1 if peer_in_heap: self.peer_heap.remove_peer(peer) return peer
def remove(self, hostport)
Delete the Peer for the given host port. Does nothing if a matching Peer does not exist. :returns: The removed Peer
4.672421
5.170458
0.903676
assert hostport, "hostport is required" assert isinstance(hostport, basestring), "hostport must be a string" if hostport not in self._peers: self._add(hostport) return self._peers[hostport]
def get(self, hostport)
Get a Peer for the given destination. A new Peer is added to the peer heap and returned if one does not already exist for the given host-port. Otherwise, the existing Peer is returned.
2.889843
2.646415
1.091984
peer = self.peer_class( tchannel=self.tchannel, hostport=hostport, on_conn_change=self._update_heap, ) peer.rank = self.rank_calculator.get_rank(peer) self._peers[peer.hostport] = peer self.peer_heap.add_and_shuffle(peer)
def _add(self, hostport)
Creates a peer from the hostport and adds it to the peer heap
5.83854
4.654508
1.254384
rank = self.rank_calculator.get_rank(peer) if rank == peer.rank: return peer.rank = rank self.peer_heap.update_peer(peer)
def _update_heap(self, peer)
Recalculate the peer's rank and update itself in the peer heap.
5.199243
3.464328
1.500794
assert hostport, "hostport is required" if hostport not in self._peers: # Add a peer directly from a hostport, do NOT add it to the peer # heap peer = self.peer_class( tchannel=self.tchannel, hostport=hostport, ) ...
def _get_isolated(self, hostport)
Get a Peer for the given destination for a request. A new Peer is added and returned if one does not already exist for the given host-port. Otherwise, the existing Peer is returned. **NOTE** new peers will not be added to the peer heap.
5.425991
4.27226
1.270052
return PeerClientOperation( peer_group=self, service=service, hostport=hostport, **kwargs)
def request(self, service, hostport=None, **kwargs)
Initiate a new request through this PeerGroup. :param hostport: If specified, requests will be sent to the specific host. Otherwise, a known peer will be picked at random. :param service: Name of the service being called. Defaults to an empty string.
8.032767
8.166477
0.983627
blacklist = blacklist or set() if hostport: return self._get_isolated(hostport) return self.peer_heap.smallest_peer( (lambda p: p.hostport not in blacklist and not p.is_ephemeral), )
def choose(self, hostport=None, blacklist=None)
Choose a Peer that matches the given criteria. :param hostport: Specifies that the returned Peer must be for the given host-port. Without this, all peers managed by this PeerGroup are candidates. :param blacklist: Peers on the blacklist won't be chosen. ...
8.648661
9.27278
0.932693
assert is_future(future), 'you forgot to pass a future' def decorator(f): @wraps(f) def new_f(*args, **kwargs): try: return f(*args, **kwargs) except Exception: future.set_exc_info(sys.exc_info()) return new_f return de...
def fail_to(future)
A decorator for function callbacks to catch uncaught non-async exceptions and forward them to the given future. The primary use for this is to catch exceptions in async callbacks and propagate them to futures. For example, consider, .. code-block:: python answer = Future() def on_don...
2.71701
3.441341
0.789521
if index < len(context.argstreams): arg = "" chunk = yield context.argstreams[index].read() while chunk: arg += chunk chunk = yield context.argstreams[index].read() raise tornado.gen.Return(arg) else: raise TChannelError()
def get_arg(context, index)
get value from arg stream in async way
4.715179
3.657384
1.289222
io_loop = IOLoop.current() new_hole = Future() new_put = Future() new_put.set_result(new_hole) with self._lock: self._put, put = new_put, self._put answer = Future() def _on_put(future): if future.exception(): # pragma: no cov...
def put(self, value)
Puts an item into the queue. Returns a Future that resolves to None once the value has been accepted by the queue.
4.014313
3.871248
1.036956
new_get = Future() with self._lock: if not self._get.done(): raise QueueEmpty get, self._get = self._get, new_get hole = get.result() if not hole.done(): # Restore the unfinished hole. new_get.set_result(hole) ...
def get_nowait(self)
Returns a value from the queue without waiting. Raises ``QueueEmpty`` if no values are available right now.
4.673251
4.712015
0.991773
io_loop = IOLoop.current() new_get = Future() with self._lock: get, self._get = self._get, new_get answer = Future() def _on_node(future): if future.exception(): # pragma: no cover (never happens) return answer.set_exc_info(fut...
def get(self)
Gets the next item from the queue. Returns a Future that resolves to the next item once it is available.
2.807838
2.729111
1.028847
new_args = [] key_length = 2 # 2bytes for size for i, arg in enumerate(self.args): if space_left >= key_length: space_left -= key_length if arg is not None: arg_length = len(arg) if space_left < arg_le...
def fragment(self, space_left, fragment_msg)
Streaming Message got fragmented based on payload size. All the data within space_left will be kept. All the rest will be shifted to next fragment message. :param space_left: space left for current frame :param fragment_msg: the type is either CallRequest...
2.940918
2.865662
1.026262
# if none then give empty Response if mixed is None: return Response() # if not Response, then treat like body if not isinstance(mixed, Response): return Response(mixed) # it's already a Response return mixed
def response_from_mixed(mixed)
Create Response from mixed input.
6.507653
5.746977
1.132361
if event_type is not None: assert type(event_type) is int, "register hooks with int values" return self.hooks[event_type].append(hook) for event_type in EventType._fields: func = getattr(hook, event_type, None) if callable(func): ...
def register_hook(self, hook, event_type=None)
If ``event_type`` is provided, then ``hook`` will be called whenever that event is fired. If no ``event_type`` is specifid, but ``hook`` implements any methods with names matching an event hook, then those will be registered with their corresponding events. This allows for more stateful...
3.550079
3.863645
0.918842
# heapify n = h.size() for i in six.moves.range(int(math.floor(n/2)) - 1, -1, -1): down(h, i, n)
def init(h)
Initialize existing object into the heap.
3.641186
4.2253
0.861758
h.push(x) up(h, h.size()-1)
def push(h, x)
Push a new value into heap.
7.370098
5.405749
1.363381
n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
def pop(h)
Pop the heap value from the heap.
5.321638
3.76052
1.415133
n = h.size() - 1 if n != i: h.swap(i, n) down(h, i, n) up(h, i) return h.pop()
def remove(h, i)
Remove the item at position i of the heap.
4.93756
3.471289
1.422399
down(h, i, h.size()) up(h, i)
def fix(h, i)
Rearrange the heap after the item at position i got updated.
11.581713
11.049464
1.04817
n = heap.size() # items contains indexes of items yet to be checked. items = deque([0]) while items: current = items.popleft() if current >= n: continue if predicate(heap.peek(current)): return current child1 = 2 * current + 1 child...
def smallest(heap, predicate)
Finds the index of the smallest item in the heap that matches the given predicate. :param heap: Heap on which this search is being performed. :param predicate: Function that accepts an item from the heap and returns true or false. :returns: Index of the first item for which ``pr...
3.160834
3.244645
0.974169
if span is None: return common.random_tracing() # noinspection PyBroadException try: carrier = {} span.tracer.inject(span, ZIPKIN_SPAN_FORMAT, carrier) tracing = Tracing(span_id=carrier['span_id'], trace_id=carrier['trace_id'], ...
def span_to_tracing_field(span)
Inject the span into Trace field, if Zipkin format is supported :param span: OpenTracing Span
4.723425
4.366578
1.081722
if trace is None: trace = default_trace trace = trace() if callable(trace) else trace if trace is False and span: span.set_tag(tags.SAMPLING_PRIORITY, 0)
def apply_trace_flag(span, trace, default_trace)
If ``trace`` (or ``default_trace``) is False, disables tracing on ``span``. :param span: :param trace: :param default_trace: :return:
3.120228
3.532976
0.883173
# noinspection PyBroadException try: # Currently Java does not populate Tracing field, so do not # mistaken it for a real trace ID. if request.tracing.trace_id: context = self.tracer.extract( format=ZIPKIN_SPAN_FORMAT, ...
def start_basic_span(self, request)
Start tracing span from the protocol's `tracing` fields. This will only work if the `tracer` supports Zipkin-style span context. :param request: inbound request :type request: tchannel.tornado.request.Request
6.031137
5.471188
1.102345
parent_context = None # noinspection PyBroadException try: if headers and hasattr(headers, 'iteritems'): tracing_headers = { k[len(TRACING_KEY_PREFIX):]: v for k, v in headers.iteritems() if k.starts...
def start_span(self, request, headers, peer_host, peer_port)
Start a new server-side span. If the span has already been started by `start_basic_span`, this method only adds baggage from the headers. :param request: inbound tchannel.tornado.request.Request :param headers: dictionary containing parsed application headers :return:
2.322868
2.298594
1.01056
return { TIMEOUT: TimeoutError, CANCELED: CanceledError, BUSY: BusyError, DECLINED: DeclinedError, UNEXPECTED_ERROR: UnexpectedError, BAD_REQUEST: BadRequestError, NETWORK_ERROR: NetworkError, UNHEALTHY: Unh...
def from_code(cls, code, **kw)
Construct a ``TChannelError`` instance from an error code. This will return the appropriate class type for the given code.
4.462851
3.888222
1.147787
logging.getLogger().setLevel(logging.DEBUG) logging.info('Python Tornado Crossdock Server Starting ...') tracer = Tracer( service_name='python', reporter=NullReporter(), sampler=ConstSampler(decision=True)) opentracing.tracer = tracer tchannel = TChannel(name='python',...
def serve()
main entry point
4.553303
4.532699
1.004546
if not service: service = service_module.__name__.rsplit('.', 1)[-1] if not method: method = handler.__name__ assert service, 'A service name could not be determined' assert method, 'A method name could not be determined' assert hasattr(service_module.Iface, method), ( ...
def register(dispatcher, service_module, handler, method=None, service=None)
Registers a Thrift service method with the given RequestDispatcher. .. code-block:: python # For, # # service HelloWorld { string hello(1: string name); } import tchannel.thrift import HelloWorld def hello(request, response): name = request.args.name...
3.481699
3.34718
1.040189