text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def pgpdf(omega, b, psi, trunc=200):
"""
Approximate the density log PG(omega | b, psi) using a
truncation of the density written as an infinite sum.
:param omega: point at which to evaluate density
:param b: first parameter of PG
:param psi: tilting of PG
:param trunc: number of terms in... | [
"def",
"pgpdf",
"(",
"omega",
",",
"b",
",",
"psi",
",",
"trunc",
"=",
"200",
")",
":",
"ns",
"=",
"np",
".",
"arange",
"(",
"trunc",
")",
"psi_ns",
"=",
"np",
".",
"array",
"(",
"[",
"_psi_n",
"(",
"omega",
",",
"n",
",",
"b",
")",
"for",
... | 28.111111 | 15.222222 |
def __choices2tkvalues(self, choices):
"""choices: iterable of key, value pairs"""
values = []
for k, v in choices:
values.append(v)
return values | [
"def",
"__choices2tkvalues",
"(",
"self",
",",
"choices",
")",
":",
"values",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"choices",
":",
"values",
".",
"append",
"(",
"v",
")",
"return",
"values"
] | 30.833333 | 11 |
def path_fraction_id_offset(points, fraction, relative_offset=False):
'''Find the segment which corresponds to the fraction
of the path length along the piecewise linear curve which
is constructed from the set of points.
Args:
points: an iterable of indexable objects with indices
0, 1, ... | [
"def",
"path_fraction_id_offset",
"(",
"points",
",",
"fraction",
",",
"relative_offset",
"=",
"False",
")",
":",
"if",
"not",
"(",
"0.",
"<=",
"fraction",
"<=",
"1.0",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid fraction: %.3f\"",
"%",
"fraction",
")",
... | 38.461538 | 17.230769 |
def getMaximinScores(profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to contain complete ordering over can... | [
"def",
"getMaximinScores",
"(",
"profile",
")",
":",
"# Currently, we expect the profile to contain complete ordering over candidates. Ties are",
"# allowed however.",
"elecType",
"=",
"profile",
".",
"getElecType",
"(",
")",
"if",
"elecType",
"!=",
"\"soc\"",
"and",
"elecTyp... | 38.066667 | 25.2 |
def _check_smart_storage_message(self):
"""Check for smart storage message.
:returns: result, raid_message
"""
ssc_mesg = self.smart_storage_config_message
result = True
raid_message = ""
for element in ssc_mesg:
if "Success" not in element['MessageId... | [
"def",
"_check_smart_storage_message",
"(",
"self",
")",
":",
"ssc_mesg",
"=",
"self",
".",
"smart_storage_config_message",
"result",
"=",
"True",
"raid_message",
"=",
"\"\"",
"for",
"element",
"in",
"ssc_mesg",
":",
"if",
"\"Success\"",
"not",
"in",
"element",
... | 33.076923 | 10.461538 |
def complete_object_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLObjectType
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
"""
Complete an Object va... | [
"def",
"complete_object_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLObjectType",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# ... | 36.130435 | 17.608696 |
def validate(self, value):
"""
Applies the validation criteria.
Returns value, new value, or None if invalid.
"""
try:
coord.Angle(value, unit=self.unit)
return value
except ValueError:
return None | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"coord",
".",
"Angle",
"(",
"value",
",",
"unit",
"=",
"self",
".",
"unit",
")",
"return",
"value",
"except",
"ValueError",
":",
"return",
"None"
] | 27.2 | 10.8 |
def question_field(self, move_x, move_y):
"""Question a grid by given position."""
field_status = self.info_map[move_y, move_x]
# a questioned or undiscovered field
if field_status != 10 and (field_status == 9 or field_status == 11):
self.info_map[move_y, move_x] = 10 | [
"def",
"question_field",
"(",
"self",
",",
"move_x",
",",
"move_y",
")",
":",
"field_status",
"=",
"self",
".",
"info_map",
"[",
"move_y",
",",
"move_x",
"]",
"# a questioned or undiscovered field",
"if",
"field_status",
"!=",
"10",
"and",
"(",
"field_status",
... | 43.857143 | 14.142857 |
def DataPath():
""" Return the default path for fit data h5 files"""
return os.path.abspath('%s/data'%(os.path.dirname( \
os.path.realpath(__file__)))) | [
"def",
"DataPath",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"'%s/data'",
"%",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
")",
")"
] | 41 | 11 |
def _mount(device):
'''
Mount the device in a temporary place.
'''
dest = tempfile.mkdtemp()
res = __states__['mount.mounted'](dest, device=device, fstype='btrfs',
opts='subvol=/', persist=False)
if not res['result']:
log.error('Cannot mount device %... | [
"def",
"_mount",
"(",
"device",
")",
":",
"dest",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"res",
"=",
"__states__",
"[",
"'mount.mounted'",
"]",
"(",
"dest",
",",
"device",
"=",
"device",
",",
"fstype",
"=",
"'btrfs'",
",",
"opts",
"=",
"'subvol=/'"... | 32.5 | 22.166667 |
def switch_format(self, gsr):
""" Convert the Wharton GSR format into the studyspaces API format. """
if "error" in gsr:
return gsr
categories = {
"cid": 1,
"name": "Huntsman Hall",
"rooms": []
}
for time in gsr["times"]:
... | [
"def",
"switch_format",
"(",
"self",
",",
"gsr",
")",
":",
"if",
"\"error\"",
"in",
"gsr",
":",
"return",
"gsr",
"categories",
"=",
"{",
"\"cid\"",
":",
"1",
",",
"\"name\"",
":",
"\"Huntsman Hall\"",
",",
"\"rooms\"",
":",
"[",
"]",
"}",
"for",
"time"... | 42.627907 | 14 |
def _key_from_json(self, data):
"""
Internal method, for creating the Key object.
"""
key = Key()
key.algorithm = data["Algorithm"]
key.cipher_mode = data["CipherMode"]
key.expiration = datetime.strptime(data["Expiration"].split(".")[0],
... | [
"def",
"_key_from_json",
"(",
"self",
",",
"data",
")",
":",
"key",
"=",
"Key",
"(",
")",
"key",
".",
"algorithm",
"=",
"data",
"[",
"\"Algorithm\"",
"]",
"key",
".",
"cipher_mode",
"=",
"data",
"[",
"\"CipherMode\"",
"]",
"key",
".",
"expiration",
"="... | 35.214286 | 11.642857 |
def deauthorize_application(request):
"""
When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's
"deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding
users as unauthorized.
"""
if request.facebook:
... | [
"def",
"deauthorize_application",
"(",
"request",
")",
":",
"if",
"request",
".",
"facebook",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"facebook_id",
"=",
"request",
".",
"facebook",
".",
"signed_request",
".",
"user",
".",
"id",
")",
"... | 31.823529 | 22.176471 |
def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):
"""A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
T... | [
"def",
"_load_mnist_dataset",
"(",
"shape",
",",
"path",
",",
"name",
"=",
"'mnist'",
",",
"url",
"=",
"'http://yann.lecun.com/exdb/mnist/'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"# Define functions for loading ... | 46.377049 | 22.57377 |
def _invalidates_cache(f):
"""
Decorator for rruleset methods which may invalidate the
cached length.
"""
def inner_func(self, *args, **kwargs):
rv = f(self, *args, **kwargs)
self._invalidate_cache()
return rv
return inner_func | [
"def",
"_invalidates_cache",
"(",
"f",
")",
":",
"def",
"inner_func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rv",
"=",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_invalidate_cache",
... | 22.166667 | 15.833333 |
def create_service(self, customer_id, name, publish_key=None, comment=None):
"""Create a service."""
body = self._formdata({
"customer_id": customer_id,
"name": name,
"publish_key": publish_key,
"comment": comment,
}, FastlyService.FIELDS)
content = self._fetch("/service", method="POST", body=body)
... | [
"def",
"create_service",
"(",
"self",
",",
"customer_id",
",",
"name",
",",
"publish_key",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"body",
"=",
"self",
".",
"_formdata",
"(",
"{",
"\"customer_id\"",
":",
"customer_id",
",",
"\"name\"",
":",
"... | 34.8 | 15.1 |
def weld_compare(array, scalar, operation, weld_type):
"""Applies comparison operation between each element in the array with scalar.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
scalar : {int, float, str, bool, bytes_}
Value to compare with; must be same ty... | [
"def",
"weld_compare",
"(",
"array",
",",
"scalar",
",",
"operation",
",",
"weld_type",
")",
":",
"obj_id",
",",
"weld_obj",
"=",
"create_weld_object",
"(",
"array",
")",
"if",
"not",
"isinstance",
"(",
"scalar",
",",
"str",
")",
":",
"scalar",
"=",
"to_... | 31.863636 | 20.363636 |
def annotate_powerlaw(text, exp, startx, starty, width=None, rx=0.5, ry=0.5, **kwargs):
r'''
Added a label to the middle of a power-law annotation (see ``goosempl.plot_powerlaw``).
:arguments:
**exp** (``float``)
The power-law exponent.
**startx, starty** (``float``)
Start coordinates.
:options:
**... | [
"def",
"annotate_powerlaw",
"(",
"text",
",",
"exp",
",",
"startx",
",",
"starty",
",",
"width",
"=",
"None",
",",
"rx",
"=",
"0.5",
",",
"ry",
"=",
"0.5",
",",
"*",
"*",
"kwargs",
")",
":",
"# get options/defaults",
"endx",
"=",
"kwargs",
".",
"pop"... | 27.696203 | 25.443038 |
def find_or_create(self, constructor, props, *, comp=None):
"""Looks for a model taht matches the given dictionary constraints. If it is not found, a new
model of the given type is created and saved to the database, then returned.
"""
model = self.find_model(constructor, comp or props)
if model is N... | [
"def",
"find_or_create",
"(",
"self",
",",
"constructor",
",",
"props",
",",
"*",
",",
"comp",
"=",
"None",
")",
":",
"model",
"=",
"self",
".",
"find_model",
"(",
"constructor",
",",
"comp",
"or",
"props",
")",
"if",
"model",
"is",
"None",
":",
"mod... | 44.333333 | 14.777778 |
def to_dict(self):
"""Returns attributes formatted as a dictionary."""
d = {'id': self.id, 'classes': self.classes}
d.update(self.kvs)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'classes'",
":",
"self",
".",
"classes",
"}",
"d",
".",
"update",
"(",
"self",
".",
"kvs",
")",
"return",
"d"
] | 34.2 | 14.4 |
def handle_bad_update(operation, ret):
'''report error for bad update'''
print("Error " + operation)
sys.exit('Return code: ' + str(ret.status_code) + ' Error: ' + ret.text) | [
"def",
"handle_bad_update",
"(",
"operation",
",",
"ret",
")",
":",
"print",
"(",
"\"Error \"",
"+",
"operation",
")",
"sys",
".",
"exit",
"(",
"'Return code: '",
"+",
"str",
"(",
"ret",
".",
"status_code",
")",
"+",
"' Error: '",
"+",
"ret",
".",
"text"... | 45.5 | 12.5 |
def getOccurrenceOfCharAtIndex(self, sym, index):
'''
This functions gets the FM-index value of a character at the specified position
@param sym - the character to find the occurrence level
@param index - the index we want to find the occurrence level at
@return - the number of o... | [
"def",
"getOccurrenceOfCharAtIndex",
"(",
"self",
",",
"sym",
",",
"index",
")",
":",
"#sampling method",
"#get the bin we occupy",
"binID",
"=",
"index",
">>",
"self",
".",
"bitPower",
"#these two methods seem to have the same approximate run time",
"if",
"(",
"binID",
... | 45.941176 | 25 |
def _search(self, model, condition=None, search_field='name',
value_field='id', label_field=None, pagination=True):
"""
Default search function
:param search_field: Used for search field, default is 'name'
:param value_field: Used for id field, default is id
:para... | [
"def",
"_search",
"(",
"self",
",",
"model",
",",
"condition",
"=",
"None",
",",
"search_field",
"=",
"'name'",
",",
"value_field",
"=",
"'id'",
",",
"label_field",
"=",
"None",
",",
"pagination",
"=",
"True",
")",
":",
"from",
"uliweb",
"import",
"json"... | 40.631579 | 18.736842 |
def get_value(self,column=None,keyValue=None,table=None,verbose=None):
"""
Returns the value from a cell as specified by row and column ids.
:param column (string, optional): Specifies the name of a column in the tab
le
:param keyValue (string, optional): Specifies a row of ... | [
"def",
"get_value",
"(",
"self",
",",
"column",
"=",
"None",
",",
"keyValue",
"=",
"None",
",",
"table",
"=",
"None",
",",
"verbose",
"=",
"None",
")",
":",
"PARAMS",
"=",
"set_param",
"(",
"[",
"'column'",
",",
"'keyValue'",
",",
"'table'",
"]",
","... | 48.823529 | 29.764706 |
def get_definition(self, name):
"""Get definitions by name."""
for definition in self.definitions:
if definition.name == name:
return definition | [
"def",
"get_definition",
"(",
"self",
",",
"name",
")",
":",
"for",
"definition",
"in",
"self",
".",
"definitions",
":",
"if",
"definition",
".",
"name",
"==",
"name",
":",
"return",
"definition"
] | 36.8 | 4 |
def inbox_count_for(user):
"""
returns the number of unread messages for the given user but does not
mark them seen
"""
return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count() | [
"def",
"inbox_count_for",
"(",
"user",
")",
":",
"return",
"Message",
".",
"objects",
".",
"filter",
"(",
"recipient",
"=",
"user",
",",
"read_at__isnull",
"=",
"True",
",",
"recipient_deleted_at__isnull",
"=",
"True",
")",
".",
"count",
"(",
")"
] | 40.833333 | 23.833333 |
def _label_generalized(self, node):
"""Helper method that labels the nodes of GST with indexes of strings
found in their descendants.
"""
if node.is_leaf():
x = {self._get_word_start_index(node.idx)}
else:
x = {n for ns in node.transition_links for n in ns... | [
"def",
"_label_generalized",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"is_leaf",
"(",
")",
":",
"x",
"=",
"{",
"self",
".",
"_get_word_start_index",
"(",
"node",
".",
"idx",
")",
"}",
"else",
":",
"x",
"=",
"{",
"n",
"for",
"ns",
"i... | 40.777778 | 12.777778 |
def isolate_region(sequences, start, end, gap_char='-'):
"""
Replace regions before and after start:end with gap chars
"""
# Check arguments
if end <= start:
raise ValueError("start of slice must precede end ({0} !> {1})".format(
end, start))
for sequence in sequences:
... | [
"def",
"isolate_region",
"(",
"sequences",
",",
"start",
",",
"end",
",",
"gap_char",
"=",
"'-'",
")",
":",
"# Check arguments",
"if",
"end",
"<=",
"start",
":",
"raise",
"ValueError",
"(",
"\"start of slice must precede end ({0} !> {1})\"",
".",
"format",
"(",
... | 32.823529 | 15.176471 |
def max_await_time_ms(self, max_await_time_ms):
"""Specifies a time limit for a getMore operation on a
:attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other
types of cursor max_await_time_ms is ignored.
Raises :exc:`TypeError` if `max_await_time_ms` is not an integer o... | [
"def",
"max_await_time_ms",
"(",
"self",
",",
"max_await_time_ms",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"max_await_time_ms",
",",
"integer_types",
")",
"and",
"max_await_time_ms",
"is",
"not",
"None",
")",
":",
"raise",
"TypeError",
"(",
"\"max_await_t... | 40.37037 | 24.111111 |
def status_to_string(cls, status):
"""
Converts a message status to a string.
:param status: Status to convert (p yqode.core.modes.CheckerMessages)
:return: The status string.
:rtype: str
"""
strings = {CheckerMessages.INFO: "Info",
CheckerMess... | [
"def",
"status_to_string",
"(",
"cls",
",",
"status",
")",
":",
"strings",
"=",
"{",
"CheckerMessages",
".",
"INFO",
":",
"\"Info\"",
",",
"CheckerMessages",
".",
"WARNING",
":",
"\"Warning\"",
",",
"CheckerMessages",
".",
"ERROR",
":",
"\"Error\"",
"}",
"re... | 34.583333 | 13.083333 |
def to_headers(self, span_context):
"""Convert a SpanContext object to B3 propagation headers.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: B3 propagation headers.
"""... | [
"def",
"to_headers",
"(",
"self",
",",
"span_context",
")",
":",
"if",
"not",
"span_context",
".",
"span_id",
":",
"span_id",
"=",
"INVALID_SPAN_ID",
"else",
":",
"span_id",
"=",
"span_context",
".",
"span_id",
"sampled",
"=",
"span_context",
".",
"trace_optio... | 28.173913 | 17.26087 |
def toggle_help(self, event, mode=None):
"""
Show/hide help message on help button click.
"""
# if mode == 'open', show no matter what.
# if mode == 'close', close. otherwise, change state
btn = self.toggle_help_btn
shown = self.help_msg_boxsizer.GetStaticBox().I... | [
"def",
"toggle_help",
"(",
"self",
",",
"event",
",",
"mode",
"=",
"None",
")",
":",
"# if mode == 'open', show no matter what.",
"# if mode == 'close', close. otherwise, change state",
"btn",
"=",
"self",
".",
"toggle_help_btn",
"shown",
"=",
"self",
".",
"help_msg_bo... | 37.625 | 10.125 |
def create(self, friendly_name=values.unset, apn_credential_sid=values.unset,
gcm_credential_sid=values.unset, messaging_service_sid=values.unset,
facebook_messenger_page_id=values.unset,
default_apn_notification_protocol_version=values.unset,
default_gcm_noti... | [
"def",
"create",
"(",
"self",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"apn_credential_sid",
"=",
"values",
".",
"unset",
",",
"gcm_credential_sid",
"=",
"values",
".",
"unset",
",",
"messaging_service_sid",
"=",
"values",
".",
"unset",
",",
"... | 56.68 | 29.8 |
def build_sort():
'''Build sort query paramter from kwargs'''
sorts = request.args.getlist('sort')
sorts = [sorts] if isinstance(sorts, basestring) else sorts
sorts = [s.split(' ') for s in sorts]
return [{SORTS[s]: d} for s, d in sorts if s in SORTS] | [
"def",
"build_sort",
"(",
")",
":",
"sorts",
"=",
"request",
".",
"args",
".",
"getlist",
"(",
"'sort'",
")",
"sorts",
"=",
"[",
"sorts",
"]",
"if",
"isinstance",
"(",
"sorts",
",",
"basestring",
")",
"else",
"sorts",
"sorts",
"=",
"[",
"s",
".",
"... | 44.333333 | 12 |
def until_protocol(self, timeout=None):
"""Return future that resolves after receipt of katcp protocol info.
If the returned future resolves, the server's protocol information is
available in the ProtocolFlags instance self.protocol_flags.
"""
t0 = self.ioloop.time()
yi... | [
"def",
"until_protocol",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"t0",
"=",
"self",
".",
"ioloop",
".",
"time",
"(",
")",
"yield",
"self",
".",
"until_running",
"(",
"timeout",
"=",
"timeout",
")",
"t1",
"=",
"self",
".",
"ioloop",
".",
... | 38.375 | 17.8125 |
def changelog(ctx, check, version, old_version, initial, quiet, dry_run):
"""Perform the operations needed to update the changelog.
This method is supposed to be used by other tasks and not directly.
"""
if check not in get_valid_checks():
abort('Check `{}` is not an Agent-based Integration'.fo... | [
"def",
"changelog",
"(",
"ctx",
",",
"check",
",",
"version",
",",
"old_version",
",",
"initial",
",",
"quiet",
",",
"dry_run",
")",
":",
"if",
"check",
"not",
"in",
"get_valid_checks",
"(",
")",
":",
"abort",
"(",
"'Check `{}` is not an Agent-based Integratio... | 36.607843 | 24.313725 |
def vectorize_range(values):
"""
This function is for url encoding.
Takes a value or a tuple or list of tuples and returns a single result,
tuples are joined by "," if necessary, elements in tuple are joined by '_'
"""
if isinstance(values, tuple):
return '_'.join(str(i) for i in values)... | [
"def",
"vectorize_range",
"(",
"values",
")",
":",
"if",
"isinstance",
"(",
"values",
",",
"tuple",
")",
":",
"return",
"'_'",
".",
"join",
"(",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"values",
")",
"if",
"isinstance",
"(",
"values",
",",
"list",
... | 43.307692 | 15.615385 |
def backoff(
max_tries=constants.BACKOFF_DEFAULT_MAXTRIES,
delay=constants.BACKOFF_DEFAULT_DELAY,
factor=constants.BACKOFF_DEFAULT_FACTOR,
exceptions=None):
"""Implements an exponential backoff decorator which will retry decorated
function upon given exceptions. This implementati... | [
"def",
"backoff",
"(",
"max_tries",
"=",
"constants",
".",
"BACKOFF_DEFAULT_MAXTRIES",
",",
"delay",
"=",
"constants",
".",
"BACKOFF_DEFAULT_DELAY",
",",
"factor",
"=",
"constants",
".",
"BACKOFF_DEFAULT_FACTOR",
",",
"exceptions",
"=",
"None",
")",
":",
"if",
"... | 41.185185 | 24 |
def decode(string):
"""Decode Erlang external term."""
if not string:
raise IncompleteData(string)
if string[0] != 131:
raise ValueError("unknown protocol version: %r" % string[0])
if string[1:2] == b'P':
# compressed term
if len(string) < 16:
raise Incomplete... | [
"def",
"decode",
"(",
"string",
")",
":",
"if",
"not",
"string",
":",
"raise",
"IncompleteData",
"(",
"string",
")",
"if",
"string",
"[",
"0",
"]",
"!=",
"131",
":",
"raise",
"ValueError",
"(",
"\"unknown protocol version: %r\"",
"%",
"string",
"[",
"0",
... | 40.047619 | 13.380952 |
def _pack(self, fname, encoding):
"""Save workflow with ``--pack`` option
This means that al tools and subworkflows are included in the workflow
file that is created. A packed workflow cannot be loaded and used in
scriptcwl.
"""
(fd, tmpfile) = tempfile.mkstemp()
... | [
"def",
"_pack",
"(",
"self",
",",
"fname",
",",
"encoding",
")",
":",
"(",
"fd",
",",
"tmpfile",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"os",
".",
"close",
"(",
"fd",
")",
"try",
":",
"self",
".",
"save",
"(",
"tmpfile",
",",
"mode",
"... | 37.833333 | 21.5 |
def build_app_loggers(log_level, apps, handlers=None):
""" Return a logger dict for app packages with the given log level and no
propogation since the apps list is parsed/normalized to be the set of top-
level apps. The optional handlers argument is provided so that this pattern
of app loggers can be u... | [
"def",
"build_app_loggers",
"(",
"log_level",
",",
"apps",
",",
"handlers",
"=",
"None",
")",
":",
"# Use 'default' handler provided by DEFAULT_LOGGING config if",
"# not supplied.",
"if",
"handlers",
"is",
"None",
":",
"handlers",
"=",
"[",
"'default'",
"]",
"# The l... | 33.148148 | 20.481481 |
def merge(args):
"""
%prog merge bedfiles > newbedfile
Concatenate bed files together. Performing seqid and name changes to avoid
conflicts in the new bed file.
"""
p = OptionParser(merge.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(no... | [
"def",
"merge",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"merge",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"1",
... | 26.227273 | 15.318182 |
def fields_to_dict(fields, type_=OrderedDict):
"""Convert a flat list of key/values into an OrderedDict"""
fields_iterator = iter(fields)
return type_(zip(fields_iterator, fields_iterator)) | [
"def",
"fields_to_dict",
"(",
"fields",
",",
"type_",
"=",
"OrderedDict",
")",
":",
"fields_iterator",
"=",
"iter",
"(",
"fields",
")",
"return",
"type_",
"(",
"zip",
"(",
"fields_iterator",
",",
"fields_iterator",
")",
")"
] | 49.5 | 6.75 |
def get_invoices_per_page(self, per_page=1000, page=1, params=None):
"""
Get invoices per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
re... | [
"def",
"get_invoices_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"INVOICES",
",",
"per_page",
"=",
"per_page",
","... | 40.7 | 20.5 |
def generator_to_list(function):
"""
Wrap a generator function so that it returns a list when called.
For example:
# Define a generator
>>> def mygen(n):
... i = 0
... while i < n:
... yield i
... i += 1
# This is ... | [
"def",
"generator_to_list",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"list",
"(",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"wrapper",
".",
"__name__",
"=",
"... | 26.724138 | 15.758621 |
def get_authorization_admin_session_for_vault(self, vault_id):
"""Gets the ``OsidSession`` associated with the authorization admin service for the given vault.
arg: vault_id (osid.id.Id): the ``Id`` of the vault
return: (osid.authorization.AuthorizationAdminSession) - ``an
_a... | [
"def",
"get_authorization_admin_session_for_vault",
"(",
"self",
",",
"vault_id",
")",
":",
"if",
"not",
"self",
".",
"supports_authorization_admin",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see if the catalog Id i... | 49.73913 | 20.826087 |
def parse_cfgstr_list(cfgstr_list, smartcast=True, oldmode=True):
r"""
Parses a list of items in the format
['var1:val1', 'var2:val2', 'var3:val3']
the '=' character can be used instead of the ':' character if desired
TODO: see ut.parse_cfgstr3
Args:
cfgstr_list (list):
Returns:
... | [
"def",
"parse_cfgstr_list",
"(",
"cfgstr_list",
",",
"smartcast",
"=",
"True",
",",
"oldmode",
"=",
"True",
")",
":",
"cfgdict",
"=",
"{",
"}",
"for",
"item",
"in",
"cfgstr_list",
":",
"if",
"item",
"==",
"''",
":",
"continue",
"if",
"oldmode",
":",
"k... | 34.92 | 22.14 |
def debug(verbose):
"""Run the experiment locally."""
(id, tmp) = setup_experiment(debug=True, verbose=verbose)
# Drop all the tables from the database.
db.init_db(drop_all=True)
# Switch to the temporary directory.
cwd = os.getcwd()
os.chdir(tmp)
# Load psiTurk configuration.
con... | [
"def",
"debug",
"(",
"verbose",
")",
":",
"(",
"id",
",",
"tmp",
")",
"=",
"setup_experiment",
"(",
"debug",
"=",
"True",
",",
"verbose",
"=",
"verbose",
")",
"# Drop all the tables from the database.",
"db",
".",
"init_db",
"(",
"drop_all",
"=",
"True",
"... | 31.974684 | 21.126582 |
def respects(g,imp):
"""
g is an int, where each bit is an attribute
implication UV is ternary coded 1 = ∈V, 2 = ∈U, 0 otherwise
g and UV have the same number of digits
"""
if isinstance(g,str):
g = int(g,2)
if isinstance(imp,int):
imp = istr(imp,3,g.bit_length())
V = int... | [
"def",
"respects",
"(",
"g",
",",
"imp",
")",
":",
"if",
"isinstance",
"(",
"g",
",",
"str",
")",
":",
"g",
"=",
"int",
"(",
"g",
",",
"2",
")",
"if",
"isinstance",
"(",
"imp",
",",
"int",
")",
":",
"imp",
"=",
"istr",
"(",
"imp",
",",
"3",... | 31.2 | 12 |
def get_subfields(self, datafield, subfield, i1=None, i2=None,
exception=False):
"""
Return content of given `subfield` in `datafield`.
Args:
datafield (str): Section name (for example "001", "100", "700").
subfield (str): Subfield name (for exampl... | [
"def",
"get_subfields",
"(",
"self",
",",
"datafield",
",",
"subfield",
",",
"i1",
"=",
"None",
",",
"i2",
"=",
"None",
",",
"exception",
"=",
"False",
")",
":",
"if",
"len",
"(",
"datafield",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"`data... | 36.617647 | 24 |
def render(self, request, template, context):
"""
Returns a response. By default, this will contain the rendered PDF, but
if both ``allow_force_html`` is ``True`` and the querystring
``html=true`` was set it will return a plain HTML.
"""
if self.allow_force_html and self.... | [
"def",
"render",
"(",
"self",
",",
"request",
",",
"template",
",",
"context",
")",
":",
"if",
"self",
".",
"allow_force_html",
"and",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"'html'",
",",
"False",
")",
":",
"html",
"=",
"get_template",
... | 42.857143 | 15.714286 |
def tools(self, extra_params=None):
""""
All Tools in this Space
"""
return self.api._get_json(
SpaceTool,
space=self,
rel_path=self._build_rel_path('space_tools'),
extra_params=extra_params,
) | [
"def",
"tools",
"(",
"self",
",",
"extra_params",
"=",
"None",
")",
":",
"return",
"self",
".",
"api",
".",
"_get_json",
"(",
"SpaceTool",
",",
"space",
"=",
"self",
",",
"rel_path",
"=",
"self",
".",
"_build_rel_path",
"(",
"'space_tools'",
")",
",",
... | 27.2 | 10.5 |
def _is_socket(cls, stream):
"""Check if the given stream is a socket."""
try:
fd = stream.fileno()
except ValueError:
# If it has no file descriptor, it's not a socket
return False
sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW)
try... | [
"def",
"_is_socket",
"(",
"cls",
",",
"stream",
")",
":",
"try",
":",
"fd",
"=",
"stream",
".",
"fileno",
"(",
")",
"except",
"ValueError",
":",
"# If it has no file descriptor, it's not a socket",
"return",
"False",
"sock",
"=",
"socket",
".",
"fromfd",
"(",
... | 35.526316 | 17.210526 |
def filter_kepler_lcdict(lcdict,
filterflags=True,
nanfilter='sap,pdc',
timestoignore=None):
'''This filters the Kepler `lcdict`, removing nans and bad
observations.
By default, this function removes points in the Kepler LC that hav... | [
"def",
"filter_kepler_lcdict",
"(",
"lcdict",
",",
"filterflags",
"=",
"True",
",",
"nanfilter",
"=",
"'sap,pdc'",
",",
"timestoignore",
"=",
"None",
")",
":",
"cols",
"=",
"lcdict",
"[",
"'columns'",
"]",
"# filter all bad LC points as noted by quality flags",
"if"... | 29.712 | 22.064 |
def get_payments(self):
"""Get all your payments.
Returns:
list of dicts: payments
For each payout in the list, a dict contains the following items:
* nmrAmount (`decimal.Decimal`)
* usdAmount (`decimal.Decimal`)
* tournament (`s... | [
"def",
"get_payments",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n query {\n user {\n payments {\n nmrAmount\n round {\n number\n openTime\n resolveTime\n resolvedGen... | 33.583333 | 15.75 |
def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False):
'''
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* a... | [
"def",
"page",
"(",
"title",
"=",
"None",
",",
"pageid",
"=",
"None",
",",
"auto_suggest",
"=",
"True",
",",
"redirect",
"=",
"True",
",",
"preload",
"=",
"False",
")",
":",
"if",
"title",
"is",
"not",
"None",
":",
"if",
"auto_suggest",
":",
"results... | 38.814815 | 25.333333 |
def glymurrc_fname():
"""Return the path to the configuration file.
Search order:
1) current working directory
2) environ var XDG_CONFIG_HOME
3) $HOME/.config/glymur/glymurrc
"""
# Current directory.
fname = os.path.join(os.getcwd(), 'glymurrc')
if os.path.exists(fname)... | [
"def",
"glymurrc_fname",
"(",
")",
":",
"# Current directory.",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'glymurrc'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"return",
"fname... | 24.818182 | 15.727273 |
def _nemo_accpars(self,vo,ro):
"""
NAME:
_nemo_accpars
PURPOSE:
return the accpars potential parameters for use of this potential with NEMO
INPUT:
vo - velocity unit in km/s
ro - length unit in kpc
OUTPUT:
accpars str... | [
"def",
"_nemo_accpars",
"(",
"self",
",",
"vo",
",",
"ro",
")",
":",
"warnings",
".",
"warn",
"(",
"\"NEMO's LogPot does not allow flattening in z (for some reason); therefore, flip y and z in NEMO wrt galpy; also does not allow the triaxial b parameter\"",
",",
"galpyWarning",
")"... | 26.266667 | 29.933333 |
def all(self, fields=None, include_fields=True, page=None, per_page=None, extra_params=None):
"""Retrieves a list of all the applications.
Important: The client_secret and encryption_key attributes can only be
retrieved with the read:client_keys scope.
Args:
fields (list of ... | [
"def",
"all",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"include_fields",
"=",
"True",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"extra_params",
"=",
"None",
")",
":",
"params",
"=",
"extra_params",
"or",
"{",
"}",
"params",
"[... | 41.875 | 28.15625 |
def send_quick_chat(self, team_only, quick_chat):
"""
Sends a quick chat to the other bots.
If it is QuickChats.CHAT_NONE or None it does not send a quick chat to other bots.
:param team_only: either True or False, this says if the quick chat should only go to team members.
:para... | [
"def",
"send_quick_chat",
"(",
"self",
",",
"team_only",
",",
"quick_chat",
")",
":",
"if",
"quick_chat",
"==",
"QuickChats",
".",
"CHAT_NONE",
"or",
"quick_chat",
"is",
"None",
":",
"return",
"self",
".",
"__quick_chat_func",
"(",
"team_only",
",",
"quick_cha... | 55 | 25.2 |
def add_raw_code(self, string_or_list):
"""Add raw Gmsh code.
"""
if _is_string(string_or_list):
self._GMSH_CODE.append(string_or_list)
else:
assert isinstance(string_or_list, list)
for string in string_or_list:
self._GMSH_CODE.append(s... | [
"def",
"add_raw_code",
"(",
"self",
",",
"string_or_list",
")",
":",
"if",
"_is_string",
"(",
"string_or_list",
")",
":",
"self",
".",
"_GMSH_CODE",
".",
"append",
"(",
"string_or_list",
")",
"else",
":",
"assert",
"isinstance",
"(",
"string_or_list",
",",
"... | 33.2 | 8.4 |
def coarsen_matrix(Z, xlevel=0, ylevel=0, method='average'):
"""
This returns a coarsened numpy matrix.
method can be 'average', 'maximum', or 'minimum'
"""
# coarsen x
if not ylevel:
Z_coarsened = Z
else:
temp = []
for z in Z: temp.append(coarsen_array(z, ylevel, m... | [
"def",
"coarsen_matrix",
"(",
"Z",
",",
"xlevel",
"=",
"0",
",",
"ylevel",
"=",
"0",
",",
"method",
"=",
"'average'",
")",
":",
"# coarsen x",
"if",
"not",
"ylevel",
":",
"Z_coarsened",
"=",
"Z",
"else",
":",
"temp",
"=",
"[",
"]",
"for",
"z",
"in"... | 26.428571 | 21.971429 |
def parse(text):
"""Try to parse into a date.
Return:
tuple (year, month, date) if successful; otherwise None.
"""
try:
ymd = text.lower().split('-')
assert len(ymd) == 3
year = -1 if ymd[0] in ('xx', 'xxxx') else int(ymd[0])
m... | [
"def",
"parse",
"(",
"text",
")",
":",
"try",
":",
"ymd",
"=",
"text",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'-'",
")",
"assert",
"len",
"(",
"ymd",
")",
"==",
"3",
"year",
"=",
"-",
"1",
"if",
"ymd",
"[",
"0",
"]",
"in",
"(",
"'xx'",... | 36.555556 | 14.5 |
def convert_layer_to_pil(layer, apply_icc=True, **kwargs):
"""Convert Layer to PIL Image."""
from PIL import Image
header = layer._psd._record.header
if header.color_mode == ColorMode.BITMAP:
raise NotImplementedError
width, height = layer.width, layer.height
channels, alpha = [], None
... | [
"def",
"convert_layer_to_pil",
"(",
"layer",
",",
"apply_icc",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"PIL",
"import",
"Image",
"header",
"=",
"layer",
".",
"_psd",
".",
"_record",
".",
"header",
"if",
"header",
".",
"color_mode",
"==",
... | 38.388889 | 15.305556 |
def get_immoralities(self):
"""
Finds all the immoralities in the model
A v-structure X -> Z <- Y is an immorality if there is no direct edge between X and Y .
Returns
-------
set: A set of all the immoralities in the model
Examples
---------
>>>... | [
"def",
"get_immoralities",
"(",
"self",
")",
":",
"immoralities",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
"(",
")",
":",
"for",
"parents",
"in",
"itertools",
".",
"combinations",
"(",
"self",
".",
"predecessors",
"(",
"node",
"... | 38.333333 | 21.833333 |
def xml_extract_date(node, xpath, date_format='%d/%m/%Y'):
"""
:param node: the node to be queried
:param xpath: the path to fetch the child node that has the wanted date
"""
return datetime.strptime(xml_extract_text(node, xpath), date_format) | [
"def",
"xml_extract_date",
"(",
"node",
",",
"xpath",
",",
"date_format",
"=",
"'%d/%m/%Y'",
")",
":",
"return",
"datetime",
".",
"strptime",
"(",
"xml_extract_text",
"(",
"node",
",",
"xpath",
")",
",",
"date_format",
")"
] | 43 | 14.333333 |
def remove_tags(self, tags, **kwargs):
"""
:param tags: Tags to remove from the app
:type tags: array
Removes the specified application name tags (aliases) from this
app, so that it is no longer addressable by those aliases.
The current user must be a developer of the a... | [
"def",
"remove_tags",
"(",
"self",
",",
"tags",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_dxid",
"is",
"not",
"None",
":",
"return",
"dxpy",
".",
"api",
".",
"app_remove_tags",
"(",
"self",
".",
"_dxid",
",",
"input_params",
"=",
"{",
... | 39.5 | 24.375 |
def _estimate_p_values(self):
"""estimate the p-values for all features
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
p_values = []
for term_i in range(len(self.terms)):
p_values.append(self._compute_p_value(... | [
"def",
"_estimate_p_values",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"p_values",
"=",
"[",
"]",
"for",
"term_i",
"in",
"range",
"(",
"len",
"(",
"sel... | 31.181818 | 17.727273 |
def split_data(data, num_slice, batch_axis=0, even_split=True):
"""Splits an NDArray into `num_slice` slices along `batch_axis`.
Usually used for data parallelism where each slices is sent
to one device (i.e. GPU).
Parameters
----------
data : NDArray
A batch of data.
num_slice : in... | [
"def",
"split_data",
"(",
"data",
",",
"num_slice",
",",
"batch_axis",
"=",
"0",
",",
"even_split",
"=",
"True",
")",
":",
"size",
"=",
"data",
".",
"shape",
"[",
"batch_axis",
"]",
"if",
"even_split",
"and",
"size",
"%",
"num_slice",
"!=",
"0",
":",
... | 36.469388 | 20.612245 |
def _parse_current_member(self, previous_rank, values):
"""
Parses the column texts of a member row into a member dictionary.
Parameters
----------
previous_rank: :class:`dict`[int, str]
The last rank present in the rows.
values: tuple[:class:`str`]
... | [
"def",
"_parse_current_member",
"(",
"self",
",",
"previous_rank",
",",
"values",
")",
":",
"rank",
",",
"name",
",",
"vocation",
",",
"level",
",",
"joined",
",",
"status",
"=",
"values",
"rank",
"=",
"previous_rank",
"[",
"1",
"]",
"if",
"rank",
"==",
... | 37.333333 | 16.857143 |
def mf_aBl(self):
"""
These are the expected log likelihoods (node potentials)
as seen from the discrete states.
"""
mf_aBl = self._mf_aBl = np.zeros((self.T, self.num_states))
ids, dds, eds = self.init_dynamics_distns, self.dynamics_distns, \
self.emission_di... | [
"def",
"mf_aBl",
"(",
"self",
")",
":",
"mf_aBl",
"=",
"self",
".",
"_mf_aBl",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"T",
",",
"self",
".",
"num_states",
")",
")",
"ids",
",",
"dds",
",",
"eds",
"=",
"self",
".",
"init_dynamics_distns",
... | 39.052632 | 15.789474 |
def _parse_row(row):
"""Parses HTML row
:param row: HTML row
:return: list of values in row
"""
data = []
labels = HtmlTable._get_row_tag(row, "th")
if labels:
data += labels
columns = HtmlTable._get_row_tag(row, "td")
if columns:
... | [
"def",
"_parse_row",
"(",
"row",
")",
":",
"data",
"=",
"[",
"]",
"labels",
"=",
"HtmlTable",
".",
"_get_row_tag",
"(",
"row",
",",
"\"th\"",
")",
"if",
"labels",
":",
"data",
"+=",
"labels",
"columns",
"=",
"HtmlTable",
".",
"_get_row_tag",
"(",
"row"... | 19.444444 | 20.5 |
def _accept_responses(self, expected_header, info_cb, timeout_ms=None):
"""Accepts responses until the expected header or a FAIL.
Arguments:
expected_header: OKAY or DATA
info_cb: Optional callback for text sent from the bootloader.
timeout_ms: Timeout in milliseconds to wait for each respons... | [
"def",
"_accept_responses",
"(",
"self",
",",
"expected_header",
",",
"info_cb",
",",
"timeout_ms",
"=",
"None",
")",
":",
"while",
"True",
":",
"response",
"=",
"self",
".",
"usb",
".",
"read",
"(",
"64",
",",
"timeout_ms",
"=",
"timeout_ms",
")",
"head... | 38.083333 | 20.305556 |
def get_vlan_brief_input_request_type_get_next_request_last_rcvd_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
input = ET.SubElement(get_vlan_brief, "input")
... | [
"def",
"get_vlan_brief_input_request_type_get_next_request_last_rcvd_vlan_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vlan_brief",
"=",
"ET",
".",
"Element",
"(",
"\"get_vlan_brief\"",
")",
... | 47.857143 | 19.357143 |
def query_remote_ref(self, remote, ref):
"""Query remote repo about given ref.
:return: ``('tag', sha)`` if ref is a tag in remote
``('branch', sha)`` if ref is branch (aka "head") in remote
``(None, ref)`` if ref does not exist in remote. This happens
... | [
"def",
"query_remote_ref",
"(",
"self",
",",
"remote",
",",
"ref",
")",
":",
"out",
"=",
"self",
".",
"log_call",
"(",
"[",
"'git'",
",",
"'ls-remote'",
",",
"remote",
",",
"ref",
"]",
",",
"cwd",
"=",
"self",
".",
"cwd",
",",
"callwith",
"=",
"sub... | 49.333333 | 14.333333 |
def submit_jobs(root_dir, jobs, sgeargs=None):
""" Submit each of the passed jobs to the SGE server, using the passed
directory as root for SGE output.
- root_dir Path to output directory
- jobs List of Job objects
"""
waiting = list(jobs) # List of jobs still to... | [
"def",
"submit_jobs",
"(",
"root_dir",
",",
"jobs",
",",
"sgeargs",
"=",
"None",
")",
":",
"waiting",
"=",
"list",
"(",
"jobs",
")",
"# List of jobs still to be done",
"# Loop over the list of pending jobs, while there still are any",
"while",
"len",
"(",
"waiting",
"... | 40.588235 | 11.823529 |
def OnFindToolbarToggle(self, event):
"""Search toolbar toggle event handler"""
self.main_window.find_toolbar.SetGripperVisible(True)
find_toolbar_info = self.main_window._mgr.GetPane("find_toolbar")
self._toggle_pane(find_toolbar_info)
event.Skip() | [
"def",
"OnFindToolbarToggle",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"main_window",
".",
"find_toolbar",
".",
"SetGripperVisible",
"(",
"True",
")",
"find_toolbar_info",
"=",
"self",
".",
"main_window",
".",
"_mgr",
".",
"GetPane",
"(",
"\"find_tool... | 28.4 | 24.1 |
def times_csv(path, times, annotations=None, delimiter=',', fmt='%0.3f'):
r"""Save time steps as in CSV format. This can be used to store the output
of a beat-tracker or segmentation algorithm.
If only `times` are provided, the file will contain each value
of `times` on a row::
times[0]\n
... | [
"def",
"times_csv",
"(",
"path",
",",
"times",
",",
"annotations",
"=",
"None",
",",
"delimiter",
"=",
"','",
",",
"fmt",
"=",
"'%0.3f'",
")",
":",
"if",
"annotations",
"is",
"not",
"None",
"and",
"len",
"(",
"annotations",
")",
"!=",
"len",
"(",
"ti... | 26.507692 | 22.138462 |
def message(self, data):
"""Function to display messages to the user
"""
msg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
gtk.BUTTONS_CLOSE, data)
msg.set_resizable(1)
msg.set_title(self.dialog_title)
self.img.set_from_file... | [
"def",
"message",
"(",
"self",
",",
"data",
")",
":",
"msg",
"=",
"gtk",
".",
"MessageDialog",
"(",
"None",
",",
"gtk",
".",
"DIALOG_MODAL",
",",
"gtk",
".",
"MESSAGE_INFO",
",",
"gtk",
".",
"BUTTONS_CLOSE",
",",
"data",
")",
"msg",
".",
"set_resizable... | 34.916667 | 12.583333 |
def delete(self, ids):
"""
Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None
"""
url = build_uri_with_ids('api/v3/networkv4/%s/', ids)
return super(ApiNetworkIPv4, self).delete(url) | [
"def",
"delete",
"(",
"self",
",",
"ids",
")",
":",
"url",
"=",
"build_uri_with_ids",
"(",
"'api/v3/networkv4/%s/'",
",",
"ids",
")",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"delete",
"(",
"url",
")"
] | 28.1 | 17.3 |
def reset(self):
"""
Resets the value of config item to its default value.
"""
old_value = self._value
old_raw_str_value = self.raw_str_value
self._value = not_set
self.raw_str_value = not_set
new_value = self._value
if old_value is not_set:
... | [
"def",
"reset",
"(",
"self",
")",
":",
"old_value",
"=",
"self",
".",
"_value",
"old_raw_str_value",
"=",
"self",
".",
"raw_str_value",
"self",
".",
"_value",
"=",
"not_set",
"self",
".",
"raw_str_value",
"=",
"not_set",
"new_value",
"=",
"self",
".",
"_va... | 27.48 | 15.48 |
def toggleCollapseBefore( self ):
"""
Collapses the splitter before this handle.
"""
if ( self.isCollapsed() ):
self.uncollapse()
else:
self.collapse( XSplitterHandle.CollapseDirection.Before ) | [
"def",
"toggleCollapseBefore",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isCollapsed",
"(",
")",
")",
":",
"self",
".",
"uncollapse",
"(",
")",
"else",
":",
"self",
".",
"collapse",
"(",
"XSplitterHandle",
".",
"CollapseDirection",
".",
"Before",
"... | 31.25 | 11.25 |
def readcols(infile, cols=[0, 1, 2, 3], hms=False):
"""
Read the columns from an ASCII file as numpy arrays.
Parameters
----------
infile : str
Filename of ASCII file with array data as columns.
cols : list of int
List of 0-indexed column numbers for columns to be turned into n... | [
"def",
"readcols",
"(",
"infile",
",",
"cols",
"=",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
",",
"hms",
"=",
"False",
")",
":",
"fin",
"=",
"open",
"(",
"infile",
",",
"'r'",
")",
"outarr",
"=",
"[",
"]",
"for",
"l",
"in",
"fin",
".",
... | 28.068182 | 21.386364 |
def _format_object(obj, format_type=None):
"""Depending on settings calls either `format_keys` or `format_field_names`"""
if json_api_settings.FORMAT_KEYS is not None:
return format_keys(obj, format_type)
return format_field_names(obj, format_type) | [
"def",
"_format_object",
"(",
"obj",
",",
"format_type",
"=",
"None",
")",
":",
"if",
"json_api_settings",
".",
"FORMAT_KEYS",
"is",
"not",
"None",
":",
"return",
"format_keys",
"(",
"obj",
",",
"format_type",
")",
"return",
"format_field_names",
"(",
"obj",
... | 37.714286 | 14.571429 |
def bundle(self, app, results_dir):
"""Create a self-contained application bundle.
The bundle will contain the target classes, dependencies and resources.
"""
assert(isinstance(app, BundleCreate.App))
bundle_dir = self.get_bundle_dir(app.id, results_dir)
self.context.log.debug('creating {}'.fo... | [
"def",
"bundle",
"(",
"self",
",",
"app",
",",
"results_dir",
")",
":",
"assert",
"(",
"isinstance",
"(",
"app",
",",
"BundleCreate",
".",
"App",
")",
")",
"bundle_dir",
"=",
"self",
".",
"get_bundle_dir",
"(",
"app",
".",
"id",
",",
"results_dir",
")"... | 38.695652 | 23.5 |
def __process_by_ccore(self):
"""!
@brief Performs cluster analysis using CCORE (C/C++ part of pyclustering library).
"""
(self.__clusters, self.__noise, self.__ordering, self.__eps,
objects_indexes, objects_core_distances, objects_reachability_distances) = \
... | [
"def",
"__process_by_ccore",
"(",
"self",
")",
":",
"(",
"self",
".",
"__clusters",
",",
"self",
".",
"__noise",
",",
"self",
".",
"__ordering",
",",
"self",
".",
"__eps",
",",
"objects_indexes",
",",
"objects_core_distances",
",",
"objects_reachability_distance... | 42.863636 | 28 |
def spidex_human(variant_obj):
"""Translate SPIDEX annotation to human readable string."""
if variant_obj.get('spidex') is None:
return 'not_reported'
elif abs(variant_obj['spidex']) < SPIDEX_HUMAN['low']['pos'][1]:
return 'low'
elif abs(variant_obj['spidex']) < SPIDEX_HUMAN['medium']['p... | [
"def",
"spidex_human",
"(",
"variant_obj",
")",
":",
"if",
"variant_obj",
".",
"get",
"(",
"'spidex'",
")",
"is",
"None",
":",
"return",
"'not_reported'",
"elif",
"abs",
"(",
"variant_obj",
"[",
"'spidex'",
"]",
")",
"<",
"SPIDEX_HUMAN",
"[",
"'low'",
"]",... | 37.5 | 16.8 |
def connect(self, node="", rpcuser="", rpcpassword="", **kwargs):
""" Connect to blockchain network (internal use only)
"""
if not node:
if "node" in self.config:
node = self.config["node"]
else:
raise ValueError("A Blockchain node needs to... | [
"def",
"connect",
"(",
"self",
",",
"node",
"=",
"\"\"",
",",
"rpcuser",
"=",
"\"\"",
",",
"rpcpassword",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"node",
":",
"if",
"\"node\"",
"in",
"self",
".",
"config",
":",
"node",
"=",
"... | 37.9375 | 19.1875 |
def getCompressMod(self):
'''
getCompressMod - Return the module used for compression on this field
@return <module> - The module for compression
'''
if self.compressMode == COMPRESS_MODE_ZLIB:
return zlib
if self.compressMode == COMPRESS_MODE_BZ2:
return bz2
if self.compressMode == COMPRESS_MODE... | [
"def",
"getCompressMod",
"(",
"self",
")",
":",
"if",
"self",
".",
"compressMode",
"==",
"COMPRESS_MODE_ZLIB",
":",
"return",
"zlib",
"if",
"self",
".",
"compressMode",
"==",
"COMPRESS_MODE_BZ2",
":",
"return",
"bz2",
"if",
"self",
".",
"compressMode",
"==",
... | 35.428571 | 32.571429 |
def set_bookmarks(self, bookmarks):
"""
Store the sequence of bookmarks `bookmarks`.
Causes signals to be fired to reflect the changes.
.. note:: This should normally not be used. It does not
mitigate the race condition between clients
concurrently m... | [
"def",
"set_bookmarks",
"(",
"self",
",",
"bookmarks",
")",
":",
"with",
"(",
"yield",
"from",
"self",
".",
"_lock",
")",
":",
"yield",
"from",
"self",
".",
"_set_bookmarks",
"(",
"bookmarks",
")",
"self",
".",
"_diff_emit_update",
"(",
"bookmarks",
")"
] | 44.5 | 17.5 |
def pass_defaults(func):
"""Decorator that returns a function named wrapper.
When invoked, wrapper invokes func with default kwargs appended.
Parameters
----------
func : callable
The function to append the default kwargs to
"""
@functools.wraps(func)
def wrapper(self, *args, *... | [
"def",
"pass_defaults",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"merged",
"=",
"{",
"}",
"merged",
".",
"update",
"(",
"self",
".... | 27.176471 | 16.705882 |
def plot_net(fignum):
"""
Draws circle and tick marks for equal area projection.
"""
# make the perimeter
plt.figure(num=fignum,)
plt.clf()
plt.axis("off")
Dcirc = np.arange(0, 361.)
Icirc = np.zeros(361, 'f')
Xcirc, Ycirc = [], []
for k in range(361):
XY = pmag.dimap(Dc... | [
"def",
"plot_net",
"(",
"fignum",
")",
":",
"# make the perimeter",
"plt",
".",
"figure",
"(",
"num",
"=",
"fignum",
",",
")",
"plt",
".",
"clf",
"(",
")",
"plt",
".",
"axis",
"(",
"\"off\"",
")",
"Dcirc",
"=",
"np",
".",
"arange",
"(",
"0",
",",
... | 26.519231 | 13.019231 |
def get_query_batch_request(self, batch_id, job_id=None):
""" Fetch the request sent for the batch. Note should only used for query batches """
if not job_id:
job_id = self.lookup_job_id(batch_id)
url = self.endpoint + "/job/{}/batch/{}/request".format(job_id, batch_id)
resp... | [
"def",
"get_query_batch_request",
"(",
"self",
",",
"batch_id",
",",
"job_id",
"=",
"None",
")",
":",
"if",
"not",
"job_id",
":",
"job_id",
"=",
"self",
".",
"lookup_job_id",
"(",
"batch_id",
")",
"url",
"=",
"self",
".",
"endpoint",
"+",
"\"/job/{}/batch/... | 45.888889 | 18.444444 |
def _fetch(self):
"""forces update of a local cached copy of the real object
(regardless of the preference setting self.cache)"""
if not self._obcache_current:
from distob import engine
ax = self._distaxis
self._obcache = concatenate([ra._ob for ra in self._su... | [
"def",
"_fetch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_obcache_current",
":",
"from",
"distob",
"import",
"engine",
"ax",
"=",
"self",
".",
"_distaxis",
"self",
".",
"_obcache",
"=",
"concatenate",
"(",
"[",
"ra",
".",
"_ob",
"for",
"ra",
... | 49.75 | 12.125 |
def new_format(self, navbar: BeautifulSoup, content: BeautifulSoup) -> List[str]:
"""
Extracts email message information if it uses the new Mailman format
Args:
content: BeautifulSoup
Returns: List[str]
"""
sender = content.find(id='from').text.spli... | [
"def",
"new_format",
"(",
"self",
",",
"navbar",
":",
"BeautifulSoup",
",",
"content",
":",
"BeautifulSoup",
")",
"->",
"List",
"[",
"str",
"]",
":",
"sender",
"=",
"content",
".",
"find",
"(",
"id",
"=",
"'from'",
")",
".",
"text",
".",
"split",
"("... | 41.84 | 22 |
def migrate_case(adapter: MongoAdapter, scout_case: dict, archive_data: dict):
"""Migrate case information from archive."""
# update collaborators
collaborators = list(set(scout_case['collaborators'] + archive_data['collaborators']))
if collaborators != scout_case['collaborators']:
LOG.info(f"se... | [
"def",
"migrate_case",
"(",
"adapter",
":",
"MongoAdapter",
",",
"scout_case",
":",
"dict",
",",
"archive_data",
":",
"dict",
")",
":",
"# update collaborators",
"collaborators",
"=",
"list",
"(",
"set",
"(",
"scout_case",
"[",
"'collaborators'",
"]",
"+",
"ar... | 43.254545 | 19.909091 |
def frame(y, frame_length=2048, hop_length=512):
'''Slice a time series into overlapping frames.
This implementation uses low-level stride manipulation to avoid
redundant copies of the time series data.
Parameters
----------
y : np.ndarray [shape=(n,)]
Time series to frame. Must be one... | [
"def",
"frame",
"(",
"y",
",",
"frame_length",
"=",
"2048",
",",
"hop_length",
"=",
"512",
")",
":",
"if",
"not",
"isinstance",
"(",
"y",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ParameterError",
"(",
"'Input must be of type numpy.ndarray, '",
"'given ... | 34.121622 | 25.472973 |
def confd_state_internal_callpoints_notification_stream_replay_registration_type_file_file(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.S... | [
"def",
"confd_state_internal_callpoints_notification_stream_replay_registration_type_file_file",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"confd_state",
"=",
"ET",
".",
"SubElement",
"(",
"config",
... | 54.235294 | 22.882353 |
def mget(self, pat=None):
"""
Get a dictionary mapping of all k:v pairs with key matching
glob style expression `pat`.
"""
if pat is None:
return {}
expr = re.compile(fnmatch.translate(pat))
m = {}
for key in tuple(self.keys()):
#ma... | [
"def",
"mget",
"(",
"self",
",",
"pat",
"=",
"None",
")",
":",
"if",
"pat",
"is",
"None",
":",
"return",
"{",
"}",
"expr",
"=",
"re",
".",
"compile",
"(",
"fnmatch",
".",
"translate",
"(",
"pat",
")",
")",
"m",
"=",
"{",
"}",
"for",
"key",
"i... | 31.6 | 10.666667 |
def SchemaValidateCtxt(self, reader, options):
"""Use W3C XSD schema context to validate the document as it
is processed. Activation is only possible before the first
Read(). If @ctxt is None, then XML Schema validation is
deactivated. """
if reader is None: reader__o = No... | [
"def",
"SchemaValidateCtxt",
"(",
"self",
",",
"reader",
",",
"options",
")",
":",
"if",
"reader",
"is",
"None",
":",
"reader__o",
"=",
"None",
"else",
":",
"reader__o",
"=",
"reader",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderSchemaValidateCtx... | 50.555556 | 14.888889 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.