text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def result_files(self):
""" returns a list of files that have finished structure """
reps = OPJ(self.workdir, self.name+"-K-*-rep-*_f")
repfiles = glob.glob(reps)
return repfiles | [
"def",
"result_files",
"(",
"self",
")",
":",
"reps",
"=",
"OPJ",
"(",
"self",
".",
"workdir",
",",
"self",
".",
"name",
"+",
"\"-K-*-rep-*_f\"",
")",
"repfiles",
"=",
"glob",
".",
"glob",
"(",
"reps",
")",
"return",
"repfiles"
] | 41.2 | 0.009524 |
def updateCameraTree(self):
self.treelist.reset_()
self.server = ServerListItem(
name = "Localhost", ip = "127.0.0.1", parent = self.root)
"""
self.server1 = ServerListItem(
name="First Server", ip="192.168.1.20", parent=self.root)
"""
"""
... | [
"def",
"updateCameraTree",
"(",
"self",
")",
":",
"self",
".",
"treelist",
".",
"reset_",
"(",
")",
"self",
".",
"server",
"=",
"ServerListItem",
"(",
"name",
"=",
"\"Localhost\"",
",",
"ip",
"=",
"\"127.0.0.1\"",
",",
"parent",
"=",
"self",
".",
"root",... | 38.684211 | 0.012608 |
def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=None):
"""Return x,y values evaluated with a given pixel step.
The returned values are computed within the corresponding
bounding box of the line.
Parameters
----------
start : float
Minimum ... | [
"def",
"linspace_pix",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"pixel_step",
"=",
"1",
",",
"y_vs_x",
"=",
"None",
")",
":",
"if",
"y_vs_x",
":",
"if",
"start",
"is",
"None",
":",
"xmin",
"=",
"self",
".",
"bb_nc1_ori... | 30.703704 | 0.001169 |
def deserialize(self, payload, obj_type):
# type: (str, Union[T, str]) -> Any
"""Deserializes payload into an instance of provided ``obj_type``.
The ``obj_type`` parameter can be a primitive type, a generic
model object or a list / dict of model objects.
The list or dict object... | [
"def",
"deserialize",
"(",
"self",
",",
"payload",
",",
"obj_type",
")",
":",
"# type: (str, Union[T, str]) -> Any",
"if",
"payload",
"is",
"None",
":",
"return",
"None",
"try",
":",
"payload",
"=",
"json",
".",
"loads",
"(",
"payload",
")",
"except",
"Excep... | 41 | 0.001662 |
def update_cache_by_increment(self, blocksize):
"""Update the internal cache by starting from the first frame
and incrementing.
Guess the next frame file name by incrementing from the first found
one. This allows a pattern to be used for the GPS folder of the file,
which is indi... | [
"def",
"update_cache_by_increment",
"(",
"self",
",",
"blocksize",
")",
":",
"start",
"=",
"float",
"(",
"self",
".",
"raw_buffer",
".",
"end_time",
")",
"end",
"=",
"float",
"(",
"start",
"+",
"blocksize",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
... | 39.717391 | 0.001603 |
def Append(self, **kw):
"""Append values to existing construction variables
in an Environment.
"""
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
# It would be easier on the eyes to write this using
# "continue" statements whenever we fini... | [
"def",
"Append",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"=",
"copy_non_reserved_keywords",
"(",
"kw",
")",
"for",
"key",
",",
"val",
"in",
"kw",
".",
"items",
"(",
")",
":",
"# It would be easier on the eyes to write this using",
"# \"continue\" sta... | 48.9125 | 0.000752 |
def numpartition_qaoa(n_step, nums, minimizer=None, sampler=None):
"""Do the Number partition QAOA.
:param n_step: The number of step of QAOA
:param nums: The edges list of the graph.
:returns Vqe object
"""
hamiltonian = pauli.Expr.zero()
for i, x in enumerate(nums):
hamiltonian +=... | [
"def",
"numpartition_qaoa",
"(",
"n_step",
",",
"nums",
",",
"minimizer",
"=",
"None",
",",
"sampler",
"=",
"None",
")",
":",
"hamiltonian",
"=",
"pauli",
".",
"Expr",
".",
"zero",
"(",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"nums",
")",
... | 34.461538 | 0.002174 |
def flightmode_menu():
'''construct flightmode menu'''
global flightmodes
ret = []
idx = 0
for (mode,t1,t2) in flightmodes:
modestr = "%s %us" % (mode, (t2-t1))
ret.append(MPMenuCheckbox(modestr, modestr, 'mode-%u' % idx))
idx += 1
mestate.flightmode_selections.append... | [
"def",
"flightmode_menu",
"(",
")",
":",
"global",
"flightmodes",
"ret",
"=",
"[",
"]",
"idx",
"=",
"0",
"for",
"(",
"mode",
",",
"t1",
",",
"t2",
")",
"in",
"flightmodes",
":",
"modestr",
"=",
"\"%s %us\"",
"%",
"(",
"mode",
",",
"(",
"t2",
"-",
... | 30.181818 | 0.008772 |
def is_copy_constructor(constructor):
"""
Check if the declaration is a copy constructor,
Args:
constructor (declarations.constructor_t): the constructor
to be checked.
Returns:
bool: True if this is a copy constructor, False instead.
"""
assert isinstance(construc... | [
"def",
"is_copy_constructor",
"(",
"constructor",
")",
":",
"assert",
"isinstance",
"(",
"constructor",
",",
"calldef_members",
".",
"constructor_t",
")",
"args",
"=",
"constructor",
".",
"arguments",
"parent",
"=",
"constructor",
".",
"parent",
"# A copy constructo... | 37.092593 | 0.000486 |
def wrap_httplib_response(response_func):
"""Wrap the httplib response function to trace.
If there is a corresponding httplib request span, update and close it.
If not, return the response.
"""
def call(self, *args, **kwargs):
_tracer = execution_context.get_opencensus_tracer()
cur... | [
"def",
"wrap_httplib_response",
"(",
"response_func",
")",
":",
"def",
"call",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_tracer",
"=",
"execution_context",
".",
"get_opencensus_tracer",
"(",
")",
"current_span_id",
"=",
"execution_con... | 31.107143 | 0.001114 |
def create_new_username(ip, devicetype=None, timeout=_DEFAULT_TIMEOUT):
"""Interactive helper function to generate a new anonymous username.
Args:
ip: ip address of the bridge
devicetype (optional): devicetype to register with the bridge. If
unprovided, generates a device type based... | [
"def",
"create_new_username",
"(",
"ip",
",",
"devicetype",
"=",
"None",
",",
"timeout",
"=",
"_DEFAULT_TIMEOUT",
")",
":",
"res",
"=",
"Resource",
"(",
"_api_url",
"(",
"ip",
")",
",",
"timeout",
")",
"prompt",
"=",
"\"Press the Bridge button, then press Return... | 38.185185 | 0.000946 |
def unix_serve(
ws_handler: Callable[[WebSocketServerProtocol, str], Awaitable[Any]],
path: str,
**kwargs: Any,
) -> Serve:
"""
Similar to :func:`serve()`, but for listening on Unix sockets.
This function calls the event loop's
:meth:`~asyncio.AbstractEventLoop.create_unix_server` method.
... | [
"def",
"unix_serve",
"(",
"ws_handler",
":",
"Callable",
"[",
"[",
"WebSocketServerProtocol",
",",
"str",
"]",
",",
"Awaitable",
"[",
"Any",
"]",
"]",
",",
"path",
":",
"str",
",",
"*",
"*",
"kwargs",
":",
"Any",
",",
")",
"->",
"Serve",
":",
"return... | 27.882353 | 0.002041 |
def _export_profiles(self, profile_name, user_pageviews, user_downloads,
ip_user=False):
"""Filter and export the user profiles."""
views_min = self.config.get('user_views_min')
views_max = self.config.get('user_views_max')
ip_user_id = 500000000000
add_u... | [
"def",
"_export_profiles",
"(",
"self",
",",
"profile_name",
",",
"user_pageviews",
",",
"user_downloads",
",",
"ip_user",
"=",
"False",
")",
":",
"views_min",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'user_views_min'",
")",
"views_max",
"=",
"self",
".... | 49.657143 | 0.001693 |
def simplex_projection(v, b=1):
r"""Projection vectors to the simplex domain
Implemented according to the paper: Efficient projections onto the
l1-ball for learning in high dimensions, John Duchi, et al. ICML 2008.
Implementation Time: 2011 June 17 by Bin@libin AT pmail.ntu.edu.sg
Optimization Prob... | [
"def",
"simplex_projection",
"(",
"v",
",",
"b",
"=",
"1",
")",
":",
"v",
"=",
"np",
".",
"asarray",
"(",
"v",
")",
"p",
"=",
"len",
"(",
"v",
")",
"# Sort v into u in descending order",
"v",
"=",
"(",
"v",
">",
"0",
")",
"*",
"v",
"u",
"=",
"n... | 31.138889 | 0.000865 |
def _build_tree(self):
"""
Build a full or a partial tree, depending on the groups/sub-groups specified.
"""
groups = self._groups or self.get_children_paths(self.root_path)
for group in groups:
node = Node(name=group, parent=self.root)
self.root.children... | [
"def",
"_build_tree",
"(",
"self",
")",
":",
"groups",
"=",
"self",
".",
"_groups",
"or",
"self",
".",
"get_children_paths",
"(",
"self",
".",
"root_path",
")",
"for",
"group",
"in",
"groups",
":",
"node",
"=",
"Node",
"(",
"name",
"=",
"group",
",",
... | 36.4 | 0.008043 |
def match_string(self, tokens, item):
"""Match prefix string."""
prefix, name = tokens
return self.match_mstring((prefix, name, None), item, use_bytes=prefix.startswith("b")) | [
"def",
"match_string",
"(",
"self",
",",
"tokens",
",",
"item",
")",
":",
"prefix",
",",
"name",
"=",
"tokens",
"return",
"self",
".",
"match_mstring",
"(",
"(",
"prefix",
",",
"name",
",",
"None",
")",
",",
"item",
",",
"use_bytes",
"=",
"prefix",
"... | 48.75 | 0.015152 |
def request_port_forward(self, address, port, handler=None):
"""
Ask the server to forward TCP connections from a listening port on
the server, across this SSH session.
If a handler is given, that handler is called from a different thread
whenever a forwarded connection arrives.... | [
"def",
"request_port_forward",
"(",
"self",
",",
"address",
",",
"port",
",",
"handler",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"raise",
"SSHException",
"(",
"\"SSH session not active\"",
")",
"port",
"=",
"int",
"(",
"port",
")",
... | 37 | 0.000994 |
def palette(self, alpha='natural'):
"""Returns a palette that is a sequence of 3-tuples or 4-tuples,
synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These
chunks should have already been processed (for example, by
calling the :meth:`preamble` method). All the tuples are the
... | [
"def",
"palette",
"(",
"self",
",",
"alpha",
"=",
"'natural'",
")",
":",
"if",
"not",
"self",
".",
"plte",
":",
"raise",
"FormatError",
"(",
"\"Required PLTE chunk is missing in colour type 3 image.\"",
")",
"plte",
"=",
"group",
"(",
"array",
"(",
"'B'",
",",... | 47.772727 | 0.001866 |
def label_const(self, const:Any=0, label_cls:Callable=None, **kwargs)->'LabelList':
"Label every item with `const`."
return self.label_from_func(func=lambda o: const, label_cls=label_cls, **kwargs) | [
"def",
"label_const",
"(",
"self",
",",
"const",
":",
"Any",
"=",
"0",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"return",
"self",
".",
"label_from_func",
"(",
"func",
"=",
"lambda",
"o",
... | 70.333333 | 0.051643 |
def to_texttree(self, indent=3, func=True, symbol='ascii'):
"""Method returning a text representation of the (sub-)tree
rooted at the current node instance (`self`).
:param indent: the indentation width for each tree level.
:type indent: int
:param func: function returning a s... | [
"def",
"to_texttree",
"(",
"self",
",",
"indent",
"=",
"3",
",",
"func",
"=",
"True",
",",
"symbol",
"=",
"'ascii'",
")",
":",
"if",
"indent",
"<",
"2",
":",
"indent",
"=",
"2",
"if",
"func",
"is",
"True",
":",
"# default func prints node.name",
"func"... | 47.890411 | 0.015695 |
def sipprverse_method(self):
"""
Reduced subset again. Only sipprverse, MASH, and confindr targets are required
"""
logging.info('Beginning sipprverse method database downloads')
if self.overwrite or not os.path.isdir(os.path.join(self.databasepath, 'genesippr')):
sel... | [
"def",
"sipprverse_method",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Beginning sipprverse method database downloads'",
")",
"if",
"self",
".",
"overwrite",
"or",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
... | 57.636364 | 0.009317 |
def wchoice(d):
"""
Given a dictionary of word: proportion, return a word randomly selected
from the keys weighted by proportion.
>>> wchoice({'a': 0, 'b': 1})
'b'
>>> choices = [wchoice({'a': 1, 'b': 2}) for x in range(1000)]
Statistically speaking, choices should be .5 a:b
>>> ratio = choices.count('a') / c... | [
"def",
"wchoice",
"(",
"d",
")",
":",
"total",
"=",
"sum",
"(",
"d",
".",
"values",
"(",
")",
")",
"target",
"=",
"random",
".",
"random",
"(",
")",
"*",
"total",
"# elect the first item which pushes the count over target",
"count",
"=",
"0",
"for",
"word"... | 25.954545 | 0.033784 |
def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT):
"""Derives a Modular Crypt Format hash using the scrypt KDF
Parameter space is smaller than for scrypt():
N must be a power of two larger than 1 but no larger than 2 ** 31
r and p m... | [
"def",
"scrypt_mcf",
"(",
"password",
",",
"salt",
"=",
"None",
",",
"N",
"=",
"SCRYPT_N",
",",
"r",
"=",
"SCRYPT_r",
",",
"p",
"=",
"SCRYPT_p",
",",
"prefix",
"=",
"SCRYPT_MCF_PREFIX_DEFAULT",
")",
":",
"if",
"isinstance",
"(",
"password",
",",
"unicode... | 43.761905 | 0.001064 |
def dropna(self, dim, how='any', thresh=None, subset=None):
"""Returns a new dataset with dropped labels for missing values along
the provided dimension.
Parameters
----------
dim : str
Dimension along which to drop missing values. Dropping along
multiple... | [
"def",
"dropna",
"(",
"self",
",",
"dim",
",",
"how",
"=",
"'any'",
",",
"thresh",
"=",
"None",
",",
"subset",
"=",
"None",
")",
":",
"# TODO: consider supporting multiple dimensions? Or not, given that",
"# there are some ugly edge cases, e.g., pandas's dropna differs",
... | 35.425926 | 0.001017 |
def update_properties(self) -> None:
"""Update properties group of parameters."""
self.update(path=URL_GET + GROUP.format(group=PROPERTIES)) | [
"def",
"update_properties",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"update",
"(",
"path",
"=",
"URL_GET",
"+",
"GROUP",
".",
"format",
"(",
"group",
"=",
"PROPERTIES",
")",
")"
] | 51.333333 | 0.012821 |
def format_struct(struct_def):
'''Returns a cython struct from a :attr:`StructSpec` instance.
'''
text = []
text.append('cdef struct {}:'.format(struct_def.tp_name))
text.extend(
['{}{}'.format(tab, format_variable(var))
for var in struct_def.members]
)
for name i... | [
"def",
"format_struct",
"(",
"struct_def",
")",
":",
"text",
"=",
"[",
"]",
"text",
".",
"append",
"(",
"'cdef struct {}:'",
".",
"format",
"(",
"struct_def",
".",
"tp_name",
")",
")",
"text",
".",
"extend",
"(",
"[",
"'{}{}'",
".",
"format",
"(",
"tab... | 29.785714 | 0.002326 |
def _calc_overlap_coef(
markers1: dict,
markers2: dict,
):
"""Calculate overlap coefficient between the values of two dictionaries
Note: dict values must be sets
"""
overlap_coef=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].i... | [
"def",
"_calc_overlap_coef",
"(",
"markers1",
":",
"dict",
",",
"markers2",
":",
"dict",
",",
")",
":",
"overlap_coef",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"markers1",
")",
",",
"len",
"(",
"markers2",
")",
")",
")",
"j",
"=",
"0",
"for"... | 28.388889 | 0.013258 |
def move(
ctx,
opts,
owner_repo_package,
destination,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
yes,
):
"""
Move (promote) a package to another repo.
This requires appropriate permissions for both the source
repository/package and the destination r... | [
"def",
"move",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_package",
",",
"destination",
",",
"skip_errors",
",",
"wait_interval",
",",
"no_wait_for_sync",
",",
"sync_attempts",
",",
"yes",
",",
")",
":",
"owner",
",",
"source",
",",
"slug",
"=",
"owner_repo_p... | 26.638889 | 0.001508 |
def subcmd_remove_parser(subcmd):
""" remove subcommand """
subcmd.add_argument(
'--broker',
action='store',
dest='broker',
help=u'Route to the Ansible Service Broker'
)
subcmd.add_argument(
'--local', '-l',
action='store_true',
dest='local',
... | [
"def",
"subcmd_remove_parser",
"(",
"subcmd",
")",
":",
"subcmd",
".",
"add_argument",
"(",
"'--broker'",
",",
"action",
"=",
"'store'",
",",
"dest",
"=",
"'broker'",
",",
"help",
"=",
"u'Route to the Ansible Service Broker'",
")",
"subcmd",
".",
"add_argument",
... | 25.410959 | 0.001038 |
def scaledBy(self, scale):
""" Return a new Selector with scale denominators scaled by a number.
"""
scaled = deepcopy(self)
for test in scaled.elements[0].tests:
if type(test.value) in (int, float):
if test.property == 'scale-denominator':
... | [
"def",
"scaledBy",
"(",
"self",
",",
"scale",
")",
":",
"scaled",
"=",
"deepcopy",
"(",
"self",
")",
"for",
"test",
"in",
"scaled",
".",
"elements",
"[",
"0",
"]",
".",
"tests",
":",
"if",
"type",
"(",
"test",
".",
"value",
")",
"in",
"(",
"int",... | 35.538462 | 0.008439 |
def execute_cmdLine_instructions(instructions, m, l):
""" Applies the instructions given via
<instructions> on the manager <m> """
opt_lut = dict()
inst_lut = dict()
for k, v in six.iteritems(instructions):
bits = k.split('-', 1)
if len(bits) == 1:
if v not in m.modul... | [
"def",
"execute_cmdLine_instructions",
"(",
"instructions",
",",
"m",
",",
"l",
")",
":",
"opt_lut",
"=",
"dict",
"(",
")",
"inst_lut",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"instructions",
")",
":",
"bits",
... | 36 | 0.001503 |
def _get_key_info(self):
"Virtual keys have extended flag set"
# copied more or less verbatim from
# http://www.pinvoke.net/default.aspx/user32.sendinput
if (
(self.key >= 33 and self.key <= 46) or
(self.key >= 91 and self.key <= 93) ):
flags = KEYEVE... | [
"def",
"_get_key_info",
"(",
"self",
")",
":",
"# copied more or less verbatim from",
"# http://www.pinvoke.net/default.aspx/user32.sendinput",
"if",
"(",
"(",
"self",
".",
"key",
">=",
"33",
"and",
"self",
".",
"key",
"<=",
"46",
")",
"or",
"(",
"self",
".",
"k... | 34.6875 | 0.010526 |
def readabt(filename, dirs='.'):
"""Read abt_*.fio type files from beamline B1, HASYLAB.
Input:
filename: the name of the file.
dirs: directories to search for files in
Output:
A dictionary. The fields are self-explanatory.
"""
# resolve filename
filename = misc.findfil... | [
"def",
"readabt",
"(",
"filename",
",",
"dirs",
"=",
"'.'",
")",
":",
"# resolve filename",
"filename",
"=",
"misc",
".",
"findfileindirs",
"(",
"filename",
",",
"dirs",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'rt'",
")",
"abt",
"=",
"{",
"'offse... | 40.414414 | 0.001523 |
def start(self):
"""
The main loop, run forever.
"""
while True:
self.thread_debug("Interval starting")
for thr in threading.enumerate():
self.thread_debug(" " + str(thr))
self.feed_monitors()
start = time.time()
... | [
"def",
"start",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"thread_debug",
"(",
"\"Interval starting\"",
")",
"for",
"thr",
"in",
"threading",
".",
"enumerate",
"(",
")",
":",
"self",
".",
"thread_debug",
"(",
"\" \"",
"+",
"str",
"(",
... | 36.954545 | 0.002398 |
def makeService():
"""Make a service
:returns: an IService
"""
configJSON = os.environ.get('NCOLONY_CONFIG')
if configJSON is None:
return None
config = json.loads(configJSON)
params = config.get('ncolony.beatcheck')
if params is None:
return None
myFilePath = filepa... | [
"def",
"makeService",
"(",
")",
":",
"configJSON",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'NCOLONY_CONFIG'",
")",
"if",
"configJSON",
"is",
"None",
":",
"return",
"None",
"config",
"=",
"json",
".",
"loads",
"(",
"configJSON",
")",
"params",
"=",
... | 29.210526 | 0.001745 |
def auth_config(self, stage=None):
"""Create auth config based on stage."""
if stage:
section = 'stages.{}'.format(stage)
else:
section = 'stages.live'
try:
username = self.lookup(section, 'username')
password = self.lookup(section, 'passw... | [
"def",
"auth_config",
"(",
"self",
",",
"stage",
"=",
"None",
")",
":",
"if",
"stage",
":",
"section",
"=",
"'stages.{}'",
".",
"format",
"(",
"stage",
")",
"else",
":",
"section",
"=",
"'stages.live'",
"try",
":",
"username",
"=",
"self",
".",
"lookup... | 35.972222 | 0.001504 |
def limit_result_set(self, start, end):
"""By default, searches return all matching results.
This method restricts the number of results by setting the start
and end of the result set, starting from 1. The starting and
ending results can be used for paging results when a certain
... | [
"def",
"limit_result_set",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"if",
"not",
"isinstance",
"(",
"start",
",",
"int",
")",
"or",
"not",
"isinstance",
"(",
"end",
",",
"int",
")",
":",
"raise",
"errors",
".",
"InvalidArgument",
"(",
"'start a... | 46.481481 | 0.002342 |
def is_closing(self) -> bool:
"""Return ``True`` if this connection is closing.
The connection is considered closing if either side has
initiated its closing handshake or if the stream has been
shut down uncleanly.
"""
return self.stream.closed() or self.client_terminate... | [
"def",
"is_closing",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"stream",
".",
"closed",
"(",
")",
"or",
"self",
".",
"client_terminated",
"or",
"self",
".",
"server_terminated"
] | 42.5 | 0.008646 |
def your_tips_breadcrumbs(context, active_breadcrumb_title=None):
"""
A template tag to display breadcrumbs on the recent and popular tip views.
:param context: takes context
"""
context = copy(context)
if get_your_tip(context):
context.update({
'your_tip_page_slug': get_you... | [
"def",
"your_tips_breadcrumbs",
"(",
"context",
",",
"active_breadcrumb_title",
"=",
"None",
")",
":",
"context",
"=",
"copy",
"(",
"context",
")",
"if",
"get_your_tip",
"(",
"context",
")",
":",
"context",
".",
"update",
"(",
"{",
"'your_tip_page_slug'",
":",... | 32.384615 | 0.002309 |
def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False):
"""Gets data from queues and organizes it by agent.
If none of the parameters are given then data from every
:class:`.QueueServer` is retrieved.
Parameters
----------
queues : int or ... | [
"def",
"get_agent_data",
"(",
"self",
",",
"queues",
"=",
"None",
",",
"edge",
"=",
"None",
",",
"edge_type",
"=",
"None",
",",
"return_header",
"=",
"False",
")",
":",
"queues",
"=",
"_get_queues",
"(",
"self",
".",
"g",
",",
"queues",
",",
"edge",
... | 38.518987 | 0.000961 |
def find_rak():
"""
Find our instance of Rak, navigating Local's and possible blueprints.
"""
if hasattr(current_app, 'rak'):
return getattr(current_app, 'rak')
else:
if hasattr(current_app, 'blueprints'):
blueprints = getattr(current_app, 'blueprints')
for bl... | [
"def",
"find_rak",
"(",
")",
":",
"if",
"hasattr",
"(",
"current_app",
",",
"'rak'",
")",
":",
"return",
"getattr",
"(",
"current_app",
",",
"'rak'",
")",
"else",
":",
"if",
"hasattr",
"(",
"current_app",
",",
"'blueprints'",
")",
":",
"blueprints",
"=",... | 39.083333 | 0.002083 |
def workers(self):
"""Get a dictionary mapping worker ID to worker information."""
worker_keys = self.redis_client.keys("Worker*")
workers_data = {}
for worker_key in worker_keys:
worker_info = self.redis_client.hgetall(worker_key)
worker_id = binary_to_hex(worke... | [
"def",
"workers",
"(",
"self",
")",
":",
"worker_keys",
"=",
"self",
".",
"redis_client",
".",
"keys",
"(",
"\"Worker*\"",
")",
"workers_data",
"=",
"{",
"}",
"for",
"worker_key",
"in",
"worker_keys",
":",
"worker_info",
"=",
"self",
".",
"redis_client",
"... | 43.190476 | 0.002157 |
def std_datetimestr(self, datetimestr):
"""Reformat a datetime string to standard format.
"""
return datetime.strftime(
self.str2datetime(datetimestr), self.std_datetimeformat) | [
"def",
"std_datetimestr",
"(",
"self",
",",
"datetimestr",
")",
":",
"return",
"datetime",
".",
"strftime",
"(",
"self",
".",
"str2datetime",
"(",
"datetimestr",
")",
",",
"self",
".",
"std_datetimeformat",
")"
] | 42.4 | 0.009259 |
def cleanup(self):
"""Delete expired nonces"""
t = time.time()
for noncefile in glob(self.path + '/*.nonce'):
if os.path.getmtime(noncefile) + self.expiration > t:
os.unlink(noncefile) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"for",
"noncefile",
"in",
"glob",
"(",
"self",
".",
"path",
"+",
"'/*.nonce'",
")",
":",
"if",
"os",
".",
"path",
".",
"getmtime",
"(",
"noncefile",
")",
"+",
"self... | 38.5 | 0.008475 |
def members(self):
""" Children of the collection's item
:rtype: [Collection]
"""
return list(
[
self.children_class(child)
for child in self.graph.subjects(RDF_NAMESPACES.DTS.parent, self.asNode())
]
) | [
"def",
"members",
"(",
"self",
")",
":",
"return",
"list",
"(",
"[",
"self",
".",
"children_class",
"(",
"child",
")",
"for",
"child",
"in",
"self",
".",
"graph",
".",
"subjects",
"(",
"RDF_NAMESPACES",
".",
"DTS",
".",
"parent",
",",
"self",
".",
"a... | 26.272727 | 0.010033 |
def resolution(x, zero=True):
"""
Compute the resolution of a data vector
Resolution is smallest non-zero distance between adjacent values
Parameters
----------
x : 1D array-like
zero : Boolean
Whether to include zero values in the computation
Result
------
res : re... | [
"def",
"resolution",
"(",
"x",
",",
"zero",
"=",
"True",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"# (unsigned) integers or an effective range of zero",
"_x",
"=",
"x",
"[",
"~",
"np",
".",
"isnan",
"(",
"x",
")",
"]",
"_x",
"=",
"(",... | 22.966667 | 0.001393 |
def set_form_parameters(context):
"""
Parameters:
+-------------+--------------+
| param_name | param_value |
+=============+==============+
| param1 | value1 |
+-------------+--------------+
| param2 | value2 |
+-------------+----... | [
"def",
"set_form_parameters",
"(",
"context",
")",
":",
"safe_add_http_request_context_to_behave_context",
"(",
"context",
")",
"context",
".",
"http_request_context",
".",
"body_params",
"=",
"get_parameters",
"(",
"context",
")",
"context",
".",
"http_request_context",
... | 34.4 | 0.001887 |
def i_batch(max_size, iterable):
"""
Generator that iteratively batches items
to a max size and consumes the items iterable
as each batch is yielded.
:param max_size: Max size of each batch.
:type max_size: int
:param iterable: An iterable
:type iterable: iter
"""
iterable_items... | [
"def",
"i_batch",
"(",
"max_size",
",",
"iterable",
")",
":",
"iterable_items",
"=",
"iter",
"(",
"iterable",
")",
"for",
"items_batch",
"in",
"iter",
"(",
"lambda",
":",
"tuple",
"(",
"islice",
"(",
"iterable_items",
",",
"max_size",
")",
")",
",",
"tup... | 30.933333 | 0.002092 |
def delete_entity(self, table_name, partition_key, row_key,
if_match='*', timeout=None):
'''
Deletes an existing entity in a table. Throws if the entity does not exist.
When an entity is successfully deleted, the entity is immediately marked
for deletion and is no... | [
"def",
"delete_entity",
"(",
"self",
",",
"table_name",
",",
"partition_key",
",",
"row_key",
",",
"if_match",
"=",
"'*'",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'table_name'",
",",
"table_name",
")",
"request",
"=",
"_delete_entity... | 50.30303 | 0.008865 |
def get_GEO_file(geo, destdir=None, annotate_gpl=False, how="full",
include_data=False, silent=False, aspera=False):
"""Download corresponding SOFT file given GEO accession.
Args:
geo (:obj:`str`): GEO database identifier.
destdir (:obj:`str`, optional): Directory to download d... | [
"def",
"get_GEO_file",
"(",
"geo",
",",
"destdir",
"=",
"None",
",",
"annotate_gpl",
"=",
"False",
",",
"how",
"=",
"\"full\"",
",",
"include_data",
"=",
"False",
",",
"silent",
"=",
"False",
",",
"aspera",
"=",
"False",
")",
":",
"geo",
"=",
"geo",
... | 45.611111 | 0.000795 |
def _GetSupportedFilesInDir(self, fileDir, fileList, supportedFormatList, ignoreDirList):
"""
Recursively get all supported files given a root search directory.
Supported file extensions are given as a list, as are any directories which
should be ignored.
The result will be appended to the given f... | [
"def",
"_GetSupportedFilesInDir",
"(",
"self",
",",
"fileDir",
",",
"fileList",
",",
"supportedFormatList",
",",
"ignoreDirList",
")",
":",
"goodlogging",
".",
"Log",
".",
"Info",
"(",
"\"CLEAR\"",
",",
"\"Parsing file directory: {0}\"",
".",
"format",
"(",
"fileD... | 38.435897 | 0.009109 |
def _to_bc_h_w(self, x, x_shape):
"""(b, h, w, c) -> (b*c, h, w)"""
x = tf.transpose(x, [0, 3, 1, 2])
x = tf.reshape(x, (-1, x_shape[1], x_shape[2]))
return x | [
"def",
"_to_bc_h_w",
"(",
"self",
",",
"x",
",",
"x_shape",
")",
":",
"x",
"=",
"tf",
".",
"transpose",
"(",
"x",
",",
"[",
"0",
",",
"3",
",",
"1",
",",
"2",
"]",
")",
"x",
"=",
"tf",
".",
"reshape",
"(",
"x",
",",
"(",
"-",
"1",
",",
... | 37.2 | 0.010526 |
def defaultFile(self):
"""Produce a reasonable default."""
filename = self.curframe.f_code.co_filename
if filename == '<string>' and self.mainpyfile:
filename = self.mainpyfile
return filename | [
"def",
"defaultFile",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"curframe",
".",
"f_code",
".",
"co_filename",
"if",
"filename",
"==",
"'<string>'",
"and",
"self",
".",
"mainpyfile",
":",
"filename",
"=",
"self",
".",
"mainpyfile",
"return",
"fi... | 38.5 | 0.008475 |
def search_blogs(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google blogs query formatted as a GoogleSearch list object.
"""
service = GOOGLE_BLOGS
return GoogleSearch(q, start, service, "", wait, asynchronous, cached) | [
"def",
"search_blogs",
"(",
"q",
",",
"start",
"=",
"0",
",",
"wait",
"=",
"10",
",",
"asynchronous",
"=",
"False",
",",
"cached",
"=",
"False",
")",
":",
"service",
"=",
"GOOGLE_BLOGS",
"return",
"GoogleSearch",
"(",
"q",
",",
"start",
",",
"service",... | 37.714286 | 0.011111 |
def compprefs(self):
"""
A ``list`` of preferred compression algorithms specified in this signature, if any. Otherwise, an empty ``list``.
"""
if 'PreferredCompressionAlgorithms' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_PreferredCompressio... | [
"def",
"compprefs",
"(",
"self",
")",
":",
"if",
"'PreferredCompressionAlgorithms'",
"in",
"self",
".",
"_signature",
".",
"subpackets",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"_signature",
".",
"subpackets",
"[",
"'h_PreferredCompressionAlgorithms'... | 50.428571 | 0.011142 |
def _call_and_format(self, req, props=None):
"""
Invokes a single request against a handler using _call() and traps any errors,
formatting them using _err(). If the request is successful it is wrapped in a
JSON-RPC 2.0 compliant dict with keys: 'jsonrpc', 'id', 'result'.
:Para... | [
"def",
"_call_and_format",
"(",
"self",
",",
"req",
",",
"props",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"req",
",",
"dict",
")",
":",
"return",
"err_response",
"(",
"None",
",",
"ERR_INVALID_REQ",
",",
"\"Invalid Request. %s is not an object.\... | 33.958333 | 0.010733 |
def fromutc(self, dt):
"""
The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`.
:param dt:
A :py:class:`datetime.datetime` object.
:raises TypeError:
Raised if ``dt`` is not a :py:class:`datetime.datetime` object.
:raises ValueError:
... | [
"def",
"fromutc",
"(",
"self",
",",
"dt",
")",
":",
"# These isinstance checks are in datetime.tzinfo, so we'll preserve",
"# them, even if we don't care about duck typing.",
"if",
"not",
"isinstance",
"(",
"dt",
",",
"datetime",
".",
"datetime",
")",
":",
"raise",
"TypeE... | 34.657143 | 0.001604 |
def drawHealpixMap(hpxmap, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs):
"""
Draw local projection of healpix map.
"""
ax = plt.gca()
x = np.linspace(-size,size,xsize)
y = np.linspace(-size,size,xsize)
xx, yy = np.meshgrid(x,y)
coord = coord.upper()
if coord == ... | [
"def",
"drawHealpixMap",
"(",
"hpxmap",
",",
"lon",
",",
"lat",
",",
"size",
"=",
"1.0",
",",
"xsize",
"=",
"501",
",",
"coord",
"=",
"'GC'",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"x",
"=",
"np",
".",
"lin... | 38.428571 | 0.030825 |
def extract_interesting_date_ranges(returns):
"""
Extracts returns based on interesting events. See
gen_date_range_interesting.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
R... | [
"def",
"extract_interesting_date_ranges",
"(",
"returns",
")",
":",
"returns_dupe",
"=",
"returns",
".",
"copy",
"(",
")",
"returns_dupe",
".",
"index",
"=",
"returns_dupe",
".",
"index",
".",
"map",
"(",
"pd",
".",
"Timestamp",
")",
"ranges",
"=",
"OrderedD... | 26.433333 | 0.001217 |
def _reshape_m_vecs(self):
"""return list of arrays, each array represents a different n mode"""
lst = []
for n in xrange(0, self.nmax + 1):
mlst = []
if n <= self.mmax:
nn = n
else:
nn = self.mmax
... | [
"def",
"_reshape_m_vecs",
"(",
"self",
")",
":",
"lst",
"=",
"[",
"]",
"for",
"n",
"in",
"xrange",
"(",
"0",
",",
"self",
".",
"nmax",
"+",
"1",
")",
":",
"mlst",
"=",
"[",
"]",
"if",
"n",
"<=",
"self",
".",
"mmax",
":",
"nn",
"=",
"n",
"el... | 32.428571 | 0.008565 |
def updateCurrentView(self, oldWidget, newWidget):
"""
Updates the current view widget.
:param oldWidget | <QtGui.QWidget>
newWidget | <QtGui.QWidget>
"""
view = projexui.ancestor(newWidget, XView)
if view is not None:
view.se... | [
"def",
"updateCurrentView",
"(",
"self",
",",
"oldWidget",
",",
"newWidget",
")",
":",
"view",
"=",
"projexui",
".",
"ancestor",
"(",
"newWidget",
",",
"XView",
")",
"if",
"view",
"is",
"not",
"None",
":",
"view",
".",
"setCurrent",
"(",
")"
] | 32.1 | 0.009091 |
def modified(self):
'return datetime.datetime'
return dateutil.parser.parse(str(self.f.latestRevision.modified)) | [
"def",
"modified",
"(",
"self",
")",
":",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"str",
"(",
"self",
".",
"f",
".",
"latestRevision",
".",
"modified",
")",
")"
] | 42 | 0.015625 |
def create(cls, ip_version, datacenter, bandwidth, vlan, vm, ip,
background):
""" Create a new iface """
if not background and not cls.intty():
background = True
datacenter_id_ = int(Datacenter.usable_id(datacenter))
iface_params = {
'ip_version':... | [
"def",
"create",
"(",
"cls",
",",
"ip_version",
",",
"datacenter",
",",
"bandwidth",
",",
"vlan",
",",
"vm",
",",
"ip",
",",
"background",
")",
":",
"if",
"not",
"background",
"and",
"not",
"cls",
".",
"intty",
"(",
")",
":",
"background",
"=",
"True... | 29.727273 | 0.002221 |
def wp_caption(self, post):
"""
Filters a Wordpress Post for Image Captions and renders to
match HTML.
"""
for match in re.finditer(r"\[caption (.*?)\](.*?)\[/caption\]", post):
meta = '<div '
caption = ''
for imatch in re.finditer(r'(\w+)="(.*... | [
"def",
"wp_caption",
"(",
"self",
",",
"post",
")",
":",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r\"\\[caption (.*?)\\](.*?)\\[/caption\\]\"",
",",
"post",
")",
":",
"meta",
"=",
"'<div '",
"caption",
"=",
"''",
"for",
"imatch",
"in",
"re",
".",... | 44.954545 | 0.00198 |
def generate(self, api):
"""
Generates a module for each namespace.
Each namespace will have Obj C classes to represent data types and
routes in the Stone spec.
"""
rsrc_folder = os.path.join(os.path.dirname(__file__), 'obj_c_rsrc')
rsrc_output_folder = os.path.j... | [
"def",
"generate",
"(",
"self",
",",
"api",
")",
":",
"rsrc_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'obj_c_rsrc'",
")",
"rsrc_output_folder",
"=",
"os",
".",
"path",
".",
"join... | 44.046512 | 0.001033 |
def pb(scalars_layout):
"""Creates a summary that contains a layout.
When users navigate to the custom scalars dashboard, they will see a layout
based on the proto provided to this function.
Args:
scalars_layout: The scalars_layout_pb2.Layout proto that specifies the
layout.
Returns:
A summ... | [
"def",
"pb",
"(",
"scalars_layout",
")",
":",
"# TODO(nickfelt): remove on-demand imports once dep situation is fixed.",
"import",
"tensorflow",
".",
"compat",
".",
"v1",
"as",
"tf",
"assert",
"isinstance",
"(",
"scalars_layout",
",",
"layout_pb2",
".",
"Layout",
")",
... | 34.153846 | 0.010953 |
def configure_crossover(self, genome1, genome2, config):
""" Configure a new genome by crossover from two parent genomes. """
assert isinstance(genome1.fitness, (int, float))
assert isinstance(genome2.fitness, (int, float))
if genome1.fitness > genome2.fitness:
parent1, paren... | [
"def",
"configure_crossover",
"(",
"self",
",",
"genome1",
",",
"genome2",
",",
"config",
")",
":",
"assert",
"isinstance",
"(",
"genome1",
".",
"fitness",
",",
"(",
"int",
",",
"float",
")",
")",
"assert",
"isinstance",
"(",
"genome2",
".",
"fitness",
"... | 40.9375 | 0.001491 |
def move_forward(num_steps):
"""Moves the pen forward a few steps in the direction that its "turtle" is facing.
Arguments:
num_steps - a number like 20. A bigger number makes the pen move farther.
"""
assert int(num_steps) == num_steps, "move_forward() only accepts integers, but you gave it " +... | [
"def",
"move_forward",
"(",
"num_steps",
")",
":",
"assert",
"int",
"(",
"num_steps",
")",
"==",
"num_steps",
",",
"\"move_forward() only accepts integers, but you gave it \"",
"+",
"str",
"(",
"num_steps",
")",
"_make_cnc_request",
"(",
"\"move.forward./\"",
"+",
"st... | 38.454545 | 0.009238 |
def get_versions(name,
default_string=DEFAULT_STRING_NOT_FOUND,
default_tuple=DEFAULT_TUPLE_NOT_FOUND,
allow_ambiguous=True):
"""
Get string and tuple versions from installed package information
It will return :attr:`default_string` and :attr:`default_tupl... | [
"def",
"get_versions",
"(",
"name",
",",
"default_string",
"=",
"DEFAULT_STRING_NOT_FOUND",
",",
"default_tuple",
"=",
"DEFAULT_TUPLE_NOT_FOUND",
",",
"allow_ambiguous",
"=",
"True",
")",
":",
"version_string",
"=",
"get_string_version",
"(",
"name",
",",
"default_str... | 32.547619 | 0.00071 |
def oembed(url, params=""):
"""
Render an OEmbed-compatible link as an embedded item.
:param url: A URL of an OEmbed provider.
:return: The OEMbed ``<embed>`` code.
"""
# Note: this method isn't currently very efficient - the data isn't
# cached or stored.
kwargs = dict(urlparse.parse_... | [
"def",
"oembed",
"(",
"url",
",",
"params",
"=",
"\"\"",
")",
":",
"# Note: this method isn't currently very efficient - the data isn't",
"# cached or stored.",
"kwargs",
"=",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"params",
")",
")",
"try",
":",
"return",
... | 26.333333 | 0.001745 |
def has_session(self, target_session, exact=True):
"""
Return True if session exists. ``$ tmux has-session``.
Parameters
----------
target_session : str
session name
exact : bool
match the session name exactly. tmux uses fnmatch by default.
... | [
"def",
"has_session",
"(",
"self",
",",
"target_session",
",",
"exact",
"=",
"True",
")",
":",
"session_check_name",
"(",
"target_session",
")",
"if",
"exact",
"and",
"has_gte_version",
"(",
"'2.1'",
")",
":",
"target_session",
"=",
"'={}'",
".",
"format",
"... | 25.3125 | 0.002378 |
def _payload(self):
"""header that implements PayloadMixin"""
return self.tcp or self.udp or self.icmpv4 or self.icmpv6 | [
"def",
"_payload",
"(",
"self",
")",
":",
"return",
"self",
".",
"tcp",
"or",
"self",
".",
"udp",
"or",
"self",
".",
"icmpv4",
"or",
"self",
".",
"icmpv6"
] | 44.333333 | 0.014815 |
def add_input_list_opt(self, opt, inputs):
""" Add an option that determines a list of inputs
"""
self.add_opt(opt)
for inp in inputs:
self.add_opt(inp)
self._add_input(inp) | [
"def",
"add_input_list_opt",
"(",
"self",
",",
"opt",
",",
"inputs",
")",
":",
"self",
".",
"add_opt",
"(",
"opt",
")",
"for",
"inp",
"in",
"inputs",
":",
"self",
".",
"add_opt",
"(",
"inp",
")",
"self",
".",
"_add_input",
"(",
"inp",
")"
] | 31.857143 | 0.008734 |
def get_documenter(obj, parent):
"""Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import AutoD... | [
"def",
"get_documenter",
"(",
"obj",
",",
"parent",
")",
":",
"from",
"sphinx",
".",
"ext",
".",
"autodoc",
"import",
"AutoDirective",
",",
"DataDocumenter",
",",
"ModuleDocumenter",
"if",
"inspect",
".",
"ismodule",
"(",
"obj",
")",
":",
"# ModuleDocumenter.c... | 33.647059 | 0.001699 |
def getFullPathToSnapshot(self, n):
"""Get the full path to snapshot n."""
return os.path.join(self.snapDir, str(n)) | [
"def",
"getFullPathToSnapshot",
"(",
"self",
",",
"n",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"snapDir",
",",
"str",
"(",
"n",
")",
")"
] | 39.333333 | 0.033333 |
def _StartSshd(self):
"""Initialize the SSH daemon."""
# Exit as early as possible.
# Instance setup systemd scripts block sshd from starting.
if os.path.exists(constants.LOCALBASE + '/bin/systemctl'):
return
elif (os.path.exists('/etc/init.d/ssh')
or os.path.exists('/etc/init/ssh.co... | [
"def",
"_StartSshd",
"(",
"self",
")",
":",
"# Exit as early as possible.",
"# Instance setup systemd scripts block sshd from starting.",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"LOCALBASE",
"+",
"'/bin/systemctl'",
")",
":",
"return",
"elif",
"... | 44.214286 | 0.009494 |
def remove_namespace(doc, namespace):
"""
Takes in a ElementTree object and namespace value. The length of that
namespace value is removed from all Element nodes within the document.
This effectively removes the namespace from that document.
:param doc: lxml.etree
:param namespace: Namespace t... | [
"def",
"remove_namespace",
"(",
"doc",
",",
"namespace",
")",
":",
"# http://homework.nwsnet.de/products/45be_remove-namespace-in-an-xml-document-using-elementtree",
"#",
"# Permission is hereby granted, free of charge, to any person obtaining",
"# a copy of this software and associated docume... | 49.405405 | 0.000536 |
def extract_array(obj, extract_numpy=False):
"""
Extract the ndarray or ExtensionArray from a Series or Index.
For all other types, `obj` is just returned as is.
Parameters
----------
obj : object
For Series / Index, the underlying ExtensionArray is unboxed.
For Numpy-backed Ex... | [
"def",
"extract_array",
"(",
"obj",
",",
"extract_numpy",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"ABCIndexClass",
",",
"ABCSeries",
")",
")",
":",
"obj",
"=",
"obj",
".",
"array",
"if",
"extract_numpy",
"and",
"isinstance",
"("... | 25.571429 | 0.000769 |
def plot_di_mean_bingham(bingham_dictionary, fignum=1, color='k', marker='o', markersize=20, label='', legend='no'):
"""
see plot_di_mean_ellipse
"""
plot_di_mean_ellipse(bingham_dictionary, fignum=fignum, color=color,
marker=marker, markersize=markersize, label=label, legend=le... | [
"def",
"plot_di_mean_bingham",
"(",
"bingham_dictionary",
",",
"fignum",
"=",
"1",
",",
"color",
"=",
"'k'",
",",
"marker",
"=",
"'o'",
",",
"markersize",
"=",
"20",
",",
"label",
"=",
"''",
",",
"legend",
"=",
"'no'",
")",
":",
"plot_di_mean_ellipse",
"... | 53.333333 | 0.009231 |
def clear(self) -> None:
"""
Treat as if the *underlying* database will also be cleared by some other mechanism.
We build a special empty changeset just for marking that all previous data should
be ignored.
"""
# these internal records are used as a way to tell the differ... | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"# these internal records are used as a way to tell the difference between",
"# changes that came before and after the clear",
"self",
".",
"record_changeset",
"(",
")",
"self",
".",
"_clears_at",
".",
"add",
"(",
"self",... | 44.090909 | 0.010101 |
def init_logging(logfile=None, loglevel=logging.INFO, configfile=None):
"""
Configures the logging using either basic filename + loglevel or passed config file path.
This is performed separately from L{init_config()} in order to support the case where
logging should happen independent of (usu. *after*... | [
"def",
"init_logging",
"(",
"logfile",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
",",
"configfile",
"=",
"None",
")",
":",
"# If a config file was specified, we will use that in place of the",
"# explicitly",
"use_configfile",
"=",
"False",
"if",
"con... | 47.642857 | 0.008325 |
def logDiffExp(A, B, out=None):
""" returns log(exp(A) - exp(B)). A and B are numpy arrays. values in A should be
greater than or equal to corresponding values in B"""
if out is None:
out = numpy.zeros(A.shape)
indicator1 = A >= B
assert indicator1.all(), "Values in the first array should be greater tha... | [
"def",
"logDiffExp",
"(",
"A",
",",
"B",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"numpy",
".",
"zeros",
"(",
"A",
".",
"shape",
")",
"indicator1",
"=",
"A",
">=",
"B",
"assert",
"indicator1",
".",
"all",
"... | 36.666667 | 0.022173 |
def set_options(self, option_type, option_dict, force_options=False):
"""set plot options """
if force_options:
self.options[option_type].update(option_dict)
elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list):
# For multi-Axis
... | [
"def",
"set_options",
"(",
"self",
",",
"option_type",
",",
"option_dict",
",",
"force_options",
"=",
"False",
")",
":",
"if",
"force_options",
":",
"self",
".",
"options",
"[",
"option_type",
"]",
".",
"update",
"(",
"option_dict",
")",
"elif",
"(",
"opti... | 54.333333 | 0.010856 |
def check(wants, has):
"""
Check if a desired scope ``wants`` is part of an available scope ``has``.
Returns ``False`` if not, return ``True`` if yes.
:example:
If a list of scopes such as
::
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
SCOPES = (
... | [
"def",
"check",
"(",
"wants",
",",
"has",
")",
":",
"if",
"wants",
"&",
"has",
"==",
"0",
":",
"return",
"False",
"if",
"wants",
"&",
"has",
"<",
"wants",
":",
"return",
"False",
"return",
"True"
] | 20.217391 | 0.001026 |
def generate(env):
"""Add Builders and construction variables for midl to an Environment."""
env['MIDL'] = 'MIDL.EXE'
env['MIDLFLAGS'] = SCons.Util.CLVar('/nologo')
env['MIDLCOM'] = '$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} /h ${TARGETS[1]} /iid ${TARGETS[2]} /proxy ${TARGETS[3]} /dlldata... | [
"def",
"generate",
"(",
"env",
")",
":",
"env",
"[",
"'MIDL'",
"]",
"=",
"'MIDL.EXE'",
"env",
"[",
"'MIDLFLAGS'",
"]",
"=",
"SCons",
".",
"Util",
".",
"CLVar",
"(",
"'/nologo'",
")",
"env",
"[",
"'MIDLCOM'",
"]",
"=",
"'$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} ... | 56.285714 | 0.0125 |
def walkfiles(startdir, regex=None, recurse=True):
"""Yields the absolute paths of files found within the given start
directory. Can optionally filter paths using a regex pattern."""
for r,_,fs in os.walk(startdir):
if not recurse and startdir != r:
return
for f in fs:
... | [
"def",
"walkfiles",
"(",
"startdir",
",",
"regex",
"=",
"None",
",",
"recurse",
"=",
"True",
")",
":",
"for",
"r",
",",
"_",
",",
"fs",
"in",
"os",
".",
"walk",
"(",
"startdir",
")",
":",
"if",
"not",
"recurse",
"and",
"startdir",
"!=",
"r",
":",... | 40.25 | 0.010121 |
def expand_composites (properties):
""" Expand all composite properties in the set so that all components
are explicitly expressed.
"""
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
explicit_features = set(p.feature for p in propertie... | [
"def",
"expand_composites",
"(",
"properties",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"property",
"import",
"Property",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"Property",
")",
"explicit_features",
"=",
"set",
"(",
"p",
".",
"feature",
"... | 42.473684 | 0.009085 |
def assemble_loopy():
"""Assemble INDRA Statements into a Loopy model using SIF Assembler."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
s... | [
"def",
"assemble_loopy",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"return",
"{",
"}",
"response",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"body",
"=",
"json",
".",
"loads",... | 35.769231 | 0.002096 |
def rmvirtualenv():
"""
Remove the current or ``env.project_version`` environment and all content in it
"""
path = '/'.join([deployment_root(),'env',env.project_fullname])
link = '/'.join([deployment_root(),'env',env.project_name])
if version_state('mkvirtualenv'):
sudo(' '.join(['rm -rf... | [
"def",
"rmvirtualenv",
"(",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
"'env'",
",",
"env",
".",
"project_fullname",
"]",
")",
"link",
"=",
"'/'",
".",
"join",
"(",
"[",
"deployment_root",
"(",
")",
",",
... | 43.363636 | 0.020534 |
def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None):
"""
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success.
https://core.telegram.org/bots/api#... | [
"def",
"create_new_sticker_set",
"(",
"self",
",",
"user_id",
",",
"name",
",",
"title",
",",
"png_sticker",
",",
"emojis",
",",
"contains_masks",
"=",
"None",
",",
"mask_position",
"=",
"None",
")",
":",
"from",
"pytgbot",
".",
"api_types",
".",
"receivable... | 52.238806 | 0.009815 |
def model(self):
"""Return the model name of the printer."""
try:
return self.data.get('identity').get('model_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | [
"def",
"model",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"'identity'",
")",
".",
"get",
"(",
"'model_name'",
")",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",
":",
"return",
"self",
".",
"device_statu... | 39.333333 | 0.008299 |
def commit(self):
"""Commit the changes accumulated in this batch.
Returns:
List[google.cloud.proto.firestore.v1beta1.\
write_pb2.WriteResult, ...]: The write results corresponding
to the changes committed, returned in the same order as the
changes we... | [
"def",
"commit",
"(",
"self",
")",
":",
"commit_response",
"=",
"self",
".",
"_client",
".",
"_firestore_api",
".",
"commit",
"(",
"self",
".",
"_client",
".",
"_database_string",
",",
"self",
".",
"_write_pbs",
",",
"transaction",
"=",
"None",
",",
"metad... | 38.333333 | 0.002424 |
def create(self, data):
"""
Create a new list in your MailChimp account.
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"name": string*,
"contact": object*
{
"company": string*,
"... | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"if",
"'name'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The list must have a name'",
")",
"if",
"'contact'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The list must have a contact'"... | 43.119403 | 0.000677 |
def register_function(self, func, magic_kind='line', magic_name=None):
"""Expose a standalone function as magic function for IPython.
This will create an IPython magic (line, cell or both) from a
standalone function. The functions should have the following
signatures:
* For l... | [
"def",
"register_function",
"(",
"self",
",",
"func",
",",
"magic_kind",
"=",
"'line'",
",",
"magic_name",
"=",
"None",
")",
":",
"# Create the new method in the user_magics and register it in the",
"# global table",
"validate_type",
"(",
"magic_kind",
")",
"magic_name",
... | 39 | 0.002274 |
def disable_digital_reporting(self, pin):
"""
Disables digital reporting. By turning reporting off for this pin, reporting
is disabled for all 8 bits in the "port" -
:param pin: Pin and all pins for this port
:return: No return value
"""
port = pin // 8
... | [
"def",
"disable_digital_reporting",
"(",
"self",
",",
"pin",
")",
":",
"port",
"=",
"pin",
"//",
"8",
"command",
"=",
"[",
"self",
".",
"_command_handler",
".",
"REPORT_DIGITAL",
"+",
"port",
",",
"self",
".",
"REPORTING_DISABLE",
"]",
"self",
".",
"_comma... | 36.666667 | 0.008869 |
def notebook_exists(self, notebook_id):
"""Does a notebook exist?"""
if notebook_id not in self.mapping:
return False
path = self.get_path_by_name(self.mapping[notebook_id])
return os.path.isfile(path) | [
"def",
"notebook_exists",
"(",
"self",
",",
"notebook_id",
")",
":",
"if",
"notebook_id",
"not",
"in",
"self",
".",
"mapping",
":",
"return",
"False",
"path",
"=",
"self",
".",
"get_path_by_name",
"(",
"self",
".",
"mapping",
"[",
"notebook_id",
"]",
")",
... | 40 | 0.008163 |
def from_unknown_text(text, strict=False):
"""
Detect crs string format and parse into crs object with appropriate function.
Arguments:
- *text*: The crs text representation of unknown type.
- *strict* (optional): When True, the parser is strict about names having to match
exactly with up... | [
"def",
"from_unknown_text",
"(",
"text",
",",
"strict",
"=",
"False",
")",
":",
"if",
"text",
".",
"startswith",
"(",
"\"+\"",
")",
":",
"crs",
"=",
"from_proj4",
"(",
"text",
",",
"strict",
")",
"elif",
"text",
".",
"startswith",
"(",
"(",
"\"PROJCS[\... | 28.222222 | 0.008563 |
def remove_app(name, site):
'''
Remove an IIS application.
Args:
name (str): The application name.
site (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_app name='app0' site... | [
"def",
"remove_app",
"(",
"name",
",",
"site",
")",
":",
"current_apps",
"=",
"list_apps",
"(",
"site",
")",
"if",
"name",
"not",
"in",
"current_apps",
":",
"log",
".",
"debug",
"(",
"'Application already absent: %s'",
",",
"name",
")",
"return",
"True",
"... | 24.047619 | 0.000951 |
def Moran_BV_matrix(variables, w, permutations=0, varnames=None):
"""
Bivariate Moran Matrix
Calculates bivariate Moran between all pairs of a set of variables.
Parameters
----------
variables : array or pandas.DataFrame
sequence of variables to be assessed
w ... | [
"def",
"Moran_BV_matrix",
"(",
"variables",
",",
"w",
",",
"permutations",
"=",
"0",
",",
"varnames",
"=",
"None",
")",
":",
"try",
":",
"# check if pandas is installed",
"import",
"pandas",
"if",
"isinstance",
"(",
"variables",
",",
"pandas",
".",
"DataFrame"... | 31.783784 | 0.001649 |
def default_handler(self, signum, frame):
""" Default handler, a generic callback method for signal processing"""
self.log.debug("Signal handler called with signal: {0}".format(signum))
# 1. If signal is HUP restart the python process
# 2. If signal is TERM, INT or QUIT we try to cleanup... | [
"def",
"default_handler",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Signal handler called with signal: {0}\"",
".",
"format",
"(",
"signum",
")",
")",
"# 1. If signal is HUP restart the python process",
"# 2. If sign... | 46.535714 | 0.002256 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.