code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
r
b = event.current_buffer
# When already navigating through completions, select the next one.
if b.complete_state:
b.complete_next()
else:
event.cli.start_completion(insert_common_part=True, select_first=False) | def generate_completions(event) | r"""
Tab-completion: where the first tab completes the common suffix and the
second tab lists all the completions. | 9.285877 | 9.267842 | 1.001946 |
# Request completions.
b = event.current_buffer
if b.completer is None:
return
complete_event = CompleteEvent(completion_requested=True)
completions = list(b.completer.get_completions(b.document, complete_event))
# Calculate the common suffix.
common_suffix = get_common_complet... | def display_completions_like_readline(event) | Key binding handler for readline-style tab completion.
This is meant to be as similar as possible to the way how readline displays
completions.
Generate the completions immediately (blocking) and display them above the
prompt in columns.
Usage::
# Call this handler when 'Tab' has been pre... | 3.375026 | 3.586486 | 0.94104 |
from prompt_toolkit.shortcuts import create_confirm_application
assert isinstance(completions, list)
# Get terminal dimensions.
term_size = cli.output.get_size()
term_width = term_size.columns
term_height = term_size.rows
# Calculate amount of required columns/rows for displaying the
... | def _display_completions_like_readline(cli, completions) | Display the list of completions in columns above the prompt.
This will ask for a confirmation if there are too many completions to fit
on a single page and provide a paginator to walk through them. | 3.247398 | 3.216888 | 1.009485 |
from prompt_toolkit.shortcuts import create_prompt_application
registry = Registry()
@registry.add_binding(' ')
@registry.add_binding('y')
@registry.add_binding('Y')
@registry.add_binding(Keys.ControlJ)
@registry.add_binding(Keys.ControlI) # Tab.
def _(event):
event.cli.se... | def _create_more_application() | Create an `Application` instance that displays the "--MORE--". | 2.959003 | 2.676876 | 1.105394 |
assert isinstance(callbacks, EventLoopCallbacks)
# Create reader class.
stdin_reader = PosixStdinReader(stdin.fileno())
if self.closed:
raise Exception('Event loop already closed.')
inputstream = InputStream(callbacks.feed_key)
try:
# ... | def run_as_coroutine(self, stdin, callbacks) | The input 'event loop'. | 4.468292 | 4.351898 | 1.026746 |
if not isinstance(bool_or_filter, (bool, SimpleFilter)):
raise TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter) | def to_simple_filter(bool_or_filter) | Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter. | 3.231131 | 3.394107 | 0.951983 |
if not isinstance(bool_or_filter, (bool, CLIFilter)):
raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter) | def to_cli_filter(bool_or_filter) | Accept both booleans and CLIFilters as input and
turn it into a CLIFilter. | 3.533571 | 3.293222 | 1.072983 |
# By default we choose a rather small chunk size, because reading
# big amounts of input at once, causes the event loop to process
# all these key bindings also at once without going back to the
# loop. This will make the application feel unresponsive.
if... | def read(self, count=1024) | Read the input and return it as a string.
Return the text. Note that this can return an empty string, even when
the input stream was not yet closed. This means that something went
wrong during the decoding. | 10.745376 | 11.226556 | 0.957139 |
lines = []
while data:
match = self._line_end_re.search(data)
if match is None:
chunk = data
else:
chunk = data[:match.end()]
data = data[len(chunk):]
if self._buf and self._buf[-1].endswith(b('\r')) a... | def add_string(self, data) | Process some data splitting it into complete lines and buffering the rest
Args:
data: A `str` in Python 2 or `bytes` in Python 3
Returns:
list of complete lines ending with a carriage return (eg. a progress
bar) or a newline. | 4.750025 | 4.340554 | 1.094336 |
if cur_time is None:
cur_time = time.time()
lines = self._line_buffer.add_string(message)
for line in lines:
#print('ts line', repr(line))
timestamp = ''
if self._prepend_timestamp:
timestamp = datetime.datetime.utcfromtime... | def write(self, message, cur_time=None) | Write some text to the pusher.
Args:
message: a string to push for this file.
cur_time: used for unit testing. override line timestamp. | 4.576999 | 4.394819 | 1.041453 |
last_step = 0
row = {}
buffer = []
last_row = {}
for summary in tf.train.summary_iterator(path):
parsed = tf_summary_to_dict(summary)
if last_step != parsed["tensorflow_step"]:
step += 1
last_step = parsed["tensorflow_step"]
# TODO: handle tim... | def stream_tfevents(path, file_api, step=0) | Parses and streams a tfevents file to the server | 5.744522 | 5.910687 | 0.971887 |
user_process_pid = args['pid']
stdout_master_fd = args['stdout_master_fd']
stderr_master_fd = args['stderr_master_fd']
try:
run = wandb.wandb_run.Run.from_environment_or_defaults()
run.enable_logging()
api = wandb.apis.InternalApi()
api.set_current_run_id(run.id)
... | def headless(args) | Headless mode is where we start a monitoring / syncing
process to watch an already-running user process. It's like
`wandb run` for a user process that has already started.
The user process that calls this waits for a signal that
everything is ready, which is sent at the end of rm.wrap_existing_process | 4.297045 | 3.590833 | 1.196671 |
run = wandb.wandb_run.Run.from_environment_or_defaults()
run.enable_logging()
api = wandb.apis.InternalApi()
api.set_current_run_id(run.id)
# TODO: better failure handling
root = api.git.root
# handle non-git directories
if not root:
root = os.path.abspath(os.getcwd())
... | def agent_run(args) | A version of `wandb run` that the agent uses to run things. | 4.430546 | 4.21315 | 1.0516 |
global Summary, Event
if tensorboardX:
tensorboard_module = "tensorboardX.writer"
if tensorflow_loaded:
wandb.termlog(
"Found TensorboardX and tensorflow, pass tensorboardX=False to patch regular tensorboard.")
from tensorboardX.proto.summary_pb2 import S... | def patch(save=True, tensorboardX=tensorboardX_loaded) | Monkeypatches tensorboard or tensorboardX so that all events are logged to tfevents files and wandb.
We save the tfevents files and graphs to wandb by default.
Arguments:
save, default: True - Passing False will skip sending events.
tensorboardX, default: True if module can be imported - You ca... | 4.352513 | 4.206951 | 1.0346 |
values = {}
if isinstance(tf_summary_str_or_pb, Summary):
summary_pb = tf_summary_str_or_pb
elif isinstance(tf_summary_str_or_pb, Event):
summary_pb = tf_summary_str_or_pb.summary
values["global_step"] = tf_summary_str_or_pb.step
values["_timestamp"] = tf_summary_str_or_... | def tf_summary_to_dict(tf_summary_str_or_pb, namespace="") | Convert a Tensorboard Summary to a dictionary
Accepts either a tensorflow.summary.Summary
or one encoded as a string. | 2.138667 | 2.143591 | 0.997703 |
# When the search buffer has focus, take that text.
if self.preview_search(cli) and cli.buffers[self.search_buffer_name].text:
return cli.buffers[self.search_buffer_name].text
# Otherwise, take the text of the last active search.
else:
return self.get_sea... | def _get_search_text(self, cli) | The text we are searching for. | 5.508532 | 5.161973 | 1.067137 |
# Try for the character under the cursor.
if document.current_char and document.current_char in self.chars:
pos = document.find_matching_bracket_position(
start_pos=document.cursor_position - self.max_cursor_distance,
end_pos=document.cursor_p... | def _get_positions_to_highlight(self, document) | Return a list of (row, col) tuples that need to be highlighted. | 2.738892 | 2.568279 | 1.066431 |
def get_static_tokens(cli):
return [(token, text)]
return cls(get_static_tokens) | def static(cls, text, token=Token) | Create a :class:`.BeforeInput` instance that always inserts the same
text. | 8.175682 | 8.085131 | 1.0112 |
if not self.connection:
self.connect()
start = time.time()
conn, _, err = select([self.connection], [], [
self.connection], max_seconds)
try:
if len(err) > 0:
raise socket.error("Couldn't open socket")
... | def listen(self, max_seconds=30) | Waits to receive up to two bytes for up to max_seconds | 2.943886 | 2.938873 | 1.001706 |
res = super()._calc_adu()
self.ensure_one()
dafs_to_apply = self.env['ddmrp.adjustment'].search(
self._daf_to_apply_domain())
if dafs_to_apply:
daf = 1
values = dafs_to_apply.mapped('value')
for val in values:
daf *... | def _calc_adu(self) | Apply DAFs if existing for the buffer. | 4.407499 | 3.980065 | 1.107394 |
self.env['ddmrp.adjustment.demand'].search([]).unlink()
super().cron_ddmrp_adu(automatic)
today = fields.Date.today()
for op in self.search([]).filtered('extra_demand_ids'):
to_add = sum(op.extra_demand_ids.filtered(
lambda r: r.date_start <= today <=... | def cron_ddmrp_adu(self, automatic=False) | Apply extra demand originated by Demand Adjustment Factors to
components after the cron update of all the buffers. | 5.325033 | 4.698447 | 1.13336 |
res = super()._compute_dlt()
for rec in self:
ltaf_to_apply = self.env['ddmrp.adjustment'].search(
rec._ltaf_to_apply_domain())
if ltaf_to_apply:
ltaf = 1
values = ltaf_to_apply.mapped('value')
for val in va... | def _compute_dlt(self) | Apply Lead Time Adj Factor if existing | 4.618146 | 3.819719 | 1.209028 |
if previous_key:
return u"{}{}{}".format(previous_key, separator, new_key)
else:
return new_key | def _construct_key(previous_key, separator, new_key) | Returns the new_key if no previous key exists, otherwise concatenates
previous key, separator, and new_key
:param previous_key:
:param separator:
:param new_key:
:return: a string if previous_key exists and simply passes through the
new_key otherwise | 2.579778 | 3.015475 | 0.855513 |
assert isinstance(nested_dict, dict), "flatten requires a dictionary input"
assert isinstance(separator, six.string_types), "separator must be string"
# This global dictionary stores the flattened keys and values and is
# ultimately returned
flattened_dict = dict()
def _flatten(object_, k... | def flatten(nested_dict, separator="_", root_keys_to_ignore=set()) | Flattens a dictionary with nested structure to a dictionary with no
hierarchy
Consider ignoring keys that you are not interested in to prevent
unnecessary processing
This is specially true for very deep objects
:param nested_dict: dictionary we want to flatten
:param separator: string to separa... | 3.101415 | 3.144879 | 0.986179 |
_unflatten_asserts(flat_dict, separator)
# This global dictionary is mutated and returned
unflattened_dict = dict()
def _unflatten(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
for item in flat_dict:
_unflatt... | def unflatten(flat_dict, separator='_') | Creates a hierarchical dictionary from a flattened dictionary
Assumes no lists are present
:param flat_dict: a dictionary with no hierarchy
:param separator: a string that separates keys
:return: a dictionary with hierarchy | 2.815125 | 3.084166 | 0.912767 |
_unflatten_asserts(flat_dict, separator)
# First unflatten the dictionary assuming no lists exist
unflattened_dict = unflatten(flat_dict, separator)
def _convert_dict_to_list(object_, parent_object, parent_object_key):
if isinstance(object_, dict):
for key in object_:
... | def unflatten_list(flat_dict, separator='_') | Unflattens a dictionary, first assuming no lists exist and then tries to
identify lists and replaces them
This is probably not very efficient and has not been tested extensively
Feel free to add test cases or rewrite the logic
Issues that stand out to me:
- Sorting all the keys in the dictionary, wh... | 2.919977 | 2.842197 | 1.027366 |
return all((True if second - first == 1 else False
for first, second in zip(list_[:-1], list_[1:]))) | def check_if_numbers_are_consecutive(list_) | Returns True if numbers in the list are consecutive
:param list_: list of integers
:return: Boolean | 4.753451 | 6.548018 | 0.725937 |
'''
Strips all color codes from a text.
'''
members = [attr for attr in Colors.__dict__.keys() if not attr.startswith( "__" ) and not attr == 'strip']
for c in members:
text = text.replace( vars( Colors )[c], '' )
return text | def strip( text ) | Strips all color codes from a text. | 6.439471 | 4.884866 | 1.318249 |
'''
get/set the verbosity level.
The verbosity level filters messages that are output
to the console. Only messages tagged with a verbosity
less-than-or-equal-to the class verbosity are output.
This does not affect output to non-console devices
such as files or ... | def verbosity(self, *args) | get/set the verbosity level.
The verbosity level filters messages that are output
to the console. Only messages tagged with a verbosity
less-than-or-equal-to the class verbosity are output.
This does not affect output to non-console devices
such as files or remote sockets.
... | 7.755634 | 1.886897 | 4.110259 |
'''
get/set the tag string itself.
If called with non-zero length argument, will toggle the
internal b_tag flag to True.
The tagstring, if flagged TRUE and non-zero length, will
prepend each output log line. In this manner, it's possible
to post-filter log files... | def tagstring(self, *args) | get/set the tag string itself.
If called with non-zero length argument, will toggle the
internal b_tag flag to True.
The tagstring, if flagged TRUE and non-zero length, will
prepend each output log line. In this manner, it's possible
to post-filter log files for specific tags.
... | 8.420909 | 1.646601 | 5.114117 |
'''
get/set the tag flag.
The tag flag toggles the most basic prepending to each log
output. The idea with the tagging text is to provide a
simple mechanism by which a log output can be filtered/parsed
for specific outputs.
tag(): returns the c... | def tag(self, *args) | get/set the tag flag.
The tag flag toggles the most basic prepending to each log
output. The idea with the tagging text is to provide a
simple mechanism by which a log output can be filtered/parsed
for specific outputs.
tag(): returns the current syslog flag
... | 12.07385 | 1.983671 | 6.086619 |
'''
get/set the syslog flag.
The syslog flag toggles prepending each message with
a syslog-style prefix.
syslog(): returns the current syslog flag
syslog(True|False): sets the flag to True|False
'''
if len(args):
self._... | def syslog(self, *args) | get/set the syslog flag.
The syslog flag toggles prepending each message with
a syslog-style prefix.
syslog(): returns the current syslog flag
syslog(True|False): sets the flag to True|False | 6.742705 | 2.386015 | 2.825927 |
'''
get/set the str_syslog, i.e. the current value of the
syslog prepend string.
str_syslog(): returns the current syslog string
str_syslog(<astr>): sets the syslog string to <astr>
'''
if len(args):
self._str_syslog = args[0]
e... | def str_syslog(self, *args) | get/set the str_syslog, i.e. the current value of the
syslog prepend string.
str_syslog(): returns the current syslog string
str_syslog(<astr>): sets the syslog string to <astr> | 5.447064 | 2.233185 | 2.439146 |
'''
get/set the tee flag.
The tee flag toggles any output that is directed to non-console
destinations to also appear on the console. Tee'd console output
is still verbosity filtered
tee(): returns the current syslog flag
tee(True|False)... | def tee(self, *args) | get/set the tee flag.
The tee flag toggles any output that is directed to non-console
destinations to also appear on the console. Tee'd console output
is still verbosity filtered
tee(): returns the current syslog flag
tee(True|False): sets the fl... | 11.746576 | 2.160275 | 5.437539 |
'''
Examines <astr_destination> and if of form <str1>:<str2> assumes
that <str1> is a host to send datagram comms to over port <str2>.
Returns True or False.
'''
t_socketInfo = astr_destination.partition(':')
if len(t_socketInfo[1]):
self._b_... | def socket_parse(self, astr_destination) | Examines <astr_destination> and if of form <str1>:<str2> assumes
that <str1> is a host to send datagram comms to over port <str2>.
Returns True or False. | 5.841474 | 2.552677 | 2.288372 |
'''
get/set the 'device' to which messages are sent.
Valid targets are:
string filenames: '/tmp/test.log'
remote hosts: 'pretoria:1701'
system devices: sys.stdout, sys.stderr
special names: 'stdout... | def to(self, *args) | get/set the 'device' to which messages are sent.
Valid targets are:
string filenames: '/tmp/test.log'
remote hosts: 'pretoria:1701'
system devices: sys.stdout, sys.stderr
special names: 'stdout'
file h... | 5.587109 | 2.804555 | 1.992155 |
'''
A verbosity-aware printf.
'''
if self._verbosity and self._verbosity >= alevel:
sys.stdout.write(format % args) | def vprintf(self, alevel, format, *args) | A verbosity-aware printf. | 7.337173 | 4.215007 | 1.740726 |
'''
Returns a string similar to:
Tue Oct 9 10:49:53 2012 pretoria message.py[26873]:
where 'pretoria' is the hostname, 'message.py' is the current process
name and 26873 is the current process id.
'''
localtime = time.asctime( time.localtime(time.time()) )
... | def syslog_generate(str_processName, str_pid) | Returns a string similar to:
Tue Oct 9 10:49:53 2012 pretoria message.py[26873]:
where 'pretoria' is the hostname, 'message.py' is the current process
name and 26873 is the current process id. | 5.81348 | 1.957021 | 2.970576 |
rows, cols = a_M.shape
a_Mmask = ones( (rows, cols) )
if len(args):
a_Mmask = args[0]
a_M *= a_Mmask
# The "binary" density determines the density of nonzero elements,
# irrespective of their actual value
f_binaryMass = float(size(nonzero(a_M)[0]))
f_actualMass ... | def density(a_M, *args, **kwargs) | ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "density" of a passed matrix. Two densities are retu... | 4.626609 | 3.529955 | 1.310671 |
counts, bin_edges = histogram(arr, **kwargs)
cdf = cumsum(counts)
return cdf | def cdf(arr, **kwargs) | ARGS
arr array to calculate cumulative distribution function
**kwargs
Passed directly to numpy.histogram. Typical options include:
bins = <num_bins>
normed = True|False
DESC
Determines the cumulative distribution function. | 4.025932 | 5.066495 | 0.794619 |
f_range = a_cdf[-1] - a_cdf[0]
f_rangePart = f_range / a_partitions
lowerBound = a_cdf[0]
vl = []
for part in arange(0, a_partitions):
# Due to possible cumulative rounding errors, relax the tolerance
# on the final partition:
if part == a_partitions - 1:
sub... | def cdf_distribution(a_cdf, a_partitions) | ARGS
a_cdf vector a vectors of values/observations
a_partitions int the number of partitions
DESC
This function returns the indices of a passed cdf such that the
the range of values across the indices is uniform across the
number of part... | 3.813404 | 3.779436 | 1.008988 |
f_x = 0
f_y = 0
f_m = 0
for i in range(len(ar_grid)):
for j in range(len(ar_grid[i])):
if ar_grid[i][j]:
# Since python arrays are zero indexed, we need to offset
# the loop counters by 1 to account for mass in the 1st
# column.
f_x +... | def com_find(ar_grid) | Find the center of mass in array grid <ar_grid>. Mass elements
are grid index values.
Return an array, in format (x, y), i.e. col, row! | 3.040549 | 2.788892 | 1.090235 |
b_reorder = True
b_oneOffset = True
for key, value in kwargs.iteritems():
if key == 'ordering' and value == 'rc': b_reorder = False
if key == 'ordering' and value == 'xy': b_reorder = True
if key == 'indexing' and value == 'zero': b_oneOffset... | def com_find2D(ar_grid, **kwargs) | ARGS
**kwargs
ordering = 'rc' or 'xy' order the return either in (x,y)
or (row, col) order.
indexing = 'zero' or 'one' return positions relative to zero (i.e.
python addressing) or one (i.e. MatLAB
... | 2.906177 | 2.405606 | 1.208085 |
rows = arr[0]
cols = arr[1]
arr_index = zeros((rows * cols, 2))
count = 0
for row in arange(0, rows):
for col in arange(0, cols):
arr_index[count] = array([row, col])
count = count + 1
return arr_index | def array2DIndices_enumerate(arr) | DESC
Given a 2D array defined by arr, prepare an explicit list
of the indices.
ARGS
arr in 2 element array with the first
element the rows and the second
the cols
... | 2.665558 | 2.708696 | 0.984074 |
i = 0;
k = 0;
# Cycle up in powers of radix until the largest exponent is found.
# This is required to determine the word length
while (pow(aradix, i)) <= anum10:
i = i + 1;
forcelength = i
# Optionally, allow user to specify word length
if len(args): forcelength = args[0]... | def b10_convertFrom(anum10, aradix, *args) | ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the length
+ of the return array. Useful ... | 4.939049 | 4.603121 | 1.072978 |
global Gtic_start
f_elapsedTime = time.time() - Gtic_start
for key, value in kwargs.items():
if key == 'sysprint': return value % f_elapsedTime
if key == 'default': return "Elapsed time = %f seconds." % f_elapsedTime
return f_elapsedTime | def toc(*args, **kwargs) | Port of the MatLAB function of same name
Behaviour is controllable to some extent by the keyword
args: | 7.769345 | 8.858425 | 0.877057 |
b_wrapGridEdges = False # If True, wrap around edges of grid
if len(args): b_wrapGridEdges = args[0]
# Check for points "less than" grid space
if b_wrapGridEdges:
W = where(A_point < 0)
A_point[W] += a_gridSize[W[1]]
Wbool = A_point >= 0
W = Wbool.prod(axis=1)
A_point... | def pointInGrid(A_point, a_gridSize, *args) | SYNOPSIS
[A_point] = pointInGrid(A_point, a_gridSize [, ab_wrapGridEdges])
ARGS
INPUT
A_point array of N-D points points in grid space
a_gridSize array the size (rows, cols) of
+ the grid space
... | 3.064423 | 2.963299 | 1.034125 |
new_num_arr = array(())
current = anum10
while current != 0:
remainder = current % aradix
new_num_arr = r_[remainder, new_num_arr]
current = current / aradix
forcelength = new_num_arr.size
# Optionally, allow user to specify word length
if len(args): forcelength = ... | def arr_base10toN(anum10, aradix, *args) | ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the length
+ of the return array. Useful ... | 3.647186 | 3.669863 | 0.993821 |
num_rep = {10:'a',
11:'b',
12:'c',
13:'d',
14:'e',
15:'f',
16:'g',
17:'h',
18:'i',
19:'j',
20:'k',
21:'l',
22:'m',
23:'n',
24:'o',
25:'p',
26:'q',
27:'r',
... | def base10toN(num, n) | Change a num to a base-n number.
Up to base-36 is supported without special notation. | 1.794718 | 1.775069 | 1.011069 |
slist = []
for el in ilist:
slist.append(str(el))
return slist | def list_i2str(ilist) | Convert an integer list into a string list. | 2.80398 | 2.479683 | 1.130782 |
adict = {}
alist = str2lst(astr_attributes, astr_separator)
for str_pair in alist:
alistTuple = str2lst(str_pair, "=")
adict.setdefault(alistTuple[0], alistTuple[1].strip(chr(0x22) + chr(0x27)))
return adict | def attributes_strToDict(astr_attributes, astr_separator=" ") | This is logical inverse of the dictToStr method. The <astr_attributes>
string *MUST* have <key>=<value> tuples separated by <astr_separator>. | 3.666313 | 3.614267 | 1.0144 |
str_tabBoundary = " "
for key, value in kwargs.iteritems():
if key == 'tabBoundary': str_tabBoundary = value
b_trailN = False
length = len(astr_buf)
ch_trailN = astr_buf[length - 1]
if ch_trailN == '\n':
b_trailN = True
astr_buf = astr_buf[0:length - 1]
str_ret = astr... | def str_blockIndent(astr_buf, a_tabs=1, a_tabLength=4, **kwargs) | For the input string <astr_buf>, replace each '\n'
with '\n<tab>' where the number of tabs is indicated
by <a_tabs> and the length of the tab by <a_tabLength>
Trailing '\n' are *not* replaced. | 2.337188 | 2.461261 | 0.94959 |
if b_echoCommand: printf('<p>str_command = %s</p>', str_command)
str_stdout = os.popen(str_command).read()
retcode = os.popen(str_command).close()
return retcode, str_stdout | def system_procRet(str_command, b_echoCommand=0) | Run the <str_command> on the underlying shell. Any stderr stream
is lost.
RETURN
Tuple (retcode, str_stdout)
o retcode: the system return code
o str_stdout: the standard output stream | 3.382447 | 3.915612 | 0.863836 |
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError('%s failed w/ exit code %d' % (command, err))
return data | def shellne(command) | Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors. | 3.509491 | 4.004444 | 0.876399 |
'''Helper around 'locate' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l | def find(pattern, root=os.curdir) | Helper around 'locate' | 5.856971 | 4.583839 | 1.277744 |
try:
index = astr_datestr.index(astr_sep)
except:
return astr_datestr.encode('ascii')
try:
tm = time.strptime(astr_datestr, '%d/%M/%Y')
except:
try:
tm = time.strptime(astr_datestr, '%d/%M/%y')
except:
error_exit('str_dateStrip', 'parsing date string',
'no co... | def str_dateStrip(astr_datestr, astr_sep='/') | Simple date strip method. Checks if the <astr_datestr>
contains <astr_sep>. If so, strips these from the string
and returns result.
The actual stripping entails falling through two layers
of exception handling... so it is something of a hack. | 3.211587 | 3.181625 | 1.009417 |
alistI = astr_input.split(astr_separator)
alistJ = []
for i in range(0, len(alistI)):
alistI[i] = alistI[i].strip()
alistI[i] = alistI[i].encode('ascii')
if len(alistI[i]):
alistJ.append(alistI[i])
return alistJ | def str2lst(astr_input, astr_separator=" ") | Breaks a string at <astr_separator> and joins into a
list. Steps along all list elements and strips white
space.
The list elements are explicitly ascii encoded. | 2.250395 | 2.154263 | 1.044624 |
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False | def match(self, *args) | Indicate whether or not to enter a case suite | 4.341633 | 6.371057 | 0.681462 |
'''
Error handling.
Based on the <astr_key>, error information is extracted from
_dictErr and sent to log object.
If <ab_exitToOs> is False, error is considered non-fatal and
processing can continue, otherwise processing terminates.
'''
log = callingClass.log()
b_syslog ... | def report( callingClass,
astr_key,
ab_exitToOs=1,
astr_header=""
) | Error handling.
Based on the <astr_key>, error information is extracted from
_dictErr and sent to log object.
If <ab_exitToOs> is False, error is considered non-fatal and
processing can continue, otherwise processing terminates. | 3.393534 | 2.676954 | 1.267685 |
'''
Convenience dispatcher to the error_exit() method.
Will raise "fatal" error, i.e. terminate script.
'''
b_exitToOS = True
report( callingClass, astr_key, b_exitToOS, astr_extraMsg ) | def fatal( callingClass, astr_key, astr_extraMsg="" ) | Convenience dispatcher to the error_exit() method.
Will raise "fatal" error, i.e. terminate script. | 11.74705 | 4.270719 | 2.750602 |
'''
Convenience dispatcher to the error_exit() method.
Will raise "warning" error, i.e. script processing continues.
'''
b_exitToOS = False
report( callingClass, astr_key, b_exitToOS, astr_extraMsg ) | def warn( callingClass, astr_key, astr_extraMsg="" ) | Convenience dispatcher to the error_exit() method.
Will raise "warning" error, i.e. script processing continues. | 15.134341 | 4.101436 | 3.690011 |
'''
get/set the internal pipeline log message object.
Caller can further manipulate the log object with object-specific
calls.
'''
if len(args):
self._log = args[0]
else:
return self._log | def log(self, *args) | get/set the internal pipeline log message object.
Caller can further manipulate the log object with object-specific
calls. | 10.041615 | 2.454341 | 4.091369 |
'''
get/set the descriptive name text of this object.
'''
if len(args):
self.__name = args[0]
else:
return self.__name | def name(self, *args) | get/set the descriptive name text of this object. | 6.035336 | 3.387951 | 1.781412 |
'''
Get / set internal object description.
'''
if len(args):
self._str_desc = args[0]
else:
return self._str_desc | def description(self, *args) | Get / set internal object description. | 5.876301 | 3.827057 | 1.535462 |
'''
Processes a single slice.
'''
if b_rot90:
self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice)
if self.func == 'invertIntensities':
self.invert_slice_intensities() | def process_slice(self, b_rot90=None) | Processes a single slice. | 6.906815 | 6.269041 | 1.101734 |
'''
Saves a single slice.
ARGS
o astr_output
The output filename to save the slice to.
'''
self._log('Outputfile = %s\n' % astr_outputFile)
fformat = astr_outputFile.split('.')[-1]
if fformat == 'dcm':
if self._dcm:
se... | def slice_save(self, astr_outputFile) | Saves a single slice.
ARGS
o astr_output
The output filename to save the slice to. | 3.932694 | 2.968267 | 1.324912 |
'''
Runs the DICOM conversion based on internal state.
'''
self._log('Converting DICOM image.\n')
try:
self._log('PatientName: %s\n' % self._dcm.PatientName)
except AttributeError:
self._log('PatientName: ... | def run(self) | Runs the DICOM conversion based on internal state. | 2.253279 | 2.13516 | 1.055321 |
'''
Runs the NIfTI conversion based on internal state.
'''
self._log('About to perform NifTI to %s conversion...\n' %
self._str_outputFileType)
frames = 1
frameStart = 0
frameEnd = 0
sliceStart = 0
sliceEnd = 0
... | def run(self) | Runs the NIfTI conversion based on internal state. | 3.279036 | 2.992054 | 1.095915 |
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# File output handler
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s %(name)12s %(levelname)8s %(lineno)s %(message)s',
datefmt='%m/%... | def get_logger(name) | Return a logger with a file handler. | 1.872282 | 1.788211 | 1.047014 |
def wrapper(*args, **kwargs):
start = time.time()
result = method(*args, **kwargs)
end = time.time()
click.echo('Cost {}s'.format(int(end-start)))
return result
return wrapper | def timeit(method) | Compute the download time. | 2.812256 | 2.699779 | 1.041661 |
def wrapper(*args, **kwargs):
crawler = args[0].crawler # args[0] is a NetEase object
try:
if os.path.isfile(cookie_path):
with open(cookie_path, 'r') as cookie_file:
cookie = cookie_file.read()
expire_time = re.compile(r'\d{4}-... | def login(method) | Require user to login. | 3.157192 | 3.104947 | 1.016827 |
try:
song = self.crawler.search_song(song_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_song_by_id(song.song_id, song.song_name, self.folder) | def download_song_by_search(self, song_name) | Download a song by its name.
:params song_name: song name. | 4.354397 | 4.319128 | 1.008166 |
try:
url = self.crawler.get_song_url(song_id)
if self.lyric:
# use old api
lyric_info = self.crawler.get_song_lyric(song_id)
else:
lyric_info = None
song_name = song_name.replace('/', '')
song_n... | def download_song_by_id(self, song_id, song_name, folder='.') | Download a song by id and save it to disk.
:params song_id: song id.
:params song_name: song name.
:params folder: storage path. | 3.32609 | 3.215645 | 1.034346 |
try:
album = self.crawler.search_album(album_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_album_by_id(album.album_id, album.album_name) | def download_album_by_search(self, album_name) | Download a album by its name.
:params album_name: album name. | 4.002076 | 4.063632 | 0.984852 |
try:
# use old api
songs = self.crawler.get_album_songs(album_id)
except RequestException as exception:
click.echo(exception)
else:
folder = os.path.join(self.folder, album_name)
for song in songs:
self.downloa... | def download_album_by_id(self, album_id, album_name) | Download a album by its name.
:params album_id: album id.
:params album_name: album name. | 3.543796 | 3.627349 | 0.976966 |
try:
artist = self.crawler.search_artist(artist_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_artist_by_id(artist.artist_id, artist.artist_name) | def download_artist_by_search(self, artist_name) | Download a artist's top50 songs by his/her name.
:params artist_name: artist name. | 4.028801 | 4.352056 | 0.925724 |
try:
# use old api
songs = self.crawler.get_artists_hot_songs(artist_id)
except RequestException as exception:
click.echo(exception)
else:
folder = os.path.join(self.folder, artist_name)
for song in songs:
self... | def download_artist_by_id(self, artist_id, artist_name) | Download a artist's top50 songs by his/her id.
:params artist_id: artist id.
:params artist_name: artist name. | 3.887652 | 3.896846 | 0.997641 |
try:
playlist = self.crawler.search_playlist(
playlist_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_playlist_by_id(
playlist.playlist_id, playlist.playlist_name) | def download_playlist_by_search(self, playlist_name) | Download a playlist's songs by its name.
:params playlist_name: playlist name. | 4.325251 | 4.380013 | 0.987497 |
try:
songs = self.crawler.get_playlist_songs(
playlist_id)
except RequestException as exception:
click.echo(exception)
else:
folder = os.path.join(self.folder, playlist_name)
for song in songs:
self.downloa... | def download_playlist_by_id(self, playlist_id, playlist_name) | Download a playlist's songs by its id.
:params playlist_id: playlist id.
:params playlist_name: playlist name. | 3.218007 | 3.157982 | 1.019007 |
try:
user = self.crawler.search_user(user_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_user_playlists_by_id(user.user_id) | def download_user_playlists_by_search(self, user_name) | Download user's playlists by his/her name.
:params user_name: user name. | 4.362395 | 4.584716 | 0.951508 |
try:
playlist = self.crawler.get_user_playlists(user_id)
except RequestException as exception:
click.echo(exception)
else:
self.download_playlist_by_id(
playlist.playlist_id, playlist.playlist_name) | def download_user_playlists_by_id(self, user_id) | Download user's playlists by his/her id.
:params user_id: user id. | 4.057256 | 4.072624 | 0.996227 |
with open(person_info_path, 'r') as person_info:
user_id = int(person_info.read())
self.download_user_playlists_by_id(user_id) | def download_person_playlists(self) | Download person playlist including private playlist.
note: login required. | 4.006613 | 3.86455 | 1.036761 |
LOG.info('%s => %s', sign, frame)
click.echo('Bye')
sys.exit(0) | def signal_handler(sign, frame) | Capture Ctrl+C. | 6.455691 | 6.217091 | 1.038378 |
ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again) | def cli(ctx, timeout, proxy, output, quiet, lyric, again) | A command tool to download NetEase-Music's songs. | 4.137251 | 3.787402 | 1.092372 |
if name:
netease.download_song_by_search(name)
if id:
netease.download_song_by_id(id, 'song'+str(id)) | def song(netease, name, id) | Download a song by name or id. | 4.251218 | 4.075033 | 1.043235 |
if name:
netease.download_album_by_search(name)
if id:
netease.download_album_by_id(id, 'album'+str(id)) | def album(netease, name, id) | Download a album's songs by name or id. | 4.390244 | 4.228622 | 1.038221 |
if name:
netease.download_artist_by_search(name)
if id:
netease.download_artist_by_id(id, 'artist'+str(id)) | def artist(netease, name, id) | Download a artist's hot songs by name or id. | 4.507348 | 4.399415 | 1.024534 |
if name:
netease.download_playlist_by_search(name)
if id:
netease.download_playlist_by_id(id, 'playlist'+str(id)) | def playlist(netease, name, id) | Download a playlist's songs by id. | 4.311046 | 4.434225 | 0.972221 |
if name:
netease.download_user_playlists_by_search(name)
if id:
netease.download_user_playlists_by_id(id) | def user(netease, name, id) | Download a user\'s playlists by id. | 3.479958 | 3.219727 | 1.080824 |
if len(songs) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Song Name', 'Artist Name'])
for i, song in enumerate(songs, 1):
table.add_row([i, song['name'], song['ar'][0]['name']])
click.echo(table)
select... | def select_one_song(songs) | Display the songs returned by search api.
:params songs: API['result']['songs']
:return: a Song object. | 2.48166 | 2.363941 | 1.049798 |
if len(albums) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Album Name', 'Artist Name'])
for i, album in enumerate(albums, 1):
table.add_row([i, album['name'], album['artist']['name']])
click.echo(table)
... | def select_one_album(albums) | Display the albums returned by search api.
:params albums: API['result']['albums']
:return: a Album object. | 2.344725 | 2.312371 | 1.013992 |
if len(artists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Artist Name'])
for i, artist in enumerate(artists, 1):
table.add_row([i, artist['name']])
click.echo(table)
select_i = click.prompt('Select on... | def select_one_artist(artists) | Display the artists returned by search api.
:params artists: API['result']['artists']
:return: a Artist object. | 2.424428 | 2.368116 | 1.023779 |
if len(playlists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, playlist in enumerate(playlists, 1):
table.add_row([i, playlist['name']])
click.echo(table)
select_i = click.prompt('Select o... | def select_one_playlist(playlists) | Display the playlists returned by search api or user playlist.
:params playlists: API['result']['playlists'] or API['playlist']
:return: a Playlist object. | 2.320439 | 2.282408 | 1.016663 |
if len(users) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, user in enumerate(users, 1):
table.add_row([i, user['nickname']])
click.echo(table)
select_i = click.prompt('Select one user', ty... | def select_one_user(users) | Display the users returned by search api.
:params users: API['result']['userprofiles']
:return: a User object. | 2.566177 | 2.52407 | 1.016682 |
def wrapper(*args, **kwargs):
try:
result = method(*args, **kwargs)
return result
except ProxyError:
LOG.exception('ProxyError when try to get %s.', args)
raise ProxyError('A proxy error occurred.')
except ConnectionException:
... | def exception_handle(method) | Handle exception raised by requests library. | 3.166923 | 2.962548 | 1.068986 |
resp = self.session.get(url, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to get %s', result, url)
raise GetRequestIllegal(result)
else:
... | def get_request(self, url) | Send a get request.
warning: old api.
:return: a dict or raise Exception. | 4.214883 | 3.940905 | 1.069522 |
data = encrypted_request(params)
resp = self.session.post(url, data=data, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to post %s => %s',
... | def post_request(self, url, params) | Send a post request.
:return: a dict or raise Exception. | 4.362993 | 4.213763 | 1.035415 |
url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='
params = {'s': search_content, 'type': search_type, 'offset': 0,
'sub': 'false', 'limit': limit}
result = self.post_request(url, params)
return result | def search(self, search_content, search_type, limit=9) | Search entrance.
:params search_content: search content.
:params search_type: search type.
:params limit: result count returned by weapi.
:return: a dict. | 2.58178 | 2.322362 | 1.111704 |
result = self.search(song_name, search_type=1, limit=limit)
if result['result']['songCount'] <= 0:
LOG.warning('Song %s not existed!', song_name)
raise SearchNotFound('Song {} not existed.'.format(song_name))
else:
songs = result['result']['songs']
... | def search_song(self, song_name, quiet=False, limit=9) | Search song by song name.
:params song_name: song name.
:params quiet: automatically select the best one.
:params limit: song count returned by weapi.
:return: a Song object. | 3.120448 | 3.034938 | 1.028175 |
result = self.search(album_name, search_type=10, limit=limit)
if result['result']['albumCount'] <= 0:
LOG.warning('Album %s not existed!', album_name)
raise SearchNotFound('Album {} not existed'.format(album_name))
else:
albums = result['result']['a... | def search_album(self, album_name, quiet=False, limit=9) | Search album by album name.
:params album_name: album name.
:params quiet: automatically select the best one.
:params limit: album count returned by weapi.
:return: a Album object. | 3.280183 | 3.135848 | 1.046028 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.