text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def mappings(self):
"""
Returns a sorted list of all the mappings for this memory.
:return: a list of mappings.
:rtype: list
"""
result = []
for m in self.maps:
if isinstance(m, AnonMap):
result.append((m.start, m.end, m.perms, 0, ''))... | [
"def",
"mappings",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"m",
"in",
"self",
".",
"maps",
":",
"if",
"isinstance",
"(",
"m",
",",
"AnonMap",
")",
":",
"result",
".",
"append",
"(",
"(",
"m",
".",
"start",
",",
"m",
".",
"end",
... | 31.941176 | 18.294118 |
def stages(self):
"""
Property for accessing :class:`StageManager` instance, which is used to manage stages.
:rtype: yagocd.resources.stage.StageManager
"""
if self._stage_manager is None:
self._stage_manager = StageManager(session=self._session)
return self.... | [
"def",
"stages",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stage_manager",
"is",
"None",
":",
"self",
".",
"_stage_manager",
"=",
"StageManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
"self",
".",
"_stage_manager"
] | 36.222222 | 18.222222 |
def normalize_words(self, ord=2, inplace=False):
"""Normalize embeddings matrix row-wise.
Args:
ord: normalization order. Possible values {1, 2, 'inf', '-inf'}
"""
if ord == 2:
ord = None # numpy uses this flag to indicate l2.
vectors = self.vectors.T / np.linalg.norm(self.vectors, ord,... | [
"def",
"normalize_words",
"(",
"self",
",",
"ord",
"=",
"2",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"ord",
"==",
"2",
":",
"ord",
"=",
"None",
"# numpy uses this flag to indicate l2.",
"vectors",
"=",
"self",
".",
"vectors",
".",
"T",
"/",
"np",
... | 34.538462 | 20.307692 |
def fuzzy_int(str_):
"""
lets some special strings be interpreted as ints
"""
try:
ret = int(str_)
return ret
except Exception:
# Parse comma separated values as ints
if re.match(r'\d*,\d*,?\d*', str_):
return tuple(map(int, str_.split(',')))
# Par... | [
"def",
"fuzzy_int",
"(",
"str_",
")",
":",
"try",
":",
"ret",
"=",
"int",
"(",
"str_",
")",
"return",
"ret",
"except",
"Exception",
":",
"# Parse comma separated values as ints",
"if",
"re",
".",
"match",
"(",
"r'\\d*,\\d*,?\\d*'",
",",
"str_",
")",
":",
"... | 29.8 | 13 |
def onDeleteRow(self, event, data_type):
"""
On button click, remove relevant object from both the data model and the grid.
"""
ancestry = self.er_magic_data.ancestry
child_type = ancestry[ancestry.index(data_type) - 1]
names = [self.grid.GetCellValue(row, 0) for row in s... | [
"def",
"onDeleteRow",
"(",
"self",
",",
"event",
",",
"data_type",
")",
":",
"ancestry",
"=",
"self",
".",
"er_magic_data",
".",
"ancestry",
"child_type",
"=",
"ancestry",
"[",
"ancestry",
".",
"index",
"(",
"data_type",
")",
"-",
"1",
"]",
"names",
"=",... | 43.586207 | 26.068966 |
def make_pipeline(context):
"""
Create our pipeline.
"""
# Filter for primary share equities. IsPrimaryShare is a built-in filter.
primary_share = IsPrimaryShare()
# Not when-issued equities.
not_wi = ~IEXCompany.symbol.latest.endswith('.WI')
# Equities without LP in their name, .matc... | [
"def",
"make_pipeline",
"(",
"context",
")",
":",
"# Filter for primary share equities. IsPrimaryShare is a built-in filter.",
"primary_share",
"=",
"IsPrimaryShare",
"(",
")",
"# Not when-issued equities.",
"not_wi",
"=",
"~",
"IEXCompany",
".",
"symbol",
".",
"latest",
".... | 25.961039 | 20.272727 |
def write_files(text, where='.'):
"""Write many files."""
for filename in text:
target = os.path.join(where, filename)
write_file(target, text[filename]) | [
"def",
"write_files",
"(",
"text",
",",
"where",
"=",
"'.'",
")",
":",
"for",
"filename",
"in",
"text",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"where",
",",
"filename",
")",
"write_file",
"(",
"target",
",",
"text",
"[",
"filename",... | 34.6 | 6 |
def _get_description(self, element):
"""
Returns the description of element.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:return: The description of element.
:rtype: str
"""
description = None
if e... | [
"def",
"_get_description",
"(",
"self",
",",
"element",
")",
":",
"description",
"=",
"None",
"if",
"element",
".",
"has_attribute",
"(",
"'title'",
")",
":",
"description",
"=",
"element",
".",
"get_attribute",
"(",
"'title'",
")",
"elif",
"element",
".",
... | 38.824561 | 15.421053 |
def get_page(self, path, return_content=True, return_html=True):
""" Get a Telegraph page
:param path: Path to the Telegraph page (in the format Title-12-31,
i.e. everything that comes after https://telegra.ph/)
:param return_content: If true, content field will be returne... | [
"def",
"get_page",
"(",
"self",
",",
"path",
",",
"return_content",
"=",
"True",
",",
"return_html",
"=",
"True",
")",
":",
"response",
"=",
"self",
".",
"_telegraph",
".",
"method",
"(",
"'getPage'",
",",
"path",
"=",
"path",
",",
"values",
"=",
"{",
... | 36.444444 | 25.944444 |
def stmt2enum(enum_type, declare=True, assign=True, wrap=True):
"""Returns a dzn enum declaration from an enum type.
Parameters
----------
enum_type : Enum
The enum to serialize.
declare : bool
Whether to include the ``enum`` declatation keyword in the statement or
just the ... | [
"def",
"stmt2enum",
"(",
"enum_type",
",",
"declare",
"=",
"True",
",",
"assign",
"=",
"True",
",",
"wrap",
"=",
"True",
")",
":",
"if",
"not",
"(",
"declare",
"or",
"assign",
")",
":",
"raise",
"ValueError",
"(",
"'The statement must be a declaration or an ... | 26.181818 | 21.022727 |
def grant_user_access(self, user, db_names, strict=True):
"""
Gives access to the databases listed in `db_names` to the user.
"""
return self._user_manager.grant_user_access(user, db_names,
strict=strict) | [
"def",
"grant_user_access",
"(",
"self",
",",
"user",
",",
"db_names",
",",
"strict",
"=",
"True",
")",
":",
"return",
"self",
".",
"_user_manager",
".",
"grant_user_access",
"(",
"user",
",",
"db_names",
",",
"strict",
"=",
"strict",
")"
] | 41.166667 | 14.166667 |
def register(linter):
"""Register all transforms with the linter."""
MANAGER.register_transform(astroid.Call, transform_declare)
MANAGER.register_transform(astroid.Module, transform_conf_module) | [
"def",
"register",
"(",
"linter",
")",
":",
"MANAGER",
".",
"register_transform",
"(",
"astroid",
".",
"Call",
",",
"transform_declare",
")",
"MANAGER",
".",
"register_transform",
"(",
"astroid",
".",
"Module",
",",
"transform_conf_module",
")"
] | 49.25 | 16.75 |
def global_iterator_to_indices(self, git=None):
"""
Return sympy expressions translating global_iterator to loop indices.
If global_iterator is given, an integer is returned
"""
# unwind global iteration count into loop counters:
base_loop_counters = {}
global_it... | [
"def",
"global_iterator_to_indices",
"(",
"self",
",",
"git",
"=",
"None",
")",
":",
"# unwind global iteration count into loop counters:",
"base_loop_counters",
"=",
"{",
"}",
"global_iterator",
"=",
"symbol_pos_int",
"(",
"'global_iterator'",
")",
"idiv",
"=",
"implem... | 43.454545 | 22.909091 |
def _subscription_thread(self, endpoint):
"""
Thread Method, running the connection for each endpoint.
:param endpoint:
:return:
"""
try:
conn = create_connection(self.addr + endpoint, timeout=5)
except WebSocketTimeoutException:
self.resta... | [
"def",
"_subscription_thread",
"(",
"self",
",",
"endpoint",
")",
":",
"try",
":",
"conn",
"=",
"create_connection",
"(",
"self",
".",
"addr",
"+",
"endpoint",
",",
"timeout",
"=",
"5",
")",
"except",
"WebSocketTimeoutException",
":",
"self",
".",
"restart_q... | 35.172414 | 17.103448 |
def setApparentDecel(self, typeID, decel):
"""setDecel(string, double) -> None
Sets the apparent deceleration in m/s^2 of vehicles of this type.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_APPARENT_DECEL, typeID, decel) | [
"def",
"setApparentDecel",
"(",
"self",
",",
"typeID",
",",
"decel",
")",
":",
"self",
".",
"_connection",
".",
"_sendDoubleCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLETYPE_VARIABLE",
",",
"tc",
".",
"VAR_APPARENT_DECEL",
",",
"typeID",
",",
"decel",
")"
] | 41.571429 | 16.714286 |
def flatten(text):
"""
Flatten the text:
* make sure each record is on one line.
* remove parenthesis
"""
lines = text.split("\n")
# tokens: sequence of non-whitespace separated by '' where a newline was
tokens = []
for l in lines:
if len(l) == 0:
continue
... | [
"def",
"flatten",
"(",
"text",
")",
":",
"lines",
"=",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
"# tokens: sequence of non-whitespace separated by '' where a newline was",
"tokens",
"=",
"[",
"]",
"for",
"l",
"in",
"lines",
":",
"if",
"len",
"(",
"l",
")",
... | 26.227273 | 19.181818 |
def constraint_from_choices(cls, value_type: type, choices: collections.Sequence):
"""
Returns a constraint callable based on choices of a given type
"""
choices_str = ', '.join(map(str, choices))
def constraint(value):
value = value_type(value)
if value ... | [
"def",
"constraint_from_choices",
"(",
"cls",
",",
"value_type",
":",
"type",
",",
"choices",
":",
"collections",
".",
"Sequence",
")",
":",
"choices_str",
"=",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"choices",
")",
")",
"def",
"constraint",
"... | 38.466667 | 19.4 |
def add_item(self, api_token, content, **kwargs):
"""Add a task to a project.
:param token: The user's login token.
:type token: str
:param content: The task description.
:type content: str
:param project_id: The project to add the task to. Default is ``Inbox``
:... | [
"def",
"add_item",
"(",
"self",
",",
"api_token",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'content'",
":",
"content",
"}",
"return",
"self",
".",
"_post",
"(",
"'add_item'",
",",
"params... | 41.039216 | 15.666667 |
def is_valid_endpoint(endpoint):
"""
Verify if endpoint is valid.
:type endpoint: string
:param endpoint: An endpoint. Must have at least a scheme and a hostname.
:return: True if the endpoint is valid. Raise :exc:`InvalidEndpointError`
otherwise.
"""
try:
if urlsplit(endpoin... | [
"def",
"is_valid_endpoint",
"(",
"endpoint",
")",
":",
"try",
":",
"if",
"urlsplit",
"(",
"endpoint",
")",
".",
"scheme",
":",
"raise",
"InvalidEndpointError",
"(",
"'Hostname cannot have a scheme.'",
")",
"hostname",
"=",
"endpoint",
".",
"split",
"(",
"':'",
... | 30.6 | 22.266667 |
def _clear_audio_file(self, audio_file):
"""
Clear audio from memory.
:param audio_file: the object to clear
:type audio_file: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"clear audio file")
audio_file.clear_data()
audio_file = None
... | [
"def",
"_clear_audio_file",
"(",
"self",
",",
"audio_file",
")",
":",
"self",
".",
"_step_begin",
"(",
"u\"clear audio file\"",
")",
"audio_file",
".",
"clear_data",
"(",
")",
"audio_file",
"=",
"None",
"self",
".",
"_step_end",
"(",
")"
] | 29.818182 | 11.090909 |
def prepare_cache_id(self, combined_args_kw):
"get the cacheid (conc. string of argument self.ids in order)"
cache_id = "".join(self.id(a) for a in combined_args_kw)
return cache_id | [
"def",
"prepare_cache_id",
"(",
"self",
",",
"combined_args_kw",
")",
":",
"cache_id",
"=",
"\"\"",
".",
"join",
"(",
"self",
".",
"id",
"(",
"a",
")",
"for",
"a",
"in",
"combined_args_kw",
")",
"return",
"cache_id"
] | 50.5 | 19 |
def clean(ctx, node=False, translations=False, all=False):
'''Cleanup all build artifacts'''
header('Clean all build artifacts')
patterns = [
'build', 'dist', 'cover', 'docs/_build',
'**/*.pyc', '*.egg-info', '.tox', 'udata/static/*'
]
if node or all:
patterns.append('node_mo... | [
"def",
"clean",
"(",
"ctx",
",",
"node",
"=",
"False",
",",
"translations",
"=",
"False",
",",
"all",
"=",
"False",
")",
":",
"header",
"(",
"'Clean all build artifacts'",
")",
"patterns",
"=",
"[",
"'build'",
",",
"'dist'",
",",
"'cover'",
",",
"'docs/_... | 36.571429 | 15 |
def _set_redistribute(self, v, load=False):
"""
Setter method for redistribute, mapped from YANG variable /rbridge_id/router/ospf/permit/redistribute (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_redistribute is considered as a private
method. Backends looki... | [
"def",
"_set_redistribute",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 109.954545 | 52.818182 |
def rmpart(self, disk, number):
"""
Remove partion from disk
:param disk: device path (/dev/sda, /dev/sdb, etc...)
:param number: Partition number (starting from 1)
"""
args = {
'disk': disk,
'number': number,
}
self._rmpart_chk.ch... | [
"def",
"rmpart",
"(",
"self",
",",
"disk",
",",
"number",
")",
":",
"args",
"=",
"{",
"'disk'",
":",
"disk",
",",
"'number'",
":",
"number",
",",
"}",
"self",
".",
"_rmpart_chk",
".",
"check",
"(",
"args",
")",
"response",
"=",
"self",
".",
"_clien... | 27.473684 | 19.368421 |
def label_correcting_check_cycle(self, j, pred):
'''
API:
label_correcting_check_cycle(self, j, pred)
Description:
Checks if predecessor dictionary has a cycle, j represents the node
that predecessor is recently updated.
Pre:
(1) predecesso... | [
"def",
"label_correcting_check_cycle",
"(",
"self",
",",
"j",
",",
"pred",
")",
":",
"labelled",
"=",
"{",
"}",
"for",
"n",
"in",
"self",
".",
"neighbors",
":",
"labelled",
"[",
"n",
"]",
"=",
"None",
"current",
"=",
"j",
"while",
"current",
"!=",
"N... | 35.148148 | 17.518519 |
def create_delete_model(record):
"""Create an S3 model from a record."""
arn = f"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}"
LOG.debug(f'[-] Deleting Dynamodb Records. Hash Key: {arn}')
data = {
'arn': arn,
'principalId': cloudwatch.get_principal(record),
... | [
"def",
"create_delete_model",
"(",
"record",
")",
":",
"arn",
"=",
"f\"arn:aws:s3:::{cloudwatch.filter_request_parameters('bucketName', record)}\"",
"LOG",
".",
"debug",
"(",
"f'[-] Deleting Dynamodb Records. Hash Key: {arn}'",
")",
"data",
"=",
"{",
"'arn'",
":",
"arn",
",... | 37.9 | 20.45 |
def _rewrite_guides(self):
"""
Write ``<a:gd>`` elements to the XML, one for each adjustment value.
Any existing guide elements are overwritten.
"""
guides = [(adj.name, adj.val) for adj in self._adjustments_]
self._prstGeom.rewrite_guides(guides) | [
"def",
"_rewrite_guides",
"(",
"self",
")",
":",
"guides",
"=",
"[",
"(",
"adj",
".",
"name",
",",
"adj",
".",
"val",
")",
"for",
"adj",
"in",
"self",
".",
"_adjustments_",
"]",
"self",
".",
"_prstGeom",
".",
"rewrite_guides",
"(",
"guides",
")"
] | 41.285714 | 13.571429 |
def pdf_merge(inputs: [str], output: str, delete: bool = False):
"""
Merge multiple Pdf input files in one output file.
:param inputs: input files
:param output: output file
:param delete: delete input files after completion if true
"""
writer = PdfFileWriter()
if os.path.isfile(output)... | [
"def",
"pdf_merge",
"(",
"inputs",
":",
"[",
"str",
"]",
",",
"output",
":",
"str",
",",
"delete",
":",
"bool",
"=",
"False",
")",
":",
"writer",
"=",
"PdfFileWriter",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"output",
")",
":",
"an... | 28.444444 | 14.166667 |
def marginal_loglike(self, x):
"""Marginal log-likelihood.
Returns ``L_marg(x) = \int L(x,y|z') L(y) dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed.
"""
if self._marg_interp is None:
# This calcu... | [
"def",
"marginal_loglike",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"_marg_interp",
"is",
"None",
":",
"# This calculates values and caches the spline",
"return",
"self",
".",
"_marginal_loglike",
"(",
"x",
")",
"x",
"=",
"np",
".",
"array",
"(",
... | 32.571429 | 15.857143 |
def shutdown_server(self):
"""
Cleanly shutdown the server.
"""
if not self._closing:
self._closing = True
else:
log.warning("Close is already in progress")
return
if self._server:
self._server.close()
yield fr... | [
"def",
"shutdown_server",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_closing",
":",
"self",
".",
"_closing",
"=",
"True",
"else",
":",
"log",
".",
"warning",
"(",
"\"Close is already in progress\"",
")",
"return",
"if",
"self",
".",
"_server",
":",... | 31.234043 | 19.489362 |
def ops(self, start=None, stop=None, **kwargs):
""" Yields all operations (excluding virtual operations) starting from
``start``.
:param int start: Starting block
:param int stop: Stop at this block
:param str mode: We here have the choice between
"h... | [
"def",
"ops",
"(",
"self",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"block",
"in",
"self",
".",
"blocks",
"(",
"start",
"=",
"start",
",",
"stop",
"=",
"stop",
",",
"*",
"*",
"kwargs",
")",
... | 43.44 | 18.76 |
def get_rendered_fields(self, ctx=None):
'''
:param ctx: rendering context in which the method was called
:return: ordered list of the fields that will be rendered
'''
res = []
if ctx is None:
ctx = RenderContext()
if self._evaluate_condition(ctx):
... | [
"def",
"get_rendered_fields",
"(",
"self",
",",
"ctx",
"=",
"None",
")",
":",
"res",
"=",
"[",
"]",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"RenderContext",
"(",
")",
"if",
"self",
".",
"_evaluate_condition",
"(",
"ctx",
")",
":",
"ctx",
".",
"... | 33.846154 | 18.615385 |
def insert(self, x1, x2, name = '', referedObject = []) :
"""Insert the segment in it's right place and returns it.
If there's already a segment S as S.x1 == x1 and S.x2 == x2. S.name will be changed to 'S.name U name' and the
referedObject will be appended to the already existing list"""
if x1 > x2 :
xx... | [
"def",
"insert",
"(",
"self",
",",
"x1",
",",
"x2",
",",
"name",
"=",
"''",
",",
"referedObject",
"=",
"[",
"]",
")",
":",
"if",
"x1",
">",
"x2",
":",
"xx1",
",",
"xx2",
"=",
"x2",
",",
"x1",
"else",
":",
"xx1",
",",
"xx2",
"=",
"x1",
",",
... | 31.6 | 23.927273 |
def find_by_campaign(campaign_id, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos for a given campaign.
"""
return connection.ItemResultSet(
'find_videos_by_campaign_id', ... | [
"def",
"find_by_campaign",
"(",
"campaign_id",
",",
"_connection",
"=",
"None",
",",
"page_size",
"=",
"100",
",",
"page_number",
"=",
"0",
",",
"sort_by",
"=",
"enums",
".",
"DEFAULT_SORT_BY",
",",
"sort_order",
"=",
"enums",
".",
"DEFAULT_SORT_ORDER",
")",
... | 45.888889 | 12.333333 |
def constant(self, name, value):
"""Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestrin... | [
"def",
"constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"self",
".",
"registry",
".",
"current",
"(",
")",... | 53.857143 | 10.428571 |
def subscribe_strategy(
self,
strategy_id: str,
last: int,
today=datetime.date.today(),
cost_coins=10
):
"""订阅一个策略
会扣减你的积分
Arguments:
strategy_id {str} -- [description]
last {int} -- [description]
... | [
"def",
"subscribe_strategy",
"(",
"self",
",",
"strategy_id",
":",
"str",
",",
"last",
":",
"int",
",",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
",",
"cost_coins",
"=",
"10",
")",
":",
"if",
"self",
".",
"coins",
">",
"cost_coin... | 27.2 | 15.818182 |
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64():
"""big 1d model for unconditional generation on imagenet."""
hparams = imagetransformer_base_10l_8h_big_cond_dr03_dan()
hparams.unconditional = True
hparams.max_length = 14000
hparams.batch_size = 1
hparams.img_len = 64
hparams.layer_prepostproces... | [
"def",
"imagetransformer_base_10l_8h_big_uncond_dr03_dan_64",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_base_10l_8h_big_cond_dr03_dan",
"(",
")",
"hparams",
".",
"unconditional",
"=",
"True",
"hparams",
".",
"max_length",
"=",
"14000",
"hparams",
".",
"batch_size",... | 38.222222 | 13.555556 |
def check_sas_base_dir(root=None):
''' Check for the SAS_BASE_DIR environment variable
Will set the SAS_BASE_DIR in your local environment
or prompt you to define one if is undefined
Parameters:
root (str):
Optional override of the SAS_BASE_DIR envvar
'''
sasbasedir = root... | [
"def",
"check_sas_base_dir",
"(",
"root",
"=",
"None",
")",
":",
"sasbasedir",
"=",
"root",
"or",
"os",
".",
"getenv",
"(",
"\"SAS_BASE_DIR\"",
")",
"if",
"not",
"sasbasedir",
":",
"sasbasedir",
"=",
"input",
"(",
"'Enter a path for SAS_BASE_DIR: '",
")",
"os"... | 30.933333 | 20.666667 |
def GET_savedmodifiedconditionitemvalues(self) -> None:
"""ToDo: extend functionality and add tests"""
dict_ = state.modifiedconditionitemvalues.get(self._id)
if dict_ is None:
self.GET_conditionitemvalues()
else:
for name, value in dict_.items():
... | [
"def",
"GET_savedmodifiedconditionitemvalues",
"(",
"self",
")",
"->",
"None",
":",
"dict_",
"=",
"state",
".",
"modifiedconditionitemvalues",
".",
"get",
"(",
"self",
".",
"_id",
")",
"if",
"dict_",
"is",
"None",
":",
"self",
".",
"GET_conditionitemvalues",
"... | 42.5 | 11.25 |
def contact_page(view, **kwargs):
"""
:param view: The view to copy to
:param kwargs:
- fa_icon
- menu: The name of the menu
- show_menu: bool - show/hide menu
- menu_order: int - position of the menu
- return_to
- email_to
:return:
"""
endpoint_na... | [
"def",
"contact_page",
"(",
"view",
",",
"*",
"*",
"kwargs",
")",
":",
"endpoint_namespace",
"=",
"view",
".",
"__name__",
"+",
"\":%s\"",
"endpoint",
"=",
"endpoint_namespace",
"%",
"\"ContactPage\"",
"template_dir",
"=",
"kwargs",
".",
"pop",
"(",
"\"templat... | 34.941176 | 17.929412 |
def connect(self):
"""Create connection to CasparCG Server"""
try:
self.connection = telnetlib.Telnet(self.host, self.port, timeout=self.timeout)
except Exception:
log_traceback()
return False
return True | [
"def",
"connect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"connection",
"=",
"telnetlib",
".",
"Telnet",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"except",
"Exception",
":",
"log_tr... | 33.125 | 20.625 |
def import_variables(self, container, varnames=None):
"""Helper method to avoid call get_variable for every variable."""
if varnames is None:
for keyword in self.tkvariables:
setattr(container, keyword, self.tkvariables[keyword])
else:
for keyword in varna... | [
"def",
"import_variables",
"(",
"self",
",",
"container",
",",
"varnames",
"=",
"None",
")",
":",
"if",
"varnames",
"is",
"None",
":",
"for",
"keyword",
"in",
"self",
".",
"tkvariables",
":",
"setattr",
"(",
"container",
",",
"keyword",
",",
"self",
".",... | 48.777778 | 14.555556 |
def set_zone_order(self, zone_ids):
""" reorder zones per the passed in list
:param zone_ids:
:return:
"""
reordered_zones = []
current_zone_ids = [z['id'] for z in self.my_osid_object_form._my_map['zones']]
if set(zone_ids) != set(current_zone_ids):
r... | [
"def",
"set_zone_order",
"(",
"self",
",",
"zone_ids",
")",
":",
"reordered_zones",
"=",
"[",
"]",
"current_zone_ids",
"=",
"[",
"z",
"[",
"'id'",
"]",
"for",
"z",
"in",
"self",
".",
"my_osid_object_form",
".",
"_my_map",
"[",
"'zones'",
"]",
"]",
"if",
... | 39.529412 | 19.588235 |
def scroll_deck(self, decknum, scroll_x, scroll_y):
"""Move a deck."""
self.scroll_deck_x(decknum, scroll_x)
self.scroll_deck_y(decknum, scroll_y) | [
"def",
"scroll_deck",
"(",
"self",
",",
"decknum",
",",
"scroll_x",
",",
"scroll_y",
")",
":",
"self",
".",
"scroll_deck_x",
"(",
"decknum",
",",
"scroll_x",
")",
"self",
".",
"scroll_deck_y",
"(",
"decknum",
",",
"scroll_y",
")"
] | 41.75 | 5.25 |
def _create_sagemaker_model(self, *args): # pylint: disable=unused-argument
"""Create a SageMaker Model Entity
Args:
*args: Arguments coming from the caller. This class
does not require any so they are ignored.
"""
if self.algorithm_arn:
# When M... | [
"def",
"_create_sagemaker_model",
"(",
"self",
",",
"*",
"args",
")",
":",
"# pylint: disable=unused-argument",
"if",
"self",
".",
"algorithm_arn",
":",
"# When ModelPackage is created using an algorithm_arn we need to first",
"# create a ModelPackage. If we had already created one t... | 49.21875 | 27.8125 |
def switch_to_aux_top_layer(self):
"""Context that construct cnn in the auxiliary arm."""
if self.aux_top_layer is None:
raise RuntimeError("Empty auxiliary top layer in the network.")
saved_top_layer = self.top_layer
saved_top_size = self.top_size
self.top_layer = se... | [
"def",
"switch_to_aux_top_layer",
"(",
"self",
")",
":",
"if",
"self",
".",
"aux_top_layer",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Empty auxiliary top layer in the network.\"",
")",
"saved_top_layer",
"=",
"self",
".",
"top_layer",
"saved_top_size",
"=",... | 42 | 6.307692 |
def _calculate_hour_and_minute(float_hour):
"""Calculate hour and minutes as integers from a float hour."""
hour, minute = int(float_hour), int(round((float_hour - int(float_hour)) * 60))
if minute == 60:
return hour + 1, 0
else:
return hour, minute | [
"def",
"_calculate_hour_and_minute",
"(",
"float_hour",
")",
":",
"hour",
",",
"minute",
"=",
"int",
"(",
"float_hour",
")",
",",
"int",
"(",
"round",
"(",
"(",
"float_hour",
"-",
"int",
"(",
"float_hour",
")",
")",
"*",
"60",
")",
")",
"if",
"minute",... | 42.714286 | 16 |
def get_plugin_data(self, plugin):
"""Get the data object of the plugin's current tab manager."""
# The data object is named "data" in the editor plugin while it is
# named "clients" in the notebook plugin.
try:
data = plugin.get_current_tab_manager().data
except Attr... | [
"def",
"get_plugin_data",
"(",
"self",
",",
"plugin",
")",
":",
"# The data object is named \"data\" in the editor plugin while it is",
"# named \"clients\" in the notebook plugin.",
"try",
":",
"data",
"=",
"plugin",
".",
"get_current_tab_manager",
"(",
")",
".",
"data",
"... | 40.3 | 18.3 |
def load_sample(sample):
""" Load meter data, temperature data, and metadata for associated with a
particular sample identifier. Note: samples are simulated, not real, data.
Parameters
----------
sample : :any:`str`
Identifier of sample. Complete list can be obtained with
:any:`eeme... | [
"def",
"load_sample",
"(",
"sample",
")",
":",
"sample_metadata",
"=",
"_load_sample_metadata",
"(",
")",
"metadata",
"=",
"sample_metadata",
".",
"get",
"(",
"sample",
")",
"if",
"metadata",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Sample not found: {}... | 36.06383 | 24.702128 |
def postproc_mask (stats_result):
"""Simple helper to postprocess angular outputs from StatsCollectors in the
way we want.
"""
n, mean, scat = stats_result
ok = np.isfinite (mean)
n = n[ok]
mean = mean[ok]
scat = scat[ok]
mean *= 180 / np.pi # rad => deg
scat /= n # variance-o... | [
"def",
"postproc_mask",
"(",
"stats_result",
")",
":",
"n",
",",
"mean",
",",
"scat",
"=",
"stats_result",
"ok",
"=",
"np",
".",
"isfinite",
"(",
"mean",
")",
"n",
"=",
"n",
"[",
"ok",
"]",
"mean",
"=",
"mean",
"[",
"ok",
"]",
"scat",
"=",
"scat"... | 25.529412 | 16.588235 |
def buscar(self):
"""Faz a busca das informações do objeto no Postmon.
Retorna um ``bool`` indicando se a busca foi bem sucedida.
"""
headers = {'User-Agent': self.user_agent}
try:
self._response = requests.get(self.url, headers=headers)
except requests.Reque... | [
"def",
"buscar",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'User-Agent'",
":",
"self",
".",
"user_agent",
"}",
"try",
":",
"self",
".",
"_response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
",",
"headers",
"=",
"headers",
")",
"except... | 36.5 | 17.8125 |
def remove_declaration(self, decl):
"""
Removes declaration from members list.
:param decl: declaration to be removed
:type decl: :class:`declaration_t`
"""
del self.declarations[self.declarations.index(decl)]
decl.cache.reset() | [
"def",
"remove_declaration",
"(",
"self",
",",
"decl",
")",
":",
"del",
"self",
".",
"declarations",
"[",
"self",
".",
"declarations",
".",
"index",
"(",
"decl",
")",
"]",
"decl",
".",
"cache",
".",
"reset",
"(",
")"
] | 25.181818 | 15.727273 |
def tag_image(self, repository=None, tag=None):
"""
Apply additional tags to the image or even add a new name
:param repository: str, see constructor
:param tag: str, see constructor
:return: instance of DockerImage
"""
if not (repository or tag):
rai... | [
"def",
"tag_image",
"(",
"self",
",",
"repository",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"not",
"(",
"repository",
"or",
"tag",
")",
":",
"raise",
"ValueError",
"(",
"\"You need to specify either repository or tag.\"",
")",
"r",
"=",
"reposi... | 39.357143 | 11.214286 |
def calculate_order_parameter(self, start_iteration = None, stop_iteration = None):
"""!
@brief Calculates level of global synchorization (order parameter).
@details This parameter is tend 1.0 when the oscillatory network close to global synchronization and it tend to 0.0 when
... | [
"def",
"calculate_order_parameter",
"(",
"self",
",",
"start_iteration",
"=",
"None",
",",
"stop_iteration",
"=",
"None",
")",
":",
"(",
"start_iteration",
",",
"stop_iteration",
")",
"=",
"self",
".",
"__get_start_stop_iterations",
"(",
"start_iteration",
",",
"s... | 55 | 40.146341 |
def get_override_votes(self, obj):
"""
Votes entered into backend.
Only used if ``override_ap_votes = True``.
"""
if hasattr(obj, "meta"): # TODO: REVISIT THIS
if obj.meta.override_ap_votes:
all_votes = None
for ce in obj.candidate_ele... | [
"def",
"get_override_votes",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"\"meta\"",
")",
":",
"# TODO: REVISIT THIS",
"if",
"obj",
".",
"meta",
".",
"override_ap_votes",
":",
"all_votes",
"=",
"None",
"for",
"ce",
"in",
"obj",
"... | 38.666667 | 10.666667 |
def send_command(self, command, arg=None):
"""Sends a command to the device.
Args:
command: The command to send.
arg: Optional argument to the command.
"""
if arg is not None:
command = '%s:%s' % (command, arg)
self._write(six.StringIO(command), len(command)) | [
"def",
"send_command",
"(",
"self",
",",
"command",
",",
"arg",
"=",
"None",
")",
":",
"if",
"arg",
"is",
"not",
"None",
":",
"command",
"=",
"'%s:%s'",
"%",
"(",
"command",
",",
"arg",
")",
"self",
".",
"_write",
"(",
"six",
".",
"StringIO",
"(",
... | 28.9 | 11.1 |
def get_attributes(self, request_envelope):
# type: (RequestEnvelope) -> Dict[str, object]
"""Get attributes from table in Dynamodb resource.
Retrieves the attributes from Dynamodb table. If the table
doesn't exist, returns an empty dict if the
``create_table`` variable is set a... | [
"def",
"get_attributes",
"(",
"self",
",",
"request_envelope",
")",
":",
"# type: (RequestEnvelope) -> Dict[str, object]",
"try",
":",
"table",
"=",
"self",
".",
"dynamodb",
".",
"Table",
"(",
"self",
".",
"table_name",
")",
"partition_key_val",
"=",
"self",
".",
... | 45.315789 | 17.5 |
async def resolution_at_vote(self, root):
"""The proposal currently being voted on.
Returns
-------
:class:`ApiQuery` of :class:`ResolutionAtVote`
:class:`ApiQuery` of None
If no resolution is currently at vote.
"""
elem = root.find('RESOLUTION')
... | [
"async",
"def",
"resolution_at_vote",
"(",
"self",
",",
"root",
")",
":",
"elem",
"=",
"root",
".",
"find",
"(",
"'RESOLUTION'",
")",
"if",
"elem",
":",
"resolution",
"=",
"ResolutionAtVote",
"(",
"elem",
")",
"resolution",
".",
"_council_id",
"=",
"self",... | 32.214286 | 12.785714 |
def build_case(case_data, adapter):
"""Build a case object that is to be inserted to the database
Args:
case_data (dict): A dictionary with the relevant case information
adapter (scout.adapter.MongoAdapter)
Returns:
case_obj (dict): A case object
dict(
case_id = str, #... | [
"def",
"build_case",
"(",
"case_data",
",",
"adapter",
")",
":",
"log",
".",
"info",
"(",
"\"build case with id: {0}\"",
".",
"format",
"(",
"case_data",
"[",
"'case_id'",
"]",
")",
")",
"case_obj",
"=",
"{",
"'_id'",
":",
"case_data",
"[",
"'case_id'",
"]... | 33.946341 | 20.912195 |
def _entry_management(self): # pylint: disable=too-many-branches
"""
Avoid to have 1 millions line into self.__init__()
"""
if not self.modulo_test: # pylint: disable=no-member
# We are not in a module usage.
# We set the file_path as the file we have to test.... | [
"def",
"_entry_management",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"self",
".",
"modulo_test",
":",
"# pylint: disable=no-member",
"# We are not in a module usage.",
"# We set the file_path as the file we have to test.",
"PyFunceble",
".",
"INT... | 40.070707 | 22.424242 |
def _parse_image_name(self, image, retry=True):
'''starting with an image string in either of the following formats:
job_id|collection
job_id|collection|job_name
Parse the job_name, job_id, and collection uri from it. If the user
provides the first option, we use th... | [
"def",
"_parse_image_name",
"(",
"self",
",",
"image",
",",
"retry",
"=",
"True",
")",
":",
"try",
":",
"job_id",
",",
"collection",
",",
"job_name",
"=",
"image",
".",
"split",
"(",
"','",
")",
"except",
":",
"# Retry and add job_name",
"if",
"retry",
"... | 39.068966 | 22.862069 |
def _utf8_params(params):
"""encode a dictionary of URL parameters (including iterables) as utf-8"""
assert isinstance(params, dict)
encoded_params = []
for k, v in params.items():
if v is None:
continue
if isinstance(v, integer_types + (float,)):
v = str(v)
... | [
"def",
"_utf8_params",
"(",
"params",
")",
":",
"assert",
"isinstance",
"(",
"params",
",",
"dict",
")",
"encoded_params",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"None",
":",
"continue",
"... | 32.933333 | 11.066667 |
def has_active_condition(self, condition, instances):
"""
Given a list of instances, and the condition active for
this switch, returns a boolean representing if the
conditional is met, including a non-instance default.
"""
return_value = None
for instance in insta... | [
"def",
"has_active_condition",
"(",
"self",
",",
"condition",
",",
"instances",
")",
":",
"return_value",
"=",
"None",
"for",
"instance",
"in",
"instances",
"+",
"[",
"None",
"]",
":",
"if",
"not",
"self",
".",
"can_execute",
"(",
"instance",
")",
":",
"... | 37.875 | 11 |
def divide(a, b):
'''
divide(a, b) returns the quotient a / b as a numpy array object. Unlike numpy's divide function
or a/b syntax, divide will thread over the earliest dimension possible; thus if a.shape is
(4,2) and b.shape is 4, divide(a,b) is a equivalent to [ai/bi for (ai,bi) in zip(a,b)].
... | [
"def",
"divide",
"(",
"a",
",",
"b",
")",
":",
"(",
"a",
",",
"b",
")",
"=",
"unbroadcast",
"(",
"a",
",",
"b",
")",
"return",
"cdivide",
"(",
"a",
",",
"b",
")"
] | 54.333333 | 40.666667 |
def predict(self, choosers, alternatives, debug=False):
"""
Choose from among alternatives for a group of agents.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
alternatives : pandas.DataFrame
... | [
"def",
"predict",
"(",
"self",
",",
"choosers",
",",
"alternatives",
",",
"debug",
"=",
"False",
")",
":",
"self",
".",
"assert_fitted",
"(",
")",
"logger",
".",
"debug",
"(",
"'start: predict LCM model {}'",
".",
"format",
"(",
"self",
".",
"name",
")",
... | 35.508475 | 20.389831 |
def list_networks(**kwargs):
'''
List all virtual networks.
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults
.. versionadded:: 2019.2.0
CLI Example:
... | [
"def",
"list_networks",
"(",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"return",
"[",
"net",
".",
"name",
"(",
")",
"for",
"net",
"in",
"conn",
".",
"listAllNetworks",
"(",
")",
"]",
"finally... | 24.095238 | 25.333333 |
def reassign_arguments(self):
"""Deal with optional stringlist before a required one."""
condition = (
"variable-list" in self.arguments and
"list-of-flags" not in self.arguments
)
if condition:
self.arguments["list-of-flags"] = (
self.... | [
"def",
"reassign_arguments",
"(",
"self",
")",
":",
"condition",
"=",
"(",
"\"variable-list\"",
"in",
"self",
".",
"arguments",
"and",
"\"list-of-flags\"",
"not",
"in",
"self",
".",
"arguments",
")",
"if",
"condition",
":",
"self",
".",
"arguments",
"[",
"\"... | 37.3 | 12.7 |
def conference_deaf(self, call_params):
"""REST Conference Deaf helper
"""
path = '/' + self.api_version + '/ConferenceDeaf/'
method = 'POST'
return self.request(path, method, call_params) | [
"def",
"conference_deaf",
"(",
"self",
",",
"call_params",
")",
":",
"path",
"=",
"'/'",
"+",
"self",
".",
"api_version",
"+",
"'/ConferenceDeaf/'",
"method",
"=",
"'POST'",
"return",
"self",
".",
"request",
"(",
"path",
",",
"method",
",",
"call_params",
... | 37.166667 | 8.333333 |
def color_to_hex(color):
"""Convert matplotlib color code to hex color code"""
if color is None or colorConverter.to_rgba(color)[3] == 0:
return 'none'
else:
rgb = colorConverter.to_rgb(color)
return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb)) | [
"def",
"color_to_hex",
"(",
"color",
")",
":",
"if",
"color",
"is",
"None",
"or",
"colorConverter",
".",
"to_rgba",
"(",
"color",
")",
"[",
"3",
"]",
"==",
"0",
":",
"return",
"'none'",
"else",
":",
"rgb",
"=",
"colorConverter",
".",
"to_rgb",
"(",
"... | 41.571429 | 18 |
def huffman_conv2bitstring(cls, s):
# type: (str) -> Tuple[int, int]
""" huffman_conv2bitstring converts a string into its bitstring
representation. It returns a tuple: the bitstring and its bitlength.
This function DOES NOT compress/decompress the string!
@param str s: the byte... | [
"def",
"huffman_conv2bitstring",
"(",
"cls",
",",
"s",
")",
":",
"# type: (str) -> Tuple[int, int]",
"i",
"=",
"0",
"ibl",
"=",
"len",
"(",
"s",
")",
"*",
"8",
"for",
"c",
"in",
"s",
":",
"i",
"=",
"(",
"i",
"<<",
"8",
")",
"+",
"orb",
"(",
"c",
... | 32.578947 | 17.210526 |
def pickFilepath( self ):
"""
Picks the image file to use for this icon path.
"""
filepath = QFileDialog.getOpenFileName( self,
'Select Image File',
QDir.currentPath(),
... | [
"def",
"pickFilepath",
"(",
"self",
")",
":",
"filepath",
"=",
"QFileDialog",
".",
"getOpenFileName",
"(",
"self",
",",
"'Select Image File'",
",",
"QDir",
".",
"currentPath",
"(",
")",
",",
"self",
".",
"fileTypes",
"(",
")",
")",
"if",
"type",
"(",
"fi... | 37.071429 | 15.5 |
def accel_rename_current_tab(self, *args):
"""Callback to show the rename tab dialog. Called by the accel
key.
"""
page_num = self.get_notebook().get_current_page()
page = self.get_notebook().get_nth_page(page_num)
self.get_notebook().get_tab_label(page).on_rename(None)
... | [
"def",
"accel_rename_current_tab",
"(",
"self",
",",
"*",
"args",
")",
":",
"page_num",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"page",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_nth_page",
"(",
"page_num",... | 41.375 | 13.5 |
def k_bn(self, n, Re):
"""
returns normalisation of the sersic profile such that Re is the half light radius given n_sersic slope
"""
bn = self.b_n(n)
k = bn*Re**(-1./n)
return k, bn | [
"def",
"k_bn",
"(",
"self",
",",
"n",
",",
"Re",
")",
":",
"bn",
"=",
"self",
".",
"b_n",
"(",
"n",
")",
"k",
"=",
"bn",
"*",
"Re",
"**",
"(",
"-",
"1.",
"/",
"n",
")",
"return",
"k",
",",
"bn"
] | 32 | 19.714286 |
def altimeter(alt: Number, unit: str = 'inHg') -> str:
"""
Format altimeter details into a spoken word string
"""
ret = 'Altimeter '
if not alt:
ret += 'unknown'
elif unit == 'inHg':
ret += core.spoken_number(alt.repr[:2]) + ' point ' + core.spoken_number(alt.repr[2:])
elif u... | [
"def",
"altimeter",
"(",
"alt",
":",
"Number",
",",
"unit",
":",
"str",
"=",
"'inHg'",
")",
"->",
"str",
":",
"ret",
"=",
"'Altimeter '",
"if",
"not",
"alt",
":",
"ret",
"+=",
"'unknown'",
"elif",
"unit",
"==",
"'inHg'",
":",
"ret",
"+=",
"core",
"... | 31.75 | 16.916667 |
def cmd_cm(self, nm=None, ch=None):
"""cm nm=color_map_name ch=chname
Set a color map (name `nm`) for the given channel.
If no value is given, reports the current color map.
"""
viewer = self.get_viewer(ch)
if viewer is None:
self.log("No current viewer/chann... | [
"def",
"cmd_cm",
"(",
"self",
",",
"nm",
"=",
"None",
",",
"ch",
"=",
"None",
")",
":",
"viewer",
"=",
"self",
".",
"get_viewer",
"(",
"ch",
")",
"if",
"viewer",
"is",
"None",
":",
"self",
".",
"log",
"(",
"\"No current viewer/channel.\"",
")",
"retu... | 28.5 | 15.277778 |
def deleteMetadata(self, remote, address, key):
"""Delete metadata of device"""
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key)
except Exception as err:
LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err)) | [
"def",
"deleteMetadata",
"(",
"self",
",",
"remote",
",",
"address",
",",
"key",
")",
":",
"try",
":",
"return",
"self",
".",
"proxies",
"[",
"\"%s-%s\"",
"%",
"(",
"self",
".",
"_interface_id",
",",
"remote",
")",
"]",
".",
"deleteMetadata",
"(",
"add... | 51.333333 | 23.5 |
def has_change_permission(self):
"""
Returns a boolean if the current user has permission to change the current object being
viewed/edited.
"""
has_permission = False
if self.user is not None:
# We check for the object level permission here, even though by de... | [
"def",
"has_change_permission",
"(",
"self",
")",
":",
"has_permission",
"=",
"False",
"if",
"self",
".",
"user",
"is",
"not",
"None",
":",
"# We check for the object level permission here, even though by default the Django",
"# admin doesn't. If the Django ModelAdmin is extended... | 42.222222 | 24.444444 |
def cross_entropy_loss(logits, one_hot_labels, label_smoothing=0,
weight=1.0, scope=None):
"""Define a Cross Entropy loss using softmax_cross_entropy_with_logits.
It can scale the loss by weight factor, and smooth the labels.
Args:
logits: [batch_size, num_classes] logits outputs of t... | [
"def",
"cross_entropy_loss",
"(",
"logits",
",",
"one_hot_labels",
",",
"label_smoothing",
"=",
"0",
",",
"weight",
"=",
"1.0",
",",
"scope",
"=",
"None",
")",
":",
"logits",
".",
"get_shape",
"(",
")",
".",
"assert_is_compatible_with",
"(",
"one_hot_labels",
... | 45.575758 | 21.454545 |
def get_dev_interface(devid, auth, url):
"""
Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces
:param devid: requires devid as the only input
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base u... | [
"def",
"get_dev_interface",
"(",
"devid",
",",
"auth",
",",
"url",
")",
":",
"get_dev_interface_url",
"=",
"\"/imcrs/plat/res/device/\"",
"+",
"str",
"(",
"devid",
")",
"+",
"\"/interface?start=0&size=1000&desc=false&total=false\"",
"f_url",
"=",
"url",
"+",
"get_dev_... | 33.317073 | 27.341463 |
def init_app(self, app):
"""
Initializes the extension for the provided Flask application.
Args:
app (flask.Flask). the Flask application for which to initialize the extension.
"""
self._key = app.config.get(CONF_KEY) or getenv(CONF_KEY)
if not self._key:
... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"_key",
"=",
"app",
".",
"config",
".",
"get",
"(",
"CONF_KEY",
")",
"or",
"getenv",
"(",
"CONF_KEY",
")",
"if",
"not",
"self",
".",
"_key",
":",
"return",
"self",
".",
"_endpoint_u... | 31.142857 | 20.952381 |
def stopPolitely(self, disconnect=False):
"""Delete all active ROSpecs. Return a Deferred that will be called
when the DELETE_ROSPEC_RESPONSE comes back."""
logger.info('stopping politely')
if disconnect:
logger.info('will disconnect when stopped')
self.discon... | [
"def",
"stopPolitely",
"(",
"self",
",",
"disconnect",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"'stopping politely'",
")",
"if",
"disconnect",
":",
"logger",
".",
"info",
"(",
"'will disconnect when stopped'",
")",
"self",
".",
"disconnecting",
"="... | 36.454545 | 14.590909 |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data["properties"]
raw_content = properties.get("accessControlList", None)
if raw_content is not None:
resource = Resource.from_raw_data(raw_content)
properties... | [
"def",
"process_raw_data",
"(",
"cls",
",",
"raw_data",
")",
":",
"properties",
"=",
"raw_data",
"[",
"\"properties\"",
"]",
"raw_content",
"=",
"properties",
".",
"get",
"(",
"\"accessControlList\"",
",",
"None",
")",
"if",
"raw_content",
"is",
"not",
"None",... | 42.153846 | 19.153846 |
def from_configuration(cls, env_name, config_name='default'):
""" Environment factory from name and configuration strings.
:param str env_name: the name string of the environment
:param str config_name: the configuration string for env_name
Environment name strings are available using... | [
"def",
"from_configuration",
"(",
"cls",
",",
"env_name",
",",
"config_name",
"=",
"'default'",
")",
":",
"env_cls",
",",
"env_configs",
",",
"_",
"=",
"environments",
"[",
"env_name",
"]",
"return",
"env_cls",
"(",
"*",
"*",
"env_configs",
"[",
"config_name... | 40.611111 | 32.305556 |
def validate(
schema: GraphQLSchema,
document_ast: DocumentNode,
rules: Sequence[RuleType] = None,
type_info: TypeInfo = None,
) -> List[GraphQLError]:
"""Implements the "Validation" section of the spec.
Validation runs synchronously, returning a list of encountered errors, or an empty
list... | [
"def",
"validate",
"(",
"schema",
":",
"GraphQLSchema",
",",
"document_ast",
":",
"DocumentNode",
",",
"rules",
":",
"Sequence",
"[",
"RuleType",
"]",
"=",
"None",
",",
"type_info",
":",
"TypeInfo",
"=",
"None",
",",
")",
"->",
"List",
"[",
"GraphQLError",... | 47 | 23.05 |
def init_multipart_upload(self, bucket, object_name, content_type=None,
amz_headers={}, metadata={}):
"""
Initiate a multipart upload to a bucket.
@param bucket: The name of the bucket
@param object_name: The object name
@param content_type: The Con... | [
"def",
"init_multipart_upload",
"(",
"self",
",",
"bucket",
",",
"object_name",
",",
"content_type",
"=",
"None",
",",
"amz_headers",
"=",
"{",
"}",
",",
"metadata",
"=",
"{",
"}",
")",
":",
"objectname_plus",
"=",
"'%s?uploads'",
"%",
"object_name",
"detail... | 40.6 | 17.8 |
def kwargs(self):
"""combine GET and POST params to be passed to the controller"""
kwargs = dict(self.query_kwargs)
kwargs.update(self.body_kwargs)
return kwargs | [
"def",
"kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"dict",
"(",
"self",
".",
"query_kwargs",
")",
"kwargs",
".",
"update",
"(",
"self",
".",
"body_kwargs",
")",
"return",
"kwargs"
] | 31.5 | 13.833333 |
def generic_meta_translator(self, meta_to_translate):
'''Translates the metadate contained in an object into a dictionary
suitable for export.
Parameters
----------
meta_to_translate : Meta
The metadata object to translate
Returns
-------
dic... | [
"def",
"generic_meta_translator",
"(",
"self",
",",
"meta_to_translate",
")",
":",
"export_dict",
"=",
"{",
"}",
"if",
"self",
".",
"_meta_translation_table",
"is",
"not",
"None",
":",
"# Create a translation table for the actual values of the meta labels.",
"# The instrume... | 46.220339 | 24.084746 |
def render_title(text, markup=True, no_smartquotes=False):
""" Convert a Markdown title to HTML """
# HACK: If the title starts with something that looks like a list, save it
# for later
pfx, text = re.match(r'([0-9. ]*)(.*)', text).group(1, 2)
text = pfx + misaka.Markdown(TitleRenderer(),
... | [
"def",
"render_title",
"(",
"text",
",",
"markup",
"=",
"True",
",",
"no_smartquotes",
"=",
"False",
")",
":",
"# HACK: If the title starts with something that looks like a list, save it",
"# for later",
"pfx",
",",
"text",
"=",
"re",
".",
"match",
"(",
"r'([0-9. ]*)(... | 31.611111 | 21.166667 |
def _get_min_mag_and_num_bins(self):
"""
Estimate the number of bins in the histogram and return it along with
the first bin center value.
Rounds ``min_mag`` and ``max_mag`` with respect to ``bin_width`` to
make the distance between them include integer number of bins.
... | [
"def",
"_get_min_mag_and_num_bins",
"(",
"self",
")",
":",
"min_mag",
"=",
"round",
"(",
"self",
".",
"min_mag",
"/",
"self",
".",
"bin_width",
")",
"*",
"self",
".",
"bin_width",
"max_mag",
"=",
"(",
"round",
"(",
"(",
"self",
".",
"char_mag",
"+",
"D... | 48.73913 | 21.869565 |
def instantiate_by_name(self, object_name):
""" Instantiate object from the environment, possibly giving some extra arguments """
if object_name not in self.instances:
instance = self.instantiate_from_data(self.environment[object_name])
self.instances[object_name] = instance
... | [
"def",
"instantiate_by_name",
"(",
"self",
",",
"object_name",
")",
":",
"if",
"object_name",
"not",
"in",
"self",
".",
"instances",
":",
"instance",
"=",
"self",
".",
"instantiate_from_data",
"(",
"self",
".",
"environment",
"[",
"object_name",
"]",
")",
"s... | 44.111111 | 16 |
def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove a collection
Given a collection_id, branch and optionally an
author, remove a collection on the given branch
and attribute the commit to author.
Returns the SHA of the commit o... | [
"def",
"remove_collection",
"(",
"self",
",",
"first_arg",
",",
"sec_arg",
",",
"third_arg",
",",
"fourth_arg",
"=",
"None",
",",
"commit_msg",
"=",
"None",
")",
":",
"if",
"fourth_arg",
"is",
"None",
":",
"collection_id",
",",
"branch_name",
",",
"author",
... | 53.875 | 22.1875 |
def _get_reference_index(self, case):
""" Returns the index of the reference bus.
"""
refs = [bus._i for bus in case.connected_buses if bus.type == REFERENCE]
if len(refs) == 1:
return refs [0]
else:
logger.error("Single swing bus required for DCPF.")
... | [
"def",
"_get_reference_index",
"(",
"self",
",",
"case",
")",
":",
"refs",
"=",
"[",
"bus",
".",
"_i",
"for",
"bus",
"in",
"case",
".",
"connected_buses",
"if",
"bus",
".",
"type",
"==",
"REFERENCE",
"]",
"if",
"len",
"(",
"refs",
")",
"==",
"1",
"... | 36.555556 | 15.444444 |
def validate_config(self, project, config, actor=None):
"""
```
if config['foo'] and not config['bar']:
raise PluginError('You cannot configure foo with bar')
return config
```
"""
client = JiraClient(config['instance_url'], config['username'], config[... | [
"def",
"validate_config",
"(",
"self",
",",
"project",
",",
"config",
",",
"actor",
"=",
"None",
")",
":",
"client",
"=",
"JiraClient",
"(",
"config",
"[",
"'instance_url'",
"]",
",",
"config",
"[",
"'username'",
"]",
",",
"config",
"[",
"'password'",
"]... | 30.333333 | 19 |
def host_exists(host=None, hostid=None, name=None, node=None, nodeids=None, **kwargs):
'''
Checks if at least one host that matches the given filter criteria exists.
.. versionadded:: 2016.3.0
:param host: technical name of the host
:param hostids: Hosts (hostids) to delete.
:param name: visib... | [
"def",
"host_exists",
"(",
"host",
"=",
"None",
",",
"hostid",
"=",
"None",
",",
"name",
"=",
"None",
",",
"node",
"=",
"None",
",",
"nodeids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conn_args",
"=",
"_login",
"(",
"*",
"*",
"kwargs",
"... | 42.238095 | 23.539683 |
def connection(self):
"""return authenticated connection"""
c = pymongo.MongoClient(
self.hostname, fsync=True,
socketTimeoutMS=self.socket_timeout, **self.kwargs)
connected(c)
if not self.is_mongos and self.login and not self.restart_required:
db = c[... | [
"def",
"connection",
"(",
"self",
")",
":",
"c",
"=",
"pymongo",
".",
"MongoClient",
"(",
"self",
".",
"hostname",
",",
"fsync",
"=",
"True",
",",
"socketTimeoutMS",
"=",
"self",
".",
"socket_timeout",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"connec... | 40.45 | 18.1 |
def start_check (aggregate, out):
"""Start checking in background and write encoded output to out."""
# check in background
t = threading.Thread(target=director.check_urls, args=(aggregate,))
t.start()
# time to wait for new data
sleep_seconds = 2
# current running time
run_seconds = 0
... | [
"def",
"start_check",
"(",
"aggregate",
",",
"out",
")",
":",
"# check in background",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"director",
".",
"check_urls",
",",
"args",
"=",
"(",
"aggregate",
",",
")",
")",
"t",
".",
"start",
"(",
"... | 33.411765 | 12.647059 |
def parse_yaml(self, y):
'''Parse a YAML specification of a service port connector into this
object.
'''
self.connector_id = y['connectorId']
self.name = y['name']
if 'transMethod' in y:
self.trans_method = y['transMethod']
else:
self.tran... | [
"def",
"parse_yaml",
"(",
"self",
",",
"y",
")",
":",
"self",
".",
"connector_id",
"=",
"y",
"[",
"'connectorId'",
"]",
"self",
".",
"name",
"=",
"y",
"[",
"'name'",
"]",
"if",
"'transMethod'",
"in",
"y",
":",
"self",
".",
"trans_method",
"=",
"y",
... | 37.864865 | 14.081081 |
def _all_keys(self):
"""Return a list of all encoded key names."""
file_keys = [self._filename_to_key(fn) for fn in self._all_filenames()]
if self._sync:
return set(file_keys)
else:
return set(file_keys + list(self._buffer)) | [
"def",
"_all_keys",
"(",
"self",
")",
":",
"file_keys",
"=",
"[",
"self",
".",
"_filename_to_key",
"(",
"fn",
")",
"for",
"fn",
"in",
"self",
".",
"_all_filenames",
"(",
")",
"]",
"if",
"self",
".",
"_sync",
":",
"return",
"set",
"(",
"file_keys",
")... | 39.142857 | 17.857143 |
def setMinGap(self, typeID, minGap):
"""setMinGap(string, double) -> None
Sets the offset (gap to front vehicle if halting) of vehicles of this type.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_MINGAP, typeID, minGap) | [
"def",
"setMinGap",
"(",
"self",
",",
"typeID",
",",
"minGap",
")",
":",
"self",
".",
"_connection",
".",
"_sendDoubleCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLETYPE_VARIABLE",
",",
"tc",
".",
"VAR_MINGAP",
",",
"typeID",
",",
"minGap",
")"
] | 41.285714 | 17.428571 |
def addInput(self, key):
"""Add key to input : key, value or map
"""
if key not in self.inputs:
self.inputs.append(key)
root = self.etree
t_inputs = root.find('inputs')
if not t_inputs :
t_inputs = ctree.SubElement(root, 'inputs')
t_inpu... | [
"def",
"addInput",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"inputs",
":",
"self",
".",
"inputs",
".",
"append",
"(",
"key",
")",
"root",
"=",
"self",
".",
"etree",
"t_inputs",
"=",
"root",
".",
"find",
"(",
"'inp... | 23.133333 | 17.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.