text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def dict_to_numpy_dict(obj_dict):
"""
Convert a dictionary of lists into a dictionary of numpy arrays
"""
return {key: np.asarray(value) if value is not None else None for key, value in obj_dict.items()} | [
"def",
"dict_to_numpy_dict",
"(",
"obj_dict",
")",
":",
"return",
"{",
"key",
":",
"np",
".",
"asarray",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
"else",
"None",
"for",
"key",
",",
"value",
"in",
"obj_dict",
".",
"items",
"(",
")",
"}"
... | 43 | 0.009132 |
def gen_timeout_resend(attempts):
"""Generate the time in seconds in which DHCPDISCOVER wil be retransmited.
[:rfc:`2131#section-3.1`]::
might retransmit the
DHCPREQUEST message four times, for a total delay of 60 seconds
[:rfc:`2131#section-4.1`]::
For example, in a 10Mb/sec Eth... | [
"def",
"gen_timeout_resend",
"(",
"attempts",
")",
":",
"timeout",
"=",
"2",
"**",
"(",
"attempts",
"+",
"1",
")",
"+",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"+",
"1",
")",
"logger",
".",
"debug",
"(",
"'next timeout resending will happen on %s'",
... | 43.8 | 0.000894 |
def select_copula(cls, X):
"""Select best copula function based on likelihood.
Args:
X: 2-dimensional `np.ndarray`
Returns:
tuple: `tuple(CopulaType, float)` best fit and model param.
"""
frank = Bivariate(CopulaTypes.FRANK)
frank.fit(X)
... | [
"def",
"select_copula",
"(",
"cls",
",",
"X",
")",
":",
"frank",
"=",
"Bivariate",
"(",
"CopulaTypes",
".",
"FRANK",
")",
"frank",
".",
"fit",
"(",
"X",
")",
"if",
"frank",
".",
"tau",
"<=",
"0",
":",
"selected_theta",
"=",
"frank",
".",
"theta",
"... | 32.58 | 0.001788 |
def parse(readDataInstance):
"""
Returns a new L{OptionalHeader} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{OptionalHeader} object.
@rtype: L{OptionalHeader}
@return: A new L{Op... | [
"def",
"parse",
"(",
"readDataInstance",
")",
":",
"oh",
"=",
"OptionalHeader",
"(",
")",
"oh",
".",
"magic",
".",
"value",
"=",
"readDataInstance",
".",
"readWord",
"(",
")",
"oh",
".",
"majorLinkerVersion",
".",
"value",
"=",
"readDataInstance",
".",
"re... | 51.895833 | 0.014578 |
def _parse_configs(self, config):
"""Builds a dict with information to connect to Clusters.
Parses the list of configuration dictionaries passed by the user and
builds an internal dict (_clusters) that holds information for creating
Clients connecting to Clusters and matching database n... | [
"def",
"_parse_configs",
"(",
"self",
",",
"config",
")",
":",
"for",
"config_dict",
"in",
"config",
":",
"label",
"=",
"config_dict",
".",
"keys",
"(",
")",
"[",
"0",
"]",
"cfg",
"=",
"config_dict",
"[",
"label",
"]",
"# Transform dbpath to something digest... | 40.325 | 0.001211 |
def strip(self):
"""Remove rollbacks, rollforwards, and all non-current files.
When distributing a refpkg, you probably want to distribute as
small a one as possible. strip removes everything from the
refpkg which is not relevant to its current state.
"""
self._sync_fro... | [
"def",
"strip",
"(",
"self",
")",
":",
"self",
".",
"_sync_from_disk",
"(",
")",
"current_filenames",
"=",
"set",
"(",
"self",
".",
"contents",
"[",
"'files'",
"]",
".",
"values",
"(",
")",
")",
"all_filenames",
"=",
"set",
"(",
"os",
".",
"listdir",
... | 42.894737 | 0.002401 |
def getVersion():
"""
Get version from local file.
"""
with open(os.path.join(REPO_DIR, "VERSION"), "r") as versionFile:
return versionFile.read().strip() | [
"def",
"getVersion",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"REPO_DIR",
",",
"\"VERSION\"",
")",
",",
"\"r\"",
")",
"as",
"versionFile",
":",
"return",
"versionFile",
".",
"read",
"(",
")",
".",
"strip",
"(",
")"
] | 26.833333 | 0.018072 |
def p_scalar__literal(self, p):
"""
scalar : B_LITERAL_START scalar_group B_LITERAL_END
"""
scalar_group = ''.join(p[2])
p[0] = ScalarDispatch('%s\n' % dedent(scalar_group).replace('\n\n\n', '\n'), cast='str') | [
"def",
"p_scalar__literal",
"(",
"self",
",",
"p",
")",
":",
"scalar_group",
"=",
"''",
".",
"join",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"ScalarDispatch",
"(",
"'%s\\n'",
"%",
"dedent",
"(",
"scalar_group",
")",
".",
"replace",
"... | 40.833333 | 0.012 |
def _read_date(settings_file):
"""Get the data from the settings.xml file
Parameters
----------
settings_file : Path
path to settings.xml inside open-ephys folder
Returns
-------
datetime
start time of the recordings
Notes
-----
The start time is present in the... | [
"def",
"_read_date",
"(",
"settings_file",
")",
":",
"root",
"=",
"ElementTree",
".",
"parse",
"(",
"settings_file",
")",
".",
"getroot",
"(",
")",
"for",
"e0",
"in",
"root",
":",
"if",
"e0",
".",
"tag",
"==",
"'INFO'",
":",
"for",
"e1",
"in",
"e0",
... | 24.423077 | 0.001515 |
def Rzderiv(self,R,Z,phi=0.,t=0.):
"""
NAME:
Rzderiv
PURPOSE:
evaluate the mixed R,z derivative
INPUT:
R - Galactocentric radius (can be Quantity)
Z - vertical height (can be Quantity)
phi - Galactocentric azimuth (can be Quan... | [
"def",
"Rzderiv",
"(",
"self",
",",
"R",
",",
"Z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"try",
":",
"return",
"self",
".",
"_amp",
"*",
"self",
".",
"_Rzderiv",
"(",
"R",
",",
"Z",
",",
"phi",
"=",
"phi",
",",
"t",
"=",
"... | 20.090909 | 0.017266 |
def _save_table(self, raw=False, cls=None, force_insert=None, force_update=None, using=None, update_fields=None):
"""
Saves the current instance.
"""
# Connection aliasing
connection = connections[using]
create = bool(force_insert or not self.dn)
# Prepare field... | [
"def",
"_save_table",
"(",
"self",
",",
"raw",
"=",
"False",
",",
"cls",
"=",
"None",
",",
"force_insert",
"=",
"None",
",",
"force_update",
"=",
"None",
",",
"using",
"=",
"None",
",",
"update_fields",
"=",
"None",
")",
":",
"# Connection aliasing",
"co... | 31.732558 | 0.001421 |
def convert_shaders(convert, shaders):
""" Modify shading code so that we can write code once
and make it run "everywhere".
"""
# New version of the shaders
out = []
if convert == 'es2':
for isfragment, shader in enumerate(shaders):
has_version = False
has_prec... | [
"def",
"convert_shaders",
"(",
"convert",
",",
"shaders",
")",
":",
"# New version of the shaders",
"out",
"=",
"[",
"]",
"if",
"convert",
"==",
"'es2'",
":",
"for",
"isfragment",
",",
"shader",
"in",
"enumerate",
"(",
"shaders",
")",
":",
"has_version",
"="... | 35.118644 | 0.000469 |
def startup(self):
"""Startup the ec2 instance
"""
import boto.ec2
if not self.browser_config.get('launch'):
self.warning_log("Skipping launch")
return True
self.info_log("Starting up")
instance = None
try:
# KEY NAME
... | [
"def",
"startup",
"(",
"self",
")",
":",
"import",
"boto",
".",
"ec2",
"if",
"not",
"self",
".",
"browser_config",
".",
"get",
"(",
"'launch'",
")",
":",
"self",
".",
"warning_log",
"(",
"\"Skipping launch\"",
")",
"return",
"True",
"self",
".",
"info_lo... | 35.657609 | 0.000297 |
def _run(self):
"""The inside of ``run``'s infinite loop.
Separated out so it can be properly unit tested.
"""
tup = self.read_tuple()
self._current_tups = [tup]
if self.is_heartbeat(tup):
self.send_message({"command": "sync"})
elif self.is_tick(tup):... | [
"def",
"_run",
"(",
"self",
")",
":",
"tup",
"=",
"self",
".",
"read_tuple",
"(",
")",
"self",
".",
"_current_tups",
"=",
"[",
"tup",
"]",
"if",
"self",
".",
"is_heartbeat",
"(",
"tup",
")",
":",
"self",
".",
"send_message",
"(",
"{",
"\"command\"",
... | 36 | 0.00246 |
def getAnalogType(self,num):
"""
Returns the type of the channel 'num' based
on its unit stored in the Comtrade header file.
Returns 'V' for a voltage channel and 'I' for a current channel.
"""
listidx = self.An.index(num)
unit = self.uu[listidx]
... | [
"def",
"getAnalogType",
"(",
"self",
",",
"num",
")",
":",
"listidx",
"=",
"self",
".",
"An",
".",
"index",
"(",
"num",
")",
"unit",
"=",
"self",
".",
"uu",
"[",
"listidx",
"]",
"if",
"unit",
"==",
"'kV'",
"or",
"unit",
"==",
"'V'",
":",
"return"... | 29.529412 | 0.009653 |
def cmp_regs(cpu, should_print=False):
"""
Compare registers from a remote gdb session to current mcore.
:param manticore.core.cpu Cpu: Current cpu
:param bool should_print: Whether to print values to stdout
:return: Whether or not any differences were detected
:rtype: bool
"""
differin... | [
"def",
"cmp_regs",
"(",
"cpu",
",",
"should_print",
"=",
"False",
")",
":",
"differing",
"=",
"False",
"gdb_regs",
"=",
"gdb",
".",
"getCanonicalRegisters",
"(",
")",
"for",
"name",
"in",
"sorted",
"(",
"gdb_regs",
")",
":",
"vg",
"=",
"gdb_regs",
"[",
... | 32.12 | 0.001209 |
def traversals(edges, mode='bfs'):
"""
Given an edge list, generate a sequence of ordered
depth first search traversals, using scipy.csgraph routines.
Parameters
------------
edges : (n,2) int, undirected edges of a graph
mode : str, 'bfs', or 'dfs'
Returns
-----------
travers... | [
"def",
"traversals",
"(",
"edges",
",",
"mode",
"=",
"'bfs'",
")",
":",
"edges",
"=",
"np",
".",
"asanyarray",
"(",
"edges",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"if",
"len",
"(",
"edges",
")",
"==",
"0",
":",
"return",
"[",
"]",
"elif",
... | 29.054545 | 0.000605 |
def guestfs_conn_ro(disk):
"""
Open a GuestFS handle and add `disk` in read only mode.
Args:
disk(disk path): Path to the disk.
Yields:
guestfs.GuestFS: Open GuestFS handle
Raises:
:exc:`GuestFSError`: On any guestfs operation failure
"""
disk_path = os.path.expan... | [
"def",
"guestfs_conn_ro",
"(",
"disk",
")",
":",
"disk_path",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"disk",
")",
"conn",
"=",
"guestfs",
".",
"GuestFS",
"(",
"python_return_dict",
"=",
"True",
")",
"conn",
".",
"add_drive_ro",
"(",
"disk_path",
... | 24.612903 | 0.001261 |
def collapse(self):
"""Collapse a private message or modmail."""
url = self.reddit_session.config['collapse_message']
self.reddit_session.request_json(url, data={'id': self.name}) | [
"def",
"collapse",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"reddit_session",
".",
"config",
"[",
"'collapse_message'",
"]",
"self",
".",
"reddit_session",
".",
"request_json",
"(",
"url",
",",
"data",
"=",
"{",
"'id'",
":",
"self",
".",
"name",
... | 50 | 0.009852 |
def getLabel(self,form):
"""A label can be a string, dict (lookup by name) or a callable (passed the form)."""
return specialInterpretValue(self.label,self.name,form=form) | [
"def",
"getLabel",
"(",
"self",
",",
"form",
")",
":",
"return",
"specialInterpretValue",
"(",
"self",
".",
"label",
",",
"self",
".",
"name",
",",
"form",
"=",
"form",
")"
] | 61.666667 | 0.032086 |
def business_rule_notification_is_blocked(self, hosts, services):
# pylint: disable=too-many-locals
"""Process business rule notifications behaviour. If all problems have
been acknowledged, no notifications should be sent if state is not OK.
By default, downtimes are ignored, unless expl... | [
"def",
"business_rule_notification_is_blocked",
"(",
"self",
",",
"hosts",
",",
"services",
")",
":",
"# pylint: disable=too-many-locals",
"# Walks through problems to check if all items in non ok are",
"# acknowledged or in downtime period.",
"acknowledged",
"=",
"0",
"for",
"src_... | 50.305556 | 0.001625 |
def data_properties(data, mask=None, background=None):
"""
Calculate the morphological properties (and centroid) of a 2D array
(e.g. an image cutout of an object) using image moments.
Parameters
----------
data : array_like or `~astropy.units.Quantity`
The 2D array of the image.
ma... | [
"def",
"data_properties",
"(",
"data",
",",
"mask",
"=",
"None",
",",
"background",
"=",
"None",
")",
":",
"from",
".",
".",
"segmentation",
"import",
"SourceProperties",
"# prevent circular imports",
"segment_image",
"=",
"np",
".",
"ones",
"(",
"data",
".",
... | 40.722222 | 0.000666 |
def get(self, show=True, proxy=None, timeout=0):
"""
Make Mediawiki, RESTBase, and Wikidata requests for page data
some sequence of:
- get_parse()
- get_query()
- get_restbase()
- get_wikidata()
"""
wikibase = self.params.get('wikibase')
i... | [
"def",
"get",
"(",
"self",
",",
"show",
"=",
"True",
",",
"proxy",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"wikibase",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'wikibase'",
")",
"if",
"wikibase",
":",
"self",
".",
"flags",
"[",
"'de... | 27.46 | 0.001406 |
def local_incoming_hook(handler=None, coro=None):
"""add a callback to run every time a greenlet is about to be switched to
:param handler:
the callback function, must be a function taking 2 arguments:
- an integer indicating whether it is being called as an incoming (1)
hook or an o... | [
"def",
"local_incoming_hook",
"(",
"handler",
"=",
"None",
",",
"coro",
"=",
"None",
")",
":",
"if",
"handler",
"is",
"None",
":",
"return",
"lambda",
"h",
":",
"local_incoming_hook",
"(",
"h",
",",
"coro",
")",
"if",
"not",
"hasattr",
"(",
"handler",
... | 35.151515 | 0.000839 |
def _match_transition(self, transition):
"""Checks whether a given Transition matches self.names."""
return (self.names == '*'
or transition in self.names
or transition.name in self.names) | [
"def",
"_match_transition",
"(",
"self",
",",
"transition",
")",
":",
"return",
"(",
"self",
".",
"names",
"==",
"'*'",
"or",
"transition",
"in",
"self",
".",
"names",
"or",
"transition",
".",
"name",
"in",
"self",
".",
"names",
")"
] | 46.4 | 0.008475 |
def get_counter(self, counter_name, default=0):
"""Get the value of the named counter from this job.
When a job is running, counter values won't be very accurate.
Args:
counter_name: name of the counter in string.
default: default value if the counter doesn't exist.
Returns:
Value i... | [
"def",
"get_counter",
"(",
"self",
",",
"counter_name",
",",
"default",
"=",
"0",
")",
":",
"self",
".",
"__update_state",
"(",
")",
"return",
"self",
".",
"_state",
".",
"counters_map",
".",
"get",
"(",
"counter_name",
",",
"default",
")"
] | 30.785714 | 0.002252 |
def _decode_quadratic_biases(quadratic_string, edgelist):
"""Inverse of _serialize_quadratic_biases
Args:
quadratic_string (str) : base 64 encoded string of little
endian 8 byte floats, one for each of the edges.
edgelist (list): a list of edges of the form [(node1, node2), ...].
... | [
"def",
"_decode_quadratic_biases",
"(",
"quadratic_string",
",",
"edgelist",
")",
":",
"quadratic_bytes",
"=",
"base64",
".",
"b64decode",
"(",
"quadratic_string",
")",
"return",
"{",
"tuple",
"(",
"edge",
")",
":",
"bias",
"for",
"edge",
",",
"bias",
"in",
... | 39.952381 | 0.002328 |
def get_as_string_with_default(self, index, default_value):
"""
Converts array element into a string or returns default value if conversion is not possible.
:param index: an index of element to get.
:param default_value: the default value
:return: string value ot the element o... | [
"def",
"get_as_string_with_default",
"(",
"self",
",",
"index",
",",
"default_value",
")",
":",
"value",
"=",
"self",
"[",
"index",
"]",
"return",
"StringConverter",
".",
"to_string_with_default",
"(",
"value",
",",
"default_value",
")"
] | 39.333333 | 0.008282 |
def sendFMS_same(self, CorpNum, PlusFriendID, Sender, Content, AltContent, AltSendType, SndDT, FilePath, ImageURL,
KakaoMessages, KakaoButtons, AdsYN=False, UserID=None, RequestNum=None):
"""
친구톡 이미지 대량 전송
:param CorpNum: 팝빌회원 사업자번호
:param PlusFriendID: 플러스친구 아이디
... | [
"def",
"sendFMS_same",
"(",
"self",
",",
"CorpNum",
",",
"PlusFriendID",
",",
"Sender",
",",
"Content",
",",
"AltContent",
",",
"AltSendType",
",",
"SndDT",
",",
"FilePath",
",",
"ImageURL",
",",
"KakaoMessages",
",",
"KakaoButtons",
",",
"AdsYN",
"=",
"Fals... | 38.825397 | 0.001994 |
def extract_lookups(value):
"""Recursively extracts any stack lookups within the data structure.
Args:
value (one of str, list, dict): a structure that contains lookups to
output values
Returns:
list: list of lookups if any
"""
lookups = set()
if isinstance(value, ... | [
"def",
"extract_lookups",
"(",
"value",
")",
":",
"lookups",
"=",
"set",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"lookups",
"=",
"lookups",
".",
"union",
"(",
"extract_lookups_from_string",
"(",
"value",
")",
")",
"elif",
... | 30.285714 | 0.001524 |
def read(self, size:int=None):
"""
:param size: number of characters to read from the buffer
:return: string that has been read from the buffer
"""
if size:
result = self._buffer[0:size]
self._buffer = self._buffer[size:]
return result
... | [
"def",
"read",
"(",
"self",
",",
"size",
":",
"int",
"=",
"None",
")",
":",
"if",
"size",
":",
"result",
"=",
"self",
".",
"_buffer",
"[",
"0",
":",
"size",
"]",
"self",
".",
"_buffer",
"=",
"self",
".",
"_buffer",
"[",
"size",
":",
"]",
"retur... | 31 | 0.012048 |
def set_input(self, input_id):
"""Send Input command."""
req_url = ENDPOINTS["setInput"].format(self.ip_address, self.zone_id)
params = {"input": input_id}
return request(req_url, params=params) | [
"def",
"set_input",
"(",
"self",
",",
"input_id",
")",
":",
"req_url",
"=",
"ENDPOINTS",
"[",
"\"setInput\"",
"]",
".",
"format",
"(",
"self",
".",
"ip_address",
",",
"self",
".",
"zone_id",
")",
"params",
"=",
"{",
"\"input\"",
":",
"input_id",
"}",
"... | 44.4 | 0.00885 |
def list_queues(region, opts=None, user=None):
'''
List the queues in the selected region.
region
Region to list SQS queues for
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
CLI Example:
... | [
"def",
"list_queues",
"(",
"region",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"out",
"=",
"_run_aws",
"(",
"'list-queues'",
",",
"region",
",",
"opts",
",",
"user",
")",
"ret",
"=",
"{",
"'retcode'",
":",
"0",
",",
"'stdout'",
... | 19.84 | 0.001923 |
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn =... | [
"def",
"avail_images",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
... | 26.947368 | 0.001887 |
def sparse_to_matrix(sparse):
"""
Take a sparse (n,3) list of integer indexes of filled cells,
turn it into a dense (m,o,p) matrix.
Parameters
-----------
sparse: (n,3) int, index of filled cells
Returns
------------
dense: (m,o,p) bool, matrix of filled cells
"""
sparse =... | [
"def",
"sparse_to_matrix",
"(",
"sparse",
")",
":",
"sparse",
"=",
"np",
".",
"asanyarray",
"(",
"sparse",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"if",
"not",
"util",
".",
"is_shape",
"(",
"sparse",
",",
"(",
"-",
"1",
",",
"3",
")",
")",
":",... | 26.037037 | 0.001372 |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and display plugin enable...
if args.disable_process:
msg = "PROCESSES DISABLED (press 'z' to dis... | [
"def",
"msg_curse",
"(",
"self",
",",
"args",
"=",
"None",
",",
"max_width",
"=",
"None",
")",
":",
"# Init the return message",
"ret",
"=",
"[",
"]",
"# Only process if stats exist and display plugin enable...",
"if",
"args",
".",
"disable_process",
":",
"msg",
"... | 36.283582 | 0.001201 |
def add_number_mapping_from_dict(self, abi, mapping):
"""
Batch-associate syscall numbers with names of functions present in the underlying SimLibrary
:param abi: The abi for which this mapping applies
:param mapping: A dict mapping syscall numbers to function names
"""
... | [
"def",
"add_number_mapping_from_dict",
"(",
"self",
",",
"abi",
",",
"mapping",
")",
":",
"self",
".",
"syscall_number_mapping",
"[",
"abi",
"]",
".",
"update",
"(",
"mapping",
")",
"self",
".",
"syscall_name_mapping",
"[",
"abi",
"]",
".",
"update",
"(",
... | 50.444444 | 0.008658 |
def walk(p, mode='all', **kw):
"""Wrapper for `os.walk`, yielding `Path` objects.
:param p: root of the directory tree to walk.
:param mode: 'all|dirs|files', defaulting to 'all'.
:param kw: Keyword arguments are passed to `os.walk`.
:return: Generator for the requested Path objects.
"""
fo... | [
"def",
"walk",
"(",
"p",
",",
"mode",
"=",
"'all'",
",",
"*",
"*",
"kw",
")",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"as_posix",
"(",
"p",
")",
",",
"*",
"*",
"kw",
")",
":",
"if",
"mode",
"in"... | 41.266667 | 0.00158 |
def _create_genome_builds(self):
"""
Various resources will map variations to either UCSC (hg*)
or to NCBI assemblies. Here we create the equivalences between them.
Data taken from:
https://genome.ucsc.edu/FAQ/FAQreleases.html#release1
:return:
"""
# TO... | [
"def",
"_create_genome_builds",
"(",
"self",
")",
":",
"# TODO add more species",
"graph",
"=",
"self",
".",
"graph",
"geno",
"=",
"Genotype",
"(",
"graph",
")",
"model",
"=",
"Model",
"(",
"graph",
")",
"LOG",
".",
"info",
"(",
"\"Adding equivalent assembly i... | 34.880952 | 0.001992 |
def set_elem(elem_ref, elem):
"""
Sets element referenced by the elem_ref. Returns the elem.
:param elem_ref:
:param elem:
:return:
"""
if elem_ref is None or elem_ref == elem or not is_elem_ref(elem_ref):
return elem
elif elem_ref[0] == ElemRefObj:
setattr(elem_ref[1],... | [
"def",
"set_elem",
"(",
"elem_ref",
",",
"elem",
")",
":",
"if",
"elem_ref",
"is",
"None",
"or",
"elem_ref",
"==",
"elem",
"or",
"not",
"is_elem_ref",
"(",
"elem_ref",
")",
":",
"return",
"elem",
"elif",
"elem_ref",
"[",
"0",
"]",
"==",
"ElemRefObj",
"... | 24.388889 | 0.002193 |
def _add_to_ref(self, rec_curr, line, lnum):
"""Add new fields to the current reference."""
# Written by DV Klopfenstein
# Examples of record lines containing ':' include:
# id: GO:0000002
# name: mitochondrial genome maintenance
# namespace: biological_process
... | [
"def",
"_add_to_ref",
"(",
"self",
",",
"rec_curr",
",",
"line",
",",
"lnum",
")",
":",
"# Written by DV Klopfenstein",
"# Examples of record lines containing ':' include:",
"# id: GO:0000002",
"# name: mitochondrial genome maintenance",
"# namespace: biological_process",
"# ... | 45.875 | 0.001334 |
def transformer_tall_pretrain_lm_tpu_adafactor_large():
"""Hparams for transformer on LM pretraining on TPU, large model."""
hparams = transformer_tall_pretrain_lm_tpu_adafactor()
hparams.hidden_size = 1024
hparams.num_heads = 16
hparams.filter_size = 32768 # max fitting in 16G memory is 49152, batch 2
hpa... | [
"def",
"transformer_tall_pretrain_lm_tpu_adafactor_large",
"(",
")",
":",
"hparams",
"=",
"transformer_tall_pretrain_lm_tpu_adafactor",
"(",
")",
"hparams",
".",
"hidden_size",
"=",
"1024",
"hparams",
".",
"num_heads",
"=",
"16",
"hparams",
".",
"filter_size",
"=",
"3... | 49.727273 | 0.019749 |
def simOnePrd(self):
'''
Simulate one period of the fashion victom model for this type. Each
agent receives an idiosyncratic preference shock and chooses whether to
change styles (using the optimal decision rule).
Parameters
----------
none
Returns
... | [
"def",
"simOnePrd",
"(",
"self",
")",
":",
"pNow",
"=",
"self",
".",
"pNow",
"sPrev",
"=",
"self",
".",
"sNow",
"J2Pprob",
"=",
"self",
".",
"switchFuncJock",
"(",
"pNow",
")",
"P2Jprob",
"=",
"self",
".",
"switchFuncPunk",
"(",
"pNow",
")",
"Shks",
... | 29.68 | 0.013055 |
def _is_numeric_data(self, data_type):
"""Private method for testing text data types."""
dt = DATA_TYPES[data_type]
if dt['min'] and dt['max']:
if type(self.data) is dt['type'] and dt['min'] < self.data < dt['max']:
self.type = data_type.upper()
self.l... | [
"def",
"_is_numeric_data",
"(",
"self",
",",
"data_type",
")",
":",
"dt",
"=",
"DATA_TYPES",
"[",
"data_type",
"]",
"if",
"dt",
"[",
"'min'",
"]",
"and",
"dt",
"[",
"'max'",
"]",
":",
"if",
"type",
"(",
"self",
".",
"data",
")",
"is",
"dt",
"[",
... | 45.625 | 0.008065 |
def location_list(arg):
"""Joins a list of locations into a pipe separated string, handling
the various formats supported for lat/lng values.
For example:
p = [{"lat" : -33.867486, "lng" : 151.206990}, "Sydney"]
convert.waypoint(p)
# '-33.867486,151.206990|Sydney'
:param arg: The lat/lng l... | [
"def",
"location_list",
"(",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"tuple",
")",
":",
"# Handle the single-tuple lat/lng case.",
"return",
"latlng",
"(",
"arg",
")",
"else",
":",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"latlng",
"(",
"loc... | 28.578947 | 0.001783 |
def hit_count(self, request, hitcount):
"""
Called with a HttpRequest and HitCount object it will return a
namedtuple:
UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message').
`hit_counted` will be True if the hit was counted and False if it was
not. `'hit_m... | [
"def",
"hit_count",
"(",
"self",
",",
"request",
",",
"hitcount",
")",
":",
"UpdateHitCountResponse",
"=",
"namedtuple",
"(",
"'UpdateHitCountResponse'",
",",
"'hit_counted hit_message'",
")",
"# as of Django 1.8.4 empty sessions are not being saved",
"# https://code.djangoproj... | 43.235294 | 0.001596 |
def download_image(self, device_label, image_id, file_name):
""" Download image taken by a smartcam
Args:
device_label (str): device label of camera
image_id (str): image id from image series
file_name (str): path to file
"""
response = None
t... | [
"def",
"download_image",
"(",
"self",
",",
"device_label",
",",
"image_id",
",",
"file_name",
")",
":",
"response",
"=",
"None",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"urls",
".",
"download_image",
"(",
"self",
".",
"_giid",
",",
"dev... | 38.272727 | 0.002317 |
def delete_external_account(resource_root, name):
"""
Delete an external account by name
@param resource_root: The root Resource object.
@param name: Account name
@return: The deleted ApiExternalAccount object
"""
return call(resource_root.delete,
EXTERNAL_ACCOUNT_FETCH_PATH % ("delete", name,),
... | [
"def",
"delete_external_account",
"(",
"resource_root",
",",
"name",
")",
":",
"return",
"call",
"(",
"resource_root",
".",
"delete",
",",
"EXTERNAL_ACCOUNT_FETCH_PATH",
"%",
"(",
"\"delete\"",
",",
"name",
",",
")",
",",
"ApiExternalAccount",
",",
"False",
")"
... | 34 | 0.014327 |
def assign(self, partitions):
"""Manually assign a list of TopicPartitions to this consumer.
Arguments:
partitions (list of TopicPartition): Assignment for this instance.
Raises:
IllegalStateError: If consumer has already called
:meth:`~kafka.KafkaConsumer.s... | [
"def",
"assign",
"(",
"self",
",",
"partitions",
")",
":",
"self",
".",
"_subscription",
".",
"assign_from_user",
"(",
"partitions",
")",
"self",
".",
"_client",
".",
"set_topics",
"(",
"[",
"tp",
".",
"topic",
"for",
"tp",
"in",
"partitions",
"]",
")"
] | 40.555556 | 0.001784 |
def _ps_extract_pid(self, line):
"""
Extract PID and parent PID from an output line from the PS command
"""
this_pid = self.regex['pid'].sub(r'\g<1>', line)
this_parent = self.regex['parent'].sub(r'\g<1>', line)
# Return the main / parent PIDs
return this... | [
"def",
"_ps_extract_pid",
"(",
"self",
",",
"line",
")",
":",
"this_pid",
"=",
"self",
".",
"regex",
"[",
"'pid'",
"]",
".",
"sub",
"(",
"r'\\g<1>'",
",",
"line",
")",
"this_parent",
"=",
"self",
".",
"regex",
"[",
"'parent'",
"]",
".",
"sub",
"(",
... | 36.555556 | 0.008902 |
def crud_handler(Model, name=None, **kwds):
"""
This action handler factory reaturns an action handler that
responds to actions with CRUD types (following nautilus conventions)
and performs the necessary mutation on the model's database.
Args:
Model (nautilus.BaseModel):... | [
"def",
"crud_handler",
"(",
"Model",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"# import the necessary modules",
"from",
"nautilus",
".",
"network",
".",
"events",
"import",
"combine_action_handlers",
"from",
".",
"import",
"update_handler",
","... | 35.16 | 0.001107 |
def analyze(self):
"""Return a list giving the parameters required by a query."""
class MockBindings(dict):
def __contains__(self, key):
self[key] = None
return True
bindings = MockBindings()
used = {}
ancestor = self.ancestor
if isinstance(ancestor, ParameterizedThing):
... | [
"def",
"analyze",
"(",
"self",
")",
":",
"class",
"MockBindings",
"(",
"dict",
")",
":",
"def",
"__contains__",
"(",
"self",
",",
"key",
")",
":",
"self",
"[",
"key",
"]",
"=",
"None",
"return",
"True",
"bindings",
"=",
"MockBindings",
"(",
")",
"use... | 30 | 0.008081 |
def is_processing(self, taskid):
'''
return True if taskid is in processing
'''
return taskid in self.processing and self.processing[taskid].taskid | [
"def",
"is_processing",
"(",
"self",
",",
"taskid",
")",
":",
"return",
"taskid",
"in",
"self",
".",
"processing",
"and",
"self",
".",
"processing",
"[",
"taskid",
"]",
".",
"taskid"
] | 35 | 0.011173 |
def days_to_liquidate_positions(positions, market_data,
max_bar_consumption=0.2,
capital_base=1e6,
mean_volume_window=5):
"""
Compute the number of days that would have been required
to fully liquidate each posit... | [
"def",
"days_to_liquidate_positions",
"(",
"positions",
",",
"market_data",
",",
"max_bar_consumption",
"=",
"0.2",
",",
"capital_base",
"=",
"1e6",
",",
"mean_volume_window",
"=",
"5",
")",
":",
"DV",
"=",
"market_data",
"[",
"'volume'",
"]",
"*",
"market_data"... | 41.396226 | 0.000445 |
def _authenticate_user(self, user, password):
"""
Returns the response of authenticating with the given
user and password.
"""
headers = self._get_headers()
params = {
'username': user,
'password': password,
'grant_type': 'p... | [
"def",
"_authenticate_user",
"(",
"self",
",",
"user",
",",
"password",
")",
":",
"headers",
"=",
"self",
".",
"_get_headers",
"(",
")",
"params",
"=",
"{",
"'username'",
":",
"user",
",",
"'password'",
":",
"password",
",",
"'grant_type'",
":",
"'password... | 34.5 | 0.00235 |
def manipulate(self, stored_instance, component_instance):
"""
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Store the stored instance
self._ipopo_instance = s... | [
"def",
"manipulate",
"(",
"self",
",",
"stored_instance",
",",
"component_instance",
")",
":",
"# Store the stored instance",
"self",
".",
"_ipopo_instance",
"=",
"stored_instance",
"# Public flags to generate (True for public accessors)",
"flags_to_generate",
"=",
"set",
"("... | 38.892857 | 0.001792 |
def _broadcast_arithmetic(op):
"""Return ``op(self, other)`` with broadcasting.
Parameters
----------
op : string
Name of the operator, e.g. ``'__add__'``.
Returns
-------
broadcast_arithmetic_op : function
Function intended to be used as a method for `ProductSpaceVector`
... | [
"def",
"_broadcast_arithmetic",
"(",
"op",
")",
":",
"def",
"_broadcast_arithmetic_impl",
"(",
"self",
",",
"other",
")",
":",
"if",
"(",
"self",
".",
"space",
".",
"is_power_space",
"and",
"other",
"in",
"self",
".",
"space",
"[",
"0",
"]",
")",
":",
... | 29.644444 | 0.000726 |
def find_matching(cls, path, patterns):
"""Yield all matching patterns for path."""
for pattern in patterns:
if pattern.match(path):
yield pattern | [
"def",
"find_matching",
"(",
"cls",
",",
"path",
",",
"patterns",
")",
":",
"for",
"pattern",
"in",
"patterns",
":",
"if",
"pattern",
".",
"match",
"(",
"path",
")",
":",
"yield",
"pattern"
] | 37.2 | 0.010526 |
def _driz_cr(sciImage, virtual_outputs, paramDict):
"""mask blemishes in dithered data by comparison of an image
with a model image and the derivative of the model image.
- ``sciImage`` is an imageObject which contains the science data
- ``blotImage`` is inferred from the ``sciImage`` object here which... | [
"def",
"_driz_cr",
"(",
"sciImage",
",",
"virtual_outputs",
",",
"paramDict",
")",
":",
"grow",
"=",
"paramDict",
"[",
"\"driz_cr_grow\"",
"]",
"ctegrow",
"=",
"paramDict",
"[",
"\"driz_cr_ctegrow\"",
"]",
"crcorr_list",
"=",
"[",
"]",
"cr_mask_dict",
"=",
"{"... | 41.796954 | 0.000356 |
def guess_header(array, name=''):
"""Guess the array header information.
Returns a header dict, with class, data type, and size information.
"""
header = {}
if isinstance(array, Sequence) and len(array) == 1:
# sequence with only one element, squeeze the array
array = array[0]
... | [
"def",
"guess_header",
"(",
"array",
",",
"name",
"=",
"''",
")",
":",
"header",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"array",
",",
"Sequence",
")",
"and",
"len",
"(",
"array",
")",
"==",
"1",
":",
"# sequence with only one element, squeeze the array",
... | 36.336283 | 0.000237 |
def optimize(self, constraints: ConstraintSet, x: BitVec, goal: str, M=10000):
"""
Iteratively finds the maximum or minimum value for the operation
(Normally Operators.UGT or Operators.ULT)
:param constraints: constraints to take into account
:param x: a symbol or expression
... | [
"def",
"optimize",
"(",
"self",
",",
"constraints",
":",
"ConstraintSet",
",",
"x",
":",
"BitVec",
",",
"goal",
":",
"str",
",",
"M",
"=",
"10000",
")",
":",
"assert",
"goal",
"in",
"(",
"'maximize'",
",",
"'minimize'",
")",
"assert",
"isinstance",
"("... | 46.03125 | 0.002326 |
def add_action(self, action, sub_menu='Advanced'):
"""
Adds an action to the editor's context menu.
:param action: QAction to add to the context menu.
:param sub_menu: The name of a sub menu where to put the action.
'Advanced' by default. If None or empty, the action will be... | [
"def",
"add_action",
"(",
"self",
",",
"action",
",",
"sub_menu",
"=",
"'Advanced'",
")",
":",
"if",
"sub_menu",
":",
"try",
":",
"mnu",
"=",
"self",
".",
"_sub_menus",
"[",
"sub_menu",
"]",
"except",
"KeyError",
":",
"mnu",
"=",
"QtWidgets",
".",
"QMe... | 36.727273 | 0.002413 |
def sed_conversion(energy, model_unit, sed):
"""
Manage conversion between differential spectrum and SED
"""
model_pt = model_unit.physical_type
ones = np.ones(energy.shape)
if sed:
# SED
f_unit = u.Unit("erg/s")
if model_pt == "power" or model_pt == "flux" or model_pt... | [
"def",
"sed_conversion",
"(",
"energy",
",",
"model_unit",
",",
"sed",
")",
":",
"model_pt",
"=",
"model_unit",
".",
"physical_type",
"ones",
"=",
"np",
".",
"ones",
"(",
"energy",
".",
"shape",
")",
"if",
"sed",
":",
"# SED",
"f_unit",
"=",
"u",
".",
... | 30.946429 | 0.000559 |
def get_parameter_limits(xval, loglike, cl_limit=0.95, cl_err=0.68269, tol=1E-2,
bounds=None):
"""Compute upper/lower limits, peak position, and 1-sigma errors
from a 1-D likelihood function. This function uses the
delta-loglikelihood method to evaluate parameter limits by
sear... | [
"def",
"get_parameter_limits",
"(",
"xval",
",",
"loglike",
",",
"cl_limit",
"=",
"0.95",
",",
"cl_err",
"=",
"0.68269",
",",
"tol",
"=",
"1E-2",
",",
"bounds",
"=",
"None",
")",
":",
"dlnl_limit",
"=",
"onesided_cl_to_dlnl",
"(",
"cl_limit",
")",
"dlnl_er... | 33.323944 | 0.001436 |
def read_url(url):
"""Reads given URL as JSON and returns data as loaded python object."""
logging.debug('reading {url} ...'.format(url=url))
token = os.environ.get("BOKEH_GITHUB_API_TOKEN")
headers = {}
if token:
headers['Authorization'] = 'token %s' % token
request = Request(url, heade... | [
"def",
"read_url",
"(",
"url",
")",
":",
"logging",
".",
"debug",
"(",
"'reading {url} ...'",
".",
"format",
"(",
"url",
"=",
"url",
")",
")",
"token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"BOKEH_GITHUB_API_TOKEN\"",
")",
"headers",
"=",
"{",
... | 40.9 | 0.002392 |
def create(vm_):
'''
To create a single VM in the VMware environment.
Sample profile and arguments that can be specified in it can be found
:ref:`here. <vmware-cloud-profile>`
CLI Example:
.. code-block:: bash
salt-cloud -p vmware-centos6.5 vmname
'''
try:
# Check for... | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"(",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
... | 42.037367 | 0.002274 |
def template(*args, **kwargs):
"""
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
"""
tpl = args[0] if args else None
for ... | [
"def",
"template",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tpl",
"=",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"None",
"for",
"dictarg",
"in",
"args",
"[",
"1",
":",
"]",
":",
"kwargs",
".",
"update",
"(",
"dictarg",
")",
"ada... | 43.4 | 0.001803 |
def filesizeformat(bytes, sep=' '):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 B, 2.3 GB etc).
Grabbed from Django (http://www.djangoproject.com), slightly modified.
:param bytes: size in bytes (as integer)
:param sep: string separator between number and a... | [
"def",
"filesizeformat",
"(",
"bytes",
",",
"sep",
"=",
"' '",
")",
":",
"try",
":",
"bytes",
"=",
"float",
"(",
"bytes",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"UnicodeDecodeError",
")",
":",
"return",
"'0%sB'",
"%",
"sep",
"if",
"by... | 29 | 0.001192 |
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None):
"""
Given a math expression, renders it in a closely-clipped bounding
box to an image file.
*s*
A math expression. The math portion should be enclosed in
dollar signs.
*filename_or_obj*
A filepath or wri... | [
"def",
"math_to_image",
"(",
"s",
",",
"filename_or_obj",
",",
"prop",
"=",
"None",
",",
"dpi",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"from",
"matplotlib",
"import",
"figure",
"# backend_agg supports all of the core output formats",
"from",
"matplotli... | 30.930233 | 0.000729 |
def terminate_all(self):
""" Terminate all currently running tasks. """
logger.info('Job {0} terminating all currently running tasks'.format(self.name))
for task in self.tasks.itervalues():
if task.started_at and not task.completed_at:
task.terminate() | [
"def",
"terminate_all",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Job {0} terminating all currently running tasks'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"for",
"task",
"in",
"self",
".",
"tasks",
".",
"itervalues",
"(",
")",
":",
... | 49.833333 | 0.009868 |
def show(self, idx):
"""
Print the instruction
"""
print(self.get_name() + " " + self.get_output(idx), end=' ') | [
"def",
"show",
"(",
"self",
",",
"idx",
")",
":",
"print",
"(",
"self",
".",
"get_name",
"(",
")",
"+",
"\" \"",
"+",
"self",
".",
"get_output",
"(",
"idx",
")",
",",
"end",
"=",
"' '",
")"
] | 27.8 | 0.013986 |
def _write_lat_lon(data_out_nc, rivid_lat_lon_z_file):
"""Add latitude and longitude each netCDF feature
Lookup table is a CSV file with rivid, Lat, Lon, columns.
Columns must be in that order and these must be the first
three columns.
"""
# only add if user adds
... | [
"def",
"_write_lat_lon",
"(",
"data_out_nc",
",",
"rivid_lat_lon_z_file",
")",
":",
"# only add if user adds\r",
"if",
"rivid_lat_lon_z_file",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"rivid_lat_lon_z_file",
")",
":",
"# get list of COMIDS\r",
"lookup_table",
"=",
... | 39.367647 | 0.000729 |
def parse(self, file_handle):
"""
parse is the main entry point for an XBRLParser. It takes a file
handle.
"""
xbrl_obj = XBRL()
# if no file handle was given create our own
if not hasattr(file_handle, 'read'):
file_handler = open(file_handle)
... | [
"def",
"parse",
"(",
"self",
",",
"file_handle",
")",
":",
"xbrl_obj",
"=",
"XBRL",
"(",
")",
"# if no file handle was given create our own",
"if",
"not",
"hasattr",
"(",
"file_handle",
",",
"'read'",
")",
":",
"file_handler",
"=",
"open",
"(",
"file_handle",
... | 30.727273 | 0.001912 |
def centroid(self):
"""Returns the envelope centroid as a (x, y) tuple."""
return self.min_x + self.width * 0.5, self.min_y + self.height * 0.5 | [
"def",
"centroid",
"(",
"self",
")",
":",
"return",
"self",
".",
"min_x",
"+",
"self",
".",
"width",
"*",
"0.5",
",",
"self",
".",
"min_y",
"+",
"self",
".",
"height",
"*",
"0.5"
] | 52.333333 | 0.012579 |
def _lock(self):
"""Lock the config DB."""
if not self.locked:
self.device.cu.lock()
self.locked = True | [
"def",
"_lock",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"locked",
":",
"self",
".",
"device",
".",
"cu",
".",
"lock",
"(",
")",
"self",
".",
"locked",
"=",
"True"
] | 27.8 | 0.013986 |
def SETNZ(cpu, dest):
"""
Sets byte if not zero.
:param cpu: current CPU.
:param dest: destination operand.
"""
dest.write(Operators.ITEBV(dest.size, cpu.ZF == False, 1, 0)) | [
"def",
"SETNZ",
"(",
"cpu",
",",
"dest",
")",
":",
"dest",
".",
"write",
"(",
"Operators",
".",
"ITEBV",
"(",
"dest",
".",
"size",
",",
"cpu",
".",
"ZF",
"==",
"False",
",",
"1",
",",
"0",
")",
")"
] | 26.875 | 0.013514 |
def precision(self):
"""Calculates precision
:return: Precision of matrix
"""
true_pos = self.matrix[0][0]
false_pos = self.matrix[1][0]
return divide(1.0 * true_pos, true_pos + false_pos) | [
"def",
"precision",
"(",
"self",
")",
":",
"true_pos",
"=",
"self",
".",
"matrix",
"[",
"0",
"]",
"[",
"0",
"]",
"false_pos",
"=",
"self",
".",
"matrix",
"[",
"1",
"]",
"[",
"0",
"]",
"return",
"divide",
"(",
"1.0",
"*",
"true_pos",
",",
"true_po... | 28.75 | 0.008439 |
def dependency_ran(self, test):
"""Returns an error string if any of the dependencies did not run"""
for d in (self.test_name(i) for i in dependencies[test]):
if d not in self.ok_results:
return "Required test '{}' did not run (does it exist?)".format(d)
return None | [
"def",
"dependency_ran",
"(",
"self",
",",
"test",
")",
":",
"for",
"d",
"in",
"(",
"self",
".",
"test_name",
"(",
"i",
")",
"for",
"i",
"in",
"dependencies",
"[",
"test",
"]",
")",
":",
"if",
"d",
"not",
"in",
"self",
".",
"ok_results",
":",
"re... | 52.166667 | 0.009434 |
def validate_address(self, address_deets):
"""Validates a customer address and returns back a collection of address matches."""
request = self._post('addresses/validate', address_deets)
return self.responder(request) | [
"def",
"validate_address",
"(",
"self",
",",
"address_deets",
")",
":",
"request",
"=",
"self",
".",
"_post",
"(",
"'addresses/validate'",
",",
"address_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | 59.25 | 0.0125 |
def repel_text_from_points(x, y, texts, renderer=None, ax=None,
expand=(1.2, 1.2), move=False):
"""
Repel texts from all points specified by x and y while expanding their
(texts'!) bounding boxes by expandby (x, y), e.g. (1.2, 1.2)
would multiply both width and height by 1.2.... | [
"def",
"repel_text_from_points",
"(",
"x",
",",
"y",
",",
"texts",
",",
"renderer",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"expand",
"=",
"(",
"1.2",
",",
"1.2",
")",
",",
"move",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
... | 37.378378 | 0.001409 |
def rolling_window(self, dim, window, window_dim, center=False,
fill_value=dtypes.NA):
"""
Make a rolling_window along dim and add a new_dim to the last place.
Parameters
----------
dim: str
Dimension over which to compute rolling_window
... | [
"def",
"rolling_window",
"(",
"self",
",",
"dim",
",",
"window",
",",
"window_dim",
",",
"center",
"=",
"False",
",",
"fill_value",
"=",
"dtypes",
".",
"NA",
")",
":",
"if",
"fill_value",
"is",
"dtypes",
".",
"NA",
":",
"# np.nan is passed",
"dtype",
","... | 38.06 | 0.001537 |
def mangle_package_path(self, files):
"""Mangle paths for post-UsrMove systems.
If the system implements UsrMove, all files will be in
'/usr/[s]bin'. This method substitutes all the /[s]bin
references in the 'files' list with '/usr/[s]bin'.
:param files: the lis... | [
"def",
"mangle_package_path",
"(",
"self",
",",
"files",
")",
":",
"paths",
"=",
"[",
"]",
"def",
"transform_path",
"(",
"path",
")",
":",
"# Some packages actually own paths in /bin: in this case,",
"# duplicate the path as both the / and /usr version.",
"skip_paths",
"=",... | 36.08 | 0.00216 |
def all_joined_units(self):
"""
A list view of all the units of all relations attached to this
:class:`~charms.reactive.endpoints.Endpoint`.
This is actually a
:class:`~charms.reactive.endpoints.CombinedUnitsView`, so the units
will be in order by relation ID and then un... | [
"def",
"all_joined_units",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_joined_units",
"is",
"None",
":",
"units",
"=",
"chain",
".",
"from_iterable",
"(",
"rel",
".",
"units",
"for",
"rel",
"in",
"self",
".",
"relations",
")",
"self",
".",
"_all_join... | 51.458333 | 0.002385 |
def compact_interval_string(value_list):
"""Compact a list of integers into a comma-separated string of intervals.
Args:
value_list: A list of sortable integers such as a list of numbers
Returns:
A compact string representation, such as "1-5,8,12-15"
"""
if not value_list:
return ''
value_li... | [
"def",
"compact_interval_string",
"(",
"value_list",
")",
":",
"if",
"not",
"value_list",
":",
"return",
"''",
"value_list",
".",
"sort",
"(",
")",
"# Start by simply building up a list of separate contiguous intervals",
"interval_list",
"=",
"[",
"]",
"curr",
"=",
"[... | 25.205882 | 0.016854 |
def _gen_file_name(self):
'''
Generates a random file name based on self._output_filename_pattern for the output to do file.
'''
date = datetime.datetime.now()
dt = "{}-{}-{}-{}-{}-{}-{}".format(str(date.year),str(date.month),str(date.day),str(date.hour),str(date.minute),str(date... | [
"def",
"_gen_file_name",
"(",
"self",
")",
":",
"date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"dt",
"=",
"\"{}-{}-{}-{}-{}-{}-{}\"",
".",
"format",
"(",
"str",
"(",
"date",
".",
"year",
")",
",",
"str",
"(",
"date",
".",
"month",
")... | 58.285714 | 0.02657 |
def get_all(self, paths: Union[str, Sequence[str]]) -> Union[Set[AccessControl], Sequence[Set[AccessControl]]]:
"""
Gets all the access controls for the entity with the given path.
:param path: the path of the entity to find access controls for
:return:
""" | [
"def",
"get_all",
"(",
"self",
",",
"paths",
":",
"Union",
"[",
"str",
",",
"Sequence",
"[",
"str",
"]",
"]",
")",
"->",
"Union",
"[",
"Set",
"[",
"AccessControl",
"]",
",",
"Sequence",
"[",
"Set",
"[",
"AccessControl",
"]",
"]",
"]",
":"
] | 48.666667 | 0.013468 |
def acquisition_function_withGradients(self, x):
"""
Returns the acquisition function and its its gradient at x.
"""
aqu_x = self.acquisition_function(x)
aqu_x_grad = self.d_acquisition_function(x)
return aqu_x, aqu_x_grad | [
"def",
"acquisition_function_withGradients",
"(",
"self",
",",
"x",
")",
":",
"aqu_x",
"=",
"self",
".",
"acquisition_function",
"(",
"x",
")",
"aqu_x_grad",
"=",
"self",
".",
"d_acquisition_function",
"(",
"x",
")",
"return",
"aqu_x",
",",
"aqu_x_grad"
] | 38.428571 | 0.010909 |
def provider(self, name, history=None):
"""
Find the provider of the property by I{name}.
@param name: The property name.
@type name: str
@param history: A history of nodes checked to prevent
circular hunting.
@type history: [L{Properties},..]
@return:... | [
"def",
"provider",
"(",
"self",
",",
"name",
",",
"history",
"=",
"None",
")",
":",
"if",
"history",
"is",
"None",
":",
"history",
"=",
"[",
"]",
"history",
".",
"append",
"(",
"self",
")",
"if",
"name",
"in",
"self",
".",
"definitions",
":",
"retu... | 32.407407 | 0.00222 |
def to_timestamp(self, freq=None, how='start'):
"""
Cast to DatetimeArray/Index.
Parameters
----------
freq : string or DateOffset, optional
Target frequency. The default is 'D' for week or longer,
'S' otherwise
how : {'s', 'e', 'start', 'end'}
... | [
"def",
"to_timestamp",
"(",
"self",
",",
"freq",
"=",
"None",
",",
"how",
"=",
"'start'",
")",
":",
"from",
"pandas",
".",
"core",
".",
"arrays",
"import",
"DatetimeArray",
"how",
"=",
"libperiod",
".",
"_validate_end_alias",
"(",
"how",
")",
"end",
"=",... | 32.775 | 0.001481 |
def run(self, h, recalculate=False):
""" Run the aggregating algorithm
Parameters
----------
h : int
How many steps to run the aggregating algorithm on
recalculate: boolean
Whether to recalculate the predictions or not
Returns
... | [
"def",
"run",
"(",
"self",
",",
"h",
",",
"recalculate",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"data",
"[",
"-",
"h",
":",
"]",
"predictions",
"=",
"self",
".",
"_model_predict_is",
"(",
"h",
",",
"recalculate",
"=",
"recalculate",
")",
... | 43.441176 | 0.02053 |
def fromHTML(html, *args, **kwargs):
"""
Creates abstraction using HTML
:param str html: HTML
:return: TreeOfContents object
"""
source = BeautifulSoup(html, 'html.parser', *args, **kwargs)
return TOC('[document]',
source=source,
descendan... | [
"def",
"fromHTML",
"(",
"html",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"source",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'html.parser'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"TOC",
"(",
"'[document]'",
",",
"source... | 29.909091 | 0.011799 |
def bool(self, var, default=NOTSET):
"""
:rtype: bool
"""
return self.get_value(var, cast=bool, default=default) | [
"def",
"bool",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
")",
":",
"return",
"self",
".",
"get_value",
"(",
"var",
",",
"cast",
"=",
"bool",
",",
"default",
"=",
"default",
")"
] | 28 | 0.013889 |
def complete_english(string):
"""
>>> complete_english('dont do this')
"don't do this"
>>> complete_english('doesnt is matched as well')
"doesn't is matched as well"
"""
for x, y in [("dont", "don't"),
("doesnt", "doesn't"),
("wont", "won't"),
... | [
"def",
"complete_english",
"(",
"string",
")",
":",
"for",
"x",
",",
"y",
"in",
"[",
"(",
"\"dont\"",
",",
"\"don't\"",
")",
",",
"(",
"\"doesnt\"",
",",
"\"doesn't\"",
")",
",",
"(",
"\"wont\"",
",",
"\"won't\"",
")",
",",
"(",
"\"wasnt\"",
",",
"\"... | 29.615385 | 0.010076 |
def get_user(self, username):
""" Get the user details from MAM. """
cmd = ["glsuser", "-u", username, "--raw"]
results = self._read_output(cmd)
if len(results) == 0:
return None
elif len(results) > 1:
logger.error(
"Command returned multi... | [
"def",
"get_user",
"(",
"self",
",",
"username",
")",
":",
"cmd",
"=",
"[",
"\"glsuser\"",
",",
"\"-u\"",
",",
"username",
",",
"\"--raw\"",
"]",
"results",
"=",
"self",
".",
"_read_output",
"(",
"cmd",
")",
"if",
"len",
"(",
"results",
")",
"==",
"0... | 35.666667 | 0.002275 |
def delete_edge(self, vertex1, vertex2, multicolor, key=None):
""" Creates a new :class:`bg.edge.BGEdge` instance from supplied information and deletes it from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicol... | [
"def",
"delete_edge",
"(",
"self",
",",
"vertex1",
",",
"vertex2",
",",
"multicolor",
",",
"key",
"=",
"None",
")",
":",
"self",
".",
"__delete_bgedge",
"(",
"bgedge",
"=",
"BGEdge",
"(",
"vertex1",
"=",
"vertex1",
",",
"vertex2",
"=",
"vertex2",
",",
... | 82.9375 | 0.008197 |
def main():
"""
Main function.
"""
msg = ''
try:
songs = parse_argv()
if not songs:
msg = 'No songs specified'
except ValueError as error:
msg = str(error)
if msg:
logger.error('%s: Error: %s', sys.argv[0], msg)
return 1
logger.debug('... | [
"def",
"main",
"(",
")",
":",
"msg",
"=",
"''",
"try",
":",
"songs",
"=",
"parse_argv",
"(",
")",
"if",
"not",
"songs",
":",
"msg",
"=",
"'No songs specified'",
"except",
"ValueError",
"as",
"error",
":",
"msg",
"=",
"str",
"(",
"error",
")",
"if",
... | 19.130435 | 0.002165 |
def set_address(self, address):
"""
Set the address.
:param address:
"""
self._query_params += str(QueryParam.ADVANCED) + str(QueryParam.ADDRESS) + address.replace(" ", "+").lower() | [
"def",
"set_address",
"(",
"self",
",",
"address",
")",
":",
"self",
".",
"_query_params",
"+=",
"str",
"(",
"QueryParam",
".",
"ADVANCED",
")",
"+",
"str",
"(",
"QueryParam",
".",
"ADDRESS",
")",
"+",
"address",
".",
"replace",
"(",
"\" \"",
",",
"\"+... | 36 | 0.013575 |
def get_website_endpoint(self):
"""
Returns the fully qualified hostname to use is you want to access this
bucket as a website. This doesn't validate whether the bucket has
been correctly configured as a website or not.
"""
l = [self.name]
l.append(S3WebsiteEndpo... | [
"def",
"get_website_endpoint",
"(",
"self",
")",
":",
"l",
"=",
"[",
"self",
".",
"name",
"]",
"l",
".",
"append",
"(",
"S3WebsiteEndpointTranslate",
".",
"translate_region",
"(",
"self",
".",
"get_location",
"(",
")",
")",
")",
"l",
".",
"append",
"(",
... | 45.4 | 0.008639 |
def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
'Build a timeseries from the internal state'
cache_key = _get_cache_key(state_uid)
state = cache.get(cache_key)
# If nothing in cache, prepopulate
if not state:
state = {}
colour_series = {}
colors = {'red'... | [
"def",
"callback_show_timeseries",
"(",
"internal_state_string",
",",
"state_uid",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_key",
"=",
"_get_cache_key",
"(",
"state_uid",
")",
"state",
"=",
"cache",
".",
"get",
"(",
"cache_key",
")",
"# If nothing in cache, prepo... | 33.25641 | 0.009738 |
def add_content(self, text=None, *markdown_files):
"""add the content of the file(s) (or the text in string) in HTML body"""
for markdown_file in markdown_files:
self.markdown_text += self._text_file(markdown_file)
if text:
self.markdown_text += text | [
"def",
"add_content",
"(",
"self",
",",
"text",
"=",
"None",
",",
"*",
"markdown_files",
")",
":",
"for",
"markdown_file",
"in",
"markdown_files",
":",
"self",
".",
"markdown_text",
"+=",
"self",
".",
"_text_file",
"(",
"markdown_file",
")",
"if",
"text",
... | 41.857143 | 0.010033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.